# API Reference¶

## Devices and Qubits¶

Classes for identifying the qubits and hardware you want to operate on.

 Device Hardware constraints for validating circuits and schedules. GridQubit(row, col) A qubit on a 2d square lattice. LineQubit(x) A qubit on a 1d lattice with nearest-neighbor connectivity. NamedQubit(name) A qubit identified by name. QubitId Identifies a qubit. UnconstrainedDevice A device that allows everything.

## Single Qubit Gates¶

Unitary operations you can apply to a single qubit. Also measurement.

 H A Gate that performs a rotation around the X+Z axis of the Bloch sphere. HPowGate(*, exponent, float] = 1.0, global_shift) A Gate that performs a rotation around the X+Z axis of the Bloch sphere. measure(*qubits, key, invert_mask, …] = ()) Returns a single MeasurementGate applied to all the given qubits. measure_each(*qubits, key_func, str] = ) Returns a list of operations individually measuring the given qubits. MeasurementGate(key, invert_mask, …] = ()) A gate that measures qubits in the computational basis. PhasedXPowGate(*, phase_exponent, …) A gate equivalent to the circuit ───Z^-p───X^t───Z^p───. Rx(rads) Returns a gate with the matrix e^{-i X rads / 2}. Ry(rads) Returns a gate with the matrix e^{-i Y rads / 2}. Rz(rads) Returns a gate with the matrix e^{-i Z rads / 2}. S A gate that rotates around the Z axis of the Bloch sphere. SingleQubitMatrixGate(matrix) A 1-qubit gate defined by its matrix. T A gate that rotates around the Z axis of the Bloch sphere. TwoQubitMatrixGate(matrix) A 2-qubit gate defined only by its matrix. X The Pauli X gate. XPowGate(*, exponent, float] = 1.0, global_shift) A gate that rotates around the X axis of the Bloch sphere. Y The Pauli Y gate. YPowGate(*, exponent, float] = 1.0, global_shift) A gate that rotates around the Y axis of the Bloch sphere. Z A gate that rotates around the Z axis of the Bloch sphere. ZPowGate(*, exponent, float] = 1.0, global_shift) A gate that rotates around the Z axis of the Bloch sphere.

## Two Qubit Gates¶

Unitary operations you can apply to pairs of qubits.

 CNOT A gate that applies a controlled power of an X gate. CNotPowGate(*, exponent, float] = 1.0, …) A gate that applies a controlled power of an X gate. CZ A gate that applies a phase to the |11⟩ state of two qubits. CZPowGate(*, exponent, float] = 1.0, …) A gate that applies a phase to the |11⟩ state of two qubits. ISWAP Rotates the |01⟩-vs-|10⟩ subspace of two qubits around its Bloch X-axis. ISwapPowGate(*, exponent, float] = 1.0, …) Rotates the |01⟩-vs-|10⟩ subspace of two qubits around its Bloch X-axis. MS(rads) The Mølmer–Sørensen gate, a native two-qubit operation in ion traps. SWAP The SWAP gate, possibly raised to a power. SwapPowGate(*, exponent, float] = 1.0, …) The SWAP gate, possibly raised to a power. XX The X-parity gate, possibly raised to a power. XXPowGate(*, exponent, float] = 1.0, …) The X-parity gate, possibly raised to a power. YY The Y-parity gate, possibly raised to a power. YYPowGate(*, exponent, float] = 1.0, …) The Y-parity gate, possibly raised to a power. ZZ The Z-parity gate, possibly raised to a power. ZZPowGate(*, exponent, float] = 1.0, …) The Z-parity gate, possibly raised to a power.

## Three Qubit Gates¶

Unitary operations you can apply to triplets of qubits, with helpful adjacency-respecting decompositions.

 CCX A Toffoli (doubly-controlled-NOT) that can be raised to a power. CCXPowGate(*, exponent, float] = 1.0, …) A Toffoli (doubly-controlled-NOT) that can be raised to a power. CCZ A doubly-controlled-Z that can be raised to a power. CCZPowGate(*, exponent, float] = 1.0, …) A doubly-controlled-Z that can be raised to a power. CSWAP A controlled swap gate. CSwapGate A controlled swap gate. FREDKIN A controlled swap gate. TOFFOLI A Toffoli (doubly-controlled-NOT) that can be raised to a power.

