docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Checks if the tensor's elements are all near zero. Args: a: Tensor of elements that could all be near zero. atol: Absolute tolerance.
def all_near_zero(a: Union[float, complex, Iterable[float], np.ndarray], *, atol: float = 1e-8) -> bool: return np.all(np.less_equal(np.abs(a), atol))
126,896
Checks if the tensor's elements are all near multiples of the period. Args: a: Tensor of elements that could all be near multiples of the period. period: The period, e.g. 2 pi when working in radians. atol: Absolute tolerance.
def all_near_zero_mod(a: Union[float, complex, Iterable[float], np.ndarray], period: float, *, atol: float = 1e-8) -> bool: b = (np.asarray(a) + period / 2) % period - period / 2 return np.all(np.less_equal(np.abs(b), atol))
126,897
Uses content from github to create a dir for testing and comparisons. Args: destination_directory: The location to fetch the contents into. repository: The github repository that the commit lives under. pull_request_number: The id of the pull request to clone. If None, then the ...
def fetch_github_pull_request(destination_directory: str, repository: github_repository.GithubRepository, pull_request_number: int, verbose: bool ) -> prepared_env.PreparedEnv: branch = 'pul...
126,902
Uses local files to create a directory for testing and comparisons. Args: destination_directory: The directory where the copied files should go. verbose: When set, more progress output is produced. Returns: Commit ids corresponding to content to test/compare.
def fetch_local_files(destination_directory: str, verbose: bool) -> prepared_env.PreparedEnv: staging_dir = destination_directory + '-staging' try: shutil.copytree(get_repo_root(), staging_dir) os.chdir(staging_dir) if verbose: print('chdir', stagin...
126,903
Transforms a circuit into a series of GroupMatrix+CZ layers. Args: circuit: The circuit to transform. grouping: How the circuit's qubits are combined into groups. Returns: A list of layers. Each layer has a matrix to apply to each group of qubits, and a list of CZs to apply to ...
def _circuit_as_layers(circuit: circuits.Circuit, grouping: _QubitGrouping) -> List[_TransformsThenCzs]: frontier = {q: 0 for q in circuit.all_qubits()} layers = [] while True: # Pull within-group operations into per-group matrices. any_group_matrices = False ...
126,916
Samples from the given Circuit or Schedule. Args: program: The circuit or schedule to simulate. param_resolver: Parameters to run with the program. repetitions: The number of repetitions to simulate. Returns: TrialResult for a run.
def run( self, program: Union[circuits.Circuit, schedules.Schedule], param_resolver: 'study.ParamResolverOrSimilarType' = None, repetitions: int = 1, ) -> study.TrialResult: return self.run_sweep(program, study.ParamResolver(param_resolver), ...
126,933
Samples from the given Circuit or Schedule. In contrast to run, this allows for sweeping over different parameter values. Args: program: The circuit or schedule to simulate. params: Parameters to run with the program. repetitions: The number of repetitions t...
def run_sweep( self, program: Union[circuits.Circuit, schedules.Schedule], params: study.Sweepable, repetitions: int = 1, ) -> List[study.TrialResult]:
126,934
Returns a list of operations individually measuring the given qubits. The qubits are measured in the computational basis. Args: *qubits: The qubits to measure. key_func: Determines the key of the measurements of each qubit. Takes the qubit and returns the key for that qubit. Defaul...
def measure_each(*qubits: raw_types.Qid, key_func: Callable[[raw_types.Qid], str] = str ) -> List[gate_operation.GateOperation]: return [MeasurementGate(1, key_func(q)).on(q) for q in qubits]
126,939
Checks if this gate can be applied to the given qubits. By default checks if input is of type Qid and qubit count. Child classes can override. Args: qubits: The collection of qubits to potentially apply the gate to. Throws: ValueError: The gate can't be applied...
def validate_args(self, qubits: Sequence[Qid]) -> None: if len(qubits) == 0: raise ValueError( "Applied a gate to an empty set of qubits. Gate: {}".format( repr(self))) if len(qubits) != self.num_qubits(): raise ValueError( ...
126,966
Returns an application of this gate to the given qubits. Args: *qubits: The collection of qubits to potentially apply the gate to.
def on(self, *qubits: Qid) -> 'gate_operation.GateOperation': # Avoids circular import. from cirq.ops import gate_operation return gate_operation.GateOperation(self, list(qubits))
126,967
Returns a controlled version of this gate. Args: control_qubits: Optional qubits to control the gate by.
def controlled_by(self, *control_qubits: Qid) -> 'Gate': # Avoids circular import. from cirq.ops import ControlledGate return ControlledGate(self, control_qubits, len(control_qubits) if control_qubits is not None ...
126,973
Returns the same operation, but with different qubits. Args: func: The function to use to turn each current qubit into a desired new qubit. Returns: The receiving operation but with qubits transformed by the given function.
def transform_qubits(self: TSelf_Operation, func: Callable[[Qid], Qid]) -> TSelf_Operation: return self.with_qubits(*(func(q) for q in self.qubits))
126,974
Returns a controlled version of this operation. Args: control_qubits: Qubits to control the operation by. Required.
def controlled_by(self, *control_qubits: Qid) -> 'Operation': # Avoids circular import. from cirq.ops import ControlledOperation if control_qubits is None or len(control_qubits) is 0: raise ValueError( "Can't get controlled operation without control qubit. Op...
126,975
The value of the display, derived from the full wavefunction. Args: state: The wavefunction. qubit_map: A dictionary from qubit to qubit index in the ordering used to define the wavefunction.
def value_derived_from_wavefunction(self, state: np.ndarray, qubit_map: Dict[raw_types.Qid, int] ) -> Any:
126,977
Evaluates the status check and returns a pass/fail with message. Args: env: Describes a prepared python 3 environment in which to run. verbose: When set, more progress output is produced. Returns: A tuple containing a pass/fail boolean and then a details message.
def perform_check(self, env: env_tools.PreparedEnv, verbose: bool) -> Tuple[bool, str]:
126,981
Evaluates this check. Args: env: The prepared python environment to run the check in. verbose: When set, more progress output is produced. previous_failures: Checks that have already run and failed. Returns: A CheckResult instance.
def run(self, env: env_tools.PreparedEnv, verbose: bool, previous_failures: Set['Check']) -> CheckResult: # Skip if a dependency failed. if previous_failures.intersection(self.dependencies): print(shell_tools.highlight( 'Skipped '...
126,982
Returns a QCircuit-based latex diagram of the given circuit. Args: circuit: The circuit to represent in latex. qubit_order: Determines the order of qubit wires in the diagram. Returns: Latex code for the diagram.
def circuit_to_latex_using_qcircuit( circuit: circuits.Circuit, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT) -> str: diagram = circuit.to_text_diagram_drawer( qubit_namer=qcircuit_qubit_namer, qubit_order=qubit_order, get_circuit_diagram_info=get_qcircuit_...
127,000
Computes the kronecker product of a sequence of matrices. A *args version of lambda args: functools.reduce(np.kron, args). Args: *matrices: The matrices and controls to combine with the kronecker product. Returns: The resulting matrix.
def kron(*matrices: np.ndarray) -> np.ndarray: product = np.eye(1) for m in matrices: product = np.kron(product, m) return np.array(product)
127,001
Computes the dot/matrix product of a sequence of values. A *args version of np.linalg.multi_dot. Args: *values: The values to combine with the dot/matrix product. Returns: The resulting value or matrix.
def dot(*values: Union[float, complex, np.ndarray] ) -> Union[float, complex, np.ndarray]: if len(values) == 1: if isinstance(values[0], np.ndarray): return np.array(values[0]) return values[0] return np.linalg.multi_dot(values)
127,003
Concatenates blocks into a block diagonal matrix. Args: *blocks: Square matrices to place along the diagonal of the result. Returns: A block diagonal matrix with the given blocks along its diagonal. Raises: ValueError: A block isn't square.
def block_diag(*blocks: np.ndarray) -> np.ndarray: for b in blocks: if b.shape[0] != b.shape[1]: raise ValueError('Blocks must be square.') if not blocks: return np.zeros((0, 0), dtype=np.complex128) n = sum(b.shape[0] for b in blocks) dtype = functools.reduce(_merge_d...
127,005
Finds the first index of a target item within a list of lists. Args: seqs: The list of lists to search. target: The item to find. Raises: ValueError: Item is not present.
def index_2d(seqs: List[List[Any]], target: Any) -> Tuple[int, int]: for i in range(len(seqs)): for j in range(len(seqs[i])): if seqs[i][j] == target: return i, j raise ValueError('Item not present.')
127,006
Greedy sequence search constructor. Args: device: Chip description. seed: Optional seed value for random number generator.
def __init__(self, device: 'cirq.google.XmonDevice', seed=None) -> None: self._c = device.qubits self._c_adj = chip_as_adjacency_list(device) self._rand = np.random.RandomState(seed)
127,007
Cost function that sums squares of lengths of sequences. Args: state: Search state, not mutated. Returns: Cost which is minus the normalized quadratic sum of each linear sequence section in the state. This promotes single, long linear sequence solutions and conv...
def _quadratic_sum_cost(self, state: _STATE) -> float: cost = 0.0 total_len = float(len(self._c)) seqs, _ = state for seq in seqs: cost += (len(seq) / total_len) ** 2 return -cost
127,009
Move function which repeats _force_edge_active_move a few times. Args: state: Search state, not mutated. Returns: New search state which consists of incremental changes of the original state.
def _force_edges_active_move(self, state: _STATE) -> _STATE: for _ in range(self._rand.randint(1, 4)): state = self._force_edge_active_move(state) return state
127,010
Move which forces a random edge to appear on some sequence. This move chooses random edge from the edges which do not belong to any sequence and modifies state in such a way, that this chosen edge appears on some sequence of the search state. Args: state: Search state, not mu...
def _force_edge_active_move(self, state: _STATE) -> _STATE: seqs, edges = state unused_edges = edges.copy() # List edges which do not belong to any linear sequence. for seq in seqs: for i in range(1, len(seq)): unused_edges.remove(self._normalize_edg...
127,011
Move which forces given edge to appear on some sequence. Args: seqs: List of linear sequences covering chip. edge: Edge to be activated. sample_bool: Callable returning random bool. Returns: New list of linear sequences with given edge on some of the s...
def _force_edge_active(self, seqs: List[List[GridQubit]], edge: EDGE, sample_bool: Callable[[], bool] ) -> List[List[GridQubit]]: n0, n1 = edge # Make a copy of original sequences. seqs = list(seqs) # Localize edge nodes w...
127,012
Gives unique representative of the edge. Two edges are equivalent if they form an edge between the same nodes. This method returns representative of this edge which can be compared using equality operator later. Args: edge: Edge to normalize. Returns: Norma...
def _normalize_edge(self, edge: EDGE) -> EDGE: def lower(n: GridQubit, m: GridQubit) -> bool: return n.row < m.row or (n.row == m.row and n.col < m.col) n1, n2 = edge return (n1, n2) if lower(n1, n2) else (n2, n1)
127,014
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]: if edges: index = self._rand.randint(len(edges)) for e in edges: if not index: return e index -= 1 return None
127,015
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', length: int) -> GridQubitLineTuple: seqs = AnnealSequenceSearch(device, self.seed).search(self.trace_func) return GridQubitLineTuple.best_of(seqs, length)
127,017
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]): index = args['index'] result = args['result'] prob_one = args['prob_one'] state = _state_shard(args) normalization = np.sqrt(prob_one if result else 1 - prob_one) state *= (_one_projector(args, index) * result + (1 - _one_projector(a...
127,055
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 ...
def simulate_w(self, index: int, half_turns: float, axis_half_turns: float): args = self._shard_num_args({ 'index': index, 'half_turns': half_turns, 'axis_half_turns': axis_half_turns }) if inde...
127,068
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: args = self._shard_num_args({'index': index}) prob_one = np.sum(self._pool.map(_one_prob_per_shard, args)) result = bool(np.random.random() <= prob_one) args = self._shard_num_args({ 'index': index, 're...
127,069
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...
def sample_measurements( self, indices: List[int], repetitions: int=1) -> List[List[bool]]: # Stepper uses little endian while sample_state uses big endian. reversed_indices = [self._num_qubits - 1 - index for index in indices] return sim.sample_state...
127,070
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): yield cirq.ISWAP(q, p), cirq.Z(p) ** 1.5 yield cirq.Z(q) ** 1.5
127,074
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...
def fermi_fourier_trans_inverse_4(qubits): yield fswap(qubits[1], qubits[2]), yield fermi_fourier_trans_2(qubits[0], qubits[1]) yield fermi_fourier_trans_2(qubits[2], qubits[3]) yield fswap(qubits[1], qubits[2]) yield fermi_fourier_trans_2(qubits[0], qubits[1]) yield cirq.S(qubits[2]) ...
127,077
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_fourier_trans_inverse_conjugate_4(qubits): yield fswap(qubits[1], qubits[2]), yield fermi_fourier_trans_2(qubits[0], qubits[1]) yield fermi_fourier_trans_2(qubits[2], qubits[3]) yield fswap(qubits[1], qubits[2]) yield fermi_fourier_trans_2(qubits[0], qubits[1]) yield cirq.S(qubit...
127,078
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...
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) # The hopping energy as a function of wave numbers hop_erg = -2 * t * np.cos(2 * np.pi * wave_num) # Finding the Fermi energy fermi_e...
127,079
Greedy sequence search constructor. Args: device: Chip description. start: Starting qubit. Raises: ValueError: When start qubit is not part of a chip.
def __init__(self, device: 'cirq.google.XmonDevice', start: GridQubit) -> None: if start not in device.qubits: raise ValueError('Starting qubit must be a qubit on the chip') self._c = device.qubits self._c_adj = chip_as_adjacency_list(devic...
127,095
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]) -> List[GridQubit]: i = 1 while i < len(seq): path = self._find_path_between(seq[i - 1], seq[i], set(seq)) if path: seq = seq[:i] + path + seq[i:] else: i += 1 return seq
127,099
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...
def _collect_unused(self, start: GridQubit, used: Set[GridQubit]) -> Set[GridQubit]: def collect(n: GridQubit, visited: Set[GridQubit]): visited.add(n) for m in self._c_adj[n]: if m not in used and m not in visited: co...
127,104
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.
def place_line(self, device: 'cirq.google.XmonDevice', length: int) -> GridQubitLineTuple: if not device.qubits: return GridQubitLineTuple() start = min(device.qubits) # type: GridQubit sequences = [] # type: List[LineSequence] ...
127,105
Constructs a moment with the given operations. Args: operations: The operations applied within the moment. Will be frozen into a tuple before storing. Raises: ValueError: A qubit appears more than once.
def __init__(self, operations: Iterable[raw_types.Operation] = ()) -> None: self.operations = tuple(operations) # Check that operations don't overlap. affected_qubits = [q for op in self.operations for q in op.qubits] self.qubits = frozenset(affected_qubits) if len(affe...
127,108
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: return any(q in qubits for q in self.qubits)
127,109
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]): qubits = frozenset(qubits) if not self.operates_on(qubits): return self return Moment( operation for operation in self.operations if qubits.isdisjoint(frozenset(operation.qubits))...
127,110
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: Schedule) -> Iterable[Dict]: last_time_picos = None # type: Optional[int] for so in schedule.scheduled_operations: op = gate_to_proto_dict( cast(ops.GateOperation, so.operation).gate, so.operation.qubits) time_picos = so.time.ra...
127,136
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: return (isinstance(op, ops.GateOperation) and is_native_xmon_gate(op.gate))
127,140
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: return isinstance(gate, (ops.CZPowGate, ops.MeasurementGate, ops.PhasedXPowGate, ops.XPowGate, ops.YPowGate, ops.ZPow...
127,141
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 (...
def xmon_op_from_proto_dict(proto_dict: Dict) -> ops.Operation: def raise_missing_fields(gate_name: str): raise ValueError( '{} missing required fields: {}'.format(gate_name, proto_dict)) param = _parameterized_value_from_proto_dict qubit = devices.GridQubit.from_proto_dict if ...
127,142
Initializes a new priority queue. Args: entries: Initial contents of the priority queue. drop_duplicate_entries: If set, the priority queue will ignore operations that enqueue a (priority, item) pair that is already in the priority queue. Note that duplic...
def __init__(self, entries: Iterable[Tuple[int, TItem]] = (), *, drop_duplicate_entries: bool=False): self._buckets = [] # type: List[List[TItem]] self._offset = 0 self._len = 0 self._drop_set = (set() ...
127,175
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) -> Dict: return self.service.projects().programs().get( name=program_resource_name).execute()
127,198
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: ...
def get_job(self, job_resource_name: str) -> Dict: return self.service.projects().programs().jobs().get( name=job_resource_name).execute()
127,199
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.
def get_job_results(self, job_resource_name: str) -> List[TrialResult]: response = self.service.projects().programs().jobs().getResult( parent=job_resource_name).execute() trial_results = [] for sweep_result in response['result']['sweepResults']: sweep_repetition...
127,200
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): self.service.projects().programs().jobs().cancel( name=job_resource_name, body={}).execute()
127,201
A job submitted to the engine. Args: job_config: The JobConfig used to create the job. job: A full Job Dict. engine: Engine connected to the job.
def __init__(self, job_config: JobConfig, job: Dict, engine: Engine) -> None: self.job_config = job_config self._job = job self._engine = engine self.job_resource_name = job['name'] self.program_resource_name = self.job_...
127,210
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...
def flatten_op_tree(root: OP_TREE, preserve_moments: bool = False ) -> Iterable[Union[Operation, Moment]]: if (isinstance(root, Operation) or preserve_moments and isinstance(root, Moment)): yield root return if isinstance(root, collection...
127,213
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...
def merge_single_qubit_gates_into_phased_x_z( circuit: circuits.Circuit, atol: float = 1e-8) -> None: def synth(qubit: ops.Qid, matrix: np.ndarray) -> List[ops.Operation]: out_gates = decompositions.single_qubit_matrix_to_phased_x_z( matrix, atol) return [gate(qubit...
127,231
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_code: int, bold: bool=False) -> str: return '{}\033[{}m{}\033[0m'.format( '\033[1m' if bold else '', color_code, text,)
127,235
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(async_chunks: collections.AsyncIterable, out: Optional[Union[TeeCapture, IO[str]]] ) -> Optional[str]: capture = isinstance(out, TeeCapture) out_pipe = out.out_pipe if isinstance(out, TeeCapture) else out chunks = [] if capture...
127,236
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...
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: process = await future_process future_output = _async_forward(process.stdout, out) future_er...
127,237
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...
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]: if len([1 for e in [half_turns, rads, degs] if e is not None]) > 1: ...
127,242
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...
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]: return canonicalize_half_turns( chosen_angle_to_half_tu...
127,243
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, ...
def single_qubit_matrix_to_pauli_rotations( mat: np.ndarray, atol: float = 0 ) -> List[Tuple[ops.Pauli, float]]: def is_clifford_rotation(half_turns): return near_zero_mod(half_turns, 0.5, atol=atol) def to_quarter_turns(half_turns): return round(2 * half_turns) % 4 def is_qu...
127,246
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 ...
def single_qubit_matrix_to_gates( mat: np.ndarray, tolerance: float = 0 ) -> List[ops.SingleQubitGate]: rotations = single_qubit_matrix_to_pauli_rotations(mat, tolerance) return [cast(ops.SingleQubitGate, pauli)**ht for pauli, ht in rotations]
127,247
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...
def _deconstruct_single_qubit_matrix_into_gate_turns( mat: np.ndarray) -> Tuple[float, float, float]: pre_phase, rotation, post_phase = ( linalg.deconstruct_single_qubit_matrix_into_angles(mat)) # Figure out parameters of the actual gates we will do. tau = 2 * np.pi xy_turn = rotat...
127,249
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...
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 = ( _deconstruct_single_qubit_matrix_into_gate_turns(mat)) # Build the intended operation out of non-negligible XY and Z rotations. resu...
127,250
Calculates probability and draws if solution should be accepted. Based on exp(-Delta*E/T) formula. Args: random_sample: Uniformly distributed random number in the range [0, 1). cost_diff: Cost difference between new and previous solutions. temp: Current temperature. Returns: ...
def _accept(random_sample: float, cost_diff: float, temp: float) -> Tuple[bool, float]: exponent = -cost_diff / temp if exponent >= 0.0: return True, 1.0 else: probability = math.exp(exponent) return probability > random_sample, probability
127,297
Density matrix simulator. Args: dtype: The `numpy.dtype` used by the simulation. One of `numpy.complex64` or `numpy.complex128` noise: A noise model to apply while simulating.
def __init__(self, *, dtype: Type[np.number] = np.complex64, noise: devices.NoiseModel = devices.NO_NOISE): if dtype not in {np.complex64, np.complex128}: raise ValueError( 'dtype must be complex64 or complex128, was {}'.for...
127,312
DensityMatrixStepResult. Args: density_matrix: The density matrix at this step. Can be mutated. measurements: The measurements for this step of the simulation. qubit_map: A map from qid to index used to define the ordering of the basis in density_matrix. ...
def __init__(self, density_matrix: np.ndarray, measurements: Dict[str, np.ndarray], qubit_map: Dict[ops.Qid, int], dtype: Type[np.number] = np.complex64): super().__init__(measurements) self._density_matrix = density_matrix self._qubit_map...
127,318
Return only the Clifford part of a circuit. See convert_and_separate_circuit(). Args: circuit: A Circuit with the gate set {SingleQubitCliffordGate, PauliInteractionGate, PauliStringPhasor}. Returns: A Circuit with SingleQubitCliffordGate and PauliInteractionGate gates. ...
def regular_half(circuit: circuits.Circuit) -> circuits.Circuit: return circuits.Circuit( ops.Moment(op for op in moment.operations if not isinstance(op, ops.PauliStringPhasor)) for moment in circuit)
127,344
Return only the non-Clifford part of a circuit. See convert_and_separate_circuit(). Args: circuit: A Circuit with the gate set {SingleQubitCliffordGate, PauliInteractionGate, PauliStringPhasor}. Returns: A Circuit with only PauliStringPhasor operations.
def pauli_string_half(circuit: circuits.Circuit) -> circuits.Circuit: return circuits.Circuit.from_ops( _pull_non_clifford_before(circuit), strategy=circuits.InsertStrategy.EARLIEST)
127,345
Initializes a circuit. Args: moments: The initial list of moments defining the circuit. device: Hardware that the circuit should be able to run on.
def __init__(self, moments: Iterable[ops.Moment] = (), device: devices.Device = devices.UnconstrainedDevice) -> None: self._moments = list(moments) self._device = device self._device.validate_circuit(self)
127,361
Creates an empty circuit and appends the given operations. Args: operations: The operations to append to the new circuit. strategy: How to append the operations. device: Hardware that the circuit should be able to run on. Returns: The constructed circuit...
def from_ops(*operations: ops.OP_TREE, strategy: InsertStrategy = InsertStrategy.EARLIEST, device: devices.Device = devices.UnconstrainedDevice ) -> 'Circuit': result = Circuit(device=device) result.append(operations, strategy) return r...
127,363
Maps the current circuit onto a new device, and validates. Args: new_device: The new device that the circuit should be on. qubit_mapping: How to translate qubits from the old device into qubits on the new device. Returns: The translated circuit.
def with_device( self, new_device: devices.Device, qubit_mapping: Callable[[ops.Qid], ops.Qid] = lambda e: e, ) -> 'Circuit': return Circuit( moments=[ops.Moment(operation.transform_qubits(qubit_mapping) for operation in mo...
127,375
Finds the operation on a qubit within a moment, if any. Args: qubit: The qubit to check for an operation on. moment_index: The index of the moment to check for an operation within. Allowed to be beyond the end of the circuit. Returns: None if there i...
def operation_at(self, qubit: ops.Qid, moment_index: int) -> Optional[ops.Operation]: if not 0 <= moment_index < len(self._moments): return None for op in self._moments[moment_index].operations: if qubit in op.qubits: ...
127,385
Find the locations of all gate operations of a given type. Args: gate_type: The type of gate to find, e.g. XPowGate or MeasurementGate. Returns: An iterator (index, operation, gate)'s for operations with the given gate type.
def findall_operations_with_gate_type( self, gate_type: Type[T_DESIRED_GATE_TYPE] ) -> Iterable[Tuple[int, ops.GateOperation, T_DESIRED_GATE_TYPE]]: result = self.findall_operations(lambda operation: bool( ops.op_ga...
127,387
Check whether all of the ops that satisfy a predicate are terminal. Args: predicate: A predicate on ops.Operations which is being checked. Returns: Whether or not all `Operation` s in a circuit that satisfy the given predicate are terminal.
def are_all_matches_terminal(self, predicate: Callable[[ops.Operation], bool]): return all( self.next_moment_operating_on(op.qubits, i + 1) is None for (i, op) in self.findall_operations(predicate) )
127,388
Determines and prepares where an insertion will occur. Args: splitter_index: The index to insert at. op: The operation that will be inserted. strategy: The insertion strategy. Returns: The index of the (possibly new) moment where the insertion should ...
def _pick_or_create_inserted_op_moment_index( self, splitter_index: int, op: ops.Operation, strategy: InsertStrategy) -> int: if (strategy is InsertStrategy.NEW or strategy is InsertStrategy.NEW_THEN_INLINE): self._moments.insert(splitter_index, ops....
127,389
Inserts operations inline at frontier. Args: operations: the operations to insert start: the moment at which to start inserting the operations frontier: frontier[q] is the earliest moment in which an operation acting on qubit q can be placed.
def insert_at_frontier(self, operations: ops.OP_TREE, start: int, frontier: Dict[ops.Qid, int] = None ) -> Dict[ops.Qid, int]: if frontier is None: frontier = defaultdict(lambda: 0) ...
127,398
Appends operations onto the end of the circuit. Moments within the operation tree are appended intact. Args: moment_or_operation_tree: The moment or operation tree to append. strategy: How to pick/create the moment to put operations into.
def append( self, moment_or_operation_tree: Union[ops.Moment, ops.OP_TREE], strategy: InsertStrategy = InsertStrategy.EARLIEST): self.insert(len(self._moments), moment_or_operation_tree, strategy)
127,402
Clears operations that are touching given qubits at given moments. Args: qubits: The qubits to check for operations on. moment_indices: The indices of moments to check for operations within.
def clear_operations_touching(self, qubits: Iterable[ops.Qid], moment_indices: Iterable[int]): qubits = frozenset(qubits) for k in moment_indices: if 0 <= k < len(self._moments): self._moments[k] = s...
127,403
Returns text containing a diagram describing the circuit. Args: use_unicode_characters: Determines if unicode characters are allowed (as opposed to ascii-only diagrams). transpose: Arranges qubit wires vertically instead of horizontally. precision: Number of ...
def to_text_diagram( self, *, use_unicode_characters: bool = True, transpose: bool = False, precision: Optional[int] = 3, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT) -> str: diagram = self.to_text_diagram_drawer( ...
127,409
Returns a QASM object equivalent to the circuit. Args: header: A multi-line string that is placed in a comment at the top of the QASM. Defaults to a cirq version specifier. precision: Number of digits to use when representing numbers. qubit_order: Determines ...
def _to_qasm_output( self, header: Optional[str] = None, precision: int = 10, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, ) -> QasmOutput: if header is None: header = 'Generated from Cirq v{}'.format( cirq._...
127,413
Returns QASM equivalent to the circuit. Args: header: A multi-line string that is placed in a comment at the top of the QASM. Defaults to a cirq version specifier. precision: Number of digits to use when representing numbers. qubit_order: Determines how qubit...
def to_qasm(self, header: Optional[str] = None, precision: int = 10, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, ) -> str: return str(self._to_qasm_output(header, precision, qubit_order))
127,414
Save a QASM file equivalent to the circuit. Args: file_path: The location of the file where the qasm will be written. header: A multi-line string that is placed in a comment at the top of the QASM. Defaults to a cirq version specifier. precision: Number of di...
def save_qasm(self, file_path: Union[str, bytes, int], header: Optional[str] = None, precision: int = 10, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, ) -> None: self._to_qasm_output(header, precisi...
127,415
Returns the big-endian integers specified by groups of bits. Args: bit_groups: Groups of descending bits, each specifying a big endian integer with the 1s bit at the end. Returns: A tuple containing the integer for each group.
def _tuple_of_big_endian_int(bit_groups: Tuple[np.ndarray, ...] ) -> Tuple[int, ...]: return tuple(_big_endian_int(bits) for bits in bit_groups)
127,423
Returns the big-endian integer specified by the given bits. For example, [True, False, False, True, False] becomes binary 10010 which is 18 in decimal. Args: bits: Descending bits of the integer, with the 1s bit at the end. Returns: The integer.
def _big_endian_int(bits: np.ndarray) -> int: result = 0 for e in bits: result <<= 1 if e: result |= 1 return result
127,424
Gives adjacency list representation of a chip. The adjacency list is constructed in order of above, left_of, below and right_of consecutively. Args: device: Chip to be converted. Returns: Map from nodes to list of qubits which represent all the neighbours of given qubit.
def chip_as_adjacency_list(device: 'cirq.google.XmonDevice', ) -> Dict[GridQubit, List[GridQubit]]: c_set = set(device.qubits) c_adj = {} # type: Dict[GridQubit, List[GridQubit]] for n in device.qubits: c_adj[n] = [] for m in [above(n), left_of(n), below(n), r...
127,430
Adds possibly stateful noise to a series of moments. Args: moments: The moments to add noise to. system_qubits: A list of all qubits in the system. Returns: A sequence of OP_TREEs, with the k'th tree corresponding to the noisy operations for the k'th mom...
def noisy_moments(self, moments: 'Iterable[cirq.Moment]', system_qubits: Sequence['cirq.Qid'] ) -> Sequence['cirq.OP_TREE']: if not hasattr(self.noisy_moment, '_not_overridden'): result = [] for moment in moments: result...
127,455
Adds noise to the operations from a moment. Args: moment: The moment to add noise to. system_qubits: A list of all qubits in the system. Returns: An OP_TREE corresponding to the noisy operations for the moment.
def noisy_moment(self, moment: 'cirq.Moment', system_qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE': if not hasattr(self.noisy_moments, '_not_overridden'): return self.noisy_moments([moment], system_qubits) if not hasattr(self.noisy_operation, '_not_overridden...
127,456
Adds noise to an individual operation. Args: operation: The operation to make noisy. Returns: An OP_TREE corresponding to the noisy operations implementing the noisy version of the given operation.
def noisy_operation(self, operation: 'cirq.Operation') -> 'cirq.OP_TREE': if not hasattr(self.noisy_moments, '_not_overridden'): return self.noisy_moments([ops.Moment([operation])], operation.qubits) if not hasattr(self.noisy_moment, '_not_over...
127,457
Generates Google Random Circuits v2 as in github.com/sboixo/GRCS cz_v2. See also https://arxiv.org/abs/1807.10749 Args: qubits: qubit grid in which to generate the circuit. cz_depth: number of layers with CZ gates. seed: seed for the random instance. Returns: A circuit corr...
def generate_supremacy_circuit_google_v2(qubits: Iterable[devices.GridQubit], cz_depth: int, seed: int) -> circuits.Circuit: non_diagonal_gates = [ops.pauli_gates.X**(1/2), ops.pauli_gates.Y**(1/2)] rand_gen = random.Random(...
127,460
Generates Google Random Circuits v2 in Bristlecone. See also https://arxiv.org/abs/1807.10749 Args: n_rows: number of rows in a Bristlecone lattice. Note that we do not include single qubit corners. cz_depth: number of layers with CZ gates. seed: seed for the random instance. ...
def generate_supremacy_circuit_google_v2_bristlecone(n_rows: int, cz_depth: int, seed: int ) -> circuits.Circuit: def get_qubits(n_rows): def count_neighbors(qubits, qubit): ...
127,462
Decomposes a two-qubit operation into MS/single-qubit rotation gates. Args: q0: The first qubit being operated on. q1: The other qubit being operated on. mat: Defines the operation to apply to the pair of qubits. tolerance: A limit on the amount of error introduced by the ...
def two_qubit_matrix_to_ion_operations(q0: ops.Qid, q1: ops.Qid, mat: np.ndarray, atol: float = 1e-8 ) -> List[ops.Operation]: kak = linalg.kak_decompositi...
127,486
Initializes the 2-qubit matrix gate. Args: matrix: The matrix that defines the gate.
def __init__(self, matrix: np.ndarray) -> None: if matrix.shape != (2, 2) or not linalg.is_unitary(matrix): raise ValueError('Not a 2x2 unitary matrix: {}'.format(matrix)) self._matrix = matrix
127,492
Attempt to resolve a Symbol or name or float to its assigned value. If unable to resolve a sympy.Symbol, returns it unchanged. If unable to resolve a name, returns a sympy.Symbol with that name. Args: value: The sympy.Symbol or name or float to try to resolve into just ...
def value_of( self, value: Union[sympy.Basic, float, str] ) -> Union[sympy.Basic, float]: if isinstance(value, str): return self.param_dict.get(value, sympy.Symbol(value)) if isinstance(value, sympy.Basic): if sys.version_info.major < 3: ...
127,503
Determines if a file should be included in incremental coverage analysis. Args: rel_path: The repo-relative file path being considered. Returns: Whether to include the file.
def is_applicable_python_file(rel_path: str) -> bool: return (rel_path.endswith('.py') and not any(re.search(pat, rel_path) for pat in IGNORED_FILE_PATTERNS))
127,515
Constructor. Arguments: year, month, day (required, base 1)
def __new__(cls, year, month=None, day=None): # if month is None and isinstance(year, bytes) and len(year) == 4 and \ # 1 <= ord(year[2]) <= 12: # # Pickle support # self = object.__new__(cls) # self.__setstate(year) # self._hashcode = -1 ...
127,883
Constructor. Arguments: hour, minute (required) second, microsecond (default to zero) tzinfo (default to None)
def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None): # if isinstance(hour, bytes) and len(hour) == 6 and ord(hour[0]) < 24: # # Pickle support # self = object.__new__(cls) # self.__setstate(hour, minute or None) # self._hashcode = -1 ...
127,900
HtmlDiff instance initializer Arguments: tabsize -- tab stop spacing, defaults to 8. wrapcolumn -- column number where lines are broken and wrapped, defaults to None where lines are not wrapped. linejunk,charjunk -- keyword arguments passed into ndiff() (used to by ...
def __init__(self,tabsize=8,wrapcolumn=None,linejunk=None, charjunk=IS_CHARACTER_JUNK): self._tabsize = tabsize self._wrapcolumn = wrapcolumn self._linejunk = linejunk self._charjunk = charjunk
128,068
Generates code that imports a module and binds it to a variable. Args: imp: Import object representing an import of the form "import x.y.z" or "from x.y import z". Expects only a single binding.
def _import_and_bind(self, imp): # Acquire handles to the Code objects in each Go package and call # ImportModule to initialize all modules. with self.block.alloc_temp() as mod, \ self.block.alloc_temp('[]*πg.Object') as mod_slice: self.writer.write_checked_call2( mod_slice, 'πg...
128,123