Beispiel #1
0
def test_w_to_proto():
    assert proto_matches_text(
        cg.ExpWGate(half_turns=Symbol('k'),
                    axis_half_turns=1).to_proto(GridQubit(2, 3)), """
        exp_w {
            target {
                row: 2
                col: 3
            }
            axis_half_turns {
                raw: 1
            }
            half_turns {
                parameter_key: "k"
            }
        }
        """)

    assert proto_matches_text(
        cg.ExpWGate(half_turns=0.5,
                    axis_half_turns=Symbol('j')).to_proto(GridQubit(2, 3)), """
        exp_w {
            target {
                row: 2
                col: 3
            }
            axis_half_turns {
                parameter_key: "j"
            }
            half_turns {
                raw: 0.5
            }
        }
        """)
Beispiel #2
0
def test_depolarizer_different_gate():
    q1 = ops.QubitId()
    q2 = ops.QubitId()
    cnot = Job(circuits.Circuit([
        circuits.Moment([ops.CNOT(q1, q2)]),
    ]))
    allerrors = DepolarizerChannel(
        probability=1.0,
        depolarizing_gates=[xmon_gates.ExpZGate(),
                            xmon_gates.ExpWGate()])
    p0 = Symbol(DepolarizerChannel._parameter_name + '0')
    p1 = Symbol(DepolarizerChannel._parameter_name + '1')
    p2 = Symbol(DepolarizerChannel._parameter_name + '2')
    p3 = Symbol(DepolarizerChannel._parameter_name + '3')

    error_sweep = (Points(p0.name, [1.0]) + Points(p1.name, [1.0]) +
                   Points(p2.name, [1.0]) + Points(p3.name, [1.0]))

    cnot_then_z = Job(
        circuits.Circuit([
            circuits.Moment([ops.CNOT(q1, q2)]),
            circuits.Moment([
                xmon_gates.ExpZGate(half_turns=p0).on(q1),
                xmon_gates.ExpZGate(half_turns=p1).on(q2)
            ]),
            circuits.Moment([
                xmon_gates.ExpWGate(half_turns=p2).on(q1),
                xmon_gates.ExpWGate(half_turns=p3).on(q2)
            ])
        ]), cnot.sweep * error_sweep)

    assert allerrors.transform_job(cnot) == cnot_then_z
Beispiel #3
0
def test_w_potential_implementation():
    assert not cirq.can_cast(cirq.KnownMatrix,
                             cg.ExpWGate(half_turns=Symbol('a')))
    assert not cirq.can_cast(cirq.ReversibleEffect,
                             cg.ExpWGate(half_turns=Symbol('a')))
    assert cirq.can_cast(cirq.KnownMatrix, cg.ExpWGate())
    assert cirq.can_cast(cirq.ReversibleEffect, cg.ExpWGate())
Beispiel #4
0
def test_cz_eq():
    eq = cirq.testing.EqualsTester()
    eq.make_equality_group(lambda: cg.Exp11Gate(half_turns=0))
    eq.add_equality_group(cg.Exp11Gate(), cg.Exp11Gate(half_turns=1),
                          cg.Exp11Gate(degs=180), cg.Exp11Gate(rads=np.pi))
    eq.make_equality_group(lambda: cg.Exp11Gate(half_turns=Symbol('a')))
    eq.make_equality_group(lambda: cg.Exp11Gate(half_turns=Symbol('b')))
    eq.add_equality_group(cg.Exp11Gate(half_turns=-1.5),
                          cg.Exp11Gate(half_turns=6.5))
Beispiel #5
0
def test_w_parameterize():
    parameterized_gate = cg.ExpWGate(half_turns=Symbol('a'),
                                     axis_half_turns=Symbol('b'))
    assert parameterized_gate.is_parameterized()
    with pytest.raises(ValueError):
        _ = parameterized_gate.matrix()
    resolver = ParamResolver({'a': 0.1, 'b': 0.2})
    resolved_gate = parameterized_gate.with_parameters_resolved_by(resolver)
    assert resolved_gate == cg.ExpWGate(half_turns=0.1, axis_half_turns=0.2)