## Other Gate and Operation Classes¶

Generic classes for creating new kinds of gates and operations.

 ControlledGate(sub_gate) Augments existing gates with a control qubit. EigenGate(*, exponent, float] = 1.0, …) A gate with a known eigendecomposition. Gate An operation type that can be applied to a collection of qubits. GateOperation(gate, qubits) An application of a gate to a sequence of qubits. InterchangeableQubitsGate Indicates operations should be equal under some qubit permutations. Operation An effect applied to a collection of qubits. ReversibleCompositeGate A composite gate that gets decomposed into reversible gates. SingleQubitGate A gate that must be applied to exactly one qubit. ThreeQubitGate A gate that must be applied to exactly three qubits. TwoQubitGate A gate that must be applied to exactly two qubits.

## Circuits and Schedules¶

Utilities for representing and manipulating quantum computations.

 Circuit(moments, device) A mutable list of groups of operations to apply to some qubits. flatten_op_tree(root, Iterable[Any]]) Performs an in-order iteration of the operations (leaves) in an OP_TREE. freeze_op_tree(root, Iterable[Any]]) Replaces all iterables in the OP_TREE with tuples. InsertStrategy(name, doc) Indicates preferences on how to add multiple operations to a circuit. Moment(operations) A simplified time-slice of operations within a sequenced circuit. moment_by_moment_schedule(device, circuit) Returns a schedule aligned with the moment structure of the Circuit. OP_TREE Union type; Union[X, Y] means either X or Y. QubitOrder(explicit_func, …) Defines the kronecker product order of qubits. QubitOrderOrList Union type; Union[X, Y] means either X or Y. Schedule(device, scheduled_operations) A quantum program with operations happening at specific times. ScheduledOperation(time, duration, operation) An operation that happens over a specified time interval. transform_op_tree(root, Iterable[Any]], …) Maps transformation functions onto the nodes of an OP_TREE.

## Trials and Simulations¶

Classes for parameterized circuits.

 bloch_vector_from_state_vector(state, index) Returns the bloch vector of a qubit. density_matrix_from_state_vector(state, indices) Returns the density matrix of the wavefunction. dirac_notation(state, decimals) Returns the wavefunction as a string in Dirac notation. Linspace(key, start, stop, length) A simple sweep over linearly-spaced values. measure_state_vector(state, indices, out) Performs a measurement of the state in the computational basis. ParamResolver(param_dict, float]) Resolves Symbols to actual values. plot_state_histogram(result) Plot the state histogram from a single result with repetitions. Points(key, points) A simple sweep with explicitly supplied values. sample_state_vector(state, indices, repetitions) Samples repeatedly from measurements in the computational basis. SimulatesSamples Simulator that mimics running on quantum hardware. SimulationTrialResult(params, measurements, …) Results of a simulation by a SimulatesFinalWaveFunction. Simulator([dtype]) A sparse matrix wave function simulator that uses numpy. SimulatorStep(state, measurements, …) StepResult(qubit_map, measurements, List[bool]]]) Results of a step of a SimulatesFinalWaveFunction. SimulatesFinalWaveFunction Simulator that allows access to a quantum computer’s wavefunction. SimulatesIntermediateWaveFunction A SimulatesFinalWaveFunction that simulates a circuit by moments. Sweep A sweep is an iterator over ParamResolvers. Sweepable Union type; Union[X, Y] means either X or Y. to_valid_state_vector(state_rep, …) Verifies the initial_state is valid and converts it to ndarray form. validate_normalized_state(state, num_qubits, …) Validates that the given state is a valid wave function. to_resolvers(sweepable, …) Convert a Sweepable to a list of ParamResolvers. TrialResult(*, params, measurements, …) The results of multiple executions of a circuit with fixed parameters. UnitSweep A sweep with a single element that assigns no parameter values.

