How to use the cirq.value function in cirq

To help you get started, we’ve selected a few cirq examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github quantumlib / Cirq / cirq / ops / swap_gates.py View on Github external
def _pauli_expansion_(self) -> value.LinearDict[str]:
        if protocols.is_parameterized(self):
            return NotImplemented
        global_phase = 1j**(2 * self._exponent * self._global_shift)
        swap_phase = 1j**self._exponent
        c = -1j * swap_phase * np.sin(np.pi * self._exponent / 2) / 2
        return value.LinearDict({
            'II': global_phase * (1 - c),
            'XX': global_phase * c,
            'YY': global_phase * c,
            'ZZ': global_phase * c,
        })
github quantumlib / Cirq / cirq / ops / identity.py View on Github external
from typing import (Any, Iterable, List, Optional, Sequence, Tuple, Union,
                    TYPE_CHECKING)

import numpy as np
import sympy

from cirq import protocols, value
from cirq._compat import deprecated
from cirq._doc import document
from cirq.ops import raw_types

if TYPE_CHECKING:
    import cirq


@value.value_equality
class IdentityGate(raw_types.Gate):
    """A Gate that perform no operation on qubits.

    The unitary matrix of this gate is a diagonal matrix with all 1s on the
    diagonal and all 0s off the diagonal in any basis.

    `cirq.I` is the single qubit identity gate.
    """

    def __init__(self,
                 num_qubits: Optional[int] = None,
                 qid_shape: Tuple[int, ...] = None):
        """
        Args:
            num_qubits:
            qid_shape: Specifies the dimension of each qid the measurement
github quantumlib / Cirq / cirq / google / api / v2 / sweeps.py View on Github external
for factor in sweep.factors:
            sweep_to_proto(factor, out=out.sweep_function.sweeps.add())
    elif isinstance(sweep, sweeps.Zip):
        out.sweep_function.function_type = run_context_pb2.SweepFunction.ZIP
        for s in sweep.sweeps:
            sweep_to_proto(s, out=out.sweep_function.sweeps.add())
    elif isinstance(sweep, sweeps.Linspace):
        out.single_sweep.parameter_key = sweep.key
        out.single_sweep.linspace.first_point = sweep.start
        out.single_sweep.linspace.last_point = sweep.stop
        out.single_sweep.linspace.num_points = sweep.length
    elif isinstance(sweep, sweeps.Points):
        out.single_sweep.parameter_key = sweep.key
        out.single_sweep.points.points.extend(sweep.points)
    elif isinstance(sweep, sweeps.ListSweep):
        sweep_dict: Dict[str, List[value.TParamVal]] = {}
        for param_resolver in sweep:
            for key in param_resolver:
                if key not in sweep_dict:
                    sweep_dict[key] = []
                sweep_dict[key].append(param_resolver.value_of(key))
        out.sweep_function.function_type = run_context_pb2.SweepFunction.ZIP
        for key in sweep_dict:
            sweep_to_proto(sweeps.Points(key, sweep_dict[key]),
                           out=out.sweep_function.sweeps.add())
    else:
        raise ValueError('cannot convert to v2 Sweep proto: {}'.format(sweep))
    return out
github quantumlib / Cirq / cirq / google / common_serializers.py View on Github external
            value_func=lambda nanos: value.Duration(nanos=cast(
                Union[int, float, sympy.Basic], nanos)))
    ])
github quantumlib / Cirq / cirq / contrib / acquaintance / shift.py View on Github external
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import itertools
from typing import Dict, Sequence, Tuple, TYPE_CHECKING

from cirq import ops, value
from cirq.contrib.acquaintance.permutation import (
        SwapPermutationGate, PermutationGate)

if TYPE_CHECKING:
    import cirq


@value.value_equality
class CircularShiftGate(PermutationGate):
    """Performs a cyclical permutation of the qubits to the left by a specified
    amount.

    Args:
        shift: how many positions to circularly left shift the qubits.
        swap_gate: the gate to use when decomposing.
    """

    def __init__(self,
                 num_qubits: int,
                 shift: int,
                 swap_gate: 'cirq.Gate' = ops.SWAP) -> None:
        super(CircularShiftGate, self).__init__(num_qubits, swap_gate)
        self.shift = shift
github quantumlib / Cirq / cirq / linalg / predicates.py View on Github external
out_size = (cast(int, num_qubits) if out_size_specified else
                max(target_qubit_axes, default=-1) + 1)
    result = cast(List[Union[slice, int, 'ellipsis']], [slice(None)] * out_size)
    if not out_size_specified:
        result.append(Ellipsis)
    if qid_shape is None:
        qid_shape = (2,) * out_size
    target_shape = tuple(qid_shape[i] for i in target_qubit_axes)
    if big_endian_qureg_value:
        digits = value.big_endian_int_to_digits(big_endian_qureg_value,
                                                base=target_shape)
    else:
        if little_endian_qureg_value < 0 and not qid_shape_specified:
            # Allow negative binary numbers
            little_endian_qureg_value &= (1 << len(target_shape)) - 1
        digits = value.big_endian_int_to_digits(little_endian_qureg_value,
                                                base=target_shape[::-1])[::-1]
    for axis, digit in zip(target_qubit_axes, digits):
        result[axis] = digit
    return tuple(result)
github quantumlib / Cirq / cirq / ops / raw_types.py View on Github external
    @value.alternative(requires='_qid_shape_',
                       implementation=_num_qubits_from_shape)
    def _num_qubits_(self) -> int:
        """The number of qubits this gate acts on."""
github quantumlib / Cirq / cirq / sim / wave_function.py View on Github external
ValueError: ``repetitions`` is less than one or size of ``state`` is not
            a power of 2.
        IndexError: An index from ``indices`` is out of range, given the number
            of qubits corresponding to the state.
    """
    if repetitions < 0:
        raise ValueError('Number of repetitions cannot be negative. Was {}'
                         .format(repetitions))
    qid_shape = _validate_qid_shape(state, qid_shape)
    num_qubits = len(qid_shape)
    _validate_indices(num_qubits, indices)

    if repetitions == 0 or len(indices) == 0:
        return np.zeros(shape=(repetitions, len(indices)), dtype=np.uint8)

    prng = value.parse_random_state(seed)

    # Calculate the measurement probabilities.
    probs = _probs(state, indices, qid_shape)

    # We now have the probability vector, correctly ordered, so sample over
    # it. Note that we us ints here, since numpy's choice does not allow for
    # choosing from a list of tuples or list of lists.
    result = prng.choice(len(probs), size=repetitions, p=probs)
    # Convert to individual qudit measurements.
    meas_shape = tuple(qid_shape[i] for i in indices)
    return np.array([
        value.big_endian_int_to_digits(result[i], base=meas_shape)
        for i in range(len(result))
    ],
                    dtype=np.uint8)
