INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
r Returns a PhaseFlipChannel that flips a qubit s phase with probability p if p is None return a guaranteed phase flip in the form of a Z operation.
def phase_flip( p: Optional[float] = None ) -> Union[common_gates.ZPowGate, PhaseFlipChannel]: r""" Returns a PhaseFlipChannel that flips a qubit's phase with probability p if p is None, return a guaranteed phase flip in the form of a Z operation. This channel evolves a density matrix via: ...
r Construct a BitFlipChannel that flips a qubit state with probability of a flip given by p. If p is None return a guaranteed flip in the form of an X operation.
def bit_flip( p: Optional[float] = None ) -> Union[common_gates.XPowGate, BitFlipChannel]: r""" Construct a BitFlipChannel that flips a qubit state with probability of a flip given by p. If p is None, return a guaranteed flip in the form of an X operation. This channel evolves a density matrix ...
Finds operations by time and qubit.
def query( self, *, # Forces keyword args. time: Timestamp, duration: Union[Duration, timedelta] = Duration(), qubits: Iterable[Qid] = None, include_query_end_time=False, include_op_end_times=False) -> List[ScheduledOperation]: ...
Finds operations happening at the same time as the given operation.
def operations_happening_at_same_time_as( self, scheduled_operation: ScheduledOperation ) -> List[ScheduledOperation]: """Finds operations happening at the same time as the given operation. Args: scheduled_operation: The operation specifying the time to query. Returns: ...
Adds a scheduled operation to the schedule.
def include(self, scheduled_operation: ScheduledOperation): """Adds a scheduled operation to the schedule. Args: scheduled_operation: The operation to add. Raises: ValueError: The operation collided with something already in the schedule. """ ...
Omits a scheduled operation from the schedule if present.
def exclude(self, scheduled_operation: ScheduledOperation) -> bool: """Omits a scheduled operation from the schedule, if present. Args: scheduled_operation: The operation to try to remove. Returns: True if the operation was present and is now removed, False if it ...
Convert the schedule to a circuit.
def to_circuit(self) -> Circuit: """Convert the schedule to a circuit. This discards most timing information from the schedule, but does place operations that are scheduled at the same time in the same Moment. """ circuit = Circuit(device=self.device) time = None # type...
Acquaints each of the qubits with another set specified by an acquaintance gate.
def acquaint_insides(swap_gate: ops.Gate, acquaintance_gate: ops.Operation, qubits: Sequence[ops.Qid], before: bool, layers: Layers, mapping: Dict[ops.Qid, int] ) -> None: """Acquaints each ...
Acquaints and shifts a pair of lists of qubits. The first part is acquainted with every qubit individually in the second part and vice versa. Operations are grouped into several layers: * prior_interstitial: The first layer of acquaintance gates. * prior: The combination of acquaintance gates and swaps that acquaints t...
def acquaint_and_shift(parts: Tuple[List[ops.Qid], List[ops.Qid]], layers: Layers, acquaintance_size: Optional[int], swap_gate: ops.Gate, mapping: Dict[ops.Qid, int]): """Acquaints and shifts a pair of lists of qubits. The f...
Compiles the QCircuit - based latex diagram of the given circuit.
def circuit_to_pdf_using_qcircuit_via_tex(circuit: circuits.Circuit, filepath: str, pdf_kwargs=None, qcircuit_kwargs=None, clean_ext=('dvi', 'ps'), ...
Breaks down a 2x2 unitary into more useful ZYZ angle parameters.
def deconstruct_single_qubit_matrix_into_angles( mat: np.ndarray) -> Tuple[float, float, float]: """Breaks down a 2x2 unitary into more useful ZYZ angle parameters. Args: mat: The 2x2 unitary matrix to break down. Returns: A tuple containing the amount to phase around Z, then rotat...
Combines similar items into groups.
def _group_similar(items: List[T], comparer: Callable[[T, T], bool]) -> List[List[T]]: """Combines similar items into groups. Args: items: The list of items to group. comparer: Determines if two items are similar. Returns: A list of groups of items. """ groups = [] # type...
An eigendecomposition that ensures eigenvectors are perpendicular.
def _perp_eigendecompose(matrix: np.ndarray, rtol: float = 1e-5, atol: float = 1e-8, ) -> Tuple[np.array, List[np.ndarray]]: """An eigendecomposition that ensures eigenvectors are perpendicular. numpy.linalg.eig doesn't guarantee that e...
Applies a function to the eigenvalues of a matrix.
def map_eigenvalues( matrix: np.ndarray, func: Callable[[complex], complex], *, rtol: float = 1e-5, atol: float = 1e-8) -> np.ndarray: """Applies a function to the eigenvalues of a matrix. Given M = sum_k a_k |v_k><v_k|, returns f(M) = sum_k f(a_k) |v_k><v_k|. Args:...
Splits a 4x4 matrix U = kron ( A B ) into A B and a global factor.
def kron_factor_4x4_to_2x2s( matrix: np.ndarray, ) -> Tuple[complex, np.ndarray, np.ndarray]: """Splits a 4x4 matrix U = kron(A, B) into A, B, and a global factor. Requires the matrix to be the kronecker product of two 2x2 unitaries. Requires the matrix to have a non-zero determinant. Giving an...
Finds 2x2 special - unitaries A B where mat = Mag. H @ kron ( A B ) @ Mag.
def so4_to_magic_su2s( mat: np.ndarray, *, rtol: float = 1e-5, atol: float = 1e-8, check_preconditions: bool = True ) -> Tuple[np.ndarray, np.ndarray]: """Finds 2x2 special-unitaries A, B where mat = Mag.H @ kron(A, B) @ Mag. Mag is the magic basis matrix: 1 0 ...
Canonicalizes an XX/ YY/ ZZ interaction by swap/ negate/ shift - ing axes.
def kak_canonicalize_vector(x: float, y: float, z: float) -> KakDecomposition: """Canonicalizes an XX/YY/ZZ interaction by swap/negate/shift-ing axes. Args: x: The strength of the XX interaction. y: The strength of the YY interaction. z: The strength of the ZZ interaction. Returns:...
Decomposes a 2 - qubit unitary into 1 - qubit ops and XX/ YY/ ZZ interactions.
def kak_decomposition( mat: np.ndarray, rtol: float = 1e-5, atol: float = 1e-8) -> KakDecomposition: """Decomposes a 2-qubit unitary into 1-qubit ops and XX/YY/ZZ interactions. Args: mat: The 4x4 unitary matrix to decompose. rtol: Per-matrix-entry relative tolerance on e...
Updates a mapping ( in place ) from qubits to logical indices according to a set of permutation gates. Any gates other than permutation gates are ignored.
def update_mapping(mapping: Dict[ops.Qid, LogicalIndex], operations: ops.OP_TREE ) -> None: """Updates a mapping (in place) from qubits to logical indices according to a set of permutation gates. Any gates other than permutation gates are ignored. Args: map...
Updates a mapping ( in place ) from qubits to logical indices.
def update_mapping(self, mapping: Dict[ops.Qid, LogicalIndex], keys: Sequence[ops.Qid] ) -> None: """Updates a mapping (in place) from qubits to logical indices. Args: mapping: The mapping to update. keys: The qubits acted on by the ...
Adds text to the given location.
def write(self, x: int, y: int, text: str, transposed_text: 'Optional[str]' = None): """Adds text to the given location. Args: x: The column in which to write the text. y: The row in which to write the text. tex...
Determines if a line or printed text is at the given location.
def content_present(self, x: int, y: int) -> bool: """Determines if a line or printed text is at the given location.""" # Text? if (x, y) in self.entries: return True # Vertical line? if any(v.x == x and v.y1 < y < v.y2 for v in self.vertical_lines): ret...
Adds a vertical or horizontal line from ( x1 y1 ) to ( x2 y2 ).
def grid_line(self, x1: int, y1: int, x2: int, y2: int, emphasize: bool = False): """Adds a vertical or horizontal line from (x1, y1) to (x2, y2). Horizontal line is selected on equality in the second coordinate and vertical line is selected on equality in the first coordinate...
Adds a line from ( x y1 ) to ( x y2 ).
def vertical_line(self, x: Union[int, float], y1: Union[int, float], y2: Union[int, float], emphasize: bool = False ) -> None: """Adds a line from (x, y1) to (x, y2).""" y1, y2 = sorted([y1, y2]...
Adds a line from ( x1 y ) to ( x2 y ).
def horizontal_line(self, y: Union[int, float], x1: Union[int, float], x2: Union[int, float], emphasize: bool = False ) -> None: """Adds a line from (x1, y) to (x2, y).""" x1, x2 = sor...
Returns the same diagram but mirrored across its diagonal.
def transpose(self) -> 'TextDiagramDrawer': """Returns the same diagram, but mirrored across its diagonal.""" out = TextDiagramDrawer() out.entries = {(y, x): _DiagramText(v.transposed_text, v.text) for (x, y), v in self.entries.items()} out.vertical_lines = [_Vert...
Determines how many entry columns are in the diagram.
def width(self) -> int: """Determines how many entry columns are in the diagram.""" max_x = -1.0 for x, _ in self.entries.keys(): max_x = max(max_x, x) for v in self.vertical_lines: max_x = max(max_x, v.x) for h in self.horizontal_lines: max_x ...
Determines how many entry rows are in the diagram.
def height(self) -> int: """Determines how many entry rows are in the diagram.""" max_y = -1.0 for _, y in self.entries.keys(): max_y = max(max_y, y) for h in self.horizontal_lines: max_y = max(max_y, h.y) for v in self.vertical_lines: max_y = ...
Change the padding after the given column.
def force_horizontal_padding_after( self, index: int, padding: Union[int, float]) -> None: """Change the padding after the given column.""" self.horizontal_padding[index] = padding
Change the padding after the given row.
def force_vertical_padding_after( self, index: int, padding: Union[int, float]) -> None: """Change the padding after the given row.""" self.vertical_padding[index] = padding
Helper method to transformer either row or column coordinates.
def _transform_coordinates( self, func: Callable[[Union[int, float], Union[int, float]], Tuple[Union[int, float], Union[int, float]]] ) -> None: """Helper method to transformer either row or column coordinates.""" def func_x(x: Union[int, float]) -...
Insert a number of columns after the given column.
def insert_empty_columns(self, x: int, amount: int = 1) -> None: """Insert a number of columns after the given column.""" def transform_columns( column: Union[int, float], row: Union[int, float] ) -> Tuple[Union[int, float], Union[int, float]]: return ...
Insert a number of rows after the given row.
def insert_empty_rows(self, y: int, amount: int = 1) -> None: """Insert a number of rows after the given row.""" def transform_rows( column: Union[int, float], row: Union[int, float] ) -> Tuple[Union[int, float], Union[int, float]]: return column, row ...
Outputs text containing the diagram.
def render(self, horizontal_spacing: int = 1, vertical_spacing: int = 1, crossing_char: str = None, use_unicode_characters: bool = True) -> str: """Outputs text containing the diagram.""" block_diagram = BlockDiagramDrawer() w = self....
Checks if the tensor s elements are all near zero.
def all_near_zero(a: Union[float, complex, Iterable[float], np.ndarray], *, atol: float = 1e-8) -> bool: """Checks if the tensor's elements are all near zero. Args: a: Tensor of elements that could all be near zero. atol: Absolute tolerance. """ retur...
Checks if the tensor s elements are all near multiples of the period.
def all_near_zero_mod(a: Union[float, complex, Iterable[float], np.ndarray], period: float, *, atol: float = 1e-8) -> bool: """Checks if the tensor's elements are all near multiples of the period. Args: a: Tensor of elements that could a...
Fetches two branches including their common ancestor.
def _git_fetch_for_comparison(remote: str, actual_branch: str, compare_branch: str, verbose: bool) -> prepared_env.PreparedEnv: """Fetches two branches including their common ancestor. Limits the depth of the fetch to avo...
Uses content from github to create a dir for testing and comparisons.
def fetch_github_pull_request(destination_directory: str, repository: github_repository.GithubRepository, pull_request_number: int, verbose: bool ) -> prepared_env.PreparedEnv: """Uses content fro...
Uses local files to create a directory for testing and comparisons.
def fetch_local_files(destination_directory: str, verbose: bool) -> prepared_env.PreparedEnv: """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 progres...
Returns a compute function and feed_dict for a cirq. Circuit s output.
def circuit_to_tensorflow_runnable( circuit: circuits.Circuit, initial_state: Union[int, np.ndarray] = 0, ) -> ComputeFuncAndFeedDict: """Returns a compute function and feed_dict for a `cirq.Circuit`'s output. `result.compute()` will return a `tensorflow.Tensor` with `tensorflow.pla...
Transforms a circuit into a series of GroupMatrix + CZ layers.
def _circuit_as_layers(circuit: circuits.Circuit, grouping: _QubitGrouping) -> List[_TransformsThenCzs]: """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. ...
Equivalent to tensor [ index... ].
def _deref(tensor: tf.Tensor, index: tf.Tensor) -> tf.Tensor: """Equivalent to `tensor[index, ...]`. This is a workaround for XLA requiring constant tensor indices. It works by producing a node representing hardcoded instructions like the following: if index == 0: return tensor[0] if index =...
Equivalent to [ t [ index... ] for t in tensors ].
def _multi_deref(tensors: List[tf.Tensor], index: tf.Tensor) -> List[tf.Tensor]: """Equivalent to `[t[index, ...] for t in tensors]`. See `_deref` for more details. """ assert tensors assert tensors[0].shape[0] > 0 return _deref_helper(lambda i: [tensor[i, ...] for tensor in tensors], ...
Samples from the given Circuit or Schedule.
def run( self, program: Union[circuits.Circuit, schedules.Schedule], param_resolver: 'study.ParamResolverOrSimilarType' = None, repetitions: int = 1, ) -> study.TrialResult: """Samples from the given Circuit or Schedule. Args: program: The...
Samples from the given Circuit or Schedule.
def run_sweep( self, program: Union[circuits.Circuit, schedules.Schedule], params: study.Sweepable, repetitions: int = 1, ) -> List[study.TrialResult]: """Samples from the given Circuit or Schedule. In contrast to run, this allows for sweeping over di...
Returns a single MeasurementGate applied to all the given qubits.
def measure(*qubits: raw_types.Qid, key: Optional[str] = None, invert_mask: Tuple[bool, ...] = () ) -> gate_operation.GateOperation: """Returns a single MeasurementGate applied to all the given qubits. The qubits are measured in the computational basis. Args: *q...
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]: """Returns a list of operations individually measuring the given qubits. The qubits are measured in the computational basis. Args: *qub...
Returns a gate with the matrix e^ { - i X rads/ 2 }.
def Rx(rads: Union[float, sympy.Basic]) -> XPowGate: """Returns a gate with the matrix e^{-i X rads / 2}.""" pi = sympy.pi if protocols.is_parameterized(rads) else np.pi return XPowGate(exponent=rads / pi, global_shift=-0.5)
Returns a gate with the matrix e^ { - i Y rads/ 2 }.
def Ry(rads: Union[float, sympy.Basic]) -> YPowGate: """Returns a gate with the matrix e^{-i Y rads / 2}.""" pi = sympy.pi if protocols.is_parameterized(rads) else np.pi return YPowGate(exponent=rads / pi, global_shift=-0.5)
Returns a gate with the matrix e^ { - i Z rads/ 2 }.
def Rz(rads: Union[float, sympy.Basic]) -> ZPowGate: """Returns a gate with the matrix e^{-i Z rads / 2}.""" pi = sympy.pi if protocols.is_parameterized(rads) else np.pi return ZPowGate(exponent=rads / pi, global_shift=-0.5)
See base class.
def _decompose_(self, qubits): """See base class.""" a, b = qubits yield CNOT(a, b) yield CNOT(b, a) ** self._exponent yield CNOT(a, b)
Checks if this gate can be applied to the given qubits.
def validate_args(self, qubits: Sequence[Qid]) -> None: """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....
Returns an application of this gate to the given qubits.
def on(self, *qubits: Qid) -> 'gate_operation.GateOperation': """Returns an application of this gate to the given qubits. Args: *qubits: The collection of qubits to potentially apply the gate to. """ # Avoids circular import. from cirq.ops import gate_operation ...
Returns a controlled version of this gate.
def controlled_by(self, *control_qubits: Qid) -> 'Gate': """Returns a controlled version of this gate. Args: control_qubits: Optional qubits to control the gate by. """ # Avoids circular import. from cirq.ops import ControlledGate return ControlledGate(self, ...
Returns the same operation but with different qubits.
def transform_qubits(self: TSelf_Operation, func: Callable[[Qid], Qid]) -> TSelf_Operation: """Returns the same operation, but with different qubits. Args: func: The function to use to turn each current qubit into a desired new qubit. Return...
Returns a controlled version of this operation.
def controlled_by(self, *control_qubits: Qid) -> 'Operation': """Returns a controlled version of this operation. Args: control_qubits: Qubits to control the operation by. Required. """ # Avoids circular import. from cirq.ops import ControlledOperation if cont...
The value of the display derived from the full wavefunction.
def value_derived_from_wavefunction(self, state: np.ndarray, qubit_map: Dict[raw_types.Qid, int] ) -> Any: """The value of the display, derived from the full wavefunction. Args: ...
Evaluates the status check and returns a pass/ fail with message.
def perform_check(self, env: env_tools.PreparedEnv, verbose: bool) -> Tuple[bool, str]: """Evaluates the status check and returns a pass/fail with message. Args: env: Describes a prepared python 3 environment in which to run. verbose: ...
Evaluates this check.
def run(self, env: env_tools.PreparedEnv, verbose: bool, previous_failures: Set['Check']) -> CheckResult: """Evaluates this check. Args: env: The prepared python environment to run the check in. verbose: When set, more progress output is produ...
Evaluates this check in python 3 or 2. 7 and reports to github.
def pick_env_and_run_and_report(self, env: env_tools.PreparedEnv, env_py2: Optional[env_tools.PreparedEnv], verbose: bool, previous_failures: Set['Check'] ...
Convert a Sweepable to a list of ParamResolvers.
def to_resolvers(sweepable: Sweepable) -> List[ParamResolver]: """Convert a Sweepable to a list of ParamResolvers.""" if isinstance(sweepable, ParamResolver): return [sweepable] elif isinstance(sweepable, Sweep): return list(sweepable) elif isinstance(sweepable, collections.Iterable): ...
Returns whether the object is parameterized with any Symbols.
def is_parameterized(val: Any) -> bool: """Returns whether the object is parameterized with any Symbols. A value is parameterized when it has an `_is_parameterized_` method and that method returns a truthy value, or if the value is an instance of sympy.Basic. Returns: True if the gate has ...
Resolves symbol parameters in the effect using the param resolver.
def resolve_parameters( val: Any, param_resolver: 'cirq.ParamResolverOrSimilarType') -> Any: """Resolves symbol parameters in the effect using the param resolver. This function will use the `_resolve_parameters_` magic method of `val` to resolve any Symbols with concrete values from the giv...
Returns a QCircuit - based latex diagram of the given circuit.
def circuit_to_latex_using_qcircuit( circuit: circuits.Circuit, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT) -> str: """Returns a QCircuit-based latex diagram of the given circuit. Args: circuit: The circuit to represent in latex. qubit_order: Determines the order...
Computes the kronecker product of a sequence of matrices.
def kron(*matrices: np.ndarray) -> np.ndarray: """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 resul...
Computes the kronecker product of a sequence of matrices and controls.
def kron_with_controls(*matrices: np.ndarray) -> np.ndarray: """Computes the kronecker product of a sequence of matrices and controls. Use linalg.CONTROL_TAG to represent controls. Any entry of the output matrix corresponding to a situation where the control is not satisfied will be overwritten by iden...
Computes the dot/ matrix product of a sequence of values.
def dot(*values: Union[float, complex, np.ndarray] ) -> Union[float, complex, np.ndarray]: """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 resulti...
Concatenates blocks into a block diagonal matrix.
def block_diag(*blocks: np.ndarray) -> np.ndarray: """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 bl...
Finds the first index of a target item within a list of lists.
def index_2d(seqs: List[List[Any]], target: Any) -> Tuple[int, int]: """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. """ for i in range(len(seqs)): ...
Issues new linear sequence search.
def search( self, trace_func: Callable[ [List[LineSequence], float, float, float, bool], None] = None) -> List[LineSequence]: """Issues new linear sequence search. Each call to this method starts new search. Args: trace_func: Op...
Cost function that sums squares of lengths of sequences.
def _quadratic_sum_cost(self, state: _STATE) -> float: """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 ...
Move function which repeats _force_edge_active_move a few times.
def _force_edges_active_move(self, state: _STATE) -> _STATE: """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. ...
Move which forces a random edge to appear on some sequence.
def _force_edge_active_move(self, state: _STATE) -> _STATE: """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...
Move which forces given edge to appear on some sequence.
def _force_edge_active(self, seqs: List[List[GridQubit]], edge: EDGE, sample_bool: Callable[[], bool] ) -> List[List[GridQubit]]: """Move which forces given edge to appear on some sequence. Args: seqs: List of linear sequences covering chi...
Creates initial solution based on the chip description.
def _create_initial_solution(self) -> _STATE: """Creates initial solution based on the chip description. Initial solution is constructed in a greedy way. Returns: Valid search state. """ def extract_sequences() -> List[List[GridQubit]]: """Creates list of...
Gives unique representative of the edge.
def _normalize_edge(self, edge: EDGE) -> EDGE: """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: ...
Picks random edge from the set of edges.
def _choose_random_edge(self, edges: Set[EDGE]) -> Optional[EDGE]: """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. """ if edges: index = self._...
Runs line sequence search.
def place_line(self, device: 'cirq.google.XmonDevice', length: int) -> GridQubitLineTuple: """Runs line sequence search. Args: device: Chip description. length: Required line length. Returns: List of linear sequences on ...
An adjacency - respecting decomposition.
def _decompose_(self, qubits): """An adjacency-respecting decomposition. 0: ───p───@──────────────@───────@──────────@────────── │ │ │ │ 1: ───p───X───@───p^-1───X───@───X──────@───X──────@─── │ │ │ ...
A decomposition assuming the control separates the targets.
def _decompose_inside_control(self, target1: raw_types.Qid, control: raw_types.Qid, target2: raw_types.Qid ) -> op_tree.OP_TREE: """A decomposition assuming the control separat...
A decomposition assuming one of the targets is in the middle.
def _decompose_outside_control(self, control: raw_types.Qid, near_target: raw_types.Qid, far_target: raw_types.Qid ) -> op_tree.OP_TREE: """A decomposition assuming one of ...
Return a sequence of tuples representing a probabilistic combination.
def mixture( val: Any, default: Any = RaiseTypeErrorIfNotProvided) -> Sequence[Tuple[float, Any]]: """Return a sequence of tuples representing a probabilistic combination. A mixture is described by an iterable of tuples of the form (probability of object, object) The probability component...
Returns whether the value has a mixture representation.
def has_mixture(val: Any) -> bool: """Returns whether the value has a mixture representation. Returns: If `val` has a `_has_mixture_` method and its result is not NotImplemented, that result is returned. Otherwise, if the value has a `_mixture_` method return True if that has a non-defa...
Return a sequence of tuples for a channel that is a mixture of unitaries.
def mixture_channel( val: Any, default: Any = RaiseTypeErrorIfNotProvided) -> Sequence[ Tuple[float, np.ndarray]]: """Return a sequence of tuples for a channel that is a mixture of unitaries. In contrast to `mixture` this method falls back to `unitary` if `_mixture_` is not implemented. A ...
Returns whether the value has a mixture channel representation.
def has_mixture_channel(val: Any) -> bool: """Returns whether the value has a mixture channel representation. In contrast to `has_mixture` this method falls back to checking whether the value has a unitary representation via `has_channel`. Returns: If `val` has a `_has_mixture_` method and its...
Validates that the mixture s tuple are valid probabilities.
def validate_mixture(supports_mixture: SupportsMixture): """Validates that the mixture's tuple are valid probabilities.""" mixture_tuple = mixture(supports_mixture, None) if mixture_tuple is None: raise TypeError('{}_mixture did not have a _mixture_ method'.format( supports_mixture)) ...
Computes displays in the supplied Circuit or Schedule.
def compute_displays( self, program: Union[circuits.Circuit, schedules.Schedule], param_resolver: study.ParamResolver = study.ParamResolver({}), qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, initial_state: Union[int, np.ndarray] = 0, ) -> study.ComputeDisplaysRe...
Decorator that ensures a pool is available for a stepper.
def ensure_pool(func): """Decorator that ensures a pool is available for a stepper.""" def func_wrapper(*args, **kwargs): if len(args) == 0 or not isinstance(args[0], Stepper): raise Exception('@ensure_pool can only be used on Stepper methods.') if args[0]._pool is None: ...
Accumulates single qubit phase gates into the scratch shards.
def _single_qubit_accumulate_into_scratch(args: Dict[str, Any]): """Accumulates single qubit phase gates into the scratch shards.""" index = args['indices'][0] shard_num = args['shard_num'] half_turns = args['half_turns'] num_shard_qubits = args['num_shard_qubits'] scratch = _scratch_shard(args)...
Returns a projector onto the |1 > subspace of the index - th qubit.
def _one_projector(args: Dict[str, Any], index: int) -> Union[int, np.ndarray]: """Returns a projector onto the |1> subspace of the index-th qubit.""" num_shard_qubits = args['num_shard_qubits'] shard_num = args['shard_num'] if index >= num_shard_qubits: return _kth_bit(shard_num, index - num_sh...
Accumulates two qubit phase gates into the scratch shards.
def _two_qubit_accumulate_into_scratch(args: Dict[str, Any]): """Accumulates two qubit phase gates into the scratch shards.""" index0, index1 = args['indices'] half_turns = args['half_turns'] scratch = _scratch_shard(args) projector = _one_projector(args, index0) * _one_projector(args, index1) ...
Takes scratch shards and applies them as exponentiated phase to state.
def _apply_scratch_as_phase(args: Dict[str, Any]): """Takes scratch shards and applies them as exponentiated phase to state. """ state = _state_shard(args) state *= np.exp(I_PI_OVER_2 * _scratch_shard(args))
Applies a W gate when the gate acts only within a shard.
def _w_within_shard(args: Dict[str, Any]): """Applies a W gate when the gate acts only within a shard.""" index = args['index'] half_turns = args['half_turns'] axis_half_turns = args['axis_half_turns'] state = _state_shard(args) pm_vect = _pm_vects(args)[index] num_shard_qubits = args['num_s...
Applies a W gate when the gate acts between shards.
def _w_between_shards(args: Dict[str, Any]): """Applies a W gate when the gate acts between shards.""" shard_num = args['shard_num'] state = _state_shard(args) num_shard_qubits = args['num_shard_qubits'] index = args['index'] half_turns = args['half_turns'] axis_half_turns = args['axis_half...
Copes scratch shards to state shards.
def _copy_scratch_to_state(args: Dict[str, Any]): """Copes scratch shards to state shards.""" np.copyto(_state_shard(args), _scratch_shard(args))
Returns the probability of getting a one measurement on a state shard.
def _one_prob_per_shard(args: Dict[str, Any]) -> float: """Returns the probability of getting a one measurement on a state shard. """ index = args['index'] state = _state_shard(args) * _one_projector(args, index) norm = np.linalg.norm(state) return norm * norm
Returns the norm for each state shard.
def _norm_squared(args: Dict[str, Any]) -> float: """Returns the norm for each state shard.""" state = _state_shard(args) return np.sum(np.abs(state) ** 2)
Renormalizes the state using the norm arg.
def _renorm(args: Dict[str, Any]): """Renormalizes the state using the norm arg.""" state = _state_shard(args) # If our gate is so bad that we have norm of zero, we have bigger problems. state /= np.sqrt(args['norm_squared'])
Projects state shards onto the appropriate post measurement state.
def _collapse_state(args: Dict[str, Any]): """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. """ index = args['index'] result = args['result'...
Initializes bitwise vectors which is precomputed in shared memory.
def init_z_vects(self): """Initializes bitwise vectors which is precomputed in shared memory. There are two types of vectors here, a zero one vectors and a pm (plus/minus) vectors. The pm vectors have rows that are Pauli Z operators acting on the all ones vector. The column-th row corre...