def test_get_device_specification(): processor = cg.EngineProcessor('a', 'p', EngineContext(), _processor=quantum.QuantumProcessor()) assert processor.get_device_specification() is None # Construct expected device proto based on example expected = v2.device_pb2.DeviceSpecification() gs = expected.valid_gate_sets.add() gs.name = 'test_set' gates = gs.valid_gates.add() gates.id = 'x' gates.number_of_qubits = 1 gates.gate_duration_picos = 1000 gates.valid_targets.extend(['1q_targets']) expected.valid_qubits.extend(['0_0', '1_1']) target = expected.valid_targets.add() target.name = '1q_targets' target.target_ordering = v2.device_pb2.TargetSet.SYMMETRIC new_target = target.targets.add() new_target.ids.extend(['0_0']) processor = cg.EngineProcessor( 'a', 'p', EngineContext(), _processor=quantum.QuantumProcessor(device_spec=_DEVICE_SPEC)) assert processor.get_device_specification() == expected
def test_get_batch_size(get_program): # Has to fetch from engine if not _program specified. program = cg.EngineProgram('a', 'b', EngineContext(), result_type=ResultType.Batch) get_program.return_value = qtypes.QuantumProgram(code=_BATCH_PROGRAM_V2) assert program.batch_size() == 1 # If _program specified, uses that value. program = cg.EngineProgram( 'a', 'b', EngineContext(), _program=qtypes.QuantumProgram(code=_BATCH_PROGRAM_V2), result_type=ResultType.Batch, ) assert program.batch_size() == 1 with pytest.raises(ValueError, match='ResultType.Program'): program = cg.EngineProgram('a', 'b', EngineContext(), result_type=ResultType.Program) _ = program.batch_size() with pytest.raises(ValueError, match='cirq.google.api.v2.Program'): get_program.return_value = qtypes.QuantumProgram(code=_PROGRAM_V2) program = cg.EngineProgram('a', 'b', EngineContext(), result_type=ResultType.Batch) _ = program.batch_size()
def test_description(get_program): program = cg.EngineProgram( 'a', 'b', EngineContext(), _program=quantum.QuantumProgram(description='hello') ) assert program.description() == 'hello' get_program.return_value = quantum.QuantumProgram(description='hello') assert cg.EngineProgram('a', 'b', EngineContext()).description() == 'hello' get_program.assert_called_once_with('a', 'b', False)
def test_supported_languages(): processor = cg.EngineProcessor('a', 'p', EngineContext(), _processor=quantum.QuantumProcessor()) assert processor.supported_languages() == [] processor = cg.EngineProcessor( 'a', 'p', EngineContext(), _processor=quantum.QuantumProcessor(supported_languages=['lang1', 'lang2']), ) assert processor.supported_languages() == ['lang1', 'lang2']
def test_description(get_job): job = cg.EngineJob('a', 'b', 'steve', EngineContext(), _job=quantum.QuantumJob(description='hello')) assert job.description() == 'hello' get_job.return_value = quantum.QuantumJob(description='hello') assert cg.EngineJob('a', 'b', 'steve', EngineContext()).description() == 'hello' get_job.assert_called_once_with('a', 'b', 'steve', False)
def test_expected_recovery_time(): processor = cg.EngineProcessor('a', 'p', EngineContext(), _processor=quantum.QuantumProcessor()) assert not processor.expected_recovery_time() processor = cg.EngineProcessor( 'a', 'p', EngineContext(), _processor=quantum.QuantumProcessor(expected_recovery_time=Timestamp(seconds=1581515101)), ) assert processor.expected_recovery_time() == datetime.datetime( 2020, 2, 12, 13, 45, 1, tzinfo=datetime.timezone.utc )
def test_expected_down_time(get_processor): processor = cg.EngineProcessor('a', 'p', EngineContext(), _processor=quantum.QuantumProcessor()) assert not processor.expected_down_time() get_processor.return_value = quantum.QuantumProcessor( expected_down_time=Timestamp(seconds=1581515101) ) assert cg.EngineProcessor('a', 'p', EngineContext()).expected_down_time() == datetime.datetime( 2020, 2, 12, 13, 45, 1, tzinfo=datetime.timezone.utc ) get_processor.assert_called_once()
def test_add_labels(add_program_labels): program = cg.EngineProgram('a', 'b', EngineContext(), _program=qtypes.QuantumProgram(labels={})) assert program.labels() == {} add_program_labels.return_value = qtypes.QuantumProgram(labels={ 'a': '1', }) assert program.add_labels({'a': '1'}).labels() == {'a': '1'} add_program_labels.assert_called_with('a', 'b', {'a': '1'}) add_program_labels.return_value = qtypes.QuantumProgram(labels={ 'a': '2', 'b': '1' }) assert program.add_labels({ 'a': '2', 'b': '1' }).labels() == { 'a': '2', 'b': '1' } add_program_labels.assert_called_with('a', 'b', {'a': '2', 'b': '1'})
def test_get_repetitions_and_sweeps_v1(get_job): job = cg.EngineJob('a', 'b', 'steve', EngineContext()) get_job.return_value = quantum.QuantumJob(run_context=util.pack_any( v1.program_pb2.RunContext( parameter_sweeps=[v1.params_pb2.ParameterSweep(repetitions=10)]))) with pytest.raises(ValueError, match='v1 RunContext is not supported'): job.get_repetitions_and_sweeps()
def test_labels(): job = cg.EngineJob('a', 'b', 'steve', EngineContext(), _job=quantum.QuantumJob(labels={'t': '1'})) assert job.labels() == {'t': '1'}
def test_timeout(patched_time_sleep, get_job): qjob = qtypes.QuantumJob(execution_status=qtypes.ExecutionStatus( state=qtypes.ExecutionStatus.State.RUNNING)) get_job.return_value = qjob job = cg.EngineJob('a', 'b', 'steve', EngineContext(timeout=500)) with pytest.raises(RuntimeError, match='Timed out'): job.results()
def test_results_len(get_job_results): qjob = qtypes.QuantumJob(execution_status=qtypes.ExecutionStatus( state=qtypes.ExecutionStatus.State.SUCCESS)) get_job_results.return_value = RESULTS job = cg.EngineJob('a', 'b', 'steve', EngineContext(), _job=qjob) assert len(job) == 2
def test_calibration_results_not_a_calibration(get_job_results): qjob = qtypes.QuantumJob(execution_status=qtypes.ExecutionStatus( state=qtypes.ExecutionStatus.State.SUCCESS)) get_job_results.return_value = RESULTS job = cg.EngineJob('a', 'b', 'steve', EngineContext(), _job=qjob) with pytest.raises(ValueError, match='calibration results'): job.calibration_results()
def test_add_labels(add_job_labels): job = cg.EngineJob('a', 'b', 'steve', EngineContext(), _job=qtypes.QuantumJob(labels={})) assert job.labels() == {} add_job_labels.return_value = qtypes.QuantumJob(labels={ 'a': '1', }) assert job.add_labels({'a': '1'}).labels() == {'a': '1'} add_job_labels.assert_called_with('a', 'b', 'steve', {'a': '1'}) add_job_labels.return_value = qtypes.QuantumJob(labels={ 'a': '2', 'b': '1' }) assert job.add_labels({ 'a': '2', 'b': '1' }).labels() == { 'a': '2', 'b': '1' } add_job_labels.assert_called_with('a', 'b', 'steve', {'a': '2', 'b': '1'})
def test_get_schedule(list_time_slots): results = [ qtypes.QuantumTimeSlot( processor_name='potofgold', start_time=Timestamp(seconds=1000020000), end_time=Timestamp(seconds=1000040000), slot_type=qenums.QuantumTimeSlot.TimeSlotType.MAINTENANCE, maintenance_config=qtypes.QuantumTimeSlot.MaintenanceConfig( title='Testing', description='Testing some new configuration.', ), ), qtypes.QuantumTimeSlot( processor_name='potofgold', start_time=Timestamp(seconds=1000010000), end_time=Timestamp(seconds=1000020000), slot_type=qenums.QuantumTimeSlot.TimeSlotType.RESERVATION, reservation_config=qtypes.QuantumTimeSlot.ReservationConfig( project_id='super_secret_quantum'), ), ] list_time_slots.return_value = results processor = cg.EngineProcessor('proj', 'p0', EngineContext()) assert (processor.get_schedule( datetime.datetime.fromtimestamp(1000000000), datetime.datetime.fromtimestamp(1000050000)) == results) list_time_slots.assert_called_once_with( 'proj', 'p0', 'start_time < 1000050000 AND end_time > 1000000000')
def test_get_repetitions_and_sweeps_unsupported(get_job): job = cg.EngineJob('a', 'b', 'steve', EngineContext()) get_job.return_value = quantum.QuantumJob(run_context=any_pb2.Any( type_url='type.googleapis.com/unknown.proto')) with pytest.raises(ValueError, match='unsupported run_context type: unknown.proto'): job.get_repetitions_and_sweeps()
def test_get_calibration(get_calibration): qjob = quantum.QuantumJob(execution_status=quantum.ExecutionStatus( calibration_name='projects/a/processors/p/calibrations/123')) calibration = quantum.QuantumCalibration(data=util.pack_any( Merge( """ timestamp_ms: 123000, metrics: [{ name: 'xeb', targets: ['0_0', '0_1'], values: [{ double_val: .9999 }] }, { name: 't1', targets: ['0_0'], values: [{ double_val: 321 }] }, { name: 'globalMetric', values: [{ int32_val: 12300 }] }] """, v2.metrics_pb2.MetricsSnapshot(), ))) get_calibration.return_value = calibration job = cg.EngineJob('a', 'b', 'steve', EngineContext(), _job=qjob) assert list(job.get_calibration()) == ['xeb', 't1', 'globalMetric'] get_calibration.assert_called_once_with('a', 'p', 123)
def test_labels(): program = cg.EngineProgram( 'a', 'b', EngineContext(), _program=qtypes.QuantumProgram(labels={'t': '1'})) assert program.labels() == {'t': '1'}
def test_batched_results(get_job_results): qjob = quantum.QuantumJob( execution_status=quantum.ExecutionStatus( state=quantum.ExecutionStatus.State.SUCCESS), update_time=UPDATE_TIME, ) 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'
def test_get_circuit_v1(get_program): program = cg.EngineProgram('a', 'b', EngineContext()) get_program.return_value = qtypes.QuantumProgram( code=_to_any(v1.program_pb2.Program())) with pytest.raises(ValueError, match='v1 Program is not supported'): program.get_circuit()
def test_list_reservation(list_reservations): name = 'projects/proj/processors/p0/reservations/rid' results = [ quantum.QuantumReservation( name=name, start_time=Timestamp(seconds=1000000000), end_time=Timestamp(seconds=1000003600), whitelisted_users=['*****@*****.**'], ), quantum.QuantumReservation( name=name + '2', start_time=Timestamp(seconds=1000003600), end_time=Timestamp(seconds=1000007200), whitelisted_users=['*****@*****.**'], ), ] list_reservations.return_value = results processor = cg.EngineProcessor('proj', 'p0', EngineContext()) assert ( processor.list_reservations( datetime.datetime.fromtimestamp(1000000000), datetime.datetime.fromtimestamp(1000010000) ) == results ) list_reservations.assert_called_once_with( 'proj', 'p0', 'start_time < 1000010000 AND end_time > 1000000000' )
def test_get_schedule_filter_by_time_slot(list_time_slots): results = [ quantum.QuantumTimeSlot( processor_name='potofgold', start_time=Timestamp(seconds=1000020000), end_time=Timestamp(seconds=1000040000), time_slot_type=quantum.QuantumTimeSlot.TimeSlotType.MAINTENANCE, maintenance_config=quantum.QuantumTimeSlot.MaintenanceConfig( title='Testing', description='Testing some new configuration.'), ) ] list_time_slots.return_value = results processor = cg.EngineProcessor('proj', 'p0', EngineContext()) assert (processor.get_schedule( datetime.datetime.fromtimestamp(1000000000), datetime.datetime.fromtimestamp(1000050000), quantum.QuantumTimeSlot.TimeSlotType.MAINTENANCE, ) == results) list_time_slots.assert_called_once_with( 'proj', 'p0', 'start_time < 1000050000 AND end_time > 1000000000 AND ' + 'time_slot_type = MAINTENANCE', )
def test_expected_recovery_time(): processor = cg.EngineProcessor('a', 'p', EngineContext(), _processor=qtypes.QuantumProcessor()) assert not processor.expected_recovery_time() processor = cg.EngineProcessor( 'a', 'p', EngineContext(), _processor=qtypes.QuantumProcessor( expected_recovery_time=qtypes.timestamp_pb2.Timestamp( seconds=1581515101)), ) assert processor.expected_recovery_time() == datetime.datetime( 2020, 2, 12, 13, 45, 1)
def test_get_missing_device(): processor = cg.EngineProcessor('a', 'p', EngineContext(), _processor=quantum.QuantumProcessor()) with pytest.raises(ValueError, match='device specification'): _ = processor.get_device(gate_sets=[_GATE_SET])
def test_current_calibration(get_current_calibration): get_current_calibration.return_value = _CALIBRATION processor = cg.EngineProcessor('a', 'p', EngineContext()) calibration = processor.get_current_calibration() assert calibration.timestamp == 1562544000021 assert set(calibration.keys()) == {'xeb', 't1', 'globalMetric'} get_current_calibration.assert_called_once_with('a', 'p')
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'
def test_delete(delete_program): program = cg.EngineProgram('a', 'b', EngineContext()) program.delete() delete_program.assert_called_with('a', 'b', delete_jobs=False) program.delete(delete_jobs=True) delete_program.assert_called_with('a', 'b', delete_jobs=True)
def test_get_circuit_unsupported_program_type(get_program): program = cg.EngineProgram('a', 'b', EngineContext()) get_program.return_value = qtypes.QuantumProgram(code=qtypes.any_pb2.Any( type_url='type.googleapis.com/unknown.proto')) with pytest.raises(ValueError, match='unknown.proto'): program.get_circuit()
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')
def test_get_circuit_v2_unknown_gateset(get_program): program = cg.EngineProgram('a', 'b', EngineContext()) get_program.return_value = qtypes.QuantumProgram(code=_to_any( v2.program_pb2.Program(language=v2.program_pb2.Language( gate_set="BAD_GATESET")))) with pytest.raises(ValueError, match='BAD_GATESET'): program.get_circuit()