예제 #1
0
def test_eq():
    eq = cirq.testing.EqualsTester()
    eq.make_equality_group(lambda: cirq.PhasedXZGate(
        x_exponent=0.25, z_exponent=0.5, axis_phase_exponent=0.75))

    # Sensitive to each parameter.
    eq.add_equality_group(
        cirq.PhasedXZGate(x_exponent=0,
                          z_exponent=0.5,
                          axis_phase_exponent=0.75))
    eq.add_equality_group(
        cirq.PhasedXZGate(x_exponent=0.25,
                          z_exponent=0,
                          axis_phase_exponent=0.75))
    eq.add_equality_group(
        cirq.PhasedXZGate(x_exponent=0.25,
                          z_exponent=0.5,
                          axis_phase_exponent=0))

    # Different from other gates.
    eq.add_equality_group(
        cirq.PhasedXPowGate(exponent=0.25, phase_exponent=0.75))
    eq.add_equality_group(cirq.X)
    eq.add_equality_group(
        cirq.PhasedXZGate(x_exponent=1, z_exponent=0, axis_phase_exponent=0))
예제 #2
0
def matrix_to_sycamore_operations(
        target_qubits: List[cirq.GridQubit],
        matrix: np.ndarray) -> Tuple[cirq.OP_TREE, List[cirq.GridQubit]]:
    """A method to convert a unitary matrix to a list of Sycamore operations.

    This method will return a list of `cirq.Operation`s using the qubits and (optionally) ancilla
    qubits to implement the unitary matrix `matrix` on the target qubits `qubits`.
    The operations are also supported by `cirq.google.gate_sets.SYC_GATESET`.

    Args:
        target_qubits: list of qubits the returned operations will act on. The qubit order defined by the list
            is assumed to be used by the operations to implement `matrix`.
        matrix: a matrix that is guaranteed to be unitary and of size (2**len(qs), 2**len(qs)).
    Returns:
        A tuple of operations and ancilla qubits allocated.
            Operations: In case the matrix is supported, a list of operations `ops` is returned.
                `ops` acts on `qs` qubits and for which `cirq.unitary(ops)` is equal to `matrix` up
                 to certain tolerance. In case the matrix is not supported, it might return NotImplemented to
                 reduce the noise in the judge output.
            Ancilla qubits: In case ancilla qubits are allocated a list of ancilla qubits. Otherwise
                an empty list.
        .
    """
    return [
        cirq.PhasedXZGate(x_exponent=0, z_exponent=0,
                          axis_phase_exponent=0)(target_qubits[0]),
        cirq.PhasedXZGate(x_exponent=0, z_exponent=0,
                          axis_phase_exponent=0)(target_qubits[0])
    ], []
예제 #3
0
def test_protocols():
    a = random.random()
    b = random.random()
    c = random.random()
    g = cirq.PhasedXZGate(x_exponent=a, z_exponent=b, axis_phase_exponent=c)
    cirq.testing.assert_implements_consistent_protocols(g)

    # Symbolic.
    t = sympy.Symbol('t')
    g = cirq.PhasedXZGate(x_exponent=t, z_exponent=b, axis_phase_exponent=c)
    cirq.testing.assert_implements_consistent_protocols(g)
    g = cirq.PhasedXZGate(x_exponent=a, z_exponent=t, axis_phase_exponent=c)
    cirq.testing.assert_implements_consistent_protocols(g)
    g = cirq.PhasedXZGate(x_exponent=a, z_exponent=b, axis_phase_exponent=t)
    cirq.testing.assert_implements_consistent_protocols(g)
예제 #4
0
def test_single_phased_xz_stays():
    gate = cirq.PhasedXZGate(axis_phase_exponent=0.2,
                             x_exponent=0.3,
                             z_exponent=0.4)
    q = cirq.NamedQubit('q')
    assert_optimizes(before=cirq.Circuit(gate(q)),
                     expected=cirq.Circuit(gate(q)))
예제 #5
0
def test_cirq_to_circuit_0_7() -> None:
    q0 = cq.LineQubit(0)
    q1 = cq.LineQubit(1)
    gate = cirq_to_circuit(cq.Circuit(cq.rx(0.5).on(q0)))[0]
    assert isinstance(gate, qf.XPow)
    assert gate.param("t") == 0.5 / pi

    gate = cirq_to_circuit(cq.Circuit(cq.ry(0.5).on(q0)))[0]
    assert isinstance(gate, qf.YPow)
    assert gate.param("t") == 0.5 / pi

    gate = cirq_to_circuit(cq.Circuit(cq.rz(0.5).on(q0)))[0]
    assert isinstance(gate, qf.ZPow)
    assert gate.param("t") == 0.5 / pi

    # gate = cirq_to_circuit(cq.Circuit(cq.IdentityGate(2).on(q0, q1)))[0]

    op = (cq.PhasedISwapPowGate()**0.5).on(q0, q1)
    circ = cirq_to_circuit(cq.Circuit(op))
    assert qf.gates_close(circ.asgate(), qf.Givens(0.5 * pi / 2, 0, 1))

    op = cq.PhasedXZGate(x_exponent=0.125,
                         z_exponent=0.25,
                         axis_phase_exponent=0.375).on(q0)
    circ = cirq_to_circuit(cq.Circuit(op))
    assert len(circ) == 3
