Beispiel #1
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)
Beispiel #2
0
def test_find_circuit_structure_violations():
    q0, q1 = cirq.LineQubit.range(2)
    circuit = cirq.Circuit([
        cirq.Moment([cirq.PhasedXPowGate(phase_exponent=0).on(q0)]),
        cirq.Moment([
            cirq.PhasedXPowGate(phase_exponent=0.5).on(q0),
            cirq.ZPowGate(exponent=1).on(q1)
        ]),
        cirq.Moment([cg.SYC(q0, q1)]),
        cirq.measure(q0, q1, key='z'),
        cirq.CNOT(q0, q1)
    ])
    violations = find_circuit_structure_violations(circuit)
    np.testing.assert_array_equal(violations, [1, 4])
    assert violations.tolist() == [1, 4]
Beispiel #3
0
    def test_simplify_circuit_merge_one_qubit_gates(self, qubits):

        q0 = qubits[0]
        c = cirq.Circuit()
        c.append([
            cirq.XPowGate(exponent=0.1)(q0),
            cirq.YPowGate(exponent=0.2)(q0),
            cirq.ZPowGate(exponent=0.3)(q0),
        ])
        new = simplify_circuit(c)

        # the one-qubit gates have been merged
        assert len(new) == 2
        assert isinstance(new[0].operations[0].gate, cirq.PhasedXPowGate)
        assert isinstance(new[1].operations[0].gate, cirq.ZPowGate)
Beispiel #4
0
  def test_import_non_line_qubits_error(self):
    qubit_a = cirq.GridQubit(0, 1)
    qubit_b = cirq.GridQubit(0, 2)

    circ = cirq.Circuit(
        cirq.PhasedXPowGate(exponent=0.47, phase_exponent=0.11).on(qubit_a),
        cirq.CZPowGate(exponent=1.0).on(qubit_a, qubit_b),
        cirq.ZPowGate(exponent=0.42).on(qubit_b)
    )

    with self.assertRaisesRegex(
        ValueError,
        r'import is supported for circuits on LineQubits only \[found qubit'
        r' type\(s\): GridQubit\]'):
      cirq_converter.import_from_cirq(circ)
