# 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. Qid Identifies a quantum object such as a qubit, qudit, resonator, etc. UnconstrainedDevice A device that allows everything.

## Single Qubit Unitary Gates¶

Unitary operations you can apply to a single qubit.

 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(num_qubits, key, …) 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, sympy.core.basic.Basic]) Returns a gate with the matrix e^{-i X rads / 2}. Ry(rads, sympy.core.basic.Basic]) Returns a gate with the matrix e^{-i Y rads / 2}. Rz(rads, sympy.core.basic.Basic]) 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 XPowGate(*, exponent, float] = 1.0, global_shift) A gate that rotates around the X axis of the Bloch sphere. Y YPowGate(*, exponent, float] = 1.0, global_shift) A gate that rotates around the Y axis of the Bloch sphere. Z ZPowGate(*, exponent, float] = 1.0, global_shift) A gate that rotates around the Z axis of the Bloch sphere.

## Two Qubit Unitary 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 Unitary 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.

## Multiqubit Unitary Gates¶

Some gates can be applied to arbitrary number of qubits

 I A Gate that perform no operation on qubits. IdentityGate(num_qubits) A Gate that perform no operation on qubits.

## Measurements¶

Measurement can be on multiple qubits. Currently only measurement in computational basis is supported.

 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(num_qubits, key, …) A gate that measures qubits in the computational basis.

## Channels and Mixture Gate¶

Non-unitary gates. Mixture gates are those that can be interpreted as applying a unitary for a fixed probability while channel encompasses the more general concept of a noisy open system quantum evolution.

 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. 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. phase_flip(p) Returns a PhaseFlipChannel that flips a qubit’s phase with probability PhaseDampingChannel(gamma) Dampen qubit phase. PhaseFlipChannel(p) Probabilistically flip the sign of the phase of a qubit.

## Other Gate and Operation Classes¶

Generic classes for creating new kinds of gates and operations.

 ControlledGate(sub_gate, control_qubits, …) Augments existing gates with a control qubit. ControlledOperation(controls, sub_operation) 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. LinearCombinationOfGates(terms, …) Represents linear operator defined by a linear combination of gates. Operation An effect applied to a collection of qubits. 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.

## Pauli and Clifford Group Concepts¶

 Pauli(index, name) Represents the Pauli gates. PauliInteractionGate(pauli0, invert0, …) PauliString(qubit_pauli_map, …) PauliTransform(to, flip) SingleQubitCliffordGate(*, _rotation_map, …) Any single qubit Clifford rotation.

## Displays¶

 ApproxPauliStringExpectation(pauli_string, …) Approximate expectation value of a Pauli string. pauli_string_expectation(pauli_string, …) DensityMatrixDisplay A display whose value is computed from the density matrix. PauliStringExpectation(pauli_string, key) Expectation value of a Pauli string. SamplesDisplay A display whose value is computed from measurement results. WaveFunctionDisplay A display whose value is computed from the full wavefunction.

## Circuits and Schedules¶

Utilities for representing and manipulating quantum computations via Circuits, Operations, and Moments.

 Circuit(moments, device) A mutable list of groups of operations to apply to some qubits. CircuitDag(can_reorder, …) A representation of a Circuit as a directed acyclic graph. 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. GateOperation(gate, qubits) An application of a gate to a sequence of qubits. 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_gate_of_type(op, gate_type) Returns the gate of given type, if the op has that gate otherwise None. OP_TREE Union type; Union[X, Y] means either X or Y. Operation An effect applied to a collection of qubits. ParallelGateOperation(gate, qubits) An application of several copies of a gate to a group of qubits. 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. Unique(val) A wrapper for a value that doesn’t compare equal to other instances.

## Trials and Simulations¶

