INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Computes SamplesDisplays in the supplied Circuit or Schedule. In contrast to `compute_displays`, this allows for sweeping over different parameter values. Args: program: The circuit or schedule to simulate. params: Parameters to run with the program. Returns: ...
def compute_samples_displays_sweep( self, program: Union[circuits.Circuit, schedules.Schedule], params: Optional[study.Sweepable] = None ) -> List[study.ComputeDisplaysResult]: """Computes SamplesDisplays in the supplied Circuit or Schedule. In contrast to `compu...
Simulates the supplied Circuit or Schedule. This method returns a result which allows access to the entire wave function. Args: program: The circuit or schedule to simulate. param_resolver: Parameters to run with the program. qubit_order: Determines the cano...
def simulate( self, program: Union[circuits.Circuit, schedules.Schedule], param_resolver: 'study.ParamResolverOrSimilarType' = None, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, initial_state: Any = None, ) -> 'SimulationTrialResult': """Simulates the s...
Simulates the supplied Circuit or Schedule. This method returns a result which allows access to the entire wave function. In contrast to simulate, this allows for sweeping over different parameter values. Args: program: The circuit or schedule to simulate. param...
def simulate_sweep( self, program: Union[circuits.Circuit, schedules.Schedule], params: study.Sweepable, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, initial_state: Any = None, ) -> List['SimulationTrialResult']: """Simulates the supplied Circuit or Sch...
Simulates the supplied Circuit or Schedule. This method returns a result which allows access to the entire wave function. In contrast to simulate, this allows for sweeping over different parameter values. Args: program: The circuit or schedule to simulate. param...
def simulate_sweep( self, program: Union[circuits.Circuit, schedules.Schedule], params: study.Sweepable, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, initial_state: Any = None, ) -> List['SimulationTrialResult']: """Simulates the supplied Circuit or Sch...
Returns an iterator of StepResults for each moment simulated. If the circuit being simulated is empty, a single step result should be returned with the state being set to the initial state. Args: circuit: The Circuit to simulate. param_resolver: A ParamResolver for dete...
def simulate_moment_steps( self, circuit: circuits.Circuit, param_resolver: 'study.ParamResolverOrSimilarType' = None, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, initial_state: Any = None ) -> Iterator: """Returns an iterator of StepResults for each m...
Iterator over StepResult from Moments of a Circuit. Args: circuit: The circuit to simulate. param_resolver: A ParamResolver for determining values of Symbols. qubit_order: Determines the canonical ordering of the qubits. This is often used in ...
def _simulator_iterator( self, circuit: circuits.Circuit, param_resolver: study.ParamResolver, qubit_order: ops.QubitOrderOrList, initial_state: Any, ) -> Iterator: """Iterator over StepResult from Moments of a Circuit. Args: circuit: The circuit ...
This method can be overridden to creation of a trial result. Args: params: The ParamResolver for this trial. measurements: The measurement results for this trial. final_simulator_state: The final state of the simulator for the StepResult. Returns: ...
def _create_simulator_trial_result(self, params: study.ParamResolver, measurements: Dict[str, np.ndarray], final_simulator_state: Any) \ -> 'SimulationTrialResult': """This method can be overridden to creation of a trial result. Args: params: The ParamResolve...
Samples from the system at this point in the computation. Note that this does not collapse the wave function. Args: qubits: The qubits to be sampled in an order that influence the returned measurement results. repetitions: The number of samples to take. ...
def sample(self, qubits: List[ops.Qid], repetitions: int = 1) -> np.ndarray: """Samples from the system at this point in the computation. Note that this does not collapse the wave function. Args: qubits: The qubits to be sampled in an order that influe...
Samples from the system at this point in the computation. Note that this does not collapse the wave function. In contrast to `sample` which samples qubits, this takes a list of `cirq.GateOperation` instances whose gates are `cirq.MeasurementGate` instances and then returns a mapping fr...
def sample_measurement_ops( self, measurement_ops: List[ops.GateOperation], repetitions: int = 1) -> Dict[str, np.ndarray]: """Samples from the system at this point in the computation. Note that this does not collapse the wave function. In contrast to `sampl...
Decomposition ignores connectivity.
def xor_nonlocal_decompose(qubits: Iterable[raw_types.Qid], onto_qubit: raw_types.Qid ) -> Iterable[raw_types.Operation]: """Decomposition ignores connectivity.""" for qubit in qubits: if qubit != onto_qubit: yield common_gates.CNOT(qubit,...
Overrides sympy and numpy returning repr strings that don't parse.
def proper_repr(value: Any) -> str: """Overrides sympy and numpy returning repr strings that don't parse.""" if isinstance(value, sympy.Basic): result = sympy.srepr(value) # HACK: work around https://github.com/sympy/sympy/issues/16074 # (only handles a few cases) fixed_tokens ...
Runs a Rabi oscillation experiment. Rotates a qubit around the x-axis of the Bloch sphere by a sequence of Rabi angles evenly spaced between 0 and max_angle. For each rotation, repeat the circuit a number of times and measure the average probability of the qubit being in the |1> state. Args: ...
def rabi_oscillations(sampler: sim.Sampler, qubit: devices.GridQubit, max_angle: float = 2 * np.pi, *, repetitions: int = 1000, num_points: int = 200) -> RabiResult: """Runs a Rabi oscillation experiment. ...
Clifford-based randomized benchmarking (RB) of a single qubit. A total of num_circuits random circuits are generated, each of which contains a fixed number of single-qubit Clifford gates plus one additional Clifford that inverts the whole sequence and a measurement in the z-basis. Each circuit is repea...
def single_qubit_randomized_benchmarking( sampler: sim.Sampler, qubit: devices.GridQubit, use_xy_basis: bool = True, *, num_clifford_range: Sequence[int] = range(10, 100, 10), num_circuits: int = 20, repetitions: int = 1000) -> RandomizedBenchMarkResult: """Cl...
Clifford-based randomized benchmarking (RB) of two qubits. A total of num_circuits random circuits are generated, each of which contains a fixed number of two-qubit Clifford gates plus one additional Clifford that inverts the whole sequence and a measurement in the z-basis. Each circuit is repeated a n...
def two_qubit_randomized_benchmarking( sampler: sim.Sampler, first_qubit: devices.GridQubit, second_qubit: devices.GridQubit, *, num_clifford_range: Sequence[int] = range(5, 50, 5), num_circuits: int = 20, repetitions: int = 1000) -> RandomizedBenchMarkResult: ...
Single-qubit state tomography. The density matrix of the output state of a circuit is measured by first doing projective measurements in the z-basis, which determine the diagonal elements of the matrix. A X/2 or Y/2 rotation is then added before the z-basis measurement, which determines the imaginary a...
def single_qubit_state_tomography(sampler: sim.Sampler, qubit: devices.GridQubit, circuit: circuits.Circuit, repetitions: int = 1000) -> TomographyResult: """Single-qubit state tomography. The density matrix o...
r"""Two-qubit state tomography. To measure the density matrix of the output state of a two-qubit circuit, different combinations of I, X/2 and Y/2 operations are applied to the two qubits before measurements in the z-basis to determine the state probabilities P_00, P_01, P_10. The density matrix r...
def two_qubit_state_tomography(sampler: sim.Sampler, first_qubit: devices.GridQubit, second_qubit: devices.GridQubit, circuit: circuits.Circuit, repetitions: int = 1000) -> TomographyResult: r...
Generates a two-qubit Clifford gate. An integer (idx) from 0 to 11519 is used to generate a two-qubit Clifford gate which is constructed with single-qubit X and Y rotations and CZ gates. The decomposition of the Cliffords follow those described in the appendix of Barends et al., Nature 508, 500. T...
def _two_qubit_clifford(q_0: devices.GridQubit, q_1: devices.GridQubit, idx: int, cliffords: Cliffords) -> Iterator[ops.OP_TREE]: """Generates a two-qubit Clifford gate. An integer (idx) from 0 to 11519 is used to generate a two-qubit Clifford gate which is c...
Returns a sequence of tuple pairs with the first item being a Rabi angle and the second item being the corresponding excited state probability.
def data(self) -> Sequence[Tuple[float, float]]: """Returns a sequence of tuple pairs with the first item being a Rabi angle and the second item being the corresponding excited state probability. """ return [(angle, prob) for angle, prob in zip(self._rabi_angles, ...
Plots excited state probability vs the Rabi angle (angle of rotation around the x-axis). Args: **plot_kwargs: Arguments to be passed to matplotlib.pyplot.plot.
def plot(self, **plot_kwargs: Any) -> None: """Plots excited state probability vs the Rabi angle (angle of rotation around the x-axis). Args: **plot_kwargs: Arguments to be passed to matplotlib.pyplot.plot. """ fig = plt.figure() plt.plot(self._rabi_angles, s...
Returns a sequence of tuple pairs with the first item being a number of Cliffords and the second item being the corresponding average ground state probability.
def data(self) -> Sequence[Tuple[int, float]]: """Returns a sequence of tuple pairs with the first item being a number of Cliffords and the second item being the corresponding average ground state probability. """ return [(num, prob) for num, prob in zip(self._num_cfds_seq, ...
Plots the average ground state probability vs the number of Cliffords in the RB study. Args: **plot_kwargs: Arguments to be passed to matplotlib.pyplot.plot.
def plot(self, **plot_kwargs: Any) -> None: """Plots the average ground state probability vs the number of Cliffords in the RB study. Args: **plot_kwargs: Arguments to be passed to matplotlib.pyplot.plot. """ fig = plt.figure() plt.plot(self._num_cfds_seq, se...
Raises a matrix with two opposing eigenvalues to a power. Args: reflection_matrix: The matrix to raise to a power. exponent: The power to raise the matrix to. Returns: The given matrix raised to the given power.
def reflection_matrix_pow(reflection_matrix: np.ndarray, exponent: float): """Raises a matrix with two opposing eigenvalues to a power. Args: reflection_matrix: The matrix to raise to a power. exponent: The power to raise the matrix to. Returns: The given matrix raised to the given...
Phases the given matrices so that they agree on the phase of one entry. To maximize precision, the position with the largest entry from one of the matrices is used when attempting to compute the phase difference between the two matrices. Args: a: A numpy array. b: Another numpy array. ...
def match_global_phase(a: np.ndarray, b: np.ndarray ) -> Tuple[np.ndarray, np.ndarray]: """Phases the given matrices so that they agree on the phase of one entry. To maximize precision, the position with the largest entry from one of the matrices is used when a...
Left-multiplies the given axes of the target tensor by the given matrix. Note that the matrix must have a compatible tensor structure. For example, if you have an 6-qubit state vector `input_state` with shape (2, 2, 2, 2, 2, 2), and a 2-qubit unitary operation `op` with shape (2, 2, 2, 2), and you wan...
def targeted_left_multiply(left_matrix: np.ndarray, right_target: np.ndarray, target_axes: Sequence[int], out: Optional[np.ndarray] = None ) -> np.ndarray: """Left-multiplies the given axes of the target tens...
r"""Conjugates the given tensor about the target tensor. This method computes a target tensor conjugated by another tensor. Here conjugate is used in the sense of conjugating by a matrix, i.a. A conjugated about B is $A B A^\dagger$ where $\dagger$ represents the conjugate transpose. Abstractly th...
def targeted_conjugate_about(tensor: np.ndarray, target: np.ndarray, indices: Sequence[int], conj_indices: Sequence[int] = None, buffer: Optional[np.ndarray] = None, out: Opti...
Left-multiplies an NxN matrix onto N slices of a numpy array. Example: The 4x4 matrix of a fractional SWAP gate can be expressed as [ 1 ] [ X**t ] [ 1 ] Where X is the 2x2 Pauli X gate and t is the power of the swap with t=1 being a full swa...
def apply_matrix_to_slices( target: np.ndarray, matrix: np.ndarray, slices: List[_TSlice], *, out: Optional[np.ndarray] = None) -> np.ndarray: """Left-multiplies an NxN matrix onto N slices of a numpy array. Example: The 4x4 matrix of a fractional SWAP gate can b...
Takes the partial trace of a given tensor. The input tensor must have shape `(d_0, ..., d_{k-1}, d_0, ..., d_{k-1})`. The trace is done over all indices that are not in keep_indices. The resulting tensor has shape `(d_{i_0}, ..., d_{i_r}, d_{i_0}, ..., d_{i_r})` where `i_j` is the `j`th element of `kee...
def partial_trace(tensor: np.ndarray, keep_indices: List[int]) -> np.ndarray: """Takes the partial trace of a given tensor. The input tensor must have shape `(d_0, ..., d_{k-1}, d_0, ..., d_{k-1})`. The trace is done over all indices that are not in keep_indices. The resulting tensor ...
Returns lhs * rhs, or else a default if the operator is not implemented. This method is mostly used by __pow__ methods trying to return NotImplemented instead of causing a TypeError. Args: lhs: Left hand side of the multiplication. rhs: Right hand side of the multiplication. defaul...
def mul(lhs: Any, rhs: Any, default: Any = RaiseTypeErrorIfNotProvided) -> Any: """Returns lhs * rhs, or else a default if the operator is not implemented. This method is mostly used by __pow__ methods trying to return NotImplemented instead of causing a TypeError. Args: lhs: Left hand side of...
Determines if a matrix is a approximately diagonal. A matrix is diagonal if i!=j implies m[i,j]==0. Args: matrix: The matrix to check. atol: The per-matrix-entry absolute tolerance on equality. Returns: Whether the matrix is diagonal within the given tolerance.
def is_diagonal(matrix: np.ndarray, *, atol: float = 1e-8) -> bool: """Determines if a matrix is a approximately diagonal. A matrix is diagonal if i!=j implies m[i,j]==0. Args: matrix: The matrix to check. atol: The per-matrix-entry absolute tolerance on equality. Returns: Whe...
Determines if a matrix is approximately Hermitian. A matrix is Hermitian if it's square and equal to its adjoint. Args: matrix: The matrix to check. rtol: The per-matrix-entry relative tolerance on equality. atol: The per-matrix-entry absolute tolerance on equality. Returns: ...
def is_hermitian( matrix: np.ndarray, *, rtol: float = 1e-5, atol: float = 1e-8) -> bool: """Determines if a matrix is approximately Hermitian. A matrix is Hermitian if it's square and equal to its adjoint. Args: matrix: The matrix to check. rtol: The per-ma...
Determines if a matrix is approximately orthogonal. A matrix is orthogonal if it's square and real and its transpose is its inverse. Args: matrix: The matrix to check. rtol: The per-matrix-entry relative tolerance on equality. atol: The per-matrix-entry absolute tolerance on equali...
def is_orthogonal( matrix: np.ndarray, *, rtol: float = 1e-5, atol: float = 1e-8) -> bool: """Determines if a matrix is approximately orthogonal. A matrix is orthogonal if it's square and real and its transpose is its inverse. Args: matrix: The matrix to check. ...
Determines if a matrix is approximately special orthogonal. A matrix is special orthogonal if it is square and real and its transpose is its inverse and its determinant is one. Args: matrix: The matrix to check. rtol: The per-matrix-entry relative tolerance on equality. atol: The p...
def is_special_orthogonal( matrix: np.ndarray, *, rtol: float = 1e-5, atol: float = 1e-8) -> bool: """Determines if a matrix is approximately special orthogonal. A matrix is special orthogonal if it is square and real and its transpose is its inverse and its determinant is o...
Determines if a matrix is approximately unitary. A matrix is unitary if it's square and its adjoint is its inverse. Args: matrix: The matrix to check. rtol: The per-matrix-entry relative tolerance on equality. atol: The per-matrix-entry absolute tolerance on equality. Returns: ...
def is_unitary( matrix: np.ndarray, *, rtol: float = 1e-5, atol: float = 1e-8) -> bool: """Determines if a matrix is approximately unitary. A matrix is unitary if it's square and its adjoint is its inverse. Args: matrix: The matrix to check. rtol: The per-ma...
Determines if a matrix is approximately unitary with unit determinant. A matrix is special-unitary if it is square and its adjoint is its inverse and its determinant is one. Args: matrix: The matrix to check. rtol: The per-matrix-entry relative tolerance on equality. atol: The per-...
def is_special_unitary( matrix: np.ndarray, *, rtol: float = 1e-5, atol: float = 1e-8) -> bool: """Determines if a matrix is approximately unitary with unit determinant. A matrix is special-unitary if it is square and its adjoint is its inverse and its determinant is one. ...
Determines if two matrices approximately commute. Two matrices A and B commute if they are square and have the same size and AB = BA. Args: m1: One of the matrices. m2: The other matrix. rtol: The per-matrix-entry relative tolerance on equality. atol: The per-matrix-entry a...
def commutes( m1: np.ndarray, m2: np.ndarray, *, rtol: float = 1e-5, atol: float = 1e-8) -> bool: """Determines if two matrices approximately commute. Two matrices A and B commute if they are square and have the same size and AB = BA. Args: m1: One of th...
Determines if a ~= b * exp(i t) for some t. Args: a: A numpy array. b: Another numpy array. rtol: Relative error tolerance. atol: Absolute error tolerance. equal_nan: Whether or not NaN entries should be considered equal to other NaN entries.
def allclose_up_to_global_phase( a: np.ndarray, b: np.ndarray, *, rtol: float = 1.e-5, atol: float = 1.e-8, equal_nan: bool = False ) -> bool: """Determines if a ~= b * exp(i t) for some t. Args: a: A numpy array. b: Another numpy array. r...
Returns an index corresponding to a desired subset of an np.ndarray. It is assumed that the np.ndarray's shape is of the form (2, 2, 2, ..., 2). Example: ```python # A '4 qubit' tensor with values from 0 to 15. r = np.array(range(16)).reshape((2,) * 4) # We want to index into...
def slice_for_qubits_equal_to(target_qubit_axes: Sequence[int], little_endian_qureg_value: int, *, # Forces keyword args. num_qubits: int = None ) -> Tuple[Union[slice, int, 'ellipsis'], ...]: ""...
Creates a scheduled operation with a device-determined duration.
def op_at_on(operation: ops.Operation, time: Timestamp, device: Device): """Creates a scheduled operation with a device-determined duration.""" return ScheduledOperation(time, device.duration_of(operation), ...
Returns number of qubits in the domain if known, None if unknown.
def num_qubits(self) -> Optional[int]: """Returns number of qubits in the domain if known, None if unknown.""" if not self: return None any_gate = next(iter(self)) return any_gate.num_qubits()
Reconstructs matrix of self using unitaries of underlying gates. Raises: TypeError: if any of the gates in self does not provide a unitary.
def matrix(self) -> np.ndarray: """Reconstructs matrix of self using unitaries of underlying gates. Raises: TypeError: if any of the gates in self does not provide a unitary. """ num_qubits = self.num_qubits() if num_qubits is None: raise ValueError('Unkn...
Finds a box drawing character based on its connectivity. For example: box_draw_character( NORMAL_BOX_CHARS, BOLD_BOX_CHARS, top=-1, right=+1) evaluates to '┕', which has a normal upward leg and bold rightward leg. Args: first: The character...
def box_draw_character(first: Optional[BoxDrawCharacterSet], second: BoxDrawCharacterSet, *, top: int = 0, bottom: int = 0, left: int = 0, right: int = 0) -> Optional[str]: """Fi...
Returns an application of this gate to the given qubits. Args: *qubits: The collection of qubits to potentially apply the gate to.
def on(self, *qubits: raw_types.Qid) -> 'SingleQubitPauliStringGateOperation': """Returns an application of this gate to the given qubits. Args: *qubits: The collection of qubits to potentially apply the gate to. """ if len(qubits) != 1: raise ValueErr...
Recursively decomposes a value into `cirq.Operation`s meeting a criteria. Args: val: The value to decompose into operations. intercepting_decomposer: An optional method that is called before the default decomposer (the value's `_decompose_` method). If `intercepting_decompos...
def decompose( val: TValue, *, intercepting_decomposer: Callable[['cirq.Operation'], Union[None, NotImplementedType, 'cirq.OP_TREE']] = None, fallback_decomposer: Callable[['cirq...
Decomposes a value into operations on the given qubits. This method is used when decomposing gates, which don't know which qubits they are being applied to unless told. It decomposes the gate exactly once, instead of decomposing it and then continuing to decomposing the decomposed operations recursivel...
def decompose_once_with_qubits(val: Any, qubits: Iterable['cirq.Qid'], default=RaiseTypeErrorIfNotProvided): """Decomposes a value into operations on the given qubits. This method is used when decomposing gates, which don't know which qubits the...
Decomposes a value into operations, if possible. This method decomposes the value exactly once, instead of decomposing it and then continuing to decomposing the decomposed operations recursively until some criteria is met (which is what `cirq.decompose` does). Args: val: The value to call `_de...
def decompose_once(val: Any, default=RaiseTypeErrorIfNotProvided, **kwargs): """Decomposes a value into operations, if possible. This method decomposes the value exactly once, instead of decomposing it and then continuing to decomposing the decomposed operations recurs...
A basis that contains exactly the given qubits in the given order. Args: fixed_qubits: The qubits in basis order. fallback: A fallback order to use for extra qubits not in the fixed_qubits list. Extra qubits will always come after the fixed_qubits, but wi...
def explicit(fixed_qubits: Iterable[raw_types.Qid], fallback: Optional['QubitOrder']=None) -> 'QubitOrder': """A basis that contains exactly the given qubits in the given order. Args: fixed_qubits: The qubits in basis order. fallback: A fallback order to use for...
A basis that orders qubits ascending based on a key function. Args: key: A function that takes a qubit and returns a key value. The basis will be ordered ascending according to these key values. Returns: A basis that orders qubits ascending based on a key funct...
def sorted_by(key: Callable[[raw_types.Qid], Any]) -> 'QubitOrder': """A basis that orders qubits ascending based on a key function. Args: key: A function that takes a qubit and returns a key value. The basis will be ordered ascending according to these key values. ...
Returns a qubit tuple ordered corresponding to the basis. Args: qubits: Qubits that should be included in the basis. (Additional qubits may be added into the output by the basis.) Returns: A tuple of qubits in the same order that their single-qubit m...
def order_for(self, qubits: Iterable[raw_types.Qid] ) -> Tuple[raw_types.Qid, ...]: """Returns a qubit tuple ordered corresponding to the basis. Args: qubits: Qubits that should be included in the basis. (Additional qubits may be added into the output by th...
Converts a value into a basis. Args: val: An iterable or a basis. Returns: The basis implied by the value.
def as_qubit_order(val: 'qubit_order_or_list.QubitOrderOrList' ) -> 'QubitOrder': """Converts a value into a basis. Args: val: An iterable or a basis. Returns: The basis implied by the value. """ if isinstance(val, collections.Iter...
Transforms the Basis so that it applies to wrapped qubits. Args: externalize: Converts an internal qubit understood by the underlying basis into an external qubit understood by the caller. internalize: Converts an external qubit understood by the caller i...
def map(self, internalize: Callable[[TExternalQubit], TInternalQubit], externalize: Callable[[TInternalQubit], TExternalQubit] ) -> 'QubitOrder': """Transforms the Basis so that it applies to wrapped qubits. Args: externalize: Converts an internal qubit u...
A str method with hacks to support better lexicographic ordering. The output strings are not intended to be human readable. The returned string will have digit-runs zero-padded up to at least 8 digits. That way, instead of 'a10' coming before 'a2', 'a000010' will come after 'a000002'. Also, the o...
def _pad_digits(text: str) -> str: """A str method with hacks to support better lexicographic ordering. The output strings are not intended to be human readable. The returned string will have digit-runs zero-padded up to at least 8 digits. That way, instead of 'a10' coming before 'a2', 'a000010' will ...
Returns a range of NamedQubits. The range returned starts with the prefix, and followed by a qubit for each number in the range, e.g.: NamedQubit.range(3, prefix="a") -> ["a1", "a2", "a3] NamedQubit.range(2, 4, prefix="a") -> ["a2", "a3] Args: *args: Args to be pas...
def range(*args, prefix: str): """Returns a range of NamedQubits. The range returned starts with the prefix, and followed by a qubit for each number in the range, e.g.: NamedQubit.range(3, prefix="a") -> ["a1", "a2", "a3] NamedQubit.range(2, 4, prefix="a") -> ["a2", "a3] ...
r"""Returns a list of matrices describing the channel for the given value. These matrices are the terms in the operator sum representation of a quantum channel. If the returned matrices are {A_0,A_1,..., A_{r-1}}, then this describes the channel: \rho \rightarrow \sum_{k=0}^{r-1} A_0 \rho A_0^\dagg...
def channel(val: Any, default: Any = RaiseTypeErrorIfNotProvided ) -> Union[Tuple[np.ndarray], Sequence[TDefault]]: r"""Returns a list of matrices describing the channel for the given value. These matrices are the terms in the operator sum representation of a quantum channel. If the...
Returns whether the value has a channel representation. Returns: If `val` has a `_has_channel_` method and its result is not NotImplemented, that result is returned. Otherwise, if `val` has a `_has_mixture_` method and its result is not NotImplemented, that result is returned. Other...
def has_channel(val: Any) -> bool: """Returns whether the value has a channel representation. Returns: If `val` has a `_has_channel_` method and its result is not NotImplemented, that result is returned. Otherwise, if `val` has a `_has_mixture_` method and its result is not NotImplement...
Assumes that the decomposition is canonical.
def _kak_decomposition_to_operations(q0: ops.Qid, q1: ops.Qid, kak: linalg.KakDecomposition, allow_partial_czs: bool, atol: float = 1e-8 ...
Decomposes a two-qubit operation into Z/XY/CZ gates. Args: q0: The first qubit being operated on. q1: The other qubit being operated on. mat: Defines the operation to apply to the pair of qubits. allow_partial_czs: Enables the use of Partial-CZ gates. atol: A limit on the am...
def two_qubit_matrix_to_operations(q0: ops.Qid, q1: ops.Qid, mat: np.ndarray, allow_partial_czs: bool, atol: float = 1e-8, clean_operations: bool...
Tests if a circuit for an operator exp(i*rad*XX) (or YY, or ZZ) can be performed with a whole CZ. Args: rad: The angle in radians, assumed to be in the range [-pi/4, pi/4]
def _is_trivial_angle(rad: float, atol: float) -> bool: """Tests if a circuit for an operator exp(i*rad*XX) (or YY, or ZZ) can be performed with a whole CZ. Args: rad: The angle in radians, assumed to be in the range [-pi/4, pi/4] """ return abs(rad) < atol or abs(abs(rad) - np.pi / 4) < at...
Yields a ZZ interaction framed by the given operation.
def _parity_interaction(q0: ops.Qid, q1: ops.Qid, rads: float, atol: float, gate: Optional[ops.Gate] = None): """Yields a ZZ interaction framed by the given operation.""" if abs(rads) < atol: return h = ...
Yields non-local operation of KAK decomposition.
def _non_local_part(q0: ops.Qid, q1: ops.Qid, interaction_coefficients: Tuple[float, float, float], allow_partial_czs: bool, atol: float = 1e-8): """Yields non-local operation of KAK decomposition.""" x, y, z = interaction_coeffici...
Runs the simulator.
def simulate(sim_type: str, num_qubits: int, num_gates: int, num_prefix_qubits: int = 0, use_processes: bool = False) -> None: """"Runs the simulator.""" circuit = cirq.Circuit(device=test_device) for _ in range(num_gates): which = np.random.choic...
See definition in `cirq.SimulatesSamples`.
def _run( self, circuit: circuits.Circuit, param_resolver: study.ParamResolver, repetitions: int) -> Dict[str, List[np.ndarray]]: """See definition in `cirq.SimulatesSamples`.""" param_resolver = param_resolver or study.ParamResolver({}) resolved_circuit = protoco...
Simulate an op that has a unitary.
def _simulate_unitary(self, op: ops.Operation, data: _StateAndBuffer, indices: List[int]) -> None: """Simulate an op that has a unitary.""" result = protocols.apply_unitary( op, args=protocols.ApplyUnitaryArgs( data.state, ...
Simulate an op that is a measurement in the computataional basis.
def _simulate_measurement(self, op: ops.Operation, data: _StateAndBuffer, indices: List[int], measurements: Dict[str, List[bool]], num_qubits: int) -> None: """Simulate an op that is a measurement in the computataional basis.""" meas = ops.op_gate_of_type(op, ops.MeasurementGate)...
Simulate an op that is a mixtures of unitaries.
def _simulate_mixture(self, op: ops.Operation, data: _StateAndBuffer, indices: List[int]) -> None: """Simulate an op that is a mixtures of unitaries.""" probs, unitaries = zip(*protocols.mixture(op)) # We work around numpy barfing on choosing from a list of # numpy arrays (wh...
Acquaints every triple of qubits. Exploits the fact that in a simple linear swap network every pair of logical qubits that starts at distance two remains so (except temporarily near the edge), and that every third one `goes through` the pair at some point in the network. The strategy then iterates thro...
def cubic_acquaintance_strategy( qubits: Iterable[ops.Qid], swap_gate: ops.Gate=ops.SWAP ) -> circuits.Circuit: """Acquaints every triple of qubits. Exploits the fact that in a simple linear swap network every pair of logical qubits that starts at distance two remains so (except tem...
Parse ASCIIart device layout into info about qubits and connectivity. Args: s: String representing the qubit layout. Each line represents a row, and each character in the row is a qubit, or a blank site if the character is a hyphen '-'. Different letters for the qubit specify ...
def _parse_device(s: str) -> Tuple[List[GridQubit], Dict[str, Set[GridQubit]]]: """Parse ASCIIart device layout into info about qubits and connectivity. Args: s: String representing the qubit layout. Each line represents a row, and each character in the row is a qubit, or a blank site if th...
Approximately compares two objects. If `val` implements SupportsApproxEquality protocol then it is invoked and takes precedence over all other checks: - For primitive numeric types `int` and `float` approximate equality is delegated to math.isclose(). - For complex primitive type the real and ...
def approx_eq(val: Any, other: Any, *, atol: Union[int, float] = 1e-8) -> bool: """Approximately compares two objects. If `val` implements SupportsApproxEquality protocol then it is invoked and takes precedence over all other checks: - For primitive numeric types `int` and `float` approximate equality...
Iterates over arguments and calls approx_eq recursively. Types of `val` and `other` does not necessarily needs to match each other. They just need to be iterable of the same length and have the same structure, approx_eq() will be called on each consecutive element of `val` and `other`. Args: ...
def _approx_eq_iterables(val: Any, other: Any, *, atol: Union[int, float]) -> bool: """Iterates over arguments and calls approx_eq recursively. Types of `val` and `other` does not necessarily needs to match each other. They just need to be iterable of the same length and have the s...
Convenience wrapper around np.isclose.
def _isclose(a: Any, b: Any, *, atol: Union[int, float]) -> bool: """Convenience wrapper around np.isclose.""" return True if np.isclose([a], [b], atol=atol, rtol=0.0)[0] else False
Returns an acquaintance strategy capable of executing a gate corresponding to any set of at most acquaintance_size qubits. Args: qubit_order: The qubits on which the strategy should be defined. acquaintance_size: The maximum number of qubits to be acted on by an operation. Returns:...
def complete_acquaintance_strategy(qubit_order: Sequence[ops.Qid], acquaintance_size: int=0, ) -> circuits.Circuit: """ Returns an acquaintance strategy capable of executing a gate corresponding to any set of at most acquaintance_size qub...
Add the specified number of input and output qubits.
def set_io_qubits(qubit_count): """Add the specified number of input and output qubits.""" input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)] output_qubit = cirq.GridQubit(qubit_count, 0) return (input_qubits, output_qubit)
Implement function {f(x) = 1 if x==x', f(x) = 0 if x!= x'}.
def make_oracle(input_qubits, output_qubit, x_bits): """Implement function {f(x) = 1 if x==x', f(x) = 0 if x!= x'}.""" # Make oracle. # for (1, 1) it's just a Toffoli gate # otherwise negate the zero-bits. yield(cirq.X(q) for (q, bit) in zip(input_qubits, x_bits) if not bit) yield(cirq.TOFFOLI(i...
Find the value recognized by the oracle in sqrt(N) attempts.
def make_grover_circuit(input_qubits, output_qubit, oracle): """Find the value recognized by the oracle in sqrt(N) attempts.""" # For 2 input qubits, that means using Grover operator only once. c = cirq.Circuit() # Initialize qubits. c.append([ cirq.X(output_qubit), cirq.H(output_qu...
Iterates through relevant python files within the given directory. Args: directory: The top-level directory to explore. Yields: File paths.
def get_unhidden_ungenerated_python_files(directory: str) -> Iterable[str]: """Iterates through relevant python files within the given directory. Args: directory: The top-level directory to explore. Yields: File paths. """ for dirpath, dirnames, filenames in os.walk(directory, topd...
Creates a new virtual environment and then installs dependencies. Args: venv_path: Where to put the virtual environment's state. requirements_paths: Location of requirements files to -r install. python_path: The python binary to use. verbose: When set, more progress output is produc...
def create_virtual_env(venv_path: str, requirements_paths: Iterable[str], python_path: str, verbose: bool) -> None: """Creates a new virtual environment and then installs dependencies. Args: venv_path: Where to put the virtual environ...
Creates a python 2.7 environment starting from a prepared python 3 one. Args: destination_directory: Where to put the python 2 environment. python3_environment: The prepared environment to start from. verbose: When set, more progress output is produced. env_name: The name to use for...
def derive_temporary_python2_environment( destination_directory: str, python3_environment: PreparedEnv, verbose: bool, env_name: str = '.test_virtualenv_py2', python_path: str = "/usr/bin/python2.7") -> PreparedEnv: """Creates a python 2.7 environment starting from a prepared...
Construct the following phase estimator circuit and execute simulations. --------- ---H---------------------@------| |---M--- [m4]:lowest bit | | | ---H---------------@-----+------| |---M--- [m3] ...
def run_estimate(unknown_gate, qnum, repetitions): """Construct the following phase estimator circuit and execute simulations. --------- ---H---------------------@------| |---M--- [m4]:lowest bit | | | ---H--------------...
Execute the phase estimator cirquit with multiple settings and show results.
def experiment(qnum, repetitions=100): """Execute the phase estimator cirquit with multiple settings and show results. """ def example_gate(phi): """An example unitary 1-qubit gate U with an eigen vector |0> and an eigen value exp(2*Pi*i*phi) """ gate = cirq.SingleQubit...
A quantum circuit (QFT_inv) with the following structure. ---H--@-------@--------@---------------------------------------------- | | | ------@^-0.5--+--------+---------H--@-------@------------------------- | | | | --------...
def _decompose_(self, qubits): """A quantum circuit (QFT_inv) with the following structure. ---H--@-------@--------@---------------------------------------------- | | | ------@^-0.5--+--------+---------H--@-------@------------------------- | ...
Searches for linear sequence of qubits on device. Args: device: Google Xmon device instance. length: Desired number of qubits making up the line. method: Line placement method. Defaults to cirq.greedy.GreedySequenceSearchMethod. Returns: Line sequences search re...
def line_on_device( device: 'cirq.google.XmonDevice', length: int, method: LinePlacementStrategy = greedy.GreedySequenceSearchStrategy() ) -> GridQubitLineTuple: """Searches for linear sequence of qubits on device. Args: device: Google Xmon device instance. length: Desir...
Returns `val**factor` of the given value, if defined. Values define an extrapolation by defining a __pow__(self, exponent) method. Note that the method may return NotImplemented to indicate a particular extrapolation can't be done. Args: val: The value or iterable of values to invert. ...
def pow(val: Any, exponent: Any, default: Any = RaiseTypeErrorIfNotProvided) -> Any: """Returns `val**factor` of the given value, if defined. Values define an extrapolation by defining a __pow__(self, exponent) method. Note that the method may return NotImplemented to indicate a particular ...
Simulates sampling from the given circuit or schedule. Args: program: The circuit or schedule to sample from. noise: Noise model to use while running the simulation. param_resolver: Parameters to run with the program. repetitions: The number of samples to take. dtype: The `n...
def sample(program: Union[circuits.Circuit, schedules.Schedule], *, noise: devices.NoiseModel = devices.NO_NOISE, param_resolver: Optional[study.ParamResolver] = None, repetitions: int = 1, dtype: Type[np.number] = np.complex64) -> study.TrialResult: """Simulat...
Runs the supplied Circuit or Schedule, mimicking quantum hardware. In contrast to run, this allows for sweeping over different parameter values. Args: program: The circuit or schedule to simulate. params: Parameters to run with the program. noise: Noise model to use while running t...
def sample_sweep(program: Union[circuits.Circuit, schedules.Schedule], params: study.Sweepable, *, noise: devices.NoiseModel = devices.NO_NOISE, repetitions: int = 1, dtype: Type[np.number] = np.complex64 ) -> List[stud...
Returns a schedule aligned with the moment structure of the Circuit. This method attempts to create a schedule in which each moment of a circuit is scheduled starting at the same time. Given the constraints of the given device, such a schedule may not be possible, in this case the the method will raise...
def moment_by_moment_schedule(device: Device, circuit: Circuit): """Returns a schedule aligned with the moment structure of the Circuit. This method attempts to create a schedule in which each moment of a circuit is scheduled starting at the same time. Given the constraints of the given device, such a ...
Minimum width necessary to render the block's contents.
def min_width(self) -> int: """Minimum width necessary to render the block's contents.""" return max( max(len(e) for e in self.content.split('\n')), # Only horizontal lines can cross 0 width blocks. int(any([self.top, self.bottom])) )
Minimum height necessary to render the block's contents.
def min_height(self) -> int: """Minimum height necessary to render the block's contents.""" return max( len(self.content.split('\n')) if self.content else 0, # Only vertical lines can cross 0 height blocks. int(any([self.left, self.right])) )
Draws lines in the box using the given character set. Supports merging the new lines with the lines from a previous call to draw_curve, including when they have different character sets (assuming there exist characters merging the two). Args: grid_characters: The character ...
def draw_curve(self, grid_characters: BoxDrawCharacterSet, *, top: bool = False, left: bool = False, right: bool = False, bottom: bool = False, crossing_char: Optional[str] = None): ...
Returns a list of text lines representing the block's contents. Args: width: The width of the output text. Must be at least as large as the block's minimum width. height: The height of the output text. Must be at least as large as the block's minimum heig...
def render(self, width: int, height: int) -> List[str]: """Returns a list of text lines representing the block's contents. Args: width: The width of the output text. Must be at least as large as the block's minimum width. height: The height of the output text. Mu...
Returns the block at (x, y) so it can be edited.
def mutable_block(self, x: int, y: int) -> Block: """Returns the block at (x, y) so it can be edited.""" if x < 0 or y < 0: raise IndexError('x < 0 or y < 0') return self._blocks[(x, y)]
Sets a minimum width for blocks in the column with coordinate x.
def set_col_min_width(self, x: int, min_width: int): """Sets a minimum width for blocks in the column with coordinate x.""" if x < 0: raise IndexError('x < 0') self._min_widths[x] = min_width
Sets a minimum height for blocks in the row with coordinate y.
def set_row_min_height(self, y: int, min_height: int): """Sets a minimum height for blocks in the row with coordinate y.""" if y < 0: raise IndexError('y < 0') self._min_heights[y] = min_height
Outputs text containing the diagram. Args: block_span_x: The width of the diagram in blocks. Set to None to default to using the smallest width that would include all accessed blocks and columns with a specified minimum width. block_span_y: The height of ...
def render(self, *, block_span_x: Optional[int] = None, block_span_y: Optional[int] = None, min_block_width: int = 0, min_block_height: int = 0) -> str: """Outputs text containing the diagram. Args: block_span_x: The...
Demonstrates Quantum Fourier transform.
def main(): """Demonstrates Quantum Fourier transform. """ # Create circuit qft_circuit = generate_2x2_grid_qft_circuit() print('Circuit:') print(qft_circuit) # Simulate and collect final_state simulator = cirq.Simulator() result = simulator.simulate(qft_circuit) print() prin...
Return an equivalent operation on new qubits with its Pauli string mapped to new qubits. new_pauli_string = self.pauli_string.map_qubits(qubit_map)
def map_qubits(self: TSelf_PauliStringGateOperation, qubit_map: Dict[raw_types.Qid, raw_types.Qid] ) -> TSelf_PauliStringGateOperation: """Return an equivalent operation on new qubits with its Pauli string mapped to new qubits. new_pauli_string = self.pauli_...
Sets a commit status indicator on github. If not running from a pull request (i.e. repository is None), then this just prints to stderr. Args: state: The state of the status indicator. Must be 'error', 'failure', 'pending', or 'success'. description: A s...
def report_status_to_github(self, state: str, description: str, context: str, target_url: Optional[str] = None): """Sets a commit status indicator on github. If not running fr...
Get the files changed on one git branch vs another. Returns: List[str]: File paths of changed files, relative to the git repo root.
def get_changed_files(self) -> List[str]: """Get the files changed on one git branch vs another. Returns: List[str]: File paths of changed files, relative to the git repo root. """ out = shell_tools.output_of( 'git', 'diff', ...
Creates a Duration from datetime.timedelta if necessary
def create(cls, duration: Union['Duration', timedelta]) -> 'Duration': """Creates a Duration from datetime.timedelta if necessary""" if isinstance(duration, cls): return duration elif isinstance(duration, timedelta): duration_in_picos = duration.total_seconds() * 10**12 ...
Returns the handle of a RawArray created from the given numpy array. Args: arr: A numpy ndarray. Returns: The handle (int) of the array. Raises: ValueError: if arr is not a ndarray or of an unsupported dtype. If the array is of an unsupported type, us...
def _create_array(self, arr: np.ndarray) -> int: """Returns the handle of a RawArray created from the given numpy array. Args: arr: A numpy ndarray. Returns: The handle (int) of the array. Raises: ValueError: if arr is not a ndarray or of an unsupported d...
Frees the memory for the array with the given handle. Args: handle: The handle of the array whose memory should be freed. This handle must come from the _create_array method.
def _free_array(self, handle: int): """Frees the memory for the array with the given handle. Args: handle: The handle of the array whose memory should be freed. This handle must come from the _create_array method. """ with self._lock: if self._arrays[ha...
Returns the array with the given handle. Args: handle: The handle of the array whose memory should be freed. This handle must come from the _create_array method. Returns: The numpy ndarray with the handle given from _create_array.
def _get_array(self, handle: int) -> np.ndarray: """Returns the array with the given handle. Args: handle: The handle of the array whose memory should be freed. This handle must come from the _create_array method. Returns: The numpy ndarray with the handle given...