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 and schedules.

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.

cirq.LineQubit(x)

A qubit on a 1d lattice with nearest-neighbor connectivity.

cirq.NamedQubit(name)

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.GivensRotation(angle_rads)

THIS FUNCTION IS DEPRECATED.

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.ISwapRotation(angle_rads)

THIS FUNCTION IS DEPRECATED.

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.QuantumFourierTransformGate(num_qubits, *)

Switches from the computational basis to the frequency basis.

cirq.SingleQubitGate

A gate that must be applied to exactly one qubit.

cirq.SingleQubitMatrixGate(matrix)

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.

cirq.TwoQubitMatrixGate(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.

cirq.amplitude_damp(gamma)

Returns an AmplitudeDampingChannel with the given probability gamma.

cirq.asymmetric_depolarize(p_x, p_y, p_z)

Returns a AsymmetricDepolarizingChannel with given parameter.

cirq.bit_flip([p])

Construct a BitFlipChannel that flips a qubit state with probability

cirq.depolarize(p)

Returns a DepolarizingChannel with given probability of error.

cirq.generalized_amplitude_damp(p, gamma)

Returns a GeneralizedAmplitudeDampingChannel with the given

cirq.phase_damp(gamma)

Creates a PhaseDampingChannel with damping constant gamma.

cirq.phase_flip([p])

Returns a PhaseFlipChannel that flips a qubit’s phase with probability

cirq.reset(qubit)

Returns a ResetChannel on the given qubit.

cirq.AmplitudeDampingChannel(gamma)

Dampen qubit amplitudes through dissipation.

cirq.AsymmetricDepolarizingChannel(p_x, p_y, p_z)

A channel that depolarizes asymmetrically along different directions.

cirq.BitFlipChannel(p)

Probabilistically flip a qubit from 1 to 0 state or vice versa.

cirq.DepolarizingChannel(p)

A channel that depolarizes a qubit.

cirq.GeneralizedAmplitudeDampingChannel(p, gamma)

Dampen qubit amplitudes through non ideal dissipation.

cirq.NoiseModel

Replaces operations and moments with noisy counterparts.

cirq.PhaseDampingChannel(gamma)

Dampen qubit phase.

cirq.PhaseFlipChannel(p)

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_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.

cirq.SingleQubitCliffordGate(*, …)

Any single qubit Clifford rotation.

cirq.StabilizerStateChForm(num_qubits[, …])

A representation of stabilizer states using the CH form,

Circuits and Schedules

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.

cirq.freeze_op_tree(root)

Replaces all iterables in the OP_TREE with tuples.

cirq.moment_by_moment_schedule(device, circuit)

Returns a schedule aligned with the moment structure of the Circuit.

cirq.op_gate_isinstance(op, gate_type)

THIS FUNCTION IS DEPRECATED.

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 simplified time-slice of operations within a sequenced 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.

cirq.Schedule(device[, scheduled_operations])

A quantum program with operations happening at specific times.

cirq.ScheduledOperation(time, duration, …)

An operation that happens over a specified time interval.

cirq.Unique(val)

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.

cirq.big_endian_bits_to_int(bits)

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.

cirq.density_matrix_from_state_vector(state)

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.

cirq.flatten(val)

Creates a copy of val with any symbols or expressions replaced

cirq.flatten_to_ops(root)

Performs an in-order iteration of the operations (leaves) in an OP_TREE.

cirq.flatten_to_ops_or_moments(root)

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

cirq.hog_score_xeb_fidelity_from_probabilities(…)

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 or schedule.

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 or Schedule, 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.

cirq.CliffordSimulator()

An efficient simulator for Clifford circuits.

cirq.CliffordSimulatorStepResult(state, …)

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.

cirq.DensityMatrixSimulatorState(…)

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.WaveFunctionSimulatorState(…)

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.

cirq.plot_state_histogram(result)

Plot the state histogram from a single result with repetitions.

cirq.scatter_plot_normalized_kak_interaction_coefficients(…)

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.

cirq.TextDiagramDrawer()

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.

cirq.has_channel(val)

Returns whether the value has a channel representation.

cirq.has_mixture(val)

Returns whether the value has a mixture representation.

cirq.has_mixture_channel(val)

Returns whether the value has a mixture channel representation.

cirq.has_unitary(val)

Determines whether the value has a unitary effect.

cirq.inverse(val[, default])

Returns the inverse val**-1 of the given value, if defined.

cirq.is_measurement(val)

Returns whether or not the given value is a measurement.

cirq.is_parameterized(val)

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.

cirq.trace_distance_bound(val)

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.

cirq.SupportsConsistentApplyUnitary(*args, …)

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.

cirq.SupportsEqualUpToGlobalPhase(*args, …)

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.

cirq.SupportsQasmWithArgsAndQubits(*args, …)

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.

cirq.merge_single_qubit_gates_into_phased_x_z(circuit)

Canonicalizes runs of single-qubit rotations in a circuit.

cirq.single_qubit_matrix_to_gates(mat[, …])

Implements a single-qubit operation with few gates.

cirq.single_qubit_matrix_to_pauli_rotations(mat)

Implements a single-qubit operation with few rotations.

cirq.single_qubit_matrix_to_phased_x_z(mat)

Implements a single-qubit operation with a PhasedX and Z gate.

cirq.single_qubit_op_to_framed_phase_form(mat)

Decomposes a 2x2 unitary M into U^-1 * diag(1, r) * U * diag(g, g).

cirq.two_qubit_matrix_to_operations(q0, q1, …)

Decomposes a two-qubit operation into Z/XY/CZ gates.

cirq.ConvertToCzAndSingleGates([…])

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.

cirq.SynchronizeTerminalMeasurements([…])

Move measurements to the end of the circuit.

Experiments

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

cirq.generate_boixo_2018_supremacy_circuits_v2(…)

Generates Google Random Circuits v2 as in github.com/sboixo/GRCS

cirq.generate_boixo_2018_supremacy_circuits_v2_bristlecone(…)

Generates Google Random Circuits v2 in Bristlecone.

cirq.generate_boixo_2018_supremacy_circuits_v2_grid(…)

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.

cirq.linear_xeb_fidelity_from_probabilities(…)

Linear XEB fidelity estimator.

cirq.log_xeb_fidelity(circuit, bitstrings[, …])

Estimates XEB fidelity from one circuit using logarithmic estimator.

cirq.log_xeb_fidelity_from_probabilities(…)

Logarithmic XEB fidelity estimator.

cirq.experiments.build_entangling_layers(…)

Builds a sequence of gates that entangle all pairs of qubits on a grid.

cirq.experiments.cross_entropy_benchmarking(…)

Cross-entropy benchmarking (XEB) of multiple qubits.

cirq.experiments.rabi_oscillations(sampler, …)

Runs a Rabi oscillation experiment.

cirq.experiments.single_qubit_randomized_benchmarking(…)

Clifford-based randomized benchmarking (RB) of a single qubit.

cirq.experiments.single_qubit_state_tomography(…)

Single-qubit state tomography.

cirq.experiments.t1_decay(sampler, *, qubit, …)

Runs a t1 decay experiment.

cirq.experiments.two_qubit_randomized_benchmarking(…)

Clifford-based randomized benchmarking (RB) of two qubits.

cirq.experiments.two_qubit_state_tomography(…)

Two-qubit state tomography.

cirq.experiments.CrossEntropyResult(…)

Results from a cross-entropy benchmarking (XEB) experiment.

cirq.experiments.RabiResult(rabi_angles, …)

Results from a Rabi oscillation experiment.

cirq.experiments.RandomizedBenchMarkResult(…)

Results from a randomized benchmarking experiment.

cirq.experiments.T1DecayResult(data)

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)

