Beispiel #1
0
def test_bad_result_proto(build):
    service = mock.Mock()
    build.return_value = service
    programs = service.projects().programs()
    jobs = programs.jobs()
    programs.create().execute.return_value = {
        'name': 'projects/project-id/programs/test'
    }
    jobs.create().execute.return_value = {
        'name': 'projects/project-id/programs/test/jobs/test',
        'executionStatus': {
            'state': 'READY'
        }
    }
    jobs.get().execute.return_value = {
        'name': 'projects/project-id/programs/test/jobs/test',
        'executionStatus': {
            'state': 'SUCCESS'
        }
    }
    result = _RESULTS_V2.copy()
    result['@type'] = 'type.googleapis.com/unknown'
    jobs.getResult().execute.return_value = {'result': result}

    engine = cg.Engine(project_id='project-id',
                       proto_version=cg.engine.engine.ProtoVersion.V2)
    job = engine.run_sweep(
        program=cirq.moment_by_moment_schedule(cirq.UnconstrainedDevice,
                                               cirq.Circuit()),
        job_config=cg.JobConfig('project-id', gcs_prefix='gs://bucket/folder'),
        params=cirq.Points('a', [1, 2]))
    with pytest.raises(ValueError, match='invalid result proto version'):
        job.results()
Beispiel #2
0
def test_moment_by_moment_schedule_validate_operation_fails():
    device = _TestDevice()
    qubits = device.qubits
    circuit = cirq.Circuit()
    circuit.append(cirq.CNOT(qubits[0], qubits[1]))
    with pytest.raises(ValueError, match="CNOT"):
        _ = cirq.moment_by_moment_schedule(device, circuit)
Beispiel #3
0
def test_moment_by_moment_schedule_empty_moment():
    device = _TestDevice()
    circuit = cirq.Circuit([
        cirq.Moment(),
    ])
    schedule = cirq.moment_by_moment_schedule(device, circuit)
    assert len(schedule.scheduled_operations) == 0
Beispiel #4
0
def test_calibration_from_job_with_no_calibration(build):
    service = mock.Mock()
    build.return_value = service

    programs = service.projects().programs()
    jobs = programs.jobs()
    programs.create().execute.return_value = {
        'name': 'projects/project-id/programs/test'
    }
    jobs.create().execute.return_value = {
        'name': 'projects/project-id/programs/test/jobs/test',
        'executionStatus': {
            'state': 'SUCCESS',
        },
    }

    calibrations = service.projects().processors().calibrations()
    engine = cg.Engine(project_id='project-id')
    job = engine.run_sweep(
        program=cirq.moment_by_moment_schedule(cirq.UnconstrainedDevice,
                                               cirq.Circuit()),
        job_config=cg.JobConfig(gcs_prefix='gs://bucket/folder'))

    calibration = job.get_calibration()
    assert not calibration
    assert not calibrations.get.called
Beispiel #5
0
def test_moment_by_moment_schedule_validate_operation_fails():
    device = _TestDevice()
    qubits = device.qubits
    circuit = cirq.Circuit()
    circuit.append(cirq.CNOT(qubits[0], qubits[1]))
    with pytest.raises(ValueError, match="CNOT"):
        _ = cirq.moment_by_moment_schedule(device, circuit)
Beispiel #6
0
def test_calibration_from_job(build):
    service = mock.Mock()
    build.return_value = service

    programs = service.projects().programs()
    jobs = programs.jobs()
    programs.create().execute.return_value = {
        'name': 'projects/project-id/programs/test'
    }
    calibrationName = '/project/p/processor/x/calibrationsi/123'
    jobs.create().execute.return_value = {
        'name': 'projects/project-id/programs/test/jobs/test',
        'executionStatus': {
            'state': 'SUCCESS',
            'calibrationName': calibrationName,
        },
    }
    calibrations = service.projects().processors().calibrations()
    calibrations.get().execute.return_value = {'data': _CALIBRATION}

    engine = cg.Engine(project_id='project-id')
    job = engine.run_sweep(
        program=cirq.moment_by_moment_schedule(cirq.UnconstrainedDevice,
                                               cirq.Circuit()),
        job_config=cg.JobConfig(gcs_prefix='gs://bucket/folder'))

    calibration = job.get_calibration()
    assert calibration.timestamp == 1562544000021
    assert set(calibration.get_metric_names()) == set(['xeb', 't1'])
    assert calibrations.get.call_args[1]['name'] == calibrationName
