Пример #1
0
def test_run_circuit_failed_missing_processor_name(client):
    client().create_program.return_value = (
        'prog', qtypes.QuantumProgram(name='projects/proj/programs/prog'))
    client().create_job.return_value = (
        'job-id',
        qtypes.QuantumJob(name='projects/proj/programs/prog/jobs/job-id',
                          execution_status={'state': 'READY'}))
    client().get_job.return_value = qtypes.QuantumJob(
        name='projects/proj/programs/prog/jobs/job-id',
        execution_status={
            'state': 'FAILURE',
            'failure': {
                'error_code': 'SYSTEM_ERROR',
                'error_message': 'Not good'
            }
        })

    engine = cg.Engine(project_id='proj')
    with pytest.raises(
            RuntimeError,
            match='Job projects/proj/programs/prog/jobs/job-id on processor'
            ' UNKNOWN failed. SYSTEM_ERROR: Not good'):
        engine.run(program=_CIRCUIT, gate_set=cg.XMON)
Пример #2
0
def test_results(get_job_results):
    qjob = qtypes.QuantumJob(execution_status=qtypes.ExecutionStatus(
        state=qtypes.ExecutionStatus.State.SUCCESS))
    results = qtypes.QuantumResult(result=_to_any(
        Merge(
            """
    sweep_results: [{
            repetitions: 4,
            parameterized_results: [{
                params: {
                    assignments: {
                        key: 'a'
                        value: 1
                    }
                },
                measurement_results: {
                    key: 'q'
                    qubit_measurement_results: [{
                      qubit: {
                        id: '1_1'
                      }
                      results: '\006'
                    }]
                }
            },{
                params: {
                    assignments: {
                        key: 'a'
                        value: 2
                    }
                },
                measurement_results: {
                    key: 'q'
                    qubit_measurement_results: [{
                      qubit: {
                        id: '1_1'
                      }
                      results: '\005'
                    }]
                }
            }]
        }]
    """, v2.result_pb2.Result())))
    get_job_results.return_value = results

    job = cg.EngineJob('a', 'b', 'steve', EngineContext(), _job=qjob)
    data = job.results()
    assert str(data[0]) == 'q=0110'
    assert str(data[1]) == 'q=1010'
    get_job_results.assert_called_once_with('a', 'b', 'steve')
Пример #3
0
def test_remove_job_labels(client_constructor):
    grpc_client = setup_mock_(client_constructor)

    existing = qtypes.QuantumJob(labels={
        'color': 'red',
        'weather': 'sun',
        'run': '1'
    },
                                 label_fingerprint='hash')
    grpc_client.get_quantum_job.return_value = existing
    result = qtypes.QuantumJob(name='projects/proj/programs/prog/jobs/job0')
    grpc_client.update_quantum_job.return_value = result

    client = EngineClient()
    assert client.remove_job_labels('proj', 'prog', 'job0',
                                    ['other']) == existing
    assert grpc_client.update_quantum_program.call_count == 0

    assert client.remove_job_labels('proj', 'prog', 'job0',
                                    ['hello', 'weather']) == result
    assert grpc_client.update_quantum_job.call_args[0] == (
        'projects/proj/programs/prog/jobs/job0',
        qtypes.QuantumJob(name='projects/proj/programs/prog/jobs/job0',
                          labels={
                              'color': 'red',
                              'run': '1',
                          },
                          label_fingerprint='hash'),
        qtypes.field_mask_pb2.FieldMask(paths=['labels']))

    assert client.remove_job_labels('proj', 'prog', 'job0',
                                    ['color', 'weather', 'run']) == result
    assert grpc_client.update_quantum_job.call_args[0] == (
        'projects/proj/programs/prog/jobs/job0',
        qtypes.QuantumJob(name='projects/proj/programs/prog/jobs/job0',
                          label_fingerprint='hash'),
        qtypes.field_mask_pb2.FieldMask(paths=['labels']))
Пример #4
0
def test_failure():
    job = cg.EngineJob(
        'a',
        'b',
        'steve',
        EngineContext(),
        _job=qtypes.QuantumJob(execution_status=qtypes.ExecutionStatus(
            state=qtypes.ExecutionStatus.State.FAILURE,
            failure=qtypes.ExecutionStatus.Failure(
                error_code=qtypes.ExecutionStatus.Failure.Code.SYSTEM_ERROR,
                error_message='boom',
            ),
        )),
    )
    assert job.failure() == ('SYSTEM_ERROR', 'boom')