THIS FUNCTION IS DEPRECATED.

cirq.ms(rads)

The Mølmer–Sørensen gate, a native two-qubit operation in ion traps.

cirq.is_native_neutral_atom_gate(gate)

cirq.is_native_neutral_atom_op(operation)

cirq.two_qubit_matrix_to_ion_operations(q0, …)

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.

Google

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.

cirq.google.engine_from_environment()

Returns an Engine instance configured using environment variables.

cirq.google.gate_to_proto_dict(gate, qubits)

cirq.google.is_native_xmon_gate(gate)

Check if a gate is a native xmon gate.

cirq.google.is_native_xmon_op(op)

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.

cirq.google.optimized_for_xmon(circuit[, …])

Optimizes a circuit with XmonDevice in mind.

cirq.google.pack_results(measurements)

Pack measurement results into a byte string.

cirq.google.schedule_from_proto_dicts(…)

Convert proto dictionaries into a Schedule for the given device.

cirq.google.schedule_to_proto_dicts(schedule)

Convert a schedule into an iterable of proto dictionaries.

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.

cirq.google.AnnealSequenceSearchStrategy([…])

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.

cirq.google.ConvertToXmonGates([ignore_failures])

Attempts to convert strange gates into XmonGates.

cirq.google.DeserializingArg(…[, …])

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.

cirq.google.GateOpDeserializer(…[, …])

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.

cirq.google.GreedySequenceSearchStrategy([…])

Greedy search method for linear sequence of qubits on a chip.

cirq.google.JobConfig([job_id, gcs_prefix, …])

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.

