Example #1
0
def test_get_engine(build):
    # Default project id present.
    with mock.patch('google.auth.default', lambda: (None, 'project!')):
        eng = cirq_google.get_engine()
        assert eng.project_id == 'project!'

    # Nothing present.
    with mock.patch('google.auth.default', lambda: (None, None)):
        with pytest.raises(EnvironmentError, match='GOOGLE_CLOUD_PROJECT'):
            _ = cirq_google.get_engine()
        _ = cirq_google.get_engine('project!')
Example #2
0
def test_get_engine(build):
    # Default project id present.
    with mock.patch.dict(
            os.environ,
        {
            'GOOGLE_CLOUD_PROJECT': 'project!',
        },
            clear=True,
    ):
        eng = cirq_google.get_engine()
        assert eng.project_id == 'project!'

    # Nothing present.
    with mock.patch.dict(os.environ, {}, clear=True):
        with pytest.raises(EnvironmentError, match='GOOGLE_CLOUD_PROJECT'):
            _ = cirq_google.get_engine()
        _ = cirq_google.get_engine('project!')
Example #3
0
def get_available_processors(processor_names: List[str]):
    """Returns a list of available processors.

    Checks the reservation status of the processors and returns a list of
    processors that are available to run on at the present time.

    Args:
        processor_names: A list of processor names which are keys from QUANTUM_PROCESSORS.
    """
    project_id = os.environ['GOOGLE_CLOUD_PROJECT']
    engine = cg.get_engine()
    available_processors = []
    current_time = _get_current_time()
    for processor_name in processor_names:
        processor_id = get_processor_id_by_device_name(processor_name)
        if processor_id is None:
            # Skip the check if this is a simulator.
            continue
        processor = engine.get_processor(processor_id)
        for time_slot in processor.get_schedule():
            try:
                time_slot = cg.EngineTimeSlot.from_proto(time_slot)
            # Parsing the end_time of the last time range in the schedule might give throw an error.
            # TODO: remove this check once it is fixed in cirq.
            except ValueError as e:
                continue
            # Ignore time slots that do not contain the current time.
            if time_slot.start_time < current_time < time_slot.end_time:
                # Time slots need to be either in OPEN_SWIM or reserved by the
                # current project to be considered available.
                if (time_slot.slot_type
                    == enums.QuantumTimeSlot.TimeSlotType.OPEN_SWIM
                ) or (time_slot.slot_type
                      == enums.QuantumTimeSlot.TimeSlotType.RESERVATION and
                      time_slot.project_id == project_id):
                    available_processors.append(processor_name)
    return available_processors
Example #4
0
 def get_processor(self) -> 'cg.EngineProcessor':
     """Return a `cg.EngineProcessor` for the specified processor_id."""
     engine = cg.get_engine()
     return engine.get_processor(self.processor_id)
Example #5
0
def get_qcs_objects_for_notebook(
    project_id: Optional[str] = None,
    processor_id: Optional[str] = None
) -> QCSObjectsForNotebook:  # pragma: nocover
    """Authenticates on Google Cloud, can return a Device and Simulator.

    Args:
        project_id: Optional explicit Google Cloud project id. Otherwise,
            this defaults to the environment variable GOOGLE_CLOUD_PROJECT.
            By using an environment variable, you can avoid hard-coding
            personal project IDs in shared code.
        processor_id: Engine processor ID (from Cloud console or
            ``Engine.list_processors``).

    Returns:
        An instance of DeviceSamplerInfo.
    """

    # Check for Google Application Default Credentials and run
    # interactive login if the notebook is executed in Colab. In
    # case the notebook is executed in Jupyter notebook or other
    # IPython runtimes, no interactive login is provided, it is
    # assumed that the `GOOGLE_APPLICATION_CREDENTIALS` env var is
    # set or `gcloud auth application-default login` was executed
    # already. For more information on using Application Default Credentials
    # see https://cloud.google.com/docs/authentication/production
    try:
        from google.colab import auth
    except ImportError:
        print(
            "Not running in a colab kernel. Will use Application Default Credentials."
        )
    else:
        print("Getting OAuth2 credentials.")
        print("Press enter after entering the verification code.")
        try:
            auth.authenticate_user(clear_output=False)
            print("Authentication complete.")
        except Exception as exc:
            print(f"Authentication failed: {exc}")

    # Attempt to connect to the Quantum Engine API, and use a simulator if unable to connect.
    sampler: Union[PhasedFSimEngineSimulator, QuantumEngineSampler]
    try:
        engine = get_engine(project_id)
        if processor_id:
            processor = engine.get_processor(processor_id)
        else:
            processors = engine.list_processors()
            if not processors:
                raise ValueError("No processors available.")
            processor = processors[0]
            print(
                f"Available processors: {[p.processor_id for p in processors]}"
            )
            print(f"Using processor: {processor.processor_id}")
        device = processor.get_device()
        sampler = processor.get_sampler()
        signed_in = True
    except Exception as exc:
        print(f"Unable to connect to quantum engine: {exc}")
        print("Using a noisy simulator.")
        sampler = PhasedFSimEngineSimulator.create_with_random_gaussian_sqrt_iswap(
            mean=SQRT_ISWAP_INV_PARAMETERS,
            sigma=PhasedFSimCharacterization(theta=0.01,
                                             zeta=0.10,
                                             chi=0.01,
                                             gamma=0.10,
                                             phi=0.02),
        )
        device = Sycamore
        signed_in = False

    return QCSObjectsForNotebook(device=device,
                                 sampler=sampler,
                                 signed_in=signed_in)