Beispiel #7
0
def test_moment_by_moment_schedule_device_validation_fails():
    device = _TestDevice()
    qubits = device.qubits
    circuit = cirq.Circuit([cirq.Moment([
        cirq.CZ(qubits[0], qubits[1]),
        cirq.CZ(qubits[2], qubits[3])
    ])])
    with pytest.raises(ValueError, match="Adjacent CZ"):
        _ = cirq.moment_by_moment_schedule(device, circuit)
Beispiel #8
0
def test_moment_by_moment_schedule_device_validation_fails():
    device = _TestDevice()
    qubits = device.qubits
    circuit = cirq.Circuit([
        cirq.Moment(
            [cirq.CZ(qubits[0], qubits[1]),
             cirq.CZ(qubits[2], qubits[3])])
    ])
    with pytest.raises(ValueError, match="Adjacent CZ"):
        _ = cirq.moment_by_moment_schedule(device, circuit)
Beispiel #9
0
def test_run_sweep_v2(build):
    service = mock.Mock()
    build.return_value = service
    programs = service.projects().programs()
    jobs = programs.jobs()
    programs.create().execute.return_value = {
        'name': 'projects/project-id/programs/test'
    }
    jobs.create().execute.return_value = {
        'name': 'projects/project-id/programs/test/jobs/test',
        'executionStatus': {
            'state': 'READY'
        }
    }
    jobs.get().execute.return_value = {
        'name': 'projects/project-id/programs/test/jobs/test',
        'executionStatus': {
            'state': 'SUCCESS'
        }
    }
    jobs.getResult().execute.return_value = {'result': _RESULTS_V2}

    engine = cg.Engine(
        project_id='project-id',
        proto_version=cg.engine.engine.ProtoVersion.V2,
    )
    job = engine.run_sweep(
        program=cirq.moment_by_moment_schedule(cirq.UnconstrainedDevice,
                                               cirq.Circuit()),
        job_config=cg.JobConfig('project-id', gcs_prefix='gs://bucket/folder'),
        params=cirq.Points('a', [1, 2]))
    results = job.results()
    assert engine.proto_version == cg.engine.engine.ProtoVersion.V2
    assert len(results) == 2
    for i, v in enumerate([1, 2]):
        assert results[i].repetitions == 1
        assert results[i].params.param_dict == {'a': v}
        assert results[i].measurements == {'q': np.array([[0]], dtype='uint8')}
    build.assert_called_with(
        'quantum',
        'v1alpha1',
        discoveryServiceUrl=('https://{api}.googleapis.com'
                             '/$discovery/rest?version='
                             '{apiVersion}'),
        requestBuilder=mock.ANY)
    assert programs.create.call_args[1]['parent'] == 'projects/project-id'
    sweeps = jobs.create.call_args[1]['body']['run_context']['parameterSweeps']
    assert len(sweeps) == 1
    assert sweeps[0]['repetitions'] == 1
    assert sweeps[0]['sweep']['singleSweep']['points']['points'] == [1, 2]
    assert jobs.create.call_args[1][
        'parent'] == 'projects/project-id/programs/test'
    assert jobs.get().execute.call_count == 1
    assert jobs.getResult().execute.call_count == 1
