コード例 #1
0
ファイル: schedule_test.py プロジェクト: yinxx/Cirq
def test_query_point_operation_inclusive():
    q = ops.QubitId()
    zero = Timestamp(picos=0)
    ps = Duration(picos=1)
    op = ScheduledOperation(zero, Duration(), ops.H(q))
    schedule = Schedule(device=UnconstrainedDevice, scheduled_operations=[op])

    def query(t, d=Duration(), qubits=None):
        return schedule.query(time=t,
                              duration=d,
                              qubits=qubits,
                              include_query_end_time=True,
                              include_op_end_times=True)

    assert query(zero) == [op]
    assert query(zero + ps) == []
    assert query(zero - ps) == []

    assert query(zero, qubits=[]) == []
    assert query(zero, qubits=[q]) == [op]

    assert query(zero, ps) == [op]
    assert query(zero - 0.5 * ps, ps) == [op]
    assert query(zero - ps, ps) == [op]
    assert query(zero - 2 * ps, ps) == []
    assert query(zero - ps, 3 * ps) == [op]
    assert query(zero + ps, ps) == []
コード例 #2
0
def test_init():
    r = ScheduledOperation(time=Timestamp(picos=5),
                           duration=Duration(picos=7),
                           operation=cirq.H(cirq.NamedQubit('a')))
    assert r.time == Timestamp(picos=5)
    assert r.duration == Duration(picos=7)
    assert r.operation == cirq.H(cirq.NamedQubit('a'))
コード例 #3
0
ファイル: duration_test.py プロジェクト: sycramore/Cirq
def test_repr():
    a = Duration(picos=1000, nanos=1000)
    cirq.testing.assert_equivalent_repr(a)
    b = Duration(picos=5000)
    cirq.testing.assert_equivalent_repr(b)
    c = Duration(nanos=1.0)
    cirq.testing.assert_equivalent_repr(c)
コード例 #4
0
ファイル: schedule_test.py プロジェクト: yinxx/Cirq
def test_query_point_operation_exclusive():
    q = ops.QubitId()
    zero = Timestamp(picos=0)
    ps = Duration(picos=1)
    op = ScheduledOperation(zero, Duration(), ops.H(q))
    schedule = Schedule(device=UnconstrainedDevice, scheduled_operations=[op])

    assert schedule.query(time=zero,
                          include_query_end_time=False,
                          include_op_end_times=False) == []
    assert schedule.query(time=zero + ps,
                          include_query_end_time=False,
                          include_op_end_times=False) == []
    assert schedule.query(time=zero - ps,
                          include_query_end_time=False,
                          include_op_end_times=False) == []
    assert schedule.query(time=zero) == []
    assert schedule.query(time=zero + ps) == []
    assert schedule.query(time=zero - ps) == []

    assert schedule.query(time=zero, qubits=[]) == []
    assert schedule.query(time=zero, qubits=[q]) == []

    assert schedule.query(time=zero, duration=ps) == []
    assert schedule.query(time=zero - 0.5 * ps, duration=ps) == [op]
    assert schedule.query(time=zero - ps, duration=ps) == []
    assert schedule.query(time=zero - 2 * ps, duration=ps) == []
    assert schedule.query(time=zero - ps, duration=3 * ps) == [op]
    assert schedule.query(time=zero + ps, duration=ps) == []
コード例 #5
0
 def duration_of(self, operation: ops.Operation) -> Duration:
     g = operation.gate
     if isinstance(g, ops.HGate):
         return Duration(nanos=20)
     elif isinstance(g, ops.Rot11Gate):
         return Duration(nanos=40)
     else:
         raise ValueError('Unsupported gate type {}'.format(repr(g)))
コード例 #6
0
def test_init():
    r = ScheduledOperation(time=Timestamp(picos=5),
                           duration=Duration(picos=7),
                           operation=ops.Operation(ops.H,
                                                   [ops.NamedQubit('a')]))
    assert r.time == Timestamp(picos=5)
    assert r.duration == Duration(picos=7)
    assert r.operation == ops.Operation(ops.H, [ops.NamedQubit('a')])
コード例 #7
0
ファイル: duration_test.py プロジェクト: sycramore/Cirq
def test_cmp_vs_other_type():
    with pytest.raises(TypeError):
        _ = Duration() < 0
    with pytest.raises(TypeError):
        _ = Duration() <= 0
    with pytest.raises(TypeError):
        _ = Duration() >= 0
    with pytest.raises(TypeError):
        _ = Duration() > 0