Beispiel #6
0
def test_partial_reflection_gate_eq():
    eq = EqualsTester()
    eq.add_equality_group(DummyGate(), DummyGate(half_turns=1))
    eq.add_equality_group(DummyGate(half_turns=3.5),
                          DummyGate(half_turns=-0.5))
    eq.make_equality_group(lambda: DummyGate(half_turns=Symbol('a')))
    eq.make_equality_group(lambda: DummyGate(half_turns=Symbol('b')))
    eq.make_equality_group(lambda: DummyGate(half_turns=0))
    eq.add_equality_group(DummyGate(half_turns=0.5), DummyGate(rads=np.pi / 2),
                          DummyGate(degs=90))
Beispiel #7
0
def test_w_eq():
    eq = cirq.testing.EqualsTester()
    eq.add_equality_group(cg.ExpWGate(),
                          cg.ExpWGate(half_turns=1, axis_half_turns=0),
                          cg.ExpWGate(degs=180, axis_degs=0),
                          cg.ExpWGate(rads=np.pi, axis_rads=0))
    eq.make_equality_group(lambda: cg.ExpWGate(half_turns=Symbol('a')))
    eq.make_equality_group(lambda: cg.ExpWGate(half_turns=0))
    eq.make_equality_group(
        lambda: cg.ExpWGate(half_turns=0, axis_half_turns=Symbol('a')))
    eq.add_equality_group(cg.ExpWGate(half_turns=0, axis_half_turns=0.5),
                          cg.ExpWGate(half_turns=0, axis_rads=np.pi / 2))
    eq.make_equality_group(lambda: cg.ExpWGate(half_turns=Symbol('ab'),
                                               axis_half_turns=Symbol('xy')))

    # Flipping the axis and negating the angle gives the same rotation.
    eq.add_equality_group(cg.ExpWGate(half_turns=0.25, axis_half_turns=1.5),
                          cg.ExpWGate(half_turns=1.75, axis_half_turns=0.5))
    # ...but not when there are parameters.
    eq.add_equality_group(
        cg.ExpWGate(half_turns=Symbol('a'), axis_half_turns=1.5))
    eq.add_equality_group(
        cg.ExpWGate(half_turns=Symbol('a'), axis_half_turns=0.5))
    eq.add_equality_group(
        cg.ExpWGate(half_turns=0.25, axis_half_turns=Symbol('a')))
    eq.add_equality_group(
        cg.ExpWGate(half_turns=1.75, axis_half_turns=Symbol('a')))

    # Adding or subtracting whole turns/phases gives the same rotation.
    eq.add_equality_group(cg.ExpWGate(half_turns=-2.25, axis_half_turns=1.25),
                          cg.ExpWGate(half_turns=7.75, axis_half_turns=11.25))
Beispiel #8
0
def test_ignores_czs_separated_by_parameterized():
    q0 = ops.QubitId()
    q1 = ops.QubitId()
    assert_optimizes(
        before=circuits.Circuit([
            circuits.Moment([ops.CZ(q0, q1)]),
            circuits.Moment([ExpZGate(
                half_turns=Symbol('boo'))(q0)]),
            circuits.Moment([ops.CZ(q0, q1)]),
        ]),
        after=circuits.Circuit([
            circuits.Moment([ops.CZ(q0, q1)]),
            circuits.Moment([ExpZGate(
                half_turns=Symbol('boo'))(q0)]),
            circuits.Moment([ops.CZ(q0, q1)]),
        ]))
Beispiel #9
0
def test_z_to_proto():
    assert proto_matches_text(
        cg.ExpZGate(half_turns=Symbol('k')).to_proto(GridQubit(2, 3)), """
        exp_z {
            target {
                row: 2
                col: 3
            }
            half_turns {
                parameter_key: "k"
            }
        }
        """)

    assert proto_matches_text(
        cg.ExpZGate(half_turns=0.5).to_proto(GridQubit(2, 3)), """
        exp_z {
            target {
                row: 2
                col: 3
            }
            half_turns {
                raw: 0.5
            }
        }
        """)
