def test_simulate_sweep_parameters_not_resolved():
    a = cirq.LineQubit(0)
    simulator = cirq.DensityMatrixSimulator()
    circuit = cirq.Circuit(
        cirq.XPowGate(exponent=sympy.Symbol('a'))(a), cirq.measure(a))
    with pytest.raises(ValueError, match='symbols were not specified'):
        _ = simulator.simulate_sweep(circuit, cirq.ParamResolver({}))
def test_gateset_with_added_gates_again():
    """Verify that adding a serializer twice doesn't mess anything up."""
    q = cirq.GridQubit(2, 2)
    x_gateset = cg.SerializableGateSet(
        gate_set_name='x',
        serializers=[X_SERIALIZER],
        deserializers=[X_DESERIALIZER],
    )
    xx_gateset = x_gateset.with_added_gates(
        gate_set_name='xx',
        serializers=[X_SERIALIZER],
        deserializers=[X_DESERIALIZER],
    )

    assert xx_gateset.gate_set_name == 'xx'
    assert xx_gateset.is_supported_operation(cirq.X(q))
    assert not xx_gateset.is_supported_operation(cirq.Y(q))

    # test serialization and deserialization
    proto = op_proto(
        {
            'gate': {'id': 'x_pow'},
            'args': {
                'half_turns': {'arg_value': {'float_value': 0.125}},
            },
            'qubits': [{'id': '1_1'}],
        }
    )

    expected_gate = cirq.XPowGate(exponent=0.125)(cirq.GridQubit(1, 1))
    assert xx_gateset.serialize_op(expected_gate) == proto
    assert xx_gateset.deserialize_op(proto) == expected_gate
Exemple #3
0
def get_match_circuit() -> cirq.Circuit:
    qubits = [cirq.LineQubit(i) for i in range(9)]

    g = cirq.CZPowGate(exponent=0.1)
    zz = cirq.ZZPowGate(exponent=0.3)
    px = cirq.PhasedXPowGate(phase_exponent=0.6, exponent=0.2)
    circ = cirq.Circuit(
        [
            cirq.H(qubits[0]),
            cirq.X(qubits[1]),
            cirq.Y(qubits[2]),
            cirq.Z(qubits[3]),
            cirq.S(qubits[4]),
            cirq.CNOT(qubits[1], qubits[4]),
            cirq.T(qubits[3]),
            cirq.CNOT(qubits[6], qubits[8]),
            cirq.I(qubits[5]),
            cirq.XPowGate(exponent=0.1)(qubits[5]),
            cirq.YPowGate(exponent=0.1)(qubits[6]),
            cirq.ZPowGate(exponent=0.1)(qubits[7]),
            g(qubits[2], qubits[3]),
            zz(qubits[3], qubits[4]),
            px(qubits[6]),
            cirq.CZ(qubits[2], qubits[3]),
            cirq.ISWAP(qubits[4], qubits[5]),
            cirq.FSimGate(1.4, 0.7)(qubits[6], qubits[7]),
            cirq.google.SYC(qubits[3], qubits[0]),
            cirq.PhasedISwapPowGate(phase_exponent=0.7, exponent=0.8)(
                qubits[3], qubits[4]),
            cirq.GlobalPhaseOperation(1j),
            cirq.measure_each(*qubits[3:-2]),
        ],
        strategy=InsertStrategy.EARLIEST,
    )
    return circ
def test_xpow_dim_4():
    x = cirq.XPowGate(dimension=4)
    # fmt: off
    expected = [
        [0, 0, 0, 1],
        [1, 0, 0, 0],
        [0, 1, 0, 0],
        [0, 0, 1, 0],
    ]
    # fmt: on
    assert np.allclose(cirq.unitary(x), expected)

    sim = cirq.Simulator()
    circuit = cirq.Circuit([x(cirq.LineQid(0, 4))**0.5] * 8)
    svs = [
        step.state_vector(copy=True)
        for step in sim.simulate_moment_steps(circuit)
    ]
    # fmt: off
    expected = [
        [0.65, 0.65, 0.27, 0.27],
        [0.0, 1.0, 0.0, 0.0],
        [0.27, 0.65, 0.65, 0.27],
        [0.0, 0.0, 1.0, 0.0],
        [0.27, 0.27, 0.65, 0.65],
        [0.0, 0.0, 0.0, 1.0],
        [0.65, 0.27, 0.27, 0.65],
        [1.0, 0.0, 0.0, 0.0],
    ]
    # fmt: on
    assert np.allclose(np.abs(svs), expected, atol=1e-2)
