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 master branch is cloned instead. verbose: When set, more progress output is produced. Returns: Commit ids corresponding to content to test/compare.
def fetch_github_pull_request(destination_directory: str, repository: github_repository.GithubRepository, pull_request_number: int, verbose: bool ) -> prepared_env.PreparedEnv: branch = 'pull/{}/head'.format(pull_request_number) os.chdir(destination_directory) print('chdir', destination_directory, file=sys.stderr) shell_tools.run_cmd( 'git', 'init', None if verbose else '--quiet', out=sys.stderr) result = _git_fetch_for_comparison(remote=repository.as_remote(), actual_branch=branch, compare_branch='master', verbose=verbose) shell_tools.run_cmd( 'git', 'branch', None if verbose else '--quiet', 'compare_commit', result.compare_commit_id, log_run_to_stderr=verbose) shell_tools.run_cmd( 'git', 'checkout', None if verbose else '--quiet', '-b', 'actual_commit', result.actual_commit_id, log_run_to_stderr=verbose) return prepared_env.PreparedEnv( github_repo=repository, actual_commit_id=result.actual_commit_id, compare_commit_id=result.compare_commit_id, destination_directory=destination_directory, virtual_env_path=None)
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', staging_dir, file=sys.stderr) shell_tools.run_cmd( 'git', 'add', '--all', out=sys.stderr, log_run_to_stderr=verbose) shell_tools.run_cmd( 'git', 'commit', '-m', 'working changes', '--allow-empty', '--no-gpg-sign', None if verbose else '--quiet', out=sys.stderr, log_run_to_stderr=verbose) cur_commit = shell_tools.output_of('git', 'rev-parse', 'HEAD') os.chdir(destination_directory) if verbose: print('chdir', destination_directory, file=sys.stderr) shell_tools.run_cmd('git', 'init', None if verbose else '--quiet', out=sys.stderr, log_run_to_stderr=verbose) result = _git_fetch_for_comparison(staging_dir, cur_commit, 'master', verbose=verbose) finally: shutil.rmtree(staging_dir, ignore_errors=True) shell_tools.run_cmd( 'git', 'branch', None if verbose else '--quiet', 'compare_commit', result.compare_commit_id, log_run_to_stderr=verbose) shell_tools.run_cmd( 'git', 'checkout', None if verbose else '--quiet', '-b', 'actual_commit', result.actual_commit_id, log_run_to_stderr=verbose) return prepared_env.PreparedEnv( github_repo=None, actual_commit_id=result.actual_commit_id, compare_commit_id=result.compare_commit_id, destination_directory=destination_directory, virtual_env_path=None)
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 pairs of qubits crossing between groups.
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 group_matrices = [] for g in grouping.groups: # Scan for reachable operations contained within the group qubits. start_frontier = {q: frontier[q] for q in g} end_frontier = circuit.reachable_frontier_from(start_frontier) mergeable_ops = circuit.findall_operations_between(start_frontier, end_frontier) # Advance frontier. for q, v in end_frontier.items(): frontier[q] = v # Fold reachable operations into a single group matrix. group_matrix = np.eye(1 << len(g)).reshape((2, 2) * len(g)) if mergeable_ops: any_group_matrices = True for _, op in mergeable_ops: group_matrix = linalg.targeted_left_multiply( left_matrix=protocols.unitary(op).reshape( (2, 2) * len(op.qubits)), right_target=group_matrix, target_axes=[grouping.loc(q)[1] for q in op.qubits]) group_matrices.append(np.transpose(group_matrix.reshape( 1 << len(g), 1 << len(g)))) # Scan for reachable CZ operations between groups. end_frontier = circuit.reachable_frontier_from( frontier, is_blocker=lambda op: grouping.all_in_same_group(*op.qubits)) cz_ops = circuit.findall_operations_between(frontier, end_frontier) # Advance frontier. frontier = end_frontier # List out qubit index pairs for each CZ. cz_indices = [] for _, cz in cz_ops: a, b = cz.qubits assert cz == ops.CZ(a, b) cz_indices.append((grouping.ind(a), grouping.ind(b))) # Combine group and CZ operations into a simulation layer. if not any_group_matrices and not cz_indices: break layer = _TransformsThenCzs(group_matrices=group_matrices, cz_indices=cz_indices) layers.append(layer) # We should have processed the whole circuit. assert frontier == {q: len(circuit) for q in circuit.all_qubits()} return layers
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), repetitions)[0]
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 to simulate. Returns: TrialResult list for this run; one for each possible parameter resolver.
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. Defaults to str. Returns: A list of operations individually measuring the given qubits.
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 to the qubits.
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( 'Wrong number of qubits for <{!r}>. ' 'Expected {} qubits but got <{!r}>.'.format( self, self.num_qubits(), qubits)) if any([not isinstance(qubit, Qid) for qubit in qubits]): raise ValueError( 'Gate was called with type different than Qid.')
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 else 1)
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: {}" .format(repr(self))) else: return ControlledOperation(control_qubits, self)
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 ' + self.command_line_switch(), shell_tools.YELLOW)) return CheckResult( self, False, 'Skipped due to dependency failing.', None) print(shell_tools.highlight( 'Running ' + self.command_line_switch(), shell_tools.GREEN)) try: success, message = self.perform_check(env, verbose=verbose) result = CheckResult(self, success, message, None) except Exception as ex: result = CheckResult(self, False, 'Unexpected error.', ex) print(shell_tools.highlight( 'Finished ' + self.command_line_switch(), shell_tools.GREEN if result.success else shell_tools.RED)) if verbose: print(result) return result
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_diagram_info) return _render(diagram)
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_dtypes, (b.dtype for b in blocks)) result = np.zeros(shape=(n, n), dtype=dtype) i = 0 for b in blocks: j = i + b.shape[0] result[i:j, i:j] = b i = j return result
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 converges to number -1. The solution with a lowest cost consists of every node being a single sequence and is always less than 0.
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 mutated. Returns: New search state with one of the unused edges appearing in some sequence.
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_edge((seq[i - 1], seq[i]))) edge = self._choose_random_edge(unused_edges) if not edge: return seqs, edges return ( self._force_edge_active(seqs, edge, lambda: bool(self._rand.randint(2))), edges)
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 sequences.
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 within current solution. i0, j0 = index_2d(seqs, n0) i1, j1 = index_2d(seqs, n1) s0 = seqs[i0] s1 = seqs[i1] # Handle case when nodes belong to different linear sequences, # separately from the case where they belong to a single linear # sequence. if i0 != i1: # Split s0 and s1 in two parts: s0 in parts before n0, and after n0 # (without n0); s1 in parts before n1, and after n1 (without n1). part = [s0[:j0], s0[j0 + 1:]], [s1[:j1], s1[j1 + 1:]] # Remove both sequences from original list. del seqs[max(i0, i1)] del seqs[min(i0, i1)] # Choose part of s0 which will be attached to n0, and make sure it # can be attached in the end. c0 = 0 if not part[0][1] else 1 if not part[0][ 0] else sample_bool() if c0: part[0][c0].reverse() # Choose part of s1 which will be attached to n1, and make sure it # can be attached in the beginning. c1 = 0 if not part[1][1] else 1 if not part[1][ 0] else sample_bool() if not c1: part[1][c1].reverse() # Append newly formed sequence from the chosen parts and new edge. seqs.append(part[0][c0] + [n0, n1] + part[1][c1]) # Append the left-overs to the solution, if they exist. other = [1, 0] seqs.append(part[0][other[c0]]) seqs.append(part[1][other[c1]]) else: # Swap nodes so that n0 always preceeds n1 on sequence. if j0 > j1: j0, j1 = j1, j0 n0, n1 = n1, n0 # Split sequence in three parts, without nodes n0 an n1 present: # head might end with n0, inner might begin with n0 and end with # n1, tail might begin with n1. head = s0[:j0] inner = s0[j0 + 1:j1] tail = s0[j1 + 1:] # Remove original sequence from sequences list. del seqs[i0] # Either append edge to inner section, or attach it between head # and tail. if sample_bool(): # Append edge either before or after inner section. if sample_bool(): seqs.append(inner + [n1, n0] + head[::-1]) seqs.append(tail) else: seqs.append(tail[::-1] + [n1, n0] + inner) seqs.append(head) else: # Form a new sequence from head, tail, and new edge. seqs.append(head + [n0, n1] + tail) seqs.append(inner) return [e for e in seqs if e]
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: Normalized edge with lexicographically lower node on the first position.
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(args, index)) * (1 - result)) state /= normalization
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 above. axis_half_turns: The angle between the pauli X and Y operators, see the formula above.
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 index >= self._num_shard_qubits: # W gate spans shards. self._pool.map(_clear_scratch, args) self._pool.map(_w_between_shards, args) self._pool.map(_copy_scratch_to_state, args) else: # W gate is within a shard. self._pool.map(_w_within_shard, args) # Normalize after every w. norm_squared = np.sum(self._pool.map(_norm_squared, args)) args = self._shard_num_args({ 'norm_squared': norm_squared }) self._pool.map(_renorm, args)
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, 'result': result, 'prob_one': prob_one }) self._pool.map(_collapse_state, args) return result
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 the inner corresponds to measurements ordered by the input indices. Raises: ValueError if repetitions is less than one.
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_vector(self._current_state(), reversed_indices, repetitions)
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 rotations. Args: qubits: list of four qubits
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]) yield fermi_fourier_trans_2(qubits[2], qubits[3]) yield fswap(qubits[1], 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(qubits[2]) ** 3 yield fermi_fourier_trans_2(qubits[2], qubits[3]) yield fswap(qubits[1], qubits[2])
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 strength Returns: float delta, List[float] bog_theta
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_erg = hop_erg[n_fermi // 2] # Set the Fermi energy to zero hop_erg = hop_erg - fermi_erg def _bcs_gap(x): s = 0. for i in range(n_site): s += 1. / np.sqrt(hop_erg[i] ** 2 + x ** 2) return 1 + s * u / (2 * n_site) # Superconducting gap delta = scipy.optimize.bisect(_bcs_gap, 0.01, 10000. * abs(u)) # The amplitude of the double excitation state bcs_v = np.sqrt(0.5 * (1 - hop_erg / np.sqrt(hop_erg ** 2 + delta ** 2))) # The rotational angle in the Bogoliubov transformation. bog_theta = np.arcsin(bcs_v) return delta, bog_theta
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(device) self._start = start self._sequence = None
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: Set of qubits that are reachable from starting qubit without traversing any of the used qubits.
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: collect(m, visited) visited = set() # type: Set[GridQubit] collect(start, visited) return visited
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] greedy_search = { 'minimal_connectivity': [ _PickFewestNeighbors(device, start), ], 'largest_area': [ _PickLargestArea(device, start), ], 'best': [ _PickFewestNeighbors(device, start), _PickLargestArea(device, start), ] } # type: Dict[str, List[GreedySequenceSearch]] algos = greedy_search.get(self.algorithm) if algos is None: raise ValueError( "Unknown greedy search algorithm %s" % self.algorithm) for algorithm in algos: sequences.append(algorithm.get_or_search()) return GridQubitLineTuple.best_of(sequences, length)
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(affected_qubits) != len(self.qubits): raise ValueError( 'Overlapping operations: {}'.format(self.operations))
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.raw_picos() if last_time_picos is None: op['incremental_delay_picoseconds'] = time_picos else: op['incremental_delay_picoseconds'] = time_picos - last_time_picos last_time_picos = time_picos yield op
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.ZPowGate))
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 (for messages). Returns: The operation. Raises: ValueError if the dictionary does not contain required values corresponding to the proto.
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 'exp_w' in proto_dict: exp_w = proto_dict['exp_w'] if ('half_turns' not in exp_w or 'axis_half_turns' not in exp_w or 'target' not in exp_w): raise_missing_fields('ExpW') return ops.PhasedXPowGate( exponent=param(exp_w['half_turns']), phase_exponent=param(exp_w['axis_half_turns']), ).on(qubit(exp_w['target'])) elif 'exp_z' in proto_dict: exp_z = proto_dict['exp_z'] if 'half_turns' not in exp_z or 'target' not in exp_z: raise_missing_fields('ExpZ') return ops.Z(qubit(exp_z['target']))**param(exp_z['half_turns']) elif 'exp_11' in proto_dict: exp_11 = proto_dict['exp_11'] if ('half_turns' not in exp_11 or 'target1' not in exp_11 or 'target2' not in exp_11): raise_missing_fields('Exp11') return ops.CZ(qubit(exp_11['target1']), qubit(exp_11['target2']))**param(exp_11['half_turns']) elif 'measurement' in proto_dict: meas = proto_dict['measurement'] invert_mask = cast(Tuple[Any, ...], ()) if 'invert_mask' in meas: invert_mask = tuple(json.loads(x) for x in meas['invert_mask']) if 'key' not in meas or 'targets' not in meas: raise_missing_fields('Measurement') return ops.MeasurementGate( num_qubits=len(meas['targets']), key=meas['key'], invert_mask=invert_mask ).on(*[qubit(q) for q in meas['targets']]) else: raise ValueError('invalid operation: {}'.format(proto_dict))
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 duplicates of an item may still be enqueued, as long as they have different priorities.
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() if drop_duplicate_entries else None) # type: Optional[Set[Tuple[int, TItem]]] for p, e in entries: self.enqueue(p, e)
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: A dictionary containing the metadata.
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_repetitions = sweep_result['repetitions'] key_sizes = [(m['key'], len(m['qubits'])) for m in sweep_result['measurementKeys']] for result in sweep_result['parameterizedResults']: data = base64.standard_b64decode(result['measurementResults']) measurements = unpack_results(data, sweep_repetitions, key_sizes) trial_results.append(TrialResult( params=ParamResolver( result.get('params', {}).get('assignments', {})), repetitions=sweep_repetitions, measurements=measurements)) return trial_results
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_resource_name.split('/jobs')[0] self._results = None
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: root isn't a valid OP_TREE.
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, collections.Iterable): for subtree in root: for item in flatten_op_tree(subtree, preserve_moments): yield item return raise TypeError('Not a collections.Iterable or an Operation: {} {}'.format( type(root), root))
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 tolerance to angle error. Larger values allow more negligible gates to be dropped, smaller values increase accuracy.
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) for gate in out_gates] MergeSingleQubitGates(synthesizer=synth).optimize_circuit(circuit)
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 else None # type: Optional[List[str]] async for chunk in async_chunks: if not isinstance(chunk, str): chunk = chunk.decode() if out_pipe: print(chunk, file=out_pipe, end='') if chunks is not None: chunks.append(chunk) return ''.join(chunks) if chunks is not None else None
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 output, return code) triplet.
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_err_output = _async_forward(process.stderr, err) output, err_output = await asyncio.gather(future_output, future_err_output) await process.wait() return CommandOutput(output, err_output, process.returncode)
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 number of degrees to rotate by default: The half turns angle to use if nothing else is specified. Returns: A number of half turns.
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: raise ValueError('Redundant angle specification. ' 'Use ONE of half_turns, rads, or degs.') if rads is not None: return rads / np.pi if degs is not None: return degs / 180 if half_turns is not None: return half_turns return default
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. degs: The number of degrees to rotate by default: The half turns angle to use if nothing else is specified. Returns: A number of half turns.
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_turns( half_turns=half_turns, rads=rads, degs=degs, default=default))
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, perform the desired operation.
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_quarter_turn(half_turns): return (is_clifford_rotation(half_turns) and to_quarter_turns(half_turns) % 2 == 1) def is_half_turn(half_turns): return (is_clifford_rotation(half_turns) and to_quarter_turns(half_turns) == 2) def is_no_turn(half_turns): return (is_clifford_rotation(half_turns) and to_quarter_turns(half_turns) == 0) # Decompose matrix z_rad_before, y_rad, z_rad_after = ( linalg.deconstruct_single_qubit_matrix_into_angles(mat)) z_ht_before = z_rad_before / np.pi - 0.5 m_ht = y_rad / np.pi m_pauli = ops.pauli_gates.X # type: ops.pauli_gates.Pauli z_ht_after = z_rad_after / np.pi + 0.5 # Clean up angles if is_clifford_rotation(z_ht_before): if ((is_quarter_turn(z_ht_before) or is_quarter_turn(z_ht_after)) ^ (is_half_turn(m_ht) and is_no_turn(z_ht_before-z_ht_after))): z_ht_before += 0.5 z_ht_after -= 0.5 m_pauli = ops.pauli_gates.Y if is_half_turn(z_ht_before) or is_half_turn(z_ht_after): z_ht_before -= 1 z_ht_after += 1 m_ht = -m_ht if is_no_turn(m_ht): z_ht_before += z_ht_after z_ht_after = 0 elif is_half_turn(m_ht): z_ht_after -= z_ht_before z_ht_before = 0 # Generate operations rotation_list = [ (ops.pauli_gates.Z, z_ht_before), (m_pauli, m_ht), (ops.pauli_gates.Z, z_ht_after)] return [(pauli, ht) for pauli, ht in rotation_list if not is_no_turn(ht)]
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 operation.
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 values canonicalized into the range [-0.5, 0.5).
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 = rotation / tau xy_phase_turn = 0.25 - pre_phase / tau total_z_turn = (post_phase + pre_phase) / tau # Normalize turns into the range [-0.5, 0.5). return (_signed_mod_1(xy_turn), _signed_mod_1(xy_phase_turn), _signed_mod_1(total_z_turn))
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 gates that, when applied in order, perform the desired operation.
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. result = [ ops.PhasedXPowGate(exponent=2 * xy_turn, phase_exponent=2 * xy_phase_turn), ops.Z**(2 * total_z_turn) ] result = [ g for g in result if protocols.trace_distance_bound(g) > atol ] # Special case: XY half-turns can absorb Z rotations. if len(result) == 2 and abs(xy_turn) >= 0.5 - atol: return [ ops.PhasedXPowGate(phase_exponent=2 * xy_phase_turn + total_z_turn) ] return result
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: Tuple of boolean and float, with boolean equal to True if solution is accepted, and False otherwise. The float value is acceptance probability.
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 {}'.format(dtype)) self._dtype = dtype self.noise = noise
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. dtype: The numpy dtype for the 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 = qubit_map self._dtype = dtype
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. It also contains MeasurementGates if the given circuit contains measurements.
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 containing the operations.
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 result
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 moment.operations) for moment in self._moments], device=new_device )
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 is no operation on the qubit at the given moment, or else the operation.
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: return op return None
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_gate_of_type(operation, gate_type))) for index, op in result: gate_op = cast(ops.GateOperation, op) yield index, gate_op, cast(T_DESIRED_GATE_TYPE, gate_op.gate)
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 occur. Raises: ValueError: Unrecognized append strategy.
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.Moment()) return splitter_index if strategy is InsertStrategy.INLINE: if (0 <= splitter_index - 1 < len(self._moments) and self._can_add_op_at(splitter_index - 1, op)): return splitter_index - 1 return self._pick_or_create_inserted_op_moment_index( splitter_index, op, InsertStrategy.NEW) if strategy is InsertStrategy.EARLIEST: if self._can_add_op_at(splitter_index, op): p = self._prev_moment_available(op, splitter_index) return p or 0 return self._pick_or_create_inserted_op_moment_index( splitter_index, op, InsertStrategy.INLINE) raise ValueError('Unrecognized append strategy: {}'.format(strategy))
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) operations = tuple(ops.flatten_op_tree(operations)) if not operations: return frontier qubits = set(q for op in operations for q in op.qubits) if any(frontier[q] > start for q in qubits): raise ValueError('The frontier for qubits on which the operations' 'to insert act cannot be after start.') next_moments = self.next_moments_operating_on(qubits, start) insertion_indices, _ = self._pick_inserted_ops_moment_indices( operations, start, frontier) self._push_frontier(frontier, next_moments) self._insert_operations(operations, insertion_indices) return frontier
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] = self._moments[k].without_operations_touching( qubits)
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 digits to display in text diagram qubit_order: Determines how qubits are ordered in the diagram. Returns: The text diagram.
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( use_unicode_characters=use_unicode_characters, precision=precision, qubit_order=qubit_order, transpose=transpose) return diagram.render( crossing_char=(None if use_unicode_characters else ('-' if transpose else '|')), horizontal_spacing=1 if transpose else 3, use_unicode_characters=use_unicode_characters)
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 how qubits are ordered in the QASM register.
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._version.__version__) qubits = ops.QubitOrder.as_qubit_order(qubit_order).order_for( self.all_qubits()) return QasmOutput(operations=self.all_operations(), qubits=qubits, header=header, precision=precision, version='2.0')
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 qubits are ordered in the QASM register.
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 digits to use when representing numbers. qubit_order: Determines how qubits are ordered in the QASM register.
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, precision, qubit_order).save(file_path)
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), right_of(n)]: if m in c_set: c_adj[n].append(m) return c_adj
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 moment.
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.append(self.noisy_moment(moment, system_qubits)) return result if not hasattr(self.noisy_operation, '_not_overridden'): result = [] for moment in moments: result.append([self.noisy_operation(op) for op in moment]) return result assert False, 'Should be unreachable.'
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'): return [self.noisy_operation(op) for op in moment] assert False, 'Should be unreachable.'
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_overridden'): return self.noisy_moment(ops.Moment([operation]), operation.qubits) assert False, 'Should be unreachable.'
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 corresponding to instance inst_{n_rows}x{n_cols}_{cz_depth+1}_{seed} The mapping of qubits is cirq.GridQubit(j,k) -> q[j*n_cols+k] (as in the QASM mapping)
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(seed).random circuit = circuits.Circuit() # Add an initial moment of Hadamards circuit.append(ops.common_gates.H(qubit) for qubit in qubits) layer_index = 0 if cz_depth: layer_index = _add_cz_layer(layer_index, circuit) # In the first moment, add T gates when possible for qubit in qubits: if not circuit.operation_at(qubit, 1): circuit.append(ops.common_gates.T(qubit), strategy=InsertStrategy.EARLIEST) for moment_index in range(2, cz_depth+1): layer_index = _add_cz_layer(layer_index, circuit) # Add single qubit gates in the same moment for qubit in qubits: if not circuit.operation_at(qubit, moment_index): last_op = circuit.operation_at(qubit, moment_index-1) if last_op: gate = cast(ops.GateOperation, last_op).gate # Add a random non diagonal gate after a CZ if gate == ops.CZ: circuit.append(_choice(rand_gen, non_diagonal_gates).on(qubit), strategy=InsertStrategy.EARLIEST) # Add a T gate after a non diagonal gate elif not gate == ops.T: circuit.append(ops.common_gates.T(qubit), strategy=InsertStrategy.EARLIEST) # Add a final moment of Hadamards circuit.append([ops.common_gates.H(qubit) for qubit in qubits], strategy=InsertStrategy.NEW_THEN_INLINE) return circuit
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. Returns: A circuit with given size and seed.
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): possibles = [ devices.GridQubit(qubit.row + 1, qubit.col), devices.GridQubit(qubit.row - 1, qubit.col), devices.GridQubit(qubit.row, qubit.col + 1), devices.GridQubit(qubit.row, qubit.col - 1), ] return len(list(e for e in possibles if e in qubits)) assert 1 <= n_rows <= 11 max_row = n_rows - 1 dev = google.Bristlecone # we need a consistent order of qubits qubits = list(dev.qubits) qubits.sort() qubits = [q for q in qubits if q.row <= max_row and q.row + q.col < n_rows + 6 and q.row - q.col < n_rows - 5] qubits = [q for q in qubits if count_neighbors(qubits, q) > 1] return qubits qubits = get_qubits(n_rows) return generate_supremacy_circuit_google_v2(qubits, cz_depth, seed)
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 construction. Returns: A list of operations implementing the matrix.
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_decomposition(mat, atol=atol) operations = _kak_decomposition_to_operations(q0, q1, kak, atol) return _cleanup_operations(operations)
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 a float. Returns: The value of the parameter as resolved by this resolver.
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: # coverage: ignore # HACK: workaround https://github.com/sympy/sympy/issues/16087 d = {k.encode(): v for k, v in self.param_dict.items()} v = value.subs(d) else: v = value.subs(self.param_dict) return v if v.free_symbols else float(v) return value
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 # return self year, month, day = _check_date_fields(year, month, day) self = object.__new__(cls) self._year = year self._month = month self._day = day self._hashcode = -1 return self
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 # return self hour, minute, second, microsecond = _check_time_fields( hour, minute, second, microsecond) _check_tzinfo_arg(tzinfo) self = object.__new__(cls) self._hour = hour self._minute = minute self._second = second self._microsecond = microsecond self._tzinfo = tzinfo self._hashcode = -1 return self
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 HtmlDiff() to generate the side by side HTML differences). See ndiff() documentation for argument default values and descriptions.
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.ImportModule(πF, {})', util.go_str(imp.name)) # Bind the imported modules or members to variables in the current scope. for binding in imp.bindings: if binding.bind_type == imputil.Import.MODULE: self.writer.write('{} = {}[{}]'.format( mod.name, mod_slice.expr, binding.value)) self.block.bind_var(self.writer, binding.alias, mod.expr) else: self.writer.write('{} = {}[{}]'.format( mod.name, mod_slice.expr, imp.name.count('.'))) # Binding a member of the imported module. with self.block.alloc_temp() as member: self.writer.write_checked_call2( member, 'πg.GetAttr(πF, {}, {}, nil)', mod.expr, self.block.root.intern(binding.value)) self.block.bind_var(self.writer, binding.alias, member.expr)
128,123