예제 #6
0
def test_serialize_deserialize_arbitrary_xyz(x_exponent, z_exponent,
                                             axis_phase_exponent):
    gate = cirq.PhasedXZGate(x_exponent=x_exponent,
                             z_exponent=z_exponent,
                             axis_phase_exponent=axis_phase_exponent)
    op = gate.on(cirq.GridQubit(1, 2))
    expected = op_proto({
        'gate': {
            'id': 'xyz'
        },
        'args': {
            'x_exponent': {
                'arg_value': {
                    'float_value': x_exponent
                }
            },
            'z_exponent': {
                'arg_value': {
                    'float_value': z_exponent
                }
            },
            'axis_phase_exponent': {
                'arg_value': {
                    'float_value': axis_phase_exponent
                }
            },
        },
        'qubits': [{
            'id': '1_2'
        }],
    })
    assert _single_qubit_gate_set().serialize_op(op) == expected
    deserialized_op = _single_qubit_gate_set().deserialize_op(expected)
    cirq.testing.assert_allclose_up_to_global_phase(
        cirq.unitary(deserialized_op), cirq.unitary(op), atol=1e-7)
예제 #7
0
def test_init_properties():
    g = cirq.PhasedXZGate(x_exponent=0.125,
                          z_exponent=0.25,
                          axis_phase_exponent=0.375)
    assert g.x_exponent == 0.125
    assert g.z_exponent == 0.25
    assert g.axis_phase_exponent == 0.375
예제 #8
0
def test_noisy_moment_one_qubit():
    q0, q1 = cirq.LineQubit.range(2)
    model = ThermalNoiseModel(
        qubits={q0, q1},
        gate_durations_ns={cirq.PhasedXZGate: 25.0, cirq.CZPowGate: 25.0},
        heat_rate_GHz={q0: 1e-5, q1: 2e-5},
        cool_rate_GHz={q0: 1e-4, q1: 2e-4},
        dephase_rate_GHz={q0: 3e-4, q1: 4e-4},
        require_physical_tag=False,
    )
    gate = cirq.PhasedXZGate(x_exponent=1, z_exponent=0.5, axis_phase_exponent=0.25)
    moment = cirq.Moment(gate.on(q0))
    noisy_moment = model.noisy_moment(moment, system_qubits=[q0, q1])
    assert noisy_moment[0] == moment
    # Noise applies to both qubits, even if only one is acted upon.
    assert len(noisy_moment[1]) == 2
    noisy_choi = cirq.kraus_to_choi(cirq.kraus(noisy_moment[1].operations[0]))
    assert np.allclose(
        noisy_choi,
        [
            [9.99750343e-01, 0, 0, 9.91164267e-01],
            [0, 2.49656565e-03, 0, 0],
            [0, 0, 2.49656565e-04, 0],
            [9.91164267e-01, 0, 0, 9.97503434e-01],
        ],
    )
def test_circuit_operation_inspection():
    q0, q1 = cirq.LineQubit.range(2)
    gate = cirq.PhasedXZGate(axis_phase_exponent=0.2, x_exponent=0.3, z_exponent=0.4)
    cop = cirq.CircuitOperation(cirq.FrozenCircuit(gate(q0)))
    assert cgoc.ConvertToSycamoreGates()._is_native_sycamore_op(cop)

    cop2 = cirq.CircuitOperation(cirq.FrozenCircuit(cirq.SWAP(q0, q1)))
    assert not cgoc.ConvertToSycamoreGates()._is_native_sycamore_op(cop2)
예제 #10
0
def test_parameterized():
    a = random.random()
    b = random.random()
    c = random.random()
    g = cirq.PhasedXZGate(x_exponent=a, z_exponent=b, axis_phase_exponent=c)
    assert not cirq.is_parameterized(g)

    t = sympy.Symbol('t')
    gt = cirq.PhasedXZGate(x_exponent=t, z_exponent=b, axis_phase_exponent=c)
    assert cirq.is_parameterized(gt)
    assert cirq.resolve_parameters(gt, {'t': a}) == g
    gt = cirq.PhasedXZGate(x_exponent=a, z_exponent=t, axis_phase_exponent=c)
    assert cirq.is_parameterized(gt)
    assert cirq.resolve_parameters(gt, {'t': b}) == g
    gt = cirq.PhasedXZGate(x_exponent=a, z_exponent=b, axis_phase_exponent=t)
    assert cirq.is_parameterized(gt)
    assert cirq.resolve_parameters(gt, {'t': c}) == g