## Magic Method Protocols¶

Utility methods for accessing generic functionality exposed by some gates, operations, and other types.

 apply_unitary(unitary_value, args, default) High performance left-multiplication of a unitary effect onto a tensor. circuit_diagram_info(val, args[, default, …]) Requests information on drawing an operation in a circuit diagram. decompose(val, *, intercepting_decomposer, …) Recursively decomposes a value into cirq.Operations meeting a criteria. decompose_once(val[, default]) Decomposes a value into operations, if possible. decompose_once_with_qubits(val, qubits[, …]) Decomposes a value into operations on the given qubits. inverse(val, default) Returns the inverse val**-1 of the given value, if defined. mul(lhs, rhs, default) Returns lhs * rhs, or else a default if the operator is not implemented. pow(val, exponent, default) Returns val**factor of the given value, if defined. qasm(val, *, args, qubits, default) Returns QASM code for the given value, if possible. is_parameterized(val) Returns whether the object is parameterized with any Symbols. resolve_parameters(val, param_resolver) Resolves symbol parameters in the effect using the param resolver. has_unitary(val) Returns whether the value has a unitary matrix representation. unitary(val, default[, dtype]) Returns a unitary matrix describing the given value. trace_distance_bound(val) Returns a maximum on the trace distance between this effect’s input phase_by(val, phase_turns, qubit_index, default) Returns a phased version of the effect.

## Magic Method Protocol Types¶

Classes defining and used by the magic method protocols.

 CircuitDiagramInfo(wire_symbols, …], …) Describes how to draw an operation in a circuit diagram. CircuitDiagramInfoArgs(known_qubits, …) A request for information on drawing an operation in a circuit diagram. QasmArgs(precision, version, qubit_id_map, …) QasmOutput(operations, Iterable[Any]], …) SupportsApplyUnitary(*args, **kwargs) An object that can be efficiently left-multiplied into tensors. SupportsCircuitDiagramInfo(*args, **kwargs) A diagrammable operation on qubits. SupportsDecompose(*args, **kwargs) An object that can be decomposed into simpler operations. SupportsDecomposeWithQubits(*args, **kwargs) An object that can be decomposed into operations on given qubits. SupportsParameterization(*args, **kwargs) An object that can be parameterized by Symbols and resolved SupportsPhase(*args, **kwargs) An effect that can be phased around the Z axis of target qubits. SupportsQasm(*args, **kwargs) An object that can be turned into QASM code. SupportsQasmWithArgs(*args, **kwargs) An object that can be turned into QASM code. SupportsQasmWithArgsAndQubits(*args, **kwargs) An object that can be turned into QASM code if it knows its qubits. SupportsTraceDistanceBound(*args, **kwargs) An effect with known bounds on how easy it is to detect. SupportsUnitary(*args, **kwargs) An object that may be describable by a unitary matrix.

## Optimization¶

Classes and methods for rewriting circuits.

 ConvertToCzAndSingleGates(ignore_failures, …) Attempts to convert strange multi-qubit gates into CZ and single qubit DropEmptyMoments Removes empty moments from a circuit. DropNegligible(tolerance) An optimization pass that removes operations with tiny effects. EjectPhasedPaulis(tolerance) Pushes X, Y, and PhasedX gates towards the end of the circuit. EjectZ(tolerance) Pushes Z gates towards the end of the circuit. ExpandComposite(no_decomp, …) An optimizer that expands composite operations via cirq.decompose. google.optimized_for_xmon(circuit, …) Optimizes a circuit with XmonDevice in mind. merge_single_qubit_gates_into_phased_x_z(…) Canonicalizes runs of single-qubit rotations in a circuit. MergeInteractions(tolerance, …) Combines series of adjacent one and two-qubit gates operating on a MergeSingleQubitGates(*, rewriter, …) Optimizes runs of adjacent unitary 1-qubit operations. OptimizationPass Rewrites a circuit’s operations in place to make them better. PointOptimizationSummary(clear_span, …) A description of a local optimization to perform. PointOptimizer(post_clean_up, …) Makes circuit improvements focused on a specific location. single_qubit_matrix_to_gates(mat, tolerance) Implements a single-qubit operation with few gates. single_qubit_matrix_to_pauli_rotations(mat, …) Implements a single-qubit operation with few rotations. single_qubit_matrix_to_phased_x_z(mat, atol) Implements a single-qubit operation with a PhasedX and Z gate. single_qubit_op_to_framed_phase_form(mat) Decomposes a 2x2 unitary M into U^-1 * diag(1, r) * U * diag(g, g). two_qubit_matrix_to_operations(q0, q1, mat, …) Decomposes a two-qubit operation into Z/XY/CZ gates.

