def test_no_calibration_from_job():
    proc = SimulatedLocalProcessor(processor_id='test_proc')
    engine = SimulatedLocalEngine([proc])
    job = engine.get_processor('test_proc').run_sweep(cirq.Circuit(),
                                                      params={},
                                                      repetitions=100)
    assert job.get_processor() == proc
    assert job.get_calibration() is None
def test_list_processor():
    processor1 = ProgramDictProcessor(programs=[], processor_id='proc')
    processor2 = ProgramDictProcessor(programs=[], processor_id='crop')
    engine = SimulatedLocalEngine([processor1, processor2])
    assert engine.get_processor('proc') == processor1
    assert engine.get_processor('crop') == processor2
    assert engine.get_processor('proc').engine() == engine
    assert engine.get_processor('crop').engine() == engine
    assert set(engine.list_processors()) == {processor1, processor2}
def test_get_calibration_from_job():
    cal_proto = v2.metrics_pb2.MetricsSnapshot(timestamp_ms=10000)
    cal = cirq_google.Calibration(cal_proto)
    proc = SimulatedLocalProcessor(processor_id='test_proc',
                                   calibrations={10000: cal})
    engine = SimulatedLocalEngine([proc])
    job = engine.get_processor('test_proc').run_sweep(cirq.Circuit(),
                                                      params={},
                                                      repetitions=100)
    assert job.get_processor() == proc
    assert job.get_calibration() == cal
def test_sampler():
    engine = SimulatedLocalEngine(
        [SimulatedLocalProcessor(processor_id='tester')])
    q = cirq.GridQubit(5, 4)
    circuit = cirq.Circuit(
        cirq.X(q)**sympy.Symbol('t'), cirq.measure(q, key='m'))
    sweep = cirq.Points(key='t', points=[1, 0])
    results = engine.get_sampler('tester').run_sweep(circuit,
                                                     params=sweep,
                                                     repetitions=100)
    assert np.all(results[0].measurements['m'] == 1)
    assert np.all(results[1].measurements['m'] == 0)
def test_get_programs():
    program1 = NothingProgram([cirq.Circuit()], None)
    job1 = NothingJob(job_id='test',
                      processor_id='test1',
                      parent_program=program1,
                      repetitions=100,
                      sweeps=[])
    program1.add_job('jerb', job1)
    job1.add_labels({'color': 'blue'})

    program2 = NothingProgram([cirq.Circuit()], None)
    job2 = NothingJob(job_id='test',
                      processor_id='test2',
                      parent_program=program2,
                      repetitions=100,
                      sweeps=[])
    program2.add_job('jerb2', job2)
    job2.add_labels({'color': 'red'})

    processor1 = ProgramDictProcessor(programs={'prog1': program1},
                                      processor_id='proc')
    processor2 = ProgramDictProcessor(programs={'prog2': program2},
                                      processor_id='crop')
    engine = SimulatedLocalEngine([processor1, processor2])

    assert engine.get_program('prog1') == program1

    with pytest.raises(KeyError, match='does not exis'):
        _ = engine.get_program('yoyo')

    assert set(engine.list_programs()) == {program1, program2}
    assert set(engine.list_jobs()) == {job1, job2}
    assert engine.list_jobs(has_labels={'color': 'blue'}) == [job1]
    assert engine.list_jobs(has_labels={'color': 'red'}) == [job2]
def test_get_processor():
    processor1 = ProgramDictProcessor(programs=[], processor_id='test')
    engine = SimulatedLocalEngine([processor1])
    assert engine.get_processor('test') == processor1
    assert engine.get_processor('test').engine() == engine
    with pytest.raises(KeyError):
        engine.get_processor('abracadabra')
    with pytest.raises(ValueError, match='Invalid processor'):
        engine.get_sampler(processor_id=['a', 'b', 'c'])