コード例 #8
0
def test_eq():
    eq = cirq.testing.EqualsTester()
    eq.add_equality_group(Duration(), Duration(picos=0), Duration(nanos=0.0), timedelta(0))
    eq.add_equality_group(Duration(picos=1000), Duration(nanos=1))
    eq.make_equality_group(lambda: Duration(picos=-1))
    eq.add_equality_group(Duration(micros=5.0), Duration(micros=5), timedelta(0, 0, 5))

    # Can't hash match 0, but no-duration is equal to 0.
    assert Duration() == 0
    assert Duration(picos=1) != 0
コード例 #9
0
def test_eq():
    q0 = ops.QubitId()

    eq = EqualsTester()
    eq.make_equality_pair(
        lambda: ScheduledOperation(Timestamp(), Duration(), ops.H(q0)))
    eq.make_equality_pair(
        lambda: ScheduledOperation(Timestamp(picos=5), Duration(), ops.H(q0)))
    eq.make_equality_pair(
        lambda: ScheduledOperation(Timestamp(), Duration(picos=5), ops.H(q0)))
    eq.make_equality_pair(
        lambda: ScheduledOperation(Timestamp(), Duration(), ops.X(q0)))
コード例 #10
0
def test_eq():
    q0 = cirq.QubitId()

    eq = EqualsTester()
    eq.make_equality_group(
        lambda: ScheduledOperation(Timestamp(), Duration(), cirq.H(q0)))
    eq.make_equality_group(
        lambda: ScheduledOperation(Timestamp(picos=5), Duration(), cirq.H(q0)))
    eq.make_equality_group(
        lambda: ScheduledOperation(Timestamp(), Duration(picos=5), cirq.H(q0)))
    eq.make_equality_group(
        lambda: ScheduledOperation(Timestamp(), Duration(), cirq.X(q0)))
コード例 #11
0
def test_parameterized(resolve_fn):
    t = sympy.Symbol('t')
    assert not cirq.is_parameterized(Duration())
    assert not cirq.is_parameterized(Duration(nanos=500))
    assert cirq.is_parameterized(Duration(nanos=500 * t))

    assert resolve_fn(Duration(), {'t': 2}) == Duration()
    assert resolve_fn(Duration(nanos=500), {'t': 2}) == Duration(nanos=500)
    assert resolve_fn(Duration(nanos=500 * t), {'t': 2}) == Duration(nanos=1000)
コード例 #12
0
ファイル: duration_test.py プロジェクト: sycramore/Cirq
def test_init():
    assert Duration().total_picos() == 0
    assert Duration(picos=513).total_picos() == 513
    assert Duration(picos=-5).total_picos() == -5
    assert Duration(nanos=211).total_picos() == 211000
    assert Duration(nanos=211, picos=1051).total_picos() == 212051

    assert isinstance(Duration(picos=1).total_picos(), int)
    assert isinstance(Duration(nanos=1).total_picos(), int)
    assert isinstance(Duration(picos=1.0).total_picos(), float)
    assert isinstance(Duration(nanos=1.0).total_picos(), float)
コード例 #13
0
def test_sub():
    assert Duration() - Duration() == Duration()
    assert Duration(picos=1) - Duration(picos=2) == Duration(picos=-1)

    with pytest.raises(TypeError):
        _ = 1 - Duration()
    with pytest.raises(TypeError):
        _ = Duration() - 1
コード例 #14
0
def test_add():
    assert Duration() + Duration() == Duration()
    assert Duration(picos=1) + Duration(picos=2) == Duration(picos=3)

    with pytest.raises(TypeError):
        _ = 1 + Duration()
    with pytest.raises(TypeError):
        _ = Duration() + 1
