INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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 (). | 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 (). | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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 in that dictionary and before any ... | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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... |
Inserts operations inline at frontier. | def insert_at_frontier(self,
operations: ops.OP_TREE,
start: int,
frontier: Dict[ops.Qid, int] = None
) -> Dict[ops.Qid, int]:
"""Inserts operations inline at frontier.
Args:
operatio... |
Removes several operations from a circuit. | 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. | 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. | 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. | 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. | 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. | 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. | 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... |
Converts the circuit into a unitary matrix if possible. | def to_unitary_matrix(
self,
qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
qubits_that_should_be_present: Iterable[ops.Qid] = (),
ignore_terminal_measurements: bool = True,
dtype: Type[np.number] = np.complex128) -> np.ndarray:
"""Convert... |
Returns text containing a diagram describing the circuit. | 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. | 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. | 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... |
Returns QASM equivalent to the circuit. | 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... |
Save a QASM file equivalent to the circuit. | 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 code for the given value if possible. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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 | 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 | 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 | 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... |
Choose a random element from a non - empty sequence. | def _choice(rand_gen: Callable[[], float], sequence: Sequence[T]) -> T:
"""Choose a random element from a non-empty sequence.
Use this instead of random.choice, with random.random(), for reproducibility
"""
return sequence[int(rand_gen() * len(sequence))] |
Each layer index corresponds to a shift/ transpose of this CZ pattern: | def _make_cz_layer(qubits: Iterable[devices.GridQubit], layer_index: int
) -> Iterable[ops.Operation]:
"""
Each layer index corresponds to a shift/transpose of this CZ pattern:
●───● ● ● ●───● ● ● . . .
● ● ●───● ● ● ●───● . . .
●───● ● ● ●... |
Determines the effect of an operation on the given qubits. | def _op_to_matrix(self,
op: Optional[ops.Operation],
qubits: Tuple[ops.Qid, ...]
) -> Optional[np.ndarray]:
"""Determines the effect of an operation on the given qubits.
If the operation is a 1-qubit operation on one of the given qubits,... |
Accumulates operations affecting the given pair of qubits. | def _scan_two_qubit_ops_into_matrix(
self,
circuit: circuits.Circuit,
index: Optional[int],
qubits: Tuple[ops.Qid, ...]
) -> Tuple[List[ops.Operation], List[int], np.ndarray]:
"""Accumulates operations affecting the given pair of qubits.
The scan term... |
Given M = sum ( kron ( a_i b_i )) returns M = sum ( kron ( b_i a_i )). | def _flip_kron_order(mat4x4: np.ndarray) -> np.ndarray:
"""Given M = sum(kron(a_i, b_i)), returns M' = sum(kron(b_i, a_i))."""
result = np.array([[0] * 4] * 4, dtype=np.complex128)
order = [0, 2, 1, 3]
for i in range(4):
for j in range(4):
result[order[i], ord... |
Returns a Controlled version of the given value if defined. | def control(controllee: Union['cirq.Gate', op_tree.OP_TREE],
control_qubits: Sequence['cirq.Qid'] = None,
default: Any = RaiseTypeErrorIfNotProvided) -> Any:
"""Returns a Controlled version of the given value, if defined.
Controllees define how to be controlled by defining a method
... |
Returns the inverse val ** - 1 of the given value if defined. | def inverse(val: Any, default: Any = RaiseTypeErrorIfNotProvided) -> Any:
"""Returns the inverse `val**-1` of the given value, if defined.
An object can define an inverse by defining a __pow__(self, exponent) method
that returns something besides NotImplemented when given the exponent -1.
The inverse o... |
Decomposes a two - qubit operation into MS/ single - qubit rotation gates. | def two_qubit_matrix_to_ion_operations(q0: ops.Qid,
q1: ops.Qid,
mat: np.ndarray,
atol: float = 1e-8
) -> List[ops.Operation]:
"""Decomposes a two-qubit operati... |
Yields an XX 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 an XX interaction framed by the given operation."""
if abs(rads) < atol:
return
if... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.