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
Stepper._init_scratch
Initializes a scratch pad equal in size to the wavefunction.
cirq/google/sim/xmon_stepper.py
def _init_scratch(self): """Initializes a scratch pad equal in size to the wavefunction.""" scratch = np.zeros((self._num_shards, self._shard_size), dtype=np.complex64) scratch_handle = mem_manager.SharedMemManager.create_array( scratch.view(dtype=np.float3...
def _init_scratch(self): """Initializes a scratch pad equal in size to the wavefunction.""" scratch = np.zeros((self._num_shards, self._shard_size), dtype=np.complex64) scratch_handle = mem_manager.SharedMemManager.create_array( scratch.view(dtype=np.float3...
[ "Initializes", "a", "scratch", "pad", "equal", "in", "size", "to", "the", "wavefunction", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/sim/xmon_stepper.py#L173-L179
[ "def", "_init_scratch", "(", "self", ")", ":", "scratch", "=", "np", ".", "zeros", "(", "(", "self", ".", "_num_shards", ",", "self", ".", "_shard_size", ")", ",", "dtype", "=", "np", ".", "complex64", ")", "scratch_handle", "=", "mem_manager", ".", "S...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
Stepper._init_state
Initializes a the shard wavefunction and sets the initial state.
cirq/google/sim/xmon_stepper.py
def _init_state(self, initial_state: Union[int, np.ndarray]): """Initializes a the shard wavefunction and sets the initial state.""" state = np.reshape( sim.to_valid_state_vector(initial_state, self._num_qubits), (self._num_shards, self._shard_size)) state_handle = mem_ma...
def _init_state(self, initial_state: Union[int, np.ndarray]): """Initializes a the shard wavefunction and sets the initial state.""" state = np.reshape( sim.to_valid_state_vector(initial_state, self._num_qubits), (self._num_shards, self._shard_size)) state_handle = mem_ma...
[ "Initializes", "a", "the", "shard", "wavefunction", "and", "sets", "the", "initial", "state", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/sim/xmon_stepper.py#L181-L188
[ "def", "_init_state", "(", "self", ",", "initial_state", ":", "Union", "[", "int", ",", "np", ".", "ndarray", "]", ")", ":", "state", "=", "np", ".", "reshape", "(", "sim", ".", "to_valid_state_vector", "(", "initial_state", ",", "self", ".", "_num_qubit...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
Stepper._shard_num_args
Helper that returns a list of dicts including a num_shard entry. The dict for each entry also includes shared_mem_dict, the number of shards, the number of shard qubits, and the supplied constant dict. Args: constant_dict: Dictionary that will be updated to every element of ...
cirq/google/sim/xmon_stepper.py
def _shard_num_args(self, constant_dict: Dict[str, Any] = None ) -> List[Dict[str, Any]]: """Helper that returns a list of dicts including a num_shard entry. The dict for each entry also includes shared_mem_dict, the number of shards, the number o...
def _shard_num_args(self, constant_dict: Dict[str, Any] = None ) -> List[Dict[str, Any]]: """Helper that returns a list of dicts including a num_shard entry. The dict for each entry also includes shared_mem_dict, the number of shards, the number o...
[ "Helper", "that", "returns", "a", "list", "of", "dicts", "including", "a", "num_shard", "entry", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/sim/xmon_stepper.py#L208-L234
[ "def", "_shard_num_args", "(", "self", ",", "constant_dict", ":", "Dict", "[", "str", ",", "Any", "]", "=", "None", ")", "->", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "args", "=", "[", "]", "for", "shard_num", "in", "range", "...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
Stepper.reset_state
Reset the state to the given initial state. Args: reset_state: If this is an int, then this is the state to reset the stepper to, expressed as an integer of the computational basis. Integer to bitwise indices is little endian. Otherwise if this is a n...
cirq/google/sim/xmon_stepper.py
def reset_state(self, reset_state): """Reset the state to the given initial state. Args: reset_state: If this is an int, then this is the state to reset the stepper to, expressed as an integer of the computational basis. Integer to bitwise indices is little e...
def reset_state(self, reset_state): """Reset the state to the given initial state. Args: reset_state: If this is an int, then this is the state to reset the stepper to, expressed as an integer of the computational basis. Integer to bitwise indices is little e...
[ "Reset", "the", "state", "to", "the", "given", "initial", "state", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/sim/xmon_stepper.py#L247-L275
[ "def", "reset_state", "(", "self", ",", "reset_state", ")", ":", "# If the pool has been closed, recreate to calculate state.'", "if", "isinstance", "(", "reset_state", ",", "int", ")", ":", "self", ".", "_pool", ".", "map", "(", "_reset_state", ",", "self", ".", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
Stepper.simulate_phases
Simulate a set of phase gates on the xmon architecture. Args: phase_map: A map from a tuple of indices to a value, one for each phase gate being simulated. If the tuple key has one index, then this is a Z phase gate on the index-th qubit with a rotation ...
cirq/google/sim/xmon_stepper.py
def simulate_phases(self, phase_map: Dict[Tuple[int, ...], float]): """Simulate a set of phase gates on the xmon architecture. Args: phase_map: A map from a tuple of indices to a value, one for each phase gate being simulated. If the tuple key has one index, then ...
def simulate_phases(self, phase_map: Dict[Tuple[int, ...], float]): """Simulate a set of phase gates on the xmon architecture. Args: phase_map: A map from a tuple of indices to a value, one for each phase gate being simulated. If the tuple key has one index, then ...
[ "Simulate", "a", "set", "of", "phase", "gates", "on", "the", "xmon", "architecture", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/sim/xmon_stepper.py#L279-L301
[ "def", "simulate_phases", "(", "self", ",", "phase_map", ":", "Dict", "[", "Tuple", "[", "int", ",", "...", "]", ",", "float", "]", ")", ":", "self", ".", "_pool", ".", "map", "(", "_clear_scratch", ",", "self", ".", "_shard_num_args", "(", ")", ")",...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
Stepper.simulate_w
Simulate a single qubit rotation gate about a X + b Y. The gate simulated is U = exp(-i pi/2 W half_turns) where W = cos(pi axis_half_turns) X + sin(pi axis_half_turns) Y Args: index: The qubit to act on. half_turns: The amount of the overall rotation, see the formula ...
cirq/google/sim/xmon_stepper.py
def simulate_w(self, index: int, half_turns: float, axis_half_turns: float): """Simulate a single qubit rotation gate about a X + b Y. The gate simulated is U = exp(-i pi/2 W half_turns) where W = cos(pi axis_half_turns) X + sin(pi ax...
def simulate_w(self, index: int, half_turns: float, axis_half_turns: float): """Simulate a single qubit rotation gate about a X + b Y. The gate simulated is U = exp(-i pi/2 W half_turns) where W = cos(pi axis_half_turns) X + sin(pi ax...
[ "Simulate", "a", "single", "qubit", "rotation", "gate", "about", "a", "X", "+", "b", "Y", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/sim/xmon_stepper.py#L304-L339
[ "def", "simulate_w", "(", "self", ",", "index", ":", "int", ",", "half_turns", ":", "float", ",", "axis_half_turns", ":", "float", ")", ":", "args", "=", "self", ".", "_shard_num_args", "(", "{", "'index'", ":", "index", ",", "'half_turns'", ":", "half_t...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
Stepper.simulate_measurement
Simulates a single qubit measurement in the computational basis. Args: index: Which qubit is measured. Returns: True iff the measurement result corresponds to the |1> state.
cirq/google/sim/xmon_stepper.py
def simulate_measurement(self, index: int) -> bool: """Simulates a single qubit measurement in the computational basis. Args: index: Which qubit is measured. Returns: True iff the measurement result corresponds to the |1> state. """ args = self._shard_nu...
def simulate_measurement(self, index: int) -> bool: """Simulates a single qubit measurement in the computational basis. Args: index: Which qubit is measured. Returns: True iff the measurement result corresponds to the |1> state. """ args = self._shard_nu...
[ "Simulates", "a", "single", "qubit", "measurement", "in", "the", "computational", "basis", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/sim/xmon_stepper.py#L342-L361
[ "def", "simulate_measurement", "(", "self", ",", "index", ":", "int", ")", "->", "bool", ":", "args", "=", "self", ".", "_shard_num_args", "(", "{", "'index'", ":", "index", "}", ")", "prob_one", "=", "np", ".", "sum", "(", "self", ".", "_pool", ".",...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
Stepper.sample_measurements
Samples from measurements in the computational basis. Note that this does not collapse the wave function. Args: indices: Which qubits are measured. Returns: Measurement results with True corresponding to the |1> state. The outer list is for repetitions, and...
cirq/google/sim/xmon_stepper.py
def sample_measurements( self, indices: List[int], repetitions: int=1) -> List[List[bool]]: """Samples from measurements in the computational basis. Note that this does not collapse the wave function. Args: indices: Which qubits are measured. ...
def sample_measurements( self, indices: List[int], repetitions: int=1) -> List[List[bool]]: """Samples from measurements in the computational basis. Note that this does not collapse the wave function. Args: indices: Which qubits are measured. ...
[ "Samples", "from", "measurements", "in", "the", "computational", "basis", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/sim/xmon_stepper.py#L363-L385
[ "def", "sample_measurements", "(", "self", ",", "indices", ":", "List", "[", "int", "]", ",", "repetitions", ":", "int", "=", "1", ")", "->", "List", "[", "List", "[", "bool", "]", "]", ":", "# Stepper uses little endian while sample_state uses big endian.", "...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
fswap
Decompose the Fermionic SWAP gate into two single-qubit gates and one iSWAP gate. Args: p: the id of the first qubit q: the id of the second qubit
examples/bcs_mean_field.py
def fswap(p, q): """Decompose the Fermionic SWAP gate into two single-qubit gates and one iSWAP gate. Args: p: the id of the first qubit q: the id of the second qubit """ yield cirq.ISWAP(q, p), cirq.Z(p) ** 1.5 yield cirq.Z(q) ** 1.5
def fswap(p, q): """Decompose the Fermionic SWAP gate into two single-qubit gates and one iSWAP gate. Args: p: the id of the first qubit q: the id of the second qubit """ yield cirq.ISWAP(q, p), cirq.Z(p) ** 1.5 yield cirq.Z(q) ** 1.5
[ "Decompose", "the", "Fermionic", "SWAP", "gate", "into", "two", "single", "-", "qubit", "gates", "and", "one", "iSWAP", "gate", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/examples/bcs_mean_field.py#L191-L201
[ "def", "fswap", "(", "p", ",", "q", ")", ":", "yield", "cirq", ".", "ISWAP", "(", "q", ",", "p", ")", ",", "cirq", ".", "Z", "(", "p", ")", "**", "1.5", "yield", "cirq", ".", "Z", "(", "q", ")", "**", "1.5" ]
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
bogoliubov_trans
r"""The 2-mode Bogoliubov transformation is mapped to two-qubit operations. We use the identity X S^\dag X S X = Y X S^\dag Y S X = X to transform the Hamiltonian XY+YX to XX+YY type. The time evolution of the XX + YY Hamiltonian can be expressed as a power of the iSWAP gate. Args: p: the fi...
examples/bcs_mean_field.py
def bogoliubov_trans(p, q, theta): r"""The 2-mode Bogoliubov transformation is mapped to two-qubit operations. We use the identity X S^\dag X S X = Y X S^\dag Y S X = X to transform the Hamiltonian XY+YX to XX+YY type. The time evolution of the XX + YY Hamiltonian can be expressed as a power of the i...
def bogoliubov_trans(p, q, theta): r"""The 2-mode Bogoliubov transformation is mapped to two-qubit operations. We use the identity X S^\dag X S X = Y X S^\dag Y S X = X to transform the Hamiltonian XY+YX to XX+YY type. The time evolution of the XX + YY Hamiltonian can be expressed as a power of the i...
[ "r", "The", "2", "-", "mode", "Bogoliubov", "transformation", "is", "mapped", "to", "two", "-", "qubit", "operations", ".", "We", "use", "the", "identity", "X", "S^", "\\", "dag", "X", "S", "X", "=", "Y", "X", "S^", "\\", "dag", "Y", "S", "X", "=...
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/examples/bcs_mean_field.py#L204-L226
[ "def", "bogoliubov_trans", "(", "p", ",", "q", ",", "theta", ")", ":", "# The iSWAP gate corresponds to evolve under the Hamiltonian XX+YY for", "# time -pi/4.", "expo", "=", "-", "4", "*", "theta", "/", "np", ".", "pi", "yield", "cirq", ".", "X", "(", "p", ")...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
fermi_fourier_trans_2
The 2-mode fermionic Fourier transformation can be implemented straightforwardly by the √iSWAP gate. The √iSWAP gate can be readily implemented with the gmon qubits using the XX + YY Hamiltonian. The matrix representation of the 2-qubit fermionic Fourier transformation is: [1 0 0 0], [0 ...
examples/bcs_mean_field.py
def fermi_fourier_trans_2(p, q): """The 2-mode fermionic Fourier transformation can be implemented straightforwardly by the √iSWAP gate. The √iSWAP gate can be readily implemented with the gmon qubits using the XX + YY Hamiltonian. The matrix representation of the 2-qubit fermionic Fourier transformatio...
def fermi_fourier_trans_2(p, q): """The 2-mode fermionic Fourier transformation can be implemented straightforwardly by the √iSWAP gate. The √iSWAP gate can be readily implemented with the gmon qubits using the XX + YY Hamiltonian. The matrix representation of the 2-qubit fermionic Fourier transformatio...
[ "The", "2", "-", "mode", "fermionic", "Fourier", "transformation", "can", "be", "implemented", "straightforwardly", "by", "the", "√iSWAP", "gate", ".", "The", "√iSWAP", "gate", "can", "be", "readily", "implemented", "with", "the", "gmon", "qubits", "using", "t...
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/examples/bcs_mean_field.py#L229-L251
[ "def", "fermi_fourier_trans_2", "(", "p", ",", "q", ")", ":", "yield", "cirq", ".", "Z", "(", "p", ")", "**", "1.5", "yield", "cirq", ".", "ISWAP", "(", "q", ",", "p", ")", "**", "0.5", "yield", "cirq", ".", "Z", "(", "p", ")", "**", "1.5" ]
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
fermi_fourier_trans_inverse_4
The reverse fermionic Fourier transformation implemented on 4 qubits on a line, which maps the momentum picture to the position picture. Using the fast Fourier transformation algorithm, the circuit can be decomposed into 2-mode fermionic Fourier transformation, the fermionic SWAP gates, and single-qubit...
examples/bcs_mean_field.py
def fermi_fourier_trans_inverse_4(qubits): """The reverse fermionic Fourier transformation implemented on 4 qubits on a line, which maps the momentum picture to the position picture. Using the fast Fourier transformation algorithm, the circuit can be decomposed into 2-mode fermionic Fourier transformati...
def fermi_fourier_trans_inverse_4(qubits): """The reverse fermionic Fourier transformation implemented on 4 qubits on a line, which maps the momentum picture to the position picture. Using the fast Fourier transformation algorithm, the circuit can be decomposed into 2-mode fermionic Fourier transformati...
[ "The", "reverse", "fermionic", "Fourier", "transformation", "implemented", "on", "4", "qubits", "on", "a", "line", "which", "maps", "the", "momentum", "picture", "to", "the", "position", "picture", ".", "Using", "the", "fast", "Fourier", "transformation", "algor...
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/examples/bcs_mean_field.py#L254-L272
[ "def", "fermi_fourier_trans_inverse_4", "(", "qubits", ")", ":", "yield", "fswap", "(", "qubits", "[", "1", "]", ",", "qubits", "[", "2", "]", ")", ",", "yield", "fermi_fourier_trans_2", "(", "qubits", "[", "0", "]", ",", "qubits", "[", "1", "]", ")", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
fermi_fourier_trans_inverse_conjugate_4
We will need to map the momentum states in the reversed order for spin-down states to the position picture. This transformation can be simply implemented the complex conjugate of the former one. We only need to change the S gate to S* = S ** 3. Args: qubits: list of four qubits
examples/bcs_mean_field.py
def fermi_fourier_trans_inverse_conjugate_4(qubits): """We will need to map the momentum states in the reversed order for spin-down states to the position picture. This transformation can be simply implemented the complex conjugate of the former one. We only need to change the S gate to S* = S ** 3. ...
def fermi_fourier_trans_inverse_conjugate_4(qubits): """We will need to map the momentum states in the reversed order for spin-down states to the position picture. This transformation can be simply implemented the complex conjugate of the former one. We only need to change the S gate to S* = S ** 3. ...
[ "We", "will", "need", "to", "map", "the", "momentum", "states", "in", "the", "reversed", "order", "for", "spin", "-", "down", "states", "to", "the", "position", "picture", ".", "This", "transformation", "can", "be", "simply", "implemented", "the", "complex",...
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/examples/bcs_mean_field.py#L275-L292
[ "def", "fermi_fourier_trans_inverse_conjugate_4", "(", "qubits", ")", ":", "yield", "fswap", "(", "qubits", "[", "1", "]", ",", "qubits", "[", "2", "]", ")", ",", "yield", "fermi_fourier_trans_2", "(", "qubits", "[", "0", "]", ",", "qubits", "[", "1", "]...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
bcs_parameters
Generate the parameters for the BCS ground state, i.e., the superconducting gap and the rotational angles in the Bogoliubov transformation. Args: n_site: the number of sites in the Hubbard model n_fermi: the number of fermions u: the interaction strength t: the tunneling st...
examples/bcs_mean_field.py
def bcs_parameters(n_site, n_fermi, u, t) : """Generate the parameters for the BCS ground state, i.e., the superconducting gap and the rotational angles in the Bogoliubov transformation. Args: n_site: the number of sites in the Hubbard model n_fermi: the number of fermions u: t...
def bcs_parameters(n_site, n_fermi, u, t) : """Generate the parameters for the BCS ground state, i.e., the superconducting gap and the rotational angles in the Bogoliubov transformation. Args: n_site: the number of sites in the Hubbard model n_fermi: the number of fermions u: t...
[ "Generate", "the", "parameters", "for", "the", "BCS", "ground", "state", "i", ".", "e", ".", "the", "superconducting", "gap", "and", "the", "rotational", "angles", "in", "the", "Bogoliubov", "transformation", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/examples/bcs_mean_field.py#L295-L338
[ "def", "bcs_parameters", "(", "n_site", ",", "n_fermi", ",", "u", ",", "t", ")", ":", "# The wave numbers satisfy the periodic boundary condition.", "wave_num", "=", "np", ".", "linspace", "(", "0", ",", "1", ",", "n_site", ",", "endpoint", "=", "False", ")", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
bloch_vector_from_state_vector
Returns the bloch vector of a qubit. Calculates the bloch vector of the qubit at index in the wavefunction given by state, assuming state follows the standard Kronecker convention of numpy.kron. Args: state: A sequence representing a wave function in which the ordering mapping to q...
cirq/sim/wave_function.py
def bloch_vector_from_state_vector(state: Sequence, index: int) -> np.ndarray: """Returns the bloch vector of a qubit. Calculates the bloch vector of the qubit at index in the wavefunction given by state, assuming state follows the standard Kronecker convention of numpy.kron. Args: state: ...
def bloch_vector_from_state_vector(state: Sequence, index: int) -> np.ndarray: """Returns the bloch vector of a qubit. Calculates the bloch vector of the qubit at index in the wavefunction given by state, assuming state follows the standard Kronecker convention of numpy.kron. Args: state: ...
[ "Returns", "the", "bloch", "vector", "of", "a", "qubit", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/sim/wave_function.py#L141-L170
[ "def", "bloch_vector_from_state_vector", "(", "state", ":", "Sequence", ",", "index", ":", "int", ")", "->", "np", ".", "ndarray", ":", "rho", "=", "density_matrix_from_state_vector", "(", "state", ",", "[", "index", "]", ")", "v", "=", "np", ".", "zeros",...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
density_matrix_from_state_vector
r"""Returns the density matrix of the wavefunction. Calculate the density matrix for the system on the given qubit indices, with the qubits not in indices that are present in state traced out. If indices is None the full density matrix for state is returned. We assume state follows the standard Kroneck...
cirq/sim/wave_function.py
def density_matrix_from_state_vector( state: Sequence, indices: Iterable[int] = None ) -> np.ndarray: r"""Returns the density matrix of the wavefunction. Calculate the density matrix for the system on the given qubit indices, with the qubits not in indices that are present in state traced out. ...
def density_matrix_from_state_vector( state: Sequence, indices: Iterable[int] = None ) -> np.ndarray: r"""Returns the density matrix of the wavefunction. Calculate the density matrix for the system on the given qubit indices, with the qubits not in indices that are present in state traced out. ...
[ "r", "Returns", "the", "density", "matrix", "of", "the", "wavefunction", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/sim/wave_function.py#L173-L234
[ "def", "density_matrix_from_state_vector", "(", "state", ":", "Sequence", ",", "indices", ":", "Iterable", "[", "int", "]", "=", "None", ")", "->", "np", ".", "ndarray", ":", "n_qubits", "=", "_validate_num_qubits", "(", "state", ")", "if", "indices", "is", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
dirac_notation
Returns the wavefunction as a string in Dirac notation. For example: state = np.array([1/np.sqrt(2), 1/np.sqrt(2)], dtype=np.complex64) print(dirac_notation(state)) -> 0.71|0⟩ + 0.71|1⟩ Args: state: A sequence representing a wave function in which the ordering mapping to q...
cirq/sim/wave_function.py
def dirac_notation(state: Sequence, decimals: int=2) -> str: """Returns the wavefunction as a string in Dirac notation. For example: state = np.array([1/np.sqrt(2), 1/np.sqrt(2)], dtype=np.complex64) print(dirac_notation(state)) -> 0.71|0⟩ + 0.71|1⟩ Args: state: A sequence represe...
def dirac_notation(state: Sequence, decimals: int=2) -> str: """Returns the wavefunction as a string in Dirac notation. For example: state = np.array([1/np.sqrt(2), 1/np.sqrt(2)], dtype=np.complex64) print(dirac_notation(state)) -> 0.71|0⟩ + 0.71|1⟩ Args: state: A sequence represe...
[ "Returns", "the", "wavefunction", "as", "a", "string", "in", "Dirac", "notation", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/sim/wave_function.py#L237-L278
[ "def", "dirac_notation", "(", "state", ":", "Sequence", ",", "decimals", ":", "int", "=", "2", ")", "->", "str", ":", "perm_list", "=", "[", "\"\"", ".", "join", "(", "seq", ")", "for", "seq", "in", "itertools", ".", "product", "(", "\"01\"", ",", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
to_valid_state_vector
Verifies the state_rep is valid and converts it to ndarray form. This method is used to support passing in an integer representing a computational basis state or a full wave function as a representation of a state. Args: state_rep: If an int, the state returned is the state corresponding to ...
cirq/sim/wave_function.py
def to_valid_state_vector(state_rep: Union[int, np.ndarray], num_qubits: int, dtype: Type[np.number] = np.complex64) -> np.ndarray: """Verifies the state_rep is valid and converts it to ndarray form. This method is used to support passing in an integer repres...
def to_valid_state_vector(state_rep: Union[int, np.ndarray], num_qubits: int, dtype: Type[np.number] = np.complex64) -> np.ndarray: """Verifies the state_rep is valid and converts it to ndarray form. This method is used to support passing in an integer repres...
[ "Verifies", "the", "state_rep", "is", "valid", "and", "converts", "it", "to", "ndarray", "form", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/sim/wave_function.py#L281-L329
[ "def", "to_valid_state_vector", "(", "state_rep", ":", "Union", "[", "int", ",", "np", ".", "ndarray", "]", ",", "num_qubits", ":", "int", ",", "dtype", ":", "Type", "[", "np", ".", "number", "]", "=", "np", ".", "complex64", ")", "->", "np", ".", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
validate_normalized_state
Validates that the given state is a valid wave function.
cirq/sim/wave_function.py
def validate_normalized_state(state: np.ndarray, num_qubits: int, dtype: Type[np.number] = np.complex64) -> None: """Validates that the given state is a valid wave function.""" if state.size != 1 << num_qubits: raise ValueError( 'St...
def validate_normalized_state(state: np.ndarray, num_qubits: int, dtype: Type[np.number] = np.complex64) -> None: """Validates that the given state is a valid wave function.""" if state.size != 1 << num_qubits: raise ValueError( 'St...
[ "Validates", "that", "the", "given", "state", "is", "a", "valid", "wave", "function", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/sim/wave_function.py#L332-L346
[ "def", "validate_normalized_state", "(", "state", ":", "np", ".", "ndarray", ",", "num_qubits", ":", "int", ",", "dtype", ":", "Type", "[", "np", ".", "number", "]", "=", "np", ".", "complex64", ")", "->", "None", ":", "if", "state", ".", "size", "!=...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
sample_state_vector
Samples repeatedly from measurements in the computational basis. Note that this does not modify the passed in state. Args: state: The multi-qubit wavefunction to be sampled. This is an array of 2 to the power of the number of qubit complex numbers, and so state must be of size ...
cirq/sim/wave_function.py
def sample_state_vector(state: np.ndarray, indices: List[int], repetitions: int=1) -> np.ndarray: """Samples repeatedly from measurements in the computational basis. Note that this does not modify the passed in state. Args: state: The multi-qubit wav...
def sample_state_vector(state: np.ndarray, indices: List[int], repetitions: int=1) -> np.ndarray: """Samples repeatedly from measurements in the computational basis. Note that this does not modify the passed in state. Args: state: The multi-qubit wav...
[ "Samples", "repeatedly", "from", "measurements", "in", "the", "computational", "basis", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/sim/wave_function.py#L349-L396
[ "def", "sample_state_vector", "(", "state", ":", "np", ".", "ndarray", ",", "indices", ":", "List", "[", "int", "]", ",", "repetitions", ":", "int", "=", "1", ")", "->", "np", ".", "ndarray", ":", "if", "repetitions", "<", "0", ":", "raise", "ValueEr...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
_probs
Returns the probabilities for a measurement on the given indices.
cirq/sim/wave_function.py
def _probs(state: np.ndarray, indices: List[int], num_qubits: int) -> List[float]: """Returns the probabilities for a measurement on the given indices.""" # Tensor of squared amplitudes, shaped a rank [2, 2, .., 2] tensor. tensor = np.reshape(state, [2] * num_qubits) # Calculate the probabil...
def _probs(state: np.ndarray, indices: List[int], num_qubits: int) -> List[float]: """Returns the probabilities for a measurement on the given indices.""" # Tensor of squared amplitudes, shaped a rank [2, 2, .., 2] tensor. tensor = np.reshape(state, [2] * num_qubits) # Calculate the probabil...
[ "Returns", "the", "probabilities", "for", "a", "measurement", "on", "the", "given", "indices", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/sim/wave_function.py#L476-L490
[ "def", "_probs", "(", "state", ":", "np", ".", "ndarray", ",", "indices", ":", "List", "[", "int", "]", ",", "num_qubits", ":", "int", ")", "->", "List", "[", "float", "]", ":", "# Tensor of squared amplitudes, shaped a rank [2, 2, .., 2] tensor.", "tensor", "...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
_validate_num_qubits
Validates that state's size is a power of 2, returning number of qubits.
cirq/sim/wave_function.py
def _validate_num_qubits(state: np.ndarray) -> int: """Validates that state's size is a power of 2, returning number of qubits. """ size = state.size if size & (size - 1): raise ValueError('state.size ({}) is not a power of two.'.format(size)) return size.bit_length() - 1
def _validate_num_qubits(state: np.ndarray) -> int: """Validates that state's size is a power of 2, returning number of qubits. """ size = state.size if size & (size - 1): raise ValueError('state.size ({}) is not a power of two.'.format(size)) return size.bit_length() - 1
[ "Validates", "that", "state", "s", "size", "is", "a", "power", "of", "2", "returning", "number", "of", "qubits", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/sim/wave_function.py#L493-L499
[ "def", "_validate_num_qubits", "(", "state", ":", "np", ".", "ndarray", ")", "->", "int", ":", "size", "=", "state", ".", "size", "if", "size", "&", "(", "size", "-", "1", ")", ":", "raise", "ValueError", "(", "'state.size ({}) is not a power of two.'", "....
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
_validate_indices
Validates that the indices have values within range of num_qubits.
cirq/sim/wave_function.py
def _validate_indices(num_qubits: int, indices: List[int]) -> None: """Validates that the indices have values within range of num_qubits.""" if any(index < 0 for index in indices): raise IndexError('Negative index in indices: {}'.format(indices)) if any(index >= num_qubits for index in indices): ...
def _validate_indices(num_qubits: int, indices: List[int]) -> None: """Validates that the indices have values within range of num_qubits.""" if any(index < 0 for index in indices): raise IndexError('Negative index in indices: {}'.format(indices)) if any(index >= num_qubits for index in indices): ...
[ "Validates", "that", "the", "indices", "have", "values", "within", "range", "of", "num_qubits", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/sim/wave_function.py#L502-L508
[ "def", "_validate_indices", "(", "num_qubits", ":", "int", ",", "indices", ":", "List", "[", "int", "]", ")", "->", "None", ":", "if", "any", "(", "index", "<", "0", "for", "index", "in", "indices", ")", ":", "raise", "IndexError", "(", "'Negative inde...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
StateVectorMixin.density_matrix_of
r"""Returns the density matrix of the state. Calculate the density matrix for the system on the list, qubits. Any qubits not in the list that are present in self.state_vector() will be traced out. If qubits is None the full density matrix for self.state_vector() is returned, given self....
cirq/sim/wave_function.py
def density_matrix_of(self, qubits: List[ops.Qid] = None) -> np.ndarray: r"""Returns the density matrix of the state. Calculate the density matrix for the system on the list, qubits. Any qubits not in the list that are present in self.state_vector() will be traced out. If qubits is None...
def density_matrix_of(self, qubits: List[ops.Qid] = None) -> np.ndarray: r"""Returns the density matrix of the state. Calculate the density matrix for the system on the list, qubits. Any qubits not in the list that are present in self.state_vector() will be traced out. If qubits is None...
[ "r", "Returns", "the", "density", "matrix", "of", "the", "state", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/sim/wave_function.py#L82-L116
[ "def", "density_matrix_of", "(", "self", ",", "qubits", ":", "List", "[", "ops", ".", "Qid", "]", "=", "None", ")", "->", "np", ".", "ndarray", ":", "return", "density_matrix_from_state_vector", "(", "self", ".", "state_vector", "(", ")", ",", "[", "self...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
StateVectorMixin.bloch_vector_of
Returns the bloch vector of a qubit in the state. Calculates the bloch vector of the given qubit in the state given by self.state_vector(), given that self.state_vector() follows the standard Kronecker convention of numpy.kron. Args: qubit: qubit who's bloch vector ...
cirq/sim/wave_function.py
def bloch_vector_of(self, qubit: ops.Qid) -> np.ndarray: """Returns the bloch vector of a qubit in the state. Calculates the bloch vector of the given qubit in the state given by self.state_vector(), given that self.state_vector() follows the standard Kronecker convention of num...
def bloch_vector_of(self, qubit: ops.Qid) -> np.ndarray: """Returns the bloch vector of a qubit in the state. Calculates the bloch vector of the given qubit in the state given by self.state_vector(), given that self.state_vector() follows the standard Kronecker convention of num...
[ "Returns", "the", "bloch", "vector", "of", "a", "qubit", "in", "the", "state", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/sim/wave_function.py#L118-L138
[ "def", "bloch_vector_of", "(", "self", ",", "qubit", ":", "ops", ".", "Qid", ")", "->", "np", ".", "ndarray", ":", "return", "bloch_vector_from_state_vector", "(", "self", ".", "state_vector", "(", ")", ",", "self", ".", "qubit_map", "[", "qubit", "]", "...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
get_acquaintance_size
The maximum number of qubits to be acquainted with each other.
cirq/contrib/acquaintance/devices.py
def get_acquaintance_size(obj: Union[circuits.Circuit, ops.Operation]) -> int: """The maximum number of qubits to be acquainted with each other.""" if isinstance(obj, circuits.Circuit): if not is_acquaintance_strategy(obj): raise TypeError('not is_acquaintance_strategy(circuit)') ret...
def get_acquaintance_size(obj: Union[circuits.Circuit, ops.Operation]) -> int: """The maximum number of qubits to be acquainted with each other.""" if isinstance(obj, circuits.Circuit): if not is_acquaintance_strategy(obj): raise TypeError('not is_acquaintance_strategy(circuit)') ret...
[ "The", "maximum", "number", "of", "qubits", "to", "be", "acquainted", "with", "each", "other", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/contrib/acquaintance/devices.py#L64-L87
[ "def", "get_acquaintance_size", "(", "obj", ":", "Union", "[", "circuits", ".", "Circuit", ",", "ops", ".", "Operation", "]", ")", "->", "int", ":", "if", "isinstance", "(", "obj", ",", "circuits", ".", "Circuit", ")", ":", "if", "not", "is_acquaintance_...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
GreedySequenceSearch.get_or_search
Starts the search or gives previously calculated sequence. Returns: The linear qubit sequence found.
cirq/google/line/placement/greedy.py
def get_or_search(self) -> List[GridQubit]: """Starts the search or gives previously calculated sequence. Returns: The linear qubit sequence found. """ if not self._sequence: self._sequence = self._find_sequence() return self._sequence
def get_or_search(self) -> List[GridQubit]: """Starts the search or gives previously calculated sequence. Returns: The linear qubit sequence found. """ if not self._sequence: self._sequence = self._find_sequence() return self._sequence
[ "Starts", "the", "search", "or", "gives", "previously", "calculated", "sequence", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/line/placement/greedy.py#L58-L66
[ "def", "get_or_search", "(", "self", ")", "->", "List", "[", "GridQubit", "]", ":", "if", "not", "self", ".", "_sequence", ":", "self", ".", "_sequence", "=", "self", ".", "_find_sequence", "(", ")", "return", "self", ".", "_sequence" ]
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
GreedySequenceSearch._find_sequence
Looks for a sequence starting at a given qubit. Search is issued twice from the starting qubit, so that longest possible sequence is found. Starting qubit might not be the first qubit on the returned sequence. Returns: The longest sequence found by this method.
cirq/google/line/placement/greedy.py
def _find_sequence(self) -> List[GridQubit]: """Looks for a sequence starting at a given qubit. Search is issued twice from the starting qubit, so that longest possible sequence is found. Starting qubit might not be the first qubit on the returned sequence. Returns: ...
def _find_sequence(self) -> List[GridQubit]: """Looks for a sequence starting at a given qubit. Search is issued twice from the starting qubit, so that longest possible sequence is found. Starting qubit might not be the first qubit on the returned sequence. Returns: ...
[ "Looks", "for", "a", "sequence", "starting", "at", "a", "given", "qubit", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/line/placement/greedy.py#L85-L103
[ "def", "_find_sequence", "(", "self", ")", "->", "List", "[", "GridQubit", "]", ":", "# Run the first pass and drop starting qubit from the found sequence.", "tail", "=", "self", ".", "_sequence_search", "(", "self", ".", "_start", ",", "[", "]", ")", "tail", ".",...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
GreedySequenceSearch._sequence_search
Search for the continuous linear sequence from the given qubit. This method is called twice for the same starting qubit, so that sequences that begin and end on this qubit are searched for. Args: start: The first qubit, where search should be trigerred from. current: Pr...
cirq/google/line/placement/greedy.py
def _sequence_search(self, start: GridQubit, current: List[GridQubit]) -> List[GridQubit]: """Search for the continuous linear sequence from the given qubit. This method is called twice for the same starting qubit, so that sequences that begin and end on this qubit are ...
def _sequence_search(self, start: GridQubit, current: List[GridQubit]) -> List[GridQubit]: """Search for the continuous linear sequence from the given qubit. This method is called twice for the same starting qubit, so that sequences that begin and end on this qubit are ...
[ "Search", "for", "the", "continuous", "linear", "sequence", "from", "the", "given", "qubit", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/line/placement/greedy.py#L105-L130
[ "def", "_sequence_search", "(", "self", ",", "start", ":", "GridQubit", ",", "current", ":", "List", "[", "GridQubit", "]", ")", "->", "List", "[", "GridQubit", "]", ":", "used", "=", "set", "(", "current", ")", "seq", "=", "[", "]", "n", "=", "sta...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
GreedySequenceSearch._expand_sequence
Tries to expand given sequence with more qubits. Args: seq: Linear sequence of qubits. Returns: New continuous linear sequence which contains all the qubits from seq and possibly new qubits inserted in between.
cirq/google/line/placement/greedy.py
def _expand_sequence(self, seq: List[GridQubit]) -> List[GridQubit]: """Tries to expand given sequence with more qubits. Args: seq: Linear sequence of qubits. Returns: New continuous linear sequence which contains all the qubits from seq and possibly new qub...
def _expand_sequence(self, seq: List[GridQubit]) -> List[GridQubit]: """Tries to expand given sequence with more qubits. Args: seq: Linear sequence of qubits. Returns: New continuous linear sequence which contains all the qubits from seq and possibly new qub...
[ "Tries", "to", "expand", "given", "sequence", "with", "more", "qubits", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/line/placement/greedy.py#L132-L149
[ "def", "_expand_sequence", "(", "self", ",", "seq", ":", "List", "[", "GridQubit", "]", ")", "->", "List", "[", "GridQubit", "]", ":", "i", "=", "1", "while", "i", "<", "len", "(", "seq", ")", ":", "path", "=", "self", ".", "_find_path_between", "(...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
GreedySequenceSearch._find_path_between
Searches for continuous sequence between two qubits. This method runs two BFS algorithms in parallel (alternating variable s in each iteration); the first one starting from qubit p, and the second one starting from qubit q. If at some point a qubit reachable from p is found to be on the...
cirq/google/line/placement/greedy.py
def _find_path_between(self, p: GridQubit, q: GridQubit, used: Set[GridQubit]) -> Optional[List[GridQubit]]: """Searches for continuous sequence between two qubits. This method runs two BFS algorithms in parallel (alternating variable s in each iteration); the first o...
def _find_path_between(self, p: GridQubit, q: GridQubit, used: Set[GridQubit]) -> Optional[List[GridQubit]]: """Searches for continuous sequence between two qubits. This method runs two BFS algorithms in parallel (alternating variable s in each iteration); the first o...
[ "Searches", "for", "continuous", "sequence", "between", "two", "qubits", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/line/placement/greedy.py#L151-L203
[ "def", "_find_path_between", "(", "self", ",", "p", ":", "GridQubit", ",", "q", ":", "GridQubit", ",", "used", ":", "Set", "[", "GridQubit", "]", ")", "->", "Optional", "[", "List", "[", "GridQubit", "]", "]", ":", "def", "assemble_path", "(", "n", "...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
_PickLargestArea._collect_unused
Lists all the qubits that are reachable from given qubit. Args: start: The first qubit for which connectivity should be calculated. Might be a member of used set. used: Already used qubits, which cannot be used during the collection. Returns...
cirq/google/line/placement/greedy.py
def _collect_unused(self, start: GridQubit, used: Set[GridQubit]) -> Set[GridQubit]: """Lists all the qubits that are reachable from given qubit. Args: start: The first qubit for which connectivity should be calculated. Might be a member of used se...
def _collect_unused(self, start: GridQubit, used: Set[GridQubit]) -> Set[GridQubit]: """Lists all the qubits that are reachable from given qubit. Args: start: The first qubit for which connectivity should be calculated. Might be a member of used se...
[ "Lists", "all", "the", "qubits", "that", "are", "reachable", "from", "given", "qubit", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/line/placement/greedy.py#L258-L281
[ "def", "_collect_unused", "(", "self", ",", "start", ":", "GridQubit", ",", "used", ":", "Set", "[", "GridQubit", "]", ")", "->", "Set", "[", "GridQubit", "]", ":", "def", "collect", "(", "n", ":", "GridQubit", ",", "visited", ":", "Set", "[", "GridQ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
GreedySequenceSearchStrategy.place_line
Runs line sequence search. Args: device: Chip description. length: Required line length. Returns: Linear sequences found on the chip. Raises: ValueError: If search algorithm passed on initialization is not recognized.
cirq/google/line/placement/greedy.py
def place_line(self, device: 'cirq.google.XmonDevice', length: int) -> GridQubitLineTuple: """Runs line sequence search. Args: device: Chip description. length: Required line length. Returns: Linear sequences found on th...
def place_line(self, device: 'cirq.google.XmonDevice', length: int) -> GridQubitLineTuple: """Runs line sequence search. Args: device: Chip description. length: Required line length. Returns: Linear sequences found on th...
[ "Runs", "line", "sequence", "search", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/line/placement/greedy.py#L301-L344
[ "def", "place_line", "(", "self", ",", "device", ":", "'cirq.google.XmonDevice'", ",", "length", ":", "int", ")", "->", "GridQubitLineTuple", ":", "if", "not", "device", ".", "qubits", ":", "return", "GridQubitLineTuple", "(", ")", "start", "=", "min", "(", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
trace_distance_bound
Returns a maximum on the trace distance between this effect's input and output. This method makes use of the effect's `_trace_distance_bound_` method to determine the maximum bound on the trace difference between before and after the effect. Args: val: The effect of which the bound should be c...
cirq/protocols/trace_distance_bound.py
def trace_distance_bound(val: Any) -> float: """Returns a maximum on the trace distance between this effect's input and output. This method makes use of the effect's `_trace_distance_bound_` method to determine the maximum bound on the trace difference between before and after the effect. Args: ...
def trace_distance_bound(val: Any) -> float: """Returns a maximum on the trace distance between this effect's input and output. This method makes use of the effect's `_trace_distance_bound_` method to determine the maximum bound on the trace difference between before and after the effect. Args: ...
[ "Returns", "a", "maximum", "on", "the", "trace", "distance", "between", "this", "effect", "s", "input", "and", "output", ".", "This", "method", "makes", "use", "of", "the", "effect", "s", "_trace_distance_bound_", "method", "to", "determine", "the", "maximum",...
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/protocols/trace_distance_bound.py#L41-L62
[ "def", "trace_distance_bound", "(", "val", ":", "Any", ")", "->", "float", ":", "getter", "=", "getattr", "(", "val", ",", "'_trace_distance_bound_'", ",", "None", ")", "result", "=", "NotImplemented", "if", "getter", "is", "None", "else", "getter", "(", "...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
Moment.operates_on
Determines if the moment has operations touching the given qubits. Args: qubits: The qubits that may or may not be touched by operations. Returns: Whether this moment has operations involving the qubits.
cirq/ops/moment.py
def operates_on(self, qubits: Iterable[raw_types.Qid]) -> bool: """Determines if the moment has operations touching the given qubits. Args: qubits: The qubits that may or may not be touched by operations. Returns: Whether this moment has operations involving the qubits....
def operates_on(self, qubits: Iterable[raw_types.Qid]) -> bool: """Determines if the moment has operations touching the given qubits. Args: qubits: The qubits that may or may not be touched by operations. Returns: Whether this moment has operations involving the qubits....
[ "Determines", "if", "the", "moment", "has", "operations", "touching", "the", "given", "qubits", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/ops/moment.py#L68-L77
[ "def", "operates_on", "(", "self", ",", "qubits", ":", "Iterable", "[", "raw_types", ".", "Qid", "]", ")", "->", "bool", ":", "return", "any", "(", "q", "in", "qubits", "for", "q", "in", "self", ".", "qubits", ")" ]
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
Moment.without_operations_touching
Returns an equal moment, but without ops on the given qubits. Args: qubits: Operations that touch these will be removed. Returns: The new moment.
cirq/ops/moment.py
def without_operations_touching(self, qubits: Iterable[raw_types.Qid]): """Returns an equal moment, but without ops on the given qubits. Args: qubits: Operations that touch these will be removed. Returns: The new moment. """ qubits = frozenset(qubits) ...
def without_operations_touching(self, qubits: Iterable[raw_types.Qid]): """Returns an equal moment, but without ops on the given qubits. Args: qubits: Operations that touch these will be removed. Returns: The new moment. """ qubits = frozenset(qubits) ...
[ "Returns", "an", "equal", "moment", "but", "without", "ops", "on", "the", "given", "qubits", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/ops/moment.py#L90-L104
[ "def", "without_operations_touching", "(", "self", ",", "qubits", ":", "Iterable", "[", "raw_types", ".", "Qid", "]", ")", ":", "qubits", "=", "frozenset", "(", "qubits", ")", "if", "not", "self", ".", "operates_on", "(", "qubits", ")", ":", "return", "s...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
Moment._approx_eq_
See `cirq.protocols.SupportsApproximateEquality`.
cirq/ops/moment.py
def _approx_eq_(self, other: Any, atol: Union[int, float]) -> bool: """See `cirq.protocols.SupportsApproximateEquality`.""" if not isinstance(other, type(self)): return NotImplemented return approx_eq(self.operations, other.operations, atol=atol)
def _approx_eq_(self, other: Any, atol: Union[int, float]) -> bool: """See `cirq.protocols.SupportsApproximateEquality`.""" if not isinstance(other, type(self)): return NotImplemented return approx_eq(self.operations, other.operations, atol=atol)
[ "See", "cirq", ".", "protocols", ".", "SupportsApproximateEquality", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/ops/moment.py#L117-L121
[ "def", "_approx_eq_", "(", "self", ",", "other", ":", "Any", ",", "atol", ":", "Union", "[", "int", ",", "float", "]", ")", "->", "bool", ":", "if", "not", "isinstance", "(", "other", ",", "type", "(", "self", ")", ")", ":", "return", "NotImplement...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
_disjoint_qubits
Returns true only if the operations have qubits in common.
cirq/circuits/circuit_dag.py
def _disjoint_qubits(op1: ops.Operation, op2: ops.Operation) -> bool: """Returns true only if the operations have qubits in common.""" return not set(op1.qubits) & set(op2.qubits)
def _disjoint_qubits(op1: ops.Operation, op2: ops.Operation) -> bool: """Returns true only if the operations have qubits in common.""" return not set(op1.qubits) & set(op2.qubits)
[ "Returns", "true", "only", "if", "the", "operations", "have", "qubits", "in", "common", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/circuits/circuit_dag.py#L49-L51
[ "def", "_disjoint_qubits", "(", "op1", ":", "ops", ".", "Operation", ",", "op2", ":", "ops", ".", "Operation", ")", "->", "bool", ":", "return", "not", "set", "(", "op1", ".", "qubits", ")", "&", "set", "(", "op2", ".", "qubits", ")" ]
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
PointOptimizer.optimization_at
Describes how to change operations near the given location. For example, this method could realize that the given operation is an X gate and that in the very next moment there is a Z gate. It would indicate that they should be combined into a Y gate by returning PointOptimizationSummary...
cirq/circuits/optimization_pass.py
def optimization_at(self, circuit: Circuit, index: int, op: ops.Operation ) -> Optional[PointOptimizationSummary]: """Describes how to change operations near the given location. For example, this method coul...
def optimization_at(self, circuit: Circuit, index: int, op: ops.Operation ) -> Optional[PointOptimizationSummary]: """Describes how to change operations near the given location. For example, this method coul...
[ "Describes", "how", "to", "change", "operations", "near", "the", "given", "location", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/circuits/optimization_pass.py#L93-L115
[ "def", "optimization_at", "(", "self", ",", "circuit", ":", "Circuit", ",", "index", ":", "int", ",", "op", ":", "ops", ".", "Operation", ")", "->", "Optional", "[", "PointOptimizationSummary", "]", ":" ]
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
schedule_to_proto_dicts
Convert a schedule into an iterable of proto dictionaries. Args: schedule: The schedule to convert to a proto dict. Must contain only gates that can be cast to xmon gates. Yields: A proto dictionary corresponding to an Operation proto.
cirq/google/programs.py
def schedule_to_proto_dicts(schedule: Schedule) -> Iterable[Dict]: """Convert a schedule into an iterable of proto dictionaries. Args: schedule: The schedule to convert to a proto dict. Must contain only gates that can be cast to xmon gates. Yields: A proto dictionary correspon...
def schedule_to_proto_dicts(schedule: Schedule) -> Iterable[Dict]: """Convert a schedule into an iterable of proto dictionaries. Args: schedule: The schedule to convert to a proto dict. Must contain only gates that can be cast to xmon gates. Yields: A proto dictionary correspon...
[ "Convert", "a", "schedule", "into", "an", "iterable", "of", "proto", "dictionaries", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/programs.py#L147-L168
[ "def", "schedule_to_proto_dicts", "(", "schedule", ":", "Schedule", ")", "->", "Iterable", "[", "Dict", "]", ":", "last_time_picos", "=", "None", "# type: Optional[int]", "for", "so", "in", "schedule", ".", "scheduled_operations", ":", "op", "=", "gate_to_proto_di...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
schedule_from_proto_dicts
Convert proto dictionaries into a Schedule for the given device.
cirq/google/programs.py
def schedule_from_proto_dicts( device: 'xmon_device.XmonDevice', ops: Iterable[Dict], ) -> Schedule: """Convert proto dictionaries into a Schedule for the given device.""" scheduled_ops = [] last_time_picos = 0 for op in ops: delay_picos = 0 if 'incremental_delay_picoseco...
def schedule_from_proto_dicts( device: 'xmon_device.XmonDevice', ops: Iterable[Dict], ) -> Schedule: """Convert proto dictionaries into a Schedule for the given device.""" scheduled_ops = [] last_time_picos = 0 for op in ops: delay_picos = 0 if 'incremental_delay_picoseco...
[ "Convert", "proto", "dictionaries", "into", "a", "Schedule", "for", "the", "given", "device", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/programs.py#L171-L190
[ "def", "schedule_from_proto_dicts", "(", "device", ":", "'xmon_device.XmonDevice'", ",", "ops", ":", "Iterable", "[", "Dict", "]", ",", ")", "->", "Schedule", ":", "scheduled_ops", "=", "[", "]", "last_time_picos", "=", "0", "for", "op", "in", "ops", ":", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
pack_results
Pack measurement results into a byte string. Args: measurements: A sequence of tuples, one for each measurement, consisting of a string key and an array of boolean data. The data should be a 2-D array indexed by (repetition, qubit_index). All data for all measurements mu...
cirq/google/programs.py
def pack_results(measurements: Sequence[Tuple[str, np.ndarray]]) -> bytes: """Pack measurement results into a byte string. Args: measurements: A sequence of tuples, one for each measurement, consisting of a string key and an array of boolean data. The data should be a 2-D array ...
def pack_results(measurements: Sequence[Tuple[str, np.ndarray]]) -> bytes: """Pack measurement results into a byte string. Args: measurements: A sequence of tuples, one for each measurement, consisting of a string key and an array of boolean data. The data should be a 2-D array ...
[ "Pack", "measurement", "results", "into", "a", "byte", "string", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/programs.py#L193-L232
[ "def", "pack_results", "(", "measurements", ":", "Sequence", "[", "Tuple", "[", "str", ",", "np", ".", "ndarray", "]", "]", ")", "->", "bytes", ":", "if", "not", "measurements", ":", "return", "b''", "shapes", "=", "[", "(", "key", ",", "np", ".", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
unpack_results
Unpack data from a bitstring into individual measurement results. Args: data: Packed measurement results, in the form <rep0><rep1>... where each repetition is <key0_0>..<key0_{size0-1}><key1_0>... with bits packed in little-endian order in each byte. repetitions: number of r...
cirq/google/programs.py
def unpack_results( data: bytes, repetitions: int, key_sizes: Sequence[Tuple[str, int]] ) -> Dict[str, np.ndarray]: """Unpack data from a bitstring into individual measurement results. Args: data: Packed measurement results, in the form <rep0><rep1>... where each rep...
def unpack_results( data: bytes, repetitions: int, key_sizes: Sequence[Tuple[str, int]] ) -> Dict[str, np.ndarray]: """Unpack data from a bitstring into individual measurement results. Args: data: Packed measurement results, in the form <rep0><rep1>... where each rep...
[ "Unpack", "data", "from", "a", "bitstring", "into", "individual", "measurement", "results", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/programs.py#L235-L266
[ "def", "unpack_results", "(", "data", ":", "bytes", ",", "repetitions", ":", "int", ",", "key_sizes", ":", "Sequence", "[", "Tuple", "[", "str", ",", "int", "]", "]", ")", "->", "Dict", "[", "str", ",", "np", ".", "ndarray", "]", ":", "bits_per_rep",...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
is_native_xmon_op
Check if the gate corresponding to an operation is a native xmon gate. Args: op: Input operation. Returns: True if the operation is native to the xmon, false otherwise.
cirq/google/programs.py
def is_native_xmon_op(op: ops.Operation) -> bool: """Check if the gate corresponding to an operation is a native xmon gate. Args: op: Input operation. Returns: True if the operation is native to the xmon, false otherwise. """ return (isinstance(op, ops.GateOperation) and ...
def is_native_xmon_op(op: ops.Operation) -> bool: """Check if the gate corresponding to an operation is a native xmon gate. Args: op: Input operation. Returns: True if the operation is native to the xmon, false otherwise. """ return (isinstance(op, ops.GateOperation) and ...
[ "Check", "if", "the", "gate", "corresponding", "to", "an", "operation", "is", "a", "native", "xmon", "gate", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/programs.py#L269-L279
[ "def", "is_native_xmon_op", "(", "op", ":", "ops", ".", "Operation", ")", "->", "bool", ":", "return", "(", "isinstance", "(", "op", ",", "ops", ".", "GateOperation", ")", "and", "is_native_xmon_gate", "(", "op", ".", "gate", ")", ")" ]
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
is_native_xmon_gate
Check if a gate is a native xmon gate. Args: gate: Input gate. Returns: True if the gate is native to the xmon, false otherwise.
cirq/google/programs.py
def is_native_xmon_gate(gate: ops.Gate) -> bool: """Check if a gate is a native xmon gate. Args: gate: Input gate. Returns: True if the gate is native to the xmon, false otherwise. """ return isinstance(gate, (ops.CZPowGate, ops.MeasurementGate, ...
def is_native_xmon_gate(gate: ops.Gate) -> bool: """Check if a gate is a native xmon gate. Args: gate: Input gate. Returns: True if the gate is native to the xmon, false otherwise. """ return isinstance(gate, (ops.CZPowGate, ops.MeasurementGate, ...
[ "Check", "if", "a", "gate", "is", "a", "native", "xmon", "gate", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/programs.py#L282-L296
[ "def", "is_native_xmon_gate", "(", "gate", ":", "ops", ".", "Gate", ")", "->", "bool", ":", "return", "isinstance", "(", "gate", ",", "(", "ops", ".", "CZPowGate", ",", "ops", ".", "MeasurementGate", ",", "ops", ".", "PhasedXPowGate", ",", "ops", ".", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
xmon_op_from_proto_dict
Convert the proto dictionary to the corresponding operation. See protos in api/google/v1 for specification of the protos. Args: proto_dict: Dictionary representing the proto. Keys are always strings, but values may be types correspond to a raw proto type or another dictionary (...
cirq/google/programs.py
def xmon_op_from_proto_dict(proto_dict: Dict) -> ops.Operation: """Convert the proto dictionary to the corresponding operation. See protos in api/google/v1 for specification of the protos. Args: proto_dict: Dictionary representing the proto. Keys are always strings, but values may be t...
def xmon_op_from_proto_dict(proto_dict: Dict) -> ops.Operation: """Convert the proto dictionary to the corresponding operation. See protos in api/google/v1 for specification of the protos. Args: proto_dict: Dictionary representing the proto. Keys are always strings, but values may be t...
[ "Convert", "the", "proto", "dictionary", "to", "the", "corresponding", "operation", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/programs.py#L299-L356
[ "def", "xmon_op_from_proto_dict", "(", "proto_dict", ":", "Dict", ")", "->", "ops", ".", "Operation", ":", "def", "raise_missing_fields", "(", "gate_name", ":", "str", ")", ":", "raise", "ValueError", "(", "'{} missing required fields: {}'", ".", "format", "(", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
apply_unitary
High performance left-multiplication of a unitary effect onto a tensor. If `unitary_value` defines an `_apply_unitary_` method, that method will be used to apply `unitary_value`'s unitary effect to the target tensor. Otherwise, if `unitary_value` defines a `_unitary_` method, its unitary matrix will be...
cirq/protocols/apply_unitary.py
def apply_unitary(unitary_value: Any, args: ApplyUnitaryArgs, default: TDefault = RaiseTypeErrorIfNotProvided ) -> Union[np.ndarray, TDefault]: """High performance left-multiplication of a unitary effect onto a tensor. If `unitary_value` defines an `_apply_...
def apply_unitary(unitary_value: Any, args: ApplyUnitaryArgs, default: TDefault = RaiseTypeErrorIfNotProvided ) -> Union[np.ndarray, TDefault]: """High performance left-multiplication of a unitary effect onto a tensor. If `unitary_value` defines an `_apply_...
[ "High", "performance", "left", "-", "multiplication", "of", "a", "unitary", "effect", "onto", "a", "tensor", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/protocols/apply_unitary.py#L161-L238
[ "def", "apply_unitary", "(", "unitary_value", ":", "Any", ",", "args", ":", "ApplyUnitaryArgs", ",", "default", ":", "TDefault", "=", "RaiseTypeErrorIfNotProvided", ")", "->", "Union", "[", "np", ".", "ndarray", ",", "TDefault", "]", ":", "# Check if the special...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
ApplyUnitaryArgs.subspace_index
An index for the subspace where the target axes equal a value. Args: little_endian_bits_int: The desired value of the qubits at the targeted `axes`, packed into an integer. The least significant bit of the integer is the desired bit for the first axis, and ...
cirq/protocols/apply_unitary.py
def subspace_index(self, little_endian_bits_int: int ) -> Tuple[Union[slice, int, 'ellipsis'], ...]: """An index for the subspace where the target axes equal a value. Args: little_endian_bits_int: The desired value of the qubits at the targeted `axes`,...
def subspace_index(self, little_endian_bits_int: int ) -> Tuple[Union[slice, int, 'ellipsis'], ...]: """An index for the subspace where the target axes equal a value. Args: little_endian_bits_int: The desired value of the qubits at the targeted `axes`,...
[ "An", "index", "for", "the", "subspace", "where", "the", "target", "axes", "equal", "a", "value", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/protocols/apply_unitary.py#L82-L111
[ "def", "subspace_index", "(", "self", ",", "little_endian_bits_int", ":", "int", ")", "->", "Tuple", "[", "Union", "[", "slice", ",", "int", ",", "'ellipsis'", "]", ",", "...", "]", ":", "return", "linalg", ".", "slice_for_qubits_equal_to", "(", "self", "....
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
LinearDict.clean
Remove terms with coefficients of absolute value atol or less.
cirq/value/linear_dict.py
def clean(self: 'TSelf', *, atol: float=1e-9) -> 'TSelf': """Remove terms with coefficients of absolute value atol or less.""" negligible = [v for v, c in self._terms.items() if abs(c) <= atol] for v in negligible: del self._terms[v] return self
def clean(self: 'TSelf', *, atol: float=1e-9) -> 'TSelf': """Remove terms with coefficients of absolute value atol or less.""" negligible = [v for v, c in self._terms.items() if abs(c) <= atol] for v in negligible: del self._terms[v] return self
[ "Remove", "terms", "with", "coefficients", "of", "absolute", "value", "atol", "or", "less", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/value/linear_dict.py#L71-L76
[ "def", "clean", "(", "self", ":", "'TSelf'", ",", "*", ",", "atol", ":", "float", "=", "1e-9", ")", "->", "'TSelf'", ":", "negligible", "=", "[", "v", "for", "v", ",", "c", "in", "self", ".", "_terms", ".", "items", "(", ")", "if", "abs", "(", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
LinearDict._approx_eq_
Checks whether two linear combinations are approximately equal.
cirq/value/linear_dict.py
def _approx_eq_(self, other: Any, atol: float) -> bool: """Checks whether two linear combinations are approximately equal.""" if not isinstance(other, LinearDict): return NotImplemented all_vs = set(self.keys()) | set(other.keys()) return all(abs(self[v] - other[v]) < atol f...
def _approx_eq_(self, other: Any, atol: float) -> bool: """Checks whether two linear combinations are approximately equal.""" if not isinstance(other, LinearDict): return NotImplemented all_vs = set(self.keys()) | set(other.keys()) return all(abs(self[v] - other[v]) < atol f...
[ "Checks", "whether", "two", "linear", "combinations", "are", "approximately", "equal", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/value/linear_dict.py#L231-L237
[ "def", "_approx_eq_", "(", "self", ",", "other", ":", "Any", ",", "atol", ":", "float", ")", "->", "bool", ":", "if", "not", "isinstance", "(", "other", ",", "LinearDict", ")", ":", "return", "NotImplemented", "all_vs", "=", "set", "(", "self", ".", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
BucketPriorityQueue.enqueue
Adds an entry to the priority queue. If drop_duplicate_entries is set and there is already a (priority, item) entry in the queue, then the enqueue is ignored. Check the return value to determine if an enqueue was kept or dropped. Args: priority: The priority of the item. Lo...
cirq/circuits/_bucket_priority_queue.py
def enqueue(self, priority: int, item: TItem) -> bool: """Adds an entry to the priority queue. If drop_duplicate_entries is set and there is already a (priority, item) entry in the queue, then the enqueue is ignored. Check the return value to determine if an enqueue was kept or dropped....
def enqueue(self, priority: int, item: TItem) -> bool: """Adds an entry to the priority queue. If drop_duplicate_entries is set and there is already a (priority, item) entry in the queue, then the enqueue is ignored. Check the return value to determine if an enqueue was kept or dropped....
[ "Adds", "an", "entry", "to", "the", "priority", "queue", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/circuits/_bucket_priority_queue.py#L86-L130
[ "def", "enqueue", "(", "self", ",", "priority", ":", "int", ",", "item", ":", "TItem", ")", "->", "bool", ":", "if", "self", ".", "_drop_set", "is", "not", "None", ":", "if", "(", "priority", ",", "item", ")", "in", "self", ".", "_drop_set", ":", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
BucketPriorityQueue.dequeue
Removes and returns an item from the priority queue. Returns: A tuple whose first element is the priority of the dequeued item and whose second element is the dequeued item. Raises: ValueError: The queue is empty.
cirq/circuits/_bucket_priority_queue.py
def dequeue(self) -> Tuple[int, TItem]: """Removes and returns an item from the priority queue. Returns: A tuple whose first element is the priority of the dequeued item and whose second element is the dequeued item. Raises: ValueError: The q...
def dequeue(self) -> Tuple[int, TItem]: """Removes and returns an item from the priority queue. Returns: A tuple whose first element is the priority of the dequeued item and whose second element is the dequeued item. Raises: ValueError: The q...
[ "Removes", "and", "returns", "an", "item", "from", "the", "priority", "queue", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/circuits/_bucket_priority_queue.py#L132-L162
[ "def", "dequeue", "(", "self", ")", "->", "Tuple", "[", "int", ",", "TItem", "]", ":", "if", "self", ".", "_len", "==", "0", ":", "raise", "ValueError", "(", "'BucketPriorityQueue is empty.'", ")", "# Drop empty buckets at the front of the queue.", "while", "sel...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
Engine.run
Runs the supplied Circuit or Schedule via Quantum Engine. Args: program: The Circuit or Schedule to execute. If a circuit is provided, a moment by moment schedule will be used. job_config: Configures the names of programs and jobs. param_resolver: Parameters ...
cirq/google/engine/engine.py
def run( self, *, # Force keyword args. program: Union[circuits.Circuit, Schedule], job_config: Optional[JobConfig] = None, param_resolver: ParamResolver = ParamResolver({}), repetitions: int = 1, priority: int = 50, proces...
def run( self, *, # Force keyword args. program: Union[circuits.Circuit, Schedule], job_config: Optional[JobConfig] = None, param_resolver: ParamResolver = ParamResolver({}), repetitions: int = 1, priority: int = 50, proces...
[ "Runs", "the", "supplied", "Circuit", "or", "Schedule", "via", "Quantum", "Engine", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/engine/engine.py#L188-L217
[ "def", "run", "(", "self", ",", "*", ",", "# Force keyword args.", "program", ":", "Union", "[", "circuits", ".", "Circuit", ",", "Schedule", "]", ",", "job_config", ":", "Optional", "[", "JobConfig", "]", "=", "None", ",", "param_resolver", ":", "ParamRes...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
Engine.run_sweep
Runs the supplied Circuit or Schedule via Quantum Engine. In contrast to run, this runs across multiple parameter sweeps, and does not block until a result is returned. Args: program: The Circuit or Schedule to execute. If a circuit is provided, a moment by moment s...
cirq/google/engine/engine.py
def run_sweep( self, *, # Force keyword args. program: Union[circuits.Circuit, Schedule], job_config: Optional[JobConfig] = None, params: Sweepable = None, repetitions: int = 1, priority: int = 500, processor_ids: Sequence[...
def run_sweep( self, *, # Force keyword args. program: Union[circuits.Circuit, Schedule], job_config: Optional[JobConfig] = None, params: Sweepable = None, repetitions: int = 1, priority: int = 500, processor_ids: Sequence[...
[ "Runs", "the", "supplied", "Circuit", "or", "Schedule", "via", "Quantum", "Engine", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/engine/engine.py#L318-L399
[ "def", "run_sweep", "(", "self", ",", "*", ",", "# Force keyword args.", "program", ":", "Union", "[", "circuits", ".", "Circuit", ",", "Schedule", "]", ",", "job_config", ":", "Optional", "[", "JobConfig", "]", "=", "None", ",", "params", ":", "Sweepable"...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
Engine.get_program
Returns the previously created quantum program. Params: program_resource_name: A string of the form `projects/project_id/programs/program_id`. Returns: A dictionary containing the metadata and the program.
cirq/google/engine/engine.py
def get_program(self, program_resource_name: str) -> Dict: """Returns the previously created quantum program. Params: program_resource_name: A string of the form `projects/project_id/programs/program_id`. Returns: A dictionary containing the metadata and...
def get_program(self, program_resource_name: str) -> Dict: """Returns the previously created quantum program. Params: program_resource_name: A string of the form `projects/project_id/programs/program_id`. Returns: A dictionary containing the metadata and...
[ "Returns", "the", "previously", "created", "quantum", "program", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/engine/engine.py#L401-L412
[ "def", "get_program", "(", "self", ",", "program_resource_name", ":", "str", ")", "->", "Dict", ":", "return", "self", ".", "service", ".", "projects", "(", ")", ".", "programs", "(", ")", ".", "get", "(", "name", "=", "program_resource_name", ")", ".", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
Engine.get_job
Returns metadata about a previously created job. See get_job_result if you want the results of the job and not just metadata about the job. Params: job_resource_name: A string of the form `projects/project_id/programs/program_id/jobs/job_id`. Returns: ...
cirq/google/engine/engine.py
def get_job(self, job_resource_name: str) -> Dict: """Returns metadata about a previously created job. See get_job_result if you want the results of the job and not just metadata about the job. Params: job_resource_name: A string of the form `projects/projec...
def get_job(self, job_resource_name: str) -> Dict: """Returns metadata about a previously created job. See get_job_result if you want the results of the job and not just metadata about the job. Params: job_resource_name: A string of the form `projects/projec...
[ "Returns", "metadata", "about", "a", "previously", "created", "job", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/engine/engine.py#L414-L428
[ "def", "get_job", "(", "self", ",", "job_resource_name", ":", "str", ")", "->", "Dict", ":", "return", "self", ".", "service", ".", "projects", "(", ")", ".", "programs", "(", ")", ".", "jobs", "(", ")", ".", "get", "(", "name", "=", "job_resource_na...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
Engine.get_job_results
Returns the actual results (not metadata) of a completed job. Params: job_resource_name: A string of the form `projects/project_id/programs/program_id/jobs/job_id`. Returns: An iterable over the TrialResult, one per parameter in the parameter sweep.
cirq/google/engine/engine.py
def get_job_results(self, job_resource_name: str) -> List[TrialResult]: """Returns the actual results (not metadata) of a completed job. Params: job_resource_name: A string of the form `projects/project_id/programs/program_id/jobs/job_id`. Returns: An it...
def get_job_results(self, job_resource_name: str) -> List[TrialResult]: """Returns the actual results (not metadata) of a completed job. Params: job_resource_name: A string of the form `projects/project_id/programs/program_id/jobs/job_id`. Returns: An it...
[ "Returns", "the", "actual", "results", "(", "not", "metadata", ")", "of", "a", "completed", "job", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/engine/engine.py#L430-L458
[ "def", "get_job_results", "(", "self", ",", "job_resource_name", ":", "str", ")", "->", "List", "[", "TrialResult", "]", ":", "response", "=", "self", ".", "service", ".", "projects", "(", ")", ".", "programs", "(", ")", ".", "jobs", "(", ")", ".", "...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
Engine.cancel_job
Cancels the given job. See also the cancel method on EngineJob. Params: job_resource_name: A string of the form `projects/project_id/programs/program_id/jobs/job_id`.
cirq/google/engine/engine.py
def cancel_job(self, job_resource_name: str): """Cancels the given job. See also the cancel method on EngineJob. Params: job_resource_name: A string of the form `projects/project_id/programs/program_id/jobs/job_id`. """ self.service.projects().progra...
def cancel_job(self, job_resource_name: str): """Cancels the given job. See also the cancel method on EngineJob. Params: job_resource_name: A string of the form `projects/project_id/programs/program_id/jobs/job_id`. """ self.service.projects().progra...
[ "Cancels", "the", "given", "job", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/engine/engine.py#L460-L470
[ "def", "cancel_job", "(", "self", ",", "job_resource_name", ":", "str", ")", ":", "self", ".", "service", ".", "projects", "(", ")", ".", "programs", "(", ")", ".", "jobs", "(", ")", ".", "cancel", "(", "name", "=", "job_resource_name", ",", "body", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
EngineJob.results
Returns the job results, blocking until the job is complete.
cirq/google/engine/engine.py
def results(self) -> List[TrialResult]: """Returns the job results, blocking until the job is complete.""" if not self._results: job = self._update_job() for _ in range(1000): if job['executionStatus']['state'] in TERMINAL_STATES: break ...
def results(self) -> List[TrialResult]: """Returns the job results, blocking until the job is complete.""" if not self._results: job = self._update_job() for _ in range(1000): if job['executionStatus']['state'] in TERMINAL_STATES: break ...
[ "Returns", "the", "job", "results", "blocking", "until", "the", "job", "is", "complete", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/engine/engine.py#L585-L600
[ "def", "results", "(", "self", ")", "->", "List", "[", "TrialResult", "]", ":", "if", "not", "self", ".", "_results", ":", "job", "=", "self", ".", "_update_job", "(", ")", "for", "_", "in", "range", "(", "1000", ")", ":", "if", "job", "[", "'exe...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
flatten_op_tree
Performs an in-order iteration of the operations (leaves) in an OP_TREE. Args: root: The operation or tree of operations to iterate. preserve_moments: Whether to yield Moments intact instead of flattening them Yields: Operations from the tree. Raises: TypeError...
cirq/ops/op_tree.py
def flatten_op_tree(root: OP_TREE, preserve_moments: bool = False ) -> Iterable[Union[Operation, Moment]]: """Performs an in-order iteration of the operations (leaves) in an OP_TREE. Args: root: The operation or tree of operations to iterate. preserve_mom...
def flatten_op_tree(root: OP_TREE, preserve_moments: bool = False ) -> Iterable[Union[Operation, Moment]]: """Performs an in-order iteration of the operations (leaves) in an OP_TREE. Args: root: The operation or tree of operations to iterate. preserve_mom...
[ "Performs", "an", "in", "-", "order", "iteration", "of", "the", "operations", "(", "leaves", ")", "in", "an", "OP_TREE", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/ops/op_tree.py#L48-L76
[ "def", "flatten_op_tree", "(", "root", ":", "OP_TREE", ",", "preserve_moments", ":", "bool", "=", "False", ")", "->", "Iterable", "[", "Union", "[", "Operation", ",", "Moment", "]", "]", ":", "if", "(", "isinstance", "(", "root", ",", "Operation", ")", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
transform_op_tree
Maps transformation functions onto the nodes of an OP_TREE. Args: root: The operation or tree of operations to transform. op_transformation: How to transform the operations (i.e. leaves). iter_transformation: How to transform the iterables (i.e. internal nodes). preserve...
cirq/ops/op_tree.py
def transform_op_tree( root: OP_TREE, op_transformation: Callable[[Operation], OP_TREE]=lambda e: e, iter_transformation: Callable[[Iterable[OP_TREE]], OP_TREE]=lambda e: e, preserve_moments: bool = False ) -> OP_TREE: """Maps transformation functions onto the nodes of an OP_TREE. ...
def transform_op_tree( root: OP_TREE, op_transformation: Callable[[Operation], OP_TREE]=lambda e: e, iter_transformation: Callable[[Iterable[OP_TREE]], OP_TREE]=lambda e: e, preserve_moments: bool = False ) -> OP_TREE: """Maps transformation functions onto the nodes of an OP_TREE. ...
[ "Maps", "transformation", "functions", "onto", "the", "nodes", "of", "an", "OP_TREE", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/ops/op_tree.py#L79-L117
[ "def", "transform_op_tree", "(", "root", ":", "OP_TREE", ",", "op_transformation", ":", "Callable", "[", "[", "Operation", "]", ",", "OP_TREE", "]", "=", "lambda", "e", ":", "e", ",", "iter_transformation", ":", "Callable", "[", "[", "Iterable", "[", "OP_T...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
circuit_to_quirk_url
Returns a Quirk URL for the given circuit. Args: circuit: The circuit to open in Quirk. prefer_unknown_gate_to_failure: If not set, gates that fail to convert will cause this function to raise an error. If set, a URL containing bad gates will be generated. (Quirk will open t...
cirq/contrib/quirk/export_to_quirk.py
def circuit_to_quirk_url(circuit: circuits.Circuit, prefer_unknown_gate_to_failure: bool=False, escape_url=True) -> str: """Returns a Quirk URL for the given circuit. Args: circuit: The circuit to open in Quirk. prefer_unknown_gate_to_failure: I...
def circuit_to_quirk_url(circuit: circuits.Circuit, prefer_unknown_gate_to_failure: bool=False, escape_url=True) -> str: """Returns a Quirk URL for the given circuit. Args: circuit: The circuit to open in Quirk. prefer_unknown_gate_to_failure: I...
[ "Returns", "a", "Quirk", "URL", "for", "the", "given", "circuit", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/contrib/quirk/export_to_quirk.py#L55-L106
[ "def", "circuit_to_quirk_url", "(", "circuit", ":", "circuits", ".", "Circuit", ",", "prefer_unknown_gate_to_failure", ":", "bool", "=", "False", ",", "escape_url", "=", "True", ")", "->", "str", ":", "circuit", "=", "circuit", ".", "copy", "(", ")", "linear...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
GridQubit.is_adjacent
Determines if two qubits are adjacent qubits.
cirq/devices/grid_qubit.py
def is_adjacent(self, other: ops.Qid) -> bool: """Determines if two qubits are adjacent qubits.""" return (isinstance(other, GridQubit) and abs(self.row - other.row) + abs(self.col - other.col) == 1)
def is_adjacent(self, other: ops.Qid) -> bool: """Determines if two qubits are adjacent qubits.""" return (isinstance(other, GridQubit) and abs(self.row - other.row) + abs(self.col - other.col) == 1)
[ "Determines", "if", "two", "qubits", "are", "adjacent", "qubits", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/devices/grid_qubit.py#L36-L39
[ "def", "is_adjacent", "(", "self", ",", "other", ":", "ops", ".", "Qid", ")", "->", "bool", ":", "return", "(", "isinstance", "(", "other", ",", "GridQubit", ")", "and", "abs", "(", "self", ".", "row", "-", "other", ".", "row", ")", "+", "abs", "...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
GridQubit.from_proto_dict
Proto dict must have 'row' and 'col' keys.
cirq/devices/grid_qubit.py
def from_proto_dict(proto_dict: Dict) -> 'GridQubit': """Proto dict must have 'row' and 'col' keys.""" if 'row' not in proto_dict or 'col' not in proto_dict: raise ValueError( 'Proto dict does not contain row or col: {}'.format(proto_dict)) return GridQubit(row=proto_...
def from_proto_dict(proto_dict: Dict) -> 'GridQubit': """Proto dict must have 'row' and 'col' keys.""" if 'row' not in proto_dict or 'col' not in proto_dict: raise ValueError( 'Proto dict does not contain row or col: {}'.format(proto_dict)) return GridQubit(row=proto_...
[ "Proto", "dict", "must", "have", "row", "and", "col", "keys", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/devices/grid_qubit.py#L55-L60
[ "def", "from_proto_dict", "(", "proto_dict", ":", "Dict", ")", "->", "'GridQubit'", ":", "if", "'row'", "not", "in", "proto_dict", "or", "'col'", "not", "in", "proto_dict", ":", "raise", "ValueError", "(", "'Proto dict does not contain row or col: {}'", ".", "form...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
ExecutionStrategy.get_operations
Gets the logical operations to apply to qubits.
cirq/contrib/acquaintance/executor.py
def get_operations(self, indices: Sequence[LogicalIndex], qubits: Sequence[ops.Qid] ) -> ops.OP_TREE: """Gets the logical operations to apply to qubits."""
def get_operations(self, indices: Sequence[LogicalIndex], qubits: Sequence[ops.Qid] ) -> ops.OP_TREE: """Gets the logical operations to apply to qubits."""
[ "Gets", "the", "logical", "operations", "to", "apply", "to", "qubits", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/contrib/acquaintance/executor.py#L61-L65
[ "def", "get_operations", "(", "self", ",", "indices", ":", "Sequence", "[", "LogicalIndex", "]", ",", "qubits", ":", "Sequence", "[", "ops", ".", "Qid", "]", ")", "->", "ops", ".", "OP_TREE", ":" ]
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
GreedyExecutionStrategy.canonicalize_gates
Canonicalizes a set of gates by the qubits they act on. Takes a set of gates specified by ordered sequences of logical indices, and groups those that act on the same qubits regardless of order.
cirq/contrib/acquaintance/executor.py
def canonicalize_gates(gates: LogicalGates ) -> Dict[frozenset, LogicalGates]: """Canonicalizes a set of gates by the qubits they act on. Takes a set of gates specified by ordered sequences of logical indices, and groups those that act on the same qubits regardless of order.""" ...
def canonicalize_gates(gates: LogicalGates ) -> Dict[frozenset, LogicalGates]: """Canonicalizes a set of gates by the qubits they act on. Takes a set of gates specified by ordered sequences of logical indices, and groups those that act on the same qubits regardless of order.""" ...
[ "Canonicalizes", "a", "set", "of", "gates", "by", "the", "qubits", "they", "act", "on", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/contrib/acquaintance/executor.py#L184-L197
[ "def", "canonicalize_gates", "(", "gates", ":", "LogicalGates", ")", "->", "Dict", "[", "frozenset", ",", "LogicalGates", "]", ":", "canonicalized_gates", "=", "defaultdict", "(", "dict", ")", "# type: DefaultDict[frozenset, LogicalGates]", "for", "indices", ",", "g...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
merge_single_qubit_gates_into_phased_x_z
Canonicalizes runs of single-qubit rotations in a circuit. Specifically, any run of non-parameterized circuits will be replaced by an optional PhasedX operation followed by an optional Z operation. Args: circuit: The circuit to rewrite. This value is mutated in-place. atol: Absolute tolera...
cirq/optimizers/merge_single_qubit_gates.py
def merge_single_qubit_gates_into_phased_x_z( circuit: circuits.Circuit, atol: float = 1e-8) -> None: """Canonicalizes runs of single-qubit rotations in a circuit. Specifically, any run of non-parameterized circuits will be replaced by an optional PhasedX operation followed by an optional Z...
def merge_single_qubit_gates_into_phased_x_z( circuit: circuits.Circuit, atol: float = 1e-8) -> None: """Canonicalizes runs of single-qubit rotations in a circuit. Specifically, any run of non-parameterized circuits will be replaced by an optional PhasedX operation followed by an optional Z...
[ "Canonicalizes", "runs", "of", "single", "-", "qubit", "rotations", "in", "a", "circuit", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/optimizers/merge_single_qubit_gates.py#L101-L120
[ "def", "merge_single_qubit_gates_into_phased_x_z", "(", "circuit", ":", "circuits", ".", "Circuit", ",", "atol", ":", "float", "=", "1e-8", ")", "->", "None", ":", "def", "synth", "(", "qubit", ":", "ops", ".", "Qid", ",", "matrix", ":", "np", ".", "ndar...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
highlight
Wraps the given string with terminal color codes. Args: text: The content to highlight. color_code: The color to highlight with, e.g. 'shelltools.RED'. bold: Whether to bold the content in addition to coloring. Returns: The highlighted string.
dev_tools/shell_tools.py
def highlight(text: str, color_code: int, bold: bool=False) -> str: """Wraps the given string with terminal color codes. Args: text: The content to highlight. color_code: The color to highlight with, e.g. 'shelltools.RED'. bold: Whether to bold the content in addition to coloring. ...
def highlight(text: str, color_code: int, bold: bool=False) -> str: """Wraps the given string with terminal color codes. Args: text: The content to highlight. color_code: The color to highlight with, e.g. 'shelltools.RED'. bold: Whether to bold the content in addition to coloring. ...
[ "Wraps", "the", "given", "string", "with", "terminal", "color", "codes", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/shell_tools.py#L45-L59
[ "def", "highlight", "(", "text", ":", "str", ",", "color_code", ":", "int", ",", "bold", ":", "bool", "=", "False", ")", "->", "str", ":", "return", "'{}\\033[{}m{}\\033[0m'", ".", "format", "(", "'\\033[1m'", "if", "bold", "else", "''", ",", "color_code...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
_async_forward
Prints/captures output from the given asynchronous iterable. Args: async_chunks: An asynchronous source of bytes or str. out: Where to put the chunks. Returns: The complete captured output, or else None if the out argument wasn't a TeeCapture instance.
dev_tools/shell_tools.py
async def _async_forward(async_chunks: collections.AsyncIterable, out: Optional[Union[TeeCapture, IO[str]]] ) -> Optional[str]: """Prints/captures output from the given asynchronous iterable. Args: async_chunks: An asynchronous source of bytes or str. ...
async def _async_forward(async_chunks: collections.AsyncIterable, out: Optional[Union[TeeCapture, IO[str]]] ) -> Optional[str]: """Prints/captures output from the given asynchronous iterable. Args: async_chunks: An asynchronous source of bytes or str. ...
[ "Prints", "/", "captures", "output", "from", "the", "given", "asynchronous", "iterable", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/shell_tools.py#L72-L97
[ "async", "def", "_async_forward", "(", "async_chunks", ":", "collections", ".", "AsyncIterable", ",", "out", ":", "Optional", "[", "Union", "[", "TeeCapture", ",", "IO", "[", "str", "]", "]", "]", ")", "->", "Optional", "[", "str", "]", ":", "capture", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
_async_wait_for_process
Awaits the creation and completion of an asynchronous process. Args: future_process: The eventually created process. out: Where to write stuff emitted by the process' stdout. err: Where to write stuff emitted by the process' stderr. Returns: A (captured output, captured error o...
dev_tools/shell_tools.py
async def _async_wait_for_process( future_process: Any, out: Optional[Union[TeeCapture, IO[str]]] = sys.stdout, err: Optional[Union[TeeCapture, IO[str]]] = sys.stderr ) -> CommandOutput: """Awaits the creation and completion of an asynchronous process. Args: future_process: The ...
async def _async_wait_for_process( future_process: Any, out: Optional[Union[TeeCapture, IO[str]]] = sys.stdout, err: Optional[Union[TeeCapture, IO[str]]] = sys.stderr ) -> CommandOutput: """Awaits the creation and completion of an asynchronous process. Args: future_process: The ...
[ "Awaits", "the", "creation", "and", "completion", "of", "an", "asynchronous", "process", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/shell_tools.py#L100-L121
[ "async", "def", "_async_wait_for_process", "(", "future_process", ":", "Any", ",", "out", ":", "Optional", "[", "Union", "[", "TeeCapture", ",", "IO", "[", "str", "]", "]", "]", "=", "sys", ".", "stdout", ",", "err", ":", "Optional", "[", "Union", "[",...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
run_cmd
Invokes a subprocess and waits for it to finish. Args: cmd: Components of the command to execute, e.g. ["echo", "dog"]. out: Where to write the process' stdout. Defaults to sys.stdout. Can be anything accepted by print's 'file' parameter, or None if the output should be drop...
dev_tools/shell_tools.py
def run_cmd(*cmd: Optional[str], out: Optional[Union[TeeCapture, IO[str]]] = sys.stdout, err: Optional[Union[TeeCapture, IO[str]]] = sys.stderr, raise_on_fail: bool = True, log_run_to_stderr: bool = True, abbreviate_non_option_arguments: bool = False, ...
def run_cmd(*cmd: Optional[str], out: Optional[Union[TeeCapture, IO[str]]] = sys.stdout, err: Optional[Union[TeeCapture, IO[str]]] = sys.stderr, raise_on_fail: bool = True, log_run_to_stderr: bool = True, abbreviate_non_option_arguments: bool = False, ...
[ "Invokes", "a", "subprocess", "and", "waits", "for", "it", "to", "finish", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/shell_tools.py#L135-L196
[ "def", "run_cmd", "(", "*", "cmd", ":", "Optional", "[", "str", "]", ",", "out", ":", "Optional", "[", "Union", "[", "TeeCapture", ",", "IO", "[", "str", "]", "]", "]", "=", "sys", ".", "stdout", ",", "err", ":", "Optional", "[", "Union", "[", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
run_shell
Invokes a shell command and waits for it to finish. Args: cmd: The command line string to execute, e.g. "echo dog | cat > file". out: Where to write the process' stdout. Defaults to sys.stdout. Can be anything accepted by print's 'file' parameter, or None if the output shoul...
dev_tools/shell_tools.py
def run_shell(cmd: str, out: Optional[Union[TeeCapture, IO[str]]] = sys.stdout, err: Optional[Union[TeeCapture, IO[str]]] = sys.stderr, raise_on_fail: bool = True, log_run_to_stderr: bool = True, **kwargs ) -> CommandOutput: """Invo...
def run_shell(cmd: str, out: Optional[Union[TeeCapture, IO[str]]] = sys.stdout, err: Optional[Union[TeeCapture, IO[str]]] = sys.stderr, raise_on_fail: bool = True, log_run_to_stderr: bool = True, **kwargs ) -> CommandOutput: """Invo...
[ "Invokes", "a", "shell", "command", "and", "waits", "for", "it", "to", "finish", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/shell_tools.py#L199-L251
[ "def", "run_shell", "(", "cmd", ":", "str", ",", "out", ":", "Optional", "[", "Union", "[", "TeeCapture", ",", "IO", "[", "str", "]", "]", "]", "=", "sys", ".", "stdout", ",", "err", ":", "Optional", "[", "Union", "[", "TeeCapture", ",", "IO", "[...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
output_of
Invokes a subprocess and returns its output as a string. Args: cmd: Components of the command to execute, e.g. ["echo", "dog"]. **kwargs: Extra arguments for asyncio.create_subprocess_shell, such as a cwd (current working directory) argument. Returns: A (captured output, ca...
dev_tools/shell_tools.py
def output_of(*cmd: Optional[str], **kwargs) -> str: """Invokes a subprocess and returns its output as a string. Args: cmd: Components of the command to execute, e.g. ["echo", "dog"]. **kwargs: Extra arguments for asyncio.create_subprocess_shell, such as a cwd (current working direc...
def output_of(*cmd: Optional[str], **kwargs) -> str: """Invokes a subprocess and returns its output as a string. Args: cmd: Components of the command to execute, e.g. ["echo", "dog"]. **kwargs: Extra arguments for asyncio.create_subprocess_shell, such as a cwd (current working direc...
[ "Invokes", "a", "subprocess", "and", "returns", "its", "output", "as", "a", "string", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/shell_tools.py#L254-L280
[ "def", "output_of", "(", "*", "cmd", ":", "Optional", "[", "str", "]", ",", "*", "*", "kwargs", ")", "->", "str", ":", "result", "=", "cast", "(", "str", ",", "run_cmd", "(", "*", "cmd", ",", "log_run_to_stderr", "=", "False", ",", "out", "=", "T...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
chosen_angle_to_half_turns
Returns a half_turns value based on the given arguments. At most one of half_turns, rads, degs must be specified. If none are specified, the output defaults to half_turns=1. Args: half_turns: The number of half turns to rotate by. rads: The number of radians to rotate by. degs: The...
cirq/value/angle.py
def chosen_angle_to_half_turns( half_turns: Optional[Union[sympy.Basic, float]] = None, rads: Optional[float] = None, degs: Optional[float] = None, default: float = 1.0, ) -> Union[sympy.Basic, float]: """Returns a half_turns value based on the given arguments. At most one of ha...
def chosen_angle_to_half_turns( half_turns: Optional[Union[sympy.Basic, float]] = None, rads: Optional[float] = None, degs: Optional[float] = None, default: float = 1.0, ) -> Union[sympy.Basic, float]: """Returns a half_turns value based on the given arguments. At most one of ha...
[ "Returns", "a", "half_turns", "value", "based", "on", "the", "given", "arguments", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/value/angle.py#L20-L54
[ "def", "chosen_angle_to_half_turns", "(", "half_turns", ":", "Optional", "[", "Union", "[", "sympy", ".", "Basic", ",", "float", "]", "]", "=", "None", ",", "rads", ":", "Optional", "[", "float", "]", "=", "None", ",", "degs", ":", "Optional", "[", "fl...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
chosen_angle_to_canonical_half_turns
Returns a canonicalized half_turns based on the given arguments. At most one of half_turns, rads, degs must be specified. If none are specified, the output defaults to half_turns=1. Args: half_turns: The number of half turns to rotate by. rads: The number of radians to rotate by. d...
cirq/value/angle.py
def chosen_angle_to_canonical_half_turns( half_turns: Optional[Union[sympy.Basic, float]] = None, rads: Optional[float] = None, degs: Optional[float] = None, default: float = 1.0, ) -> Union[sympy.Basic, float]: """Returns a canonicalized half_turns based on the given arguments. ...
def chosen_angle_to_canonical_half_turns( half_turns: Optional[Union[sympy.Basic, float]] = None, rads: Optional[float] = None, degs: Optional[float] = None, default: float = 1.0, ) -> Union[sympy.Basic, float]: """Returns a canonicalized half_turns based on the given arguments. ...
[ "Returns", "a", "canonicalized", "half_turns", "based", "on", "the", "given", "arguments", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/value/angle.py#L57-L82
[ "def", "chosen_angle_to_canonical_half_turns", "(", "half_turns", ":", "Optional", "[", "Union", "[", "sympy", ".", "Basic", ",", "float", "]", "]", "=", "None", ",", "rads", ":", "Optional", "[", "float", "]", "=", "None", ",", "degs", ":", "Optional", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
canonicalize_half_turns
Wraps the input into the range (-1, +1].
cirq/value/angle.py
def canonicalize_half_turns( half_turns: Union[sympy.Basic, float] ) -> Union[sympy.Basic, float]: """Wraps the input into the range (-1, +1].""" if isinstance(half_turns, sympy.Basic): return half_turns half_turns %= 2 if half_turns > 1: half_turns -= 2 return half_turns
def canonicalize_half_turns( half_turns: Union[sympy.Basic, float] ) -> Union[sympy.Basic, float]: """Wraps the input into the range (-1, +1].""" if isinstance(half_turns, sympy.Basic): return half_turns half_turns %= 2 if half_turns > 1: half_turns -= 2 return half_turns
[ "Wraps", "the", "input", "into", "the", "range", "(", "-", "1", "+", "1", "]", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/value/angle.py#L96-L105
[ "def", "canonicalize_half_turns", "(", "half_turns", ":", "Union", "[", "sympy", ".", "Basic", ",", "float", "]", ")", "->", "Union", "[", "sympy", ".", "Basic", ",", "float", "]", ":", "if", "isinstance", "(", "half_turns", ",", "sympy", ".", "Basic", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
single_qubit_matrix_to_pauli_rotations
Implements a single-qubit operation with few rotations. Args: mat: The 2x2 unitary matrix of the operation to implement. atol: A limit on the amount of absolute error introduced by the construction. Returns: A list of (Pauli, half_turns) tuples that, when applied in order, ...
cirq/optimizers/decompositions.py
def single_qubit_matrix_to_pauli_rotations( mat: np.ndarray, atol: float = 0 ) -> List[Tuple[ops.Pauli, float]]: """Implements a single-qubit operation with few rotations. Args: mat: The 2x2 unitary matrix of the operation to implement. atol: A limit on the amount of absolute error intr...
def single_qubit_matrix_to_pauli_rotations( mat: np.ndarray, atol: float = 0 ) -> List[Tuple[ops.Pauli, float]]: """Implements a single-qubit operation with few rotations. Args: mat: The 2x2 unitary matrix of the operation to implement. atol: A limit on the amount of absolute error intr...
[ "Implements", "a", "single", "-", "qubit", "operation", "with", "few", "rotations", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/optimizers/decompositions.py#L33-L97
[ "def", "single_qubit_matrix_to_pauli_rotations", "(", "mat", ":", "np", ".", "ndarray", ",", "atol", ":", "float", "=", "0", ")", "->", "List", "[", "Tuple", "[", "ops", ".", "Pauli", ",", "float", "]", "]", ":", "def", "is_clifford_rotation", "(", "half...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
single_qubit_matrix_to_gates
Implements a single-qubit operation with few gates. Args: mat: The 2x2 unitary matrix of the operation to implement. tolerance: A limit on the amount of error introduced by the construction. Returns: A list of gates that, when applied in order, perform the desired ...
cirq/optimizers/decompositions.py
def single_qubit_matrix_to_gates( mat: np.ndarray, tolerance: float = 0 ) -> List[ops.SingleQubitGate]: """Implements a single-qubit operation with few gates. Args: mat: The 2x2 unitary matrix of the operation to implement. tolerance: A limit on the amount of error introduced by the ...
def single_qubit_matrix_to_gates( mat: np.ndarray, tolerance: float = 0 ) -> List[ops.SingleQubitGate]: """Implements a single-qubit operation with few gates. Args: mat: The 2x2 unitary matrix of the operation to implement. tolerance: A limit on the amount of error introduced by the ...
[ "Implements", "a", "single", "-", "qubit", "operation", "with", "few", "gates", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/optimizers/decompositions.py#L100-L115
[ "def", "single_qubit_matrix_to_gates", "(", "mat", ":", "np", ".", "ndarray", ",", "tolerance", ":", "float", "=", "0", ")", "->", "List", "[", "ops", ".", "SingleQubitGate", "]", ":", "rotations", "=", "single_qubit_matrix_to_pauli_rotations", "(", "mat", ","...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
single_qubit_op_to_framed_phase_form
Decomposes a 2x2 unitary M into U^-1 * diag(1, r) * U * diag(g, g). U translates the rotation axis of M to the Z axis. g fixes a global phase factor difference caused by the translation. r's phase is the amount of rotation around M's rotation axis. This decomposition can be used to decompose controlle...
cirq/optimizers/decompositions.py
def single_qubit_op_to_framed_phase_form( mat: np.ndarray) -> Tuple[np.ndarray, complex, complex]: """Decomposes a 2x2 unitary M into U^-1 * diag(1, r) * U * diag(g, g). U translates the rotation axis of M to the Z axis. g fixes a global phase factor difference caused by the translation. r's ph...
def single_qubit_op_to_framed_phase_form( mat: np.ndarray) -> Tuple[np.ndarray, complex, complex]: """Decomposes a 2x2 unitary M into U^-1 * diag(1, r) * U * diag(g, g). U translates the rotation axis of M to the Z axis. g fixes a global phase factor difference caused by the translation. r's ph...
[ "Decomposes", "a", "2x2", "unitary", "M", "into", "U^", "-", "1", "*", "diag", "(", "1", "r", ")", "*", "U", "*", "diag", "(", "g", "g", ")", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/optimizers/decompositions.py#L118-L143
[ "def", "single_qubit_op_to_framed_phase_form", "(", "mat", ":", "np", ".", "ndarray", ")", "->", "Tuple", "[", "np", ".", "ndarray", ",", "complex", ",", "complex", "]", ":", "vals", ",", "vecs", "=", "np", ".", "linalg", ".", "eig", "(", "mat", ")", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
_deconstruct_single_qubit_matrix_into_gate_turns
Breaks down a 2x2 unitary into gate parameters. Args: mat: The 2x2 unitary matrix to break down. Returns: A tuple containing the amount to rotate around an XY axis, the phase of that axis, and the amount to phase around Z. All results will be in fractions of a whole turn, with val...
cirq/optimizers/decompositions.py
def _deconstruct_single_qubit_matrix_into_gate_turns( mat: np.ndarray) -> Tuple[float, float, float]: """Breaks down a 2x2 unitary into gate parameters. Args: mat: The 2x2 unitary matrix to break down. Returns: A tuple containing the amount to rotate around an XY axis, the phase of ...
def _deconstruct_single_qubit_matrix_into_gate_turns( mat: np.ndarray) -> Tuple[float, float, float]: """Breaks down a 2x2 unitary into gate parameters. Args: mat: The 2x2 unitary matrix to break down. Returns: A tuple containing the amount to rotate around an XY axis, the phase of ...
[ "Breaks", "down", "a", "2x2", "unitary", "into", "gate", "parameters", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/optimizers/decompositions.py#L146-L170
[ "def", "_deconstruct_single_qubit_matrix_into_gate_turns", "(", "mat", ":", "np", ".", "ndarray", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "pre_phase", ",", "rotation", ",", "post_phase", "=", "(", "linalg", ".", "deconstruct_sin...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
single_qubit_matrix_to_phased_x_z
Implements a single-qubit operation with a PhasedX and Z gate. If one of the gates isn't needed, it will be omitted. Args: mat: The 2x2 unitary matrix of the operation to implement. atol: A limit on the amount of error introduced by the construction. Returns: A list of...
cirq/optimizers/decompositions.py
def single_qubit_matrix_to_phased_x_z( mat: np.ndarray, atol: float = 0 ) -> List[ops.SingleQubitGate]: """Implements a single-qubit operation with a PhasedX and Z gate. If one of the gates isn't needed, it will be omitted. Args: mat: The 2x2 unitary matrix of the operation to impl...
def single_qubit_matrix_to_phased_x_z( mat: np.ndarray, atol: float = 0 ) -> List[ops.SingleQubitGate]: """Implements a single-qubit operation with a PhasedX and Z gate. If one of the gates isn't needed, it will be omitted. Args: mat: The 2x2 unitary matrix of the operation to impl...
[ "Implements", "a", "single", "-", "qubit", "operation", "with", "a", "PhasedX", "and", "Z", "gate", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/optimizers/decompositions.py#L173-L211
[ "def", "single_qubit_matrix_to_phased_x_z", "(", "mat", ":", "np", ".", "ndarray", ",", "atol", ":", "float", "=", "0", ")", "->", "List", "[", "ops", ".", "SingleQubitGate", "]", ":", "xy_turn", ",", "xy_phase_turn", ",", "total_z_turn", "=", "(", "_decon...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
unitary
Returns a unitary matrix describing the given value. Args: val: The value to describe with a unitary matrix. default: Determines the fallback behavior when `val` doesn't have a unitary matrix. If `default` is not set, a TypeError is raised. If default is set to a value, that...
cirq/protocols/unitary.py
def unitary(val: Any, default: TDefault = RaiseTypeErrorIfNotProvided ) -> Union[np.ndarray, TDefault]: """Returns a unitary matrix describing the given value. Args: val: The value to describe with a unitary matrix. default: Determines the fallback behavior when `val` do...
def unitary(val: Any, default: TDefault = RaiseTypeErrorIfNotProvided ) -> Union[np.ndarray, TDefault]: """Returns a unitary matrix describing the given value. Args: val: The value to describe with a unitary matrix. default: Determines the fallback behavior when `val` do...
[ "Returns", "a", "unitary", "matrix", "describing", "the", "given", "value", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/protocols/unitary.py#L76-L119
[ "def", "unitary", "(", "val", ":", "Any", ",", "default", ":", "TDefault", "=", "RaiseTypeErrorIfNotProvided", ")", "->", "Union", "[", "np", ".", "ndarray", ",", "TDefault", "]", ":", "from", "cirq", "import", "Gate", ",", "Operation", "# HACK: Avoids circu...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
has_unitary
Returns whether the value has a unitary matrix representation. Returns: If `val` has a _has_unitary_ method and its result is not NotImplemented, that result is returned. Otherwise, if `val` is a cirq.Gate or cirq.Operation, a decomposition is attempted and the resulting unitary is ...
cirq/protocols/unitary.py
def has_unitary(val: Any) -> bool: """Returns whether the value has a unitary matrix representation. Returns: If `val` has a _has_unitary_ method and its result is not NotImplemented, that result is returned. Otherwise, if `val` is a cirq.Gate or cirq.Operation, a decomposition is attem...
def has_unitary(val: Any) -> bool: """Returns whether the value has a unitary matrix representation. Returns: If `val` has a _has_unitary_ method and its result is not NotImplemented, that result is returned. Otherwise, if `val` is a cirq.Gate or cirq.Operation, a decomposition is attem...
[ "Returns", "whether", "the", "value", "has", "a", "unitary", "matrix", "representation", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/protocols/unitary.py#L122-L163
[ "def", "has_unitary", "(", "val", ":", "Any", ")", "->", "bool", ":", "from", "cirq", ".", "protocols", ".", "decompose", "import", "(", "decompose_once", ",", "decompose_once_with_qubits", ")", "# HACK: Avoids circular dependencies.", "from", "cirq", "import", "G...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
_decompose_and_get_unitary
Try to decompose a cirq.Operation or cirq.Gate, and return its unitary if it exists. Returns: If `val` can be decomposed into unitaries, calculate the resulting unitary and return it. If it doesn't exist, None is returned.
cirq/protocols/unitary.py
def _decompose_and_get_unitary(val: Union['cirq.Operation', 'cirq.Gate'] ) -> np.ndarray: """Try to decompose a cirq.Operation or cirq.Gate, and return its unitary if it exists. Returns: If `val` can be decomposed into unitaries, calculate the resulting unitar...
def _decompose_and_get_unitary(val: Union['cirq.Operation', 'cirq.Gate'] ) -> np.ndarray: """Try to decompose a cirq.Operation or cirq.Gate, and return its unitary if it exists. Returns: If `val` can be decomposed into unitaries, calculate the resulting unitar...
[ "Try", "to", "decompose", "a", "cirq", ".", "Operation", "or", "cirq", ".", "Gate", "and", "return", "its", "unitary", "if", "it", "exists", "." ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/protocols/unitary.py#L166-L210
[ "def", "_decompose_and_get_unitary", "(", "val", ":", "Union", "[", "'cirq.Operation'", ",", "'cirq.Gate'", "]", ")", "->", "np", ".", "ndarray", ":", "from", "cirq", ".", "protocols", ".", "apply_unitary", "import", "apply_unitary", ",", "ApplyUnitaryArgs", "fr...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
check_collaborator_has_write
References: https://developer.github.com/v3/issues/events/#list-events-for-an-issue
dev_tools/auto_merge.py
def check_collaborator_has_write(repo: GithubRepository, username: str ) -> Optional[CannotAutomergeError]: """ References: https://developer.github.com/v3/issues/events/#list-events-for-an-issue """ url = ("https://api.github.com/repos/{}/{}/collaborators/{}/per...
def check_collaborator_has_write(repo: GithubRepository, username: str ) -> Optional[CannotAutomergeError]: """ References: https://developer.github.com/v3/issues/events/#list-events-for-an-issue """ url = ("https://api.github.com/repos/{}/{}/collaborators/{}/per...
[ "References", ":", "https", ":", "//", "developer", ".", "github", ".", "com", "/", "v3", "/", "issues", "/", "events", "/", "#list", "-", "events", "-", "for", "-", "an", "-", "issue" ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/auto_merge.py#L126-L150
[ "def", "check_collaborator_has_write", "(", "repo", ":", "GithubRepository", ",", "username", ":", "str", ")", "->", "Optional", "[", "CannotAutomergeError", "]", ":", "url", "=", "(", "\"https://api.github.com/repos/{}/{}/collaborators/{}/permission\"", "\"?access_token={}...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
check_auto_merge_labeler
References: https://developer.github.com/v3/issues/events/#list-events-for-an-issue
dev_tools/auto_merge.py
def check_auto_merge_labeler(repo: GithubRepository, pull_id: int ) -> Optional[CannotAutomergeError]: """ References: https://developer.github.com/v3/issues/events/#list-events-for-an-issue """ url = ("https://api.github.com/repos/{}/{}/issues/{}/events" ...
def check_auto_merge_labeler(repo: GithubRepository, pull_id: int ) -> Optional[CannotAutomergeError]: """ References: https://developer.github.com/v3/issues/events/#list-events-for-an-issue """ url = ("https://api.github.com/repos/{}/{}/issues/{}/events" ...
[ "References", ":", "https", ":", "//", "developer", ".", "github", ".", "com", "/", "v3", "/", "issues", "/", "events", "/", "#list", "-", "events", "-", "for", "-", "an", "-", "issue" ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/auto_merge.py#L153-L180
[ "def", "check_auto_merge_labeler", "(", "repo", ":", "GithubRepository", ",", "pull_id", ":", "int", ")", "->", "Optional", "[", "CannotAutomergeError", "]", ":", "url", "=", "(", "\"https://api.github.com/repos/{}/{}/issues/{}/events\"", "\"?access_token={}\"", ".", "f...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
add_comment
References: https://developer.github.com/v3/issues/comments/#create-a-comment
dev_tools/auto_merge.py
def add_comment(repo: GithubRepository, pull_id: int, text: str) -> None: """ References: https://developer.github.com/v3/issues/comments/#create-a-comment """ url = ("https://api.github.com/repos/{}/{}/issues/{}/comments" "?access_token={}".format(repo.organization, ...
def add_comment(repo: GithubRepository, pull_id: int, text: str) -> None: """ References: https://developer.github.com/v3/issues/comments/#create-a-comment """ url = ("https://api.github.com/repos/{}/{}/issues/{}/comments" "?access_token={}".format(repo.organization, ...
[ "References", ":", "https", ":", "//", "developer", ".", "github", ".", "com", "/", "v3", "/", "issues", "/", "comments", "/", "#create", "-", "a", "-", "comment" ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/auto_merge.py#L183-L200
[ "def", "add_comment", "(", "repo", ":", "GithubRepository", ",", "pull_id", ":", "int", ",", "text", ":", "str", ")", "->", "None", ":", "url", "=", "(", "\"https://api.github.com/repos/{}/{}/issues/{}/comments\"", "\"?access_token={}\"", ".", "format", "(", "repo...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
edit_comment
References: https://developer.github.com/v3/issues/comments/#edit-a-comment
dev_tools/auto_merge.py
def edit_comment(repo: GithubRepository, text: str, comment_id: int) -> None: """ References: https://developer.github.com/v3/issues/comments/#edit-a-comment """ url = ("https://api.github.com/repos/{}/{}/issues/comments/{}" "?access_token={}".format(repo.organization, ...
def edit_comment(repo: GithubRepository, text: str, comment_id: int) -> None: """ References: https://developer.github.com/v3/issues/comments/#edit-a-comment """ url = ("https://api.github.com/repos/{}/{}/issues/comments/{}" "?access_token={}".format(repo.organization, ...
[ "References", ":", "https", ":", "//", "developer", ".", "github", ".", "com", "/", "v3", "/", "issues", "/", "comments", "/", "#edit", "-", "a", "-", "comment" ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/auto_merge.py#L203-L220
[ "def", "edit_comment", "(", "repo", ":", "GithubRepository", ",", "text", ":", "str", ",", "comment_id", ":", "int", ")", "->", "None", ":", "url", "=", "(", "\"https://api.github.com/repos/{}/{}/issues/comments/{}\"", "\"?access_token={}\"", ".", "format", "(", "...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
get_branch_details
References: https://developer.github.com/v3/repos/branches/#get-branch
dev_tools/auto_merge.py
def get_branch_details(repo: GithubRepository, branch: str) -> Any: """ References: https://developer.github.com/v3/repos/branches/#get-branch """ url = ("https://api.github.com/repos/{}/{}/branches/{}" "?access_token={}".format(repo.organization, ...
def get_branch_details(repo: GithubRepository, branch: str) -> Any: """ References: https://developer.github.com/v3/repos/branches/#get-branch """ url = ("https://api.github.com/repos/{}/{}/branches/{}" "?access_token={}".format(repo.organization, ...
[ "References", ":", "https", ":", "//", "developer", ".", "github", ".", "com", "/", "v3", "/", "repos", "/", "branches", "/", "#get", "-", "branch" ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/auto_merge.py#L223-L240
[ "def", "get_branch_details", "(", "repo", ":", "GithubRepository", ",", "branch", ":", "str", ")", "->", "Any", ":", "url", "=", "(", "\"https://api.github.com/repos/{}/{}/branches/{}\"", "\"?access_token={}\"", ".", "format", "(", "repo", ".", "organization", ",", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
classify_pr_synced_state
References: https://developer.github.com/v3/pulls/#get-a-single-pull-request https://developer.github.com/v4/enum/mergestatestatus/
dev_tools/auto_merge.py
def classify_pr_synced_state(pr: PullRequestDetails) -> Optional[bool]: """ References: https://developer.github.com/v3/pulls/#get-a-single-pull-request https://developer.github.com/v4/enum/mergestatestatus/ """ state = pr.payload['mergeable_state'].lower() classification = { ...
def classify_pr_synced_state(pr: PullRequestDetails) -> Optional[bool]: """ References: https://developer.github.com/v3/pulls/#get-a-single-pull-request https://developer.github.com/v4/enum/mergestatestatus/ """ state = pr.payload['mergeable_state'].lower() classification = { ...
[ "References", ":", "https", ":", "//", "developer", ".", "github", ".", "com", "/", "v3", "/", "pulls", "/", "#get", "-", "a", "-", "single", "-", "pull", "-", "request", "https", ":", "//", "developer", ".", "github", ".", "com", "/", "v4", "/", ...
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/auto_merge.py#L312-L323
[ "def", "classify_pr_synced_state", "(", "pr", ":", "PullRequestDetails", ")", "->", "Optional", "[", "bool", "]", ":", "state", "=", "pr", ".", "payload", "[", "'mergeable_state'", "]", ".", "lower", "(", ")", "classification", "=", "{", "'behind'", ":", "...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
get_pr_review_status
References: https://developer.github.com/v3/pulls/reviews/#list-reviews-on-a-pull-request
dev_tools/auto_merge.py
def get_pr_review_status(pr: PullRequestDetails) -> Any: """ References: https://developer.github.com/v3/pulls/reviews/#list-reviews-on-a-pull-request """ url = ("https://api.github.com/repos/{}/{}/pulls/{}/reviews" "?access_token={}".format(pr.repo.organization, ...
def get_pr_review_status(pr: PullRequestDetails) -> Any: """ References: https://developer.github.com/v3/pulls/reviews/#list-reviews-on-a-pull-request """ url = ("https://api.github.com/repos/{}/{}/pulls/{}/reviews" "?access_token={}".format(pr.repo.organization, ...
[ "References", ":", "https", ":", "//", "developer", ".", "github", ".", "com", "/", "v3", "/", "pulls", "/", "reviews", "/", "#list", "-", "reviews", "-", "on", "-", "a", "-", "pull", "-", "request" ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/auto_merge.py#L326-L343
[ "def", "get_pr_review_status", "(", "pr", ":", "PullRequestDetails", ")", "->", "Any", ":", "url", "=", "(", "\"https://api.github.com/repos/{}/{}/pulls/{}/reviews\"", "\"?access_token={}\"", ".", "format", "(", "pr", ".", "repo", ".", "organization", ",", "pr", "."...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
get_pr_checks
References: https://developer.github.com/v3/checks/runs/#list-check-runs-for-a-specific-ref
dev_tools/auto_merge.py
def get_pr_checks(pr: PullRequestDetails) -> Dict[str, Any]: """ References: https://developer.github.com/v3/checks/runs/#list-check-runs-for-a-specific-ref """ url = ("https://api.github.com/repos/{}/{}/commits/{}/check-runs" "?access_token={}".format(pr.repo.organization, ...
def get_pr_checks(pr: PullRequestDetails) -> Dict[str, Any]: """ References: https://developer.github.com/v3/checks/runs/#list-check-runs-for-a-specific-ref """ url = ("https://api.github.com/repos/{}/{}/commits/{}/check-runs" "?access_token={}".format(pr.repo.organization, ...
[ "References", ":", "https", ":", "//", "developer", ".", "github", ".", "com", "/", "v3", "/", "checks", "/", "runs", "/", "#list", "-", "check", "-", "runs", "-", "for", "-", "a", "-", "specific", "-", "ref" ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/auto_merge.py#L346-L365
[ "def", "get_pr_checks", "(", "pr", ":", "PullRequestDetails", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "url", "=", "(", "\"https://api.github.com/repos/{}/{}/commits/{}/check-runs\"", "\"?access_token={}\"", ".", "format", "(", "pr", ".", "repo", ".", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
get_repo_ref
References: https://developer.github.com/v3/git/refs/#get-a-reference
dev_tools/auto_merge.py
def get_repo_ref(repo: GithubRepository, ref: str) -> Dict[str, Any]: """ References: https://developer.github.com/v3/git/refs/#get-a-reference """ url = ("https://api.github.com/repos/{}/{}/git/refs/{}" "?access_token={}".format(repo.organization, ...
def get_repo_ref(repo: GithubRepository, ref: str) -> Dict[str, Any]: """ References: https://developer.github.com/v3/git/refs/#get-a-reference """ url = ("https://api.github.com/repos/{}/{}/git/refs/{}" "?access_token={}".format(repo.organization, ...
[ "References", ":", "https", ":", "//", "developer", ".", "github", ".", "com", "/", "v3", "/", "git", "/", "refs", "/", "#get", "-", "a", "-", "reference" ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/auto_merge.py#L401-L418
[ "def", "get_repo_ref", "(", "repo", ":", "GithubRepository", ",", "ref", ":", "str", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "url", "=", "(", "\"https://api.github.com/repos/{}/{}/git/refs/{}\"", "\"?access_token={}\"", ".", "format", "(", "repo", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
list_pr_comments
References: https://developer.github.com/v3/issues/comments/#list-comments-on-an-issue
dev_tools/auto_merge.py
def list_pr_comments(repo: GithubRepository, pull_id: int ) -> List[Dict[str, Any]]: """ References: https://developer.github.com/v3/issues/comments/#list-comments-on-an-issue """ url = ("https://api.github.com/repos/{}/{}/issues/{}/comments" "?access_token={}".fo...
def list_pr_comments(repo: GithubRepository, pull_id: int ) -> List[Dict[str, Any]]: """ References: https://developer.github.com/v3/issues/comments/#list-comments-on-an-issue """ url = ("https://api.github.com/repos/{}/{}/issues/{}/comments" "?access_token={}".fo...
[ "References", ":", "https", ":", "//", "developer", ".", "github", ".", "com", "/", "v3", "/", "issues", "/", "comments", "/", "#list", "-", "comments", "-", "on", "-", "an", "-", "issue" ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/auto_merge.py#L426-L443
[ "def", "list_pr_comments", "(", "repo", ":", "GithubRepository", ",", "pull_id", ":", "int", ")", "->", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "url", "=", "(", "\"https://api.github.com/repos/{}/{}/issues/{}/comments\"", "\"?access_token={}\""...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
delete_comment
References: https://developer.github.com/v3/issues/comments/#delete-a-comment
dev_tools/auto_merge.py
def delete_comment(repo: GithubRepository, comment_id: int) -> None: """ References: https://developer.github.com/v3/issues/comments/#delete-a-comment """ url = ("https://api.github.com/repos/{}/{}/issues/comments/{}" "?access_token={}".format(repo.organization, ...
def delete_comment(repo: GithubRepository, comment_id: int) -> None: """ References: https://developer.github.com/v3/issues/comments/#delete-a-comment """ url = ("https://api.github.com/repos/{}/{}/issues/comments/{}" "?access_token={}".format(repo.organization, ...
[ "References", ":", "https", ":", "//", "developer", ".", "github", ".", "com", "/", "v3", "/", "issues", "/", "comments", "/", "#delete", "-", "a", "-", "comment" ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/auto_merge.py#L446-L460
[ "def", "delete_comment", "(", "repo", ":", "GithubRepository", ",", "comment_id", ":", "int", ")", "->", "None", ":", "url", "=", "(", "\"https://api.github.com/repos/{}/{}/issues/comments/{}\"", "\"?access_token={}\"", ".", "format", "(", "repo", ".", "organization",...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
attempt_sync_with_master
References: https://developer.github.com/v3/repos/merging/#perform-a-merge
dev_tools/auto_merge.py
def attempt_sync_with_master(pr: PullRequestDetails ) -> Union[bool, CannotAutomergeError]: """ References: https://developer.github.com/v3/repos/merging/#perform-a-merge """ master_sha = get_master_sha(pr.repo) remote = pr.remote_repo url = ("https://api.git...
def attempt_sync_with_master(pr: PullRequestDetails ) -> Union[bool, CannotAutomergeError]: """ References: https://developer.github.com/v3/repos/merging/#perform-a-merge """ master_sha = get_master_sha(pr.repo) remote = pr.remote_repo url = ("https://api.git...
[ "References", ":", "https", ":", "//", "developer", ".", "github", ".", "com", "/", "v3", "/", "repos", "/", "merging", "/", "#perform", "-", "a", "-", "merge" ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/auto_merge.py#L516-L557
[ "def", "attempt_sync_with_master", "(", "pr", ":", "PullRequestDetails", ")", "->", "Union", "[", "bool", ",", "CannotAutomergeError", "]", ":", "master_sha", "=", "get_master_sha", "(", "pr", ".", "repo", ")", "remote", "=", "pr", ".", "remote_repo", "url", ...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
attempt_squash_merge
References: https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-button
dev_tools/auto_merge.py
def attempt_squash_merge(pr: PullRequestDetails ) -> Union[bool, CannotAutomergeError]: """ References: https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-button """ url = ("https://api.github.com/repos/{}/{}/pulls/{}/merge" "?access_token={}".f...
def attempt_squash_merge(pr: PullRequestDetails ) -> Union[bool, CannotAutomergeError]: """ References: https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-button """ url = ("https://api.github.com/repos/{}/{}/pulls/{}/merge" "?access_token={}".f...
[ "References", ":", "https", ":", "//", "developer", ".", "github", ".", "com", "/", "v3", "/", "pulls", "/", "#merge", "-", "a", "-", "pull", "-", "request", "-", "merge", "-", "button" ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/auto_merge.py#L560-L595
[ "def", "attempt_squash_merge", "(", "pr", ":", "PullRequestDetails", ")", "->", "Union", "[", "bool", ",", "CannotAutomergeError", "]", ":", "url", "=", "(", "\"https://api.github.com/repos/{}/{}/pulls/{}/merge\"", "\"?access_token={}\"", ".", "format", "(", "pr", "."...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
auto_delete_pr_branch
References: https://developer.github.com/v3/git/refs/#delete-a-reference
dev_tools/auto_merge.py
def auto_delete_pr_branch(pr: PullRequestDetails) -> bool: """ References: https://developer.github.com/v3/git/refs/#delete-a-reference """ open_pulls = list_open_pull_requests(pr.repo, base_branch=pr.branch_name) if any(open_pulls): log('Not deleting branch {!r}. It is used elsewhe...
def auto_delete_pr_branch(pr: PullRequestDetails) -> bool: """ References: https://developer.github.com/v3/git/refs/#delete-a-reference """ open_pulls = list_open_pull_requests(pr.repo, base_branch=pr.branch_name) if any(open_pulls): log('Not deleting branch {!r}. It is used elsewhe...
[ "References", ":", "https", ":", "//", "developer", ".", "github", ".", "com", "/", "v3", "/", "git", "/", "refs", "/", "#delete", "-", "a", "-", "reference" ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/auto_merge.py#L598-L632
[ "def", "auto_delete_pr_branch", "(", "pr", ":", "PullRequestDetails", ")", "->", "bool", ":", "open_pulls", "=", "list_open_pull_requests", "(", "pr", ".", "repo", ",", "base_branch", "=", "pr", ".", "branch_name", ")", "if", "any", "(", "open_pulls", ")", "...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
add_labels_to_pr
References: https://developer.github.com/v3/issues/labels/#add-labels-to-an-issue
dev_tools/auto_merge.py
def add_labels_to_pr(repo: GithubRepository, pull_id: int, *labels: str, override_token: str = None) -> None: """ References: https://developer.github.com/v3/issues/labels/#add-labels-to-an-issue """ url = ("https://api.github.com/re...
def add_labels_to_pr(repo: GithubRepository, pull_id: int, *labels: str, override_token: str = None) -> None: """ References: https://developer.github.com/v3/issues/labels/#add-labels-to-an-issue """ url = ("https://api.github.com/re...
[ "References", ":", "https", ":", "//", "developer", ".", "github", ".", "com", "/", "v3", "/", "issues", "/", "labels", "/", "#add", "-", "labels", "-", "to", "-", "an", "-", "issue" ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/auto_merge.py#L642-L660
[ "def", "add_labels_to_pr", "(", "repo", ":", "GithubRepository", ",", "pull_id", ":", "int", ",", "*", "labels", ":", "str", ",", "override_token", ":", "str", "=", "None", ")", "->", "None", ":", "url", "=", "(", "\"https://api.github.com/repos/{}/{}/issues/{...
0827da80dd7880e5b923eb69407e980ed9bc0bd2
train
remove_label_from_pr
References: https://developer.github.com/v3/issues/labels/#remove-a-label-from-an-issue
dev_tools/auto_merge.py
def remove_label_from_pr(repo: GithubRepository, pull_id: int, label: str) -> bool: """ References: https://developer.github.com/v3/issues/labels/#remove-a-label-from-an-issue """ url = ("https://api.github.com/repos/{}/{}/issues/{}/labels/{}" ...
def remove_label_from_pr(repo: GithubRepository, pull_id: int, label: str) -> bool: """ References: https://developer.github.com/v3/issues/labels/#remove-a-label-from-an-issue """ url = ("https://api.github.com/repos/{}/{}/issues/{}/labels/{}" ...
[ "References", ":", "https", ":", "//", "developer", ".", "github", ".", "com", "/", "v3", "/", "issues", "/", "labels", "/", "#remove", "-", "a", "-", "label", "-", "from", "-", "an", "-", "issue" ]
quantumlib/Cirq
python
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/auto_merge.py#L663-L689
[ "def", "remove_label_from_pr", "(", "repo", ":", "GithubRepository", ",", "pull_id", ":", "int", ",", "label", ":", "str", ")", "->", "bool", ":", "url", "=", "(", "\"https://api.github.com/repos/{}/{}/issues/{}/labels/{}\"", "\"?access_token={}\"", ".", "format", "...
0827da80dd7880e5b923eb69407e980ed9bc0bd2