Beispiel #10
0
def test_moment_by_moment_schedule_moment_of_single_qubit_ops():
    device = _TestDevice()
    qubits = device.qubits

    circuit = cirq.Circuit([cirq.Moment(cirq.H(q) for q in qubits),])
    schedule = cirq.moment_by_moment_schedule(device, circuit)

    zero_ns = cirq.Timestamp()
    assert set(schedule.scheduled_operations) == {
        cirq.ScheduledOperation.op_at_on(cirq.H(q), zero_ns, device)
        for q in qubits}
Beispiel #11
0
def test_infer_language():
    q = cirq.GridQubit(0, 0)
    a = sympy.Symbol('a')
    b = sympy.Symbol('b')

    c_linear = cirq.Circuit(cirq.X(q)**(b - a))
    packed = cirq.google.XMON.serialize(c_linear)
    assert packed.language.arg_function_language == 'linear'

    c_empty = cirq.Circuit(cirq.X(q)**b)
    packed = cirq.google.XMON.serialize(c_empty)
    assert packed.language.arg_function_language == ''

    s_linear = cirq.moment_by_moment_schedule(cirq.google.Foxtail, c_linear)
    packed = cirq.google.XMON.serialize(s_linear)
    assert packed.language.arg_function_language == 'linear'

    s_empty = cirq.moment_by_moment_schedule(cirq.google.Foxtail, c_empty)
    packed = cirq.google.XMON.serialize(s_empty)
    assert packed.language.arg_function_language == ''
Beispiel #12
0
def test_protobuf_round_trip():
    device = cg.Foxtail
    circuit = cirq.Circuit([cirq.X(q)**0.5 for q in device.qubits], [
        cirq.CZ(q, q2) for q in [cirq.GridQubit(0, 0)]
        for q2 in device.neighbors_of(q)
    ])
    s1 = cirq.moment_by_moment_schedule(device, circuit)

    protos = list(cg.schedule_to_proto_dicts(s1))
    s2 = cg.schedule_from_proto_dicts(device, protos)

    assert s2 == s1
Beispiel #13
0
def test_run_sweep_params(build):
    service = mock.Mock()
    build.return_value = service
    programs = service.projects().programs()
    jobs = programs.jobs()
    programs.create().execute.return_value = {
        'name': 'projects/project-id/programs/test'
    }
    jobs.create().execute.return_value = {
        'name': 'projects/project-id/programs/test/jobs/test',
        'executionStatus': {
            'state': 'READY'
        }
    }
    jobs.get().execute.return_value = {
        'name': 'projects/project-id/programs/test/jobs/test',
        'executionStatus': {
            'state': 'SUCCESS'
        }
    }
    jobs.getResult().execute.return_value = {'result': _RESULTS}

    job = cg.Engine(api_key="key").run_sweep(
        program=cirq.moment_by_moment_schedule(cirq.UnconstrainedDevice,
                                               cirq.Circuit()),
        job_config=cg.JobConfig('project-id', gcs_prefix='gs://bucket/folder'),
        params=[cirq.ParamResolver({'a': 1}),
                cirq.ParamResolver({'a': 2})])
    results = job.results()
    assert len(results) == 2
    for i, v in enumerate([1, 2]):
        assert results[i].repetitions == 1
        assert results[i].params.param_dict == {'a': v}
        assert results[i].measurements == {'q': np.array([[0]], dtype='uint8')}
    build.assert_called_with(
        'quantum',
        'v1alpha1',
        discoveryServiceUrl=('https://{api}.googleapis.com'
                             '/$discovery/rest?version='
                             '{apiVersion}&key=key'))
    assert programs.create.call_args[1]['parent'] == 'projects/project-id'
    sweeps = programs.create.call_args[1]['body']['code']['parameter_sweeps']
    assert len(sweeps) == 2
    for i, v in enumerate([1, 2]):
        assert sweeps[i]['repetitions'] == 1
        assert sweeps[i]['sweep']['factors'][0]['sweeps'][0]['points'][
            'points'] == [v]
    assert jobs.create.call_args[1][
        'parent'] == 'projects/project-id/programs/test'
    assert jobs.get().execute.call_count == 1
    assert jobs.getResult().execute.call_count == 1