コード例 #15
0
    def __init__(
        self,
        measurement_duration: 'cirq.DURATION_LIKE',
        gate_duration: 'cirq.DURATION_LIKE',
        control_radius: float,
        max_parallel_z: int,
        max_parallel_xy: int,
        max_parallel_c: int,
        qubits: Iterable[GridQubit],
    ) -> None:
        """
        Initializes the description of the AQuA device.

        Args:
            measurement_duration: the maximum duration of a measurement.
            gate_duration: the maximum duration of a gate
            control_radius: the maximum distance between qubits for a controlled
                gate. Distance is measured in units of the indices passed into
                the GridQubit constructor.
            max_parallel_z: The maximum number of qubits that can be acted on
                in parallel by a Z gate
            max_parallel_xy: The maximum number of qubits that can be acted on
                in parallel by a local XY gate
            max_parallel_c: the maximum number of qubits that can be acted on in
                parallel by a controlled gate. Must be less than or equal to the
                lesser of max_parallel_z and max_parallel_xy
            qubits: Qubits on the device, identified by their x, y location.
                Must be of type GridQubit

        Raises:
            ValueError: if the wrong qubit type is provided or if invalid
                parallel parameters are provided
        """
        self._measurement_duration = Duration(measurement_duration)
        self._gate_duration = Duration(gate_duration)
        self._control_radius = control_radius
        self._max_parallel_z = max_parallel_z
        self._max_parallel_xy = max_parallel_xy
        if max_parallel_c > min(max_parallel_z, max_parallel_xy):
            raise ValueError(
                "max_parallel_c must be less than or equal to the"
                "min of max_parallel_z and max_parallel_xy"
            )
        self._max_parallel_c = max_parallel_c
        for q in qubits:
            if not isinstance(q, GridQubit):
                raise ValueError('Unsupported qubit type: {!r}'.format(q))
        self.qubits = frozenset(qubits)
コード例 #16
0
ファイル: serializable_device.py プロジェクト: sycramore/Cirq
    def from_proto(
        cls, proto: v2.device_pb2.DeviceSpecification,
        gate_set: serializable_gate_set.SerializableGateSet
    ) -> 'SerializableDevice':
        """

        Args:
            proto: A proto describing the qubits on the device, as well as the
                supported gates and timing information.
            gate_set: A SerializableGateSet that can translate the gate_ids
                into cirq Gates.
        """

        # Store target sets, since they are refered to by name later
        allowed_targets: Dict[str, Set[Tuple['cirq.Qid', ...]]] = {}
        permutation_ids: Set[str] = set()
        for ts in proto.valid_targets:
            allowed_targets[ts.name] = cls._create_target_set(ts)
            if ts.target_ordering == v2.device_pb2.TargetSet.SUBSET_PERMUTATION:
                permutation_ids.add(ts.name)

        # Store gate definitions from proto
        gate_definitions: Dict[str, _GateDefinition] = {}
        for gs in proto.valid_gate_sets:
            for gate_def in gs.valid_gates:
                # Combine all valid targets in the gate's listed target sets
                gate_target_set = set([
                    target for ts_name in gate_def.valid_targets
                    for target in allowed_targets[ts_name]
                ])
                which_are_permutations = [
                    t in permutation_ids for t in gate_def.valid_targets
                ]
                is_permutation = any(which_are_permutations)
                if is_permutation:
                    if not all(which_are_permutations):
                        msg = f'Id {gate_def.id} in {gate_set.gate_set_name} ' \
                            ' mixes SUBSET_PERMUTATION with other types which' \
                            ' is not currently allowed.'
                        raise NotImplementedError(msg)
                gate_definitions[gate_def.id] = _GateDefinition(
                    duration=Duration(picos=gate_def.gate_duration_picos),
                    target_set=gate_target_set,
                    is_permutation=is_permutation,
                    number_of_qubits=gate_def.number_of_qubits)

        # Loop through serializers and map gate_definitions to type
        gates_by_type: Dict[Type['cirq.Gate'], _GateDefinition] = {}
        for gate_type in gate_set.supported_gate_types():
            for serializer in gate_set.serializers[gate_type]:
                gate_id = serializer.serialized_gate_id
                if gate_id not in gate_definitions:
                    raise ValueError(f'Serializer has {gate_id} which is not '
                                     'supported by the device specification')
                gates_by_type[gate_type] = gate_definitions[gate_id]

        return SerializableDevice(
            qubits=SerializableDevice._qubits_from_ids(proto.valid_qubits),
            gate_definitions=gates_by_type,
        )
コード例 #17
0
def test_init_timedelta():
    r = ScheduledOperation(time=Timestamp(picos=5),
                           duration=timedelta(microseconds=7),
                           operation=cirq.H(cirq.NamedQubit('a')))
    assert r.time == Timestamp(picos=5)
    assert r.duration == Duration(picos=7 * 10**6)
    assert r.operation == cirq.H(cirq.NamedQubit('a'))