Classes for simulations and results.

 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. DensityMatrixSimulator(*, dtype, noise) A simulator for density matrices and noisy quantum circuits. DensityMatrixSimulatorState(density_matrix, …) The simulator state for DensityMatrixSimulator DensityMatrixStepResult(density_matrix, …) A single step in the simulation of the DensityMatrixSimulator. DensityMatrixTrialResult(params, …) A SimulationTrialResult for DensityMatrixSimulator runs. dirac_notation(state, decimals) Returns the wavefunction as a string in Dirac notation. measure_density_matrix(density_matrix, …) Performs a measurement of the density matrix in the computational basis. measure_state_vector(state, indices, out) Performs a measurement of the state in the computational basis. sample(program, …) Simulates sampling from the given circuit or schedule. sample_density_matrix(density_matrix, …) Samples repeatedly from measurements in the computational basis. sample_state_vector(state, indices, repetitions) Samples repeatedly from measurements in the computational basis. sample_sweep(program, …) Runs the supplied Circuit or Schedule, mimicking quantum hardware. SimulatesFinalState Simulator that allows access to a quantum computer’s final state. SimulatesIntermediateState A SimulatesFinalState that simulates a circuit by moments. SimulatesIntermediateWaveFunction A simulator that accesses its wave function as it does its simulation. SimulatesSamples Simulator that mimics running on quantum hardware. SimulationTrialResult(params, measurements, …) Results of a simulation by a SimulatesFinalState. Simulator(*[, dtype]) A sparse matrix wave function simulator that uses numpy. SparseSimulatorStep(state_vector, …) A StepResult that includes StateVectorMixin methods. StateVectorMixin(qubit_map, int]] = None, …) A mixin that provide methods for objects that have a state vector. StepResult(measurements, List[bool]]] = None) Results of a step of a SimulatesIntermediateState. TrialResult(*, params, measurements, …) The results of multiple executions of a circuit with fixed parameters. to_valid_density_matrix(density_matrix_rep, …) Verifies the density_matrix_rep is valid and converts it to ndarray form. to_valid_state_vector(state_rep, …) Verifies the state_rep is valid and converts it to ndarray form. validate_normalized_state(state, num_qubits, …) Validates that the given state is a valid wave function. validate_probability(p, p_str) Validates that a probability is between 0 and 1 inclusively. WaveFunctionSimulatorState(state_vector, …) WaveFunctionStepResult(measurements, …) WaveFunctionTrialResult(params, …) A SimulationTrialResult that includes the StateVectorMixin methods.

## Parameterization¶

Handling of parameterized values.

 Linspace(key, sympy.core.symbol.Symbol], …) A simple sweep over linearly-spaced values. ParamResolver(param_dict, Dict[str, float], …) Resolves sympy.Symbols to actual values. plot_state_histogram(result) Plot the state histogram from a single result with repetitions. Points(key, sympy.core.symbol.Symbol], points) A simple sweep with explicitly supplied values. Sweep A sweep is an iterator over ParamResolvers. Sweepable Union type; Union[X, Y] means either X or Y. to_resolvers(sweepable, …) Convert a Sweepable to a list of ParamResolvers. 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_channel(val, args, default[, dtype]) High performance evolution under a channel evolution. apply_unitary(unitary_value, args, default) High performance left-multiplication of a unitary effect onto a tensor. approx_eq(val, other, *, atol, float] = 1e-08) Approximately compares two objects. channel(val, default[, dtype]) Returns a list of matrices describing the channel for the given value. 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. has_channel(val) Returns whether the value has a channel representation. has_mixture(val) Returns whether the value has a mixture representation. has_mixture_channel(val) Returns whether the value has a mixture channel representation. has_unitary(val) Returns whether the value has a unitary matrix representation. inverse(val, default) Returns the inverse val**-1 of the given value, if defined. is_measurement(val) Returns whether or not the given value is a measurement. is_parameterized(val) Returns whether the object is parameterized with any Symbols. measurement_key(val, default) Get the measurement key for the given value. mixture(val, default, []),)) Return a sequence of tuples representing a probabilistic combination. mixture_channel(val, default, []),)) Return a sequence of tuples for a channel that is a mixture of unitaries. mul(lhs, rhs, default) Returns lhs * rhs, or else a default if the operator is not implemented. pauli_expansion(val, *, default, …) Returns coefficients of the expansion of val in the Pauli basis. phase_by(val, phase_turns, qubit_index, default) Returns a phased version of the effect. 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. resolve_parameters(val, param_resolver) Resolves symbol parameters in the effect using the param resolver. trace_distance_bound(val) Returns a maximum on the trace distance between this effect’s input unitary(val, default[, dtype]) Returns a unitary matrix describing the given value. validate_mixture(supports_mixture) Validates that the mixture’s tuple are valid probabilities.

## Magic Method Protocol Types¶

