Python typing.Sequence() Examples

The following are 30 code examples of typing.Sequence(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module typing , or try the search function .
Example #1
Source File: state_preparation.py    From OpenFermion-Cirq with Apache License 2.0 7 votes vote down vote up
def _generic_gaussian_circuit(
        qubits: Sequence[cirq.Qid],
        quadratic_hamiltonian: QuadraticHamiltonian,
        occupied_orbitals: Optional[Sequence[int]],
        initial_state: Union[int, Sequence[int]]) -> cirq.OP_TREE:

    n_qubits = len(qubits)
    circuit_description, start_orbitals = gaussian_state_preparation_circuit(
            quadratic_hamiltonian, occupied_orbitals)

    if isinstance(initial_state, int):
        initially_occupied_orbitals = _occupied_orbitals(
                initial_state, n_qubits)
    else:
        initially_occupied_orbitals = initial_state  # type: ignore

    # Flip bits so that the correct starting orbitals are occupied
    yield (cirq.X(qubits[j]) for j in range(n_qubits)
           if (j in initially_occupied_orbitals) != (j in start_orbitals))

    yield _ops_from_givens_rotations_circuit_description(
            qubits, circuit_description) 
Example #2
Source File: pytype_test.py    From typeshed with Apache License 2.0 6 votes vote down vote up
def determine_files_to_test(*, typeshed_location: str, paths: Sequence[str]) -> List[Tuple[str, int]]:
    """Determine all files to test, checking if it's in the exclude list and which Python versions to use.

    Returns a list of pairs of the file path and Python version as an int."""
    skipped = PathMatcher(load_exclude_list(typeshed_location))
    filenames = find_stubs_in_paths(paths)
    files = []
    for f in sorted(filenames):
        rel = _get_relative(f)
        if skipped.search(rel):
            continue
        if _is_version(f, "2and3"):
            files.append((f, 2))
            files.append((f, 3))
        elif _is_version(f, "2"):
            files.append((f, 2))
        elif _is_version(f, "3"):
            files.append((f, 3))
        else:
            print("Unrecognized path: {}".format(f))
    return files 
Example #3
Source File: linear_swap_network.py    From OpenFermion-Cirq with Apache License 2.0 6 votes vote down vote up
def trotter_step(
            self,
            qubits: Sequence[cirq.Qid],
            time: float,
            control_qubit: Optional[cirq.Qid]=None
            ) -> cirq.OP_TREE:

        n_qubits = len(qubits)

        # Apply one- and two-body interactions for the full time
        def one_and_two_body_interaction(p, q, a, b) -> cirq.OP_TREE:
            yield Rxxyy(
                    self.hamiltonian.one_body[p, q].real * time).on(a, b)
            yield Ryxxy(
                    self.hamiltonian.one_body[p, q].imag * time).on(a, b)
            yield rot11(rads=
                    -2 * self.hamiltonian.two_body[p, q] * time).on(a, b)
        yield swap_network(qubits, one_and_two_body_interaction, fermionic=True)
        qubits = qubits[::-1]

        # Apply one-body potential for the full time
        yield (cirq.rz(rads=
                   -self.hamiltonian.one_body[i, i].real * time).on(qubits[i])
               for i in range(n_qubits)) 
Example #4
Source File: wrapped.py    From OpenFermion-Cirq with Apache License 2.0 6 votes vote down vote up
def assert_implements_consistent_protocols(
        val: Any,
        *,
        exponents: Sequence[Any] = (
            0, 1, -1, 0.5, 0.25, -0.5, 0.1, sympy.Symbol('s')),
        qubit_count: Optional[int] = None,
        ignoring_global_phase: bool=False,
        setup_code: str = _setup_code,
        global_vals: Optional[Dict[str, Any]] = None,
        local_vals: Optional[Dict[str, Any]] = None
        ) -> None:
    """Checks that a value is internally consistent and has a good __repr__."""

    cirq.testing.assert_implements_consistent_protocols(
        val,
        exponents=exponents,
        qubit_count=qubit_count,
        ignoring_global_phase=ignoring_global_phase,
        setup_code=setup_code,
        global_vals=global_vals,
        local_vals=local_vals) 
Example #5
Source File: wrapped.py    From OpenFermion-Cirq with Apache License 2.0 6 votes vote down vote up
def assert_eigengate_implements_consistent_protocols(
        eigen_gate_type: Type[cirq.EigenGate],
        *,
        exponents: Sequence[Union[sympy.Basic, float]] = (
            0, 1, -1, 0.25, -0.5, 0.1, sympy.Symbol('s')),
        global_shifts: Sequence[float] = (0, -0.5, 0.1),
        qubit_count: Optional[int] = None,
        ignoring_global_phase: bool=False,
        setup_code: str = _setup_code,
        global_vals: Optional[Dict[str, Any]] = None,
        local_vals: Optional[Dict[str, Any]] = None) -> None:
    """Checks that an EigenGate subclass is internally consistent and has a
    good __repr__."""

    cirq.testing.assert_eigengate_implements_consistent_protocols(
        eigen_gate_type,
        exponents=exponents,
        global_shifts=global_shifts,
        qubit_count=qubit_count,
        ignoring_global_phase=ignoring_global_phase,
        setup_code=setup_code,
        global_vals=global_vals,
        local_vals=local_vals) 
Example #6
Source File: trotter_algorithm.py    From OpenFermion-Cirq with Apache License 2.0 6 votes vote down vote up
def finish(self,
               qubits: Sequence[cirq.Qid],
               n_steps: int,
               control_qubit: Optional[cirq.Qid]=None,
               omit_final_swaps: bool=False
               ) -> cirq.OP_TREE:
        """Operations to perform after all Trotter steps are done.

        Args:
            qubits: The qubits on which to perform operations.
            hamiltonian: The Hamiltonian to simulate.
            n_steps: The total number of Trotter steps that have been performed.
            control_qubit: The control qubit, if the algorithm is controlled.
            omit_final_swaps: Whether or not to omit swap gates at the end of
                the circuit.
        """
        # Default: do nothing
        return () 
Example #7
Source File: many_to_one.py    From matchpy with MIT License 6 votes vote down vote up
def _match_sequence_variables(
            self,
            subjects: MultisetOfExpression,
            pattern_vars: Sequence[VariableWithCount],
            substitution: Substitution,
    ) -> Iterator[Substitution]:
        only_counts = [info for info, _ in pattern_vars]
        wrapped_vars = [name for (name, _, _, _), wrap in pattern_vars if wrap and name]
        for variable_substitution in commutative_sequence_variable_partition_iter(subjects, only_counts):
            for var in wrapped_vars:
                operands = variable_substitution[var]
                if isinstance(operands, (tuple, list, Multiset)):
                    if len(operands) > 1:
                        variable_substitution[var] = self.associative(*operands)
                    else:
                        variable_substitution[var] = next(iter(operands))
            try:
                result_substitution = substitution.union(variable_substitution)
            except ValueError:
                continue
            yield result_substitution 
Example #8
Source File: many_to_one.py    From matchpy with MIT License 6 votes vote down vote up
def replace_post_order(self, expression: Expression) -> Union[Expression, Sequence[Expression]]:
        """Replace all occurrences of the patterns according to the replacement rules.

        Replaces innermost expressions first.

        Args:
            expression:
                The expression to which the replacement rules are applied.
            max_count:
                If given, at most *max_count* applications of the rules are performed. Otherwise, the rules
                are applied until there is no more match. If the set of replacement rules is not confluent,
                the replacement might not terminate without a *max_count* set.

        Returns:
            The resulting expression after the application of the replacement rules. This can also be a sequence of
            expressions, if the root expression is replaced with a sequence of expressions by a rule.
        """
        return self._replace_post_order(expression)[0] 
Example #9
Source File: split_operator.py    From OpenFermion-Cirq with Apache License 2.0 5 votes vote down vote up
def trotter_step(
            self,
            qubits: Sequence[cirq.Qid],
            time: float,
            control_qubit: Optional[cirq.Qid]=None
            ) -> cirq.OP_TREE:

        n_qubits = len(qubits)

        # Simulate the two-body terms for the full time
        def two_body_interaction(p, q, a, b) -> cirq.OP_TREE:
            yield rot11(rads=
                    -2 * self.hamiltonian.two_body[p, q] * time).on(a, b)
        yield swap_network(qubits, two_body_interaction)
        # The qubit ordering has been reversed
        qubits = qubits[::-1]

        # Rotate to the basis in which the one-body term is diagonal
        yield cirq.inverse(
                bogoliubov_transform(qubits, self.basis_change_matrix))

        # Simulate the one-body terms for the full time
        yield (cirq.rz(rads=
                   -self.orbital_energies[i] * time).on(qubits[i])
               for i in range(n_qubits))

        # Rotate back to the computational basis
        yield bogoliubov_transform(qubits, self.basis_change_matrix) 
Example #10
Source File: device.py    From btle-sniffer with MIT License 5 votes vote down vote up
def __init__(self, uuid: str, value: Optional[Sequence[int]],
                 flags: Optional[Sequence[str]]):
        self.uuid = uuid
        self.value = value
        self.flags = flags 
Example #11
Source File: pytype_test.py    From typeshed with Apache License 2.0 5 votes vote down vote up
def __init__(self, patterns: Sequence[str]) -> None:
        patterns = [re.escape(os.path.join(*x.split("/"))) for x in patterns]
        self.matcher = re.compile(r"({})$".format("|".join(patterns))) if patterns else None 
Example #12
Source File: one_to_one.py    From matchpy with MIT License 5 votes vote down vote up
def _build_full_partition(
        optional_parts, sequence_var_partition: Sequence[int], subjects: Sequence[Expression], operation: Operation
) -> List[Sequence[Expression]]:
    """Distribute subject operands among pattern operands.

    Given a partitoning for the variable part of the operands (i.e. a list of how many extra operands each sequence
    variable gets assigned).
    """
    i = 0
    var_index = 0
    opt_index = 0
    result = []
    for operand in op_iter(operation):
        wrap_associative = False
        if isinstance(operand, Wildcard):
            count = operand.min_count if operand.optional is None else 0
            if not operand.fixed_size or isinstance(operation, AssociativeOperation):
                count += sequence_var_partition[var_index]
                var_index += 1
                wrap_associative = operand.fixed_size and operand.min_count
            elif operand.optional is not None:
                count = optional_parts[opt_index]
                opt_index += 1
        else:
            count = 1

        operand_expressions = list(op_iter(subjects))[i:i + count]
        i += count

        if wrap_associative and len(operand_expressions) > wrap_associative:
            fixed = wrap_associative - 1
            operand_expressions = tuple(operand_expressions[:fixed]) + (
                create_operation_expression(operation, operand_expressions[fixed:]),
            )

        result.append(operand_expressions)

    return result 
Example #13
Source File: functions.py    From matchpy with MIT License 5 votes vote down vote up
def replace(expression: Expression, position: Sequence[int], replacement: Replacement) -> Replacement:
    r"""Replaces the subexpression of `expression` at the given `position` with the given `replacement`.

    The original `expression` itself is not modified, but a modified copy is returned. If the replacement
    is a list of expressions, it will be expanded into the list of operands of the respective operation:

    >>> print(replace(f(a), (0, ), [b, c]))
    f(b, c)

    Parameters:
        expression:
            An :class:`Expression` where a (sub)expression is to be replaced.
        position:
            A tuple of indices, e.g. the empty tuple refers to the `expression` itself,
            `(0, )` refers to the first child (operand) of the `expression`, `(0, 0)` to the first
            child of the first child etc.
        replacement:
            Either an :class:`Expression` or a list of :class:`Expression`\s to be
            inserted into the `expression` instead of the original expression at that `position`.

    Returns:
        The resulting expression from the replacement.

    Raises:
        IndexError: If the position is invalid or out of range.
    """
    if len(position) == 0:
        return replacement
    if not isinstance(expression, Operation):
        raise IndexError("Invalid position {!r} for expression {!s}".format(position, expression))
    if position[0] >= op_len(expression):
        raise IndexError("Position {!r} out of range for expression {!s}".format(position, expression))
    pos = position[0]
    operands = list(op_iter(expression))
    subexpr = replace(operands[pos], position[1:], replacement)
    if isinstance(subexpr, Sequence):
        new_operands = tuple(operands[:pos]) + tuple(subexpr) + tuple(operands[pos + 1:])
        return create_operation_expression(expression, new_operands)
    operands[pos] = subexpr
    return create_operation_expression(expression, operands) 
Example #14
Source File: device.py    From btle-sniffer with MIT License 5 votes vote down vote up
def __init__(self,
                 path: str, address: str,
                 paired: bool, connected: bool, services_resolved: bool,
                 name: Optional[str] = None, device_class: Optional[int] = None,
                 appearance: Optional[int] = None, uuids: Sequence[str] = None,
                 rssi: int = None, tx_power: int = None,
                 manufacturer_data: Dict[int, Sequence[int]] = None,
                 service_data: Dict[str, Sequence[int]] = None) -> None:
        self.active = True
        self.path = path
        self.address = address
        self.paired = paired
        self.connected = connected
        self.services_resolved = services_resolved
        self.name = name
        self.device_class = device_class
        self.appearance = appearance
        self.uuids = set(uuids) if uuids is not None else set()
        self.rssis = [rssi] if rssi is not None else list()
        self.tx_power = tx_power
        self.first_seen = datetime.datetime.now()
        self.last_seen = datetime.datetime.now()
        self.services: MutableMapping[str, GATTService] = dict()

        self.manufacturer_data = dict()
        if manufacturer_data is not None:
            for k, v in manufacturer_data.items():
                self.manufacturer_data[k] = [v]

        self.service_data = dict()
        if service_data is not None:
            self.uuids = self.uuids.union(service_data.keys())
            for k, v in service_data.items():
                self.service_data[k] = [v] 
Example #15
Source File: device.py    From btle-sniffer with MIT License 5 votes vote down vote up
def __init__(self, uuid: str, value: Optional[Sequence[int]],
                 flags: Sequence[str]):
        self.uuid = uuid
        self.value = value
        self.flags = flags
        self.descriptors: MutableMapping[str, GATTDescriptor] = dict() 
Example #16
Source File: functions.py    From matchpy with MIT License 5 votes vote down vote up
def replace_all_post_order(expression: Expression, rules: Iterable[ReplacementRule]) \
        -> Union[Expression, Sequence[Expression]]:
    """Replace all occurrences of the patterns according to the replacement rules.

    A replacement rule consists of a *pattern*, that is matched against any subexpression
    of the expression. If a match is found, the *replacement* callback of the rule is called with
    the variables from the match substitution. Whatever the callback returns is used as a replacement for the
    matched subexpression. This can either be a single expression or a sequence of expressions, which is then
    integrated into the surrounding operation in place of the subexpression.

    Note that the pattern can therefore not be a single sequence variable/wildcard, because only single expressions
    will be matched.

    Args:
        expression:
            The expression to which the replacement rules are applied.
        rules:
            A collection of replacement rules that are applied to the expression.
        max_count:
            If given, at most *max_count* applications of the rules are performed. Otherwise, the rules
            are applied until there is no more match. If the set of replacement rules is not confluent,
            the replacement might not terminate without a *max_count* set.

    Returns:
        The resulting expression after the application of the replacement rules. This can also be a sequence of
        expressions, if the root expression is replaced with a sequence of expressions by a rule.
    """
    return _replace_all_post_order(expression, rules)[0] 
Example #17
Source File: split_operator.py    From OpenFermion-Cirq with Apache License 2.0 5 votes vote down vote up
def trotter_step(
            self,
            qubits: Sequence[cirq.Qid],
            time: float,
            control_qubit: Optional[cirq.Qid]=None
            ) -> cirq.OP_TREE:

        n_qubits = len(qubits)

        if not isinstance(control_qubit, cirq.Qid):
            raise TypeError('Control qudit must be specified.')

        # Simulate the two-body terms for the full time
        def two_body_interaction(p, q, a, b) -> cirq.OP_TREE:
            yield rot111(-2 * self.hamiltonian.two_body[p, q] * time).on(
                cast(cirq.Qid, control_qubit), a, b)
        yield swap_network(qubits, two_body_interaction)
        # The qubit ordering has been reversed
        qubits = qubits[::-1]

        # Rotate to the basis in which the one-body term is diagonal
        yield cirq.inverse(
                bogoliubov_transform(qubits, self.basis_change_matrix))

        # Simulate the one-body terms for the full time
        yield (rot11(rads=
                   -self.orbital_energies[i] * time).on(
                       control_qubit, qubits[i])
               for i in range(n_qubits))

        # Rotate back to the computational basis
        yield bogoliubov_transform(qubits, self.basis_change_matrix)

        # Apply phase from constant term
        yield cirq.rz(rads=
                -self.hamiltonian.constant * time).on(control_qubit) 
Example #18
Source File: split_operator.py    From OpenFermion-Cirq with Apache License 2.0 5 votes vote down vote up
def finish(self,
               qubits: Sequence[cirq.Qid],
               n_steps: int,
               control_qubit: Optional[cirq.Qid]=None,
               omit_final_swaps: bool=False
               ) -> cirq.OP_TREE:
        # If the number of Trotter steps is odd, possibly swap qubits back
        if n_steps & 1 and not omit_final_swaps:
            yield swap_network(qubits) 
Example #19
Source File: trotter_algorithm.py    From OpenFermion-Cirq with Apache License 2.0 5 votes vote down vote up
def trotter_step(
            self,
            qubits: Sequence[cirq.Qid],
            time: float,
            control_qubit: Optional[cirq.Qid]=None
            ) -> cirq.OP_TREE:
        """Yield operations to perform a Trotter step.

        Args:
            qubits: The qubits on which to apply the Trotter step.
            hamiltonian: The Hamiltonian to simulate.
            time: The evolution time.
            control_qubit: The control qubit, if the algorithm is controlled.
        """ 
Example #20
Source File: split_operator.py    From OpenFermion-Cirq with Apache License 2.0 5 votes vote down vote up
def step_qubit_permutation(self,
                               qubits: Sequence[cirq.Qid],
                               control_qubit: Optional[cirq.Qid]=None
                               ) -> Tuple[Sequence[cirq.Qid],
                                          Optional[cirq.Qid]]:
        # A Trotter step reverses the qubit ordering
        return qubits[::-1], None 
Example #21
Source File: split_operator.py    From OpenFermion-Cirq with Apache License 2.0 5 votes vote down vote up
def step_qubit_permutation(self,
                               qubits: Sequence[cirq.Qid],
                               control_qubit: Optional[cirq.Qid]=None
                               ) -> Tuple[Sequence[cirq.Qid],
                                          Optional[cirq.Qid]]:
        # A Trotter step reverses the qubit ordering
        return qubits[::-1], control_qubit 
Example #22
Source File: split_operator.py    From OpenFermion-Cirq with Apache License 2.0 5 votes vote down vote up
def prepare(self,
                qubits: Sequence[cirq.Qid],
                control_qubits: Optional[cirq.Qid]=None
                ) -> cirq.OP_TREE:
        # Change to the basis in which the one-body term is diagonal
        yield cirq.inverse(
                bogoliubov_transform(qubits, self.basis_change_matrix)) 
Example #23
Source File: pytype_test.py    From typeshed with Apache License 2.0 5 votes vote down vote up
def find_stubs_in_paths(paths: Sequence[str]) -> List[str]:
    filenames = []
    for path in paths:
        if os.path.isdir(path):
            for root, _, fns in os.walk(path):
                filenames.extend(os.path.join(root, fn) for fn in fns if fn.endswith(".pyi"))
        else:
            filenames.append(path)
    return filenames 
Example #24
Source File: trotter_algorithm.py    From OpenFermion-Cirq with Apache License 2.0 5 votes vote down vote up
def step_qubit_permutation(self,
                               qubits: Sequence[cirq.Qid],
                               control_qubit: Optional[cirq.Qid]=None
                               ) -> Tuple[Sequence[cirq.Qid],
                                          Optional[cirq.Qid]]:
        """The qubit permutation induced by a single Trotter step.

        Returns:
            A tuple whose first element is the new list of system qubits and
            second element is the new control qubit
        """
        # Default: identity permutation
        return qubits, control_qubit 
Example #25
Source File: split_operator.py    From OpenFermion-Cirq with Apache License 2.0 5 votes vote down vote up
def finish(self,
               qubits: Sequence[cirq.Qid],
               n_steps: int,
               control_qubit: Optional[cirq.Qid]=None,
               omit_final_swaps: bool=False
               ) -> cirq.OP_TREE:
        # Rotate back to the computational basis
        yield bogoliubov_transform(
                qubits, self.basis_change_matrix)
        # If the number of Trotter steps is odd, possibly swap qubits back
        if n_steps & 1 and not omit_final_swaps:
            yield swap_network(qubits) 
Example #26
Source File: split_operator.py    From OpenFermion-Cirq with Apache License 2.0 5 votes vote down vote up
def step_qubit_permutation(self,
                               qubits: Sequence[cirq.Qid],
                               control_qubit: Optional[cirq.Qid]=None
                               ) -> Tuple[Sequence[cirq.Qid],
                                          Optional[cirq.Qid]]:
        # A Trotter step reverses the qubit ordering
        return qubits[::-1], None 
Example #27
Source File: split_operator.py    From OpenFermion-Cirq with Apache License 2.0 5 votes vote down vote up
def prepare(self,
                qubits: Sequence[cirq.Qid],
                control_qubits: Optional[cirq.Qid]=None
                ) -> cirq.OP_TREE:
        # Change to the basis in which the one-body term is diagonal
        yield cirq.inverse(
                bogoliubov_transform(qubits, self.basis_change_matrix)) 
Example #28
Source File: low_rank.py    From OpenFermion-Cirq with Apache License 2.0 5 votes vote down vote up
def finish(self,
               qubits: Sequence[cirq.Qid],
               n_steps: int,
               control_qubit: Optional[cirq.Qid]=None,
               omit_final_swaps: bool=False
               ) -> cirq.OP_TREE:
        if not omit_final_swaps:
            # If the number of swap networks was odd, swap the qubits back
            if n_steps & 1 and len(self.eigenvalues) & 1:
                yield swap_network(qubits) 
Example #29
Source File: low_rank.py    From OpenFermion-Cirq with Apache License 2.0 5 votes vote down vote up
def step_qubit_permutation(self,
                               qubits: Sequence[cirq.Qid],
                               control_qubit: Optional[cirq.Qid]=None
                               ) -> Tuple[Sequence[cirq.Qid],
                                          Optional[cirq.Qid]]:
        # A Trotter step reverses the qubit ordering when the number of
        # eigenvalues is odd
        if len(self.eigenvalues) & 1:
            return qubits[::-1], control_qubit
        else:
            return qubits, control_qubit 
Example #30
Source File: low_rank.py    From OpenFermion-Cirq with Apache License 2.0 5 votes vote down vote up
def finish(self,
               qubits: Sequence[cirq.Qid],
               n_steps: int,
               control_qubit: Optional[cirq.Qid]=None,
               omit_final_swaps: bool=False
               ) -> cirq.OP_TREE:
        if not omit_final_swaps:
            # If the number of swap networks was odd, swap the qubits back
            if n_steps & 1 and len(self.eigenvalues) & 1:
                yield swap_network(qubits)