## Utilities¶

General utility methods, mostly related to performing relevant linear algebra operations and decompositions.

 allclose_up_to_global_phase(a, b, rtol, …) Determines if a ~= b * exp(i t) for some t. apply_matrix_to_slices(target, matrix, …) Left-multiplies an NxN matrix onto N slices of a numpy array. bidiagonalize_real_matrix_pair_with_symmetric_products(…) Finds orthogonal matrices that diagonalize both mat1 and mat2. bidiagonalize_unitary_with_special_orthogonals(…) Finds orthogonal matrices L, R such that L @ matrix @ R is diagonal. canonicalize_half_turns(half_turns, float]) Wraps the input into the range (-1, +1]. chosen_angle_to_canonical_half_turns(…) Returns a canonicalized half_turns based on the given arguments. chosen_angle_to_half_turns(half_turns, …) Returns a half_turns value based on the given arguments. slice_for_qubits_equal_to(target_qubit_axes, …) Returns an index corresponding to a desired subset of an np.ndarray. block_diag(*blocks) Concatenates blocks into a block diagonal matrix. match_global_phase(a, b) Phases the given matrices so that they agree on the phase of one entry. commutes(m1, m2, tolerance[, atol, equal_nan]) Determines if two matrices approximately commute. CONTROL_TAG diagonalize_real_symmetric_and_sorted_diagonal_matrices(…) Returns an orthogonal matrix that diagonalizes both given matrices. diagonalize_real_symmetric_matrix(matrix, …) Returns an orthogonal matrix that diagonalizes the given matrix. dot(*values) Computes the dot/matrix product of a sequence of values. Duration(*, picos, float] = 0, nanos, float] = 0) A time delta that supports picosecond accuracy. is_diagonal(matrix, tolerance[, atol, equal_nan]) Determines if a matrix is a approximately diagonal. is_hermitian(matrix, tolerance[, atol, …]) Determines if a matrix is approximately Hermitian. is_negligible_turn(turns, tolerance) is_orthogonal(matrix, tolerance[, atol, …]) Determines if a matrix is approximately orthogonal. is_special_orthogonal(matrix, tolerance[, …]) Determines if a matrix is approximately special orthogonal. is_special_unitary(matrix, tolerance[, …]) Determines if a matrix is approximately unitary with unit determinant. is_unitary(matrix, tolerance[, atol, equal_nan]) Determines if a matrix is approximately unitary. kak_canonicalize_vector(x, y, z) Canonicalizes an XX/YY/ZZ interaction by swap/negate/shift-ing axes. kak_decomposition(mat, tolerance[, atol, …]) Decomposes a 2-qubit unitary into 1-qubit ops and XX/YY/ZZ interactions. KakDecomposition(*, global_phase, …) A convenient description of an arbitrary two-qubit operation. kron(*matrices) Computes the kronecker product of a sequence of matrices. kron_factor_4x4_to_2x2s(matrix, tolerance[, …]) Splits a 4x4 matrix U = kron(A, B) into A, B, and a global factor. kron_with_controls(*matrices) Computes the kronecker product of a sequence of matrices and controls. map_eigenvalues(matrix, func, complex], …) Applies a function to the eigenvalues of a matrix. reflection_matrix_pow(reflection_matrix, …) Raises a matrix with two opposing eigenvalues to a power. so4_to_magic_su2s(mat, tolerance[, atol, …]) Finds 2x2 special-unitaries A, B where mat = Mag.H @ kron(A, B) @ Mag. Symbol(name) A constant plus the runtime value of a parameter with a given key. targeted_left_multiply(left_matrix, …) Left-multiplies the given axes of the target tensor by the given matrix. TextDiagramDrawer() A utility class for creating simple text diagrams. Timestamp(*, picos, float] = 0, nanos, …) A location in time with picosecond accuracy. Tolerance(rtol, atol, equal_nan) Specifies thresholds for doing approximate equality. value_equality(cls, *, unhashable, …) Implements eq/ne/hash via a value_equality_values method.

