Example #1
0
def test_remove_reservation_cancel(cancel_reservation, get_reservation):
    name = 'projects/proj/processors/p0/reservations/rid'
    now = int(datetime.datetime.now().timestamp())
    result = qtypes.QuantumReservation(
        name=name,
        start_time=Timestamp(seconds=now + 10),
        end_time=Timestamp(seconds=now + 3610),
        whitelisted_users=['*****@*****.**'],
    )
    get_reservation.return_value = result
    cancel_reservation.return_value = result
    processor = cg.EngineProcessor(
        'proj', 'p0', EngineContext(),
        qtypes.QuantumProcessor(schedule_frozen_period=Duration(seconds=10000)))
    assert processor.remove_reservation('rid') == result
    cancel_reservation.assert_called_once_with('proj', 'p0', 'rid')
Example #2
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]
    }
Example #3
0
def test_create_reservation(create_reservation):
    name = 'projects/proj/processors/p0/reservations/psherman-wallaby-way'
    result = qtypes.QuantumReservation(
        name=name,
        start_time=Timestamp(seconds=1000000000),
        end_time=Timestamp(seconds=1000003600),
        whitelisted_users=['*****@*****.**'],
    )
    create_reservation.return_value = result
    processor = cg.EngineProcessor('proj', 'p0', EngineContext())
    assert processor.create_reservation(
        datetime.datetime.fromtimestamp(1000000000),
        datetime.datetime.fromtimestamp(1000003600), ['*****@*****.**'])
    create_reservation.assert_called_once_with(
        'proj', 'p0', datetime.datetime.fromtimestamp(1000000000),
        datetime.datetime.fromtimestamp(1000003600), ['*****@*****.**'])
def test_update_reservation(update_reservation):
    name = 'projects/proj/processors/p0/reservations/rid'
    result = qtypes.QuantumReservation(
        name=name,
        start_time=Timestamp(seconds=1000000000),
        end_time=Timestamp(seconds=1000003600),
        whitelisted_users=['*****@*****.**'],
    )
    start = datetime.datetime.fromtimestamp(1000000000)
    end = datetime.datetime.fromtimestamp(1000003600)
    update_reservation.return_value = result
    processor = cg.EngineProcessor('proj', 'p0', EngineContext())
    assert processor.update_reservation('rid', start, end, ['*****@*****.**']) == result
    update_reservation.assert_called_once_with(
        'proj', 'p0', 'rid', start=start, end=end, whitelisted_users=['*****@*****.**']
    )
Example #5
0
def test_list_jobs(list_jobs):
    job1 = qtypes.QuantumJob(name='projects/proj/programs/prog1/jobs/job1')
    job2 = qtypes.QuantumJob(name='projects/proj/programs/prog2/jobs/job2')
    list_jobs.return_value = [job1, job2]

    ctx = EngineContext()
    result = cg.Engine(project_id='proj', context=ctx).list_jobs()
    list_jobs.assert_called_once_with('proj',
                                      None,
                                      created_after=None,
                                      created_before=None,
                                      has_labels=None,
                                      execution_states=None)
    assert [(j.project_id, j.program_id, j.job_id, j.context, j._job)
            for j in result] == [('proj', 'prog1', 'job1', ctx, job1),
                                 ('proj', 'prog2', 'job2', ctx, job2)]
def test_run_batch_no_sweeps(create_job):
    # Running with no sweeps is fine. Uses program's batch size to create
    # proper empty sweeps.
    create_job.return_value = ('kittens', qtypes.QuantumJob())
    program = cg.EngineProgram(
        'my-meow',
        'my-meow',
        _program=qtypes.QuantumProgram(code=_BATCH_PROGRAM_V2),
        context=EngineContext(),
        result_type=ResultType.Batch,
    )
    job = program.run_batch(job_id='steve', repetitions=10, processor_ids=['lazykitty'])
    assert job._job == qtypes.QuantumJob()
    batch_run_context = v2.batch_pb2.BatchRunContext()
    create_job.call_args[1]['run_context'].Unpack(batch_run_context)
    assert len(batch_run_context.run_contexts) == 1
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)},
    )