Classes defining and used by the magic method protocols.

 ApplyChannelArgs(target_tensor, out_buffer, …) Arguments for efficiently performing a channel. ApplyUnitaryArgs(target_tensor, …) Arguments for performing an efficient left-multiplication by a unitary. 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]], …) SupportsApplyChannel(*args, **kwargs) An object that can efficiently implement a channel. SupportsApplyUnitary(*args, **kwargs) An object that can be efficiently left-multiplied into tensors. SupportsApproximateEquality(*args, **kwargs) Object which can be compared approximately. SupportsChannel(*args, **kwargs) An object that may be describable as a quantum channel. 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. SupportsMixture(*args, **kwargs) An object that may be describable as a probabilistic combination. 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. 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, atol) 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. block_diag(*blocks) Concatenates blocks into a block diagonal matrix. commutes(m1, m2, *, rtol, atol) Determines if two matrices approximately commute. 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. commutes(m1, m2, *, rtol, atol) 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. expand_matrix_in_orthogonal_basis(m, basis, …) Computes coefficients of expansion of m in basis. hilbert_schmidt_inner_product(m1, m2) Computes Hilbert-Schmidt inner product of two matrices. is_diagonal(matrix, *, atol) Determines if a matrix is a approximately diagonal. is_hermitian(matrix, *, rtol, atol) Determines if a matrix is approximately Hermitian. is_negligible_turn(turns, tolerance) is_orthogonal(matrix, *, rtol, atol) Determines if a matrix is approximately orthogonal. is_special_orthogonal(matrix, *, rtol, atol) Determines if a matrix is approximately special orthogonal. is_special_unitary(matrix, *, rtol, atol) Determines if a matrix is approximately unitary with unit determinant. is_unitary(matrix, *, rtol, atol) 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, rtol, 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) 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. LinearDict(terms, Union[complex, float]], …) Represents linear combination of things. map_eigenvalues(matrix, func, complex], *, …) Applies a function to the eigenvalues of a matrix. match_global_phase(a, b) Phases the given matrices so that they agree on the phase of one entry. matrix_from_basis_coefficients(expansion, …) Computes linear combination of basis vectors with given coefficients. partial_trace(tensor, keep_indices) Takes the partial trace of a given tensor. PeriodicValue(value, float], period, float]) Wrapper for periodic numerical values. reflection_matrix_pow(reflection_matrix, …) Raises a matrix with two opposing eigenvalues to a power. slice_for_qubits_equal_to(target_qubit_axes, …) Returns an index corresponding to a desired subset of an np.ndarray. so4_to_magic_su2s(mat, *, rtol, atol, …) Finds 2x2 special-unitaries A, B where mat = Mag.H @ kron(A, B) @ Mag. targeted_conjugate_about(tensor, target, …) Conjugates the given tensor about the target tensor. 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. 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

## Ion traps and neutral atoms¶

Support for ion trap an neutral atom devices.

 ConvertToIonGates(ignore_failures) Attempts to convert non-native gates into IonGates. IonDevice(measurement_duration, …) A device with qubits placed on a line. MS(rads) The Mølmer–Sørensen gate, a native two-qubit operation in ion traps. two_qubit_matrix_to_ion_operations(q0, q1, …) Decomposes a two-qubit operation into MS/single-qubit rotation gates. ConvertToNeutralAtomGates([ignore_failures]) Attempts to convert gates into native Atom gates. NeutralAtomDevice(measurement_duration, …) A device with qubits placed on a grid.

Functionality specific to quantum hardware and services from Google.

 google.AnnealSequenceSearchStrategy(…) Linearized sequence search using simulated annealing method. 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.GreedySequenceSearchStrategy(algorithm) Greedy search method for linear sequence of qubits on a chip. 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 quantum circuits with an Xmon device. 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_eigengate_implements_consistent_protocols(…) Checks that an EigenGate subclass is internally consistent and has a 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_implements_consistent_protocols(…) Checks that a value is internally consistent and has a good repr. testing.assert_pauli_expansion_is_consistent_with_unitary(val) Checks Pauli expansion against unitary matrix. 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) Returns a random orthogonal matrix distributed with Haar measure. testing.random_special_orthogonal(dim) Returns a random special orthogonal matrix distributed with Haar measure. testing.random_special_unitary(dim) Returns a random special unitary distributed with Haar measure. testing.random_superposition(dim) Returns a random unit-length vector from the uniform distribution. 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

## 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 Tools for creating and using acquaintance strategies. contrib.jobs contrib.paulistring contrib.qcircuit Converts cirq circuits into latex using qcircuit. contrib.quirk Converts cirq circuits into quirk circuits. contrib.tpu