# API Reference¶

## Devices and Qubits¶

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

 cirq.UNCONSTRAINED_DEVICE A device with no constraints on operations or qubits. cirq.Device Hardware constraints for validating circuits. cirq.GridQubit(row, col) A qubit on a 2d square lattice. cirq.LineQid(x, dimension) A qid on a 1d lattice with nearest-neighbor connectivity. A qubit on a 1d lattice with nearest-neighbor connectivity. A qubit identified by name. cirq.Qid Identifies a quantum object such as a qubit, qudit, resonator, etc.

## Measurement¶

Methods and classes for performing measurement operations.

 cirq.measure(*target[, key, invert_mask]) Returns a single MeasurementGate applied to all the given qubits. cirq.measure_each(*qubits[, key_func]) Returns a list of operations individually measuring the given qubits. cirq.MeasurementGate([num_qubits, key, …]) A gate that measures qubits in the computational basis.

## Unitary Gates and Operations¶

Unitary effects that can be applied to one or more qubits.

 cirq.H The Hadamard gate. cirq.I The one qubit identity gate. cirq.S The Clifford S gate. cirq.T The non-Clifford T gate. cirq.X The Pauli X gate. cirq.Y The Pauli Y gate. cirq.Z The Pauli Z gate. cirq.CX The controlled NOT gate. cirq.CZ The controlled Z gate. cirq.XX The tensor product of two X gates. cirq.YY The tensor product of two Y gates. cirq.ZZ The tensor product of two Z gates. cirq.rx(rads) Returns a gate with the matrix e^{-i X rads / 2}. cirq.ry(rads) Returns a gate with the matrix e^{-i Y rads / 2}. cirq.rz(rads) Returns a gate with the matrix e^{-i Z rads / 2}. cirq.CCNOT The TOFFOLI gate. cirq.CCX The TOFFOLI gate. cirq.CCZ The Controlled-Controlled-Z gate. cirq.CNOT The controlled NOT gate. cirq.CSWAP The Controlled Swap gate. cirq.FREDKIN The Controlled Swap gate. cirq.ISWAP The iswap gate. cirq.QFT(*qubits[, without_reverse, inverse]) The quantum Fourier transform. cirq.SWAP The swap gate. cirq.TOFFOLI The TOFFOLI gate. cirq.givens(angle_rads) Returns gate with matrix exp(-i angle_rads (Y⊗X - X⊗Y) / 2). cirq.identity_each(*qubits) Returns a single IdentityGate applied to all the given qubits. cirq.riswap(rads) Returns gate with matrix exp(+i angle_rads (X⊗X + Y⊗Y) / 2). cirq.CCXPowGate(*[, exponent, global_shift]) A Toffoli (doubly-controlled-NOT) that can be raised to a power. cirq.CCZPowGate(*[, exponent, global_shift]) A doubly-controlled-Z that can be raised to a power. cirq.CNotPowGate(*[, exponent, global_shift]) A gate that applies a controlled power of an X gate. cirq.CSwapGate A controlled swap gate. cirq.CZPowGate(*[, exponent, global_shift]) A gate that applies a phase to the |11⟩ state of two qubits. cirq.ControlledGate(sub_gate[, …]) Augments existing gates to have one or more control qubits. cirq.ControlledOperation(controls, sub_operation) Augments existing operations to have one or more control qubits. cirq.EigenGate(*[, exponent, global_shift]) A gate with a known eigendecomposition. cirq.FSimGate(theta, phi) Fermionic simulation gate family. cirq.Gate An operation type that can be applied to a collection of qubits. cirq.GlobalPhaseOperation(coefficient[, atol]) cirq.HPowGate(*[, exponent, global_shift]) A Gate that performs a rotation around the X+Z axis of the Bloch sphere. cirq.ISwapPowGate(*[, exponent, global_shift]) Rotates the |01⟩ vs |10⟩ subspace of two qubits around its Bloch X-axis. cirq.IdentityGate([num_qubits, qid_shape]) A Gate that perform no operation on qubits. cirq.IdentityOperation An application of the identity gate to a sequence of qubits. cirq.MatrixGate(matrix, *[, qid_shape]) A unitary qubit or qudit gate defined entirely by its matrix. cirq.Operation An effect applied to a collection of qubits. cirq.PhaseGradientGate(*, num_qubits, exponent) Phases each state |k⟩ out of n by e^(2piik/nexponent). cirq.PhasedISwapPowGate(*[, phase_exponent, …]) Fractional ISWAP conjugated by Z rotations. cirq.PhasedXPowGate(*, phase_exponent[, …]) A gate equivalent to the circuit ───Z^-p───X^t───Z^p───. cirq.PhasedXZGate(*, x_exponent, z_exponent, …) A single qubit operation expressed as $Z^z Z^a X^x Z^{-a}$. cirq.QuantumFourierTransformGate(num_qubits, *) Switches from the computational basis to the frequency basis. cirq.SingleQubitGate A gate that must be applied to exactly one qubit. A 1-qubit or qudit gate defined by its matrix. cirq.SwapPowGate(*[, exponent, global_shift]) The SWAP gate, possibly raised to a power. cirq.ThreeQubitDiagonalGate(diag_angles_radians) A gate given by a diagonal 8x8 matrix. A 2-qubit gate defined only by its matrix. cirq.WaitGate(duration) A single-qubit idle gate that represents waiting. cirq.XPowGate(*[, exponent, global_shift]) A gate that rotates around the X axis of the Bloch sphere. cirq.XXPowGate(*[, exponent, global_shift]) The X-parity gate, possibly raised to a power. cirq.YPowGate(*[, exponent, global_shift]) A gate that rotates around the Y axis of the Bloch sphere. cirq.YYPowGate(*[, exponent, global_shift]) The Y-parity gate, possibly raised to a power. cirq.ZPowGate(*[, exponent, global_shift]) A gate that rotates around the Z axis of the Bloch sphere. cirq.ZZPowGate(*[, exponent, global_shift]) The Z-parity gate, possibly raised to a power.