Beispiel #14
0
def test_moment_by_moment_schedule_moment_of_single_qubit_ops():
    device = _TestDevice()
    qubits = device.qubits

    circuit = cirq.Circuit([
        cirq.Moment(cirq.H(q) for q in qubits),
    ])
    schedule = cirq.moment_by_moment_schedule(device, circuit)

    zero_ns = cirq.Timestamp()
    assert set(schedule.scheduled_operations) == {
        cirq.ScheduledOperation.op_at_on(cirq.H(q), zero_ns, device)
        for q in qubits
    }
Beispiel #15
0
def test_moment_by_moment_schedule_moment_of_two_qubit_ops():
    device = _TestDevice()
    qubits = device.qubits

    circuit = cirq.Circuit([
        cirq.Moment(
            (cirq.CZ(qubits[i], qubits[i + 1]) for i in range(0, 9, 3)))
    ])
    schedule = cirq.moment_by_moment_schedule(device, circuit)

    zero_ns = cirq.Timestamp()
    expected = set(
        cirq.ScheduledOperation.op_at_on(cirq.CZ(qubits[i], qubits[
            i + 1]), zero_ns, device) for i in range(0, 9, 3))
    assert set(schedule.scheduled_operations) == expected
Beispiel #16
0
def test_moment_by_moment_schedule_empty_moment_ignored():
    device = _TestDevice()
    qubits = device.qubits

    circuit = cirq.Circuit([cirq.Moment([cirq.H(qubits[0])]),
                       cirq.Moment([]),
                       cirq.Moment([cirq.H(qubits[0])])])
    schedule = cirq.moment_by_moment_schedule(device, circuit)

    zero_ns = cirq.Timestamp()
    twenty_ns = cirq.Timestamp(nanos=20)
    assert set(schedule.scheduled_operations) == {
        cirq.ScheduledOperation.op_at_on(cirq.H(qubits[0]), zero_ns, device),
        cirq.ScheduledOperation.op_at_on(cirq.H(qubits[0]), twenty_ns, device),
    }
Beispiel #17
0
def test_moment_by_moment_schedule_moment_of_two_qubit_ops():
    device = _TestDevice()
    qubits = device.qubits

    circuit = cirq.Circuit(
        [cirq.Moment((cirq.CZ(qubits[i], qubits[i + 1])
                      for i in range(0, 9, 3)))])
    schedule = cirq.moment_by_moment_schedule(device, circuit)

    zero_ns = cirq.Timestamp()
    expected = set(
        cirq.ScheduledOperation.op_at_on(cirq.CZ(qubits[i], qubits[i + 1]),
                                         zero_ns,
                                         device)
        for i in range(0, 9, 3))
    assert set(schedule.scheduled_operations) == expected
Beispiel #18
0
def test_moment_by_moment_schedule_empty_moment_ignored():
    device = _TestDevice()
    qubits = device.qubits

    circuit = cirq.Circuit([
        cirq.Moment([cirq.H(qubits[0])]),
        cirq.Moment([]),
        cirq.Moment([cirq.H(qubits[0])])
    ])
    schedule = cirq.moment_by_moment_schedule(device, circuit)

    zero_ns = cirq.Timestamp()
    twenty_ns = cirq.Timestamp(nanos=20)
    assert set(schedule.scheduled_operations) == {
        cirq.ScheduledOperation.op_at_on(cirq.H(qubits[0]), zero_ns, device),
        cirq.ScheduledOperation.op_at_on(cirq.H(qubits[0]), twenty_ns, device),
    }
