partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | rabi_oscillations | Runs a Rabi oscillation experiment.
Rotates a qubit around the x-axis of the Bloch sphere by a sequence of Rabi
angles evenly spaced between 0 and max_angle. For each rotation, repeat
the circuit a number of times and measure the average probability of the
qubit being in the |1> state.
Args:
... | cirq/experiments/qubit_characterizations.py | def rabi_oscillations(sampler: sim.Sampler,
qubit: devices.GridQubit,
max_angle: float = 2 * np.pi,
*,
repetitions: int = 1000,
num_points: int = 200) -> RabiResult:
"""Runs a Rabi oscillation experiment.
... | def rabi_oscillations(sampler: sim.Sampler,
qubit: devices.GridQubit,
max_angle: float = 2 * np.pi,
*,
repetitions: int = 1000,
num_points: int = 200) -> RabiResult:
"""Runs a Rabi oscillation experiment.
... | [
"Runs",
"a",
"Rabi",
"oscillation",
"experiment",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/experiments/qubit_characterizations.py#L122-L157 | [
"def",
"rabi_oscillations",
"(",
"sampler",
":",
"sim",
".",
"Sampler",
",",
"qubit",
":",
"devices",
".",
"GridQubit",
",",
"max_angle",
":",
"float",
"=",
"2",
"*",
"np",
".",
"pi",
",",
"*",
",",
"repetitions",
":",
"int",
"=",
"1000",
",",
"num_p... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | single_qubit_randomized_benchmarking | Clifford-based randomized benchmarking (RB) of a single qubit.
A total of num_circuits random circuits are generated, each of which
contains a fixed number of single-qubit Clifford gates plus one
additional Clifford that inverts the whole sequence and a measurement in
the z-basis. Each circuit is repea... | cirq/experiments/qubit_characterizations.py | def single_qubit_randomized_benchmarking(
sampler: sim.Sampler,
qubit: devices.GridQubit,
use_xy_basis: bool = True,
*,
num_clifford_range: Sequence[int] = range(10, 100, 10),
num_circuits: int = 20,
repetitions: int = 1000) -> RandomizedBenchMarkResult:
"""Cl... | def single_qubit_randomized_benchmarking(
sampler: sim.Sampler,
qubit: devices.GridQubit,
use_xy_basis: bool = True,
*,
num_clifford_range: Sequence[int] = range(10, 100, 10),
num_circuits: int = 20,
repetitions: int = 1000) -> RandomizedBenchMarkResult:
"""Cl... | [
"Clifford",
"-",
"based",
"randomized",
"benchmarking",
"(",
"RB",
")",
"of",
"a",
"single",
"qubit",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/experiments/qubit_characterizations.py#L160-L216 | [
"def",
"single_qubit_randomized_benchmarking",
"(",
"sampler",
":",
"sim",
".",
"Sampler",
",",
"qubit",
":",
"devices",
".",
"GridQubit",
",",
"use_xy_basis",
":",
"bool",
"=",
"True",
",",
"*",
",",
"num_clifford_range",
":",
"Sequence",
"[",
"int",
"]",
"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | two_qubit_randomized_benchmarking | Clifford-based randomized benchmarking (RB) of two qubits.
A total of num_circuits random circuits are generated, each of which
contains a fixed number of two-qubit Clifford gates plus one additional
Clifford that inverts the whole sequence and a measurement in the
z-basis. Each circuit is repeated a n... | cirq/experiments/qubit_characterizations.py | def two_qubit_randomized_benchmarking(
sampler: sim.Sampler,
first_qubit: devices.GridQubit,
second_qubit: devices.GridQubit,
*,
num_clifford_range: Sequence[int] = range(5, 50, 5),
num_circuits: int = 20,
repetitions: int = 1000) -> RandomizedBenchMarkResult:
... | def two_qubit_randomized_benchmarking(
sampler: sim.Sampler,
first_qubit: devices.GridQubit,
second_qubit: devices.GridQubit,
*,
num_clifford_range: Sequence[int] = range(5, 50, 5),
num_circuits: int = 20,
repetitions: int = 1000) -> RandomizedBenchMarkResult:
... | [
"Clifford",
"-",
"based",
"randomized",
"benchmarking",
"(",
"RB",
")",
"of",
"two",
"qubits",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/experiments/qubit_characterizations.py#L219-L275 | [
"def",
"two_qubit_randomized_benchmarking",
"(",
"sampler",
":",
"sim",
".",
"Sampler",
",",
"first_qubit",
":",
"devices",
".",
"GridQubit",
",",
"second_qubit",
":",
"devices",
".",
"GridQubit",
",",
"*",
",",
"num_clifford_range",
":",
"Sequence",
"[",
"int",... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | single_qubit_state_tomography | Single-qubit state tomography.
The density matrix of the output state of a circuit is measured by first
doing projective measurements in the z-basis, which determine the
diagonal elements of the matrix. A X/2 or Y/2 rotation is then added before
the z-basis measurement, which determines the imaginary a... | cirq/experiments/qubit_characterizations.py | def single_qubit_state_tomography(sampler: sim.Sampler,
qubit: devices.GridQubit,
circuit: circuits.Circuit,
repetitions: int = 1000) -> TomographyResult:
"""Single-qubit state tomography.
The density matrix o... | def single_qubit_state_tomography(sampler: sim.Sampler,
qubit: devices.GridQubit,
circuit: circuits.Circuit,
repetitions: int = 1000) -> TomographyResult:
"""Single-qubit state tomography.
The density matrix o... | [
"Single",
"-",
"qubit",
"state",
"tomography",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/experiments/qubit_characterizations.py#L278-L321 | [
"def",
"single_qubit_state_tomography",
"(",
"sampler",
":",
"sim",
".",
"Sampler",
",",
"qubit",
":",
"devices",
".",
"GridQubit",
",",
"circuit",
":",
"circuits",
".",
"Circuit",
",",
"repetitions",
":",
"int",
"=",
"1000",
")",
"->",
"TomographyResult",
"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | two_qubit_state_tomography | r"""Two-qubit state tomography.
To measure the density matrix of the output state of a two-qubit circuit,
different combinations of I, X/2 and Y/2 operations are applied to the
two qubits before measurements in the z-basis to determine the state
probabilities P_00, P_01, P_10.
The density matrix r... | cirq/experiments/qubit_characterizations.py | def two_qubit_state_tomography(sampler: sim.Sampler,
first_qubit: devices.GridQubit,
second_qubit: devices.GridQubit,
circuit: circuits.Circuit,
repetitions: int = 1000) -> TomographyResult:
r... | def two_qubit_state_tomography(sampler: sim.Sampler,
first_qubit: devices.GridQubit,
second_qubit: devices.GridQubit,
circuit: circuits.Circuit,
repetitions: int = 1000) -> TomographyResult:
r... | [
"r",
"Two",
"-",
"qubit",
"state",
"tomography",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/experiments/qubit_characterizations.py#L324-L440 | [
"def",
"two_qubit_state_tomography",
"(",
"sampler",
":",
"sim",
".",
"Sampler",
",",
"first_qubit",
":",
"devices",
".",
"GridQubit",
",",
"second_qubit",
":",
"devices",
".",
"GridQubit",
",",
"circuit",
":",
"circuits",
".",
"Circuit",
",",
"repetitions",
"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | _two_qubit_clifford | Generates a two-qubit Clifford gate.
An integer (idx) from 0 to 11519 is used to generate a two-qubit Clifford
gate which is constructed with single-qubit X and Y rotations and CZ gates.
The decomposition of the Cliffords follow those described in the appendix
of Barends et al., Nature 508, 500.
T... | cirq/experiments/qubit_characterizations.py | def _two_qubit_clifford(q_0: devices.GridQubit, q_1: devices.GridQubit,
idx: int,
cliffords: Cliffords) -> Iterator[ops.OP_TREE]:
"""Generates a two-qubit Clifford gate.
An integer (idx) from 0 to 11519 is used to generate a two-qubit Clifford
gate which is c... | def _two_qubit_clifford(q_0: devices.GridQubit, q_1: devices.GridQubit,
idx: int,
cliffords: Cliffords) -> Iterator[ops.OP_TREE]:
"""Generates a two-qubit Clifford gate.
An integer (idx) from 0 to 11519 is used to generate a two-qubit Clifford
gate which is c... | [
"Generates",
"a",
"two",
"-",
"qubit",
"Clifford",
"gate",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/experiments/qubit_characterizations.py#L557-L633 | [
"def",
"_two_qubit_clifford",
"(",
"q_0",
":",
"devices",
".",
"GridQubit",
",",
"q_1",
":",
"devices",
".",
"GridQubit",
",",
"idx",
":",
"int",
",",
"cliffords",
":",
"Cliffords",
")",
"->",
"Iterator",
"[",
"ops",
".",
"OP_TREE",
"]",
":",
"c1",
"="... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | RabiResult.data | Returns a sequence of tuple pairs with the first item being a Rabi
angle and the second item being the corresponding excited state
probability. | cirq/experiments/qubit_characterizations.py | def data(self) -> Sequence[Tuple[float, float]]:
"""Returns a sequence of tuple pairs with the first item being a Rabi
angle and the second item being the corresponding excited state
probability.
"""
return [(angle, prob) for angle, prob in zip(self._rabi_angles,
... | def data(self) -> Sequence[Tuple[float, float]]:
"""Returns a sequence of tuple pairs with the first item being a Rabi
angle and the second item being the corresponding excited state
probability.
"""
return [(angle, prob) for angle, prob in zip(self._rabi_angles,
... | [
"Returns",
"a",
"sequence",
"of",
"tuple",
"pairs",
"with",
"the",
"first",
"item",
"being",
"a",
"Rabi",
"angle",
"and",
"the",
"second",
"item",
"being",
"the",
"corresponding",
"excited",
"state",
"probability",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/experiments/qubit_characterizations.py#L35-L41 | [
"def",
"data",
"(",
"self",
")",
"->",
"Sequence",
"[",
"Tuple",
"[",
"float",
",",
"float",
"]",
"]",
":",
"return",
"[",
"(",
"angle",
",",
"prob",
")",
"for",
"angle",
",",
"prob",
"in",
"zip",
"(",
"self",
".",
"_rabi_angles",
",",
"self",
".... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | RabiResult.plot | Plots excited state probability vs the Rabi angle (angle of rotation
around the x-axis).
Args:
**plot_kwargs: Arguments to be passed to matplotlib.pyplot.plot. | cirq/experiments/qubit_characterizations.py | def plot(self, **plot_kwargs: Any) -> None:
"""Plots excited state probability vs the Rabi angle (angle of rotation
around the x-axis).
Args:
**plot_kwargs: Arguments to be passed to matplotlib.pyplot.plot.
"""
fig = plt.figure()
plt.plot(self._rabi_angles, s... | def plot(self, **plot_kwargs: Any) -> None:
"""Plots excited state probability vs the Rabi angle (angle of rotation
around the x-axis).
Args:
**plot_kwargs: Arguments to be passed to matplotlib.pyplot.plot.
"""
fig = plt.figure()
plt.plot(self._rabi_angles, s... | [
"Plots",
"excited",
"state",
"probability",
"vs",
"the",
"Rabi",
"angle",
"(",
"angle",
"of",
"rotation",
"around",
"the",
"x",
"-",
"axis",
")",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/experiments/qubit_characterizations.py#L43-L55 | [
"def",
"plot",
"(",
"self",
",",
"*",
"*",
"plot_kwargs",
":",
"Any",
")",
"->",
"None",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
")",
"plt",
".",
"plot",
"(",
"self",
".",
"_rabi_angles",
",",
"self",
".",
"_excited_state_probs",
",",
"'ro-'",
... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | RandomizedBenchMarkResult.data | Returns a sequence of tuple pairs with the first item being a
number of Cliffords and the second item being the corresponding average
ground state probability. | cirq/experiments/qubit_characterizations.py | def data(self) -> Sequence[Tuple[int, float]]:
"""Returns a sequence of tuple pairs with the first item being a
number of Cliffords and the second item being the corresponding average
ground state probability.
"""
return [(num, prob) for num, prob in zip(self._num_cfds_seq,
... | def data(self) -> Sequence[Tuple[int, float]]:
"""Returns a sequence of tuple pairs with the first item being a
number of Cliffords and the second item being the corresponding average
ground state probability.
"""
return [(num, prob) for num, prob in zip(self._num_cfds_seq,
... | [
"Returns",
"a",
"sequence",
"of",
"tuple",
"pairs",
"with",
"the",
"first",
"item",
"being",
"a",
"number",
"of",
"Cliffords",
"and",
"the",
"second",
"item",
"being",
"the",
"corresponding",
"average",
"ground",
"state",
"probability",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/experiments/qubit_characterizations.py#L74-L80 | [
"def",
"data",
"(",
"self",
")",
"->",
"Sequence",
"[",
"Tuple",
"[",
"int",
",",
"float",
"]",
"]",
":",
"return",
"[",
"(",
"num",
",",
"prob",
")",
"for",
"num",
",",
"prob",
"in",
"zip",
"(",
"self",
".",
"_num_cfds_seq",
",",
"self",
".",
... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | RandomizedBenchMarkResult.plot | Plots the average ground state probability vs the number of
Cliffords in the RB study.
Args:
**plot_kwargs: Arguments to be passed to matplotlib.pyplot.plot. | cirq/experiments/qubit_characterizations.py | def plot(self, **plot_kwargs: Any) -> None:
"""Plots the average ground state probability vs the number of
Cliffords in the RB study.
Args:
**plot_kwargs: Arguments to be passed to matplotlib.pyplot.plot.
"""
fig = plt.figure()
plt.plot(self._num_cfds_seq, se... | def plot(self, **plot_kwargs: Any) -> None:
"""Plots the average ground state probability vs the number of
Cliffords in the RB study.
Args:
**plot_kwargs: Arguments to be passed to matplotlib.pyplot.plot.
"""
fig = plt.figure()
plt.plot(self._num_cfds_seq, se... | [
"Plots",
"the",
"average",
"ground",
"state",
"probability",
"vs",
"the",
"number",
"of",
"Cliffords",
"in",
"the",
"RB",
"study",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/experiments/qubit_characterizations.py#L82-L94 | [
"def",
"plot",
"(",
"self",
",",
"*",
"*",
"plot_kwargs",
":",
"Any",
")",
"->",
"None",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
")",
"plt",
".",
"plot",
"(",
"self",
".",
"_num_cfds_seq",
",",
"self",
".",
"_gnd_state_probs",
",",
"'ro-'",
","... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | reflection_matrix_pow | Raises a matrix with two opposing eigenvalues to a power.
Args:
reflection_matrix: The matrix to raise to a power.
exponent: The power to raise the matrix to.
Returns:
The given matrix raised to the given power. | cirq/linalg/transformations.py | def reflection_matrix_pow(reflection_matrix: np.ndarray, exponent: float):
"""Raises a matrix with two opposing eigenvalues to a power.
Args:
reflection_matrix: The matrix to raise to a power.
exponent: The power to raise the matrix to.
Returns:
The given matrix raised to the given... | def reflection_matrix_pow(reflection_matrix: np.ndarray, exponent: float):
"""Raises a matrix with two opposing eigenvalues to a power.
Args:
reflection_matrix: The matrix to raise to a power.
exponent: The power to raise the matrix to.
Returns:
The given matrix raised to the given... | [
"Raises",
"a",
"matrix",
"with",
"two",
"opposing",
"eigenvalues",
"to",
"a",
"power",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/linalg/transformations.py#L22-L48 | [
"def",
"reflection_matrix_pow",
"(",
"reflection_matrix",
":",
"np",
".",
"ndarray",
",",
"exponent",
":",
"float",
")",
":",
"# The eigenvalues are x and -x for some complex unit x. Determine x.",
"squared_phase",
"=",
"np",
".",
"dot",
"(",
"reflection_matrix",
"[",
"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | match_global_phase | Phases the given matrices so that they agree on the phase of one entry.
To maximize precision, the position with the largest entry from one of the
matrices is used when attempting to compute the phase difference between
the two matrices.
Args:
a: A numpy array.
b: Another numpy array.
... | cirq/linalg/transformations.py | def match_global_phase(a: np.ndarray,
b: np.ndarray
) -> Tuple[np.ndarray, np.ndarray]:
"""Phases the given matrices so that they agree on the phase of one entry.
To maximize precision, the position with the largest entry from one of the
matrices is used when a... | def match_global_phase(a: np.ndarray,
b: np.ndarray
) -> Tuple[np.ndarray, np.ndarray]:
"""Phases the given matrices so that they agree on the phase of one entry.
To maximize precision, the position with the largest entry from one of the
matrices is used when a... | [
"Phases",
"the",
"given",
"matrices",
"so",
"that",
"they",
"agree",
"on",
"the",
"phase",
"of",
"one",
"entry",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/linalg/transformations.py#L51-L88 | [
"def",
"match_global_phase",
"(",
"a",
":",
"np",
".",
"ndarray",
",",
"b",
":",
"np",
".",
"ndarray",
")",
"->",
"Tuple",
"[",
"np",
".",
"ndarray",
",",
"np",
".",
"ndarray",
"]",
":",
"# Not much point when they have different shapes.",
"if",
"a",
".",
... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | targeted_left_multiply | Left-multiplies the given axes of the target tensor by the given matrix.
Note that the matrix must have a compatible tensor structure.
For example, if you have an 6-qubit state vector `input_state` with shape
(2, 2, 2, 2, 2, 2), and a 2-qubit unitary operation `op` with shape
(2, 2, 2, 2), and you wan... | cirq/linalg/transformations.py | def targeted_left_multiply(left_matrix: np.ndarray,
right_target: np.ndarray,
target_axes: Sequence[int],
out: Optional[np.ndarray] = None
) -> np.ndarray:
"""Left-multiplies the given axes of the target tens... | def targeted_left_multiply(left_matrix: np.ndarray,
right_target: np.ndarray,
target_axes: Sequence[int],
out: Optional[np.ndarray] = None
) -> np.ndarray:
"""Left-multiplies the given axes of the target tens... | [
"Left",
"-",
"multiplies",
"the",
"given",
"axes",
"of",
"the",
"target",
"tensor",
"by",
"the",
"given",
"matrix",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/linalg/transformations.py#L91-L149 | [
"def",
"targeted_left_multiply",
"(",
"left_matrix",
":",
"np",
".",
"ndarray",
",",
"right_target",
":",
"np",
".",
"ndarray",
",",
"target_axes",
":",
"Sequence",
"[",
"int",
"]",
",",
"out",
":",
"Optional",
"[",
"np",
".",
"ndarray",
"]",
"=",
"None"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | targeted_conjugate_about | r"""Conjugates the given tensor about the target tensor.
This method computes a target tensor conjugated by another tensor.
Here conjugate is used in the sense of conjugating by a matrix, i.a.
A conjugated about B is $A B A^\dagger$ where $\dagger$ represents the
conjugate transpose.
Abstractly th... | cirq/linalg/transformations.py | def targeted_conjugate_about(tensor: np.ndarray,
target: np.ndarray,
indices: Sequence[int],
conj_indices: Sequence[int] = None,
buffer: Optional[np.ndarray] = None,
out: Opti... | def targeted_conjugate_about(tensor: np.ndarray,
target: np.ndarray,
indices: Sequence[int],
conj_indices: Sequence[int] = None,
buffer: Optional[np.ndarray] = None,
out: Opti... | [
"r",
"Conjugates",
"the",
"given",
"tensor",
"about",
"the",
"target",
"tensor",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/linalg/transformations.py#L152-L201 | [
"def",
"targeted_conjugate_about",
"(",
"tensor",
":",
"np",
".",
"ndarray",
",",
"target",
":",
"np",
".",
"ndarray",
",",
"indices",
":",
"Sequence",
"[",
"int",
"]",
",",
"conj_indices",
":",
"Sequence",
"[",
"int",
"]",
"=",
"None",
",",
"buffer",
... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | apply_matrix_to_slices | Left-multiplies an NxN matrix onto N slices of a numpy array.
Example:
The 4x4 matrix of a fractional SWAP gate can be expressed as
[ 1 ]
[ X**t ]
[ 1 ]
Where X is the 2x2 Pauli X gate and t is the power of the swap with t=1
being a full swa... | cirq/linalg/transformations.py | def apply_matrix_to_slices(
target: np.ndarray,
matrix: np.ndarray,
slices: List[_TSlice],
*,
out: Optional[np.ndarray] = None) -> np.ndarray:
"""Left-multiplies an NxN matrix onto N slices of a numpy array.
Example:
The 4x4 matrix of a fractional SWAP gate can b... | def apply_matrix_to_slices(
target: np.ndarray,
matrix: np.ndarray,
slices: List[_TSlice],
*,
out: Optional[np.ndarray] = None) -> np.ndarray:
"""Left-multiplies an NxN matrix onto N slices of a numpy array.
Example:
The 4x4 matrix of a fractional SWAP gate can b... | [
"Left",
"-",
"multiplies",
"an",
"NxN",
"matrix",
"onto",
"N",
"slices",
"of",
"a",
"numpy",
"array",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/linalg/transformations.py#L208-L271 | [
"def",
"apply_matrix_to_slices",
"(",
"target",
":",
"np",
".",
"ndarray",
",",
"matrix",
":",
"np",
".",
"ndarray",
",",
"slices",
":",
"List",
"[",
"_TSlice",
"]",
",",
"*",
",",
"out",
":",
"Optional",
"[",
"np",
".",
"ndarray",
"]",
"=",
"None",
... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | partial_trace | Takes the partial trace of a given tensor.
The input tensor must have shape `(d_0, ..., d_{k-1}, d_0, ..., d_{k-1})`.
The trace is done over all indices that are not in keep_indices. The
resulting tensor has shape `(d_{i_0}, ..., d_{i_r}, d_{i_0}, ..., d_{i_r})`
where `i_j` is the `j`th element of `kee... | cirq/linalg/transformations.py | def partial_trace(tensor: np.ndarray,
keep_indices: List[int]) -> np.ndarray:
"""Takes the partial trace of a given tensor.
The input tensor must have shape `(d_0, ..., d_{k-1}, d_0, ..., d_{k-1})`.
The trace is done over all indices that are not in keep_indices. The
resulting tensor ... | def partial_trace(tensor: np.ndarray,
keep_indices: List[int]) -> np.ndarray:
"""Takes the partial trace of a given tensor.
The input tensor must have shape `(d_0, ..., d_{k-1}, d_0, ..., d_{k-1})`.
The trace is done over all indices that are not in keep_indices. The
resulting tensor ... | [
"Takes",
"the",
"partial",
"trace",
"of",
"a",
"given",
"tensor",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/linalg/transformations.py#L274-L306 | [
"def",
"partial_trace",
"(",
"tensor",
":",
"np",
".",
"ndarray",
",",
"keep_indices",
":",
"List",
"[",
"int",
"]",
")",
"->",
"np",
".",
"ndarray",
":",
"ndim",
"=",
"tensor",
".",
"ndim",
"//",
"2",
"if",
"not",
"all",
"(",
"tensor",
".",
"shape... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | mul | Returns lhs * rhs, or else a default if the operator is not implemented.
This method is mostly used by __pow__ methods trying to return
NotImplemented instead of causing a TypeError.
Args:
lhs: Left hand side of the multiplication.
rhs: Right hand side of the multiplication.
defaul... | cirq/protocols/mul.py | def mul(lhs: Any, rhs: Any, default: Any = RaiseTypeErrorIfNotProvided) -> Any:
"""Returns lhs * rhs, or else a default if the operator is not implemented.
This method is mostly used by __pow__ methods trying to return
NotImplemented instead of causing a TypeError.
Args:
lhs: Left hand side of... | def mul(lhs: Any, rhs: Any, default: Any = RaiseTypeErrorIfNotProvided) -> Any:
"""Returns lhs * rhs, or else a default if the operator is not implemented.
This method is mostly used by __pow__ methods trying to return
NotImplemented instead of causing a TypeError.
Args:
lhs: Left hand side of... | [
"Returns",
"lhs",
"*",
"rhs",
"or",
"else",
"a",
"default",
"if",
"the",
"operator",
"is",
"not",
"implemented",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/protocols/mul.py#L24-L72 | [
"def",
"mul",
"(",
"lhs",
":",
"Any",
",",
"rhs",
":",
"Any",
",",
"default",
":",
"Any",
"=",
"RaiseTypeErrorIfNotProvided",
")",
"->",
"Any",
":",
"# Use left-hand-side's __mul__.",
"left_mul",
"=",
"getattr",
"(",
"lhs",
",",
"'__mul__'",
",",
"None",
"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | is_diagonal | Determines if a matrix is a approximately diagonal.
A matrix is diagonal if i!=j implies m[i,j]==0.
Args:
matrix: The matrix to check.
atol: The per-matrix-entry absolute tolerance on equality.
Returns:
Whether the matrix is diagonal within the given tolerance. | cirq/linalg/predicates.py | def is_diagonal(matrix: np.ndarray, *, atol: float = 1e-8) -> bool:
"""Determines if a matrix is a approximately diagonal.
A matrix is diagonal if i!=j implies m[i,j]==0.
Args:
matrix: The matrix to check.
atol: The per-matrix-entry absolute tolerance on equality.
Returns:
Whe... | def is_diagonal(matrix: np.ndarray, *, atol: float = 1e-8) -> bool:
"""Determines if a matrix is a approximately diagonal.
A matrix is diagonal if i!=j implies m[i,j]==0.
Args:
matrix: The matrix to check.
atol: The per-matrix-entry absolute tolerance on equality.
Returns:
Whe... | [
"Determines",
"if",
"a",
"matrix",
"is",
"a",
"approximately",
"diagonal",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/linalg/predicates.py#L27-L42 | [
"def",
"is_diagonal",
"(",
"matrix",
":",
"np",
".",
"ndarray",
",",
"*",
",",
"atol",
":",
"float",
"=",
"1e-8",
")",
"->",
"bool",
":",
"matrix",
"=",
"np",
".",
"copy",
"(",
"matrix",
")",
"for",
"i",
"in",
"range",
"(",
"min",
"(",
"matrix",
... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | is_hermitian | Determines if a matrix is approximately Hermitian.
A matrix is Hermitian if it's square and equal to its adjoint.
Args:
matrix: The matrix to check.
rtol: The per-matrix-entry relative tolerance on equality.
atol: The per-matrix-entry absolute tolerance on equality.
Returns:
... | cirq/linalg/predicates.py | def is_hermitian(
matrix: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8) -> bool:
"""Determines if a matrix is approximately Hermitian.
A matrix is Hermitian if it's square and equal to its adjoint.
Args:
matrix: The matrix to check.
rtol: The per-ma... | def is_hermitian(
matrix: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8) -> bool:
"""Determines if a matrix is approximately Hermitian.
A matrix is Hermitian if it's square and equal to its adjoint.
Args:
matrix: The matrix to check.
rtol: The per-ma... | [
"Determines",
"if",
"a",
"matrix",
"is",
"approximately",
"Hermitian",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/linalg/predicates.py#L45-L63 | [
"def",
"is_hermitian",
"(",
"matrix",
":",
"np",
".",
"ndarray",
",",
"*",
",",
"rtol",
":",
"float",
"=",
"1e-5",
",",
"atol",
":",
"float",
"=",
"1e-8",
")",
"->",
"bool",
":",
"return",
"(",
"matrix",
".",
"shape",
"[",
"0",
"]",
"==",
"matrix... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | is_orthogonal | Determines if a matrix is approximately orthogonal.
A matrix is orthogonal if it's square and real and its transpose is its
inverse.
Args:
matrix: The matrix to check.
rtol: The per-matrix-entry relative tolerance on equality.
atol: The per-matrix-entry absolute tolerance on equali... | cirq/linalg/predicates.py | def is_orthogonal(
matrix: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8) -> bool:
"""Determines if a matrix is approximately orthogonal.
A matrix is orthogonal if it's square and real and its transpose is its
inverse.
Args:
matrix: The matrix to check.
... | def is_orthogonal(
matrix: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8) -> bool:
"""Determines if a matrix is approximately orthogonal.
A matrix is orthogonal if it's square and real and its transpose is its
inverse.
Args:
matrix: The matrix to check.
... | [
"Determines",
"if",
"a",
"matrix",
"is",
"approximately",
"orthogonal",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/linalg/predicates.py#L66-L88 | [
"def",
"is_orthogonal",
"(",
"matrix",
":",
"np",
".",
"ndarray",
",",
"*",
",",
"rtol",
":",
"float",
"=",
"1e-5",
",",
"atol",
":",
"float",
"=",
"1e-8",
")",
"->",
"bool",
":",
"return",
"(",
"matrix",
".",
"shape",
"[",
"0",
"]",
"==",
"matri... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | is_special_orthogonal | Determines if a matrix is approximately special orthogonal.
A matrix is special orthogonal if it is square and real and its transpose
is its inverse and its determinant is one.
Args:
matrix: The matrix to check.
rtol: The per-matrix-entry relative tolerance on equality.
atol: The p... | cirq/linalg/predicates.py | def is_special_orthogonal(
matrix: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8) -> bool:
"""Determines if a matrix is approximately special orthogonal.
A matrix is special orthogonal if it is square and real and its transpose
is its inverse and its determinant is o... | def is_special_orthogonal(
matrix: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8) -> bool:
"""Determines if a matrix is approximately special orthogonal.
A matrix is special orthogonal if it is square and real and its transpose
is its inverse and its determinant is o... | [
"Determines",
"if",
"a",
"matrix",
"is",
"approximately",
"special",
"orthogonal",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/linalg/predicates.py#L91-L111 | [
"def",
"is_special_orthogonal",
"(",
"matrix",
":",
"np",
".",
"ndarray",
",",
"*",
",",
"rtol",
":",
"float",
"=",
"1e-5",
",",
"atol",
":",
"float",
"=",
"1e-8",
")",
"->",
"bool",
":",
"return",
"(",
"is_orthogonal",
"(",
"matrix",
",",
"rtol",
"=... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | is_unitary | Determines if a matrix is approximately unitary.
A matrix is unitary if it's square and its adjoint is its inverse.
Args:
matrix: The matrix to check.
rtol: The per-matrix-entry relative tolerance on equality.
atol: The per-matrix-entry absolute tolerance on equality.
Returns:
... | cirq/linalg/predicates.py | def is_unitary(
matrix: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8) -> bool:
"""Determines if a matrix is approximately unitary.
A matrix is unitary if it's square and its adjoint is its inverse.
Args:
matrix: The matrix to check.
rtol: The per-ma... | def is_unitary(
matrix: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8) -> bool:
"""Determines if a matrix is approximately unitary.
A matrix is unitary if it's square and its adjoint is its inverse.
Args:
matrix: The matrix to check.
rtol: The per-ma... | [
"Determines",
"if",
"a",
"matrix",
"is",
"approximately",
"unitary",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/linalg/predicates.py#L114-L134 | [
"def",
"is_unitary",
"(",
"matrix",
":",
"np",
".",
"ndarray",
",",
"*",
",",
"rtol",
":",
"float",
"=",
"1e-5",
",",
"atol",
":",
"float",
"=",
"1e-8",
")",
"->",
"bool",
":",
"return",
"(",
"matrix",
".",
"shape",
"[",
"0",
"]",
"==",
"matrix",... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | is_special_unitary | Determines if a matrix is approximately unitary with unit determinant.
A matrix is special-unitary if it is square and its adjoint is its inverse
and its determinant is one.
Args:
matrix: The matrix to check.
rtol: The per-matrix-entry relative tolerance on equality.
atol: The per-... | cirq/linalg/predicates.py | def is_special_unitary(
matrix: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8) -> bool:
"""Determines if a matrix is approximately unitary with unit determinant.
A matrix is special-unitary if it is square and its adjoint is its inverse
and its determinant is one.
... | def is_special_unitary(
matrix: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8) -> bool:
"""Determines if a matrix is approximately unitary with unit determinant.
A matrix is special-unitary if it is square and its adjoint is its inverse
and its determinant is one.
... | [
"Determines",
"if",
"a",
"matrix",
"is",
"approximately",
"unitary",
"with",
"unit",
"determinant",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/linalg/predicates.py#L137-L157 | [
"def",
"is_special_unitary",
"(",
"matrix",
":",
"np",
".",
"ndarray",
",",
"*",
",",
"rtol",
":",
"float",
"=",
"1e-5",
",",
"atol",
":",
"float",
"=",
"1e-8",
")",
"->",
"bool",
":",
"return",
"(",
"is_unitary",
"(",
"matrix",
",",
"rtol",
"=",
"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | commutes | Determines if two matrices approximately commute.
Two matrices A and B commute if they are square and have the same size and
AB = BA.
Args:
m1: One of the matrices.
m2: The other matrix.
rtol: The per-matrix-entry relative tolerance on equality.
atol: The per-matrix-entry a... | cirq/linalg/predicates.py | def commutes(
m1: np.ndarray,
m2: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8) -> bool:
"""Determines if two matrices approximately commute.
Two matrices A and B commute if they are square and have the same size and
AB = BA.
Args:
m1: One of th... | def commutes(
m1: np.ndarray,
m2: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8) -> bool:
"""Determines if two matrices approximately commute.
Two matrices A and B commute if they are square and have the same size and
AB = BA.
Args:
m1: One of th... | [
"Determines",
"if",
"two",
"matrices",
"approximately",
"commute",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/linalg/predicates.py#L160-L183 | [
"def",
"commutes",
"(",
"m1",
":",
"np",
".",
"ndarray",
",",
"m2",
":",
"np",
".",
"ndarray",
",",
"*",
",",
"rtol",
":",
"float",
"=",
"1e-5",
",",
"atol",
":",
"float",
"=",
"1e-8",
")",
"->",
"bool",
":",
"return",
"(",
"m1",
".",
"shape",
... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | allclose_up_to_global_phase | Determines if a ~= b * exp(i t) for some t.
Args:
a: A numpy array.
b: Another numpy array.
rtol: Relative error tolerance.
atol: Absolute error tolerance.
equal_nan: Whether or not NaN entries should be considered equal to
other NaN entries. | cirq/linalg/predicates.py | def allclose_up_to_global_phase(
a: np.ndarray,
b: np.ndarray,
*,
rtol: float = 1.e-5,
atol: float = 1.e-8,
equal_nan: bool = False
) -> bool:
"""Determines if a ~= b * exp(i t) for some t.
Args:
a: A numpy array.
b: Another numpy array.
r... | def allclose_up_to_global_phase(
a: np.ndarray,
b: np.ndarray,
*,
rtol: float = 1.e-5,
atol: float = 1.e-8,
equal_nan: bool = False
) -> bool:
"""Determines if a ~= b * exp(i t) for some t.
Args:
a: A numpy array.
b: Another numpy array.
r... | [
"Determines",
"if",
"a",
"~",
"=",
"b",
"*",
"exp",
"(",
"i",
"t",
")",
"for",
"some",
"t",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/linalg/predicates.py#L186-L208 | [
"def",
"allclose_up_to_global_phase",
"(",
"a",
":",
"np",
".",
"ndarray",
",",
"b",
":",
"np",
".",
"ndarray",
",",
"*",
",",
"rtol",
":",
"float",
"=",
"1.e-5",
",",
"atol",
":",
"float",
"=",
"1.e-8",
",",
"equal_nan",
":",
"bool",
"=",
"False",
... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | slice_for_qubits_equal_to | Returns an index corresponding to a desired subset of an np.ndarray.
It is assumed that the np.ndarray's shape is of the form (2, 2, 2, ..., 2).
Example:
```python
# A '4 qubit' tensor with values from 0 to 15.
r = np.array(range(16)).reshape((2,) * 4)
# We want to index into... | cirq/linalg/predicates.py | def slice_for_qubits_equal_to(target_qubit_axes: Sequence[int],
little_endian_qureg_value: int,
*, # Forces keyword args.
num_qubits: int = None
) -> Tuple[Union[slice, int, 'ellipsis'], ...]:
""... | def slice_for_qubits_equal_to(target_qubit_axes: Sequence[int],
little_endian_qureg_value: int,
*, # Forces keyword args.
num_qubits: int = None
) -> Tuple[Union[slice, int, 'ellipsis'], ...]:
""... | [
"Returns",
"an",
"index",
"corresponding",
"to",
"a",
"desired",
"subset",
"of",
"an",
"np",
".",
"ndarray",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/linalg/predicates.py#L211-L263 | [
"def",
"slice_for_qubits_equal_to",
"(",
"target_qubit_axes",
":",
"Sequence",
"[",
"int",
"]",
",",
"little_endian_qureg_value",
":",
"int",
",",
"*",
",",
"# Forces keyword args.",
"num_qubits",
":",
"int",
"=",
"None",
")",
"->",
"Tuple",
"[",
"Union",
"[",
... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | ScheduledOperation.op_at_on | Creates a scheduled operation with a device-determined duration. | cirq/schedules/scheduled_operation.py | def op_at_on(operation: ops.Operation,
time: Timestamp,
device: Device):
"""Creates a scheduled operation with a device-determined duration."""
return ScheduledOperation(time,
device.duration_of(operation),
... | def op_at_on(operation: ops.Operation,
time: Timestamp,
device: Device):
"""Creates a scheduled operation with a device-determined duration."""
return ScheduledOperation(time,
device.duration_of(operation),
... | [
"Creates",
"a",
"scheduled",
"operation",
"with",
"a",
"device",
"-",
"determined",
"duration",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/schedules/scheduled_operation.py#L40-L46 | [
"def",
"op_at_on",
"(",
"operation",
":",
"ops",
".",
"Operation",
",",
"time",
":",
"Timestamp",
",",
"device",
":",
"Device",
")",
":",
"return",
"ScheduledOperation",
"(",
"time",
",",
"device",
".",
"duration_of",
"(",
"operation",
")",
",",
"operation... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | LinearCombinationOfGates.num_qubits | Returns number of qubits in the domain if known, None if unknown. | cirq/ops/linear_combinations.py | def num_qubits(self) -> Optional[int]:
"""Returns number of qubits in the domain if known, None if unknown."""
if not self:
return None
any_gate = next(iter(self))
return any_gate.num_qubits() | def num_qubits(self) -> Optional[int]:
"""Returns number of qubits in the domain if known, None if unknown."""
if not self:
return None
any_gate = next(iter(self))
return any_gate.num_qubits() | [
"Returns",
"number",
"of",
"qubits",
"in",
"the",
"domain",
"if",
"known",
"None",
"if",
"unknown",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/ops/linear_combinations.py#L55-L60 | [
"def",
"num_qubits",
"(",
"self",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"if",
"not",
"self",
":",
"return",
"None",
"any_gate",
"=",
"next",
"(",
"iter",
"(",
"self",
")",
")",
"return",
"any_gate",
".",
"num_qubits",
"(",
")"
] | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | LinearCombinationOfGates.matrix | Reconstructs matrix of self using unitaries of underlying gates.
Raises:
TypeError: if any of the gates in self does not provide a unitary. | cirq/ops/linear_combinations.py | def matrix(self) -> np.ndarray:
"""Reconstructs matrix of self using unitaries of underlying gates.
Raises:
TypeError: if any of the gates in self does not provide a unitary.
"""
num_qubits = self.num_qubits()
if num_qubits is None:
raise ValueError('Unkn... | def matrix(self) -> np.ndarray:
"""Reconstructs matrix of self using unitaries of underlying gates.
Raises:
TypeError: if any of the gates in self does not provide a unitary.
"""
num_qubits = self.num_qubits()
if num_qubits is None:
raise ValueError('Unkn... | [
"Reconstructs",
"matrix",
"of",
"self",
"using",
"unitaries",
"of",
"underlying",
"gates",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/ops/linear_combinations.py#L94-L107 | [
"def",
"matrix",
"(",
"self",
")",
"->",
"np",
".",
"ndarray",
":",
"num_qubits",
"=",
"self",
".",
"num_qubits",
"(",
")",
"if",
"num_qubits",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Unknown number of qubits'",
")",
"num_dim",
"=",
"2",
"**",
"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | box_draw_character | Finds a box drawing character based on its connectivity.
For example:
box_draw_character(
NORMAL_BOX_CHARS,
BOLD_BOX_CHARS,
top=-1,
right=+1)
evaluates to '┕', which has a normal upward leg and bold rightward leg.
Args:
first: The character... | cirq/circuits/_box_drawing_character_data.py | def box_draw_character(first: Optional[BoxDrawCharacterSet],
second: BoxDrawCharacterSet,
*,
top: int = 0,
bottom: int = 0,
left: int = 0,
right: int = 0) -> Optional[str]:
"""Fi... | def box_draw_character(first: Optional[BoxDrawCharacterSet],
second: BoxDrawCharacterSet,
*,
top: int = 0,
bottom: int = 0,
left: int = 0,
right: int = 0) -> Optional[str]:
"""Fi... | [
"Finds",
"a",
"box",
"drawing",
"character",
"based",
"on",
"its",
"connectivity",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/circuits/_box_drawing_character_data.py#L329-L383 | [
"def",
"box_draw_character",
"(",
"first",
":",
"Optional",
"[",
"BoxDrawCharacterSet",
"]",
",",
"second",
":",
"BoxDrawCharacterSet",
",",
"*",
",",
"top",
":",
"int",
"=",
"0",
",",
"bottom",
":",
"int",
"=",
"0",
",",
"left",
":",
"int",
"=",
"0",
... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | Pauli.on | Returns an application of this gate to the given qubits.
Args:
*qubits: The collection of qubits to potentially apply the gate to. | cirq/ops/pauli_gates.py | def on(self,
*qubits: raw_types.Qid) -> 'SingleQubitPauliStringGateOperation':
"""Returns an application of this gate to the given qubits.
Args:
*qubits: The collection of qubits to potentially apply the gate to.
"""
if len(qubits) != 1:
raise ValueErr... | def on(self,
*qubits: raw_types.Qid) -> 'SingleQubitPauliStringGateOperation':
"""Returns an application of this gate to the given qubits.
Args:
*qubits: The collection of qubits to potentially apply the gate to.
"""
if len(qubits) != 1:
raise ValueErr... | [
"Returns",
"an",
"application",
"of",
"this",
"gate",
"to",
"the",
"given",
"qubits",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/ops/pauli_gates.py#L72-L83 | [
"def",
"on",
"(",
"self",
",",
"*",
"qubits",
":",
"raw_types",
".",
"Qid",
")",
"->",
"'SingleQubitPauliStringGateOperation'",
":",
"if",
"len",
"(",
"qubits",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"'Expected a single qubit, got <{!r}>.'",
".",
"fo... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | decompose | Recursively decomposes a value into `cirq.Operation`s meeting a criteria.
Args:
val: The value to decompose into operations.
intercepting_decomposer: An optional method that is called before the
default decomposer (the value's `_decompose_` method). If
`intercepting_decompos... | cirq/protocols/decompose.py | def decompose(
val: TValue,
*,
intercepting_decomposer: Callable[['cirq.Operation'],
Union[None,
NotImplementedType,
'cirq.OP_TREE']] = None,
fallback_decomposer: Callable[['cirq... | def decompose(
val: TValue,
*,
intercepting_decomposer: Callable[['cirq.Operation'],
Union[None,
NotImplementedType,
'cirq.OP_TREE']] = None,
fallback_decomposer: Callable[['cirq... | [
"Recursively",
"decomposes",
"a",
"value",
"into",
"cirq",
".",
"Operation",
"s",
"meeting",
"a",
"criteria",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/protocols/decompose.py#L155-L270 | [
"def",
"decompose",
"(",
"val",
":",
"TValue",
",",
"*",
",",
"intercepting_decomposer",
":",
"Callable",
"[",
"[",
"'cirq.Operation'",
"]",
",",
"Union",
"[",
"None",
",",
"NotImplementedType",
",",
"'cirq.OP_TREE'",
"]",
"]",
"=",
"None",
",",
"fallback_de... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | decompose_once | Decomposes a value into operations, if possible.
This method decomposes the value exactly once, instead of decomposing it
and then continuing to decomposing the decomposed operations recursively
until some criteria is met (which is what `cirq.decompose` does).
Args:
val: The value to call `_de... | cirq/protocols/decompose.py | def decompose_once(val: Any,
default=RaiseTypeErrorIfNotProvided,
**kwargs):
"""Decomposes a value into operations, if possible.
This method decomposes the value exactly once, instead of decomposing it
and then continuing to decomposing the decomposed operations recurs... | def decompose_once(val: Any,
default=RaiseTypeErrorIfNotProvided,
**kwargs):
"""Decomposes a value into operations, if possible.
This method decomposes the value exactly once, instead of decomposing it
and then continuing to decomposing the decomposed operations recurs... | [
"Decomposes",
"a",
"value",
"into",
"operations",
"if",
"possible",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/protocols/decompose.py#L286-L327 | [
"def",
"decompose_once",
"(",
"val",
":",
"Any",
",",
"default",
"=",
"RaiseTypeErrorIfNotProvided",
",",
"*",
"*",
"kwargs",
")",
":",
"method",
"=",
"getattr",
"(",
"val",
",",
"'_decompose_'",
",",
"None",
")",
"decomposed",
"=",
"NotImplemented",
"if",
... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | decompose_once_with_qubits | Decomposes a value into operations on the given qubits.
This method is used when decomposing gates, which don't know which qubits
they are being applied to unless told. It decomposes the gate exactly once,
instead of decomposing it and then continuing to decomposing the decomposed
operations recursivel... | cirq/protocols/decompose.py | def decompose_once_with_qubits(val: Any,
qubits: Iterable['cirq.Qid'],
default=RaiseTypeErrorIfNotProvided):
"""Decomposes a value into operations on the given qubits.
This method is used when decomposing gates, which don't know which qubits
the... | def decompose_once_with_qubits(val: Any,
qubits: Iterable['cirq.Qid'],
default=RaiseTypeErrorIfNotProvided):
"""Decomposes a value into operations on the given qubits.
This method is used when decomposing gates, which don't know which qubits
the... | [
"Decomposes",
"a",
"value",
"into",
"operations",
"on",
"the",
"given",
"qubits",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/protocols/decompose.py#L348-L376 | [
"def",
"decompose_once_with_qubits",
"(",
"val",
":",
"Any",
",",
"qubits",
":",
"Iterable",
"[",
"'cirq.Qid'",
"]",
",",
"default",
"=",
"RaiseTypeErrorIfNotProvided",
")",
":",
"return",
"decompose_once",
"(",
"val",
",",
"default",
",",
"qubits",
"=",
"tupl... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | QubitOrder.explicit | A basis that contains exactly the given qubits in the given order.
Args:
fixed_qubits: The qubits in basis order.
fallback: A fallback order to use for extra qubits not in the
fixed_qubits list. Extra qubits will always come after the
fixed_qubits, but wi... | cirq/ops/qubit_order.py | def explicit(fixed_qubits: Iterable[raw_types.Qid],
fallback: Optional['QubitOrder']=None) -> 'QubitOrder':
"""A basis that contains exactly the given qubits in the given order.
Args:
fixed_qubits: The qubits in basis order.
fallback: A fallback order to use for... | def explicit(fixed_qubits: Iterable[raw_types.Qid],
fallback: Optional['QubitOrder']=None) -> 'QubitOrder':
"""A basis that contains exactly the given qubits in the given order.
Args:
fixed_qubits: The qubits in basis order.
fallback: A fallback order to use for... | [
"A",
"basis",
"that",
"contains",
"exactly",
"the",
"given",
"qubits",
"in",
"the",
"given",
"order",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/ops/qubit_order.py#L56-L85 | [
"def",
"explicit",
"(",
"fixed_qubits",
":",
"Iterable",
"[",
"raw_types",
".",
"Qid",
"]",
",",
"fallback",
":",
"Optional",
"[",
"'QubitOrder'",
"]",
"=",
"None",
")",
"->",
"'QubitOrder'",
":",
"result",
"=",
"tuple",
"(",
"fixed_qubits",
")",
"if",
"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | QubitOrder.sorted_by | A basis that orders qubits ascending based on a key function.
Args:
key: A function that takes a qubit and returns a key value. The
basis will be ordered ascending according to these key values.
Returns:
A basis that orders qubits ascending based on a key funct... | cirq/ops/qubit_order.py | def sorted_by(key: Callable[[raw_types.Qid], Any]) -> 'QubitOrder':
"""A basis that orders qubits ascending based on a key function.
Args:
key: A function that takes a qubit and returns a key value. The
basis will be ordered ascending according to these key values.
... | def sorted_by(key: Callable[[raw_types.Qid], Any]) -> 'QubitOrder':
"""A basis that orders qubits ascending based on a key function.
Args:
key: A function that takes a qubit and returns a key value. The
basis will be ordered ascending according to these key values.
... | [
"A",
"basis",
"that",
"orders",
"qubits",
"ascending",
"based",
"on",
"a",
"key",
"function",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/ops/qubit_order.py#L88-L99 | [
"def",
"sorted_by",
"(",
"key",
":",
"Callable",
"[",
"[",
"raw_types",
".",
"Qid",
"]",
",",
"Any",
"]",
")",
"->",
"'QubitOrder'",
":",
"return",
"QubitOrder",
"(",
"lambda",
"qubits",
":",
"tuple",
"(",
"sorted",
"(",
"qubits",
",",
"key",
"=",
"k... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | QubitOrder.order_for | Returns a qubit tuple ordered corresponding to the basis.
Args:
qubits: Qubits that should be included in the basis. (Additional
qubits may be added into the output by the basis.)
Returns:
A tuple of qubits in the same order that their single-qubit
m... | cirq/ops/qubit_order.py | def order_for(self, qubits: Iterable[raw_types.Qid]
) -> Tuple[raw_types.Qid, ...]:
"""Returns a qubit tuple ordered corresponding to the basis.
Args:
qubits: Qubits that should be included in the basis. (Additional
qubits may be added into the output by th... | def order_for(self, qubits: Iterable[raw_types.Qid]
) -> Tuple[raw_types.Qid, ...]:
"""Returns a qubit tuple ordered corresponding to the basis.
Args:
qubits: Qubits that should be included in the basis. (Additional
qubits may be added into the output by th... | [
"Returns",
"a",
"qubit",
"tuple",
"ordered",
"corresponding",
"to",
"the",
"basis",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/ops/qubit_order.py#L101-L114 | [
"def",
"order_for",
"(",
"self",
",",
"qubits",
":",
"Iterable",
"[",
"raw_types",
".",
"Qid",
"]",
")",
"->",
"Tuple",
"[",
"raw_types",
".",
"Qid",
",",
"...",
"]",
":",
"return",
"self",
".",
"_explicit_func",
"(",
"qubits",
")"
] | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | QubitOrder.as_qubit_order | Converts a value into a basis.
Args:
val: An iterable or a basis.
Returns:
The basis implied by the value. | cirq/ops/qubit_order.py | def as_qubit_order(val: 'qubit_order_or_list.QubitOrderOrList'
) -> 'QubitOrder':
"""Converts a value into a basis.
Args:
val: An iterable or a basis.
Returns:
The basis implied by the value.
"""
if isinstance(val, collections.Iter... | def as_qubit_order(val: 'qubit_order_or_list.QubitOrderOrList'
) -> 'QubitOrder':
"""Converts a value into a basis.
Args:
val: An iterable or a basis.
Returns:
The basis implied by the value.
"""
if isinstance(val, collections.Iter... | [
"Converts",
"a",
"value",
"into",
"a",
"basis",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/ops/qubit_order.py#L117-L132 | [
"def",
"as_qubit_order",
"(",
"val",
":",
"'qubit_order_or_list.QubitOrderOrList'",
")",
"->",
"'QubitOrder'",
":",
"if",
"isinstance",
"(",
"val",
",",
"collections",
".",
"Iterable",
")",
":",
"return",
"QubitOrder",
".",
"explicit",
"(",
"val",
")",
"if",
"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | QubitOrder.map | Transforms the Basis so that it applies to wrapped qubits.
Args:
externalize: Converts an internal qubit understood by the underlying
basis into an external qubit understood by the caller.
internalize: Converts an external qubit understood by the caller
i... | cirq/ops/qubit_order.py | def map(self,
internalize: Callable[[TExternalQubit], TInternalQubit],
externalize: Callable[[TInternalQubit], TExternalQubit]
) -> 'QubitOrder':
"""Transforms the Basis so that it applies to wrapped qubits.
Args:
externalize: Converts an internal qubit u... | def map(self,
internalize: Callable[[TExternalQubit], TInternalQubit],
externalize: Callable[[TInternalQubit], TExternalQubit]
) -> 'QubitOrder':
"""Transforms the Basis so that it applies to wrapped qubits.
Args:
externalize: Converts an internal qubit u... | [
"Transforms",
"the",
"Basis",
"so",
"that",
"it",
"applies",
"to",
"wrapped",
"qubits",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/ops/qubit_order.py#L134-L157 | [
"def",
"map",
"(",
"self",
",",
"internalize",
":",
"Callable",
"[",
"[",
"TExternalQubit",
"]",
",",
"TInternalQubit",
"]",
",",
"externalize",
":",
"Callable",
"[",
"[",
"TInternalQubit",
"]",
",",
"TExternalQubit",
"]",
")",
"->",
"'QubitOrder'",
":",
"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | _pad_digits | A str method with hacks to support better lexicographic ordering.
The output strings are not intended to be human readable.
The returned string will have digit-runs zero-padded up to at least 8
digits. That way, instead of 'a10' coming before 'a2', 'a000010' will come
after 'a000002'.
Also, the o... | cirq/ops/named_qubit.py | def _pad_digits(text: str) -> str:
"""A str method with hacks to support better lexicographic ordering.
The output strings are not intended to be human readable.
The returned string will have digit-runs zero-padded up to at least 8
digits. That way, instead of 'a10' coming before 'a2', 'a000010' will ... | def _pad_digits(text: str) -> str:
"""A str method with hacks to support better lexicographic ordering.
The output strings are not intended to be human readable.
The returned string will have digit-runs zero-padded up to at least 8
digits. That way, instead of 'a10' coming before 'a2', 'a000010' will ... | [
"A",
"str",
"method",
"with",
"hacks",
"to",
"support",
"better",
"lexicographic",
"ordering",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/ops/named_qubit.py#L59-L90 | [
"def",
"_pad_digits",
"(",
"text",
":",
"str",
")",
"->",
"str",
":",
"was_on_digits",
"=",
"False",
"last_transition",
"=",
"0",
"chunks",
"=",
"[",
"]",
"def",
"handle_transition_at",
"(",
"k",
")",
":",
"chunk",
"=",
"text",
"[",
"last_transition",
":... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | NamedQubit.range | Returns a range of NamedQubits.
The range returned starts with the prefix, and followed by a qubit for
each number in the range, e.g.:
NamedQubit.range(3, prefix="a") -> ["a1", "a2", "a3]
NamedQubit.range(2, 4, prefix="a") -> ["a2", "a3]
Args:
*args: Args to be pas... | cirq/ops/named_qubit.py | def range(*args, prefix: str):
"""Returns a range of NamedQubits.
The range returned starts with the prefix, and followed by a qubit for
each number in the range, e.g.:
NamedQubit.range(3, prefix="a") -> ["a1", "a2", "a3]
NamedQubit.range(2, 4, prefix="a") -> ["a2", "a3]
... | def range(*args, prefix: str):
"""Returns a range of NamedQubits.
The range returned starts with the prefix, and followed by a qubit for
each number in the range, e.g.:
NamedQubit.range(3, prefix="a") -> ["a1", "a2", "a3]
NamedQubit.range(2, 4, prefix="a") -> ["a2", "a3]
... | [
"Returns",
"a",
"range",
"of",
"NamedQubits",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/ops/named_qubit.py#L40-L56 | [
"def",
"range",
"(",
"*",
"args",
",",
"prefix",
":",
"str",
")",
":",
"return",
"[",
"NamedQubit",
"(",
"prefix",
"+",
"str",
"(",
"i",
")",
")",
"for",
"i",
"in",
"range",
"(",
"*",
"args",
")",
"]"
] | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | channel | r"""Returns a list of matrices describing the channel for the given value.
These matrices are the terms in the operator sum representation of
a quantum channel. If the returned matrices are {A_0,A_1,..., A_{r-1}},
then this describes the channel:
\rho \rightarrow \sum_{k=0}^{r-1} A_0 \rho A_0^\dagg... | cirq/protocols/channel.py | def channel(val: Any,
default: Any = RaiseTypeErrorIfNotProvided
) -> Union[Tuple[np.ndarray], Sequence[TDefault]]:
r"""Returns a list of matrices describing the channel for the given value.
These matrices are the terms in the operator sum representation of
a quantum channel. If the... | def channel(val: Any,
default: Any = RaiseTypeErrorIfNotProvided
) -> Union[Tuple[np.ndarray], Sequence[TDefault]]:
r"""Returns a list of matrices describing the channel for the given value.
These matrices are the terms in the operator sum representation of
a quantum channel. If the... | [
"r",
"Returns",
"a",
"list",
"of",
"matrices",
"describing",
"the",
"channel",
"for",
"the",
"given",
"value",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/protocols/channel.py#L88-L150 | [
"def",
"channel",
"(",
"val",
":",
"Any",
",",
"default",
":",
"Any",
"=",
"RaiseTypeErrorIfNotProvided",
")",
"->",
"Union",
"[",
"Tuple",
"[",
"np",
".",
"ndarray",
"]",
",",
"Sequence",
"[",
"TDefault",
"]",
"]",
":",
"channel_getter",
"=",
"getattr",... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | has_channel | Returns whether the value has a channel representation.
Returns:
If `val` has a `_has_channel_` method and its result is not
NotImplemented, that result is returned. Otherwise, if `val` has a
`_has_mixture_` method and its result is not NotImplemented, that
result is returned. Other... | cirq/protocols/channel.py | def has_channel(val: Any) -> bool:
"""Returns whether the value has a channel representation.
Returns:
If `val` has a `_has_channel_` method and its result is not
NotImplemented, that result is returned. Otherwise, if `val` has a
`_has_mixture_` method and its result is not NotImplement... | def has_channel(val: Any) -> bool:
"""Returns whether the value has a channel representation.
Returns:
If `val` has a `_has_channel_` method and its result is not
NotImplemented, that result is returned. Otherwise, if `val` has a
`_has_mixture_` method and its result is not NotImplement... | [
"Returns",
"whether",
"the",
"value",
"has",
"a",
"channel",
"representation",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/protocols/channel.py#L153-L177 | [
"def",
"has_channel",
"(",
"val",
":",
"Any",
")",
"->",
"bool",
":",
"channel_getter",
"=",
"getattr",
"(",
"val",
",",
"'_has_channel_'",
",",
"None",
")",
"result",
"=",
"NotImplemented",
"if",
"channel_getter",
"is",
"None",
"else",
"channel_getter",
"("... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | two_qubit_matrix_to_operations | Decomposes a two-qubit operation into Z/XY/CZ gates.
Args:
q0: The first qubit being operated on.
q1: The other qubit being operated on.
mat: Defines the operation to apply to the pair of qubits.
allow_partial_czs: Enables the use of Partial-CZ gates.
atol: A limit on the am... | cirq/optimizers/two_qubit_decompositions.py | def two_qubit_matrix_to_operations(q0: ops.Qid,
q1: ops.Qid,
mat: np.ndarray,
allow_partial_czs: bool,
atol: float = 1e-8,
clean_operations: bool... | def two_qubit_matrix_to_operations(q0: ops.Qid,
q1: ops.Qid,
mat: np.ndarray,
allow_partial_czs: bool,
atol: float = 1e-8,
clean_operations: bool... | [
"Decomposes",
"a",
"two",
"-",
"qubit",
"operation",
"into",
"Z",
"/",
"XY",
"/",
"CZ",
"gates",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/optimizers/two_qubit_decompositions.py#L30-L58 | [
"def",
"two_qubit_matrix_to_operations",
"(",
"q0",
":",
"ops",
".",
"Qid",
",",
"q1",
":",
"ops",
".",
"Qid",
",",
"mat",
":",
"np",
".",
"ndarray",
",",
"allow_partial_czs",
":",
"bool",
",",
"atol",
":",
"float",
"=",
"1e-8",
",",
"clean_operations",
... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | _kak_decomposition_to_operations | Assumes that the decomposition is canonical. | cirq/optimizers/two_qubit_decompositions.py | def _kak_decomposition_to_operations(q0: ops.Qid,
q1: ops.Qid,
kak: linalg.KakDecomposition,
allow_partial_czs: bool,
atol: float = 1e-8
... | def _kak_decomposition_to_operations(q0: ops.Qid,
q1: ops.Qid,
kak: linalg.KakDecomposition,
allow_partial_czs: bool,
atol: float = 1e-8
... | [
"Assumes",
"that",
"the",
"decomposition",
"is",
"canonical",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/optimizers/two_qubit_decompositions.py#L125-L145 | [
"def",
"_kak_decomposition_to_operations",
"(",
"q0",
":",
"ops",
".",
"Qid",
",",
"q1",
":",
"ops",
".",
"Qid",
",",
"kak",
":",
"linalg",
".",
"KakDecomposition",
",",
"allow_partial_czs",
":",
"bool",
",",
"atol",
":",
"float",
"=",
"1e-8",
")",
"->",... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | _is_trivial_angle | Tests if a circuit for an operator exp(i*rad*XX) (or YY, or ZZ) can
be performed with a whole CZ.
Args:
rad: The angle in radians, assumed to be in the range [-pi/4, pi/4] | cirq/optimizers/two_qubit_decompositions.py | def _is_trivial_angle(rad: float, atol: float) -> bool:
"""Tests if a circuit for an operator exp(i*rad*XX) (or YY, or ZZ) can
be performed with a whole CZ.
Args:
rad: The angle in radians, assumed to be in the range [-pi/4, pi/4]
"""
return abs(rad) < atol or abs(abs(rad) - np.pi / 4) < at... | def _is_trivial_angle(rad: float, atol: float) -> bool:
"""Tests if a circuit for an operator exp(i*rad*XX) (or YY, or ZZ) can
be performed with a whole CZ.
Args:
rad: The angle in radians, assumed to be in the range [-pi/4, pi/4]
"""
return abs(rad) < atol or abs(abs(rad) - np.pi / 4) < at... | [
"Tests",
"if",
"a",
"circuit",
"for",
"an",
"operator",
"exp",
"(",
"i",
"*",
"rad",
"*",
"XX",
")",
"(",
"or",
"YY",
"or",
"ZZ",
")",
"can",
"be",
"performed",
"with",
"a",
"whole",
"CZ",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/optimizers/two_qubit_decompositions.py#L148-L155 | [
"def",
"_is_trivial_angle",
"(",
"rad",
":",
"float",
",",
"atol",
":",
"float",
")",
"->",
"bool",
":",
"return",
"abs",
"(",
"rad",
")",
"<",
"atol",
"or",
"abs",
"(",
"abs",
"(",
"rad",
")",
"-",
"np",
".",
"pi",
"/",
"4",
")",
"<",
"atol"
] | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | _parity_interaction | Yields a ZZ interaction framed by the given operation. | cirq/optimizers/two_qubit_decompositions.py | def _parity_interaction(q0: ops.Qid,
q1: ops.Qid,
rads: float,
atol: float,
gate: Optional[ops.Gate] = None):
"""Yields a ZZ interaction framed by the given operation."""
if abs(rads) < atol:
return
h = ... | def _parity_interaction(q0: ops.Qid,
q1: ops.Qid,
rads: float,
atol: float,
gate: Optional[ops.Gate] = None):
"""Yields a ZZ interaction framed by the given operation."""
if abs(rads) < atol:
return
h = ... | [
"Yields",
"a",
"ZZ",
"interaction",
"framed",
"by",
"the",
"given",
"operation",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/optimizers/two_qubit_decompositions.py#L158-L182 | [
"def",
"_parity_interaction",
"(",
"q0",
":",
"ops",
".",
"Qid",
",",
"q1",
":",
"ops",
".",
"Qid",
",",
"rads",
":",
"float",
",",
"atol",
":",
"float",
",",
"gate",
":",
"Optional",
"[",
"ops",
".",
"Gate",
"]",
"=",
"None",
")",
":",
"if",
"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | _non_local_part | Yields non-local operation of KAK decomposition. | cirq/optimizers/two_qubit_decompositions.py | def _non_local_part(q0: ops.Qid,
q1: ops.Qid,
interaction_coefficients: Tuple[float, float, float],
allow_partial_czs: bool,
atol: float = 1e-8):
"""Yields non-local operation of KAK decomposition."""
x, y, z = interaction_coeffici... | def _non_local_part(q0: ops.Qid,
q1: ops.Qid,
interaction_coefficients: Tuple[float, float, float],
allow_partial_czs: bool,
atol: float = 1e-8):
"""Yields non-local operation of KAK decomposition."""
x, y, z = interaction_coeffici... | [
"Yields",
"non",
"-",
"local",
"operation",
"of",
"KAK",
"decomposition",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/optimizers/two_qubit_decompositions.py#L190-L213 | [
"def",
"_non_local_part",
"(",
"q0",
":",
"ops",
".",
"Qid",
",",
"q1",
":",
"ops",
".",
"Qid",
",",
"interaction_coefficients",
":",
"Tuple",
"[",
"float",
",",
"float",
",",
"float",
"]",
",",
"allow_partial_czs",
":",
"bool",
",",
"atol",
":",
"floa... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | simulate | Runs the simulator. | dev_tools/profiling/benchmark_simulators.py | def simulate(sim_type: str,
num_qubits: int,
num_gates: int,
num_prefix_qubits: int = 0,
use_processes: bool = False) -> None:
""""Runs the simulator."""
circuit = cirq.Circuit(device=test_device)
for _ in range(num_gates):
which = np.random.choic... | def simulate(sim_type: str,
num_qubits: int,
num_gates: int,
num_prefix_qubits: int = 0,
use_processes: bool = False) -> None:
""""Runs the simulator."""
circuit = cirq.Circuit(device=test_device)
for _ in range(num_gates):
which = np.random.choic... | [
"Runs",
"the",
"simulator",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/profiling/benchmark_simulators.py#L39-L72 | [
"def",
"simulate",
"(",
"sim_type",
":",
"str",
",",
"num_qubits",
":",
"int",
",",
"num_gates",
":",
"int",
",",
"num_prefix_qubits",
":",
"int",
"=",
"0",
",",
"use_processes",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"circuit",
"=",
"cirq"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | Simulator._run | See definition in `cirq.SimulatesSamples`. | cirq/sim/sparse_simulator.py | def _run(
self,
circuit: circuits.Circuit,
param_resolver: study.ParamResolver,
repetitions: int) -> Dict[str, List[np.ndarray]]:
"""See definition in `cirq.SimulatesSamples`."""
param_resolver = param_resolver or study.ParamResolver({})
resolved_circuit = protoco... | def _run(
self,
circuit: circuits.Circuit,
param_resolver: study.ParamResolver,
repetitions: int) -> Dict[str, List[np.ndarray]]:
"""See definition in `cirq.SimulatesSamples`."""
param_resolver = param_resolver or study.ParamResolver({})
resolved_circuit = protoco... | [
"See",
"definition",
"in",
"cirq",
".",
"SimulatesSamples",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/sim/sparse_simulator.py#L136-L149 | [
"def",
"_run",
"(",
"self",
",",
"circuit",
":",
"circuits",
".",
"Circuit",
",",
"param_resolver",
":",
"study",
".",
"ParamResolver",
",",
"repetitions",
":",
"int",
")",
"->",
"Dict",
"[",
"str",
",",
"List",
"[",
"np",
".",
"ndarray",
"]",
"]",
"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | Simulator._simulate_unitary | Simulate an op that has a unitary. | cirq/sim/sparse_simulator.py | def _simulate_unitary(self, op: ops.Operation, data: _StateAndBuffer,
indices: List[int]) -> None:
"""Simulate an op that has a unitary."""
result = protocols.apply_unitary(
op,
args=protocols.ApplyUnitaryArgs(
data.state,
... | def _simulate_unitary(self, op: ops.Operation, data: _StateAndBuffer,
indices: List[int]) -> None:
"""Simulate an op that has a unitary."""
result = protocols.apply_unitary(
op,
args=protocols.ApplyUnitaryArgs(
data.state,
... | [
"Simulate",
"an",
"op",
"that",
"has",
"a",
"unitary",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/sim/sparse_simulator.py#L277-L288 | [
"def",
"_simulate_unitary",
"(",
"self",
",",
"op",
":",
"ops",
".",
"Operation",
",",
"data",
":",
"_StateAndBuffer",
",",
"indices",
":",
"List",
"[",
"int",
"]",
")",
"->",
"None",
":",
"result",
"=",
"protocols",
".",
"apply_unitary",
"(",
"op",
",... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | Simulator._simulate_measurement | Simulate an op that is a measurement in the computataional basis. | cirq/sim/sparse_simulator.py | def _simulate_measurement(self, op: ops.Operation, data: _StateAndBuffer,
indices: List[int], measurements: Dict[str, List[bool]],
num_qubits: int) -> None:
"""Simulate an op that is a measurement in the computataional basis."""
meas = ops.op_gate_of_type(op, ops.MeasurementGate)... | def _simulate_measurement(self, op: ops.Operation, data: _StateAndBuffer,
indices: List[int], measurements: Dict[str, List[bool]],
num_qubits: int) -> None:
"""Simulate an op that is a measurement in the computataional basis."""
meas = ops.op_gate_of_type(op, ops.MeasurementGate)... | [
"Simulate",
"an",
"op",
"that",
"is",
"a",
"measurement",
"in",
"the",
"computataional",
"basis",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/sim/sparse_simulator.py#L290-L305 | [
"def",
"_simulate_measurement",
"(",
"self",
",",
"op",
":",
"ops",
".",
"Operation",
",",
"data",
":",
"_StateAndBuffer",
",",
"indices",
":",
"List",
"[",
"int",
"]",
",",
"measurements",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"bool",
"]",
"]",
... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | Simulator._simulate_mixture | Simulate an op that is a mixtures of unitaries. | cirq/sim/sparse_simulator.py | def _simulate_mixture(self, op: ops.Operation, data: _StateAndBuffer,
indices: List[int]) -> None:
"""Simulate an op that is a mixtures of unitaries."""
probs, unitaries = zip(*protocols.mixture(op))
# We work around numpy barfing on choosing from a list of
# numpy arrays (wh... | def _simulate_mixture(self, op: ops.Operation, data: _StateAndBuffer,
indices: List[int]) -> None:
"""Simulate an op that is a mixtures of unitaries."""
probs, unitaries = zip(*protocols.mixture(op))
# We work around numpy barfing on choosing from a list of
# numpy arrays (wh... | [
"Simulate",
"an",
"op",
"that",
"is",
"a",
"mixtures",
"of",
"unitaries",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/sim/sparse_simulator.py#L307-L320 | [
"def",
"_simulate_mixture",
"(",
"self",
",",
"op",
":",
"ops",
".",
"Operation",
",",
"data",
":",
"_StateAndBuffer",
",",
"indices",
":",
"List",
"[",
"int",
"]",
")",
"->",
"None",
":",
"probs",
",",
"unitaries",
"=",
"zip",
"(",
"*",
"protocols",
... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | cubic_acquaintance_strategy | Acquaints every triple of qubits.
Exploits the fact that in a simple linear swap network every pair of
logical qubits that starts at distance two remains so (except temporarily
near the edge), and that every third one `goes through` the pair at some
point in the network. The strategy then iterates thro... | cirq/contrib/acquaintance/strategies/cubic.py | def cubic_acquaintance_strategy(
qubits: Iterable[ops.Qid],
swap_gate: ops.Gate=ops.SWAP
) -> circuits.Circuit:
"""Acquaints every triple of qubits.
Exploits the fact that in a simple linear swap network every pair of
logical qubits that starts at distance two remains so (except tem... | def cubic_acquaintance_strategy(
qubits: Iterable[ops.Qid],
swap_gate: ops.Gate=ops.SWAP
) -> circuits.Circuit:
"""Acquaints every triple of qubits.
Exploits the fact that in a simple linear swap network every pair of
logical qubits that starts at distance two remains so (except tem... | [
"Acquaints",
"every",
"triple",
"of",
"qubits",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/contrib/acquaintance/strategies/cubic.py#L34-L77 | [
"def",
"cubic_acquaintance_strategy",
"(",
"qubits",
":",
"Iterable",
"[",
"ops",
".",
"Qid",
"]",
",",
"swap_gate",
":",
"ops",
".",
"Gate",
"=",
"ops",
".",
"SWAP",
")",
"->",
"circuits",
".",
"Circuit",
":",
"qubits",
"=",
"tuple",
"(",
"qubits",
")... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | _parse_device | Parse ASCIIart device layout into info about qubits and connectivity.
Args:
s: String representing the qubit layout. Each line represents a row,
and each character in the row is a qubit, or a blank site if the
character is a hyphen '-'. Different letters for the qubit specify
... | cirq/google/known_devices.py | def _parse_device(s: str) -> Tuple[List[GridQubit], Dict[str, Set[GridQubit]]]:
"""Parse ASCIIart device layout into info about qubits and connectivity.
Args:
s: String representing the qubit layout. Each line represents a row,
and each character in the row is a qubit, or a blank site if th... | def _parse_device(s: str) -> Tuple[List[GridQubit], Dict[str, Set[GridQubit]]]:
"""Parse ASCIIart device layout into info about qubits and connectivity.
Args:
s: String representing the qubit layout. Each line represents a row,
and each character in the row is a qubit, or a blank site if th... | [
"Parse",
"ASCIIart",
"device",
"layout",
"into",
"info",
"about",
"qubits",
"and",
"connectivity",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/known_devices.py#L22-L47 | [
"def",
"_parse_device",
"(",
"s",
":",
"str",
")",
"->",
"Tuple",
"[",
"List",
"[",
"GridQubit",
"]",
",",
"Dict",
"[",
"str",
",",
"Set",
"[",
"GridQubit",
"]",
"]",
"]",
":",
"lines",
"=",
"s",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\n... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | approx_eq | Approximately compares two objects.
If `val` implements SupportsApproxEquality protocol then it is invoked and
takes precedence over all other checks:
- For primitive numeric types `int` and `float` approximate equality is
delegated to math.isclose().
- For complex primitive type the real and ... | cirq/protocols/approximate_equality.py | def approx_eq(val: Any, other: Any, *, atol: Union[int, float] = 1e-8) -> bool:
"""Approximately compares two objects.
If `val` implements SupportsApproxEquality protocol then it is invoked and
takes precedence over all other checks:
- For primitive numeric types `int` and `float` approximate equality... | def approx_eq(val: Any, other: Any, *, atol: Union[int, float] = 1e-8) -> bool:
"""Approximately compares two objects.
If `val` implements SupportsApproxEquality protocol then it is invoked and
takes precedence over all other checks:
- For primitive numeric types `int` and `float` approximate equality... | [
"Approximately",
"compares",
"two",
"objects",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/protocols/approximate_equality.py#L48-L105 | [
"def",
"approx_eq",
"(",
"val",
":",
"Any",
",",
"other",
":",
"Any",
",",
"*",
",",
"atol",
":",
"Union",
"[",
"int",
",",
"float",
"]",
"=",
"1e-8",
")",
"->",
"bool",
":",
"# Check if val defines approximate equality via _approx_eq_. This takes",
"# precede... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | _approx_eq_iterables | Iterates over arguments and calls approx_eq recursively.
Types of `val` and `other` does not necessarily needs to match each other.
They just need to be iterable of the same length and have the same
structure, approx_eq() will be called on each consecutive element of `val`
and `other`.
Args:
... | cirq/protocols/approximate_equality.py | def _approx_eq_iterables(val: Any, other: Any, *,
atol: Union[int, float]) -> bool:
"""Iterates over arguments and calls approx_eq recursively.
Types of `val` and `other` does not necessarily needs to match each other.
They just need to be iterable of the same length and have the s... | def _approx_eq_iterables(val: Any, other: Any, *,
atol: Union[int, float]) -> bool:
"""Iterates over arguments and calls approx_eq recursively.
Types of `val` and `other` does not necessarily needs to match each other.
They just need to be iterable of the same length and have the s... | [
"Iterates",
"over",
"arguments",
"and",
"calls",
"approx_eq",
"recursively",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/protocols/approximate_equality.py#L108-L158 | [
"def",
"_approx_eq_iterables",
"(",
"val",
":",
"Any",
",",
"other",
":",
"Any",
",",
"*",
",",
"atol",
":",
"Union",
"[",
"int",
",",
"float",
"]",
")",
"->",
"bool",
":",
"def",
"get_iter",
"(",
"iterable",
")",
":",
"try",
":",
"return",
"iter",... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | _isclose | Convenience wrapper around np.isclose. | cirq/protocols/approximate_equality.py | def _isclose(a: Any, b: Any, *, atol: Union[int, float]) -> bool:
"""Convenience wrapper around np.isclose."""
return True if np.isclose([a], [b], atol=atol, rtol=0.0)[0] else False | def _isclose(a: Any, b: Any, *, atol: Union[int, float]) -> bool:
"""Convenience wrapper around np.isclose."""
return True if np.isclose([a], [b], atol=atol, rtol=0.0)[0] else False | [
"Convenience",
"wrapper",
"around",
"np",
".",
"isclose",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/protocols/approximate_equality.py#L161-L163 | [
"def",
"_isclose",
"(",
"a",
":",
"Any",
",",
"b",
":",
"Any",
",",
"*",
",",
"atol",
":",
"Union",
"[",
"int",
",",
"float",
"]",
")",
"->",
"bool",
":",
"return",
"True",
"if",
"np",
".",
"isclose",
"(",
"[",
"a",
"]",
",",
"[",
"b",
"]",... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | complete_acquaintance_strategy | Returns an acquaintance strategy capable of executing a gate corresponding
to any set of at most acquaintance_size qubits.
Args:
qubit_order: The qubits on which the strategy should be defined.
acquaintance_size: The maximum number of qubits to be acted on by
an operation.
Returns:... | cirq/contrib/acquaintance/strategies/complete.py | def complete_acquaintance_strategy(qubit_order: Sequence[ops.Qid],
acquaintance_size: int=0,
) -> circuits.Circuit:
"""
Returns an acquaintance strategy capable of executing a gate corresponding
to any set of at most acquaintance_size qub... | def complete_acquaintance_strategy(qubit_order: Sequence[ops.Qid],
acquaintance_size: int=0,
) -> circuits.Circuit:
"""
Returns an acquaintance strategy capable of executing a gate corresponding
to any set of at most acquaintance_size qub... | [
"Returns",
"an",
"acquaintance",
"strategy",
"capable",
"of",
"executing",
"a",
"gate",
"corresponding",
"to",
"any",
"set",
"of",
"at",
"most",
"acquaintance_size",
"qubits",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/contrib/acquaintance/strategies/complete.py#L25-L59 | [
"def",
"complete_acquaintance_strategy",
"(",
"qubit_order",
":",
"Sequence",
"[",
"ops",
".",
"Qid",
"]",
",",
"acquaintance_size",
":",
"int",
"=",
"0",
",",
")",
"->",
"circuits",
".",
"Circuit",
":",
"if",
"acquaintance_size",
"<",
"0",
":",
"raise",
"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | set_io_qubits | Add the specified number of input and output qubits. | examples/grover.py | def set_io_qubits(qubit_count):
"""Add the specified number of input and output qubits."""
input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]
output_qubit = cirq.GridQubit(qubit_count, 0)
return (input_qubits, output_qubit) | def set_io_qubits(qubit_count):
"""Add the specified number of input and output qubits."""
input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]
output_qubit = cirq.GridQubit(qubit_count, 0)
return (input_qubits, output_qubit) | [
"Add",
"the",
"specified",
"number",
"of",
"input",
"and",
"output",
"qubits",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/examples/grover.py#L34-L38 | [
"def",
"set_io_qubits",
"(",
"qubit_count",
")",
":",
"input_qubits",
"=",
"[",
"cirq",
".",
"GridQubit",
"(",
"i",
",",
"0",
")",
"for",
"i",
"in",
"range",
"(",
"qubit_count",
")",
"]",
"output_qubit",
"=",
"cirq",
".",
"GridQubit",
"(",
"qubit_count",... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | make_oracle | Implement function {f(x) = 1 if x==x', f(x) = 0 if x!= x'}. | examples/grover.py | def make_oracle(input_qubits, output_qubit, x_bits):
"""Implement function {f(x) = 1 if x==x', f(x) = 0 if x!= x'}."""
# Make oracle.
# for (1, 1) it's just a Toffoli gate
# otherwise negate the zero-bits.
yield(cirq.X(q) for (q, bit) in zip(input_qubits, x_bits) if not bit)
yield(cirq.TOFFOLI(i... | def make_oracle(input_qubits, output_qubit, x_bits):
"""Implement function {f(x) = 1 if x==x', f(x) = 0 if x!= x'}."""
# Make oracle.
# for (1, 1) it's just a Toffoli gate
# otherwise negate the zero-bits.
yield(cirq.X(q) for (q, bit) in zip(input_qubits, x_bits) if not bit)
yield(cirq.TOFFOLI(i... | [
"Implement",
"function",
"{",
"f",
"(",
"x",
")",
"=",
"1",
"if",
"x",
"==",
"x",
"f",
"(",
"x",
")",
"=",
"0",
"if",
"x!",
"=",
"x",
"}",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/examples/grover.py#L41-L48 | [
"def",
"make_oracle",
"(",
"input_qubits",
",",
"output_qubit",
",",
"x_bits",
")",
":",
"# Make oracle.",
"# for (1, 1) it's just a Toffoli gate",
"# otherwise negate the zero-bits.",
"yield",
"(",
"cirq",
".",
"X",
"(",
"q",
")",
"for",
"(",
"q",
",",
"bit",
")"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | make_grover_circuit | Find the value recognized by the oracle in sqrt(N) attempts. | examples/grover.py | def make_grover_circuit(input_qubits, output_qubit, oracle):
"""Find the value recognized by the oracle in sqrt(N) attempts."""
# For 2 input qubits, that means using Grover operator only once.
c = cirq.Circuit()
# Initialize qubits.
c.append([
cirq.X(output_qubit),
cirq.H(output_qu... | def make_grover_circuit(input_qubits, output_qubit, oracle):
"""Find the value recognized by the oracle in sqrt(N) attempts."""
# For 2 input qubits, that means using Grover operator only once.
c = cirq.Circuit()
# Initialize qubits.
c.append([
cirq.X(output_qubit),
cirq.H(output_qu... | [
"Find",
"the",
"value",
"recognized",
"by",
"the",
"oracle",
"in",
"sqrt",
"(",
"N",
")",
"attempts",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/examples/grover.py#L51-L78 | [
"def",
"make_grover_circuit",
"(",
"input_qubits",
",",
"output_qubit",
",",
"oracle",
")",
":",
"# For 2 input qubits, that means using Grover operator only once.",
"c",
"=",
"cirq",
".",
"Circuit",
"(",
")",
"# Initialize qubits.",
"c",
".",
"append",
"(",
"[",
"cir... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | get_unhidden_ungenerated_python_files | Iterates through relevant python files within the given directory.
Args:
directory: The top-level directory to explore.
Yields:
File paths. | dev_tools/env_tools.py | def get_unhidden_ungenerated_python_files(directory: str) -> Iterable[str]:
"""Iterates through relevant python files within the given directory.
Args:
directory: The top-level directory to explore.
Yields:
File paths.
"""
for dirpath, dirnames, filenames in os.walk(directory, topd... | def get_unhidden_ungenerated_python_files(directory: str) -> Iterable[str]:
"""Iterates through relevant python files within the given directory.
Args:
directory: The top-level directory to explore.
Yields:
File paths.
"""
for dirpath, dirnames, filenames in os.walk(directory, topd... | [
"Iterates",
"through",
"relevant",
"python",
"files",
"within",
"the",
"given",
"directory",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/env_tools.py#L25-L41 | [
"def",
"get_unhidden_ungenerated_python_files",
"(",
"directory",
":",
"str",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"for",
"dirpath",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"directory",
",",
"topdown",
"=",
"True",
")",
":"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | create_virtual_env | Creates a new virtual environment and then installs dependencies.
Args:
venv_path: Where to put the virtual environment's state.
requirements_paths: Location of requirements files to -r install.
python_path: The python binary to use.
verbose: When set, more progress output is produc... | dev_tools/env_tools.py | def create_virtual_env(venv_path: str,
requirements_paths: Iterable[str],
python_path: str,
verbose: bool) -> None:
"""Creates a new virtual environment and then installs dependencies.
Args:
venv_path: Where to put the virtual environ... | def create_virtual_env(venv_path: str,
requirements_paths: Iterable[str],
python_path: str,
verbose: bool) -> None:
"""Creates a new virtual environment and then installs dependencies.
Args:
venv_path: Where to put the virtual environ... | [
"Creates",
"a",
"new",
"virtual",
"environment",
"and",
"then",
"installs",
"dependencies",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/env_tools.py#L44-L69 | [
"def",
"create_virtual_env",
"(",
"venv_path",
":",
"str",
",",
"requirements_paths",
":",
"Iterable",
"[",
"str",
"]",
",",
"python_path",
":",
"str",
",",
"verbose",
":",
"bool",
")",
"->",
"None",
":",
"shell_tools",
".",
"run_cmd",
"(",
"'virtualenv'",
... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | derive_temporary_python2_environment | Creates a python 2.7 environment starting from a prepared python 3 one.
Args:
destination_directory: Where to put the python 2 environment.
python3_environment: The prepared environment to start from.
verbose: When set, more progress output is produced.
env_name: The name to use for... | dev_tools/env_tools.py | def derive_temporary_python2_environment(
destination_directory: str,
python3_environment: PreparedEnv,
verbose: bool,
env_name: str = '.test_virtualenv_py2',
python_path: str = "/usr/bin/python2.7") -> PreparedEnv:
"""Creates a python 2.7 environment starting from a prepared... | def derive_temporary_python2_environment(
destination_directory: str,
python3_environment: PreparedEnv,
verbose: bool,
env_name: str = '.test_virtualenv_py2',
python_path: str = "/usr/bin/python2.7") -> PreparedEnv:
"""Creates a python 2.7 environment starting from a prepared... | [
"Creates",
"a",
"python",
"2",
".",
"7",
"environment",
"starting",
"from",
"a",
"prepared",
"python",
"3",
"one",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/env_tools.py#L141-L195 | [
"def",
"derive_temporary_python2_environment",
"(",
"destination_directory",
":",
"str",
",",
"python3_environment",
":",
"PreparedEnv",
",",
"verbose",
":",
"bool",
",",
"env_name",
":",
"str",
"=",
"'.test_virtualenv_py2'",
",",
"python_path",
":",
"str",
"=",
"\"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | run_estimate | Construct the following phase estimator circuit and execute simulations.
---------
---H---------------------@------| |---M--- [m4]:lowest bit
| | |
---H---------------@-----+------| |---M--- [m3]
... | examples/phase_estimator.py | def run_estimate(unknown_gate, qnum, repetitions):
"""Construct the following phase estimator circuit and execute simulations.
---------
---H---------------------@------| |---M--- [m4]:lowest bit
| | |
---H--------------... | def run_estimate(unknown_gate, qnum, repetitions):
"""Construct the following phase estimator circuit and execute simulations.
---------
---H---------------------@------| |---M--- [m4]:lowest bit
| | |
---H--------------... | [
"Construct",
"the",
"following",
"phase",
"estimator",
"circuit",
"and",
"execute",
"simulations",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/examples/phase_estimator.py#L85-L117 | [
"def",
"run_estimate",
"(",
"unknown_gate",
",",
"qnum",
",",
"repetitions",
")",
":",
"qubits",
"=",
"[",
"None",
"]",
"*",
"qnum",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"qubits",
")",
")",
":",
"qubits",
"[",
"i",
"]",
"=",
"cirq",
".",
"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | experiment | Execute the phase estimator cirquit with multiple settings and
show results. | examples/phase_estimator.py | def experiment(qnum, repetitions=100):
"""Execute the phase estimator cirquit with multiple settings and
show results.
"""
def example_gate(phi):
"""An example unitary 1-qubit gate U with an eigen vector |0> and an
eigen value exp(2*Pi*i*phi)
"""
gate = cirq.SingleQubit... | def experiment(qnum, repetitions=100):
"""Execute the phase estimator cirquit with multiple settings and
show results.
"""
def example_gate(phi):
"""An example unitary 1-qubit gate U with an eigen vector |0> and an
eigen value exp(2*Pi*i*phi)
"""
gate = cirq.SingleQubit... | [
"Execute",
"the",
"phase",
"estimator",
"cirquit",
"with",
"multiple",
"settings",
"and",
"show",
"results",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/examples/phase_estimator.py#L120-L146 | [
"def",
"experiment",
"(",
"qnum",
",",
"repetitions",
"=",
"100",
")",
":",
"def",
"example_gate",
"(",
"phi",
")",
":",
"\"\"\"An example unitary 1-qubit gate U with an eigen vector |0> and an\n eigen value exp(2*Pi*i*phi)\n \"\"\"",
"gate",
"=",
"cirq",
".",
... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | QftInverse._decompose_ | A quantum circuit (QFT_inv) with the following structure.
---H--@-------@--------@----------------------------------------------
| | |
------@^-0.5--+--------+---------H--@-------@-------------------------
| | | |
--------... | examples/phase_estimator.py | def _decompose_(self, qubits):
"""A quantum circuit (QFT_inv) with the following structure.
---H--@-------@--------@----------------------------------------------
| | |
------@^-0.5--+--------+---------H--@-------@-------------------------
| ... | def _decompose_(self, qubits):
"""A quantum circuit (QFT_inv) with the following structure.
---H--@-------@--------@----------------------------------------------
| | |
------@^-0.5--+--------+---------H--@-------@-------------------------
| ... | [
"A",
"quantum",
"circuit",
"(",
"QFT_inv",
")",
"with",
"the",
"following",
"structure",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/examples/phase_estimator.py#L63-L82 | [
"def",
"_decompose_",
"(",
"self",
",",
"qubits",
")",
":",
"qubits",
"=",
"list",
"(",
"qubits",
")",
"while",
"len",
"(",
"qubits",
")",
">",
"0",
":",
"q_head",
"=",
"qubits",
".",
"pop",
"(",
"0",
")",
"yield",
"cirq",
".",
"H",
"(",
"q_head"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | line_on_device | Searches for linear sequence of qubits on device.
Args:
device: Google Xmon device instance.
length: Desired number of qubits making up the line.
method: Line placement method. Defaults to
cirq.greedy.GreedySequenceSearchMethod.
Returns:
Line sequences search re... | cirq/google/line/placement/line.py | def line_on_device(
device: 'cirq.google.XmonDevice',
length: int,
method: LinePlacementStrategy = greedy.GreedySequenceSearchStrategy()
) -> GridQubitLineTuple:
"""Searches for linear sequence of qubits on device.
Args:
device: Google Xmon device instance.
length: Desir... | def line_on_device(
device: 'cirq.google.XmonDevice',
length: int,
method: LinePlacementStrategy = greedy.GreedySequenceSearchStrategy()
) -> GridQubitLineTuple:
"""Searches for linear sequence of qubits on device.
Args:
device: Google Xmon device instance.
length: Desir... | [
"Searches",
"for",
"linear",
"sequence",
"of",
"qubits",
"on",
"device",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/line/placement/line.py#L25-L41 | [
"def",
"line_on_device",
"(",
"device",
":",
"'cirq.google.XmonDevice'",
",",
"length",
":",
"int",
",",
"method",
":",
"LinePlacementStrategy",
"=",
"greedy",
".",
"GreedySequenceSearchStrategy",
"(",
")",
")",
"->",
"GridQubitLineTuple",
":",
"return",
"method",
... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | pow | Returns `val**factor` of the given value, if defined.
Values define an extrapolation by defining a __pow__(self, exponent) method.
Note that the method may return NotImplemented to indicate a particular
extrapolation can't be done.
Args:
val: The value or iterable of values to invert.
... | cirq/protocols/pow.py | def pow(val: Any,
exponent: Any,
default: Any = RaiseTypeErrorIfNotProvided) -> Any:
"""Returns `val**factor` of the given value, if defined.
Values define an extrapolation by defining a __pow__(self, exponent) method.
Note that the method may return NotImplemented to indicate a particular
... | def pow(val: Any,
exponent: Any,
default: Any = RaiseTypeErrorIfNotProvided) -> Any:
"""Returns `val**factor` of the given value, if defined.
Values define an extrapolation by defining a __pow__(self, exponent) method.
Note that the method may return NotImplemented to indicate a particular
... | [
"Returns",
"val",
"**",
"factor",
"of",
"the",
"given",
"value",
"if",
"defined",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/protocols/pow.py#L66-L103 | [
"def",
"pow",
"(",
"val",
":",
"Any",
",",
"exponent",
":",
"Any",
",",
"default",
":",
"Any",
"=",
"RaiseTypeErrorIfNotProvided",
")",
"->",
"Any",
":",
"raiser",
"=",
"getattr",
"(",
"val",
",",
"'__pow__'",
",",
"None",
")",
"result",
"=",
"NotImple... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | sample | Simulates sampling from the given circuit or schedule.
Args:
program: The circuit or schedule to sample from.
noise: Noise model to use while running the simulation.
param_resolver: Parameters to run with the program.
repetitions: The number of samples to take.
dtype: The `n... | cirq/sim/mux.py | def sample(program: Union[circuits.Circuit, schedules.Schedule],
*,
noise: devices.NoiseModel = devices.NO_NOISE,
param_resolver: Optional[study.ParamResolver] = None,
repetitions: int = 1,
dtype: Type[np.number] = np.complex64) -> study.TrialResult:
"""Simulat... | def sample(program: Union[circuits.Circuit, schedules.Schedule],
*,
noise: devices.NoiseModel = devices.NO_NOISE,
param_resolver: Optional[study.ParamResolver] = None,
repetitions: int = 1,
dtype: Type[np.number] = np.complex64) -> study.TrialResult:
"""Simulat... | [
"Simulates",
"sampling",
"from",
"the",
"given",
"circuit",
"or",
"schedule",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/sim/mux.py#L25-L53 | [
"def",
"sample",
"(",
"program",
":",
"Union",
"[",
"circuits",
".",
"Circuit",
",",
"schedules",
".",
"Schedule",
"]",
",",
"*",
",",
"noise",
":",
"devices",
".",
"NoiseModel",
"=",
"devices",
".",
"NO_NOISE",
",",
"param_resolver",
":",
"Optional",
"[... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | sample_sweep | Runs the supplied Circuit or Schedule, mimicking quantum hardware.
In contrast to run, this allows for sweeping over different parameter
values.
Args:
program: The circuit or schedule to simulate.
params: Parameters to run with the program.
noise: Noise model to use while running t... | cirq/sim/mux.py | def sample_sweep(program: Union[circuits.Circuit, schedules.Schedule],
params: study.Sweepable,
*,
noise: devices.NoiseModel = devices.NO_NOISE,
repetitions: int = 1,
dtype: Type[np.number] = np.complex64
) -> List[stud... | def sample_sweep(program: Union[circuits.Circuit, schedules.Schedule],
params: study.Sweepable,
*,
noise: devices.NoiseModel = devices.NO_NOISE,
repetitions: int = 1,
dtype: Type[np.number] = np.complex64
) -> List[stud... | [
"Runs",
"the",
"supplied",
"Circuit",
"or",
"Schedule",
"mimicking",
"quantum",
"hardware",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/sim/mux.py#L56-L94 | [
"def",
"sample_sweep",
"(",
"program",
":",
"Union",
"[",
"circuits",
".",
"Circuit",
",",
"schedules",
".",
"Schedule",
"]",
",",
"params",
":",
"study",
".",
"Sweepable",
",",
"*",
",",
"noise",
":",
"devices",
".",
"NoiseModel",
"=",
"devices",
".",
... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | moment_by_moment_schedule | Returns a schedule aligned with the moment structure of the Circuit.
This method attempts to create a schedule in which each moment of a circuit
is scheduled starting at the same time. Given the constraints of the
given device, such a schedule may not be possible, in this case the
the method will raise... | cirq/schedules/schedulers.py | def moment_by_moment_schedule(device: Device, circuit: Circuit):
"""Returns a schedule aligned with the moment structure of the Circuit.
This method attempts to create a schedule in which each moment of a circuit
is scheduled starting at the same time. Given the constraints of the
given device, such a ... | def moment_by_moment_schedule(device: Device, circuit: Circuit):
"""Returns a schedule aligned with the moment structure of the Circuit.
This method attempts to create a schedule in which each moment of a circuit
is scheduled starting at the same time. Given the constraints of the
given device, such a ... | [
"Returns",
"a",
"schedule",
"aligned",
"with",
"the",
"moment",
"structure",
"of",
"the",
"Circuit",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/schedules/schedulers.py#L24-L57 | [
"def",
"moment_by_moment_schedule",
"(",
"device",
":",
"Device",
",",
"circuit",
":",
"Circuit",
")",
":",
"schedule",
"=",
"Schedule",
"(",
"device",
")",
"t",
"=",
"Timestamp",
"(",
")",
"for",
"moment",
"in",
"circuit",
":",
"if",
"not",
"moment",
".... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | Block.min_width | Minimum width necessary to render the block's contents. | cirq/circuits/_block_diagram_drawer.py | def min_width(self) -> int:
"""Minimum width necessary to render the block's contents."""
return max(
max(len(e) for e in self.content.split('\n')),
# Only horizontal lines can cross 0 width blocks.
int(any([self.top, self.bottom]))
) | def min_width(self) -> int:
"""Minimum width necessary to render the block's contents."""
return max(
max(len(e) for e in self.content.split('\n')),
# Only horizontal lines can cross 0 width blocks.
int(any([self.top, self.bottom]))
) | [
"Minimum",
"width",
"necessary",
"to",
"render",
"the",
"block",
"s",
"contents",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/circuits/_block_diagram_drawer.py#L37-L43 | [
"def",
"min_width",
"(",
"self",
")",
"->",
"int",
":",
"return",
"max",
"(",
"max",
"(",
"len",
"(",
"e",
")",
"for",
"e",
"in",
"self",
".",
"content",
".",
"split",
"(",
"'\\n'",
")",
")",
",",
"# Only horizontal lines can cross 0 width blocks.",
"int... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | Block.min_height | Minimum height necessary to render the block's contents. | cirq/circuits/_block_diagram_drawer.py | def min_height(self) -> int:
"""Minimum height necessary to render the block's contents."""
return max(
len(self.content.split('\n')) if self.content else 0,
# Only vertical lines can cross 0 height blocks.
int(any([self.left, self.right]))
) | def min_height(self) -> int:
"""Minimum height necessary to render the block's contents."""
return max(
len(self.content.split('\n')) if self.content else 0,
# Only vertical lines can cross 0 height blocks.
int(any([self.left, self.right]))
) | [
"Minimum",
"height",
"necessary",
"to",
"render",
"the",
"block",
"s",
"contents",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/circuits/_block_diagram_drawer.py#L45-L51 | [
"def",
"min_height",
"(",
"self",
")",
"->",
"int",
":",
"return",
"max",
"(",
"len",
"(",
"self",
".",
"content",
".",
"split",
"(",
"'\\n'",
")",
")",
"if",
"self",
".",
"content",
"else",
"0",
",",
"# Only vertical lines can cross 0 height blocks.",
"in... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | Block.draw_curve | Draws lines in the box using the given character set.
Supports merging the new lines with the lines from a previous call to
draw_curve, including when they have different character sets (assuming
there exist characters merging the two).
Args:
grid_characters: The character ... | cirq/circuits/_block_diagram_drawer.py | def draw_curve(self,
grid_characters: BoxDrawCharacterSet,
*,
top: bool = False,
left: bool = False,
right: bool = False,
bottom: bool = False,
crossing_char: Optional[str] = None):
... | def draw_curve(self,
grid_characters: BoxDrawCharacterSet,
*,
top: bool = False,
left: bool = False,
right: bool = False,
bottom: bool = False,
crossing_char: Optional[str] = None):
... | [
"Draws",
"lines",
"in",
"the",
"box",
"using",
"the",
"given",
"character",
"set",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/circuits/_block_diagram_drawer.py#L53-L107 | [
"def",
"draw_curve",
"(",
"self",
",",
"grid_characters",
":",
"BoxDrawCharacterSet",
",",
"*",
",",
"top",
":",
"bool",
"=",
"False",
",",
"left",
":",
"bool",
"=",
"False",
",",
"right",
":",
"bool",
"=",
"False",
",",
"bottom",
":",
"bool",
"=",
"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | Block.render | Returns a list of text lines representing the block's contents.
Args:
width: The width of the output text. Must be at least as large as
the block's minimum width.
height: The height of the output text. Must be at least as large as
the block's minimum heig... | cirq/circuits/_block_diagram_drawer.py | def render(self, width: int, height: int) -> List[str]:
"""Returns a list of text lines representing the block's contents.
Args:
width: The width of the output text. Must be at least as large as
the block's minimum width.
height: The height of the output text. Mu... | def render(self, width: int, height: int) -> List[str]:
"""Returns a list of text lines representing the block's contents.
Args:
width: The width of the output text. Must be at least as large as
the block's minimum width.
height: The height of the output text. Mu... | [
"Returns",
"a",
"list",
"of",
"text",
"lines",
"representing",
"the",
"block",
"s",
"contents",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/circuits/_block_diagram_drawer.py#L109-L154 | [
"def",
"render",
"(",
"self",
",",
"width",
":",
"int",
",",
"height",
":",
"int",
")",
"->",
"List",
"[",
"str",
"]",
":",
"if",
"width",
"==",
"0",
"or",
"height",
"==",
"0",
":",
"return",
"[",
"''",
"]",
"*",
"height",
"out_chars",
"=",
"["... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | BlockDiagramDrawer.mutable_block | Returns the block at (x, y) so it can be edited. | cirq/circuits/_block_diagram_drawer.py | def mutable_block(self, x: int, y: int) -> Block:
"""Returns the block at (x, y) so it can be edited."""
if x < 0 or y < 0:
raise IndexError('x < 0 or y < 0')
return self._blocks[(x, y)] | def mutable_block(self, x: int, y: int) -> Block:
"""Returns the block at (x, y) so it can be edited."""
if x < 0 or y < 0:
raise IndexError('x < 0 or y < 0')
return self._blocks[(x, y)] | [
"Returns",
"the",
"block",
"at",
"(",
"x",
"y",
")",
"so",
"it",
"can",
"be",
"edited",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/circuits/_block_diagram_drawer.py#L173-L177 | [
"def",
"mutable_block",
"(",
"self",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
")",
"->",
"Block",
":",
"if",
"x",
"<",
"0",
"or",
"y",
"<",
"0",
":",
"raise",
"IndexError",
"(",
"'x < 0 or y < 0'",
")",
"return",
"self",
".",
"_blocks",
"[",
"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | BlockDiagramDrawer.set_col_min_width | Sets a minimum width for blocks in the column with coordinate x. | cirq/circuits/_block_diagram_drawer.py | def set_col_min_width(self, x: int, min_width: int):
"""Sets a minimum width for blocks in the column with coordinate x."""
if x < 0:
raise IndexError('x < 0')
self._min_widths[x] = min_width | def set_col_min_width(self, x: int, min_width: int):
"""Sets a minimum width for blocks in the column with coordinate x."""
if x < 0:
raise IndexError('x < 0')
self._min_widths[x] = min_width | [
"Sets",
"a",
"minimum",
"width",
"for",
"blocks",
"in",
"the",
"column",
"with",
"coordinate",
"x",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/circuits/_block_diagram_drawer.py#L179-L183 | [
"def",
"set_col_min_width",
"(",
"self",
",",
"x",
":",
"int",
",",
"min_width",
":",
"int",
")",
":",
"if",
"x",
"<",
"0",
":",
"raise",
"IndexError",
"(",
"'x < 0'",
")",
"self",
".",
"_min_widths",
"[",
"x",
"]",
"=",
"min_width"
] | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | BlockDiagramDrawer.set_row_min_height | Sets a minimum height for blocks in the row with coordinate y. | cirq/circuits/_block_diagram_drawer.py | def set_row_min_height(self, y: int, min_height: int):
"""Sets a minimum height for blocks in the row with coordinate y."""
if y < 0:
raise IndexError('y < 0')
self._min_heights[y] = min_height | def set_row_min_height(self, y: int, min_height: int):
"""Sets a minimum height for blocks in the row with coordinate y."""
if y < 0:
raise IndexError('y < 0')
self._min_heights[y] = min_height | [
"Sets",
"a",
"minimum",
"height",
"for",
"blocks",
"in",
"the",
"row",
"with",
"coordinate",
"y",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/circuits/_block_diagram_drawer.py#L185-L189 | [
"def",
"set_row_min_height",
"(",
"self",
",",
"y",
":",
"int",
",",
"min_height",
":",
"int",
")",
":",
"if",
"y",
"<",
"0",
":",
"raise",
"IndexError",
"(",
"'y < 0'",
")",
"self",
".",
"_min_heights",
"[",
"y",
"]",
"=",
"min_height"
] | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | BlockDiagramDrawer.render | Outputs text containing the diagram.
Args:
block_span_x: The width of the diagram in blocks. Set to None to
default to using the smallest width that would include all
accessed blocks and columns with a specified minimum width.
block_span_y: The height of ... | cirq/circuits/_block_diagram_drawer.py | def render(self,
*,
block_span_x: Optional[int] = None,
block_span_y: Optional[int] = None,
min_block_width: int = 0,
min_block_height: int = 0) -> str:
"""Outputs text containing the diagram.
Args:
block_span_x: The... | def render(self,
*,
block_span_x: Optional[int] = None,
block_span_y: Optional[int] = None,
min_block_width: int = 0,
min_block_height: int = 0) -> str:
"""Outputs text containing the diagram.
Args:
block_span_x: The... | [
"Outputs",
"text",
"containing",
"the",
"diagram",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/circuits/_block_diagram_drawer.py#L191-L265 | [
"def",
"render",
"(",
"self",
",",
"*",
",",
"block_span_x",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"block_span_y",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"min_block_width",
":",
"int",
"=",
"0",
",",
"min_block_height",
":",
... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | main | Demonstrates Quantum Fourier transform. | examples/quantum_fourier_transform.py | def main():
"""Demonstrates Quantum Fourier transform.
"""
# Create circuit
qft_circuit = generate_2x2_grid_qft_circuit()
print('Circuit:')
print(qft_circuit)
# Simulate and collect final_state
simulator = cirq.Simulator()
result = simulator.simulate(qft_circuit)
print()
prin... | def main():
"""Demonstrates Quantum Fourier transform.
"""
# Create circuit
qft_circuit = generate_2x2_grid_qft_circuit()
print('Circuit:')
print(qft_circuit)
# Simulate and collect final_state
simulator = cirq.Simulator()
result = simulator.simulate(qft_circuit)
print()
prin... | [
"Demonstrates",
"Quantum",
"Fourier",
"transform",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/examples/quantum_fourier_transform.py#L28-L40 | [
"def",
"main",
"(",
")",
":",
"# Create circuit",
"qft_circuit",
"=",
"generate_2x2_grid_qft_circuit",
"(",
")",
"print",
"(",
"'Circuit:'",
")",
"print",
"(",
"qft_circuit",
")",
"# Simulate and collect final_state",
"simulator",
"=",
"cirq",
".",
"Simulator",
"(",... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | PauliStringGateOperation.map_qubits | Return an equivalent operation on new qubits with its Pauli string
mapped to new qubits.
new_pauli_string = self.pauli_string.map_qubits(qubit_map) | cirq/ops/pauli_string_raw_types.py | def map_qubits(self: TSelf_PauliStringGateOperation,
qubit_map: Dict[raw_types.Qid, raw_types.Qid]
) -> TSelf_PauliStringGateOperation:
"""Return an equivalent operation on new qubits with its Pauli string
mapped to new qubits.
new_pauli_string = self.pauli_... | def map_qubits(self: TSelf_PauliStringGateOperation,
qubit_map: Dict[raw_types.Qid, raw_types.Qid]
) -> TSelf_PauliStringGateOperation:
"""Return an equivalent operation on new qubits with its Pauli string
mapped to new qubits.
new_pauli_string = self.pauli_... | [
"Return",
"an",
"equivalent",
"operation",
"on",
"new",
"qubits",
"with",
"its",
"Pauli",
"string",
"mapped",
"to",
"new",
"qubits",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/ops/pauli_string_raw_types.py#L42-L49 | [
"def",
"map_qubits",
"(",
"self",
":",
"TSelf_PauliStringGateOperation",
",",
"qubit_map",
":",
"Dict",
"[",
"raw_types",
".",
"Qid",
",",
"raw_types",
".",
"Qid",
"]",
")",
"->",
"TSelf_PauliStringGateOperation",
":"
] | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | PreparedEnv.report_status_to_github | Sets a commit status indicator on github.
If not running from a pull request (i.e. repository is None), then this
just prints to stderr.
Args:
state: The state of the status indicator.
Must be 'error', 'failure', 'pending', or 'success'.
description: A s... | dev_tools/prepared_env.py | def report_status_to_github(self,
state: str,
description: str,
context: str,
target_url: Optional[str] = None):
"""Sets a commit status indicator on github.
If not running fr... | def report_status_to_github(self,
state: str,
description: str,
context: str,
target_url: Optional[str] = None):
"""Sets a commit status indicator on github.
If not running fr... | [
"Sets",
"a",
"commit",
"status",
"indicator",
"on",
"github",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/prepared_env.py#L63-L118 | [
"def",
"report_status_to_github",
"(",
"self",
",",
"state",
":",
"str",
",",
"description",
":",
"str",
",",
"context",
":",
"str",
",",
"target_url",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
":",
"if",
"state",
"not",
"in",
"[",
"'error'",... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | PreparedEnv.get_changed_files | Get the files changed on one git branch vs another.
Returns:
List[str]: File paths of changed files, relative to the git repo
root. | dev_tools/prepared_env.py | def get_changed_files(self) -> List[str]:
"""Get the files changed on one git branch vs another.
Returns:
List[str]: File paths of changed files, relative to the git repo
root.
"""
out = shell_tools.output_of(
'git',
'diff',
... | def get_changed_files(self) -> List[str]:
"""Get the files changed on one git branch vs another.
Returns:
List[str]: File paths of changed files, relative to the git repo
root.
"""
out = shell_tools.output_of(
'git',
'diff',
... | [
"Get",
"the",
"files",
"changed",
"on",
"one",
"git",
"branch",
"vs",
"another",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/prepared_env.py#L120-L135 | [
"def",
"get_changed_files",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"out",
"=",
"shell_tools",
".",
"output_of",
"(",
"'git'",
",",
"'diff'",
",",
"'--name-only'",
",",
"self",
".",
"compare_commit_id",
",",
"self",
".",
"actual_commit_id",
"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | Duration.create | Creates a Duration from datetime.timedelta if necessary | cirq/value/duration.py | def create(cls, duration: Union['Duration', timedelta]) -> 'Duration':
"""Creates a Duration from datetime.timedelta if necessary"""
if isinstance(duration, cls):
return duration
elif isinstance(duration, timedelta):
duration_in_picos = duration.total_seconds() * 10**12
... | def create(cls, duration: Union['Duration', timedelta]) -> 'Duration':
"""Creates a Duration from datetime.timedelta if necessary"""
if isinstance(duration, cls):
return duration
elif isinstance(duration, timedelta):
duration_in_picos = duration.total_seconds() * 10**12
... | [
"Creates",
"a",
"Duration",
"from",
"datetime",
".",
"timedelta",
"if",
"necessary"
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/value/duration.py#L42-L51 | [
"def",
"create",
"(",
"cls",
",",
"duration",
":",
"Union",
"[",
"'Duration'",
",",
"timedelta",
"]",
")",
"->",
"'Duration'",
":",
"if",
"isinstance",
"(",
"duration",
",",
"cls",
")",
":",
"return",
"duration",
"elif",
"isinstance",
"(",
"duration",
",... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | SharedMemManager._create_array | Returns the handle of a RawArray created from the given numpy array.
Args:
arr: A numpy ndarray.
Returns:
The handle (int) of the array.
Raises:
ValueError: if arr is not a ndarray or of an unsupported dtype. If
the array is of an unsupported type, us... | cirq/google/sim/mem_manager.py | def _create_array(self, arr: np.ndarray) -> int:
"""Returns the handle of a RawArray created from the given numpy array.
Args:
arr: A numpy ndarray.
Returns:
The handle (int) of the array.
Raises:
ValueError: if arr is not a ndarray or of an unsupported d... | def _create_array(self, arr: np.ndarray) -> int:
"""Returns the handle of a RawArray created from the given numpy array.
Args:
arr: A numpy ndarray.
Returns:
The handle (int) of the array.
Raises:
ValueError: if arr is not a ndarray or of an unsupported d... | [
"Returns",
"the",
"handle",
"of",
"a",
"RawArray",
"created",
"from",
"the",
"given",
"numpy",
"array",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/sim/mem_manager.py#L53-L91 | [
"def",
"_create_array",
"(",
"self",
",",
"arr",
":",
"np",
".",
"ndarray",
")",
"->",
"int",
":",
"if",
"not",
"isinstance",
"(",
"arr",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"ValueError",
"(",
"'Array is not a numpy ndarray.'",
")",
"try",
":",... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | SharedMemManager._free_array | Frees the memory for the array with the given handle.
Args:
handle: The handle of the array whose memory should be freed. This
handle must come from the _create_array method. | cirq/google/sim/mem_manager.py | def _free_array(self, handle: int):
"""Frees the memory for the array with the given handle.
Args:
handle: The handle of the array whose memory should be freed. This
handle must come from the _create_array method.
"""
with self._lock:
if self._arrays[ha... | def _free_array(self, handle: int):
"""Frees the memory for the array with the given handle.
Args:
handle: The handle of the array whose memory should be freed. This
handle must come from the _create_array method.
"""
with self._lock:
if self._arrays[ha... | [
"Frees",
"the",
"memory",
"for",
"the",
"array",
"with",
"the",
"given",
"handle",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/sim/mem_manager.py#L102-L112 | [
"def",
"_free_array",
"(",
"self",
",",
"handle",
":",
"int",
")",
":",
"with",
"self",
".",
"_lock",
":",
"if",
"self",
".",
"_arrays",
"[",
"handle",
"]",
"is",
"not",
"None",
":",
"self",
".",
"_arrays",
"[",
"handle",
"]",
"=",
"None",
"self",
... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | SharedMemManager._get_array | Returns the array with the given handle.
Args:
handle: The handle of the array whose memory should be freed. This
handle must come from the _create_array method.
Returns:
The numpy ndarray with the handle given from _create_array. | cirq/google/sim/mem_manager.py | def _get_array(self, handle: int) -> np.ndarray:
"""Returns the array with the given handle.
Args:
handle: The handle of the array whose memory should be freed. This
handle must come from the _create_array method.
Returns:
The numpy ndarray with the handle given... | def _get_array(self, handle: int) -> np.ndarray:
"""Returns the array with the given handle.
Args:
handle: The handle of the array whose memory should be freed. This
handle must come from the _create_array method.
Returns:
The numpy ndarray with the handle given... | [
"Returns",
"the",
"array",
"with",
"the",
"given",
"handle",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/sim/mem_manager.py#L114-L131 | [
"def",
"_get_array",
"(",
"self",
",",
"handle",
":",
"int",
")",
"->",
"np",
".",
"ndarray",
":",
"tup",
"=",
"self",
".",
"_arrays",
"[",
"handle",
"]",
"assert",
"tup",
"is",
"not",
"None",
"c_arr",
",",
"shape",
"=",
"tup",
"with",
"warnings",
... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | QasmOutput.save | Write QASM output to a file specified by path. | cirq/circuits/qasm_output.py | def save(self, path: Union[str, bytes, int]) -> None:
"""Write QASM output to a file specified by path."""
with open(path, 'w') as f:
def write(s: str) -> None:
f.write(s)
self._write_qasm(write) | def save(self, path: Union[str, bytes, int]) -> None:
"""Write QASM output to a file specified by path."""
with open(path, 'w') as f:
def write(s: str) -> None:
f.write(s)
self._write_qasm(write) | [
"Write",
"QASM",
"output",
"to",
"a",
"file",
"specified",
"by",
"path",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/circuits/qasm_output.py#L187-L192 | [
"def",
"save",
"(",
"self",
",",
"path",
":",
"Union",
"[",
"str",
",",
"bytes",
",",
"int",
"]",
")",
"->",
"None",
":",
"with",
"open",
"(",
"path",
",",
"'w'",
")",
"as",
"f",
":",
"def",
"write",
"(",
"s",
":",
"str",
")",
"->",
"None",
... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | rectify_acquaintance_strategy | Splits moments so that they contain either only acquaintance gates
or only permutation gates. Orders resulting moments so that the first one
is of the same type as the previous one.
Args:
circuit: The acquaintance strategy to rectify.
acquaint_first: Whether to make acquaintance moment firs... | cirq/contrib/acquaintance/mutation_utils.py | def rectify_acquaintance_strategy(
circuit: circuits.Circuit,
acquaint_first: bool=True
) -> None:
"""Splits moments so that they contain either only acquaintance gates
or only permutation gates. Orders resulting moments so that the first one
is of the same type as the previous one.
... | def rectify_acquaintance_strategy(
circuit: circuits.Circuit,
acquaint_first: bool=True
) -> None:
"""Splits moments so that they contain either only acquaintance gates
or only permutation gates. Orders resulting moments so that the first one
is of the same type as the previous one.
... | [
"Splits",
"moments",
"so",
"that",
"they",
"contain",
"either",
"only",
"acquaintance",
"gates",
"or",
"only",
"permutation",
"gates",
".",
"Orders",
"resulting",
"moments",
"so",
"that",
"the",
"first",
"one",
"is",
"of",
"the",
"same",
"type",
"as",
"the",... | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/contrib/acquaintance/mutation_utils.py#L36-L67 | [
"def",
"rectify_acquaintance_strategy",
"(",
"circuit",
":",
"circuits",
".",
"Circuit",
",",
"acquaint_first",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"if",
"not",
"is_acquaintance_strategy",
"(",
"circuit",
")",
":",
"raise",
"TypeError",
"(",
"'no... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | replace_acquaintance_with_swap_network | Replace every moment containing acquaintance gates (after
rectification) with a generalized swap network, with the partition
given by the acquaintance gates in that moment (and singletons for the
free qubits). Accounts for reversing effect of swap networks.
Args:
circuit: The acquaintance strat... | cirq/contrib/acquaintance/mutation_utils.py | def replace_acquaintance_with_swap_network(
circuit: circuits.Circuit,
qubit_order: Sequence[ops.Qid],
acquaintance_size: Optional[int] = 0,
swap_gate: ops.Gate = ops.SWAP
) -> bool:
"""
Replace every moment containing acquaintance gates (after
rectification) with a g... | def replace_acquaintance_with_swap_network(
circuit: circuits.Circuit,
qubit_order: Sequence[ops.Qid],
acquaintance_size: Optional[int] = 0,
swap_gate: ops.Gate = ops.SWAP
) -> bool:
"""
Replace every moment containing acquaintance gates (after
rectification) with a g... | [
"Replace",
"every",
"moment",
"containing",
"acquaintance",
"gates",
"(",
"after",
"rectification",
")",
"with",
"a",
"generalized",
"swap",
"network",
"with",
"the",
"partition",
"given",
"by",
"the",
"acquaintance",
"gates",
"in",
"that",
"moment",
"(",
"and",... | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/contrib/acquaintance/mutation_utils.py#L70-L115 | [
"def",
"replace_acquaintance_with_swap_network",
"(",
"circuit",
":",
"circuits",
".",
"Circuit",
",",
"qubit_order",
":",
"Sequence",
"[",
"ops",
".",
"Qid",
"]",
",",
"acquaintance_size",
":",
"Optional",
"[",
"int",
"]",
"=",
"0",
",",
"swap_gate",
":",
"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | is_native_ion_gate | Check if a gate is a native ion gate.
Args:
gate: Input gate.
Returns:
True if the gate is native to the ion, false otherwise. | cirq/ion/convert_to_ion_gates.py | def is_native_ion_gate(gate: ops.Gate) -> bool:
"""Check if a gate is a native ion gate.
Args:
gate: Input gate.
Returns:
True if the gate is native to the ion, false otherwise.
"""
return isinstance(gate, (ops.XXPowGate,
ops.MeasurementGate,
... | def is_native_ion_gate(gate: ops.Gate) -> bool:
"""Check if a gate is a native ion gate.
Args:
gate: Input gate.
Returns:
True if the gate is native to the ion, false otherwise.
"""
return isinstance(gate, (ops.XXPowGate,
ops.MeasurementGate,
... | [
"Check",
"if",
"a",
"gate",
"is",
"a",
"native",
"ion",
"gate",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/ion/convert_to_ion_gates.py#L90-L103 | [
"def",
"is_native_ion_gate",
"(",
"gate",
":",
"ops",
".",
"Gate",
")",
"->",
"bool",
":",
"return",
"isinstance",
"(",
"gate",
",",
"(",
"ops",
".",
"XXPowGate",
",",
"ops",
".",
"MeasurementGate",
",",
"ops",
".",
"XPowGate",
",",
"ops",
".",
"YPowGa... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | ConvertToIonGates.convert_one | Convert a single (one- or two-qubit) operation
into ion trap native gates
Args:
op: gate operation to be converted
Returns:
the desired operation implemented with ion trap gates | cirq/ion/convert_to_ion_gates.py | def convert_one(self, op: ops.Operation) -> ops.OP_TREE:
"""Convert a single (one- or two-qubit) operation
into ion trap native gates
Args:
op: gate operation to be converted
Returns:
the desired operation implemented with ion trap gates
"""
# K... | def convert_one(self, op: ops.Operation) -> ops.OP_TREE:
"""Convert a single (one- or two-qubit) operation
into ion trap native gates
Args:
op: gate operation to be converted
Returns:
the desired operation implemented with ion trap gates
"""
# K... | [
"Convert",
"a",
"single",
"(",
"one",
"-",
"or",
"two",
"-",
"qubit",
")",
"operation"
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/ion/convert_to_ion_gates.py#L34-L79 | [
"def",
"convert_one",
"(",
"self",
",",
"op",
":",
"ops",
".",
"Operation",
")",
"->",
"ops",
".",
"OP_TREE",
":",
"# Known gate name",
"if",
"not",
"isinstance",
"(",
"op",
",",
"ops",
".",
"GateOperation",
")",
":",
"raise",
"TypeError",
"(",
"\"{!r} i... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | diagonalize_real_symmetric_matrix | Returns an orthogonal matrix that diagonalizes the given matrix.
Args:
matrix: A real symmetric matrix to diagonalize.
rtol: float = 1e-5,
atol: float = 1e-8
Returns:
An orthogonal matrix P such that P.T @ matrix @ P is diagonal.
Raises:
ValueError: Matrix isn't re... | cirq/linalg/diagonalize.py | def diagonalize_real_symmetric_matrix(
matrix: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8) -> np.ndarray:
"""Returns an orthogonal matrix that diagonalizes the given matrix.
Args:
matrix: A real symmetric matrix to diagonalize.
rtol: float = 1e-5,
... | def diagonalize_real_symmetric_matrix(
matrix: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8) -> np.ndarray:
"""Returns an orthogonal matrix that diagonalizes the given matrix.
Args:
matrix: A real symmetric matrix to diagonalize.
rtol: float = 1e-5,
... | [
"Returns",
"an",
"orthogonal",
"matrix",
"that",
"diagonalizes",
"the",
"given",
"matrix",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/linalg/diagonalize.py#L24-L49 | [
"def",
"diagonalize_real_symmetric_matrix",
"(",
"matrix",
":",
"np",
".",
"ndarray",
",",
"*",
",",
"rtol",
":",
"float",
"=",
"1e-5",
",",
"atol",
":",
"float",
"=",
"1e-8",
")",
"->",
"np",
".",
"ndarray",
":",
"# TODO: Determine if thresholds should be pas... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | _contiguous_groups | Splits range(length) into approximate equivalence classes.
Args:
length: The length of the range to split.
comparator: Determines if two indices have approximately equal items.
Returns:
A list of (inclusive_start, exclusive_end) range endpoints. Each
corresponds to a run of app... | cirq/linalg/diagonalize.py | def _contiguous_groups(
length: int,
comparator: Callable[[int, int], bool]
) -> List[Tuple[int, int]]:
"""Splits range(length) into approximate equivalence classes.
Args:
length: The length of the range to split.
comparator: Determines if two indices have approximately equal it... | def _contiguous_groups(
length: int,
comparator: Callable[[int, int], bool]
) -> List[Tuple[int, int]]:
"""Splits range(length) into approximate equivalence classes.
Args:
length: The length of the range to split.
comparator: Determines if two indices have approximately equal it... | [
"Splits",
"range",
"(",
"length",
")",
"into",
"approximate",
"equivalence",
"classes",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/linalg/diagonalize.py#L52-L74 | [
"def",
"_contiguous_groups",
"(",
"length",
":",
"int",
",",
"comparator",
":",
"Callable",
"[",
"[",
"int",
",",
"int",
"]",
",",
"bool",
"]",
")",
"->",
"List",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
":",
"result",
"=",
"[",
"]",
"star... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | diagonalize_real_symmetric_and_sorted_diagonal_matrices | Returns an orthogonal matrix that diagonalizes both given matrices.
The given matrices must commute.
Guarantees that the sorted diagonal matrix is not permuted by the
diagonalization (except for nearly-equal values).
Args:
symmetric_matrix: A real symmetric matrix.
diagonal_matrix: A r... | cirq/linalg/diagonalize.py | def diagonalize_real_symmetric_and_sorted_diagonal_matrices(
symmetric_matrix: np.ndarray,
diagonal_matrix: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8,
check_preconditions: bool = True) -> np.ndarray:
"""Returns an orthogonal matrix that diagonalizes both g... | def diagonalize_real_symmetric_and_sorted_diagonal_matrices(
symmetric_matrix: np.ndarray,
diagonal_matrix: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8,
check_preconditions: bool = True) -> np.ndarray:
"""Returns an orthogonal matrix that diagonalizes both g... | [
"Returns",
"an",
"orthogonal",
"matrix",
"that",
"diagonalizes",
"both",
"given",
"matrices",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/linalg/diagonalize.py#L77-L142 | [
"def",
"diagonalize_real_symmetric_and_sorted_diagonal_matrices",
"(",
"symmetric_matrix",
":",
"np",
".",
"ndarray",
",",
"diagonal_matrix",
":",
"np",
".",
"ndarray",
",",
"*",
",",
"rtol",
":",
"float",
"=",
"1e-5",
",",
"atol",
":",
"float",
"=",
"1e-8",
"... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | bidiagonalize_real_matrix_pair_with_symmetric_products | Finds orthogonal matrices that diagonalize both mat1 and mat2.
Requires mat1 and mat2 to be real.
Requires mat1.T @ mat2 to be symmetric.
Requires mat1 @ mat2.T to be symmetric.
Args:
mat1: One of the real matrices.
mat2: The other real matrix.
rtol: Relative numeric error thre... | cirq/linalg/diagonalize.py | def bidiagonalize_real_matrix_pair_with_symmetric_products(
mat1: np.ndarray,
mat2: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8,
check_preconditions: bool = True) -> Tuple[np.ndarray, np.ndarray]:
"""Finds orthogonal matrices that diagonalize both mat1 and m... | def bidiagonalize_real_matrix_pair_with_symmetric_products(
mat1: np.ndarray,
mat2: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8,
check_preconditions: bool = True) -> Tuple[np.ndarray, np.ndarray]:
"""Finds orthogonal matrices that diagonalize both mat1 and m... | [
"Finds",
"orthogonal",
"matrices",
"that",
"diagonalize",
"both",
"mat1",
"and",
"mat2",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/linalg/diagonalize.py#L153-L230 | [
"def",
"bidiagonalize_real_matrix_pair_with_symmetric_products",
"(",
"mat1",
":",
"np",
".",
"ndarray",
",",
"mat2",
":",
"np",
".",
"ndarray",
",",
"*",
",",
"rtol",
":",
"float",
"=",
"1e-5",
",",
"atol",
":",
"float",
"=",
"1e-8",
",",
"check_preconditio... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | bidiagonalize_unitary_with_special_orthogonals | Finds orthogonal matrices L, R such that L @ matrix @ R is diagonal.
Args:
mat: A unitary matrix.
rtol: Relative numeric error threshold.
atol: Absolute numeric error threshold.
check_preconditions: If set, verifies that the input is a unitary matrix
(to the given tolera... | cirq/linalg/diagonalize.py | def bidiagonalize_unitary_with_special_orthogonals(
mat: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8,
check_preconditions: bool = True
) -> Tuple[np.ndarray, np.array, np.ndarray]:
"""Finds orthogonal matrices L, R such that L @ matrix @ R is diagonal.
Args:
... | def bidiagonalize_unitary_with_special_orthogonals(
mat: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8,
check_preconditions: bool = True
) -> Tuple[np.ndarray, np.array, np.ndarray]:
"""Finds orthogonal matrices L, R such that L @ matrix @ R is diagonal.
Args:
... | [
"Finds",
"orthogonal",
"matrices",
"L",
"R",
"such",
"that",
"L",
"@",
"matrix",
"@",
"R",
"is",
"diagonal",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/linalg/diagonalize.py#L233-L278 | [
"def",
"bidiagonalize_unitary_with_special_orthogonals",
"(",
"mat",
":",
"np",
".",
"ndarray",
",",
"*",
",",
"rtol",
":",
"float",
"=",
"1e-5",
",",
"atol",
":",
"float",
"=",
"1e-8",
",",
"check_preconditions",
":",
"bool",
"=",
"True",
")",
"->",
"Tupl... | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
train | asymmetric_depolarize | r"""Returns a AsymmetricDepolarizingChannel with given parameter.
This channel evolves a density matrix via
$$
\rho \rightarrow (1 - p_x - p_y - p_z) \rho
+ p_x X \rho X + p_y Y \rho Y + p_z Z \rho Z
$$
Args:
p_x: The probability that a Pauli X and no other gat... | cirq/ops/common_channels.py | def asymmetric_depolarize(
p_x: float, p_y: float, p_z: float
) -> AsymmetricDepolarizingChannel:
r"""Returns a AsymmetricDepolarizingChannel with given parameter.
This channel evolves a density matrix via
$$
\rho \rightarrow (1 - p_x - p_y - p_z) \rho
+ p_x X \rho X + p_y ... | def asymmetric_depolarize(
p_x: float, p_y: float, p_z: float
) -> AsymmetricDepolarizingChannel:
r"""Returns a AsymmetricDepolarizingChannel with given parameter.
This channel evolves a density matrix via
$$
\rho \rightarrow (1 - p_x - p_y - p_z) \rho
+ p_x X \rho X + p_y ... | [
"r",
"Returns",
"a",
"AsymmetricDepolarizingChannel",
"with",
"given",
"parameter",
"."
] | quantumlib/Cirq | python | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/ops/common_channels.py#L90-L110 | [
"def",
"asymmetric_depolarize",
"(",
"p_x",
":",
"float",
",",
"p_y",
":",
"float",
",",
"p_z",
":",
"float",
")",
"->",
"AsymmetricDepolarizingChannel",
":",
"return",
"AsymmetricDepolarizingChannel",
"(",
"p_x",
",",
"p_y",
",",
"p_z",
")"
] | 0827da80dd7880e5b923eb69407e980ed9bc0bd2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.