Beispiel #10
0
    def transform_job(self, job):
        """Creates a new job object with depolarizing channel.

        This job will contain the existing Job's circuit with an error gate per
        qubit at every moment.  Creates the parameter sweep for each gate and
        populates with random values as per the specifications of the
        depolarizer channel.

        Args:
            job: Job object to transform

        Returns:
            A new Job object that contains a circuit with up to double the
            moments as the original job, with every other moment being a
            moment containing error gates.  It will also contain a Sweep
            containing values for each error gate.  Note that moments that
            contain no error gates for any repetition will be automatically
            omitted.
        """
        # A set for quick lookup of pre-existing qubits
        qubit_set = set()
        # A list with deterministic qubit order
        qubit_list = []
        circuit = job.circuit

        # Retrieve the set of qubits used in the circuit
        for moment in circuit:
            for op in moment.operations:
                for qubit in op.qubits:
                    if qubit not in qubit_set:
                        qubit_set.add(qubit)
                        qubit_list.append(qubit)

        # Add error circuits
        moments = []
        error_number = 0
        error_sweep = Zip()

        for moment in circuit:
            moments.append(moment)

            for gate in self.depolarizing_gates:
                error_gates = []
                for q in qubit_list:
                    errors = np.random.random(self.realizations) < self.p
                    if any(errors):
                        key = self._parameter_name + str(error_number)
                        new_error_gate = gate**Symbol(key)
                        error_gates.append(new_error_gate.on(q))
                        error_sweep += Points(key, list(errors * 1.0))
                        error_number += 1

                if error_gates:
                    moments.append(ops.Moment(error_gates))

        sweep = job.sweep
        if error_sweep:
            sweep *= error_sweep

        return Job(Circuit(moments), sweep, job.repetitions)
Beispiel #11
0
def test_parameterized_value_from_proto():
    from_proto = cg.XmonGate.parameterized_value_from_proto

    m1 = operations_pb2.ParameterizedFloat(raw=5)
    assert from_proto(m1) == 5

    with pytest.raises(ValueError):
        from_proto(operations_pb2.ParameterizedFloat())

    m3 = operations_pb2.ParameterizedFloat(parameter_key='rr')
    assert from_proto(m3) == Symbol('rr')
Beispiel #12
0
def test_depolarizer_multiple_realizations():
    q1 = ops.QubitId()
    q2 = ops.QubitId()
    cnot = Job(circuits.Circuit([
        circuits.Moment([ops.CNOT(q1, q2)]),
    ]))
    allerrors3 = DepolarizerChannel(probability=1.0, realizations=3)
    p0 = Symbol(DepolarizerChannel._parameter_name + '0')
    p1 = Symbol(DepolarizerChannel._parameter_name + '1')

    error_sweep = (Points(p0.name, [1.0, 1.0, 1.0]) +
                   Points(p1.name, [1.0, 1.0, 1.0]))

    cnot_then_z3 = Job(
        circuits.Circuit([
            circuits.Moment([ops.CNOT(q1, q2)]),
            circuits.Moment([
                xmon_gates.ExpZGate(half_turns=p0).on(q1),
                xmon_gates.ExpZGate(half_turns=p1).on(q2)
            ])
        ]), cnot.sweep * error_sweep)
    assert allerrors3.transform_job(cnot) == cnot_then_z3
