コード例 #1
0
def test_measure_key_on():
    q = cirq.GridQubit(0, 0)

    assert cg.XmonMeasurementGate(key='').on(q) == cirq.GateOperation(
        gate=cg.XmonMeasurementGate(key=''), qubits=(q, ))
    assert cg.XmonMeasurementGate(key='a').on(q) == cirq.GateOperation(
        gate=cg.XmonMeasurementGate(key='a'), qubits=(q, ))
コード例 #2
0
def bit_flip_circuit(flip0, flip1):
    q1, q2 = cirq.GridQubit(0, 0), cirq.GridQubit(0, 1)
    g1, g2 = cg.ExpWGate(half_turns=flip0)(q1), cg.ExpWGate(
        half_turns=flip1)(q2)
    m1, m2 = cg.XmonMeasurementGate('q1')(q1), cg.XmonMeasurementGate('q2')(q2)
    circuit = cirq.Circuit()
    circuit.append([g1, g2, m1, m2])
    return circuit
コード例 #3
0
def test_validate_circuit_repeat_measurement_keys():
    d = square_device(3, 3)

    circuit = cirq.Circuit()
    circuit.append([cg.XmonMeasurementGate('a').on(cirq.GridQubit(0, 0)),
                    cg.XmonMeasurementGate('a').on(cirq.GridQubit(0, 1))])

    with pytest.raises(ValueError, message='Measurement key a repeated'):
        d.validate_circuit(circuit)
コード例 #4
0
def test_measurement_eq():
    eq = cirq.testing.EqualsTester()
    eq.make_equality_group(lambda: cg.XmonMeasurementGate(key=''))
    eq.make_equality_group(lambda: cg.XmonMeasurementGate('a'))
    eq.make_equality_group(lambda: cg.XmonMeasurementGate('b'))
    eq.make_equality_group(
        lambda: cg.XmonMeasurementGate(key='', invert_mask=(True, )))
    eq.make_equality_group(
        lambda: cg.XmonMeasurementGate(key='', invert_mask=(False, )))
コード例 #5
0
def test_inverted_measurement_multiple_qubits(scheduler):
    circuit = cirq.Circuit.from_ops(
        cg.XmonMeasurementGate('a', invert_mask=(False, True))(Q1, Q2),
        cg.XmonMeasurementGate('b', invert_mask=(True, False))(Q1, Q2),
        cg.XmonMeasurementGate('c', invert_mask=(True, False))(Q2, Q1))
    simulator = cg.XmonSimulator()
    result = run(simulator, circuit, scheduler)
    np.testing.assert_equal(result.measurements['a'], [[False, True]])
    np.testing.assert_equal(result.measurements['b'], [[True, False]])
    np.testing.assert_equal(result.measurements['c'], [[True, False]])
コード例 #6
0
def test_measurement_multiple_measurements_qubit_order(scheduler):
    circuit = cirq.Circuit()
    measure_a = cg.XmonMeasurementGate('a')
    measure_b = cg.XmonMeasurementGate('b')
    circuit.append(cirq.X(Q1))
    circuit.append([measure_a.on(Q1, Q2)])
    circuit.append([measure_b.on(Q2, Q1)])
    simulator = cg.XmonSimulator()
    result = run(simulator, circuit, scheduler)
    np.testing.assert_equal(result.measurements['a'], [[True, False]])
    np.testing.assert_equal(result.measurements['b'], [[False, True]])
コード例 #7
0
def test_run_no_sharing_few_qubits(scheduler):
    np.random.seed(0)
    circuit = basic_circuit()
    circuit.append([
        cg.XmonMeasurementGate(key='a')(Q1),
        cg.XmonMeasurementGate(key='b')(Q2)
    ])

    simulator = cg.XmonSimulator(cg.XmonOptions(min_qubits_before_shard=0))
    result = run(simulator, circuit, scheduler)
    np.testing.assert_equal(result.measurements['a'], [[True]])
    np.testing.assert_equal(result.measurements['b'], [[False]])
コード例 #8
0
def test_inverted_measurement(scheduler):
    circuit = cirq.Circuit.from_ops(
        cg.XmonMeasurementGate('a', invert_mask=(False,))(Q1),
        cirq.X(Q1),
        cg.XmonMeasurementGate('b', invert_mask=(False,))(Q1),
        cg.XmonMeasurementGate('c', invert_mask=(True,))(Q1),
        cirq.X(Q1),
        cg.XmonMeasurementGate('d', invert_mask=(True,))(Q1))
    simulator = cg.XmonSimulator()
    result = run(simulator, circuit, scheduler)
    np.testing.assert_equal(result.measurements,
                            {'a': [[False]], 'b': [[True]], 'c': [[False]],
                             'd': [[True]]})
コード例 #9
0
def test_run(scheduler):
    np.random.seed(0)
    circuit = basic_circuit()
    circuit.append(
        [cg.XmonMeasurementGate(key='a')(Q1),
         cg.XmonMeasurementGate(key='b')(Q2)])

    simulator = cg.XmonSimulator()
    result = run(simulator, circuit, scheduler)
    assert result.measurements['a'].dtype == bool
    assert result.measurements['b'].dtype == bool
    np.testing.assert_equal(result.measurements,
                            {'a': [[True]], 'b': [[False]]})
コード例 #10
0
def test_validate_schedule_repeat_measurement_keys():
    d = square_device(3, 3)

    s = cirq.Schedule(d, [
        cirq.ScheduledOperation.op_at_on(
            cg.XmonMeasurementGate('a').on(
                cirq.GridQubit(0, 0)), cirq.Timestamp(), d),
        cirq.ScheduledOperation.op_at_on(
            cg.XmonMeasurementGate('a').on(
                cirq.GridQubit(0, 1)), cirq.Timestamp(), d),
    ])

    with pytest.raises(ValueError, message='Measurement key a repeated'):
        d.validate_schedule(s)
コード例 #11
0
def test_simulate_moment_steps():
    np.random.seed(0)
    circuit = basic_circuit()
    circuit.append(
        [cg.XmonMeasurementGate(key='a')(Q1),
         cg.XmonMeasurementGate(key='b')(Q2)])

    simulator = cg.XmonSimulator()
    results = []
    for step in simulator.simulate_moment_steps(circuit):
        results.append(step)
    expected = [{}, {}, {}, {}, {'a': [False], 'b': [False]}]
    assert len(results) == len(expected)
    assert all(a.measurements == b for a, b in zip(results, expected))
コード例 #12
0
def test_simulate_moment_steps_sample():
    np.random.seed(0)
    circuit = cirq.Circuit.from_ops(cirq.X(Q1),
                                    cg.XmonMeasurementGate(key='a')(Q1),
                                    cg.XmonMeasurementGate(key='b')(Q2))
    simulator = cg.XmonSimulator()
    for step in simulator.simulate_moment_steps(circuit, qubit_order=[Q1, Q2]):
        pass
    assert [[True]] == step.sample([Q1])
    assert [[True, False]] == step.sample([Q1, Q2])
    assert [[False]] == step.sample([Q2])

    assert [[True]] * 3 == step.sample([Q1], 3)
    assert [[True, False]] * 3 == step.sample([Q1, Q2], 3)
    assert [[False]] * 3 == step.sample([Q2], 3)
コード例 #13
0
ファイル: supremacy.py プロジェクト: sheshuguang/qutrits
def generate_supremacy_circuit(
    device: cg.XmonDevice,
    cz_depth: int,
    seed: int = None,
    measure: bool = True,
) -> cirq.Circuit:

    randint = random.randint if seed is None else random.Random(seed).randint

    circuit = cirq.Circuit()

    for layer_index in itertools.count():
        if cz_depth <= 0:
            break
        cz_layer = list(_make_cz_layer(device, layer_index))
        if cz_layer:
            circuit.append(_make_random_single_qubit_op_layer(device, randint))
            circuit.append(cz_layer)
            cz_depth -= 1

    circuit.append(_make_random_single_qubit_op_layer(device, randint))
    if measure:
        circuit.append([cg.XmonMeasurementGate(key='').on(*device.qubits)])

    return circuit
コード例 #14
0
def test_measurement_keys_repeat(scheduler):
    circuit = cirq.Circuit()
    meas = cg.XmonMeasurementGate('a')
    circuit.append([meas.on(Q1), cirq.X.on(Q1), cirq.X.on(Q2), meas.on(Q2)])
    simulator = cg.XmonSimulator()
    with pytest.raises(ValueError, message='Repeated Measurement key a'):
        run(simulator, circuit, scheduler)
コード例 #15
0
def test_toggles_measurements():
    a = cirq.NamedQubit('a')
    b = cirq.NamedQubit('b')

    # Single.
    assert_optimizes(
        before=quick_circuit(
            [cg.ExpWGate(axis_half_turns=0.25).on(a)],
            [cirq.measure(a, b)],
        ),
        expected=quick_circuit(
            [],
            [cirq.measure(a, b, invert_mask=(True,))],
        ))
    assert_optimizes(
        before=quick_circuit(
            [cg.ExpWGate(axis_half_turns=0.25).on(b)],
            [cirq.measure(a, b)],
        ),
        expected=quick_circuit(
            [],
            [cirq.measure(a, b, invert_mask=(False, True))],
        ))

    # Multiple.
    assert_optimizes(
        before=quick_circuit(
            [cg.ExpWGate(axis_half_turns=0.25).on(a)],
            [cg.ExpWGate(axis_half_turns=0.25).on(b)],
            [cirq.measure(a, b)],
        ),
        expected=quick_circuit(
            [],
            [],
            [cirq.measure(a, b, invert_mask=(True, True))],
        ))

    # Xmon.
    assert_optimizes(
        before=quick_circuit(
            [cg.ExpWGate(axis_half_turns=0.25).on(a)],
            [cg.XmonMeasurementGate(key='t').on(a, b)],
        ),
        expected=quick_circuit(
            [],
            [cg.XmonMeasurementGate(key='t', invert_mask=(True,)).on(a, b)],
        ))
コード例 #16
0
def test_composite_gates(scheduler):
    circuit = cirq.Circuit()
    circuit.append([cirq.X(Q1), cirq.CNOT(Q1, Q2)])
    m = cg.XmonMeasurementGate('a')
    circuit.append([m(Q1, Q2)])

    simulator = cg.XmonSimulator()
    result = run(simulator, circuit, scheduler)
    np.testing.assert_equal(result.measurements['a'], [[True, True]])
コード例 #17
0
def test_measurement_qubit_order(scheduler):
    circuit = cirq.Circuit()
    meas = cg.XmonMeasurementGate(key='')
    circuit.append(cirq.X(Q2))
    circuit.append(cirq.X(Q1))
    circuit.append([meas.on(Q1, Q3, Q2)])
    simulator = cg.XmonSimulator()
    result = run(simulator, circuit, scheduler)
    np.testing.assert_equal(result.measurements[''], [[True, False, True]])
コード例 #18
0
def test_handedness_of_basic_gates():
    circuit = cirq.Circuit.from_ops(
        cirq.X(Q1)**-0.5,
        cirq.Z(Q1)**-0.5,
        cirq.Y(Q1)**0.5,
        cg.XmonMeasurementGate(key='').on(Q1),
    )
    result = cg.XmonSimulator().run(circuit)
    np.testing.assert_equal(result.measurements[''], [[True]])
コード例 #19
0
def test_handedness_of_xmon_gates():
    circuit = cirq.Circuit.from_ops(
        cg.ExpWGate(half_turns=-0.5).on(Q1),
        cg.ExpZGate(half_turns=-0.5).on(Q1),
        cg.ExpWGate(axis_half_turns=0.5, half_turns=0.5).on(Q1),
        cg.XmonMeasurementGate(key='').on(Q1),
    )
    result = cg.XmonSimulator().run(circuit)
    np.testing.assert_equal(result.measurements[''], [[True]])
コード例 #20
0
ファイル: visualize_test.py プロジェクト: sheshuguang/qutrits
def test_plot_state_histogram():
    pl.switch_backend('PDF')
    simulator = cg.XmonSimulator()

    rot_w_gate = cg.ExpWGate(half_turns=1.)

    q0 = GridQubit(0, 0)
    q1 = GridQubit(1, 0)
    circuit = cirq.Circuit()
    circuit.append([rot_w_gate(q0), rot_w_gate(q1)])
    circuit.append([cg.XmonMeasurementGate(key='q0')(q0),
                    cg.XmonMeasurementGate(key='q1')(q1)])
    results = simulator.run_sweep(program=circuit,
                                  repetitions=5)

    values_plotted = visualize.plot_state_histogram(results[0])
    expected_values = [0., 0., 0., 5.]

    np.testing.assert_equal(values_plotted, expected_values)
コード例 #21
0
def large_circuit():
    np.random.seed(0)
    qubits = [cirq.GridQubit(i, 0) for i in range(10)]
    sqrt_x = cg.ExpWGate(half_turns=0.5, axis_half_turns=0.0)
    cz = cg.Exp11Gate()
    circuit = cirq.Circuit()
    for _ in range(11):
        circuit.append(
            [sqrt_x(qubit) for qubit in qubits if np.random.random() < 0.5])
        circuit.append([cz(qubits[i], qubits[i + 1]) for i in range(9)])
    circuit.append([cg.XmonMeasurementGate(key='meas')(*qubits)])
    return circuit