github quantumlib / Cirq / cirq / ops / common_channels.py View on Github external
$$
            \rho \rightarrow (1 - p_x - p_y - p_z) \rho
                    + p_x X \rho X + p_y Y \rho Y + p_z Z \rho Z
            $$

        Args:
            p_x: The probability that a Pauli X and no other gate occurs.
            p_y: The probability that a Pauli Y and no other gate occurs.
            p_z: The probability that a Pauli Z and no other gate occurs.

        Raises:
            ValueError: if the args or the sum of args are not probabilities.
        """

        self._p_x = value.validate_probability(p_x, 'p_x')
        self._p_y = value.validate_probability(p_y, 'p_y')
        self._p_z = value.validate_probability(p_z, 'p_z')
        self._p_i = 1 - value.validate_probability(p_x + p_y + p_z,
                                                   'p_x + p_y + p_z')
github quantumlib / Cirq / cirq / ops / parallel_gate_operation.py View on Github external
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


from typing import Sequence, Tuple, Union, Any, Optional

import numpy as np

from cirq import protocols, value
from cirq.ops import raw_types, op_tree
from cirq.type_workarounds import NotImplementedType


@value.value_equality
class ParallelGateOperation(raw_types.Operation):
    """An application of several copies of a gate to a group of qubits."""

    def __init__(self,
                 gate: raw_types.Gate,
                 qubits: Sequence[raw_types.Qid]) -> None:
        """
        Args:
            gate: the gate to apply.
            qubits: list of qubits to apply the gate to.
        """
        if gate.num_qubits() != 1:
            raise ValueError("gate must be a single qubit gate")
        if len(set(qubits)) != len(qubits):
            raise ValueError("repeated qubits are not allowed")
        for qubit in qubits: