text stringlengths 81 112k |
|---|
Picks random edge from the set of edges.
Args:
edges: Set of edges to pick from.
Returns:
Random edge from the supplied set, or None for empty set.
def _choose_random_edge(self, edges: Set[EDGE]) -> Optional[EDGE]:
"""Picks random edge from the set of edges.
Args:... |
Runs line sequence search.
Args:
device: Chip description.
length: Required line length.
Returns:
List of linear sequences on the chip found by simulated annealing
method.
def place_line(self,
device: 'cirq.google.XmonDevice',
... |
An adjacency-respecting decomposition.
0: ───p───@──────────────@───────@──────────@──────────
│ │ │ │
1: ───p───X───@───p^-1───X───@───X──────@───X──────@───
│ │ │ │
2: ───p───────X───p──────────... |
A decomposition assuming the control separates the targets.
target1: ─@─X───────T──────@────────@─────────X───@─────X^-0.5─
│ │ │ │ │ │
control: ─X─@─X─────@─T^-1─X─@─T────X─@─X^0.5─@─@─X─@──────────
│ │ │ │ ... |
A decomposition assuming one of the targets is in the middle.
control: ───T──────@────────@───@────────────@────────────────
│ │ │ │
near: ─X─T──────X─@─T^-1─X─@─X────@─X^0.5─X─@─X^0.5────────
│ │ │ │ │
... |
Return a sequence of tuples representing a probabilistic combination.
A mixture is described by an iterable of tuples of the form
(probability of object, object)
The probability components of the tuples must sum to 1.0 and be between
0 and 1 (inclusive).
Args:
val: The value whose mi... |
Returns whether the value has a mixture representation.
Returns:
If `val` has a `_has_mixture_` method and its result is not
NotImplemented, that result is returned. Otherwise, if the value
has a `_mixture_` method return True if that has a non-default value.
Returns False if neithe... |
Return a sequence of tuples for a channel that is a mixture of unitaries.
In contrast to `mixture` this method falls back to `unitary` if `_mixture_`
is not implemented.
A mixture channel is described by an iterable of tuples of the form
(probability of unitary, unitary)
The probability comp... |
Returns whether the value has a mixture channel representation.
In contrast to `has_mixture` this method falls back to checking whether
the value has a unitary representation via `has_channel`.
Returns:
If `val` has a `_has_mixture_` method and its result is not
NotImplemented, that result... |
Validates that the mixture's tuple are valid probabilities.
def validate_mixture(supports_mixture: SupportsMixture):
"""Validates that the mixture's tuple are valid probabilities."""
mixture_tuple = mixture(supports_mixture, None)
if mixture_tuple is None:
raise TypeError('{}_mixture did not have a... |
Computes displays in the supplied Circuit or Schedule.
Args:
program: The circuit or schedule to simulate.
param_resolver: Parameters to run with the program.
qubit_order: Determines the canonical ordering of the qubits used
to define the order of amplitudes ... |
Decorator that ensures a pool is available for a stepper.
def ensure_pool(func):
"""Decorator that ensures a pool is available for a stepper."""
def func_wrapper(*args, **kwargs):
if len(args) == 0 or not isinstance(args[0], Stepper):
raise Exception('@ensure_pool can only be used on Steppe... |
Accumulates single qubit phase gates into the scratch shards.
def _single_qubit_accumulate_into_scratch(args: Dict[str, Any]):
"""Accumulates single qubit phase gates into the scratch shards."""
index = args['indices'][0]
shard_num = args['shard_num']
half_turns = args['half_turns']
num_shard_qubit... |
Returns a projector onto the |1> subspace of the index-th qubit.
def _one_projector(args: Dict[str, Any], index: int) -> Union[int, np.ndarray]:
"""Returns a projector onto the |1> subspace of the index-th qubit."""
num_shard_qubits = args['num_shard_qubits']
shard_num = args['shard_num']
if index >= n... |
Accumulates two qubit phase gates into the scratch shards.
def _two_qubit_accumulate_into_scratch(args: Dict[str, Any]):
"""Accumulates two qubit phase gates into the scratch shards."""
index0, index1 = args['indices']
half_turns = args['half_turns']
scratch = _scratch_shard(args)
projector = _one... |
Takes scratch shards and applies them as exponentiated phase to state.
def _apply_scratch_as_phase(args: Dict[str, Any]):
"""Takes scratch shards and applies them as exponentiated phase to state.
"""
state = _state_shard(args)
state *= np.exp(I_PI_OVER_2 * _scratch_shard(args)) |
Applies a W gate when the gate acts only within a shard.
def _w_within_shard(args: Dict[str, Any]):
"""Applies a W gate when the gate acts only within a shard."""
index = args['index']
half_turns = args['half_turns']
axis_half_turns = args['axis_half_turns']
state = _state_shard(args)
pm_vect =... |
Applies a W gate when the gate acts between shards.
def _w_between_shards(args: Dict[str, Any]):
"""Applies a W gate when the gate acts between shards."""
shard_num = args['shard_num']
state = _state_shard(args)
num_shard_qubits = args['num_shard_qubits']
index = args['index']
half_turns = args... |
Copes scratch shards to state shards.
def _copy_scratch_to_state(args: Dict[str, Any]):
"""Copes scratch shards to state shards."""
np.copyto(_state_shard(args), _scratch_shard(args)) |
Returns the probability of getting a one measurement on a state shard.
def _one_prob_per_shard(args: Dict[str, Any]) -> float:
"""Returns the probability of getting a one measurement on a state shard.
"""
index = args['index']
state = _state_shard(args) * _one_projector(args, index)
norm = np.lina... |
Returns the norm for each state shard.
def _norm_squared(args: Dict[str, Any]) -> float:
"""Returns the norm for each state shard."""
state = _state_shard(args)
return np.sum(np.abs(state) ** 2) |
Renormalizes the state using the norm arg.
def _renorm(args: Dict[str, Any]):
"""Renormalizes the state using the norm arg."""
state = _state_shard(args)
# If our gate is so bad that we have norm of zero, we have bigger problems.
state /= np.sqrt(args['norm_squared']) |
Projects state shards onto the appropriate post measurement state.
This function makes no assumptions about the interpretation of quantum
theory.
Args:
args: The args from shard_num_args.
def _collapse_state(args: Dict[str, Any]):
"""Projects state shards onto the appropriate post measurement... |
Initializes bitwise vectors which is precomputed in shared memory.
There are two types of vectors here, a zero one vectors and a pm
(plus/minus) vectors. The pm vectors have rows that are Pauli Z
operators acting on the all ones vector. The column-th row corresponds
to the Pauli Z actin... |
Initializes a scratch pad equal in size to the wavefunction.
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.SharedMem... |
Initializes a the shard wavefunction and sets the initial state.
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),
(... |
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
... |
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... |
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
... |
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
... |
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.
def simulate_measurement(self, index: int) -> bool:
"""Simulates a single qubit measurement in ... |
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... |
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
def fswap(p, q):
"""Decompose the Fermionic SWAP gate into two single-qubit gates and
one iSWAP gate.
Args:
p: the id of the f... |
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... |
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 ... |
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... |
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
def fermi_fouri... |
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... |
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... |
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... |
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... |
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
... |
Validates that the given state is a valid wave function.
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 != ... |
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 ... |
Returns the probabilities for a measurement on the given indices.
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 ... |
Validates that state's size is a power of 2, returning number of qubits.
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 o... |
Validates that the indices have values within range of num_qubits.
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... |
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.... |
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 ... |
The maximum number of qubits to be acquainted with each other.
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):
rais... |
Starts the search or gives previously calculated sequence.
Returns:
The linear qubit sequence found.
def get_or_search(self) -> List[GridQubit]:
"""Starts the search or gives previously calculated sequence.
Returns:
The linear qubit sequence found.
"""
... |
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.
def _find_s... |
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... |
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.
def _expand_sequence(self, seq: List[GridQubit]) -> Li... |
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... |
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... |
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.
de... |
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... |
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:
"... |
Returns an equal moment, but without ops on the given qubits.
Args:
qubits: Operations that touch these will be removed.
Returns:
The new moment.
def without_operations_touching(self, qubits: Iterable[raw_types.Qid]):
"""Returns an equal moment, but without ops on the ... |
See `cirq.protocols.SupportsApproximateEquality`.
def _approx_eq_(self, other: Any, atol: Union[int, float]) -> bool:
"""See `cirq.protocols.SupportsApproximateEquality`."""
if not isinstance(other, type(self)):
return NotImplemented
return approx_eq(self.operations, other.operation... |
Returns true only if the operations have qubits in common.
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) |
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... |
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.
def schedule_to_proto_dicts(schedule: Schedul... |
Convert proto dictionaries into a Schedule for the given device.
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 o... |
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... |
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... |
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.
def is_native_xmon_op(op: ops.Operation) -> bool:
"""Check if the gate corresponding to an operation is a native xmon ga... |
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.
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 th... |
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 (... |
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... |
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
... |
Remove terms with coefficients of absolute value atol or less.
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 s... |
Checks whether two linear combinations are approximately equal.
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(... |
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... |
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.
def dequeue(self) -> Tuple[int, TIt... |
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 ... |
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... |
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.
def get_program(self, program_resource_name: str) -> Di... |
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:
... |
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.
... |
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`.
def cancel_job(self, job_resource_name: str):
"""Cancels the given job.
See also the canc... |
Returns the job results, blocking until the job is complete.
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'][... |
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... |
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... |
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... |
Determines if two qubits are adjacent qubits.
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) |
Proto dict must have 'row' and 'col' keys.
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(prot... |
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.""" |
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]:
"""Ca... |
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... |
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.
def highlight(text: str, color_co... |
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.
async def _async_forward... |
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... |
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... |
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... |
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... |
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... |
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... |
Wraps the input into the range (-1, +1].
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:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.