Пример #5
0
def test_calibration_defaults(get_job_results):
    qjob = qtypes.QuantumJob(execution_status=qtypes.ExecutionStatus(
        state=qtypes.ExecutionStatus.State.SUCCESS))
    result = v2.calibration_pb2.FocusedCalibrationResult()
    result.results.add()
    get_job_results.return_value = qtypes.QuantumResult(result=_to_any(result))
    job = cg.EngineJob('a', 'b', 'steve', EngineContext(), _job=qjob)
    data = job.calibration_results()
    get_job_results.assert_called_once_with('a', 'b', 'steve')
    assert len(data) == 1
    assert data[0].code == v2.calibration_pb2.CALIBRATION_RESULT_UNSPECIFIED
    assert data[0].error_message is None
    assert data[0].token is None
    assert data[0].valid_until is None
    assert len(data[0].metrics) == 0
Пример #6
0
def test_run_circuit_cancelled(client):
    client().create_program.return_value = (
        'prog',
        qtypes.QuantumProgram(name='projects/proj/programs/prog'),
    )
    client().create_job.return_value = (
        'job-id',
        qtypes.QuantumJob(name='projects/proj/programs/prog/jobs/job-id',
                          execution_status={'state': 'READY'}),
    )
    client().get_job.return_value = qtypes.QuantumJob(
        name='projects/proj/programs/prog/jobs/job-id',
        execution_status={
            'state': 'CANCELLED',
        },
    )

    engine = cg.Engine(project_id='proj')
    with pytest.raises(
            RuntimeError,
            match=
            'Job projects/proj/programs/prog/jobs/job-id failed in state CANCELLED.',
    ):
        engine.run(program=_CIRCUIT, gate_set=cg.XMON)
Пример #7
0
def test_run_delegation(create_job, get_results):
    create_job.return_value = (
        'steve',
        qtypes.QuantumJob(
            name='projects/a/programs/b/jobs/steve',
            execution_status=qtypes.ExecutionStatus(
                state=qtypes.ExecutionStatus.State.SUCCESS),
        ),
    )
    get_results.return_value = qtypes.QuantumResult(result=_to_any(
        Merge(
            """sweep_results: [{
        repetitions: 4,
        parameterized_results: [{
            params: {
                assignments: {
                    key: 'a'
                    value: 1
                }
            },
            measurement_results: {
                key: 'q'
                qubit_measurement_results: [{
                  qubit: {
                    id: '1_1'
                  }
                  results: '\006'
                }]
            }
        }]
    }]
""",
            v2.result_pb2.Result(),
        )))

    program = cg.EngineProgram('a', 'b', EngineContext())
    param_resolver = cirq.ParamResolver({})
    results = program.run(job_id='steve',
                          repetitions=10,
                          param_resolver=param_resolver,
                          processor_ids=['mine'])

    assert results == cirq.Result(
        params=cirq.ParamResolver({'a': 1.0}),
        measurements={
            'q': np.array([[False], [True], [True], [False]], dtype=np.bool)
        },
    )
Пример #8
0
def test_calibration_results(get_job_results):
    qjob = qtypes.QuantumJob(execution_status=qtypes.ExecutionStatus(
        state=qtypes.ExecutionStatus.State.SUCCESS))
    get_job_results.return_value = CALIBRATION_RESULT
    job = cg.EngineJob('a', 'b', 'steve', EngineContext(), _job=qjob)
    data = job.calibration_results()
    get_job_results.assert_called_once_with('a', 'b', 'steve')
    assert len(data) == 1
    assert data[0].code == v2.calibration_pb2.ERROR_CALIBRATION_FAILED
    assert data[0].error_message == 'uh oh'
    assert data[0].token == 'abc'
    assert data[0].valid_until.timestamp() == 1234567891
    assert len(data[0].metrics)
    assert data[0].metrics['theta'] == {
        (cirq.GridQubit(0, 0), cirq.GridQubit(0, 1)): [0.9999]
    }
Пример #9
0
def test_calibration_from_job_with_no_calibration(client_constructor):
    client = mock.Mock()
    client_constructor.return_value = client

    client.create_quantum_program.return_value = qtypes.QuantumProgram(
        name='projects/project-id/programs/test')
    client.create_quantum_job.return_value = qtypes.QuantumJob(
        name='projects/project-id/programs/test/jobs/test',
        execution_status={'state': 'SUCCESS'})

    engine = cg.Engine(project_id='project-id')
    job = engine.run_sweep(program=cirq.Circuit())

    calibration = job.get_calibration()
    assert not calibration
    assert not client.get_quantum_calibration.called
Пример #10
0
def test_cancel(client_constructor):
    job_return_value = qtypes.QuantumJob(
        name='projects/project-id/programs/test/jobs/test',
        execution_status={
            'state': 'CANCELLED',
        })
    client = setup_run_circuit_with_job_state_(client_constructor,
                                               job_return_value)

    engine = cg.Engine(project_id='project-id')
    job = engine.run_sweep(program=_CIRCUIT,
                           job_config=cg.JobConfig('project-id'))
    job.cancel()
    assert job.job_resource_name == ('projects/project-id/programs/test/'
                                     'jobs/test')
    assert job.status() == 'CANCELLED'
    assert client.cancel_quantum_job.call_args[0][
        0] == 'projects/project-id/programs/test/jobs/test'