예제 #11
0
def test_parameterized(resolve_fn):
    a = random.random()
    b = random.random()
    c = random.random()
    g = cirq.PhasedXZGate(x_exponent=a, z_exponent=b, axis_phase_exponent=c)
    assert not cirq.is_parameterized(g)

    t = sympy.Symbol('t')
    gt = cirq.PhasedXZGate(x_exponent=t, z_exponent=b, axis_phase_exponent=c)
    assert cirq.is_parameterized(gt)
    assert resolve_fn(gt, {'t': a}) == g
    gt = cirq.PhasedXZGate(x_exponent=a, z_exponent=t, axis_phase_exponent=c)
    assert cirq.is_parameterized(gt)
    assert resolve_fn(gt, {'t': b}) == g
    gt = cirq.PhasedXZGate(x_exponent=a, z_exponent=b, axis_phase_exponent=t)
    assert cirq.is_parameterized(gt)
    assert resolve_fn(gt, {'t': c}) == g

    resolver = {'t': 0.5j}
    with pytest.raises(ValueError, match='Complex exponent'):
        resolve_fn(
            cirq.PhasedXZGate(x_exponent=t,
                              z_exponent=b,
                              axis_phase_exponent=c), resolver)
    with pytest.raises(ValueError, match='Complex exponent'):
        resolve_fn(
            cirq.PhasedXZGate(x_exponent=a,
                              z_exponent=t,
                              axis_phase_exponent=c), resolver)
    with pytest.raises(ValueError, match='Complex exponent'):
        resolve_fn(
            cirq.PhasedXZGate(x_exponent=a,
                              z_exponent=b,
                              axis_phase_exponent=t), resolver)
예제 #12
0
    def test_gate_approx_eq_error(self):
        """Confirms that bad inputs cause an error to be raised."""
        # junk
        with self.assertRaisesRegex(TypeError,
                                    expected_regex="`gate_true` not a cirq"):
            _ = util.gate_approx_eq("junk", cirq.I)
        with self.assertRaisesRegex(TypeError,
                                    expected_regex="`gate_deser` not a cirq"):
            _ = util.gate_approx_eq(cirq.I, "junk")

        # Unsupported gates
        with self.assertRaisesRegex(
                ValueError, expected_regex="`gate_true` not a valid TFQ gate"):
            _ = util.gate_approx_eq(
                cirq.PhasedXZGate(x_exponent=1,
                                  z_exponent=1,
                                  axis_phase_exponent=1), cirq.I)
        with self.assertRaisesRegex(
                ValueError,
                expected_regex="`gate_deser` not a valid TFQ gate"):
            _ = util.gate_approx_eq(
                cirq.I,
                cirq.PhasedXZGate(x_exponent=1,
                                  z_exponent=1,
                                  axis_phase_exponent=1))
        # Unsupported gates inside a controlled gate
        with self.assertRaisesRegex(
                ValueError, expected_regex="`gate_true` not a valid TFQ gate"):
            _ = util.gate_approx_eq(
                cirq.ops.ControlledGate(
                    cirq.PhasedXZGate(x_exponent=1,
                                      z_exponent=1,
                                      axis_phase_exponent=1), 2,
                    [1, 0], [2, 2]),
                cirq.ops.ControlledGate(cirq.X, 2, [1, 0], [2, 2]))
        with self.assertRaisesRegex(
                ValueError,
                expected_regex="`gate_deser` not a valid TFQ gate"):
            _ = util.gate_approx_eq(
                cirq.ops.ControlledGate(cirq.X, 2, [1, 0], [2, 2]),
                cirq.ops.ControlledGate(
                    cirq.PhasedXZGate(x_exponent=1,
                                      z_exponent=1,
                                      axis_phase_exponent=1), 2, [1, 0],
                    [2, 2]))
def test_single_qubit_gate_phased_xz():
    q = cirq.LineQubit(0)
    gate = cirq.PhasedXZGate(axis_phase_exponent=0.2, x_exponent=0.3, z_exponent=0.4)
    circuit = cirq.Circuit(gate(q))
    converted_circuit = circuit.copy()
    cgoc.ConvertToSycamoreGates().optimize_circuit(converted_circuit)
    ops = list(converted_circuit.all_operations())
    assert len(ops) == 1
    assert ops[0].gate == gate
def test_single_qubit_gate_phased_xz():
    q = cirq.LineQubit(0)
    gate = cirq.PhasedXZGate(axis_phase_exponent=0.2, x_exponent=0.3, z_exponent=0.4)
    circuit = cirq.Circuit(gate(q))
    converted_circuit = circuit.copy()
    with cirq.testing.assert_deprecated("Use cirq.optimize_for_target_gateset", deadline='v1.0'):
        cgoc.ConvertToSycamoreGates().optimize_circuit(converted_circuit)
    ops = list(converted_circuit.all_operations())
    assert len(ops) == 1
    assert ops[0].gate == gate
