Ejemplo n.º 1
0
def test_sampler(client):
    client().create_program.return_value = (
        'prog',
        quantum.QuantumProgram(name='projects/proj/programs/prog'),
    )
    client().create_job.return_value = (
        'job-id',
        quantum.QuantumJob(name='projects/proj/programs/prog/jobs/job-id',
                           execution_status={'state': 'READY'}),
    )
    client().get_job.return_value = quantum.QuantumJob(
        execution_status={'state': 'SUCCESS'},
        update_time=_to_timestamp('2019-07-09T23:39:59Z'))
    client().get_job_results.return_value = quantum.QuantumResult(
        result=util.pack_any(_RESULTS_V2))
    processor = cg.EngineProcessor('proj', 'mysim', EngineContext())
    sampler = processor.get_sampler()
    results = sampler.run_sweep(
        program=_CIRCUIT,
        params=[cirq.ParamResolver({'a': 1}),
                cirq.ParamResolver({'a': 2})])
    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')}
    assert client().create_program.call_args[0][0] == 'proj'
Ejemplo n.º 2
0
def test_job_results(client_constructor):
    grpc_client = setup_mock_(client_constructor)

    result = quantum.QuantumResult(parent='projects/proj/programs/prog/jobs/job0')
    grpc_client.get_quantum_result.return_value = result

    client = EngineClient()
    assert client.get_job_results('proj', 'prog', 'job0') == result
    grpc_client.get_quantum_result.assert_called_with(
        quantum.GetQuantumResultRequest(parent='projects/proj/programs/prog/jobs/job0')
    )