## Noisy Gates and Operations¶

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.

 cirq.NOISE_MODEL_LIKE A cirq.NoiseModel or a value that can be trivially converted into one. cirq.NO_NOISE The trivial noise model with no effects. Returns an AmplitudeDampingChannel with the given probability gamma. cirq.asymmetric_depolarize(p_x, p_y, p_z) Returns a AsymmetricDepolarizingChannel with given parameter. Construct a BitFlipChannel that flips a qubit state with probability Returns a DepolarizingChannel with given probability of error. Returns a GeneralizedAmplitudeDampingChannel with the given cirq.phase_damp(gamma) Creates a PhaseDampingChannel with damping constant gamma. Returns a PhaseFlipChannel that flips a qubit’s phase with probability cirq.reset(qubit) Returns a ResetChannel on the given qubit. Dampen qubit amplitudes through dissipation. cirq.AsymmetricDepolarizingChannel(p_x, p_y, p_z) A channel that depolarizes asymmetrically along different directions. Probabilistically flip a qubit from 1 to 0 state or vice versa. A channel that depolarizes a qubit. Dampen qubit amplitudes through non ideal dissipation. cirq.NoiseModel Replaces operations and moments with noisy counterparts. Dampen qubit phase. Probabilistically flip the sign of the phase of a qubit. cirq.ResetChannel([dimension]) Reset a qubit back to its |0⟩ state.

## Pauli and Clifford Groups¶

Classes and methods related to representing and operating on states using sums and products of Pauli operations.

 cirq.PAULI_BASIS The four Pauli matrices (including identity) keyed by character. cirq.PAULI_GATE_LIKE An object that can be interpreted as a Pauli gate. cirq.PAULI_STRING_LIKE A cirq.PauliString or a value that can easily be converted into one. cirq.pow_pauli_combination(ai, ax, ay, az, …) Computes non-negative integer power of single-qubit Pauli combination. cirq.BaseDensePauliString(pauli_mask, *[, …]) Parent class for DensePauliString and MutableDensePauliString. cirq.CliffordState(qubit_map[, initial_state]) A state of the Clifford simulation. cirq.CliffordTableau(num_qubits[, initial_state]) Tableau representation of a stabilizer state cirq.DensePauliString(pauli_mask, *[, …]) cirq.MutableDensePauliString(pauli_mask, *) cirq.Pauli(index, name) Represents the Pauli gates. cirq.PauliInteractionGate(pauli0, invert0, …) A CZ conjugated by arbitrary single qubit Cliffords. cirq.PauliString(*contents[, …]) cirq.PauliStringGateOperation(pauli_string) cirq.PauliStringPhasor(pauli_string, *[, …]) An operation that phases the eigenstates of a Pauli string. cirq.PauliSum([linear_dict]) Represents operator defined by linear combination of PauliStrings. cirq.PauliSumLike Any value that can be easily translated into a sum of Pauli products. cirq.PauliTransform(to, flip) +X, -X, +Y, -Y, +Z, or -Z. Any single qubit Clifford rotation. cirq.StabilizerStateChForm(num_qubits[, …]) A representation of stabilizer states using the CH form,