Beispiel #19
0
def test_moment_by_moment_schedule_max_duration():
    device = _TestDevice()
    qubits = device.qubits

    circuit = cirq.Circuit([
        cirq.Moment([cirq.H(qubits[0]), cirq.CZ(qubits[1], qubits[2])]),
        cirq.Moment([cirq.H(qubits[0])])])
    schedule = cirq.moment_by_moment_schedule(device, circuit)

    zero_ns = cirq.Timestamp()
    fourty_ns = cirq.Timestamp(nanos=40)
    assert set(schedule.scheduled_operations) == {
        cirq.ScheduledOperation.op_at_on(cirq.H(qubits[0]), zero_ns, device),
        cirq.ScheduledOperation.op_at_on(
            cirq.CZ(qubits[1], qubits[2]), zero_ns, device),
        cirq.ScheduledOperation.op_at_on(cirq.H(qubits[0]), fourty_ns, device),
    }
Beispiel #20
0
def test_moment_by_moment_schedule_max_duration():
    device = _TestDevice()
    qubits = device.qubits

    circuit = cirq.Circuit([
        cirq.Moment([cirq.H(qubits[0]),
                     cirq.CZ(qubits[1], qubits[2])]),
        cirq.Moment([cirq.H(qubits[0])])
    ])
    schedule = cirq.moment_by_moment_schedule(device, circuit)

    zero_ns = cirq.Timestamp()
    fourty_ns = cirq.Timestamp(nanos=40)
    assert set(schedule.scheduled_operations) == {
        cirq.ScheduledOperation.op_at_on(cirq.H(qubits[0]), zero_ns, device),
        cirq.ScheduledOperation.op_at_on(cirq.CZ(qubits[1], qubits[2]),
                                         zero_ns, device),
        cirq.ScheduledOperation.op_at_on(cirq.H(qubits[0]), fourty_ns, device),
    }
Beispiel #21
0
def test_moment_by_moment_schedule_two_moments():
    device = _TestDevice()
    qubits = device.qubits

    circuit = cirq.Circuit([cirq.Moment(cirq.H(q) for q in qubits),
                       cirq.Moment((cirq.CZ(qubits[i], qubits[i + 1])
                                    for i in range(0, 9, 3)))])
    schedule = cirq.moment_by_moment_schedule(device, circuit)

    zero_ns = cirq.Timestamp()
    twenty_ns = cirq.Timestamp(nanos=20)
    expected_one_qubit = set(
        cirq.ScheduledOperation.op_at_on(cirq.H(q), zero_ns, device)
        for q in qubits)
    expected_two_qubit = set(
        cirq.ScheduledOperation.op_at_on(
            cirq.CZ(qubits[i], qubits[i + 1]), twenty_ns,
            device) for i in range(0, 9, 3))
    expected = expected_one_qubit.union(expected_two_qubit)
    assert set(schedule.scheduled_operations) == expected
Beispiel #22
0
def test_moment_by_moment_schedule_two_moments():
    device = _TestDevice()
    qubits = device.qubits

    circuit = cirq.Circuit([
        cirq.Moment(cirq.H(q) for q in qubits),
        cirq.Moment(
            (cirq.CZ(qubits[i], qubits[i + 1]) for i in range(0, 9, 3)))
    ])
    schedule = cirq.moment_by_moment_schedule(device, circuit)

    zero_ns = cirq.Timestamp()
    twenty_ns = cirq.Timestamp(nanos=20)
    expected_one_qubit = set(
        cirq.ScheduledOperation.op_at_on(cirq.H(q), zero_ns, device)
        for q in qubits)
    expected_two_qubit = set(
        cirq.ScheduledOperation.op_at_on(cirq.CZ(qubits[i], qubits[
            i + 1]), twenty_ns, device) for i in range(0, 9, 3))
    expected = expected_one_qubit.union(expected_two_qubit)
    assert set(schedule.scheduled_operations) == expected