def test_remove_labels(remove_program_labels):
    program = cg.EngineProgram(
        'a', 'b', EngineContext(), _program=qtypes.QuantumProgram(labels={'a': '1', 'b': '1'})
    )
    assert program.labels() == {'a': '1', 'b': '1'}

    remove_program_labels.return_value = qtypes.QuantumProgram(
        labels={
            'b': '1',
        }
    )
    assert program.remove_labels(['a']).labels() == {'b': '1'}
    remove_program_labels.assert_called_with('a', 'b', ['a'])

    remove_program_labels.return_value = qtypes.QuantumProgram(labels={})
    assert program.remove_labels(['a', 'b', 'c']).labels() == {}
    remove_program_labels.assert_called_with('a', 'b', ['a', 'b', 'c'])
Example #9
0
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_list_calibrations(list_calibrations):
    list_calibrations.return_value = [_CALIBRATION]
    processor = cg.EngineProcessor('a', 'p', EngineContext())
    assert [c.timestamp for c in processor.list_calibrations()] == [1562544000021]
    list_calibrations.assert_called_with('a', 'p', '')
    assert [c.timestamp for c in processor.list_calibrations(1562500000000)] == [1562544000021]
    list_calibrations.assert_called_with('a', 'p', 'timestamp >= 1562500000000')
    assert [
        c.timestamp for c in processor.list_calibrations(latest_timestamp_seconds=1562600000000)
    ] == [1562544000021]
    list_calibrations.assert_called_with('a', 'p', 'timestamp <= 1562600000000')
    assert [c.timestamp for c in processor.list_calibrations(1562500000000, 1562600000000)] == [
        1562544000021
    ]
    list_calibrations.assert_called_with(
        'a', 'p', 'timestamp >= 1562500000000 AND timestamp <= 1562600000000'
    )
Example #11
0
def test_set_labels(set_job_labels):
    job = cg.EngineJob('a', 'b', 'steve', EngineContext())
    set_job_labels.return_value = qtypes.QuantumJob(labels={
        'a': '1',
        'b': '1'
    })
    assert job.set_labels({
        'a': '1',
        'b': '1'
    }).labels() == {
        'a': '1',
        'b': '1'
    }
    set_job_labels.assert_called_with('a', 'b', 'steve', {'a': '1', 'b': '1'})

    set_job_labels.return_value = qtypes.QuantumJob()
    assert job.set_labels({}).labels() == {}
    set_job_labels.assert_called_with('a', 'b', 'steve', {})
Example #12
0
def test_set_labels(set_program_labels):
    program = cg.EngineProgram('a', 'b', EngineContext())
    set_program_labels.return_value = qtypes.QuantumProgram(labels={
        'a': '1',
        'b': '1'
    })
    assert program.set_labels({
        'a': '1',
        'b': '1'
    }).labels() == {
        'a': '1',
        'b': '1'
    }
    set_program_labels.assert_called_with('a', 'b', {'a': '1', 'b': '1'})

    set_program_labels.return_value = qtypes.QuantumProgram()
    assert program.set_labels({}).labels() == {}
    set_program_labels.assert_called_with('a', 'b', {})
def test_list_reservations_time_filter_behavior(list_reservations):
    list_reservations.return_value = []
    processor = cg.EngineProcessor('proj', 'p0', EngineContext())

    now = int(datetime.datetime.now().timestamp())
    in_two_weeks = int(
        (datetime.datetime.now() + datetime.timedelta(weeks=2)).timestamp())
    processor.list_reservations()
    list_reservations.assert_called_with(
        'proj', 'p0', f'start_time < {in_two_weeks} AND end_time > {now}')

    with pytest.raises(ValueError, match='from_time of type'):
        processor.list_reservations(from_time=object())

    with pytest.raises(ValueError, match='to_time of type'):
        processor.list_reservations(to_time=object())

    processor.list_reservations(from_time=None, to_time=None)
    list_reservations.assert_called_with('proj', 'p0', '')

    processor.list_reservations(from_time=datetime.timedelta(0), to_time=None)
    list_reservations.assert_called_with('proj', 'p0', f'end_time > {now}')

    processor.list_reservations(from_time=datetime.timedelta(seconds=200),
                                to_time=None)
    list_reservations.assert_called_with('proj', 'p0',
                                         f'end_time > {now + 200}')

    test_timestamp = datetime.datetime.utcfromtimestamp(52)
    utc_ts = int(test_timestamp.timestamp())
    processor.list_reservations(from_time=test_timestamp, to_time=None)
    list_reservations.assert_called_with('proj', 'p0', f'end_time > {utc_ts}')

    processor.list_reservations(from_time=None, to_time=datetime.timedelta(0))
    list_reservations.assert_called_with('proj', 'p0', f'start_time < {now}')

    processor.list_reservations(from_time=None,
                                to_time=datetime.timedelta(seconds=200))
    list_reservations.assert_called_with('proj', 'p0',
                                         f'start_time < {now + 200}')

    processor.list_reservations(from_time=None, to_time=test_timestamp)
    list_reservations.assert_called_with('proj', 'p0',
                                         f'start_time < {utc_ts}')