예제 #15
0
def test_single_qubit_gate_phased_xz():
    q = cirq.LineQubit(0)
    gate = cirq.PhasedXZGate(axis_phase_exponent=0.2, x_exponent=0.3, z_exponent=0.4)
    circuit = cirq.Circuit(gate(q))
    compiled_circuit = cirq.optimize_for_target_gateset(
        circuit, gateset=cirq_google.SycamoreTargetGateset()
    )
    ops = list(compiled_circuit.all_operations())
    assert len(ops) == 1
    assert ops[0].gate == gate
예제 #16
0
def test_inverse():
    a = random.random()
    b = random.random()
    c = random.random()
    q = cirq.LineQubit(0)
    g = cirq.PhasedXZGate(x_exponent=a, z_exponent=b, axis_phase_exponent=c).on(q)

    cirq.testing.assert_allclose_up_to_global_phase(
        cirq.unitary(g ** -1), np.transpose(np.conjugate(cirq.unitary(g))), atol=1e-8
    )
def test_circuit_operation_inspection():
    q0, q1 = cirq.LineQubit.range(2)
    gate = cirq.PhasedXZGate(axis_phase_exponent=0.2, x_exponent=0.3, z_exponent=0.4)
    cop = cirq.CircuitOperation(cirq.FrozenCircuit(gate(q0)))
    with cirq.testing.assert_deprecated("Use cirq.optimize_for_target_gateset", deadline='v1.0'):
        assert cgoc.ConvertToSycamoreGates()._is_native_sycamore_op(cop)

    cop2 = cirq.CircuitOperation(cirq.FrozenCircuit(cirq.SWAP(q0, q1)))
    with cirq.testing.assert_deprecated("Use cirq.optimize_for_target_gateset", deadline='v1.0'):
        assert not cgoc.ConvertToSycamoreGates()._is_native_sycamore_op(cop2)
예제 #18
0
def test_str_diagram():
    g = cirq.PhasedXZGate(x_exponent=0.5, z_exponent=0.25, axis_phase_exponent=0.125)

    assert str(g) == "PhXZ(a=0.125,x=0.5,z=0.25)"

    cirq.testing.assert_has_diagram(
        cirq.Circuit(g.on(cirq.LineQubit(0))),
        """
0: ───PhXZ(a=0.125,x=0.5,z=0.25)───
    """,
    )
def test_two_qubit_compilation_merges_runs_of_single_qubit_gates():
    q = cirq.LineQubit.range(2)
    c = cirq.Circuit(cirq.CNOT(*q), cirq.X(q[0]), cirq.Y(q[0]), cirq.CNOT(*q))
    cirq.testing.assert_same_circuits(
        cirq.optimize_for_target_gateset(c, gateset=DummyCXTargetGateset()),
        cirq.Circuit(
            cirq.CNOT(*q),
            cirq.PhasedXZGate(axis_phase_exponent=-0.5, x_exponent=0, z_exponent=-1).on(q[0]),
            cirq.CNOT(*q),
        ),
    )
예제 #20
0
def test_eject_phased_xz():
    a = cirq.NamedQubit('a')
    b = cirq.NamedQubit('b')
    c = cirq.Circuit(
        cirq.PhasedXZGate(x_exponent=1, z_exponent=0.5, axis_phase_exponent=0.5).on(a),
        cirq.CZ(a, b) ** 0.25,
    )
    c_expected = cirq.Circuit(
        cirq.CZ(a, b) ** -0.25, cirq.PhasedXPowGate(phase_exponent=0.75).on(a), cirq.T(b)
    )
    cirq.testing.assert_same_circuits(
        cirq.eject_z(cirq.eject_phased_paulis(cirq.eject_z(c))), c_expected
    )
    cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent(c, c_expected, 1e-8)
예제 #21
0
def test_serialize_deserialize_arbitrary_xyz(
    x_exponent,
    z_exponent,
    axis_phase_exponent,
):
    gateset = cg.serializable_gate_set.SerializableGateSet(
        gate_set_name='test_xyz',
        serializers=([cgc.PHASED_X_Z_SERIALIZER]),
        deserializers=([cgc.PHASED_X_Z_DESERIALIZER]))
    gate = cirq.PhasedXZGate(
        x_exponent=x_exponent,
        z_exponent=z_exponent,
        axis_phase_exponent=axis_phase_exponent,
    )
    op = gate.on(cirq.GridQubit(1, 2))
    expected = {
        'gate': {
            'id': 'xyz'
        },
        'args': {
            'x_exponent': {
                'arg_value': {
                    'float_value': x_exponent
                }
            },
            'z_exponent': {
                'arg_value': {
                    'float_value': z_exponent
                }
            },
            'axis_phase_exponent': {
                'arg_value': {
                    'float_value': axis_phase_exponent
                }
            }
        },
        'qubits': [{
            'id': '1_2'
        }]
    }
    assert gateset.serialize_op_dict(op) == expected
    deserialized_op = gateset.deserialize_op_dict(expected)
    cirq.testing.assert_allclose_up_to_global_phase(
        cirq.unitary(deserialized_op),
        cirq.unitary(op),
        atol=1e-7,
    )