Пример #11
0
def test_calibration_from_job(client_constructor):
    calibration_name = '/project/p/processor/x/calibrations/123'
    client = setup_run_circuit_with_job_state_(
        client_constructor,
        qtypes.QuantumJob(name='projects/project-id/programs/test/jobs/test',
                          execution_status={
                              'state': 'SUCCESS',
                              'calibration_name': calibration_name
                          }))
    client.get_quantum_calibration.return_value = _CALIBRATION

    engine = cg.Engine(project_id='project-id')
    job = engine.run_sweep(program=_CIRCUIT)

    job.status()
    calibration = job.get_calibration()
    assert calibration.timestamp == 1562544000021
    assert set(calibration.keys()) == set(['xeb', 't1', 'globalMetric'])
    assert client.get_quantum_calibration.call_args[0][0] == calibration_name
Пример #12
0
def test_run_circuit_failed_missing_processor_name(client_constructor):
    job_return_value = qtypes.QuantumJob(
        name='projects/project-id/programs/test/jobs/test',
        execution_status={
            'state': 'FAILURE',
            'failure': {
                'error_code': 'SYSTEM_ERROR',
                'error_message': 'Not good'
            }
        })
    setup_run_circuit_with_job_state_(client_constructor, job_return_value)

    engine = cg.Engine(project_id='project-id')
    with pytest.raises(RuntimeError, match='UNKNOWN'):
        engine.run(program=_CIRCUIT)
    with pytest.raises(RuntimeError, match='SYSTEM_ERROR'):
        engine.run(program=_CIRCUIT)
    with pytest.raises(RuntimeError, match='Not good'):
        engine.run(program=_CIRCUIT)
    with pytest.raises(RuntimeError, match='jobs/test'):
        engine.run(program=_CIRCUIT)
Пример #13
0
def test_batched_results(get_job_results):
    qjob = qtypes.QuantumJob(execution_status=qtypes.ExecutionStatus(
        state=qtypes.ExecutionStatus.State.SUCCESS))
    get_job_results.return_value = BATCH_RESULTS

    job = cg.EngineJob('a', 'b', 'steve', EngineContext(), _job=qjob)
    data = job.results()
    assert len(data) == 4
    assert str(data[0]) == 'q=011'
    assert str(data[1]) == 'q=111'
    assert str(data[2]) == 'q=1101'
    assert str(data[3]) == 'q=1001'
    get_job_results.assert_called_once_with('a', 'b', 'steve')

    data = job.batched_results()
    assert len(data) == 2
    assert len(data[0]) == 2
    assert len(data[1]) == 2
    assert str(data[0][0]) == 'q=011'
    assert str(data[0][1]) == 'q=111'
    assert str(data[1][0]) == 'q=1101'
    assert str(data[1][1]) == 'q=1001'
Пример #14
0
def test_run_circuit(client):
    setup_run_circuit_with_result_(client, _A_RESULT)

    engine = cg.Engine(project_id='proj', service_args={'client_info': 1})
    result = engine.run(
        program=_CIRCUIT,
        program_id='prog',
        job_id='job-id',
        processor_ids=['mysim'],
        gate_set=cg.XMON,
    )

    assert result.repetitions == 1
    assert result.params.param_dict == {'a': 1}
    assert result.measurements == {'q': np.array([[0]], dtype='uint8')}
    client.assert_called_with(service_args={'client_info': 1}, verbose=None)
    client.create_program.called_once_with()
    client.create_job.called_once_with(
        'projects/project-id/programs/test',
        qtypes.QuantumJob(
            name='projects/project-id/programs/test/jobs/job-id',
            scheduling_config={
                'priority': 50,
                'processor_selector': {
                    'processor_names':
                    ['projects/project-id/processors/mysim']
                },
            },
            run_context=_to_any(
                v2.run_context_pb2.RunContext(parameter_sweeps=[
                    v2.run_context_pb2.ParameterSweep(repetitions=1)
                ])),
        ),
        False,
    )

    client.get_job.called_once_with('proj', 'prog')
    client.get_job_result.called_once_with()
Пример #15
0
def test_run_calibration_no_processors(create_job):
    create_job.return_value = ('dogs', qtypes.QuantumJob())
    program = cg.EngineProgram('woof', 'woof', EngineContext(), result_type=ResultType.Calibration)
    with pytest.raises(ValueError, match='No processors specified'):
        _ = program.run_calibration(job_id='spot')
Пример #16
0
def test_run_calibration_delegation(create_job):
    create_job.return_value = ('dogs', qtypes.QuantumJob())
    program = cg.EngineProgram('woof', 'woof', EngineContext(), result_type=ResultType.Calibration)
    job = program.run_calibration(processor_ids=['lazydog'])
    assert job._job == qtypes.QuantumJob()