コード例 #22
0
def test_validate_scheduled_operation_adjacent_exp_11_measure():
    d = square_device(3, 3, holes=[cirq.GridQubit(1, 1)])
    q0 = cirq.GridQubit(0, 0)
    q1 = cirq.GridQubit(1, 0)
    q2 = cirq.GridQubit(2, 0)
    s = cirq.Schedule(d, [
        cirq.ScheduledOperation.op_at_on(cg.XmonMeasurementGate().on(q0),
                                         cirq.Timestamp(), d),
        cirq.ScheduledOperation.op_at_on(cg.Exp11Gate().on(q1, q2),
                                         cirq.Timestamp(), d),
    ])
    d.validate_schedule(s)
コード例 #23
0
def test_single_qubit_measurement_proto_dict_convert():
    gate = cg.XmonMeasurementGate('test')
    proto_dict = {
        'measurement': {
            'targets': [{
                'row': 2,
                'col': 3
            }],
            'key': 'test'
        }
    }
    assert_proto_dict_convert(cg.XmonMeasurementGate, gate, proto_dict,
                              cirq.GridQubit(2, 3))
コード例 #24
0
def test_run_circuit_sweep():
    circuit = cirq.Circuit.from_ops(
        cg.ExpWGate(half_turns=cirq.Symbol('a')).on(Q1),
        cg.XmonMeasurementGate('m').on(Q1),
    )

    sweep = cirq.Linspace('a', 0, 10, 11)
    simulator = cg.XmonSimulator()

    for i, result in enumerate(
            simulator.run_sweep(circuit, sweep, repetitions=1)):
        assert result.params['a'] == i
        np.testing.assert_equal(result.measurements['m'], [[i % 2 != 0]])
コード例 #25
0
def test_single_qubit_measurement_to_proto_dict_convert_invert_mask():
    gate = cg.XmonMeasurementGate('test', invert_mask=(True, ))
    proto_dict = {
        'measurement': {
            'targets': [{
                'row': 2,
                'col': 3
            }],
            'key': 'test',
            'invert_mask': ['true']
        }
    }
    assert_proto_dict_convert(cg.XmonMeasurementGate, gate, proto_dict,
                              cirq.GridQubit(2, 3))
コード例 #26
0
ファイル: xmon_gates_test.py プロジェクト: zhoudaqing/Cirq
def test_single_qubit_measurement_to_proto():
    assert proto_matches_text(
        cg.XmonMeasurementGate('test').to_proto(GridQubit(2, 3)), """
        measurement {
            targets {
                row: 2
                col: 3
            }
            key: "test"
        }
        """)
    assert proto_matches_text(
        cg.XmonMeasurementGate('test',
                               invert_mask=[True]).to_proto(GridQubit(2, 3)),
        """
        measurement {
            targets {
                row: 2
                col: 3
            }
            key: "test"
            invert_mask: true
        }
        """)
コード例 #27
0
ファイル: xmon_gates_test.py プロジェクト: zhoudaqing/Cirq
def test_multi_qubit_measurement_to_proto():
    assert proto_matches_text(
        cg.XmonMeasurementGate('test').to_proto(GridQubit(2, 3),
                                                GridQubit(3, 4)), """
        measurement {
            targets {
                row: 2
                col: 3
            }
            targets {
                row: 3
                col: 4
            }
            key: "test"
        }
        """)
コード例 #28
0
def test_supports_extensions_for_parameter_resolving():
    class DummyGate(cirq.Gate):
        pass

    ext = cirq.Extensions()
    ext.add_cast(cirq.ParameterizableEffect, DummyGate,
                 lambda _: cg.ExpWGate(half_turns=cirq.Symbol('x')))

    a = cirq.NamedQubit('a')
    circuit = cirq.Circuit.from_ops(DummyGate().on(a),
                                    cg.XmonMeasurementGate('a').on(a))
    results = cirq.google.XmonSimulator().run(
        circuit=circuit,
        param_resolver=cirq.ParamResolver({'x': 1}),
        extensions=ext)

    assert str(results) == 'a=1'
コード例 #29
0
def test_invalid_measurement_gate():
    with pytest.raises(ValueError, match='length'):
        cg.XmonMeasurementGate('test', invert_mask=(True, )).to_proto_dict(
            cirq.GridQubit(2, 3), cirq.GridQubit(3, 4))
    with pytest.raises(ValueError, match='no qubits'):
        cg.XmonMeasurementGate('test').to_proto_dict()
コード例 #30
0
def test_validate_measurement_non_adjacent_qubits_ok():
    d = square_device(3, 3)

    d.validate_operation(cirq.GateOperation(
        cg.XmonMeasurementGate(key=''),
        (cirq.GridQubit(0, 0), cirq.GridQubit(2, 0))))