Example #14
0
def test_remove_labels(remove_job_labels):
    job = cg.EngineJob('a',
                       'b',
                       'steve',
                       EngineContext(),
                       _job=qtypes.QuantumJob(labels={
                           'a': '1',
                           'b': '1'
                       }))
    assert job.labels() == {'a': '1', 'b': '1'}

    remove_job_labels.return_value = qtypes.QuantumJob(labels={
        'b': '1',
    })
    assert job.remove_labels(['a']).labels() == {'b': '1'}
    remove_job_labels.assert_called_with('a', 'b', 'steve', ['a'])

    remove_job_labels.return_value = qtypes.QuantumJob(labels={})
    assert job.remove_labels(['a', 'b', 'c']).labels() == {}
    remove_job_labels.assert_called_with('a', 'b', 'steve', ['a', 'b', 'c'])
Example #15
0
def test_list_reservations_time_filter_behavior(list_reservations):
    list_reservations.return_value = []
    processor = cg.EngineProcessor('proj', 'p0', EngineContext())

    processor.list_reservations()
    list_reservations.assert_called_with(
        'proj', 'p0',
        f'start_time < {100_000 + 60*60*24*14} AND end_time > {100_000}')

    with pytest.raises(ValueError, match='from_time of type'):
        processor.list_reservations(from_time=object())

    with pytest.raises(ValueError, match='to_time of type'):
        processor.list_reservations(to_time=object())

    processor.list_reservations(from_time=None, to_time=None)
    list_reservations.assert_called_with('proj', 'p0', '')

    processor.list_reservations(from_time=datetime.timedelta(0), to_time=None)
    list_reservations.assert_called_with('proj', 'p0', f'end_time > {100_000}')

    processor.list_reservations(from_time=datetime.timedelta(seconds=200),
                                to_time=None)
    list_reservations.assert_called_with('proj', 'p0', f'end_time > {100_200}')

    processor.list_reservations(
        from_time=datetime.datetime.utcfromtimestamp(52), to_time=None)
    list_reservations.assert_called_with('proj', 'p0', f'end_time > {52}')

    processor.list_reservations(from_time=None, to_time=datetime.timedelta(0))
    list_reservations.assert_called_with('proj', 'p0',
                                         f'start_time < {100_000}')

    processor.list_reservations(from_time=None,
                                to_time=datetime.timedelta(seconds=200))
    list_reservations.assert_called_with('proj', 'p0',
                                         f'start_time < {100_200}')

    processor.list_reservations(from_time=None,
                                to_time=datetime.datetime.utcfromtimestamp(52))
    list_reservations.assert_called_with('proj', 'p0', f'start_time < {52}')