예제 #22
0
def test_serialize_deserialize_arbitrary_xyz(
        x_exponent,
        z_exponent,
        axis_phase_exponent,
):
    gate = cirq.PhasedXZGate(
        x_exponent=x_exponent,
        z_exponent=z_exponent,
        axis_phase_exponent=axis_phase_exponent,
    )
    op = gate.on(cirq.GridQubit(1, 2))
    expected = {
        'gate': {
            'id': 'xyz'
        },
        'args': {
            'x_exponent': {
                'arg_value': {
                    'float_value': x_exponent
                }
            },
            'z_exponent': {
                'arg_value': {
                    'float_value': z_exponent
                }
            },
            'axis_phase_exponent': {
                'arg_value': {
                    'float_value': axis_phase_exponent
                }
            }
        },
        'qubits': [{
            'id': '1_2'
        }]
    }
    assert SINGLE_QUBIT_GATE_SET.serialize_op_dict(op) == expected
    deserialized_op = SINGLE_QUBIT_GATE_SET.deserialize_op_dict(expected)
    cirq.testing.assert_allclose_up_to_global_phase(
        cirq.unitary(deserialized_op),
        cirq.unitary(op),
        atol=1e-7,
    )
예제 #23
0
def test_removes_zs():
    a = cirq.NamedQubit('a')
    b = cirq.NamedQubit('b')

    assert_removes_all_z_gates(cirq.Circuit(cirq.Z(a), cirq.measure(a)))

    assert_removes_all_z_gates(cirq.Circuit(cirq.Z(a), cirq.measure(a, b)))

    assert_removes_all_z_gates(
        cirq.Circuit(cirq.Z(a), cirq.Z(a), cirq.measure(a)))

    assert_removes_all_z_gates(
        cirq.Circuit(cirq.Z(a), cirq.measure(a, key='k')))

    assert_removes_all_z_gates(
        cirq.Circuit(cirq.Z(a), cirq.X(a), cirq.measure(a)))

    assert_removes_all_z_gates(
        cirq.Circuit(cirq.Z(a), cirq.X(a), cirq.X(a), cirq.measure(a)))

    assert_removes_all_z_gates(
        cirq.Circuit(cirq.Z(a), cirq.Z(b), cirq.CZ(a, b), cirq.CZ(a, b),
                     cirq.measure(a, b)))

    assert_removes_all_z_gates(
        cirq.Circuit(
            cirq.PhasedXZGate(axis_phase_exponent=0,
                              x_exponent=0,
                              z_exponent=1).on(a),
            cirq.measure(a),
        ))

    assert_removes_all_z_gates(
        cirq.Circuit(
            cirq.Z(a)**sympy.Symbol('a'),
            cirq.Z(b)**(sympy.Symbol('a') + 1),
            cirq.CZ(a, b),
            cirq.CZ(a, b),
            cirq.measure(a, b),
        ),
        eject_parameterized=True,
    )
예제 #24
0
def _sq_layer(qubits: List[cirq.Qid], parameterized: bool,
              symbol_start: int) -> (cirq.Moment, int):
    """Creates a layer of single-qubit gates.

        If parameteried is true, this will add symbols to the qubits
        in order to test parameter resolution.
        """
    m = cirq.Moment()
    current_sym = symbol_start
    for q in qubits:
        if parameterized:
            symbol = f's_{current_sym}'
            current_sym += 1
            m = m.with_operation(cirq.X(q)**sympy.Symbol(symbol))
        else:
            m = m.with_operation(
                cirq.PhasedXZGate(x_exponent=random.random(),
                                  z_exponent=random.random(),
                                  axis_phase_exponent=random.random())(q))
    return (m, current_sym)