Beispiel #5
0
def test_validate_well_structured_inhomo():
    q0, q1 = cirq.LineQubit.range(2)
    circuit = cirq.Circuit([
        cirq.Moment([cirq.PhasedXPowGate(phase_exponent=0).on(q0)]),
        cirq.Moment([
            cirq.PhasedXPowGate(phase_exponent=0.5).on(q0),
            cirq.ZPowGate(exponent=1).on(q1)
        ]),
        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('Inhomogeneous')
def test_parameterizable(resolve_fn):
    a = sympy.Symbol('a')
    qubits = cirq.LineQubit.range(3)

    cz = cirq.ControlledOperation(qubits[:1], cirq.Z(qubits[1]))
    cza = cirq.ControlledOperation(qubits[:1], cirq.ZPowGate(exponent=a)(qubits[1]))
    assert cirq.is_parameterized(cza)
    assert not cirq.is_parameterized(cz)
    assert resolve_fn(cza, cirq.ParamResolver({'a': 1})) == cz

    cchan = cirq.ControlledOperation(
        [qubits[0]],
        cirq.RandomGateChannel(sub_gate=cirq.PhaseDampingChannel(0.1), probability=a)(qubits[1]),
    )
    with pytest.raises(ValueError, match='Cannot control channel'):
        resolve_fn(cchan, cirq.ParamResolver({'a': 0.1}))
    def operations(self, qubits: Sequence[cirq.Qid]) -> cirq.OP_TREE:
        """Produce the operations of the ansatz circuit."""
        # TODO implement asymmetric ansatz

        param_set = set(self.params())

        for i in range(self.iterations):

            # Apply one- and two-body interactions with a swap network that
            # reverses the order of the modes
            def one_and_two_body_interaction(p, q, a, b) -> cirq.OP_TREE:
                t_symbol = LetterWithSubscripts('T', p, q, i)
                w_symbol = LetterWithSubscripts('W', p, q, i)
                v_symbol = LetterWithSubscripts('V', p, q, i)
                if t_symbol in param_set:
                    yield cirq.ISwapPowGate(exponent=-t_symbol).on(a, b)
                if w_symbol in param_set:
                    yield cirq.PhasedISwapPowGate(exponent=w_symbol).on(a, b)
                if v_symbol in param_set:
                    yield cirq.CZPowGate(exponent=v_symbol).on(a, b)
            yield swap_network(
                    qubits, one_and_two_body_interaction, fermionic=True)
            qubits = qubits[::-1]

            # Apply one-body potential
            for p in range(len(qubits)):
                u_symbol = LetterWithSubscripts('U', p, i)
                if u_symbol in param_set:
                    yield cirq.ZPowGate(exponent=u_symbol).on(qubits[p])

            # Apply one- and two-body interactions again. This time, reorder
            # them so that the entire iteration is symmetric
            def one_and_two_body_interaction_reversed_order(p, q, a, b
                    ) -> cirq.OP_TREE:
                t_symbol = LetterWithSubscripts('T', p, q, i)
                w_symbol = LetterWithSubscripts('W', p, q, i)
                v_symbol = LetterWithSubscripts('V', p, q, i)
                if v_symbol in param_set:
                    yield cirq.CZPowGate(exponent=v_symbol).on(a, b)
                if w_symbol in param_set:
                    yield cirq.PhasedISwapPowGate(exponent=w_symbol).on(a, b)
                if t_symbol in param_set:
                    yield cirq.ISwapPowGate(exponent=-t_symbol).on(a, b)
            yield swap_network(
                    qubits, one_and_two_body_interaction_reversed_order,
                    fermionic=True, offset=True)
            qubits = qubits[::-1]
Beispiel #8
0
def test_deserialize_exp_z_parameterized():
    serialized_op = {
        'gate': {
            'id': 'exp_z'
        },
        'args': {
            'half_turns': {
                'symbol': 'x'
            }
        },
        'qubits': [{
            'id': '1_2'
        }]
    }
    q = cirq.GridQubit(1, 2)
    expected = cirq.ZPowGate(exponent=sympy.Symbol('x'))(q)
    assert cg.XMON.deserialize_op_dict(serialized_op) == expected
Beispiel #9
0
def qft_cirq(n):
    q = cirq.GridQubit.rect(1, n)

    gates = []
    for j in range(n):
        for k in range(j):
            gates.append(
                cirq.ZPowGate(exponent=math.pi /
                              float(2**(j - k))).controlled()(q[j], q[k]))
        gates.append(cirq.H(q[j]))

    for i in range(n):
        gates.append(cirq.measure(q[i], key='c' + str(i)))

    circ = cirq.Circuit(gates)

    return circ
Beispiel #10
0
def encode_classical_datapoint(vector, qubits=None):
    vec_norm = vector / np.linalg.norm(vector)
    n = max(1, int(np.ceil(np.log2(len(vec_norm)))))

    if qubits is None:
        qubits = cirq.LineQubit.range(n)

    N = 2 ** n 
    while len(vec_norm) < N:
        vec_norm = np.append(vec_norm, 0)

    magnitudes = list(map(np.abs, vec_norm))
    phases = list(map(np.angle, vec_norm))
    M = get_uniformly_controlled_rotation_matrix(n - 1)
    rotation_cnots = get_cnot_control_positions(n - 1)
    reversed_prog = cirq.Circuit()

    for step in range(n):
        reversed_step_prog = cirq.Circuit()
        z_thetas, y_thetas, phases, magnitudes = \
            get_rotation_parameters(phases, magnitudes)

        converted_z_thetas = np.dot(M, z_thetas)
        converted_y_thetas = np.dot(M, y_thetas)
        phase_prog = get_reversed_unification_program(converted_z_thetas,
                                                      rotation_cnots,
                                                      qubits[0],
                                                      qubits[step + 1:],
                                                      'phase')
        prob_prog = get_reversed_unification_program(converted_y_thetas,
                                                     rotation_cnots,
                                                     qubits[0],
                                                     qubits[step + 1:],
                                                     'magnitude')
        if step < n - 1:
            reversed_step_prog.append(cirq.SWAP(qubits[0], qubits[step + 1]))
            M = M[0:int(len(M) / 2), 0:int(len(M) / 2)] * 2
            rotation_cnots = rotation_cnots[:int(len(rotation_cnots) / 2)]
            rotation_cnots[-1] -= 1

        reversed_step_prog.append(prob_prog)
        reversed_step_prog.append(phase_prog)
        reversed_prog.append(reversed_step_prog)
    reversed_prog.append(cirq.H(i) for i in qubits)
    reversed_prog.append([cirq.rz(-2 * phases[0])(qubits[0]), cirq.ZPowGate(exponent=2 * phases[0]/np.pi)(qubits[0])])
    return reversed_prog
Beispiel #11
0
def test_ixyz_circuit_diagram():
    q = cirq.NamedQubit('q')
    ix = cirq.XPowGate(exponent=1, global_shift=0.5)
    iy = cirq.YPowGate(exponent=1, global_shift=0.5)
    iz = cirq.ZPowGate(exponent=1, global_shift=0.5)

    cirq.testing.assert_has_diagram(
        cirq.Circuit(
            ix(q),
            ix(q)**-1,
            ix(q)**-0.99999,
            ix(q)**-1.00001,
            ix(q)**3,
            ix(q)**4.5,
            ix(q)**4.500001,
        ),
        """
q: ───X───X───X───X───X───X^0.5───X^0.5───
        """,
    )

    cirq.testing.assert_has_diagram(
        cirq.Circuit(
            iy(q),
            iy(q)**-1,
            iy(q)**3,
            iy(q)**4.5,
            iy(q)**4.500001,
        ),
        """
q: ───Y───Y───Y───Y^0.5───Y^0.5───
    """,
    )

    cirq.testing.assert_has_diagram(
        cirq.Circuit(
            iz(q),
            iz(q)**-1,
            iz(q)**3,
            iz(q)**4.5,
            iz(q)**4.500001,
        ),
        """
q: ───Z───Z───Z───S───S───
    """,
    )
Beispiel #12
0
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)
def test_wrong_dims():
    x3 = cirq.XPowGate(dimension=3)
    with pytest.raises(ValueError, match='Wrong shape'):
        _ = x3.on(cirq.LineQubit(0))
    with pytest.raises(ValueError, match='Wrong shape'):
        _ = x3.on(cirq.LineQid(0, dimension=4))

    z3 = cirq.ZPowGate(dimension=3)
    with pytest.raises(ValueError, match='Wrong shape'):
        _ = z3.on(cirq.LineQubit(0))
    with pytest.raises(ValueError, match='Wrong shape'):
        _ = z3.on(cirq.LineQid(0, dimension=4))

    with pytest.raises(ValueError, match='Wrong shape'):
        _ = cirq.X.on(cirq.LineQid(0, dimension=3))

    with pytest.raises(ValueError, match='Wrong shape'):
        _ = cirq.Z.on(cirq.LineQid(0, dimension=3))
Beispiel #14
0
def unitary_design_block(circuit: cirq.Circuit, n: int) -> cirq.Circuit:
    """
    random Haar measure approximation

    :param circuit: cirq.Circuit, empty circuit
    :param n: # of qubit
    :return:
    """
    for i in range(n):
        theta = np.random.choice([0, 2 / 3, 4 / 3])
        circuit.append(cirq.ZPowGate(exponent=theta)(q(i)))
    for i in range(n - 1):
        for j in range(i + 1, n):
            if np.random.choice([0, 1]) < 0.5:
                circuit.append(cirq.CZ(q(i), q(j)))
    for i in range(n):
        circuit.append(cirq.H(q(i)))
    return circuit
Beispiel #15
0
def test_z_init():
    z = cirq.ZPowGate(exponent=5)
    assert z.exponent == 5

    # Canonicalizes exponent for equality, but keeps the inner details.
    assert cirq.Z**0.5 != cirq.Z**-0.5
    assert (cirq.Z**-1)**0.5 == cirq.Z**-0.5
    assert cirq.Z**-1 == cirq.Z
    assert cirq.Z.controlled(num_controls=2) == cirq.ControlledGate(
        cirq.Z, num_controls=2)
    assert cirq.Z.controlled(num_controls=1) == cirq.CZ
    assert cirq.Z.controlled(control_values=((1, ), )) == cirq.CZ
    assert cirq.Z.controlled(control_qid_shape=(2, )) == cirq.CZ
    assert cirq.Z.controlled(num_controls=1,
                             control_qid_shape=(3, )) == cirq.ControlledGate(
                                 cirq.Z,
                                 num_controls=1,
                                 control_qid_shape=(3, ))
    assert z.controlled() == cirq.CZPowGate(exponent=5)
Beispiel #16
0
def test_deserialize_exp_z(half_turns):
    serialized_op = {
        'gate': {
            'id': 'exp_z'
        },
        'args': {
            'half_turns': {
                'arg_value': {
                    'float_value': half_turns
                }
            }
        },
        'qubits': [{
            'id': '1_2'
        }]
    }
    q = cirq.GridQubit(1, 2)
    expected = cirq.ZPowGate(exponent=half_turns)(q)
    assert cg.XMON.deserialize_op_dict(serialized_op) == expected
Beispiel #17
0
def export_to_cirq(obj):
    """Imports a gate, operation or circuit from Cirq.

  Args:
      obj: the object to be exported to Cirq.

  Returns:
      the exported Cirq object (an instance of cirq.Circuit, cirq.GateOperation,
      or a subclass of cirq.Gate).

  Raises:
      TypeError: if export is not supported for the given type.
      ValueError: if the object cannot be exported successfully.
  """

    if isinstance(obj, circuit.PhasedXGate):
        return cirq.PhasedXPowGate(exponent=obj.get_rotation_angle() / np.pi,
                                   phase_exponent=obj.get_phase_angle() /
                                   np.pi)
    elif isinstance(obj, circuit.RotZGate):
        return cirq.ZPowGate(exponent=obj.get_rotation_angle() / np.pi)
    elif isinstance(obj, circuit.ControlledZGate):
        return cirq.CZPowGate(exponent=1.0)
    elif isinstance(obj, circuit.MatrixGate):
        num_qubits = obj.get_num_qubits()
        operator = obj.get_operator()

        if num_qubits == 1:
            return cirq.SingleQubitMatrixGate(operator)
        elif num_qubits == 2:
            return cirq.TwoQubitMatrixGate(operator)
        else:
            raise ValueError('MatrixGate for %d qubits not supported (Cirq has'
                             ' matrix gates only up to 2 qubits)' % num_qubits)
    elif isinstance(obj, circuit.Operation):
        return cirq.GateOperation(
            export_to_cirq(obj.get_gate()),
            [cirq.LineQubit(qubit) for qubit in obj.get_qubits()])
    elif isinstance(obj, circuit.Circuit):
        return cirq.Circuit(export_to_cirq(operation) for operation in obj)
    else:
        raise TypeError('unknown type: %s' % type(obj).__name__)
Beispiel #18
0
def test_exponentiate_single_value_as_exponent():
    q = cirq.LineQubit(0)

    assert cirq.approx_eq(math.e**(-0.25j * math.pi * cirq.X(q)),
                          cirq.Rx(0.25 * math.pi).on(q))

    assert cirq.approx_eq(math.e**(-0.25j * math.pi * cirq.Y(q)),
                          cirq.Ry(0.25 * math.pi).on(q))

    assert cirq.approx_eq(math.e**(-0.25j * math.pi * cirq.Z(q)),
                          cirq.Rz(0.25 * math.pi).on(q))

    assert cirq.approx_eq(np.exp(-0.3j * math.pi * cirq.X(q)),
                          cirq.Rx(0.3 * math.pi).on(q))

    assert cirq.approx_eq(cirq.X(q)**0.5, cirq.XPowGate(exponent=0.5).on(q))

    assert cirq.approx_eq(cirq.Y(q)**0.5, cirq.YPowGate(exponent=0.5).on(q))

    assert cirq.approx_eq(cirq.Z(q)**0.5, cirq.ZPowGate(exponent=0.5).on(q))
def test_deserialize_z_parameterized():
    serialized_op = op_proto({
        'gate': {
            'id': 'z'
        },
        'args': {
            'half_turns': {
                'symbol': 'a'
            },
            'type': {
                'arg_value': {
                    'string_value': cgc.VIRTUAL_Z
                }
            },
        },
        'qubits': [{
            'id': '1_2'
        }],
    })
    q = cirq.GridQubit(1, 2)
    expected = cirq.ZPowGate(exponent=sympy.Symbol('a'))(q)
    assert SINGLE_QUBIT_GATE_SET.deserialize_op(serialized_op) == expected
Beispiel #20
0
def test_deserialize_z_parameterized():
    serialized_op = {
        'gate': {
            'id': 'z'
        },
        'args': {
            'half_turns': {
                'symbol': 'a'
            },
            'type': {
                'arg_value': {
                    'string_value': 'virtual_propagates_forward'
                }
            }
        },
        'qubits': [{
            'id': '1_2'
        }]
    }
    q = cirq.GridQubit(1, 2)
    expected = cirq.ZPowGate(exponent=sympy.Symbol('a'))(q)
    assert SINGLE_QUBIT_GATE_SET.deserialize_op_dict(serialized_op) == expected
def test_deserialize_exp_z_parameterized():
    serialized_op = op_proto({
        'gate': {
            'id': 'z'
        },
        'args': {
            'half_turns': {
                'symbol': 'x'
            },
            'type': {
                'arg_value': {
                    'string_value': 'virtual_propagates_forward'
                }
            },
        },
        'qubits': [{
            'id': '1_2'
        }],
    })
    q = cirq.GridQubit(1, 2)
    expected = cirq.ZPowGate(exponent=sympy.Symbol('x'))(q)
    assert cg.XMON.deserialize_op(serialized_op) == expected
Beispiel #22
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)
Beispiel #23
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.SWAP) == 'SWAP'
    assert str(cirq.SWAP**0.5) == 'SWAP**0.5'

    assert str(cirq.ISWAP) == 'ISWAP'
    assert str(cirq.ISWAP**0.5) == 'ISWAP**0.5'