## Experiments¶

Utilities for running experiments on hardware, or producing things required to run experiments.

 generate_supremacy_circuit_google_v2(qubits, …) Generates Google Random Circuits v2 as in github.com/sboixo/GRCS generate_supremacy_circuit_google_v2_bristlecone(…) Generates Google Random Circuits v2 in Bristlecone. generate_supremacy_circuit_google_v2_grid(…) Generates Google Random Circuits v2 as in github.com/sboixo/GRCS

Functionality specific to quantum hardware and services from Google.

 google.AnnealSequenceSearchStrategy(…) Linearized sequence search using simulated annealing method. google.GreedySequenceSearchStrategy(algorithm) Greedy search method for linear sequence of qubits on a chip. google.Bristlecone google.ConvertToXmonGates([ignore_failures]) Attempts to convert strange gates into XmonGates. google.Engine(api_key, api, version, …) Runs programs via the Quantum Engine API. google.engine_from_environment() Returns an Engine instance configured using environment variables. google.Foxtail google.gate_to_proto_dict(gate, qubits, …]) google.is_native_xmon_op(op) Check if the gate corresponding to an operation is a native xmon gate. google.JobConfig(project_id, program_id, …) Configuration for a program and job to run on the Quantum Engine API. google.line_on_device(device, length, method) Searches for linear sequence of qubits on device. google.LinePlacementStrategy Choice and options for the line placement calculation method. google.optimized_for_xmon(circuit, …) Optimizes a circuit with XmonDevice in mind. google.pack_results(measurements, …) Pack measurement results into a byte string. google.schedule_from_proto_dicts(device, ops) Convert proto dictionaries into a Schedule for the given device. google.schedule_to_proto_dicts(schedule) Convert a schedule into an iterable of proto dictionaries. google.unpack_results(data, repetitions, …) Unpack data from a bitstring into individual measurement results. google.xmon_op_from_proto_dict(proto_dict) Convert the proto dictionary to the corresponding operation. google.XmonDevice(measurement_duration, …) A device with qubits placed in a grid. google.XmonOptions(num_shards, …) XmonOptions for the XmonSimulator. google.XmonSimulator(options) XmonSimulator for Xmon class quantum circuits. google.XmonStepResult(stepper, qubit_map, …) Results of a step of the simulator.

## Testing¶