Exemple #5
0
def test_arbitrary_xyz_repr():
    cirq.testing.assert_equivalent_repr(
        cirq.XPowGate(exponent=0.1, global_shift=0.2))
    cirq.testing.assert_equivalent_repr(
        cirq.YPowGate(exponent=0.1, global_shift=0.2))
    cirq.testing.assert_equivalent_repr(
        cirq.ZPowGate(exponent=0.1, global_shift=0.2))
Exemple #6
0
 def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
     assert len(qubits) == 1
     q = qubits[0]
     z = cirq.Z(q)**self._phase_exponent
     x = cirq.XPowGate(exponent=self._exponent,
                       global_shift=self.global_shift).on(q)
     return z**-1, x, z
Exemple #7
0
def test_str():
    assert str(cirq.X) == 'X'
    assert str(cirq.X**0.5) == 'X**0.5'
    assert str(cirq.rx(np.pi)) == 'Rx(π)'
    assert str(cirq.rx(0.5 * np.pi)) == 'Rx(0.5π)'
    assert str(cirq.XPowGate(
        global_shift=-0.25)) == 'XPowGate(exponent=1.0, global_shift=-0.25)'

    assert str(cirq.Z) == 'Z'
    assert str(cirq.Z**0.5) == 'S'
    assert str(cirq.Z**0.125) == 'Z**0.125'
    assert str(cirq.rz(np.pi)) == 'Rz(π)'
    assert str(cirq.rz(1.4 * np.pi)) == 'Rz(1.4π)'
    assert str(cirq.ZPowGate(
        global_shift=0.25)) == 'ZPowGate(exponent=1.0, global_shift=0.25)'

    assert str(cirq.S) == 'S'
    assert str(cirq.S**-1) == 'S**-1'
    assert str(cirq.T) == 'T'
    assert str(cirq.T**-1) == 'T**-1'

    assert str(cirq.Y) == 'Y'
    assert str(cirq.Y**0.5) == 'Y**0.5'
    assert str(cirq.ry(np.pi)) == 'Ry(π)'
    assert str(cirq.ry(3.14 * np.pi)) == 'Ry(3.14π)'
    assert str(cirq.YPowGate(
        exponent=2,
        global_shift=-0.25)) == 'YPowGate(exponent=2, global_shift=-0.25)'

    assert str(cirq.CX) == 'CNOT'
    assert str(cirq.CNOT**0.5) == 'CNOT**0.5'
    assert str(cirq.CZ) == 'CZ'
    assert str(cirq.CZ**0.5) == 'CZ**0.5'
    assert str(cirq.cphase(np.pi)) == 'CZ'
    assert str(cirq.cphase(np.pi / 2)) == 'CZ**0.5'
Exemple #8
0
def test_equivalent_unitaries():
    """This test covers the factor of pi change. However, it will be skipped
    if pyquil is unavailable for import.

    References:
        https://docs.pytest.org/en/latest/skipping.html#skipping-on-a-missing-import-dependency
    """
    pyquil = pytest.importorskip("pyquil")
    pyquil_simulation_tools = pytest.importorskip("pyquil.simulation.tools")
    q0, q1 = _make_qubits(2)
    operations = [
        cirq.XPowGate(exponent=0.5, global_shift=-0.5)(q0),
        cirq.YPowGate(exponent=0.5, global_shift=-0.5)(q0),
        cirq.ZPowGate(exponent=0.5, global_shift=-0.5)(q0),
        cirq.CZPowGate(exponent=0.5)(q0, q1),
        cirq.ISwapPowGate(exponent=0.5)(q0, q1),
    ]
    output = cirq.QuilOutput(operations, (q0, q1))
    program = pyquil.Program(str(output))
    pyquil_unitary = pyquil_simulation_tools.program_unitary(program,
                                                             n_qubits=2)
    # Qubit ordering differs between pyQuil and Cirq.
    cirq_unitary = cirq.Circuit(cirq.SWAP(q0, q1), operations,
                                cirq.SWAP(q0, q1)).unitary()
    assert np.allclose(pyquil_unitary, cirq_unitary)