## Circuits¶

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

 cirq.OP_TREE An operation or nested collections of operations. cirq.flatten_op_tree(root[, preserve_moments]) Performs an in-order iteration of the operations (leaves) in an OP_TREE. Replaces all iterables in the OP_TREE with tuples. cirq.op_gate_of_type(op, gate_type) THIS FUNCTION IS DEPRECATED. cirq.transform_op_tree(root[, …]) Maps transformation functions onto the nodes of an OP_TREE. cirq.Circuit(*contents[, strategy, device]) A mutable list of groups of operations to apply to some qubits. cirq.CircuitDag([can_reorder, …]) A representation of a Circuit as a directed acyclic graph. cirq.GateOperation(gate, qubits) An application of a gate to a sequence of qubits. cirq.InsertStrategy(name, doc) Indicates preferences on how to add multiple operations to a circuit. cirq.Moment([operations]) A time-slice of operations within a circuit. cirq.ParallelGateOperation(gate, qubits) An application of several copies of a gate to a group of qubits. cirq.QubitOrder(explicit_func) Defines the kronecker product order of qubits. cirq.QubitOrderOrList Specifies a qubit ordering. A wrapper for a value that doesn’t compare equal to other instances.

## Importing and Exporting¶

Utilities for interoperating with other quantum software libraries and products.

 cirq.quirk_json_to_circuit(data, *[, …]) Constructs a Cirq circuit from Quirk’s JSON format. cirq.quirk_url_to_circuit(quirk_url, *[, …]) Parses a Cirq circuit out of a Quirk URL.

## Sampling, Simulations, and Data Collection¶

Objects for collecting data about a quantum circuit. Includes methods and classes for defining parameter sweeps, performing simulations, and analyzing results.

 cirq.STATE_VECTOR_LIKE Union type; Union[X, Y] means either X or Y. Returns the big-endian integer specified by the given bits. cirq.big_endian_digits_to_int(digits, *, base) Returns the big-endian integer specified by the given digits and base. cirq.big_endian_int_to_bits(val, *, bit_count) Returns the big-endian bits of an integer. cirq.big_endian_int_to_digits(val, *[, …]) Separates an integer into big-endian digits. cirq.bloch_vector_from_state_vector(state, index) Returns the bloch vector of a qubit. Returns the density matrix of the wavefunction. cirq.dirac_notation(state[, decimals, qid_shape]) Returns the wavefunction as a string in Dirac notation. cirq.final_wavefunction(program, *[, …]) Returns the state vector resulting from acting operations on a state. Creates a copy of val with any symbols or expressions replaced Performs an in-order iteration of the operations (leaves) in an OP_TREE. Performs an in-order iteration OP_TREE, yielding ops and moments. cirq.flatten_with_params(val, params) Creates a copy of val with any symbols or expressions replaced cirq.flatten_with_sweep(val, sweep) Creates a copy of val with any symbols or expressions replaced XEB fidelity estimator based on normalized HOG score. cirq.measure_density_matrix(density_matrix, …) Performs a measurement of the density matrix in the computational basis. cirq.measure_state_vector(state, indices, *) Performs a measurement of the state in the computational basis. cirq.sample(program, *[, noise, …]) Simulates sampling from the given circuit. cirq.sample_density_matrix(density_matrix, …) Samples repeatedly from measurements in the computational basis. cirq.sample_state_vector(state, indices, *) Samples repeatedly from measurements in the computational basis. cirq.sample_sweep(program, params, *[, …]) Runs the supplied Circuit, mimicking quantum hardware. cirq.to_resolvers(sweepable) Convert a Sweepable to a list of ParamResolvers. cirq.to_sweep(sweep_or_resolver_list) Converts the argument into a cirq.Sweep. cirq.to_valid_density_matrix(density_matrix_rep) Verifies the density_matrix_rep is valid and converts it to ndarray form. cirq.to_valid_state_vector(state_rep[, …]) Verifies the state_rep is valid and converts it to ndarray form. cirq.validate_mixture(supports_mixture) Validates that the mixture’s tuple are valid probabilities. cirq.validate_normalized_state(state, *, …) Validates that the given state is a valid wave function. cirq.validate_probability(p, p_str) Validates that a probability is between 0 and 1 inclusively. cirq.xeb_fidelity(circuit, bitstrings[, …]) Estimates XEB fidelity from one circuit using user-supplied estimator. cirq.CircuitSampleJob(circuit, *, repetitions) Describes a sampling task. An efficient simulator for Clifford circuits. A StepResult that includes StateVectorMixin methods. cirq.CliffordTrialResult(params, …) cirq.Collector Collects data from a sampler, in parallel, towards some purpose. cirq.DensityMatrixSimulator(*[, dtype, …]) A simulator for density matrices and noisy quantum circuits. The simulator state for DensityMatrixSimulator cirq.DensityMatrixStepResult(density_matrix, …) A single step in the simulation of the DensityMatrixSimulator. cirq.DensityMatrixTrialResult(params, …) A SimulationTrialResult for DensityMatrixSimulator runs. cirq.ExpressionMap(*args, **kwargs) A dictionary with sympy expressions and symbols for keys and sympy cirq.Linspace(key, start, stop, length) A simple sweep over linearly-spaced values. cirq.ListSweep(resolver_list) A wrapper around a list of ParamResolvers. cirq.ParamDictType alias of typing.Dict cirq.ParamResolver([param_dict]) Resolves sympy.Symbols to actual values. cirq.ParamResolverOrSimilarType Something that can be used to turn parameters into values. cirq.PauliSumCollector(circuit, observable, …) Estimates the energy of a linear combination of Pauli observables. cirq.Points(key, points) A simple sweep with explicitly supplied values. cirq.Product(*factors) Cartesian product of one or more sweeps. cirq.Sampler Something capable of sampling quantum circuits. cirq.SimulatesAmplitudes Simulator that computes final amplitudes of given bitstrings. cirq.SimulatesFinalState Simulator that allows access to a quantum computer’s final state. cirq.SimulatesIntermediateState A SimulatesFinalState that simulates a circuit by moments. cirq.SimulatesIntermediateWaveFunction A simulator that accesses its wave function as it does its simulation. cirq.SimulatesSamples Simulator that mimics running on quantum hardware. cirq.SimulationTrialResult(params, …) Results of a simulation by a SimulatesFinalState. cirq.Simulator(*[, dtype, seed]) A sparse matrix wave function simulator that uses numpy. cirq.SparseSimulatorStep(state_vector, …) A StepResult that includes StateVectorMixin methods. cirq.StateVectorMixin([qubit_map]) A mixin that provide methods for objects that have a state vector. cirq.StepResult([measurements]) Results of a step of a SimulatesIntermediateState. cirq.Sweep A sweep is an iterator over ParamResolvers. cirq.Sweepable An object or collection of objects representing a parameter sweep. cirq.TrialResult(*, params, measurements) The results of multiple executions of a circuit with fixed parameters. cirq.UnitSweep The singleton sweep with no parameters. cirq.WaveFunctionStepResult([measurements]) cirq.WaveFunctionTrialResult(params, …) A SimulationTrialResult that includes the StateVectorMixin methods. cirq.Zip(*sweeps) Zip product (direct sum) of one or more sweeps.