예제 #25
0
    def _deserialize_gate_op(
        self,
        operation_proto: v2.program_pb2.Operation,
        *,
        arg_function_language: str = '',
        constants: Optional[List[v2.program_pb2.Constant]] = None,
        deserialized_constants: Optional[List[Any]] = None,
    ) -> cirq.Operation:
        """Deserialize an Operation from a cirq_google.api.v2.Operation.

        Args:
            operation_proto: A dictionary representing a
                cirq.google.api.v2.Operation proto.
            arg_function_language: The `arg_function_language` field from
                `Program.Language`.
            constants: The list of Constant protos referenced by constant
                table indices in `proto`.
            deserialized_constants: The deserialized contents of `constants`.
                cirq_google.api.v2.Operation proto.

        Returns:
            The deserialized Operation.
        """
        if deserialized_constants is not None:
            qubits = [
                deserialized_constants[q]
                for q in operation_proto.qubit_constant_index
            ]
        else:
            qubits = []
        for q in operation_proto.qubits:
            # Preserve previous functionality in case
            # constants table was not used
            qubits.append(v2.qubit_from_proto_id(q.id))

        which_gate_type = operation_proto.WhichOneof('gate_value')

        if which_gate_type == 'xpowgate':
            op = cirq.XPowGate(exponent=arg_func_langs.float_arg_from_proto(
                operation_proto.xpowgate.exponent,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            ))(*qubits)
        elif which_gate_type == 'ypowgate':
            op = cirq.YPowGate(exponent=arg_func_langs.float_arg_from_proto(
                operation_proto.ypowgate.exponent,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            ))(*qubits)
        elif which_gate_type == 'zpowgate':
            op = cirq.ZPowGate(exponent=arg_func_langs.float_arg_from_proto(
                operation_proto.zpowgate.exponent,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            ))(*qubits)
            if operation_proto.zpowgate.is_physical_z:
                op = op.with_tags(PhysicalZTag())
        elif which_gate_type == 'phasedxpowgate':
            exponent = arg_func_langs.float_arg_from_proto(
                operation_proto.phasedxpowgate.exponent,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            )
            phase_exponent = arg_func_langs.float_arg_from_proto(
                operation_proto.phasedxpowgate.phase_exponent,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            )
            op = cirq.PhasedXPowGate(exponent=exponent,
                                     phase_exponent=phase_exponent)(*qubits)
        elif which_gate_type == 'phasedxzgate':
            x_exponent = arg_func_langs.float_arg_from_proto(
                operation_proto.phasedxzgate.x_exponent,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            )
            z_exponent = arg_func_langs.float_arg_from_proto(
                operation_proto.phasedxzgate.z_exponent,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            )
            axis_phase_exponent = arg_func_langs.float_arg_from_proto(
                operation_proto.phasedxzgate.axis_phase_exponent,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            )
            op = cirq.PhasedXZGate(
                x_exponent=x_exponent,
                z_exponent=z_exponent,
                axis_phase_exponent=axis_phase_exponent,
            )(*qubits)
        elif which_gate_type == 'czpowgate':
            op = cirq.CZPowGate(exponent=arg_func_langs.float_arg_from_proto(
                operation_proto.czpowgate.exponent,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            ))(*qubits)
        elif which_gate_type == 'iswappowgate':
            op = cirq.ISwapPowGate(
                exponent=arg_func_langs.float_arg_from_proto(
                    operation_proto.iswappowgate.exponent,
                    arg_function_language=arg_function_language,
                    required_arg_name=None,
                ))(*qubits)
        elif which_gate_type == 'fsimgate':
            theta = arg_func_langs.float_arg_from_proto(
                operation_proto.fsimgate.theta,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            )
            phi = arg_func_langs.float_arg_from_proto(
                operation_proto.fsimgate.phi,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            )
            if isinstance(theta, (float, sympy.Basic)) and isinstance(
                    phi, (float, sympy.Basic)):
                op = cirq.FSimGate(theta=theta, phi=phi)(*qubits)
            else:
                raise ValueError(
                    'theta and phi must be specified for FSimGate')
        elif which_gate_type == 'measurementgate':
            key = arg_func_langs.arg_from_proto(
                operation_proto.measurementgate.key,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            )
            invert_mask = arg_func_langs.arg_from_proto(
                operation_proto.measurementgate.invert_mask,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            )
            if isinstance(invert_mask, list) and isinstance(key, str):
                op = cirq.MeasurementGate(
                    num_qubits=len(qubits),
                    key=key,
                    invert_mask=tuple(invert_mask))(*qubits)
            else:
                raise ValueError(
                    f'Incorrect types for measurement gate {invert_mask} {key}'
                )

        elif which_gate_type == 'waitgate':
            total_nanos = arg_func_langs.float_arg_from_proto(
                operation_proto.waitgate.duration_nanos,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            )
            op = cirq.WaitGate(duration=cirq.Duration(nanos=total_nanos))(
                *qubits)
        else:
            raise ValueError(
                f'Unsupported serialized gate with type "{which_gate_type}".'
                f'\n\noperation_proto:\n{operation_proto}')

        which = operation_proto.WhichOneof('token')
        if which == 'token_constant_index':
            if not constants:
                raise ValueError('Proto has references to constants table '
                                 'but none was passed in, value ='
                                 f'{operation_proto}')
            op = op.with_tags(
                CalibrationTag(constants[
                    operation_proto.token_constant_index].string_value))
        elif which == 'token_value':
            op = op.with_tags(CalibrationTag(operation_proto.token_value))

        return op