Пример #17
0
def test_update_time(get_job):
    job = cg.EngineJob('a', 'b', 'steve', EngineContext())
    get_job.return_value = qtypes.QuantumJob(
        update_time=qtypes.timestamp_pb2.Timestamp(seconds=1581515101))
    assert job.update_time() == datetime.datetime(2020, 2, 12, 13, 45, 1)
    get_job.assert_called_once_with('a', 'b', 'steve', False)
Пример #18
0
def test_get_processor_no_processor():
    qjob = qtypes.QuantumJob(execution_status=qtypes.ExecutionStatus())

    job = cg.EngineJob('a', 'b', 'steve', EngineContext(), _job=qjob)
    assert not job.get_processor()
Пример #19
0
def test_get_processor():
    qjob = qtypes.QuantumJob(execution_status=qtypes.ExecutionStatus(
        processor_name='projects/a/processors/p'))

    job = cg.EngineJob('a', 'b', 'steve', EngineContext(), _job=qjob)
    assert job.get_processor().processor_id == 'p'
Пример #20
0
def test_create_job(client_constructor):
    grpc_client = setup_mock_(client_constructor)

    result = qtypes.QuantumJob(name='projects/proj/programs/prog/jobs/job0')
    grpc_client.create_quantum_job.return_value = result

    run_context = qtypes.any_pb2.Any()
    labels = {'hello': 'world'}
    client = EngineClient()
    assert client.create_job('proj', 'prog', 'job0', ['processor0'],
                             run_context, 10, 'A job',
                             labels) == ('job0', result)
    assert grpc_client.create_quantum_job.call_args[0] == (
        'projects/proj/programs/prog',
        qtypes.QuantumJob(
            name='projects/proj/programs/prog/jobs/job0',
            run_context=run_context,
            scheduling_config=qtypes.SchedulingConfig(
                priority=10,
                processor_selector=qtypes.SchedulingConfig.ProcessorSelector(
                    processor_names=['projects/proj/processors/processor0'])),
            description='A job',
            labels=labels), False)

    assert client.create_job(
        'proj',
        'prog',
        'job0',
        ['processor0'],
        run_context,
        10,
        'A job',
    ) == ('job0', result)
    assert grpc_client.create_quantum_job.call_args[0] == (
        'projects/proj/programs/prog',
        qtypes.QuantumJob(
            name='projects/proj/programs/prog/jobs/job0',
            run_context=run_context,
            scheduling_config=qtypes.SchedulingConfig(
                priority=10,
                processor_selector=qtypes.SchedulingConfig.ProcessorSelector(
                    processor_names=['projects/proj/processors/processor0'])),
            description='A job'), False)

    assert client.create_job('proj',
                             'prog',
                             'job0', ['processor0'],
                             run_context,
                             10,
                             labels=labels) == ('job0', result)
    assert grpc_client.create_quantum_job.call_args[0] == (
        'projects/proj/programs/prog',
        qtypes.QuantumJob(
            name='projects/proj/programs/prog/jobs/job0',
            run_context=run_context,
            scheduling_config=qtypes.SchedulingConfig(
                priority=10,
                processor_selector=qtypes.SchedulingConfig.ProcessorSelector(
                    processor_names=['projects/proj/processors/processor0'])),
            labels=labels), False)

    assert client.create_job('proj', 'prog', 'job0', ['processor0'],
                             run_context, 10) == ('job0', result)
    assert grpc_client.create_quantum_job.call_args[0] == (
        'projects/proj/programs/prog',
        qtypes.QuantumJob(
            name='projects/proj/programs/prog/jobs/job0',
            run_context=run_context,
            scheduling_config=qtypes.SchedulingConfig(
                priority=10,
                processor_selector=qtypes.SchedulingConfig.ProcessorSelector(
                    processor_names=['projects/proj/processors/processor0'])),
        ), False)

    assert client.create_job('proj',
                             'prog',
                             job_id=None,
                             processor_ids=['processor0'],
                             run_context=run_context,
                             priority=10) == ('job0', result)
    assert grpc_client.create_quantum_job.call_args[0] == (
        'projects/proj/programs/prog',
        qtypes.QuantumJob(
            run_context=run_context,
            scheduling_config=qtypes.SchedulingConfig(
                priority=10,
                processor_selector=qtypes.SchedulingConfig.ProcessorSelector(
                    processor_names=['projects/proj/processors/processor0'])),
        ), False)

    with pytest.raises(ValueError,
                       match='priority must be between 0 and 1000'):
        client.create_job('proj',
                          'prog',
                          job_id=None,
                          processor_ids=['processor0'],
                          run_context=run_context,
                          priority=5000)