## Visualization¶

Classes and methods for visualizing data.

 Plot the state histogram from a single result with repetitions. Plots the interaction coefficients of many two-qubit operations. cirq.Heatmap(value_map) Distribution of a value in 2D qubit lattice as a color map. A utility class for creating simple text diagrams.

## Magic Method Protocols¶

A magic method is a special named method, like _unitary_, that a class can implement in order to indicate it supports certain functionality. There will be a corresponding global method, such as cirq.unitary, for easily accessing this functionality.

Classes that being with Supports are templates demonstrating and documenting the magic methods that can be implemented.

 cirq.apply_channel(val, args[, default]) High performance evolution under a channel evolution. cirq.apply_mixture(val, args, *[, default]) High performance evolution under a mixture of unitaries evolution. cirq.apply_unitaries(unitary_values, qubits) Apply a series of unitaries onto a state tensor. cirq.apply_unitary(unitary_value, args[, …]) High performance left-multiplication of a unitary effect onto a tensor. cirq.approx_eq(val, other, *[, atol]) Approximately compares two objects. cirq.channel(val[, default]) Returns a list of matrices describing the channel for the given value. cirq.circuit_diagram_info(val[, args, …]) Requests information on drawing an operation in a circuit diagram. cirq.decompose(val, *[, …]) Recursively decomposes a value into cirq.Operations meeting a criteria. cirq.decompose_once(val[, default]) Decomposes a value into operations, if possible. cirq.decompose_once_with_qubits(val, qubits) Decomposes a value into operations on the given qubits. cirq.equal_up_to_global_phase(val, other, *) Determine whether two objects are equal up to global phase. Returns whether the value has a channel representation. Returns whether the value has a mixture representation. Returns whether the value has a mixture channel representation. Determines whether the value has a unitary effect. cirq.inverse(val[, default]) Returns the inverse val**-1 of the given value, if defined. Returns whether or not the given value is a measurement. Returns whether the object is parameterized with any Symbols. cirq.measurement_key(val[, default]) Get the measurement key for the given value. cirq.mixture(val[, default]) Return a sequence of tuples representing a probabilistic combination. cirq.mixture_channel(val[, default]) Return a sequence of tuples for a channel that is a mixture of unitaries. cirq.mul(lhs, rhs[, default]) Returns lhs * rhs, or else a default if the operator is not implemented. cirq.num_qubits(val[, default]) Returns the number of qubits, qudits, or qids val operates on. cirq.pauli_expansion(val, *[, default, atol]) Returns coefficients of the expansion of val in the Pauli basis. cirq.phase_by(val, phase_turns, qubit_index) Returns a phased version of the effect. cirq.pow(val, exponent[, default]) Returns val**factor of the given value, if defined. cirq.qasm(val, *[, args, qubits, default]) Returns QASM code for the given value, if possible. cirq.qid_shape(val[, default]) Returns a tuple describing the number of quantum levels of each cirq.read_json([file_or_fn, json_text, …]) Read a JSON file that optionally contains cirq objects. cirq.resolve_parameters(val, param_resolver) Resolves symbol parameters in the effect using the param resolver. cirq.to_json(obj[, file_or_fn, indent, cls]) Write a JSON file containing a representation of obj. Returns a maximum on the trace distance between this effect’s input cirq.unitary(val[, default]) Returns a unitary matrix describing the given value. cirq.ApplyChannelArgs(target_tensor, …) Arguments for efficiently performing a channel. cirq.ApplyMixtureArgs(target_tensor, …[, …]) Arguments for performing a mixture of unitaries. cirq.ApplyUnitaryArgs(target_tensor, …) Arguments for performing an efficient left-multiplication by a unitary. cirq.CircuitDiagramInfo(wire_symbols[, …]) Describes how to draw an operation in a circuit diagram. cirq.CircuitDiagramInfoArgs(known_qubits, …) A request for information on drawing an operation in a circuit diagram. cirq.QasmArgs([precision, version, …]) cirq.QasmOutput(operations, qubits[, …]) cirq.SupportsApplyChannel(*args, **kwargs) An object that can efficiently implement a channel. cirq.SupportsApplyMixture(*args, **kwargs) An object that can efficiently implement a mixture. cirq.SupportsApproximateEquality(*args, **kwargs) Object which can be compared approximately. cirq.SupportsChannel(*args, **kwargs) An object that may be describable as a quantum channel. cirq.SupportsCircuitDiagramInfo(*args, **kwargs) A diagrammable operation on qubits. An object that can be efficiently left-multiplied into tensors. cirq.SupportsDecompose(*args, **kwargs) An object that can be decomposed into simpler operations. cirq.SupportsDecomposeWithQubits(*args, **kwargs) An object that can be decomposed into operations on given qubits. Object which can be compared for equality mod global phase. cirq.SupportsExplicitHasUnitary(*args, **kwargs) An object that explicitly specifies whether it has a unitary effect. cirq.SupportsExplicitNumQubits(*args, **kwargs) A unitary, channel, mixture or other object that operates on a known cirq.SupportsExplicitQidShape(*args, **kwargs) A unitary, channel, mixture or other object that operates on a known cirq.SupportsJSON(*args, **kwargs) An object that can be turned into JSON dictionaries. cirq.SupportsMeasurementKey(*args, **kwargs) An object that is a measurement and has a measurement key. cirq.SupportsMixture(*args, **kwargs) An object that may be describable as a probabilistic combination. cirq.SupportsParameterization(*args, **kwargs) An object that can be parameterized by Symbols and resolved cirq.SupportsPhase(*args, **kwargs) An effect that can be phased around the Z axis of target qubits. cirq.SupportsQasm(*args, **kwargs) An object that can be turned into QASM code. cirq.SupportsQasmWithArgs(*args, **kwargs) An object that can be turned into QASM code. An object that can be turned into QASM code if it knows its qubits. cirq.SupportsTraceDistanceBound(*args, **kwargs) An effect with known bounds on how easy it is to detect. cirq.SupportsUnitary(*args, **kwargs) An object that may be describable by a unitary matrix.