예제 #26
0
    def test_cirq_qsim_all_supported_gates(self):
        q0 = cirq.GridQubit(1, 1)
        q1 = cirq.GridQubit(1, 0)
        q2 = cirq.GridQubit(0, 1)
        q3 = cirq.GridQubit(0, 0)

        circuit = cirq.Circuit(
            cirq.Moment([
                cirq.H(q0),
                cirq.H(q1),
                cirq.H(q2),
                cirq.H(q3),
            ]),
            cirq.Moment([
                cirq.T(q0),
                cirq.T(q1),
                cirq.T(q2),
                cirq.T(q3),
            ]),
            cirq.Moment([
                cirq.CZPowGate(exponent=0.7, global_shift=0.2)(q0, q1),
                cirq.CXPowGate(exponent=1.2, global_shift=0.4)(q2, q3),
            ]),
            cirq.Moment([
                cirq.XPowGate(exponent=0.3, global_shift=1.1)(q0),
                cirq.YPowGate(exponent=0.4, global_shift=1)(q1),
                cirq.ZPowGate(exponent=0.5, global_shift=0.9)(q2),
                cirq.HPowGate(exponent=0.6, global_shift=0.8)(q3),
            ]),
            cirq.Moment([
                cirq.CX(q0, q2),
                cirq.CZ(q1, q3),
            ]),
            cirq.Moment([
                cirq.X(q0),
                cirq.Y(q1),
                cirq.Z(q2),
                cirq.S(q3),
            ]),
            cirq.Moment([
                cirq.XXPowGate(exponent=0.4, global_shift=0.7)(q0, q1),
                cirq.YYPowGate(exponent=0.8, global_shift=0.5)(q2, q3),
            ]),
            cirq.Moment([cirq.I(q0),
                         cirq.I(q1),
                         cirq.IdentityGate(2)(q2, q3)]),
            cirq.Moment([
                cirq.rx(0.7)(q0),
                cirq.ry(0.2)(q1),
                cirq.rz(0.4)(q2),
                cirq.PhasedXPowGate(phase_exponent=0.8,
                                    exponent=0.6,
                                    global_shift=0.3)(q3),
            ]),
            cirq.Moment([
                cirq.ZZPowGate(exponent=0.3, global_shift=1.3)(q0, q2),
                cirq.ISwapPowGate(exponent=0.6, global_shift=1.2)(q1, q3),
            ]),
            cirq.Moment([
                cirq.XPowGate(exponent=0.1, global_shift=0.9)(q0),
                cirq.YPowGate(exponent=0.2, global_shift=1)(q1),
                cirq.ZPowGate(exponent=0.3, global_shift=1.1)(q2),
                cirq.HPowGate(exponent=0.4, global_shift=1.2)(q3),
            ]),
            cirq.Moment([
                cirq.SwapPowGate(exponent=0.2, global_shift=0.9)(q0, q1),
                cirq.PhasedISwapPowGate(phase_exponent=0.8, exponent=0.6)(q2,
                                                                          q3),
            ]),
            cirq.Moment([
                cirq.PhasedXZGate(x_exponent=0.2,
                                  z_exponent=0.3,
                                  axis_phase_exponent=1.4)(q0),
                cirq.T(q1),
                cirq.H(q2),
                cirq.S(q3),
            ]),
            cirq.Moment([
                cirq.SWAP(q0, q2),
                cirq.XX(q1, q3),
            ]),
            cirq.Moment([
                cirq.rx(0.8)(q0),
                cirq.ry(0.9)(q1),
                cirq.rz(1.2)(q2),
                cirq.T(q3),
            ]),
            cirq.Moment([
                cirq.YY(q0, q1),
                cirq.ISWAP(q2, q3),
            ]),
            cirq.Moment([
                cirq.T(q0),
                cirq.Z(q1),
                cirq.Y(q2),
                cirq.X(q3),
            ]),
            cirq.Moment([
                cirq.FSimGate(0.3, 1.7)(q0, q2),
                cirq.ZZ(q1, q3),
            ]),
            cirq.Moment([
                cirq.ry(1.3)(q0),
                cirq.rz(0.4)(q1),
                cirq.rx(0.7)(q2),
                cirq.S(q3),
            ]),
            cirq.Moment([
                cirq.MatrixGate(
                    np.array([[0, -0.5 - 0.5j, -0.5 - 0.5j, 0],
                              [0.5 - 0.5j, 0, 0, -0.5 + 0.5j],
                              [0.5 - 0.5j, 0, 0, 0.5 - 0.5j],
                              [0, -0.5 - 0.5j, 0.5 + 0.5j, 0]]))(q0, q1),
                cirq.MatrixGate(
                    np.array([[0.5 - 0.5j, 0, 0, -0.5 + 0.5j],
                              [0, 0.5 - 0.5j, -0.5 + 0.5j, 0],
                              [0, -0.5 + 0.5j, -0.5 + 0.5j, 0],
                              [0.5 - 0.5j, 0, 0, 0.5 - 0.5j]]))(q2, q3),
            ]),
            cirq.Moment([
                cirq.MatrixGate(np.array([[1, 0], [0, 1j]]))(q0),
                cirq.MatrixGate(np.array([[0, -1j], [1j, 0]]))(q1),
                cirq.MatrixGate(np.array([[0, 1], [1, 0]]))(q2),
                cirq.MatrixGate(np.array([[1, 0], [0, -1]]))(q3),
            ]),
            cirq.Moment([
                cirq.riswap(0.7)(q0, q1),
                cirq.givens(1.2)(q2, q3),
            ]),
            cirq.Moment([
                cirq.H(q0),
                cirq.H(q1),
                cirq.H(q2),
                cirq.H(q3),
            ]),
        )

        simulator = cirq.Simulator()
        cirq_result = simulator.simulate(circuit)

        qsim_simulator = qsimcirq.QSimSimulator()
        qsim_result = qsim_simulator.simulate(circuit)

        assert cirq.linalg.allclose_up_to_global_phase(
            qsim_result.state_vector(), cirq_result.state_vector())