Beispiel #13
0
def test_depolarizer_parameterized_gates():
    q1 = ops.QubitId()
    q2 = ops.QubitId()
    cnot_param = Symbol('cnot_turns')
    cnot_gate = xmon_gates.Exp11Gate(half_turns=cnot_param).on(q1, q2)

    job_sweep = Points('cnot_turns', [0.5])

    cnot = Job(circuits.Circuit([circuits.Moment([cnot_gate])]), job_sweep)
    allerrors = DepolarizerChannel(probability=1.0)
    p0 = Symbol(DepolarizerChannel._parameter_name + '0')
    p1 = Symbol(DepolarizerChannel._parameter_name + '1')

    error_sweep = Points(p0.name, [1.0]) + Points(p1.name, [1.0])
    cnot_then_z = Job(
        circuits.Circuit([
            circuits.Moment([cnot_gate]),
            circuits.Moment([
                xmon_gates.ExpZGate(half_turns=p0).on(q1),
                xmon_gates.ExpZGate(half_turns=p1).on(q2)
            ])
        ]), job_sweep * error_sweep)
    assert allerrors.transform_job(cnot) == cnot_then_z
Beispiel #14
0
    def value_of(self, value: Union[Symbol, float,
                                    str]) -> Union[Symbol, float]:
        """Attempt to resolve a Symbol or name or float to its assigned value.

        If unable to resolve a Symbol, returns it unchanged.
        If unable to resolve a name, returns a Symbol with that name.

        Args:
            value: The Symbol or name or float to try to resolve into just
                a float.

        Returns:
            The value of the parameter as resolved by this resolver.
        """
        if isinstance(value, str):
            return self.param_dict.get(value, Symbol(value))
        if isinstance(value, Symbol):
            return self.param_dict.get(value.name, value)
        return value
Beispiel #15
0
def test_cz_to_proto():
    assert proto_matches_text(
        cg.Exp11Gate(half_turns=Symbol('k')).to_proto(GridQubit(2, 3),
                                                      GridQubit(4, 5)), """
        exp_11 {
            target1 {
                row: 2
                col: 3
            }
            target2 {
                row: 4
                col: 5
            }
            half_turns {
                parameter_key: "k"
            }
        }
        """)

    assert proto_matches_text(
        cg.Exp11Gate(half_turns=0.5).to_proto(GridQubit(2, 3),
                                              GridQubit(4, 5)), """
        exp_11 {
            target1 {
                row: 2
                col: 3
            }
            target2 {
                row: 4
                col: 5
            }
            half_turns {
                raw: 0.5
            }
        }
        """)
Beispiel #16
0
def _values(sweep, key):
    p = Symbol(key)
    return [resolver.value_of(p) for resolver in sweep]
Beispiel #17
0
def test_value_of():
    r = resolver.ParamResolver({'a': 0.5, 'b': 0.1})
    assert r.value_of(Symbol('a')) == 0.5
    assert r.value_of(0.5) == 0.5
    assert r.value_of(Symbol('b')) == 0.1
    assert r.value_of(0.3) == 0.3
Beispiel #18
0
def test_parameterized_value_init():
    assert Symbol('a').name == 'a'
    assert Symbol('b').name == 'b'
Beispiel #19
0
def test_cz_potential_implementation():
    assert not cirq.can_cast(cirq.KnownMatrix,
                             cg.Exp11Gate(half_turns=Symbol('a')))
    assert cirq.can_cast(cirq.KnownMatrix, cg.Exp11Gate())
Beispiel #20
0
def test_string_representation():
    assert str(Symbol('a1')) == 'a1'
    assert str(Symbol('_b23_')) == '_b23_'
    assert str(Symbol('1a')) == 'Symbol("1a")'
    assert str(Symbol('&%#')) == 'Symbol("&%#")'
    assert str(Symbol('')) == 'Symbol("")'
Beispiel #21
0
def test_parameterized_value_eq():
    eq = EqualsTester()
    eq.add_equality_group(Symbol('a'))
    eq.make_equality_pair(lambda: Symbol('rr'))
Beispiel #22
0
def test_partial_reflection_gate_with_parameters_resolved_by():
    gate = DummyGate(half_turns=Symbol('a'))
    resolver = ParamResolver({'a': 0.1})
    resolved_gate = gate.with_parameters_resolved_by(resolver)
    assert resolved_gate.half_turns == 0.1