## Optimization¶

Classes and methods for rewriting circuits.

 Decomposes operations into an FSimGate near theta=pi/2, phi=0. Canonicalizes runs of single-qubit rotations in a circuit. Implements a single-qubit operation with few gates. Implements a single-qubit operation with few rotations. Implements a single-qubit operation with a PhasedX and Z gate. Decomposes a 2x2 unitary M into U^-1 * diag(1, r) * U * diag(g, g). Decomposes a two-qubit operation into Z/XY/CZ gates. Attempts to convert strange multi-qubit gates into CZ and single qubit cirq.DropEmptyMoments Removes empty moments from a circuit. cirq.DropNegligible([tolerance]) An optimization pass that removes operations with tiny effects. cirq.EjectPhasedPaulis([tolerance, …]) Pushes X, Y, and PhasedX gates towards the end of the circuit. cirq.EjectZ([tolerance, eject_parameterized]) Pushes Z gates towards the end of the circuit. cirq.ExpandComposite([no_decomp]) An optimizer that expands composite operations via cirq.decompose. cirq.MergeInteractions([tolerance, …]) Combines series of adjacent one and two-qubit gates operating on a cirq.MergeSingleQubitGates(*[, rewriter, …]) Optimizes runs of adjacent unitary 1-qubit operations. cirq.PointOptimizationSummary(clear_span, …) A description of a local optimization to perform. cirq.PointOptimizer([post_clean_up]) Makes circuit improvements focused on a specific location. Move measurements to the end of the circuit.