def test_gate_operation_approx_eq():
    a = [cirq.NamedQubit('r1')]
    b = [cirq.NamedQubit('r2')]

    assert cirq.approx_eq(cirq.GateOperation(cirq.XPowGate(), a),
                          cirq.GateOperation(cirq.XPowGate(), a))
    assert not cirq.approx_eq(cirq.GateOperation(cirq.XPowGate(), a),
                              cirq.GateOperation(cirq.XPowGate(), b))

    assert cirq.approx_eq(cirq.GateOperation(cirq.XPowGate(exponent=0), a),
                          cirq.GateOperation(cirq.XPowGate(exponent=1e-9), a))
    assert not cirq.approx_eq(
        cirq.GateOperation(cirq.XPowGate(exponent=0), a),
        cirq.GateOperation(cirq.XPowGate(exponent=1e-7), a))
    assert cirq.approx_eq(cirq.GateOperation(cirq.XPowGate(exponent=0), a),
                          cirq.GateOperation(cirq.XPowGate(exponent=1e-7), a),
                          atol=1e-6)
Exemple #10
0
def test_simulate_sweep_parameters_not_resolved():
    a = cirq.LineQubit(0)
    circuit = cirq.Circuit(
        cirq.XPowGate(exponent=sympy.Symbol('a'))(a), cirq.measure(a))
    simulator = cirq.KnowledgeCompilationSimulator(circuit)
    with pytest.raises(AttributeError,
                       match="'Add' object has no attribute 'real'"):
        _ = simulator.simulate_sweep(circuit, cirq.ParamResolver({}))
Exemple #11
0
def test_decompose():
    q0 = cirq.LineQubit(0)
    op = cirq.H(q0).with_classical_controls('a')
    assert cirq.decompose(op) == [
        (cirq.Y(q0)**0.5).with_classical_controls('a'),
        cirq.XPowGate(exponent=1.0,
                      global_shift=-0.25).on(q0).with_classical_controls('a'),
    ]
Exemple #12
0
def test_parameterizable():
    s = sympy.Symbol('s')
    q0 = cirq.LineQubit(0)
    op = cirq.X(q0).with_classical_controls('a')
    opa = cirq.XPowGate(exponent=s).on(q0).with_classical_controls('a')
    assert cirq.is_parameterized(opa)
    assert not cirq.is_parameterized(op)
    assert cirq.resolve_parameters(opa, cirq.ParamResolver({'s': 1})) == op
Exemple #13
0
def test_is_supported_operation_can_serialize_predicate():
    q = cirq.GridQubit(1, 2)
    serializer = cg.GateOpSerializer(
        gate_type=cirq.XPowGate,
        serialized_gate_id='x_pow',
        args=[
            cg.SerializingArg(
                serialized_name='half_turns', serialized_type=float, op_getter='exponent'
            )
        ],
        can_serialize_predicate=lambda x: x.gate.exponent == 1.0,
    )
    gate_set = cg.SerializableGateSet(
        gate_set_name='my_gate_set', serializers=[serializer], deserializers=[X_DESERIALIZER]
    )
    assert gate_set.is_supported_operation(cirq.XPowGate()(q))
    assert not gate_set.is_supported_operation(cirq.XPowGate()(q) ** 0.5)
    assert gate_set.is_supported_operation(cirq.X(q))