Ejemplo n.º 3
0
def test_run_delegation(create_job, get_results):
    dt = datetime.datetime.now(tz=datetime.timezone.utc)
    create_job.return_value = (
        'steve',
        quantum.QuantumJob(
            name='projects/a/programs/b/jobs/steve',
            execution_status=quantum.ExecutionStatus(state=quantum.ExecutionStatus.State.SUCCESS),
            update_time=dt,
        ),
    )
    get_results.return_value = quantum.QuantumResult(
        result=util.pack_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 == cg.EngineResult(
        params=cirq.ParamResolver({'a': 1.0}),
        measurements={'q': np.array([[False], [True], [True], [False]], dtype=bool)},
        job_id='steve',
        job_finished_time=dt,
    )
Ejemplo n.º 4
0
def setup_run_circuit_with_result_(client, result):
    client().create_program.return_value = (
        'prog',
        quantum.QuantumProgram(name='projects/proj/programs/prog'),
    )
    client().create_job.return_value = (
        'job-id',
        quantum.QuantumJob(name='projects/proj/programs/prog/jobs/job-id',
                           execution_status={'state': 'READY'}),
    )
    client().get_job.return_value = quantum.QuantumJob(
        execution_status={'state': 'SUCCESS'}, update_time=_DT)
    client().get_job_results.return_value = quantum.QuantumResult(
        result=result)
Ejemplo n.º 5
0
def test_run_batch(client):
    client().create_program.return_value = (
        'prog',
        quantum.QuantumProgram(name='projects/proj/programs/prog'),
    )
    client().create_job.return_value = (
        'job-id',
        quantum.QuantumJob(name='projects/proj/programs/prog/jobs/job-id',
                           execution_status={'state': 'READY'}),
    )
    client().get_job.return_value = quantum.QuantumJob(
        execution_status={'state': 'SUCCESS'},
        update_time=_to_timestamp('2019-07-09T23:39:59Z'))
    client().get_job_results.return_value = quantum.QuantumResult(
        result=_BATCH_RESULTS_V2)

    processor = cg.EngineProcessor('a', 'p', EngineContext())
    job = processor.run_batch(
        programs=[_CIRCUIT, _CIRCUIT],
        job_id='job-id',
        params_list=[cirq.Points('a', [1, 2]),
                     cirq.Points('a', [3, 4])],
    )
    results = job.results()
    assert len(results) == 4
    for i, v in enumerate([1, 2, 3, 4]):
        assert results[i].repetitions == 1
        assert results[i].params.param_dict == {'a': v}
        assert results[i].measurements == {'q': np.array([[0]], dtype='uint8')}
    for result in results:
        assert result.job_id == job.id()
    client().create_program.assert_called_once()
    client().create_job.assert_called_once()
    run_context = v2.batch_pb2.BatchRunContext()
    client().create_job.call_args[1]['run_context'].Unpack(run_context)
    assert len(run_context.run_contexts) == 2
    for idx, rc in enumerate(run_context.run_contexts):
        sweeps = rc.parameter_sweeps
        assert len(sweeps) == 1
        assert sweeps[0].repetitions == 1
        if idx == 0:
            assert sweeps[0].sweep.single_sweep.points.points == [1.0, 2.0]
        if idx == 1:
            assert sweeps[0].sweep.single_sweep.points.points == [3.0, 4.0]
    client().get_job.assert_called_once()
    client().get_job_results.assert_called_once()
Ejemplo n.º 6
0
def test_run_sweep_params(client):
    client().create_program.return_value = (
        'prog',
        quantum.QuantumProgram(name='projects/proj/programs/prog'),
    )
    client().create_job.return_value = (
        'job-id',
        quantum.QuantumJob(name='projects/proj/programs/prog/jobs/job-id',
                           execution_status={'state': 'READY'}),
    )
    client().get_job.return_value = quantum.QuantumJob(
        execution_status={'state': 'SUCCESS'},
        update_time=_to_timestamp('2019-07-09T23:39:59Z'))
    client().get_job_results.return_value = quantum.QuantumResult(
        result=util.pack_any(_RESULTS_V2))

    processor = cg.EngineProcessor('a', 'p', EngineContext())
    job = processor.run_sweep(
        program=_CIRCUIT,
        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')}
    for result in results:
        assert result.job_id == job.id()
        assert result.job_finished_time is not None
    assert results == cirq.read_json(json_text=cirq.to_json(results))

    client().create_program.assert_called_once()
    client().create_job.assert_called_once()

    run_context = v2.run_context_pb2.RunContext()
    client().create_job.call_args[1]['run_context'].Unpack(run_context)
    sweeps = run_context.parameter_sweeps
    assert len(sweeps) == 2
    for i, v in enumerate([1.0, 2.0]):
        assert sweeps[i].repetitions == 1
        assert sweeps[i].sweep.sweep_function.sweeps[
            0].single_sweep.points.points == [v]
    client().get_job.assert_called_once()
    client().get_job_results.assert_called_once()
Ejemplo n.º 7
0
def test_run_calibration(client):
    client().create_program_async.return_value = (
        'prog',
        quantum.QuantumProgram(name='projects/proj/programs/prog'),
    )
    client().create_job_async.return_value = (
        'job-id',
        quantum.QuantumJob(
            name='projects/proj/programs/prog/jobs/job-id', execution_status={'state': 'READY'}
        ),
    )
    client().get_job_async.return_value = quantum.QuantumJob(execution_status={'state': 'SUCCESS'})
    client().get_job_results_async.return_value = quantum.QuantumResult(
        result=_CALIBRATION_RESULTS_V2
    )

    q1 = cirq.GridQubit(2, 3)
    q2 = cirq.GridQubit(2, 4)
    layer1 = cg.CalibrationLayer('xeb', cirq.Circuit(cirq.CZ(q1, q2)), {'num_layers': 42})
    layer2 = cg.CalibrationLayer(
        'readout', cirq.Circuit(cirq.measure(q1, q2)), {'num_samples': 4242}
    )
    processor = cg.EngineProcessor('proj', 'mysim', EngineContext())
    job = processor.run_calibration(layers=[layer1, layer2], job_id='job-id')
    results = job.calibration_results()
    assert len(results) == 2
    assert results[0].code == v2.calibration_pb2.SUCCESS
    assert results[0].error_message == 'First success'
    assert results[0].token == 'abc123'
    assert len(results[0].metrics) == 1
    assert len(results[0].metrics['fidelity']) == 1
    assert results[0].metrics['fidelity'][(q1, q2)] == [0.75]
    assert results[1].code == v2.calibration_pb2.SUCCESS
    assert results[1].error_message == 'Second success'

    # assert label is correct
    client().create_job_async.assert_called_once_with(
        project_id='proj',
        program_id='prog',
        job_id='job-id',
        processor_ids=['mysim'],
        run_context=util.pack_any(v2.run_context_pb2.RunContext()),
        description=None,
        labels={'calibration': ''},
    )
Ejemplo n.º 8
0
def test_calibration_defaults(get_job_results):
    qjob = quantum.QuantumJob(
        execution_status=quantum.ExecutionStatus(
            state=quantum.ExecutionStatus.State.SUCCESS),
        update_time=UPDATE_TIME,
    )
    result = v2.calibration_pb2.FocusedCalibrationResult()
    result.results.add()
    get_job_results.return_value = quantum.QuantumResult(
        result=util.pack_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
Ejemplo n.º 9
0
RESULTS = quantum.QuantumResult(result=util.pack_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(),
    )))