## Experiments¶

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

 Estimate single-qubit readout error. Generates Google Random Circuits v2 as in github.com/sboixo/GRCS Generates Google Random Circuits v2 in Bristlecone. Generates Google Random Circuits v2 as in github.com/sboixo/GRCS cirq.linear_xeb_fidelity(circuit, bitstrings) Estimates XEB fidelity from one circuit using linear estimator. Linear XEB fidelity estimator. cirq.log_xeb_fidelity(circuit, bitstrings[, …]) Estimates XEB fidelity from one circuit using logarithmic estimator. Logarithmic XEB fidelity estimator. Builds a sequence of gates that entangle all pairs of qubits on a grid. Cross-entropy benchmarking (XEB) of multiple qubits. cirq.experiments.rabi_oscillations(sampler, …) Runs a Rabi oscillation experiment. Clifford-based randomized benchmarking (RB) of a single qubit. Single-qubit state tomography. cirq.experiments.t1_decay(sampler, *, qubit, …) Runs a t1 decay experiment. Clifford-based randomized benchmarking (RB) of two qubits. Two-qubit state tomography. Results from a cross-entropy benchmarking (XEB) experiment. cirq.experiments.RabiResult(rabi_angles, …) Results from a Rabi oscillation experiment. Results from a randomized benchmarking experiment. Result of estimating single qubit readout error. Results from a Rabi oscillation experiment. cirq.experiments.TomographyResult(density_matrix) Results from a state tomography experiment.

## Ion traps and neutral atoms¶

Support for ion trap an neutral atom devices.

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

Functionality specific to quantum hardware and services from Google.

 cirq.google.SQRT_ISWAP_GATESET Gate set with sqrt(iswap) as the core 2 qubit interaction. cirq.google.SYC The Sycamore gate is a two-qubit gate equivalent to FSimGate(π/2, π/6). cirq.google.SYC_GATESET Gate set with fsim(pi/4, pi/6) as the core 2 qubit interaction. cirq.google.XMON Gate set for XMON devices. Convert a circuit into an iterable of proto dictionaries. Convert proto dictionaries into a Circuit for the given device. Returns an Engine instance configured using environment variables. cirq.google.gate_to_proto_dict(gate, qubits) Check if a gate is a native xmon gate. Check if the gate corresponding to an operation is a native xmon gate. cirq.google.line_on_device(device, length[, …]) Searches for linear sequence of qubits on device. Optimizes a circuit for Google devices. cirq.google.optimized_for_xmon(circuit[, …]) cirq.google.pack_results(measurements) Pack measurement results into a byte string. cirq.google.sweep_from_proto_dict(param_sweep) cirq.google.sweep_to_proto_dict(sweep[, …]) Converts sweep into an equivalent protobuf representation. cirq.google.unpack_results(data, …) Unpack data from a bitstring into individual measurement results. cirq.google.xmon_op_from_proto_dict(proto_dict) Convert the proto dictionary to the corresponding operation. Linearized sequence search using simulated annealing method. cirq.google.Bristlecone 72 xmon qubit device. cirq.google.Calibration(calibration) A convenience wrapper for calibrations that acts like a dictionary. Attempts to convert gates into ISWAP**-0.5 gates. Attempts to convert non-native gates into SycamoreGates. cirq.google.ConvertToXmonGates([ignore_failures]) Attempts to convert strange gates into XmonGates. Specification of the arguments to deserialize an argument to a gate. cirq.google.Engine(project_id[, version, …]) Runs programs via the Quantum Engine API. cirq.google.EngineJob(job_config, job, engine) A job created via the Quantum Engine API. cirq.google.EngineProgram(resource_name, engine) A program created via the Quantum Engine API. cirq.google.Foxtail 72 xmon qubit device. Describes how to deserialize a proto to a given Gate type. cirq.google.GateOpSerializer(*, gate_type, …) Describes how to serialize a GateOperation for a given Gate type. Greedy search method for linear sequence of qubits on a chip. cirq.google.JobConfig([job_id]) Configuration for a job to run on the Quantum Engine API. cirq.google.LinePlacementStrategy Choice and options for the line placement calculation method. cirq.google.ProtoVersion Protocol buffer version to use for requests to the quantum engine. cirq.google.QuantumEngineSampler(*, engine, …) A sampler that samples from processors managed by the Quantum Engine. cirq.google.SerializableDevice(qubits, …) Device object generated from a device specification proto. A class for serializing and deserializing programs and operations. cirq.google.SerializingArg(serialized_name, …) Specification of the arguments for a Gate and its serialization. cirq.google.Sycamore Device object generated from a device specification proto. cirq.google.Sycamore23 Device object generated from a device specification proto. The Sycamore gate is a two-qubit gate equivalent to FSimGate(π/2, π/6). cirq.google.XmonDevice(measurement_duration, …) A device with qubits placed in a grid.