Beispiel #24
0
def gate_to_cirq(gate1):
    """Converts list of gate sequences to its cirq analogue

    Args:
        gate1: Sequence of gate to be transcribed

    Returns:
        --

    Raises:
        RuntimeError: Gate value passed cannot be implemented by cirq library

    """

    if gate1[0] == 'X':
        return cirq.X
    elif gate1[0] == 'Ry':
        return cirq.ry(-gate1[1])
    elif gate1[0] == 'Rz':
        return cirq.rz(-gate1[1])
    elif gate1[0] == 'R1':
        return cirq.ZPowGate(exponent=gate1[1] / np.pi)
    else:
        raise RuntimeError("Can't implement: %s" % gate1)
Beispiel #25
0
def test_deserialize_z(half_turns):
    serialized_op = {
        'gate': {
            'id': 'z'
        },
        'args': {
            'half_turns': {
                'arg_value': {
                    'float_value': half_turns
                }
            },
            'type': {
                'arg_value': {
                    'string_value': 'virtual_propagates_forward'
                }
            }
        },
        'qubits': [{
            'id': '1_2'
        }]
    }
    q = cirq.GridQubit(1, 2)
    expected = cirq.ZPowGate(exponent=half_turns)(q)
    assert SINGLE_QUBIT_GATE_SET.deserialize_op_dict(serialized_op) == expected
