INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Runs a Rabi oscillation experiment.
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.
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.
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.
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.
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.
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 ).
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 if possible.
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...
Decomposes a value into operations on the given qubits.
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...
A basis that contains exactly the given qubits in the given order.
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.
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.
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.
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.
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.
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.
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.
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.
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...
Decomposes a two - qubit operation into Z/ XY/ CZ gates.
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...
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 ...
Tests if a circuit for an operator exp ( i * rad * XX ) ( or YY or ZZ ) can be performed with a whole CZ.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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...
Write QASM output to a file specified by path.
def save(self, path: Union[str, bytes, int]) -> None: """Write QASM output to a file specified by path.""" with open(path, 'w') as f: def write(s: str) -> None: f.write(s) self._write_qasm(write)
Splits moments so that they contain either only acquaintance gates or only permutation gates. Orders resulting moments so that the first one is of the same type as the previous one.
def rectify_acquaintance_strategy( circuit: circuits.Circuit, acquaint_first: bool=True ) -> None: """Splits moments so that they contain either only acquaintance gates or only permutation gates. Orders resulting moments so that the first one is of the same type as the previous one. ...
Replace every moment containing acquaintance gates ( after rectification ) with a generalized swap network with the partition given by the acquaintance gates in that moment ( and singletons for the free qubits ). Accounts for reversing effect of swap networks.
def replace_acquaintance_with_swap_network( circuit: circuits.Circuit, qubit_order: Sequence[ops.Qid], acquaintance_size: Optional[int] = 0, swap_gate: ops.Gate = ops.SWAP ) -> bool: """ Replace every moment containing acquaintance gates (after rectification) with a g...
Check if a gate is a native ion gate.
def is_native_ion_gate(gate: ops.Gate) -> bool: """Check if a gate is a native ion gate. Args: gate: Input gate. Returns: True if the gate is native to the ion, false otherwise. """ return isinstance(gate, (ops.XXPowGate, ops.MeasurementGate, ...
Convert a single ( one - or two - qubit ) operation
def convert_one(self, op: ops.Operation) -> ops.OP_TREE: """Convert a single (one- or two-qubit) operation into ion trap native gates Args: op: gate operation to be converted Returns: the desired operation implemented with ion trap gates """ # K...
Returns an orthogonal matrix that diagonalizes the given matrix.
def diagonalize_real_symmetric_matrix( matrix: np.ndarray, *, rtol: float = 1e-5, atol: float = 1e-8) -> np.ndarray: """Returns an orthogonal matrix that diagonalizes the given matrix. Args: matrix: A real symmetric matrix to diagonalize. rtol: float = 1e-5, ...
Splits range ( length ) into approximate equivalence classes.
def _contiguous_groups( length: int, comparator: Callable[[int, int], bool] ) -> List[Tuple[int, int]]: """Splits range(length) into approximate equivalence classes. Args: length: The length of the range to split. comparator: Determines if two indices have approximately equal it...
Returns an orthogonal matrix that diagonalizes both given matrices.
def diagonalize_real_symmetric_and_sorted_diagonal_matrices( symmetric_matrix: np.ndarray, diagonal_matrix: np.ndarray, *, rtol: float = 1e-5, atol: float = 1e-8, check_preconditions: bool = True) -> np.ndarray: """Returns an orthogonal matrix that diagonalizes both g...
Finds orthogonal matrices that diagonalize both mat1 and mat2.
def bidiagonalize_real_matrix_pair_with_symmetric_products( mat1: np.ndarray, mat2: np.ndarray, *, rtol: float = 1e-5, atol: float = 1e-8, check_preconditions: bool = True) -> Tuple[np.ndarray, np.ndarray]: """Finds orthogonal matrices that diagonalize both mat1 and m...
Finds orthogonal matrices L R such that L @ matrix @ R is diagonal.
def bidiagonalize_unitary_with_special_orthogonals( mat: np.ndarray, *, rtol: float = 1e-5, atol: float = 1e-8, check_preconditions: bool = True ) -> Tuple[np.ndarray, np.array, np.ndarray]: """Finds orthogonal matrices L, R such that L @ matrix @ R is diagonal. Args: ...
r Returns a AsymmetricDepolarizingChannel with given parameter.
def asymmetric_depolarize( p_x: float, p_y: float, p_z: float ) -> AsymmetricDepolarizingChannel: r"""Returns a AsymmetricDepolarizingChannel with given parameter. This channel evolves a density matrix via $$ \rho \rightarrow (1 - p_x - p_y - p_z) \rho + p_x X \rho X + p_y ...