## Contrib¶

Contributed code that is not yet considered stable, may not yet fit well with the main library, and may require extra dependencies to be installed (via python -m pip install cirq[contrib]). A waiting area. All packages within contrib may change without notice.

 cirq.contrib.acquaintance Tools for creating and using acquaintance strategies. cirq.contrib.paulistring Methods related to optimizing and transforming PauliStrings. cirq.contrib.qcircuit Converts cirq circuits into latex using qcircuit. cirq.contrib.quirk Converts cirq circuits into quirk circuits.

## Coding and Testing Tools¶

These objects are not relevant when simply constructing and sampling circuits, but are useful for customization tasks like defining and validating a custom operation.

 cirq.alternative(*, requires, implementation) A decorator indicating an abstract method with an alternative default cirq.obj_to_dict_helper(obj, attribute_names) Construct a dictionary containing attributes from obj cirq.value_equality([cls, unhashable, …]) Implements eq/ne/hash via a value_equality_values method. cirq.ABCMetaImplementAnyOneOf A metaclass extending abc.ABCMeta for defining abstract base cirq.ArithmeticOperation A helper class for implementing reversible classical arithmetic. cirq.InterchangeableQubitsGate Indicates operations should be equal under some qubit permutations. cirq.LinearDict([terms, validator]) Represents linear combination of things. cirq.PeriodicValue(value, period) Wrapper for periodic numerical values. Checks if a ~= b * exp(i t) for some t. Determines if two circuits have equivalent effects. Uses val._unitary_ to check val._phase_by_’s behavior. Checks that an EigenGate subclass is internally consistent and has a Checks that eval(repr(v)) == v. Tests whether a value’s apply_unitary is correct. Tests whether a value’s apply_unitary is correct. Tests whether a value’s _qid_shape_ and _num_qubits_ are cirq.testing.assert_has_diagram(actual, …) Determines if a given circuit has the desired text diagram. Checks that a value is internally consistent and has a good repr. Tests that the given object can serialized and de-serialized Checks Pauli expansion against unitary matrix. Uses val._unitary_ to check val._phase_by_’s behavior. Uses val._unitary_ to check val._qasm_’s behavior. cirq.testing.assert_same_circuits(actual, …) Asserts that two circuits are identical, with a descriptive error. cirq.testing.asyncio_pending(future[, timeout]) Gives the given future a chance to complete, and determines if it didn’t. cirq.testing.random_circuit(qubits, …[, …]) Generates a random circuit. cirq.testing.random_orthogonal(dim, *[, …]) Returns a random orthogonal matrix distributed with Haar measure. Returns a random special orthogonal matrix distributed with Haar measure. Returns a random special unitary distributed with Haar measure. cirq.testing.random_superposition(dim, *[, …]) Returns a random unit-length vector from the uniform distribution. cirq.testing.random_unitary(dim, *[, …]) Returns a random unitary matrix distributed with Haar measure. Tests equality against user-provided disjoint equivalence groups. Tests ordering against user-provided disjoint ordered groups or items.