Functionality for writing unit tests involving objects from Cirq, and also some general testing utilities.

 testing.assert_allclose_up_to_global_phase(…) Checks if a ~= b * exp(i t) for some t. testing.assert_circuits_with_terminal_measurements_are_equivalent(…) Determines if two circuits have equivalent effects. testing.assert_decompose_is_consistent_with_unitary(…) Uses val._unitary_ to check val._phase_by_’s behavior. testing.assert_eigen_gate_has_consistent_apply_unitary(…) Tests whether an EigenGate type’s apply_unitary is correct. testing.assert_equivalent_repr(value, *, …) Checks that eval(repr(v)) == v. testing.assert_has_consistent_apply_unitary(…) Tests whether a value’s apply_unitary is correct. testing.assert_has_consistent_apply_unitary_for_various_exponents(val, *) Tests whether a value’s apply_unitary is correct. testing.assert_has_diagram(actual, desired, …) Determines if a given circuit has the desired text diagram. testing.assert_phase_by_is_consistent_with_unitary(val) Uses val._unitary_ to check val._phase_by_’s behavior. testing.assert_qasm_is_consistent_with_unitary(val) Uses val._unitary_ to check val._qasm_’s behavior. testing.assert_same_circuits(actual, expected) Asserts that two circuits are identical, with a descriptive error. testing.EqualsTester() Tests equality against user-provided disjoint equivalence groups. testing.highlight_text_differences(actual, …) testing.nonoptimal_toffoli_circuit(q0, q1, …) testing.only_test_in_python3(func) A decorator that indicates a test should not execute in python 2. testing.OrderTester() Tests ordering against user-provided disjoint ordered groups or items. testing.random_circuit(qubits, int], …) Generates a random circuit. testing.random_orthogonal(dim) testing.random_special_orthogonal(dim) testing.random_special_unitary(dim) testing.random_unitary(dim) Returns a random unitary matrix distributed with Haar measure. testing.TempDirectoryPath A context manager that provides a temporary directory for use within a testing.TempFilePath A context manager that provides a temporary file path for use within a

## Work in Progress - Noisy Channels¶

Imperfect operations.

 amplitude_damp(gamma) Returns an AmplitudeDampingChannel with the given probability gamma. AmplitudeDampingChannel(gamma) Dampen qubit amplitudes through dissipation. asymmetric_depolarize(p_x, p_y, p_z) Returns a AsymmetricDepolarizingChannel with given parameter. AsymmetricDepolarizingChannel(p_x, p_y, p_z) A channel that depolarizes asymmetrically along different directions. bit_flip(p) Construct a BitFlipChannel that flips a qubit state BitFlipChannel(p) Probabilistically flip a qubit from 1 to 0 state or vice versa. channel(val, default[, dtype]) Returns a list of matrices describing the channel for the given value. depolarize(p) Returns a DepolarizingChannel with given probability of error. DepolarizingChannel(p) A channel that depolarizes a qubit. generalized_amplitude_damp(p, gamma) Returns a GeneralizedAmplitudeDampingChannel with the given GeneralizedAmplitudeDampingChannel(p, gamma) Dampen qubit amplitudes through non ideal dissipation. phase_damp(gamma) Creates a PhaseDampingChannel with damping constant gamma. PhaseDampingChannel(gamma) Dampen qubit phase. phase_flip(p) Returns a PhaseFlipChannel that flips a qubit’s phase with probability PhaseFlipChannel(p) Probabilistically flip the sign of the phase of a qubit. rotation_error(eps_x, eps_y, eps_z) Constructs a RotationErrorChannel that can over/under rotate RotationErrorChannel(eps_x, eps_y, eps_z) Channel to introduce rotation error in X, Y, Z. SupportsChannel(*args, **kwargs) An object that may be describable as a quantum channel.

## Work in Progress - Stabilizers¶

Tools for working with the well-behaved operations from the Clifford+Measurement set.

 CircuitDag(can_reorder, …) A representation of a Circuit as a directed acyclic graph. SingleQubitCliffordGate(*, _rotation_map, …) Any single qubit Clifford rotation. Pauli(*, _index, _name) Represents the X, Y, or Z axis of the Bloch sphere. PauliInteractionGate(pauli0, invert0, …) PauliString(qubit_pauli_map, …) PauliTransform(to, flip) Unique(val) A wrapper for a value that doesn’t compare equal to other instances.

## Contrib¶

Contributed code that requires extra dependencies to be installed, code that may be unstable, and code that may or may not be a fit for the main library. A waiting area.

 contrib.acquaintance Primitives for generalized swap networks. contrib.jobs Package for handling a full quantum job. contrib.paulistring contrib.qcircuit Converts cirq circuits into latex using qcircuit. contrib.quirk Converts cirq circuits into quirk circuits. contrib.tpu