text stringlengths 81 112k |
|---|
Implements a single-qubit operation with few rotations.
Args:
mat: The 2x2 unitary matrix of the operation to implement.
atol: A limit on the amount of absolute error introduced by the
construction.
Returns:
A list of (Pauli, half_turns) tuples that, when applied in order,
... |
Implements a single-qubit operation with few gates.
Args:
mat: The 2x2 unitary matrix of the operation to implement.
tolerance: A limit on the amount of error introduced by the
construction.
Returns:
A list of gates that, when applied in order, perform the desired
... |
Decomposes a 2x2 unitary M into U^-1 * diag(1, r) * U * diag(g, g).
U translates the rotation axis of M to the Z axis.
g fixes a global phase factor difference caused by the translation.
r's phase is the amount of rotation around M's rotation axis.
This decomposition can be used to decompose controlle... |
Breaks down a 2x2 unitary into gate parameters.
Args:
mat: The 2x2 unitary matrix to break down.
Returns:
A tuple containing the amount to rotate around an XY axis, the phase of
that axis, and the amount to phase around Z. All results will be in
fractions of a whole turn, with val... |
Implements a single-qubit operation with a PhasedX and Z gate.
If one of the gates isn't needed, it will be omitted.
Args:
mat: The 2x2 unitary matrix of the operation to implement.
atol: A limit on the amount of error introduced by the
construction.
Returns:
A list of... |
Returns a unitary matrix describing the given value.
Args:
val: The value to describe with a unitary matrix.
default: Determines the fallback behavior when `val` doesn't have
a unitary matrix. If `default` is not set, a TypeError is raised. If
default is set to a value, that... |
Returns whether the value has a unitary matrix representation.
Returns:
If `val` has a _has_unitary_ method and its result is not
NotImplemented, that result is returned. Otherwise, if `val` is a
cirq.Gate or cirq.Operation, a decomposition is attempted and the
resulting unitary is ... |
Try to decompose a cirq.Operation or cirq.Gate, and return its unitary
if it exists.
Returns:
If `val` can be decomposed into unitaries, calculate the resulting
unitary and return it. If it doesn't exist, None is returned.
def _decompose_and_get_unitary(val: Union['cirq.Operation', 'cirq.Gate'... |
References:
https://developer.github.com/v3/issues/events/#list-events-for-an-issue
def check_collaborator_has_write(repo: GithubRepository, username: str
) -> Optional[CannotAutomergeError]:
"""
References:
https://developer.github.com/v3/issues/events/#list-ev... |
References:
https://developer.github.com/v3/issues/events/#list-events-for-an-issue
def check_auto_merge_labeler(repo: GithubRepository, pull_id: int
) -> Optional[CannotAutomergeError]:
"""
References:
https://developer.github.com/v3/issues/events/#list-events-for-... |
References:
https://developer.github.com/v3/issues/comments/#create-a-comment
def add_comment(repo: GithubRepository, pull_id: int, text: str) -> None:
"""
References:
https://developer.github.com/v3/issues/comments/#create-a-comment
"""
url = ("https://api.github.com/repos/{}/{}/issues... |
References:
https://developer.github.com/v3/issues/comments/#edit-a-comment
def edit_comment(repo: GithubRepository, text: str, comment_id: int) -> None:
"""
References:
https://developer.github.com/v3/issues/comments/#edit-a-comment
"""
url = ("https://api.github.com/repos/{}/{}/issues... |
References:
https://developer.github.com/v3/repos/branches/#get-branch
def get_branch_details(repo: GithubRepository, branch: str) -> Any:
"""
References:
https://developer.github.com/v3/repos/branches/#get-branch
"""
url = ("https://api.github.com/repos/{}/{}/branches/{}"
"?... |
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
... |
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/{}/{}... |
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/rep... |
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/{}"
"... |
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
"""
... |
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/comm... |
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_s... |
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
"""
... |
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)... |
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... |
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-l... |
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[CannotA... |
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
"""
ur... |
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 ]
... |
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:
... |
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... |
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.ga... |
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... |
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 ansa... |
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 ... |
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 ... |
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({})
... |
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... |
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... |
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... |
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... |
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)... |
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,
... |
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 = n... |
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.C... |
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... |
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... |
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.
... |
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 i... |
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_q... |
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.auxili... |
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... |
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.
... |
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(... |
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),
... |
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... |
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.resh... |
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) !=... |
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... |
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
... |
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... |
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... |
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... |
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
... |
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... |
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
... |
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)
... |
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... |
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... |
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... |
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:
... |
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_w... |
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_term... |
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
... |
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... |
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,
... |
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... |
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
... |
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... |
Inserts operations inline at frontier.
Args:
operations: the operations to insert
start: the moment at which to start inserting the operations
frontier: frontier[q] is the earliest moment in which an operation
acting on qubit q can be placed.
def insert_at_f... |
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 ... |
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... |
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... |
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,
... |
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: I... |
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... |
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... |
Converts the circuit into a unitary matrix, if possible.
Args:
qubit_order: Determines how qubits are ordered when passing matrices
into np.kron.
qubits_that_should_be_present: Qubits that may or may not appear
in operations within the circuit, but that s... |
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 ... |
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 ... |
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 ... |
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... |
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... |
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.
... |
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)):
... |
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(out... |
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),
... |
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.ndar... |
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) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.