def create_noiseless_virtual_engine_from_device(
        processor_id: str, device: cirq.Device) -> SimulatedLocalEngine:
    """Creates an Engine object with a single processor backed by a noiseless simulator.

    Creates a noiseless engine object based on the cirq simulator,
    a default validator, and a provided device.

    Args:
         processor_id: name of the processor to simulate.  This is an arbitrary
             string identifier and does not have to match the processor's name
             in QCS.
         device: A `cirq.Device` to validate circuits against.
    """
    return SimulatedLocalEngine(
        [_create_virtual_processor_from_device(processor_id, device)])
def create_noiseless_virtual_engine_from_proto(
    processor_ids: Union[str, List[str]],
    device_specifications: Union[v2.device_pb2.DeviceSpecification,
                                 List[v2.device_pb2.DeviceSpecification]],
    gate_sets: Optional[Iterable[
        serializable_gate_set.SerializableGateSet]] = None,
) -> SimulatedLocalEngine:
    """Creates a noiseless virtual engine object from a device specification proto.a

    The device specification protocol buffer specifies qubits and gates on the device
    and can be retrieved from a stored "proto.txt" file or from the QCS API.

    Args:
         processor_ids: name of the processor to simulate.  This is an arbitrary
             string identifier and does not have to match the processor's name
             in QCS.  This can be a single string or list of strings.
         device_specifications:  `v2.device_pb2.DeviceSpecification` proto to create
             a validating device from.  This can be a single DeviceSpecification
             or a list of them.  There should be one DeviceSpecification for each
             processor_id.
         gate_sets: Iterable of serializers to use in the processor.  Defaults
             to the FSIM_GATESET.

    Raises:
        ValueError: if processor_ids and device_specifications are not the same length.
    """
    if gate_sets is None:
        gate_sets = [FSIM_GATESET]
    if isinstance(processor_ids, str):
        processor_ids = [processor_ids]
    if isinstance(device_specifications, v2.device_pb2.DeviceSpecification):
        device_specifications = [device_specifications]
    if len(processor_ids) != len(device_specifications):
        raise ValueError(
            'Must provide equal numbers of processor ids and device specifications.'
        )

    processors: List[abstract_local_processor.AbstractLocalProcessor] = []
    for idx in range(len(processor_ids)):
        device = serializable_device.SerializableDevice.from_proto(
            device_specifications[idx], gate_sets)
        processors.append(
            _create_virtual_processor_from_device(processor_ids[idx], device))
    return SimulatedLocalEngine(processors)
def create_noiseless_virtual_engine_from_proto(
    processor_ids: Union[str, List[str]],
    device_specifications: Union[v2.device_pb2.DeviceSpecification,
                                 List[v2.device_pb2.DeviceSpecification]],
    gate_sets: Optional[Iterable[
        serializable_gate_set.SerializableGateSet]] = None,
) -> SimulatedLocalEngine:
    """Creates a noiseless virtual engine object from a device specification proto.

    The device specification protocol buffer specifies qubits and gates on the device
    and can be retrieved from a stored "proto.txt" file or from the QCS API.

    Args:
        processor_ids: names of the processors to simulate.  These are arbitrary
            string identifiers and do not have to match the processors' names
            in QCS.  This can be a single string or list of strings.
        device_specifications:  `v2.device_pb2.DeviceSpecification` proto to create
            validating devices from.  This can be a single DeviceSpecification
            or a list of them.  There should be one DeviceSpecification for each
            processor_id.
        gate_sets: Iterable of serializers to use in the processor.

    Raises:
        ValueError: if processor_ids and device_specifications are not the same length.
    """
    if isinstance(processor_ids, str):
        processor_ids = [processor_ids]
    if isinstance(device_specifications, v2.device_pb2.DeviceSpecification):
        device_specifications = [device_specifications]
    if len(processor_ids) != len(device_specifications):
        raise ValueError(
            'Must provide equal numbers of processor ids and device specifications.'
        )

    return SimulatedLocalEngine(processors=[
        create_noiseless_virtual_processor_from_proto(
            processor_id, device_spec) for device_spec, processor_id in zip(
                device_specifications, processor_ids)
    ])