コード例 #18
0
def test_greedy_method_calls_greedy_search():
    q00 = XmonQubit(0, 0)
    q01 = XmonQubit(0, 1)
    q03 = XmonQubit(0, 3)
    device = XmonDevice(Duration(nanos=0),
                        Duration(nanos=0),
                        Duration(nanos=0),
                        qubits=[q00, q01, q03])
    method = greedy.GreedySequenceSearchMethod()

    with mock.patch.object(method, 'place_line') as place_line:
        sequences = [[q00, q01]]
        place_line.return_value = sequences

        assert place_on_device(device, method) == sequences
        place_line.assert_called_once_with(device)
コード例 #19
0
ファイル: schedule_test.py プロジェクト: yinxx/Cirq
def test_query_overlapping_operations_inclusive():
    q = ops.QubitId()
    zero = Timestamp(picos=0)
    ps = Duration(picos=1)
    op1 = ScheduledOperation(zero, 2 * ps, ops.H(q))
    op2 = ScheduledOperation(zero + ps, 2 * ps, ops.H(q))
    schedule = Schedule(device=UnconstrainedDevice,
                        scheduled_operations=[op2, op1])

    def query(t, d=Duration(), qubits=None):
        return schedule.query(time=t,
                              duration=d,
                              qubits=qubits,
                              include_query_end_time=True,
                              include_op_end_times=True)

    assert query(zero - 0.5 * ps, ps) == [op1]
    assert query(zero - 0.5 * ps, 2 * ps) == [op1, op2]
    assert query(zero, ps) == [op1, op2]
    assert query(zero + 0.5 * ps, ps) == [op1, op2]
    assert query(zero + ps, ps) == [op1, op2]
    assert query(zero + 1.5 * ps, ps) == [op1, op2]
    assert query(zero + 2.0 * ps, ps) == [op1, op2]
    assert query(zero + 2.5 * ps, ps) == [op2]
    assert query(zero + 3.0 * ps, ps) == [op2]
    assert query(zero + 3.5 * ps, ps) == []