def test_deserialize_exp_z(half_turns):
    serialized_op = op_proto({
        'gate': {
            'id': 'z'
        },
        'args': {
            'half_turns': {
                'arg_value': {
                    'float_value': half_turns
                }
            },
            'type': {
                'arg_value': {
                    'string_value': 'virtual_propagates_forward'
                }
            },
        },
        'qubits': [{
            'id': '1_2'
        }],
    })
    q = cirq.GridQubit(1, 2)
    expected = cirq.ZPowGate(exponent=half_turns)(q)
    assert cg.XMON.deserialize_op(serialized_op) == expected
Beispiel #27
0
def test_equals():
    eq = cirq.testing.EqualsTester()
    eq.add_equality_group(cirq.X, cirq.ops.pauli_gates.X, cirq.XPowGate())
    eq.add_equality_group(cirq.Y, cirq.ops.pauli_gates.Y, cirq.YPowGate())
    eq.add_equality_group(cirq.Z, cirq.ops.pauli_gates.Z, cirq.ZPowGate())
Beispiel #28
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
Beispiel #29
0
    class NonGateOperation(cirq.Operation):
        def qubits(self):
            pass

        def with_qubits(self, *new_qubits):
            pass

    assert not cirq.op_gate_isinstance(NonGateOperation(), cirq.XPowGate)
    assert not cirq.op_gate_isinstance(NonGateOperation(), NonGateOperation)