def test_is_supported_gate_can_serialize_predicate():
    serializer = cg.GateOpSerializer(
        gate_type=cirq.XPowGate,
        serialized_gate_id='x_pow',
        args=[
            cg.SerializingArg(
                serialized_name='half_turns',
                serialized_type=float,
                gate_getter='exponent',
            )
        ],
        can_serialize_predicate=lambda x: x.exponent == 1.0)
    gate_set = cg.SerializableGateSet(gate_set_name='my_gate_set',
                                      serializers=[serializer],
                                      deserializers=[X_DESERIALIZER])
    assert gate_set.is_supported_gate(cirq.XPowGate())
    assert not gate_set.is_supported_gate(cirq.XPowGate()**0.5)
    assert gate_set.is_supported_gate(cirq.X)
Exemple #15
0
def test_sweep_unparameterized_prefix_not_repeated_iff_unitary():
    q = cirq.LineQubit(0)

    class TestOp(cirq.Operation):
        def __init__(self, *, has_unitary: bool):
            self.count = 0
            self.has_unitary = has_unitary

        def _act_on_(self, sim_state):
            self.count += 1
            return True

        def with_qubits(self, qubits):
            pass

        @property
        def qubits(self):
            return (q, )

        def _has_unitary_(self):
            return self.has_unitary

    simulator = CountingSimulator()
    params = [cirq.ParamResolver({'a': 0}), cirq.ParamResolver({'a': 1})]

    op1 = TestOp(has_unitary=True)
    op2 = TestOp(has_unitary=True)
    circuit = cirq.Circuit(op1,
                           cirq.XPowGate(exponent=sympy.Symbol('a'))(q), op2)
    rs = simulator.simulate_sweep(program=circuit, params=params)
    assert rs[0]._final_simulator_state.copy_count == 1
    assert rs[1]._final_simulator_state.copy_count == 0
    assert op1.count == 1
    assert op2.count == 2

    op1 = TestOp(has_unitary=False)
    op2 = TestOp(has_unitary=False)
    circuit = cirq.Circuit(op1,
                           cirq.XPowGate(exponent=sympy.Symbol('a'))(q), op2)
    rs = simulator.simulate_sweep(program=circuit, params=params)
    assert rs[0]._final_simulator_state.copy_count == 1
    assert rs[1]._final_simulator_state.copy_count == 0
    assert op1.count == 2
    assert op2.count == 2
Exemple #16
0
    def _mixer_unitary(self, alpha: float):
        """Operator mi.

        Args:
            alpha: Parameter.

        """
        for qubit_idx in range(self.num_qubits):
            qubit = self._qubits[qubit_idx]
            yield cirq.XPowGate(exponent=-1 * alpha / math.pi).on(qubit)
 def _decompose_(self, qubits):
     a, b = qubits
     yield cirq.X(a)**0.5
     yield cirq.CNOT(a, b)
     yield cirq.XPowGate(exponent=self.exponent / 2,
                         global_shift=self._global_shift - 0.5).on(a)
     yield cirq.YPowGate(exponent=self.exponent / 2,
                         global_shift=self._global_shift - 0.5).on(b)
     yield cirq.CNOT(a, b)
     yield cirq.X(a)**-0.5
Exemple #18
0
def test_serialize_deserialize_op():
    q0 = cirq.GridQubit(1, 1)
    proto = {
        'gate': {
            'id': 'x_pow'
        },
        'args': {
            'half_turns': {
                'arg_value': {
                    'float_value': 0.1
                }
            },
        },
        'qubits': [{
            'id': '1_1'
        }]
    }
    assert proto == MY_GATE_SET.serialize_op(cirq.XPowGate(exponent=0.1)(q0))
    assert MY_GATE_SET.deserialize_op(proto) == cirq.XPowGate(exponent=0.1)(q0)
Exemple #19
0
    def rot_x_layer(length, half_turns):
        """Yields X rotations by half_turns on a square grid of given length."""

        # Define the gate once and then re-use it for each Operation.
        rot = cirq.XPowGate(exponent=half_turns)

        # Create an X rotation Operation for each qubit in the grid.
        for i in range(length):
            for j in range(length):
                yield rot(cirq.GridQubit(i, j))