コード例 #20
0
    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 by time and qubit.

        Args:
            time: Operations must end after this time to be returned.
            duration: Operations must start by time+duration to be
                returned.
            qubits: If specified, only operations touching one of the included
                qubits will be returned.
            include_query_end_time: Determines if the query interval includes
                its end time. Defaults to no.
            include_op_end_times: Determines if the scheduled operation
                intervals include their end times or not. Defaults to no.

        Returns:
            A list of scheduled operations meeting the specified conditions.
        """
        duration = Duration.create(duration)
        earliest_time = time - self._max_duration
        end_time = time + duration
        qubits = None if qubits is None else frozenset(qubits)

        def overlaps_interval(op):
            if not include_op_end_times and op.time + op.duration == time:
                return False
            if not include_query_end_time and op.time == end_time:
                return False
            return op.time + op.duration >= time and op.time <= end_time

        def overlaps_qubits(op):
            if qubits is None:
                return True
            return not qubits.isdisjoint(op.operation.qubits)

        potential_matches = self.scheduled_operations.irange_key(
            earliest_time, end_time)
        return [
            op for op in potential_matches
            if overlaps_interval(op) and overlaps_qubits(op)
        ]
コード例 #21
0
ファイル: duration_test.py プロジェクト: ybc1991/Cirq
def test_str():
    assert str(Duration(picos=-2)) == '-2 ps'
    assert str(Duration()) == 'Duration(0)'
    assert str(Duration(picos=2)) == '2 ps'
    assert str(Duration(nanos=2)) == '2 ns'
    assert str(Duration(micros=2)) == '2 us'
    assert str(Duration(millis=2)) == '2 ms'
    assert str(Duration(micros=1.5)) == '1500.0 ns'
    assert str(Duration(micros=1.5 * sympy.Symbol('t'))) == '(1500.0*t) ns'
コード例 #22
0
ファイル: duration_test.py プロジェクト: ybc1991/Cirq
def test_mul():
    assert Duration(picos=2) * 3 == Duration(picos=6)
    assert 4 * Duration(picos=3) == Duration(picos=12)

    t = sympy.Symbol('t')
    assert t * Duration(picos=3) == Duration(picos=3 * t)

    with pytest.raises(TypeError):
        _ = Duration() * Duration()
コード例 #23
0
ファイル: duration_test.py プロジェクト: ybc1991/Cirq
def test_total():
    assert Duration().total_nanos() == 0
    assert Duration(picos=3000).total_nanos() == 3
    assert Duration(nanos=5).total_nanos() == 5

    assert Duration().total_nanos() == 0
    assert Duration(picos=500).total_nanos() == 0.5
    assert Duration(nanos=500).total_micros() == 0.5
    assert Duration(micros=500).total_millis() == 0.5
    assert Duration(millis=500).total_millis() == 500
コード例 #24
0
ファイル: duration_test.py プロジェクト: ybc1991/Cirq
def test_init_timedelta():
    assert Duration(timedelta(microseconds=0)).total_picos() == 0
    assert Duration(timedelta(microseconds=513)).total_picos() == 513 * 10**6
    assert Duration(timedelta(microseconds=-5)).total_picos() == -5 * 10**6
    assert Duration(timedelta(microseconds=211)).total_picos() == 211 * 10**6

    assert Duration(timedelta(seconds=3)).total_picos() == 3 * 10**12
    assert Duration(timedelta(seconds=-5)).total_picos() == -5 * 10**12
    assert Duration(timedelta(seconds=3)).total_nanos() == 3 * 10**9
    assert Duration(timedelta(seconds=-5)).total_nanos() == -5 * 10**9
コード例 #25
0
def test_repr():
    cirq.testing.assert_equivalent_repr(Duration(millis=2))
    cirq.testing.assert_equivalent_repr(Duration(micros=2))
    cirq.testing.assert_equivalent_repr(Duration(picos=1000, nanos=1000))
    cirq.testing.assert_equivalent_repr(Duration(picos=5000))
    cirq.testing.assert_equivalent_repr(Duration(nanos=1.0))
    cirq.testing.assert_equivalent_repr(Duration(micros=sympy.Symbol('t')))
    cirq.testing.assert_equivalent_repr(Duration(micros=1.5 * sympy.Symbol('t')))
コード例 #26
0
ファイル: xmon_device_test.py プロジェクト: YZNIU/Cirq
def square_device(width, height, holes=()):
    ns = Duration(nanos=1)
    return XmonDevice(measurement_duration=ns,
                      exp_w_duration=2 * ns,
                      exp_11_duration=3 * ns,
                      qubits=[
                          XmonQubit(x, y) for x in range(width)
                          for y in range(height)
                          if XmonQubit(x, y) not in holes
                      ])
コード例 #27
0
ファイル: schedule_test.py プロジェクト: YZNIU/Cirq
 def simple_schedule(q, start_picos=0, duration_picos=1, num_ops=1):
     time_picos = start_picos
     scheduled_ops = []
     for _ in range(num_ops):
         op = ScheduledOperation(Timestamp(picos=time_picos),
                                 Duration(picos=duration_picos), ops.H(q))
         scheduled_ops.append(op)
         time_picos += duration_picos
     return Schedule(device=UnconstrainedDevice,
                     scheduled_operations=scheduled_ops)
コード例 #28
0
 def duration_of(self, operation):
     g = xmon_gate_ext.try_cast(operation.gate, xmon_gates.XmonGate)
     if isinstance(g, xmon_gates.Exp11Gate):
         return self._exp_z_duration
     if isinstance(g, xmon_gates.ExpWGate):
         return self._exp_w_duration
     if isinstance(g, xmon_gates.XmonMeasurementGate):
         return self._measurement_duration
     if isinstance(g, xmon_gates.ExpZGate):
         return Duration()  # Z gates are performed in the control software.
     raise ValueError('Unsupported gate type: {}'.format(repr(g)))
コード例 #29
0
    def __init__(self, time: Timestamp, duration: 'cirq.DURATION_LIKE',
                 operation: ops.Operation) -> None:
        """Initializes the scheduled operation.

        Args:
            time: When the operation starts.
            duration: How long the operation lasts.
            operation: The operation.
        """
        self.time = time
        self.duration = Duration(duration)
        self.operation = operation
コード例 #30
0
ファイル: scheduled_operation.py プロジェクト: YZNIU/Cirq-1
    def __init__(self, time: Timestamp, duration: Union[Duration, timedelta],
                 operation: ops.Operation) -> None:
        """Initializes the scheduled operation.

        Args:
            time: When the operation starts.
            duration: How long the operation lasts.
            operation: The operation.
        """
        self.time = time
        self.duration = Duration.create(duration)
        self.operation = operation