@pytest.mark.parametrize('gate1,gate2,eq_up_to_global_phase', [
    (cirq.rz(0.3 * np.pi), cirq.Z**0.3, True),
    (cirq.rz(0.3), cirq.Z**0.3, False),
    (cirq.ZZPowGate(global_shift=0.5), cirq.ZZ, True),
    (cirq.ZPowGate(global_shift=0.5)**sympy.Symbol('e'), cirq.Z, False),
    (cirq.Z**sympy.Symbol('e'), cirq.Z**sympy.Symbol('f'), False),
])
def test_equal_up_to_global_phase_on_gates(gate1, gate2,
                                           eq_up_to_global_phase):
    num_qubits1, num_qubits2 = (cirq.num_qubits(g) for g in (gate1, gate2))
    qubits = cirq.LineQubit.range(max(num_qubits1, num_qubits2) + 1)
    op1, op2 = gate1(*qubits[:num_qubits1]), gate2(*qubits[:num_qubits2])
    assert cirq.equal_up_to_global_phase(op1, op2) == eq_up_to_global_phase
    op2_on_diff_qubits = gate2(*qubits[1:num_qubits2 + 1])
    assert not cirq.equal_up_to_global_phase(op1, op2_on_diff_qubits)


def test_equal_up_to_global_phase_on_diff_types():
    op = cirq.X(cirq.LineQubit(0))
    assert not cirq.equal_up_to_global_phase(op, 3)