Beispiel #23
0
def test_final_wavefunction_different_program_types():
    a, b = cirq.LineQubit.range(2)

    np.testing.assert_allclose(cirq.final_wavefunction(cirq.X), [0, 1],
                               atol=1e-8)

    ops = [cirq.H(a), cirq.CNOT(a, b)]

    np.testing.assert_allclose(
        cirq.final_wavefunction(ops),
        [np.sqrt(0.5), 0, 0, np.sqrt(0.5)],
        atol=1e-8)

    np.testing.assert_allclose(
        cirq.final_wavefunction(cirq.Circuit.from_ops(ops)),
        [np.sqrt(0.5), 0, 0, np.sqrt(0.5)],
        atol=1e-8)

    np.testing.assert_allclose(
        cirq.final_wavefunction(
            cirq.moment_by_moment_schedule(cirq.UNCONSTRAINED_DEVICE,
                                           cirq.Circuit.from_ops(ops))),
        [np.sqrt(0.5), 0, 0, np.sqrt(0.5)],
        atol=1e-8)
Beispiel #24
0
"""Tests for engine."""
import base64
import copy
import re
from unittest import mock
import numpy as np
import pytest

from apiclient import discovery, http
from apiclient.errors import HttpError

import cirq
import cirq.google as cg

_CIRCUIT = cirq.Circuit()
_SCHEDULE = cirq.moment_by_moment_schedule(cirq.UNCONSTRAINED_DEVICE, _CIRCUIT)