Exemple #20
0
    def _decompose_(self, qubits):
        q = qubits[0]

        if self._exponent == 1:
            yield cirq.Y(q)**0.5
            yield cirq.XPowGate(global_shift=-0.25).on(q)
            return

        yield YPowGate(exponent=0.25).on(q)
        yield XPowGate(exponent=self._exponent).on(q)
        yield YPowGate(exponent=-0.25).on(q)
Exemple #21
0
def test_serialize_deserialize_op():
    q0 = cirq.GridQubit(1, 1)
    proto = op_proto({
        'gate': {
            'id': 'x_pow'
        },
        'args': {
            'half_turns': {
                'arg_value': {
                    'float_value': 0.125
                }
            }
        },
        'qubits': [{
            'id': '1_1'
        }],
    })
    assert proto == _my_gate_set().serialize_op(
        cirq.XPowGate(exponent=0.125)(q0))
    assert _my_gate_set().deserialize_op(proto) == cirq.XPowGate(
        exponent=0.125)(q0)
 def test_serialize_deserialize_op(self):
     """Simple serialize and deserialize back test."""
     q0 = cirq.GridQubit(1, 1)
     proto = op_proto({
         'gate': {
             'id': 'x_pow'
         },
         'args': {
             'half_turns': {
                 'arg_value': {
                     'float_value': 0.125
                 }
             },
         },
         'qubits': [{
             'id': '1_1'
         }]
     })
     self.assertEqual(
         proto, MY_GATE_SET.serialize_op(cirq.XPowGate(exponent=0.125)(q0)))
     self.assertEqual(MY_GATE_SET.deserialize_op(proto),
                      cirq.XPowGate(exponent=0.125)(q0))
Exemple #23
0
    def create_circuit(self, train_Data):

        circuit_List = []
        for x in train_Data:
            qubits = cirq.GridQubit.rect(1, 2)
            circuit = cirq.Circuit()
            for i, val in enumerate(x):
                if i == 0:
                    circuit.append(cirq.XPowGate(exponent=val)(qubits[i]))
                if i == 1:
                    circuit.append(cirq.YPowGate(exponent=val)(qubits[i]))
            circuit_List.append(circuit)
        return circuit_List
Exemple #24
0
def test_serialize_deserialize_op_with_token():
    q0 = cirq.GridQubit(1, 1)
    proto = op_proto(
        {
            'gate': {'id': 'x_pow'},
            'args': {'half_turns': {'arg_value': {'float_value': 0.125}}},
            'qubits': [{'id': '1_1'}],
            'token_value': 'abc123',
        }
    )
    op = cirq.XPowGate(exponent=0.125)(q0).with_tags(cg.CalibrationTag('abc123'))
    assert proto == MY_GATE_SET.serialize_op(op)
    assert MY_GATE_SET.deserialize_op(proto) == op
 def test_is_supported_operation_can_serialize_predicate(self):
     """Test can_serialize predicate for operations."""
     q = cirq.GridQubit(1, 2)
     serializer = op_serializer.GateOpSerializer(
         gate_type=cirq.XPowGate,
         serialized_gate_id='x_pow',
         args=[
             op_serializer.SerializingArg(
                 serialized_name='half_turns',
                 serialized_type=float,
                 op_getter='exponent',
             )
         ],
         can_serialize_predicate=lambda x: x.gate.exponent == 1.0)
     gate_set = serializable_gate_set.SerializableGateSet(
         gate_set_name='my_gate_set',
         serializers=[serializer],
         deserializers=[X_DESERIALIZER])
     self.assertTrue(gate_set.is_supported_operation(cirq.XPowGate()(q)))
     self.assertFalse(
         gate_set.is_supported_operation(cirq.XPowGate()(q)**0.5))
     self.assertTrue(gate_set.is_supported_operation(cirq.X(q)))