Beispiel #30
0
    def test_cirq_qsim_global_shift(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.CXPowGate(exponent=1, global_shift=0.7)(q0, q1),
                cirq.CZPowGate(exponent=1, global_shift=0.9)(q2, q3),
            ]),
            cirq.Moment([
                cirq.XPowGate(exponent=1, global_shift=1.1)(q0),
                cirq.YPowGate(exponent=1, global_shift=1)(q1),
                cirq.ZPowGate(exponent=1, global_shift=0.9)(q2),
                cirq.HPowGate(exponent=1, global_shift=0.8)(q3),
            ]),
            cirq.Moment([
                cirq.XXPowGate(exponent=1, global_shift=0.2)(q0, q1),
                cirq.YYPowGate(exponent=1, global_shift=0.3)(q2, q3),
            ]),
            cirq.Moment([
                cirq.ZPowGate(exponent=0.25, global_shift=0.4)(q0),
                cirq.ZPowGate(exponent=0.5, global_shift=0.5)(q1),
                cirq.YPowGate(exponent=1, global_shift=0.2)(q2),
                cirq.ZPowGate(exponent=1, global_shift=0.3)(q3),
            ]),
            cirq.Moment([
                cirq.ZZPowGate(exponent=1, global_shift=0.2)(q0, q1),
                cirq.SwapPowGate(exponent=1, global_shift=0.3)(q2, q3),
            ]),
            cirq.Moment([
                cirq.XPowGate(exponent=1, global_shift=0)(q0),
                cirq.YPowGate(exponent=1, global_shift=0)(q1),
                cirq.ZPowGate(exponent=1, global_shift=0)(q2),
                cirq.HPowGate(exponent=1, global_shift=0)(q3),
            ]),
            cirq.Moment([
                cirq.ISwapPowGate(exponent=1, global_shift=0.3)(q0, q1),
                cirq.ZZPowGate(exponent=1, global_shift=0.5)(q2, q3),
            ]),
            cirq.Moment([
                cirq.ZPowGate(exponent=0.5, global_shift=0)(q0),
                cirq.ZPowGate(exponent=0.25, global_shift=0)(q1),
                cirq.XPowGate(exponent=0.9, global_shift=0)(q2),
                cirq.YPowGate(exponent=0.8, global_shift=0)(q3),
            ]),
            cirq.Moment([
                cirq.CZPowGate(exponent=0.3, global_shift=0)(q0, q1),
                cirq.CXPowGate(exponent=0.4, global_shift=0)(q2, q3),
            ]),
            cirq.Moment([
                cirq.ZPowGate(exponent=1.3, global_shift=0)(q0),
                cirq.HPowGate(exponent=0.8, global_shift=0)(q1),
                cirq.XPowGate(exponent=0.9, global_shift=0)(q2),
                cirq.YPowGate(exponent=0.4, global_shift=0)(q3),
            ]),
            cirq.Moment([
                cirq.XXPowGate(exponent=0.8, global_shift=0)(q0, q1),
                cirq.YYPowGate(exponent=0.6, global_shift=0)(q2, q3),
            ]),
            cirq.Moment([
                cirq.HPowGate(exponent=0.7, global_shift=0)(q0),
                cirq.ZPowGate(exponent=0.2, global_shift=0)(q1),
                cirq.YPowGate(exponent=0.3, global_shift=0)(q2),
                cirq.XPowGate(exponent=0.7, global_shift=0)(q3),
            ]),
            cirq.Moment([
                cirq.ZZPowGate(exponent=0.1, global_shift=0)(q0, q1),
                cirq.SwapPowGate(exponent=0.6, global_shift=0)(q2, q3),
            ]),
            cirq.Moment([
                cirq.XPowGate(exponent=0.4, global_shift=0)(q0),
                cirq.YPowGate(exponent=0.3, global_shift=0)(q1),
                cirq.ZPowGate(exponent=0.2, global_shift=0)(q2),
                cirq.HPowGate(exponent=0.1, global_shift=0)(q3),
            ]),
            cirq.Moment([
                cirq.ISwapPowGate(exponent=1.3, global_shift=0)(q0, q1),
                cirq.CXPowGate(exponent=0.5, global_shift=0)(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())