## Algebra and Representation¶

 cirq.CONTROL_TAG A special indicator value for cirq.kron_with_controls. cirq.DURATION_LIKE A cirq.Duration or value that can trivially converted to one. cirq.all_near_zero(a, *[, atol]) Checks if the tensor’s elements are all near zero. cirq.all_near_zero_mod(a, period, *[, atol]) Checks if the tensor’s elements are all near multiples of the period. cirq.allclose_up_to_global_phase(a, b, *[, …]) Determines if a ~= b * exp(i t) for some t. cirq.apply_matrix_to_slices(target, matrix, …) Left-multiplies an NxN matrix onto N slices of a numpy array. cirq.axis_angle(single_qubit_unitary) Decomposes a single-qubit unitary into axis, angle, and global phase. Finds orthogonal matrices that diagonalize both mat1 and mat2. Finds orthogonal matrices L, R such that L @ matrix @ R is diagonal. cirq.block_diag(*blocks) Concatenates blocks into a block diagonal matrix. cirq.canonicalize_half_turns(half_turns) Wraps the input into the range (-1, +1]. Returns a canonicalized half_turns based on the given arguments. Returns a half_turns value based on the given arguments. cirq.commutes(left_val, right_val, *[, …]) Determines whether two values commute. cirq.definitely_commutes(left_val, right_val, *) Determines whether two values definitely commute. Returns an orthogonal matrix that diagonalizes both given matrices. Returns an orthogonal matrix that diagonalizes the given matrix. cirq.dot(*values) Computes the dot/matrix product of a sequence of values. Computes coefficients of expansion of m in basis. cirq.eye_tensor(half_shape, *, dtype) Returns an identity matrix reshaped into a tensor. Computes Hilbert-Schmidt inner product of two matrices. cirq.is_diagonal(matrix, *[, atol]) Determines if a matrix is a approximately diagonal. cirq.is_hermitian(matrix, *[, rtol, atol]) Determines if a matrix is approximately Hermitian. cirq.is_negligible_turn(turns, tolerance) cirq.is_orthogonal(matrix, *[, rtol, atol]) Determines if a matrix is approximately orthogonal. cirq.is_special_orthogonal(matrix, *[, …]) Determines if a matrix is approximately special orthogonal. cirq.is_special_unitary(matrix, *[, rtol, atol]) Determines if a matrix is approximately unitary with unit determinant. cirq.is_unitary(matrix, *[, rtol, atol]) Determines if a matrix is approximately unitary. cirq.kak_canonicalize_vector(x, y, z[, atol]) Canonicalizes an XX/YY/ZZ interaction by swap/negate/shift-ing axes. cirq.kak_decomposition(unitary_object, *[, …]) Decomposes a 2-qubit unitary into 1-qubit ops and XX/YY/ZZ interactions. cirq.kak_vector(unitary, *[, rtol, atol, …]) Compute the KAK vectors of one or more two qubit unitaries. cirq.kron(*factors[, shape_len]) Computes the kronecker product of a sequence of values. cirq.kron_bases(*bases[, repeat]) Creates tensor product of bases. Splits a 4x4 matrix U = kron(A, B) into A, B, and a global factor. cirq.kron_with_controls(*factors) Computes the kronecker product of a sequence of values and control tags. cirq.map_eigenvalues(matrix, func, *[, …]) Applies a function to the eigenvalues of a matrix. Phases the given matrices so that they agree on the phase of one entry. Computes linear combination of basis vectors with given coefficients. cirq.one_hot(*[, index, value]) Returns a numpy array with all 0s and a single non-zero entry(default 1). cirq.partial_trace(tensor, keep_indices) Takes the partial trace of a given tensor. Raises a matrix with two opposing eigenvalues to a power. cirq.slice_for_qubits_equal_to(target_qubit_axes) Returns an index corresponding to a desired subset of an np.ndarray. cirq.so4_to_magic_su2s(mat, *[, rtol, atol, …]) Finds 2x2 special-unitaries A, B where mat = Mag.H @ kron(A, B) @ Mag. cirq.subwavefunction(wavefunction, …[, …]) Attempts to factor a wavefunction into two parts and return one of them. cirq.targeted_conjugate_about(tensor, …[, …]) Conjugates the given tensor about the target tensor. cirq.targeted_left_multiply(left_matrix, …) Left-multiplies the given axes of the target tensor by the given matrix. cirq.von_neumann_entropy(density_matrix) Calculates von Neumann entropy of density matrix in bits. Returns a mixture representing a wavefunction with only some qubits kept. cirq.AxisAngleDecomposition(*, angle, axis, …) Represents a unitary operation as an axis, angle, and global phase. cirq.Duration([value, picos, nanos, micros, …]) A time delta that supports symbols and picosecond accuracy. cirq.KakDecomposition(*[, global_phase, …]) A convenient description of an arbitrary two-qubit operation. cirq.Timestamp(*[, picos, nanos]) A location in time with picosecond accuracy.

## Internal Implementation Details¶

Neither users nor developers will commonly refer to these objects, but they play important roles in the internal machinery of the library.

 cirq.ConstantQubitNoiseModel(qubit_noise_gate) Applies noise to each qubit individually at the start of every moment. Represents linear operator defined by a linear combination of gates. Represents operator defined by linear combination of gate operations. A Pauli operation applied to a qubit. cirq.TParamVal A value that a parameter resolver may return for a symbol.

## Deprecated¶

These objects will be removed in a future version of the library.

 cirq.MS(rads) THIS FUNCTION IS DEPRECATED. cirq.Rx(rads) THIS FUNCTION IS DEPRECATED. cirq.Ry(rads) THIS FUNCTION IS DEPRECATED. cirq.Rz(rads) THIS FUNCTION IS DEPRECATED. cirq.GivensRotation(angle_rads) THIS FUNCTION IS DEPRECATED. cirq.ISwapRotation(angle_rads) THIS FUNCTION IS DEPRECATED. cirq.ThreeQubitGate A gate that must be applied to exactly three qubits. cirq.TwoQubitGate A gate that must be applied to exactly two qubits.