Exemple #26
0
def test_multiple_fsim_gatesets():
    """This tests that gate sets with two different definitions for the same
    gate perform correctly.  In this case, we set the XPowGate to be
    half the duration of the full exponent and make sure it still works.
    """
    half_pi_gs = cirq_google.SerializableGateSet(
        gate_set_name='half_pi',
        serializers=[*cgc.SINGLE_QUBIT_HALF_PI_SERIALIZERS],
        deserializers=[*cgc.SINGLE_QUBIT_HALF_PI_DESERIALIZERS],
    )
    durations_dict = {'xy_pi': 20_000, 'xy_half_pi': 10_000}
    spec = cirq_google.devices.known_devices.create_device_proto_from_diagram(
        "aa\naa", [half_pi_gs], durations_dict)

    # The gate set defines two different serializations for PhasedXPowGate
    device = cg.SerializableDevice.from_proto(proto=spec,
                                              gate_sets=[half_pi_gs])
    q = cirq.GridQubit(0, 0)
    pi = cirq.XPowGate(exponent=1.0)
    half_pi = cirq.XPowGate(exponent=0.5)
    assert device.duration_of(pi(q)) == cirq.Duration(picos=20_000)
    assert device.duration_of(half_pi(q)) == cirq.Duration(picos=10_000)
Exemple #27
0
def test_validate_well_structured_bad_gate():
    q0, q1 = cirq.LineQubit.range(2)
    circuit = cirq.Circuit([
        cirq.Moment([cirq.PhasedXPowGate(phase_exponent=0).on(q0)]),
        cirq.Moment([
            cirq.XPowGate(exponent=0.5).on(q0), ]),
        cirq.Moment([cg.SYC(q0, q1)]),
        cirq.measure(q0, q1, key='z'),
    ])

    with pytest.raises(BadlyStructuredCircuitError) as e:
        validate_well_structured(circuit)
    assert e.match('non-device')
def test_equivalent_circuit():
    qreg = cirq.LineQubit.range(4)
    oldc = cirq.Circuit()
    newc = cirq.Circuit()
    gates = [cirq.XPowGate() ** (1 / 2), cirq.YPowGate() ** (1 / 3), cirq.ZPowGate() ** -1]

    for gate in gates:
        for qubit in qreg:
            oldc.append(gate.on(qubit))
        newc.append(cirq.ops.ParallelGateOperation(gate, qreg))

    cirq.testing.assert_has_diagram(newc, oldc.to_text_diagram())
    cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent(oldc, newc, atol=1e-6)
Exemple #29
0
 def tr2_step(self, dt: float) -> cirq.Circuit:
     '''
     Second-order Trotter step for Hamiltonian simulation.
     '''
     c = cirq.Circuit()
     c.append(
         cirq.XPowGate(exponent=(dt * -self.B / np.pi))(self.qubits[i])
         for i in range(self.L))
     c.append(
         cirq.ZZPowGate(
             exponent=(dt * -self.J * 2 /
                       np.pi))(self.qubits[2 * i], self.qubits[2 * i + 1])
         for i in range(self.L // 2))
     c.append(
         cirq.ZZPowGate(
             exponent=(dt * -self.J * 2 /
                       np.pi))(self.qubits[2 * i + 1], self.qubits[2 * i +
                                                                   2])
         for i in range((self.L - 1) // 2))
     c.append(
         cirq.XPowGate(exponent=(dt * -self.B / np.pi))(self.qubits[i])
         for i in range(self.L))
     return (c)
Exemple #30
0
def test_runtime_types_of_rot_gates():
    for gate_type in [lambda p: cirq.CZPowGate(exponent=p),
                      lambda p: cirq.XPowGate(exponent=p),
                      lambda p: cirq.YPowGate(exponent=p),
                      lambda p: cirq.ZPowGate(exponent=p)]:
        p = gate_type(sympy.Symbol('a'))
        assert cirq.unitary(p, None) is None
        assert cirq.pow(p, 2, None) == gate_type(2 * sympy.Symbol('a'))
        assert cirq.inverse(p, None) == gate_type(-sympy.Symbol('a'))

        c = gate_type(0.5)
        assert cirq.unitary(c, None) is not None
        assert cirq.pow(c, 2) == gate_type(1)
        assert cirq.inverse(c) == gate_type(-0.5)