예제 #27
0
     cirq.PhasedXPowGate(phase_exponent=0.125, exponent=0.5)(Q0),
     op_proto({
         'phasedxpowgate': {
             'phase_exponent': {
                 'float_value': 0.125
             },
             'exponent': {
                 'float_value': 0.5
             },
         },
         'qubit_constant_index': [0],
     }),
 ),
 (
     cirq.PhasedXZGate(x_exponent=0.125,
                       z_exponent=0.5,
                       axis_phase_exponent=0.25)(Q0),
     op_proto({
         'phasedxzgate': {
             'x_exponent': {
                 'float_value': 0.125
             },
             'z_exponent': {
                 'float_value': 0.5
             },
             'axis_phase_exponent': {
                 'float_value': 0.25
             },
         },
         'qubit_constant_index': [0],
     }),
예제 #28
0
    cirq.Z,
    cirq.ZPowGate(exponent=-0.23),
]

finally_decomposed_1q_gates = []

native_2q_gates = [
    ig.IsingGate(exponent=0.45),
    ig.XYGate(exponent=0.38),
]

non_native_1q_gates = [
    cirq.H,
    cirq.HPowGate(exponent=-0.55),
    cirq.PhasedXZGate(x_exponent=0.2,
                      z_exponent=-0.5,
                      axis_phase_exponent=0.75),
]

non_native_2q_gates = [
    cirq.ISwapPowGate(exponent=0.27),
    cirq.ISWAP,
    cirq.SWAP,
    cirq.CNOT,
    cirq.CXPowGate(exponent=-2.2),
    cirq.CZ,
    cirq.CZPowGate(exponent=1.6),
]


class TestOperationValidation:
예제 #29
0
    gpe_op_id_1 = cirq.OpIdentifier(cirq.PhasedXZGate, q1)
    assert props_v2.gate_pauli_errors[gpe_op_id_0] == expected_vals['gate_pauli_errors']
    assert props_v2.gate_pauli_errors[gpe_op_id_1] == expected_vals['gate_pauli_errors']

    fsim_op_id_0 = cirq.OpIdentifier(cirq.CZPowGate, q0, q1)
    fsim_op_id_1 = cirq.OpIdentifier(cirq.CZPowGate, q1, q0)
    assert props_v2.fsim_errors[fsim_op_id_0] == expected_vals['fsim_errors']
    assert props_v2.fsim_errors[fsim_op_id_1] == expected_vals['fsim_errors']


@pytest.mark.parametrize(
    'op',
    [
        (cirq.Z(cirq.LineQubit(0)) ** 0.3).with_tags(cirq_google.PhysicalZTag),
        cirq.PhasedXZGate(x_exponent=0.8, z_exponent=0.2, axis_phase_exponent=0.1).on(
            cirq.LineQubit(0)
        ),
    ],
)
def test_single_qubit_gates(op):
    q0 = cirq.LineQubit(0)
    props = sample_noise_properties([q0], [])
    model = NoiseModelFromGoogleNoiseProperties(props)
    circuit = cirq.Circuit(op)
    noisy_circuit = circuit.with_noise(model)
    assert len(noisy_circuit.moments) == 3
    assert len(noisy_circuit.moments[0].operations) == 1
    assert noisy_circuit.moments[0].operations[0] == op.with_tags(PHYSICAL_GATE_TAG)

    # Depolarizing noise
    assert len(noisy_circuit.moments[1].operations) == 1
예제 #30
0
 def phxz(a, x, z):
     return cirq.PhasedXZGate(
         axis_phase_exponent=a,
         x_exponent=x,
         z_exponent=z,
     )