INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
References: https://developer.github.com/v3/pulls/#get-a-single-pull-request https://developer.github.com/v4/enum/mergestatestatus/
def classify_pr_synced_state(pr: PullRequestDetails) -> Optional[bool]: """ References: https://developer.github.com/v3/pulls/#get-a-single-pull-request https://developer.github.com/v4/enum/mergestatestatus/ """ state = pr.payload['mergeable_state'].lower() classification = { ...
References: https://developer.github.com/v3/checks/runs/#list-check-runs-for-a-specific-ref
def get_pr_checks(pr: PullRequestDetails) -> Dict[str, Any]: """ References: https://developer.github.com/v3/checks/runs/#list-check-runs-for-a-specific-ref """ url = ("https://api.github.com/repos/{}/{}/commits/{}/check-runs" "?access_token={}".format(pr.repo.organization, ...
References: https://developer.github.com/v3/pulls/reviews/#list-reviews-on-a-pull-request
def get_pr_review_status(pr: PullRequestDetails) -> Any: """ References: https://developer.github.com/v3/pulls/reviews/#list-reviews-on-a-pull-request """ url = ("https://api.github.com/repos/{}/{}/pulls/{}/reviews" "?access_token={}".format(pr.repo.organization, ...
References: https://developer.github.com/v3/git/refs/#get-a-reference
def get_repo_ref(repo: GithubRepository, ref: str) -> Dict[str, Any]: """ References: https://developer.github.com/v3/git/refs/#get-a-reference """ url = ("https://api.github.com/repos/{}/{}/git/refs/{}" "?access_token={}".format(repo.organization, ...
References: https://developer.github.com/v3/issues/comments/#list-comments-on-an-issue
def list_pr_comments(repo: GithubRepository, pull_id: int ) -> List[Dict[str, Any]]: """ References: https://developer.github.com/v3/issues/comments/#list-comments-on-an-issue """ url = ("https://api.github.com/repos/{}/{}/issues/{}/comments" "?access_token={}".fo...
References: https://developer.github.com/v3/issues/comments/#delete-a-comment
def delete_comment(repo: GithubRepository, comment_id: int) -> None: """ References: https://developer.github.com/v3/issues/comments/#delete-a-comment """ url = ("https://api.github.com/repos/{}/{}/issues/comments/{}" "?access_token={}".format(repo.organization, ...
References: https://developer.github.com/v3/repos/merging/#perform-a-merge
def attempt_sync_with_master(pr: PullRequestDetails ) -> Union[bool, CannotAutomergeError]: """ References: https://developer.github.com/v3/repos/merging/#perform-a-merge """ master_sha = get_master_sha(pr.repo) remote = pr.remote_repo url = ("https://api.git...
References: https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-button
def attempt_squash_merge(pr: PullRequestDetails ) -> Union[bool, CannotAutomergeError]: """ References: https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-button """ url = ("https://api.github.com/repos/{}/{}/pulls/{}/merge" "?access_token={}".f...
References: https://developer.github.com/v3/git/refs/#delete-a-reference
def auto_delete_pr_branch(pr: PullRequestDetails) -> bool: """ References: https://developer.github.com/v3/git/refs/#delete-a-reference """ open_pulls = list_open_pull_requests(pr.repo, base_branch=pr.branch_name) if any(open_pulls): log('Not deleting branch {!r}. It is used elsewhe...
References: https://developer.github.com/v3/issues/labels/#add-labels-to-an-issue
def add_labels_to_pr(repo: GithubRepository, pull_id: int, *labels: str, override_token: str = None) -> None: """ References: https://developer.github.com/v3/issues/labels/#add-labels-to-an-issue """ url = ("https://api.github.com/re...
References: https://developer.github.com/v3/issues/labels/#remove-a-label-from-an-issue
def remove_label_from_pr(repo: GithubRepository, pull_id: int, label: str) -> bool: """ References: https://developer.github.com/v3/issues/labels/#remove-a-label-from-an-issue """ url = ("https://api.github.com/repos/{}/{}/issues/{}/labels/{}" ...
Filters out problems that may be temporary.
def drop_temporary(pr: PullRequestDetails, problem: Optional[CannotAutomergeError], prev_seen_times: Dict[int, datetime.datetime], next_seen_times: Dict[int, datetime.datetime], ) -> Optional[CannotAutomergeError]: """Filters out problems t...
References: https://developer.github.com/v3/pulls/#get-a-single-pull-request
def from_github(repo: GithubRepository, pull_id: int) -> 'PullRequestDetails': """ References: https://developer.github.com/v3/pulls/#get-a-single-pull-request """ url = ("https://api.github.com/repos/{}/{}/pulls/{}" "?access_token={}".forma...
The Mølmer–Sørensen gate, a native two-qubit operation in ion traps. A rotation around the XX axis in the two-qubit bloch sphere. The gate implements the following unitary: exp(-i t XX) = [ cos(t) 0 0 -isin(t)] [ 0 cos(t) -isin(t) 0 ] ...
def MS(rads: float) -> ops.XXPowGate: """The Mølmer–Sørensen gate, a native two-qubit operation in ion traps. A rotation around the XX axis in the two-qubit bloch sphere. The gate implements the following unitary: exp(-i t XX) = [ cos(t) 0 0 -isin(t)] [ 0 ...
Calculates probability and draws if solution should be accepted. Based on exp(-Delta*E/T) formula. Args: random_sample: Uniformly distributed random number in the range [0, 1). cost_diff: Cost difference between new and previous solutions. temp: Current temperature. Returns: ...
def _accept(random_sample: float, cost_diff: float, temp: float) -> Tuple[bool, float]: """Calculates probability and draws if solution should be accepted. Based on exp(-Delta*E/T) formula. Args: random_sample: Uniformly distributed random number in the range [0, 1). cost_diff:...
Minimize solution using Simulated Annealing meta-heuristic. Args: initial: Initial solution of type T to the problem. cost_func: Callable which takes current solution of type T, evaluates it and returns float with the cost estimate. The better solution is, the lower resultin...
def anneal_minimize( initial: T, cost_func: Callable[[T], float], move_func: Callable[[T], T], random_sample: Callable[[], float], temp_initial: float = 1.0e-2, temp_final: float = 1e-6, cooling_factor: float = 0.99, repeat: int = 100, trace_func: ...
Returns the gate of given type, if the op has that gate otherwise None.
def op_gate_of_type(op: raw_types.Operation, gate_type: Type[TV]) -> Optional[TV]: """Returns the gate of given type, if the op has that gate otherwise None. """ if isinstance(op, GateOperation) and isinstance(op.gate, gate_type): return op.gate return None
Takes a sequence of qubit pairs and returns a sequence in which every pair is at distance two. Specifically, given pairs (1a, 1b), (2a, 2b), etc. returns (1a, 2a, 1b, 2b, 3a, 4a, 3b, 4b, ...).
def qubit_pairs_to_qubit_order( qubit_pairs: Sequence[Sequence[ops.Qid]] ) -> List[ops.Qid]: """Takes a sequence of qubit pairs and returns a sequence in which every pair is at distance two. Specifically, given pairs (1a, 1b), (2a, 2b), etc. returns (1a, 2a, 1b, 2b, 3a, 4a, 3b, 4b, ...). ""...
Acquaintance strategy for pairs of pairs. Implements UpCCGSD ansatz from arXiv:1810.02327.
def quartic_paired_acquaintance_strategy( qubit_pairs: Iterable[Tuple[ops.Qid, ops.Qid]] ) -> Tuple[circuits.Circuit, Sequence[ops.Qid]]: """Acquaintance strategy for pairs of pairs. Implements UpCCGSD ansatz from arXiv:1810.02327. """ qubit_pairs = tuple( cast(Tuple[ops.Qid, ops.Q...
Requests information on drawing an operation in a circuit diagram. Calls _circuit_diagram_info_ on `val`. If `val` doesn't have _circuit_diagram_info_, or it returns NotImplemented, that indicates that diagram information is not available. Args: val: The operation or gate that will need to be ...
def circuit_diagram_info(val: Any, args: Optional[CircuitDiagramInfoArgs] = None, default=RaiseTypeErrorIfNotProvided): """Requests information on drawing an operation in a circuit diagram. Calls _circuit_diagram_info_ on `val`. If `val` doesn't have _circu...
Returns coefficients of the expansion of val in the Pauli basis. Args: val: The value whose Pauli expansion is to returned. default: Determines what happens when `val` does not have methods that allow Pauli expansion to be obtained (see below). If set, the value is returned ...
def pauli_expansion( val: Any, *, default: Union[value.LinearDict[str], TDefault] = RaiseTypeErrorIfNotProvided, atol: float = 1e-9 ) -> Union[value.LinearDict[str], TDefault]: """Returns coefficients of the expansion of val in the Pauli basis. Args: val: The value whose Pauli e...
See definition in `cirq.SimulatesSamples`.
def _run(self, circuit: circuits.Circuit, param_resolver: study.ParamResolver, repetitions: int) -> Dict[str, np.ndarray]: """See definition in `cirq.SimulatesSamples`.""" param_resolver = param_resolver or study.ParamResolver({}) resolved_circuit = protocols.resolve_pa...
See definition in `cirq.SimulatesIntermediateState`. If the initial state is an int, the state is set to the computational basis state corresponding to this state. Otherwise if the initial state is a np.ndarray it is the full initial state, either a pure state or the full density matri...
def _simulator_iterator(self, circuit: circuits.Circuit, param_resolver: study.ParamResolver, qubit_order: ops.QubitOrderOrList, initial_state: Union[int, np.ndarray]) -> Iterator: """See definition in `cirq.SimulatesIntermediat...
Computes displays 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. qubit_order: D...
def compute_displays_sweep( self, program: Union[circuits.Circuit, schedules.Schedule], params: Optional[study.Sweepable] = None, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, initial_state: Union[int, np.ndarray] = 0, ) -> List[study.ComputeDisplaysResult]: ...
Set the density matrix to a new density matrix. Args: density_matrix_repr: If this is an int, the density matrix is set to the computational basis state corresponding to this state. Otherwise if this is a np.ndarray it is the full state, either a pure state or th...
def set_density_matrix(self, density_matrix_repr: Union[int, np.ndarray]): """Set the density matrix to a new density matrix. Args: density_matrix_repr: If this is an int, the density matrix is set to the computational basis state corresponding to this state. Otherwise ...
Returns the density matrix at this step in the simulation. The density matrix that is stored in this result is returned in the computational basis with these basis states defined by the qubit_map. In particular the value in the qubit_map is the index of the qubit, and these are translat...
def density_matrix(self): """Returns the density matrix at this step in the simulation. The density matrix that is stored in this result is returned in the computational basis with these basis states defined by the qubit_map. In particular the value in the qubit_map is the index of the ...
Creates tensor product of bases.
def kron_bases(*bases: Dict[str, np.ndarray], repeat: int = 1) -> Dict[str, np.ndarray]: """Creates tensor product of bases.""" product_basis = {'': 1} for basis in bases * repeat: product_basis = { name1 + name2: np.kron(matrix1, matrix2) for name1, matrix1 in...
Computes Hilbert-Schmidt inner product of two matrices. Linear in second argument.
def hilbert_schmidt_inner_product(m1: np.ndarray, m2: np.ndarray) -> complex: """Computes Hilbert-Schmidt inner product of two matrices. Linear in second argument. """ return np.einsum('ij,ij', m1.conj(), m2)
Computes coefficients of expansion of m in basis. We require that basis be orthogonal w.r.t. the Hilbert-Schmidt inner product. We do not require that basis be orthonormal. Note that Pauli basis (I, X, Y, Z) is orthogonal, but not orthonormal.
def expand_matrix_in_orthogonal_basis( m: np.ndarray, basis: Dict[str, np.ndarray], ) -> value.LinearDict[str]: """Computes coefficients of expansion of m in basis. We require that basis be orthogonal w.r.t. the Hilbert-Schmidt inner product. We do not require that basis be orthonormal. Not...
Computes linear combination of basis vectors with given coefficients.
def matrix_from_basis_coefficients(expansion: value.LinearDict[str], basis: Dict[str, np.ndarray]) -> np.ndarray: """Computes linear combination of basis vectors with given coefficients.""" some_element = next(iter(basis.values())) result = np.zeros_like(some_element, dtyp...
Returns a new, equivalent circuit using the gate set {SingleQubitCliffordGate, CZ/PauliInteractionGate, PauliStringPhasor}.
def converted_gate_set(circuit: circuits.Circuit, no_clifford_gates: bool = False, atol: float = 1e-8, ) -> circuits.Circuit: """Returns a new, equivalent circuit using the gate set {SingleQubitCliffordGate, CZ/PauliInteractionGate, PauliS...
Optimizes a circuit with XmonDevice in mind. Starts by converting the circuit's operations to the xmon gate set, then begins merging interactions and rotations, ejecting pi-rotations and phasing operations, dropping unnecessary operations, and pushing operations earlier. Args: circuit: The cir...
def optimized_for_xmon( circuit: circuits.Circuit, new_device: Optional[xmon_device.XmonDevice] = None, qubit_map: Callable[[ops.Qid], devices.GridQubit] = lambda e: cast(devices.GridQubit, e), allow_partial_czs: bool = False, ) -> circuits.Circuit: """Optimizes a circuit...
High performance evolution under a channel evolution. If `val` defines an `_apply_channel_` method, that method will be used to apply `val`'s channel effect to the target tensor. Otherwise, if `val` defines an `_apply_unitary_` method, that method will be used to apply `val`s channel effect to the targ...
def apply_channel(val: Any, args: ApplyChannelArgs, default: TDefault = RaiseTypeErrorIfNotProvided ) -> Union[np.ndarray, TDefault]: """High performance evolution under a channel evolution. If `val` defines an `_apply_channel_` method, that method will be used to apply `val`'s channel effe...
Attempt to use `apply_unitary` and return the result. If `val` does not support `apply_unitary` returns None.
def _apply_unitary(val: Any, args: 'ApplyChannelArgs') -> Optional[np.ndarray]: """Attempt to use `apply_unitary` and return the result. If `val` does not support `apply_unitary` returns None. """ left_args = ApplyUnitaryArgs(target_tensor=args.target_tensor, available_...
Directly apply the kraus operators to the target tensor.
def _apply_krauss(krauss: Union[Tuple[np.ndarray], Sequence[Any]], args: 'ApplyChannelArgs') -> np.ndarray: """Directly apply the kraus operators to the target tensor.""" # Initialize output. args.out_buffer[:] = 0 # Stash initial state into buffer0. np.copyto(dst=args.auxiliary_buffer0, src...
Use slicing to apply single qubit channel.
def _apply_krauss_single_qubit(krauss: Union[Tuple[Any], Sequence[Any]], args: 'ApplyChannelArgs') -> np.ndarray: """Use slicing to apply single qubit channel.""" zero_left = linalg.slice_for_qubits_equal_to(args.left_axes, 0) one_left = linalg.slice_for_qubits_equal_to(args.left_axes, 1) zero_r...
Use numpy's einsum to apply a multi-qubit channel.
def _apply_krauss_multi_qubit(krauss: Union[Tuple[Any], Sequence[Any]], args: 'ApplyChannelArgs') -> np.ndarray: """Use numpy's einsum to apply a multi-qubit channel.""" for krauss_op in krauss: np.copyto(dst=args.target_tensor, src=args.auxiliary_buffer0) krauss_tensor = np.reshape( ...
Converts any circuit into two circuits where (circuit_left+circuit_right) is equivalent to the given circuit. Args: circuit: Any Circuit that cirq.google.optimized_for_xmon() supports. All gates should either provide a decomposition or have a known one or two qubit unitary matri...
def convert_and_separate_circuit(circuit: circuits.Circuit, leave_cliffords: bool = True, atol: float = 1e-8, ) -> Tuple[circuits.Circuit, circuits.Circuit]: """Converts any circuit into two circuits where (circuit_le...
Return only the Clifford part of a circuit. See convert_and_separate_circuit(). Args: circuit: A Circuit with the gate set {SingleQubitCliffordGate, PauliInteractionGate, PauliStringPhasor}. Returns: A Circuit with SingleQubitCliffordGate and PauliInteractionGate gates. ...
def regular_half(circuit: circuits.Circuit) -> circuits.Circuit: """Return only the Clifford part of a circuit. See convert_and_separate_circuit(). Args: circuit: A Circuit with the gate set {SingleQubitCliffordGate, PauliInteractionGate, PauliStringPhasor}. Returns: A Cir...
Return only the non-Clifford part of a circuit. See convert_and_separate_circuit(). Args: circuit: A Circuit with the gate set {SingleQubitCliffordGate, PauliInteractionGate, PauliStringPhasor}. Returns: A Circuit with only PauliStringPhasor operations.
def pauli_string_half(circuit: circuits.Circuit) -> circuits.Circuit: """Return only the non-Clifford part of a circuit. See convert_and_separate_circuit(). Args: circuit: A Circuit with the gate set {SingleQubitCliffordGate, PauliInteractionGate, PauliStringPhasor}. Returns: ...
Verifies the density_matrix_rep is valid and converts it to ndarray form. This method is used to support passing a matrix, a vector (wave function), or a computational basis state as a representation of a state. Args: density_matrix_rep: If an numpy array, if it is of rank 2 (a matrix), ...
def to_valid_density_matrix( density_matrix_rep: Union[int, np.ndarray], num_qubits: int, dtype: Type[np.number] = np.complex64) -> np.ndarray: """Verifies the density_matrix_rep is valid and converts it to ndarray form. This method is used to support passing a matrix, a vector (wave function), ...
Performs a measurement of the density matrix in the computational basis. This does not modify `density_matrix` unless the optional `out` is `density_matrix`. Args: density_matrix: The density matrix to be measured. This matrix is assumed to be positive semidefinite and trace one. The m...
def measure_density_matrix( density_matrix: np.ndarray, indices: List[int], out: np.ndarray = None) -> Tuple[List[bool], np.ndarray]: """Performs a measurement of the density matrix in the computational basis. This does not modify `density_matrix` unless the optional `out` is `density_matrix`. ...
Returns the probabilities for a measurement on the given indices.
def _probs(density_matrix: np.ndarray, indices: List[int], num_qubits: int) -> List[float]: """Returns the probabilities for a measurement on the given indices.""" # Only diagonal elements matter. all_probs = np.diagonal( np.reshape(density_matrix, (2 ** num_qubits, 2 ** num_qubits))) # Shap...
Validates that matrix's shape is a valid shape for qubits.
def _validate_num_qubits(density_matrix: np.ndarray) -> int: """Validates that matrix's shape is a valid shape for qubits. """ shape = density_matrix.shape half_index = len(shape) // 2 row_size = np.prod(shape[:half_index]) if len(shape) != 0 else 0 col_size = np.prod(shape[half_index:]) if len(...
Applies a circuit's unitary effect to the given vector or matrix. This method assumes that the caller wants to ignore measurements. Args: circuit: The circuit to simulate. All operations must have a known matrix or decompositions leading to known matrices. Measurements are allo...
def _apply_unitary_circuit(circuit: Circuit, state: np.ndarray, qubits: Tuple[ops.Qid, ...], dtype: Type[np.number]) -> np.ndarray: """Applies a circuit's unitary effect to the given vector or matrix. This method assumes that the ...
Groups runs of items that are identical according to a keying function. Args: items: The items to group. key: If two adjacent items produce the same output from this function, they will be grouped. value: Maps each item into a value to put in the group. Defaults to the ...
def _group_until_different(items: Iterable[TIn], key: Callable[[TIn], TKey], value=lambda e: e): """Groups runs of items that are identical according to a keying function. Args: items: The items to group. key: If two adjacent items produce t...
Creates an empty circuit and appends the given operations. Args: operations: The operations to append to the new circuit. strategy: How to append the operations. device: Hardware that the circuit should be able to run on. Returns: The constructed circuit...
def from_ops(*operations: ops.OP_TREE, strategy: InsertStrategy = InsertStrategy.EARLIEST, device: devices.Device = devices.UnconstrainedDevice ) -> 'Circuit': """Creates an empty circuit and appends the given operations. Args: operations: ...
See `cirq.protocols.SupportsApproximateEquality`.
def _approx_eq_(self, other: Any, atol: Union[int, float]) -> bool: """See `cirq.protocols.SupportsApproximateEquality`.""" if not isinstance(other, type(self)): return NotImplemented return cirq.protocols.approx_eq( self._moments, other._moments, ...
Maps the current circuit onto a new device, and validates. Args: new_device: The new device that the circuit should be on. qubit_mapping: How to translate qubits from the old device into qubits on the new device. Returns: The translated circuit.
def with_device( self, new_device: devices.Device, qubit_mapping: Callable[[ops.Qid], ops.Qid] = lambda e: e, ) -> 'Circuit': """Maps the current circuit onto a new device, and validates. Args: new_device: The new device that the circuit should be on....
Print ASCII diagram in Jupyter.
def _repr_pretty_(self, p: Any, cycle: bool) -> None: """Print ASCII diagram in Jupyter.""" if cycle: # There should never be a cycle. This is just in case. p.text('Circuit(...)') else: p.text(self.to_text_diagram())
Finds the index of the next moment that touches the given qubits. Args: qubits: We're looking for operations affecting any of these qubits. start_moment_index: The starting point of the search. max_distance: The number of moments (starting from the start index ...
def next_moment_operating_on(self, qubits: Iterable[ops.Qid], start_moment_index: int = 0, max_distance: int = None) -> Optional[int]: """Finds the index of the next moment that touches the given qubits. ...
Finds the index of the next moment that touches each qubit. Args: qubits: The qubits to find the next moments acting on. start_moment_index: The starting point of the search. Returns: The index of the next moment that touches each qubit. If there is no s...
def next_moments_operating_on(self, qubits: Iterable[ops.Qid], start_moment_index: int = 0 ) -> Dict[ops.Qid, int]: """Finds the index of the next moment that touches each qubit. Args: qubi...
Finds the index of the next moment that touches the given qubits. Args: qubits: We're looking for operations affecting any of these qubits. end_moment_index: The moment index just after the starting point of the reverse search. Defaults to the length of the list of ...
def prev_moment_operating_on( self, qubits: Sequence[ops.Qid], end_moment_index: Optional[int] = None, max_distance: Optional[int] = None) -> Optional[int]: """Finds the index of the next moment that touches the given qubits. Args: qubits: We'...
Determines how far can be reached into a circuit under certain rules. The location L = (qubit, moment_index) is *reachable* if and only if: a) L is one of the items in `start_frontier`. OR b) There is no operation at L and prev(L) = (qubit, moment_index-1) ...
def reachable_frontier_from( self, start_frontier: Dict[ops.Qid, int], *, is_blocker: Callable[[ops.Operation], bool] = lambda op: False ) -> Dict[ops.Qid, int]: """Determines how far can be reached into a circuit under certain rules. The location L =...
Finds operations between the two given frontiers. If a qubit is in `start_frontier` but not `end_frontier`, its end index defaults to the end of the circuit. If a qubit is in `end_frontier` but not `start_frontier`, its start index defaults to the start of the circuit. Operations on qub...
def findall_operations_between(self, start_frontier: Dict[ops.Qid, int], end_frontier: Dict[ops.Qid, int], omit_crossing_operations: bool = False ) -> List[Tuple[int, ops.Operation...
Finds all operations until a blocking operation is hit. This returns a list of all operations from the starting frontier until a blocking operation is encountered. An operation is part of the list if it is involves a qubit in the start_frontier dictionary, comes after the moment listed...
def findall_operations_until_blocked( self, start_frontier: Dict[ops.Qid, int], is_blocker: Callable[[ops.Operation], bool] = lambda op: False ) -> List[Tuple[int, ops.Operation]]: """ Finds all operations until a blocking operation is hit. This returns a...
Finds the operation on a qubit within a moment, if any. Args: qubit: The qubit to check for an operation on. moment_index: The index of the moment to check for an operation within. Allowed to be beyond the end of the circuit. Returns: None if there i...
def operation_at(self, qubit: ops.Qid, moment_index: int) -> Optional[ops.Operation]: """Finds the operation on a qubit within a moment, if any. Args: qubit: The qubit to check for an operation on. moment_index: The index of the moment t...
Find the locations of all operations that satisfy a given condition. This returns an iterator of (index, operation) tuples where each operation satisfies op_cond(operation) is truthy. The indices are in order of the moments and then order of the ops within that moment. Args: ...
def findall_operations(self, predicate: Callable[[ops.Operation], bool] ) -> Iterable[Tuple[int, ops.Operation]]: """Find the locations of all operations that satisfy a given condition. This returns an iterator of (index, operation) tuples where each operation satisfi...
Find the locations of all gate operations of a given type. Args: gate_type: The type of gate to find, e.g. XPowGate or MeasurementGate. Returns: An iterator (index, operation, gate)'s for operations with the given gate type.
def findall_operations_with_gate_type( self, gate_type: Type[T_DESIRED_GATE_TYPE] ) -> Iterable[Tuple[int, ops.GateOperation, T_DESIRED_GATE_TYPE]]: """Find the locations of all gate operations of a given type. Args: ...
Check whether all of the ops that satisfy a predicate are terminal. Args: predicate: A predicate on ops.Operations which is being checked. Returns: Whether or not all `Operation` s in a circuit that satisfy the given predicate are terminal.
def are_all_matches_terminal(self, predicate: Callable[[ops.Operation], bool]): """Check whether all of the ops that satisfy a predicate are terminal. Args: predicate: A predicate on ops.Operations which is being checked. Returns: Whether or not all `Operati...
Determines and prepares where an insertion will occur. Args: splitter_index: The index to insert at. op: The operation that will be inserted. strategy: The insertion strategy. Returns: The index of the (possibly new) moment where the insertion should ...
def _pick_or_create_inserted_op_moment_index( self, splitter_index: int, op: ops.Operation, strategy: InsertStrategy) -> int: """Determines and prepares where an insertion will occur. Args: splitter_index: The index to insert at. op: The operation that wi...
Inserts operations into the circuit. Operations are inserted into the moment specified by the index and 'InsertStrategy'. Moments within the operation tree are inserted intact. Args: index: The index to insert all of the operations at. moment_or_opera...
def insert( self, index: int, moment_or_operation_tree: Union[ops.Moment, ops.OP_TREE], strategy: InsertStrategy = InsertStrategy.EARLIEST) -> int: """ Inserts operations into the circuit. Operations are inserted into the moment specified by the index ...
Writes operations inline into an area of the circuit. Args: start: The start of the range (inclusive) to write the given operations into. end: The end of the range (exclusive) to write the given operations into. If there are still operations remaining, ...
def insert_into_range(self, operations: ops.OP_TREE, start: int, end: int) -> int: """Writes operations inline into an area of the circuit. Args: start: The start of the range (inclusive) to write the ...
Greedily assigns operations to moments. Args: operations: The operations to assign to moments. start: The first moment to consider assignment to. frontier: The first moment to which an operation acting on a qubit can be assigned. Updated in place as operation...
def _pick_inserted_ops_moment_indices(operations: Sequence[ops.Operation], start: int = 0, frontier: Dict[ops.Qid, int] = None ) -> Tuple...
Inserts moments to separate two frontiers. After insertion n_new moments, the following holds: for q in late_frontier: early_frontier[q] <= late_frontier[q] + n_new for q in update_qubits: early_frontier[q] the identifies the same moment as before ...
def _push_frontier(self, early_frontier: Dict[ops.Qid, int], late_frontier: Dict[ops.Qid, int], update_qubits: Iterable[ops.Qid] = None ) -> Tuple[int, int]: """Inserts moments to separate two frontiers. After i...
Inserts operations at the specified moments. Appends new moments if necessary. Args: operations: The operations to insert. insertion_indices: Where to insert them, i.e. operations[i] is inserted into moments[insertion_indices[i]. Raises: Valu...
def _insert_operations(self, operations: Sequence[ops.Operation], insertion_indices: Sequence[int]) -> None: """Inserts operations at the specified moments. Appends new moments if necessary. Args: operations: The operations to in...
Removes several operations from a circuit. Args: removals: A sequence of (moment_index, operation) tuples indicating operations to delete from the moments that are present. All listed operations must actually be present or the edit will fail (without ...
def batch_remove(self, removals: Iterable[Tuple[int, ops.Operation]]) -> None: """Removes several operations from a circuit. Args: removals: A sequence of (moment_index, operation) tuples indicating operations to delete from the moments that are present....
Inserts operations into empty spaces in existing moments. If any of the insertions fails (due to colliding with an existing operation), this method fails without making any changes to the circuit. Args: insert_intos: A sequence of (moment_index, new_operation) pairs...
def batch_insert_into(self, insert_intos: Iterable[Tuple[int, ops.Operation]] ) -> None: """Inserts operations into empty spaces in existing moments. If any of the insertions fails (due to colliding with an existing operation), this method fai...
Applies a batched insert operation to the circuit. Transparently handles the fact that earlier insertions may shift the index that later insertions should occur at. For example, if you insert an operation at index 2 and at index 4, but the insert at index 2 causes a new moment to be cre...
def batch_insert(self, insertions: Iterable[Tuple[int, ops.OP_TREE]]) -> None: """Applies a batched insert operation to the circuit. Transparently handles the fact that earlier insertions may shift the index that later insertions should occur at. For example, if you ...
Appends operations onto the end of the circuit. Moments within the operation tree are appended intact. Args: moment_or_operation_tree: The moment or operation tree to append. strategy: How to pick/create the moment to put operations into.
def append( self, moment_or_operation_tree: Union[ops.Moment, ops.OP_TREE], strategy: InsertStrategy = InsertStrategy.EARLIEST): """Appends operations onto the end of the circuit. Moments within the operation tree are appended intact. Args: momen...
Clears operations that are touching given qubits at given moments. Args: qubits: The qubits to check for operations on. moment_indices: The indices of moments to check for operations within.
def clear_operations_touching(self, qubits: Iterable[ops.Qid], moment_indices: Iterable[int]): """Clears operations that are touching given qubits at given moments. Args: qubits: The qubits to check for operations on. ...
Returns the qubits acted upon by Operations in this circuit.
def all_qubits(self) -> FrozenSet[ops.Qid]: """Returns the qubits acted upon by Operations in this circuit.""" return frozenset(q for m in self._moments for q in m.qubits)
Iterates over the operations applied by this circuit. Operations from earlier moments will be iterated over first. Operations within a moment are iterated in the order they were given to the moment's constructor.
def all_operations(self) -> Iterator[ops.Operation]: """Iterates over the operations applied by this circuit. Operations from earlier moments will be iterated over first. Operations within a moment are iterated in the order they were given to the moment's constructor. """ ...
Converts the circuit into a unitary matrix, if possible. If the circuit contains any non-terminal measurements, the conversion into a unitary matrix fails (i.e. returns NotImplemented). Terminal measurements are ignored when computing the unitary matrix. The unitary matrix is the produc...
def _unitary_(self) -> Union[np.ndarray, NotImplementedType]: """Converts the circuit into a unitary matrix, if possible. If the circuit contains any non-terminal measurements, the conversion into a unitary matrix fails (i.e. returns NotImplemented). Terminal measurements are ignored wh...
Returns text containing a diagram describing the circuit. Args: use_unicode_characters: Determines if unicode characters are allowed (as opposed to ascii-only diagrams). transpose: Arranges qubit wires vertically instead of horizontally. precision: Number of ...
def to_text_diagram( self, *, use_unicode_characters: bool = True, transpose: bool = False, precision: Optional[int] = 3, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT) -> str: """Returns text containing a diagram describing th...
Returns a TextDiagramDrawer with the circuit drawn into it. Args: use_unicode_characters: Determines if unicode characters are allowed (as opposed to ascii-only diagrams). qubit_namer: Names qubits in diagram. Defaults to str. transpose: Arranges qubit wires ...
def to_text_diagram_drawer( self, *, use_unicode_characters: bool = True, qubit_namer: Optional[Callable[[ops.Qid], str]] = None, transpose: bool = False, precision: Optional[int] = 3, qubit_order: ops.QubitOrderOrList = ops.QubitOrder....
Returns a QASM object equivalent to the circuit. Args: header: A multi-line string that is placed in a comment at the top of the QASM. Defaults to a cirq version specifier. precision: Number of digits to use when representing numbers. qubit_order: Determines ...
def _to_qasm_output( self, header: Optional[str] = None, precision: int = 10, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, ) -> QasmOutput: """Returns a QASM object equivalent to the circuit. Args: header: A multi-line strin...
Save a QASM file equivalent to the circuit. Args: file_path: The location of the file where the qasm will be written. header: A multi-line string that is placed in a comment at the top of the QASM. Defaults to a cirq version specifier. precision: Number of di...
def save_qasm(self, file_path: Union[str, bytes, int], header: Optional[str] = None, precision: int = 10, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, ) -> None: """Save a QASM file equivalent to the circuit...
Returns QASM equivalent to the circuit. Args: header: A multi-line string that is placed in a comment at the top of the QASM. Defaults to a cirq version specifier. precision: Number of digits to use when representing numbers. qubit_order: Determines how qubit...
def to_qasm(self, header: Optional[str] = None, precision: int = 10, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, ) -> str: """Returns QASM equivalent to the circuit. Args: header: A multi-line string that is pla...
Returns QASM code for the given value, if possible. Different values require different sets of arguments. The general rule of thumb is that circuits don't need any, operations need a `QasmArgs`, and gates need both a `QasmArgs` and `qubits`. Args: val: The value to turn into QASM code. ...
def qasm(val: Any, *, args: Optional[QasmArgs] = None, qubits: Optional[Iterable['cirq.Qid']] = None, default: TDefault = RaiseTypeErrorIfNotProvided ) -> Union[str, TDefault]: """Returns QASM code for the given value, if possible. Different values require different...
Method of string.Formatter that specifies the output of format().
def format_field(self, value: Any, spec: str) -> str: """Method of string.Formatter that specifies the output of format().""" from cirq import ops # HACK: avoids cyclic dependency. if isinstance(value, (float, int)): if isinstance(value, float): value = round(value, ...
Gates implementing the function f(a) = a·factors + bias (mod 2).
def make_oracle(input_qubits, output_qubit, secret_factor_bits, secret_bias_bit): """Gates implementing the function f(a) = a·factors + bias (mod 2).""" if secret_bias_bit: yield cirq.X(output_qubit) for qubit, bit in zip(input_qubits, secret_factor_...
Solves for factors in f(a) = a·factors + bias (mod 2) with one query.
def make_bernstein_vazirani_circuit(input_qubits, output_qubit, oracle): """Solves for factors in f(a) = a·factors + bias (mod 2) with one query.""" c = cirq.Circuit() # Initialize qubits. c.append([ cirq.X(output_qubit), cirq.H(output_qubit), cirq.H.on_each(*input_qubits), ...
Returns the big-endian integers specified by groups of bits. Args: bit_groups: Groups of descending bits, each specifying a big endian integer with the 1s bit at the end. Returns: A tuple containing the integer for each group.
def _tuple_of_big_endian_int(bit_groups: Tuple[np.ndarray, ...] ) -> Tuple[int, ...]: """Returns the big-endian integers specified by groups of bits. Args: bit_groups: Groups of descending bits, each specifying a big endian integer with the 1s bit at the end. ...
Returns the big-endian integer specified by the given bits. For example, [True, False, False, True, False] becomes binary 10010 which is 18 in decimal. Args: bits: Descending bits of the integer, with the 1s bit at the end. Returns: The integer.
def _big_endian_int(bits: np.ndarray) -> int: """Returns the big-endian integer specified by the given bits. For example, [True, False, False, True, False] becomes binary 10010 which is 18 in decimal. Args: bits: Descending bits of the integer, with the 1s bit at the end. Returns: ...
Gates implementing the secret function f(x).
def make_oracle(q0, q1, secret_function): """ Gates implementing the secret function f(x).""" # coverage: ignore if secret_function[0]: yield [CNOT(q0, q1), X(q1)] if secret_function[1]: yield CNOT(q0, q1)
Gives adjacency list representation of a chip. The adjacency list is constructed in order of above, left_of, below and right_of consecutively. Args: device: Chip to be converted. Returns: Map from nodes to list of qubits which represent all the neighbours of given qubit.
def chip_as_adjacency_list(device: 'cirq.google.XmonDevice', ) -> Dict[GridQubit, List[GridQubit]]: """Gives adjacency list representation of a chip. The adjacency list is constructed in order of above, left_of, below and right_of consecutively. Args: device: Chip to...
Constructs the HHL circuit. A is the input Hermitian matrix. C and t are tunable parameters for the algorithm. register_size is the size of the eigenvalue register. input_prep_gates is a list of gates to be applied to |0> to generate the desired input state |b>.
def hhl_circuit(A, C, t, register_size, *input_prep_gates): """ Constructs the HHL circuit. A is the input Hermitian matrix. C and t are tunable parameters for the algorithm. register_size is the size of the eigenvalue register. input_prep_gates is a list of gates to be applied to |0> to genera...
Simulates HHL with matrix input, and outputs Pauli observables of the resulting qubit state |x>. Expected observables are calculated from the expected solution |x>.
def main(): """ Simulates HHL with matrix input, and outputs Pauli observables of the resulting qubit state |x>. Expected observables are calculated from the expected solution |x>. """ # Eigendecomposition: # (4.537, [-0.971555, -0.0578339+0.229643j]) # (0.349, [-0.236813, 0.237270-...
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`.""" circuit = protocols.resolve_parameters(circuit, param_resolver) _verify_xmon_c...
See definition in `cirq.SimulatesIntermediateState`. If the initial state is an int, the state is set to the computational basis state corresponding to this state. Otherwise if the initial state is a np.ndarray it is the full initial state. In this case it must be the correct size, be ...
def _base_iterator( self, circuit: circuits.Circuit, qubit_order: ops.QubitOrderOrList, initial_state: Union[int, np.ndarray], perform_measurements: bool=True, ) -> Iterator['XmonStepResult']: """See definition in `cirq.SimulatesIntermediateState`. If the ini...
Updates the state of the simulator to the given new state. Args: state: If this is an int, then this is the state to reset the stepper to, expressed as an integer of the computational basis. Integer to bitwise indices is little endian. Otherwise if this is a np.n...
def set_state_vector(self, state: Union[int, np.ndarray]): """Updates the state of the simulator to the given new state. Args: state: If this is an int, then this is the state to reset the stepper to, expressed as an integer of the computational basis. Integer to bit...
Samples from the wave function at this point in the computation. Note that this does not collapse the wave function. Returns: Measurement results with True corresponding to the `|1>` state. The outer list is for repetitions, and the inner corresponds to measurements...
def sample(self, qubits: List[ops.Qid], repetitions: int=1): """Samples from the wave function at this point in the computation. Note that this does not collapse the wave function. Returns: Measurement results with True corresponding to the `|1>` state. The outer list i...
Adds possibly stateful noise to a series of moments. Args: moments: The moments to add noise to. system_qubits: A list of all qubits in the system. Returns: A sequence of OP_TREEs, with the k'th tree corresponding to the noisy operations for the k'th mom...
def noisy_moments(self, moments: 'Iterable[cirq.Moment]', system_qubits: Sequence['cirq.Qid'] ) -> Sequence['cirq.OP_TREE']: """Adds possibly stateful noise to a series of moments. Args: moments: The moments to add noise to. system_qubi...
Adds noise to the operations from a moment. Args: moment: The moment to add noise to. system_qubits: A list of all qubits in the system. Returns: An OP_TREE corresponding to the noisy operations for the moment.
def noisy_moment(self, moment: 'cirq.Moment', system_qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE': """Adds noise to the operations from a moment. Args: moment: The moment to add noise to. system_qubits: A list of all qubits in the system. Returns...
Adds noise to an individual operation. Args: operation: The operation to make noisy. Returns: An OP_TREE corresponding to the noisy operations implementing the noisy version of the given operation.
def noisy_operation(self, operation: 'cirq.Operation') -> 'cirq.OP_TREE': """Adds noise to an individual operation. Args: operation: The operation to make noisy. Returns: An OP_TREE corresponding to the noisy operations implementing the noisy version of the ...
Get the measurement key for the given value. Args: val: The value which has the measurement key.. default: Determines the fallback behavior when `val` doesn't have a measurement key. If `default` is not set, a TypeError is raised. If default is set to a value, that value is ...
def measurement_key( val: Any, default: Any = RaiseTypeErrorIfNotProvided): """Get the measurement key for the given value. Args: val: The value which has the measurement key.. default: Determines the fallback behavior when `val` doesn't have a measurement key. If `d...
Generates Google Random Circuits v2 as in github.com/sboixo/GRCS cz_v2. See also https://arxiv.org/abs/1807.10749 Args: qubits: qubit grid in which to generate the circuit. cz_depth: number of layers with CZ gates. seed: seed for the random instance. Returns: A circuit corr...
def generate_supremacy_circuit_google_v2(qubits: Iterable[devices.GridQubit], cz_depth: int, seed: int) -> circuits.Circuit: """ Generates Google Random Circuits v2 as in github.com/sboixo/GRCS cz_v2. See also https://arxiv.or...
Generates Google Random Circuits v2 as in github.com/sboixo/GRCS cz_v2. See also https://arxiv.org/abs/1807.10749 Args: n_rows: number of rows of a 2D lattice. n_cols: number of columns. cz_depth: number of layers with CZ gates. seed: seed for the random instance. Returns: ...
def generate_supremacy_circuit_google_v2_grid(n_rows: int, n_cols: int, cz_depth: int, seed: int ) -> circuits.Circuit: """ Generates Google Random Circuits v2 as in github.com/sboixo/GRCS cz_v2. See also https://arx...
Generates Google Random Circuits v2 in Bristlecone. See also https://arxiv.org/abs/1807.10749 Args: n_rows: number of rows in a Bristlecone lattice. Note that we do not include single qubit corners. cz_depth: number of layers with CZ gates. seed: seed for the random instance. ...
def generate_supremacy_circuit_google_v2_bristlecone(n_rows: int, cz_depth: int, seed: int ) -> circuits.Circuit: """ Generates Google Random Circuits v2 in Bristlecone. See also https://arxiv.org/abs/1...