cirq.google.SerializableGateSet(…)

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.SycamoreGate()

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.

cirq.contrib.tpu

Functionality for simulating circuits with google cloud TPUs.

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.

cirq.testing.assert_allclose_up_to_global_phase(…)

Checks if a ~= b * exp(i t) for some t.

cirq.testing.assert_asyncio_still_running(future)

Checks that the given asyncio future has not completed.

cirq.testing.assert_asyncio_will_have_result(future)

Checks that the given asyncio future completes with the given value.

cirq.testing.assert_asyncio_will_raise(…)

Checks that the given asyncio future fails with a matching error.

cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent(…)

Determines if two circuits have equivalent effects.

cirq.testing.assert_decompose_is_consistent_with_unitary(val)

Uses val._unitary_ to check val._phase_by_’s behavior.

cirq.testing.assert_eigengate_implements_consistent_protocols(…)

Checks that an EigenGate subclass is internally consistent and has a

cirq.testing.assert_equivalent_repr(value, *)

Checks that eval(repr(v)) == v.

cirq.testing.assert_has_consistent_apply_unitary(val, *)

Tests whether a value’s apply_unitary is correct.

cirq.testing.assert_has_consistent_apply_unitary_for_various_exponents(val, *)

Tests whether a value’s apply_unitary is correct.

cirq.testing.assert_has_consistent_qid_shape(val)

Tests whether a value’s _qid_shape_ and _num_qubits_ are

cirq.testing.assert_has_consistent_trace_distance_bound(val)

cirq.testing.assert_has_diagram(actual, …)

Determines if a given circuit has the desired text diagram.

cirq.testing.assert_implements_consistent_protocols(val, *)

Checks that a value is internally consistent and has a good repr.

cirq.testing.assert_pauli_expansion_is_consistent_with_unitary(val)

Checks Pauli expansion against unitary matrix.

cirq.testing.assert_phase_by_is_consistent_with_unitary(val)

Uses val._unitary_ to check val._phase_by_’s behavior.

cirq.testing.assert_qasm_is_consistent_with_unitary(val)

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.highlight_text_differences(…)

cirq.testing.nonoptimal_toffoli_circuit(q0, …)

cirq.testing.random_circuit(qubits, …[, …])

Generates a random circuit.

cirq.testing.random_orthogonal(dim, *[, …])

Returns a random orthogonal matrix distributed with Haar measure.

cirq.testing.random_special_orthogonal(dim, *)

Returns a random special orthogonal matrix distributed with Haar measure.

cirq.testing.random_special_unitary(dim, *)

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.

cirq.testing.EqualsTester()

Tests equality against user-provided disjoint equivalence groups.

cirq.testing.OrderTester()

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.

cirq.bidiagonalize_real_matrix_pair_with_symmetric_products(…)

Finds orthogonal matrices that diagonalize both mat1 and mat2.

cirq.bidiagonalize_unitary_with_special_orthogonals(mat, *)

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].

cirq.chosen_angle_to_canonical_half_turns([…])

Returns a canonicalized half_turns based on the given arguments.

cirq.chosen_angle_to_half_turns([…])

Returns a half_turns value based on the given arguments.

cirq.commutes(m1, m2, *[, rtol, atol])

Determines if two matrices approximately commute.

cirq.diagonalize_real_symmetric_and_sorted_diagonal_matrices(…)

Returns an orthogonal matrix that diagonalizes both given matrices.

cirq.diagonalize_real_symmetric_matrix(matrix, *)

Returns an orthogonal matrix that diagonalizes the given matrix.

cirq.dot(*values)

Computes the dot/matrix product of a sequence of values.

cirq.expand_matrix_in_orthogonal_basis(m, basis)

Computes coefficients of expansion of m in basis.

cirq.eye_tensor(half_shape, *, dtype)

Returns an identity matrix reshaped into a tensor.

cirq.hilbert_schmidt_inner_product(m1, m2)

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.

cirq.kron_factor_4x4_to_2x2s(matrix)

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.

cirq.match_global_phase(a, b)

Phases the given matrices so that they agree on the phase of one entry.

cirq.matrix_from_basis_coefficients(…)

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.

cirq.reflection_matrix_pow(…)

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.

cirq.wavefunction_partial_trace_as_mixture(…)

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.

cirq.LinearCombinationOfGates(terms)

Represents linear operator defined by a linear combination of gates.

cirq.LinearCombinationOfOperations(terms)

Represents operator defined by linear combination of gate operations.

cirq.SingleQubitPauliStringGateOperation(…)

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.ThreeQubitGate

A gate that must be applied to exactly three qubits.

cirq.TwoQubitGate

A gate that must be applied to exactly two qubits.