_A_RESULT = {
    '@type':
    'type.googleapis.com/cirq.api.google.v1.Result',
    'sweepResults': [{
        'repetitions':
        1,
        'measurementKeys': [{
            'key': 'q',
            'qubits': [{
                'row': 1,
                'col': 1
            }]
        }],
        'parameterizedResults': [{
Beispiel #25
0
def test_moment_by_moment_schedule_empty_moment():
    device = _TestDevice()
    circuit = cirq.Circuit([cirq.Moment(),])
    schedule = cirq.moment_by_moment_schedule(device, circuit)
    assert len(schedule.scheduled_operations) == 0
Beispiel #26
0


device = Xmon10Device()
circuit =cirq.Circuit()
circuit.append([cirq.CZ(device.qubits[0], device.qubits[2])])
try:
    device.validate_circuit(circuit)
except ValueError as e:
    print(e)

#//with scheduling

import cirq

circuit = cirq.Circuit()
circuit.append([cirq.CZ(device.qubits[0], device.qubits[1]), cirq.X(device.qubits[0])])
print(circuit)

#convert into a scheduled_operation

schedule = cirq.moment_by_moment_schedule(device, circuit)
print(schedule[cirq.Timestamp(nanos=15)])


#slice and device?

slice = schedule[cirq.Timestamp(nanos=5):cirq.Timestamp(nanos=15)]
slice_schedule = cirq.Schedule(device, slice)
print(slice_schedule ==schedule)
Beispiel #27
0
"""Tests for engine."""
import base64
import re
from unittest import mock
import numpy as np
import pytest
import matplotlib as mpl

from apiclient import discovery, http

import cirq
import cirq.google as cg

_CIRCUIT = cirq.Circuit()
_SCHEDULE = cirq.moment_by_moment_schedule(cirq.UnconstrainedDevice, _CIRCUIT)

_A_RESULT = {
    '@type':
    'type.googleapis.com/cirq.api.google.v1.Result',
    'sweepResults': [{
        'repetitions':
        1,
        'measurementKeys': [{
            'key': 'q',
            'qubits': [{
                'row': 1,
                'col': 1
            }]
        }],
        'parameterizedResults': [{
Beispiel #28
0
def test_graph_device():
    one_qubit_duration = cirq.Duration(picos=10)
    two_qubit_duration = cirq.Duration(picos=1)
    one_qubit_edge = ccgd.FixedDurationUndirectedGraphDeviceEdge(
        one_qubit_duration)
    two_qubit_edge = ccgd.FixedDurationUndirectedGraphDeviceEdge(
        two_qubit_duration)

    empty_device = ccgd.UndirectedGraphDevice()
    assert not empty_device.qubits
    assert not empty_device.edges

    n_qubits = 4
    qubits = cirq.LineQubit.range(n_qubits)
    edges = {(cirq.LineQubit(i), cirq.LineQubit((i + 1) % n_qubits)):
             two_qubit_edge
             for i in range(n_qubits)}
    edges.update({(cirq.LineQubit(i), ): one_qubit_edge
                  for i in range(n_qubits)})
    device_graph = ccgd.UndirectedHypergraph(labelled_edges=edges)

    def not_cnots(first_op, second_op):
        if all(
                isinstance(op, cirq.GateOperation) and op.gate == cirq.CNOT
                for op in (first_op, second_op)):
            raise ValueError('Simultaneous CNOTs')

    assert ccgd.is_undirected_device_graph(device_graph)
    with pytest.raises(TypeError):
        ccgd.UndirectedGraphDevice('abc')
    constraint_edges = {
        (frozenset(cirq.LineQubit.range(2)),
         frozenset(cirq.LineQubit.range(2, 4))):
        None,
        (frozenset(cirq.LineQubit.range(1, 3)),
         frozenset((cirq.LineQubit(0), cirq.LineQubit(3)))):
        not_cnots
    }
    crosstalk_graph = ccgd.UndirectedHypergraph(
        labelled_edges=constraint_edges)
    assert ccgd.is_crosstalk_graph(crosstalk_graph)

    with pytest.raises(TypeError):
        ccgd.UndirectedGraphDevice(device_graph, crosstalk_graph='abc')

    graph_device = ccgd.UndirectedGraphDevice(device_graph)
    assert graph_device.crosstalk_graph == ccgd.UndirectedHypergraph()

    graph_device = ccgd.UndirectedGraphDevice(device_graph,
                                              crosstalk_graph=crosstalk_graph)
    assert sorted(graph_device.edges) == sorted(device_graph.edges)
    assert graph_device.qubits == tuple(qubits)
    assert graph_device.device_graph == device_graph
    assert graph_device.labelled_edges == device_graph.labelled_edges

    assert graph_device.duration_of(cirq.X(qubits[2])) == one_qubit_duration
    assert (graph_device.duration_of(
        cirq.CNOT(*qubits[:2])) == two_qubit_duration)
    with pytest.raises(KeyError):
        graph_device.duration_of(cirq.CNOT(qubits[0], qubits[2]))
    with pytest.raises(ValueError):
        graph_device.validate_operation(cirq.CNOT(qubits[0], qubits[2]))
    with pytest.raises(AttributeError):
        graph_device.validate_operation(list((2, 3)))

    moment = cirq.Moment([cirq.CNOT(*qubits[:2]), cirq.CNOT(*qubits[2:])])
    with pytest.raises(ValueError):
        graph_device.validate_moment(moment)
    with pytest.raises(ValueError):
        scheduled_operations = (cirq.ScheduledOperation.op_at_on(
            op, cirq.Timestamp(), graph_device) for op in moment.operations)
        schedule = cirq.Schedule(graph_device, scheduled_operations)
        graph_device.validate_schedule(schedule)

    moment = cirq.Moment(
        [cirq.CNOT(qubits[0], qubits[3]),
         cirq.CZ(qubits[1], qubits[2])])
    graph_device.validate_moment(moment)
    circuit = cirq.Circuit([moment], graph_device)
    schedule = cirq.moment_by_moment_schedule(graph_device, circuit)
    assert graph_device.validate_schedule(schedule) is None

    moment = cirq.Moment(
        [cirq.CNOT(qubits[0], qubits[3]),
         cirq.CNOT(qubits[1], qubits[2])])
    with pytest.raises(ValueError):
        graph_device.validate_moment(moment)
    with pytest.raises(ValueError):
        scheduled_operations = (cirq.ScheduledOperation.op_at_on(
            op, cirq.Timestamp(), graph_device) for op in moment.operations)
        schedule = cirq.Schedule(graph_device, scheduled_operations)
        graph_device.validate_schedule(schedule)