Example #16
0
def test_get_schedule_time_filter_behavior(list_time_slots):
    list_time_slots.return_value = []
    processor = cg.EngineProcessor('proj', 'p0', EngineContext())

    now = int(datetime.datetime.now().timestamp())
    processor.get_schedule()
    list_time_slots.assert_called_with(
        'proj', 'p0', f'start_time < {now + 60*60*24*14} AND end_time > {now}')

    with pytest.raises(ValueError, match='from_time of type'):
        processor.get_schedule(from_time=object())

    with pytest.raises(ValueError, match='to_time of type'):
        processor.get_schedule(to_time=object())

    processor.get_schedule(from_time=None, to_time=None)
    list_time_slots.assert_called_with('proj', 'p0', '')

    processor.get_schedule(from_time=datetime.timedelta(0), to_time=None)
    list_time_slots.assert_called_with('proj', 'p0', f'end_time > {now}')

    processor.get_schedule(from_time=datetime.timedelta(seconds=200),
                           to_time=None)
    list_time_slots.assert_called_with('proj', 'p0', f'end_time > {now + 200}')

    test_timestamp = datetime.datetime.utcfromtimestamp(52)
    utc_ts = int(test_timestamp.timestamp())
    processor.get_schedule(from_time=test_timestamp, to_time=None)
    list_time_slots.assert_called_with('proj', 'p0', f'end_time > {utc_ts}')

    processor.get_schedule(from_time=None, to_time=datetime.timedelta(0))
    list_time_slots.assert_called_with('proj', 'p0', f'start_time < {now}')

    processor.get_schedule(from_time=None,
                           to_time=datetime.timedelta(seconds=200))
    list_time_slots.assert_called_with('proj', 'p0',
                                       f'start_time < {now + 200}')

    processor.get_schedule(from_time=None, to_time=test_timestamp)
    list_time_slots.assert_called_with('proj', 'p0', f'start_time < {utc_ts}')
Example #17
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'
Example #18
0
def test_list_reservation(list_reservations):
    name = 'projects/proj/processors/p0/reservations/rid'
    results = [
        qtypes.QuantumReservation(
            name=name,
            start_time=Timestamp(seconds=1000000000),
            end_time=Timestamp(seconds=1000003600),
            whitelisted_users=['*****@*****.**'],
        ),
        qtypes.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')
Example #19
0
def test_get_schedule_filter_by_time_slot(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.',
            ),
        )
    ]
    list_time_slots.return_value = results
    processor = cg.EngineProcessor('proj', 'p0', EngineContext())

    assert processor.get_schedule(
        datetime.datetime.fromtimestamp(1000000000),
        datetime.datetime.fromtimestamp(1000050000),
        qenums.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_missing_latest_calibration(get_current_calibration):
    get_current_calibration.return_value = None
    processor = cg.EngineProcessor('a', 'p', EngineContext())
    assert not processor.get_current_calibration()
    get_current_calibration.assert_called_once_with('a', 'p')
def test_get_missing_device():
    processor = cg.EngineProcessor('a', 'p', EngineContext(), _processor=qtypes.QuantumProcessor())
    with pytest.raises(ValueError, match='device specification'):
        _ = processor.get_device(gate_sets=[_GATE_SET])
def test_engine():
    processor = cg.EngineProcessor('a', 'p', EngineContext())
    assert processor.engine().project_id == 'a'
def test_str():
    program = cg.EngineProgram('my-proj', 'my-prog', EngineContext())
    assert str(program) == 'EngineProgram(project_id=\'my-proj\', program_id=\'my-prog\')'
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_labels():
    program = cg.EngineProgram(
        'a', 'b', EngineContext(), _program=qtypes.QuantumProgram(labels={'t': '1'})
    )
    assert program.labels() == {'t': '1'}
def test_get_job():
    program = cg.EngineProgram('a', 'b', EngineContext())
    assert program.get_job('c').job_id == 'c'
def test_engine():
    program = cg.EngineProgram('a', 'b', EngineContext())
    assert program.engine().project_id == 'a'
def test_run_in_batch_mode():
    program = cg.EngineProgram('no-meow', 'no-meow', EngineContext(), result_type=ResultType.Batch)
    with pytest.raises(ValueError, match='Please use run_batch'):
        _ = program.run_sweep(
            repetitions=1, processor_ids=['lazykitty'], params=cirq.Points('cats', [1.0, 2.0, 3.0])
        )
def test_str():
    processor = cg.EngineProcessor('a', 'p', EngineContext())
    assert str(processor) == 'EngineProcessor(project_id=\'a\', processor_id=\'p\')'
def test_run_batch_not_in_batch_mode():
    program = cg.EngineProgram('no-meow', 'no-meow', EngineContext())
    resolver_list = [cirq.Points('cats', [1.0, 2.0, 3.0]), cirq.Points('cats', [4.0, 5.0, 6.0])]
    with pytest.raises(ValueError, match='Can only use run_batch'):
        _ = program.run_batch(repetitions=1, processor_ids=['lazykitty'], params_list=resolver_list)