Beispiel #1
0
    def get_device(self) -> 'cirq.Device':
        """Return a `cg.SerializableDevice` for the specified processor_id.

        This method presumes the GOOGLE_CLOUD_PROJECT environment
        variable is set to establish a connection to the cloud service.
        """
        return cg.get_engine_device(self.processor_id)
Beispiel #2
0
def test_get_engine_device(get_processor):
    device_spec = _to_any(
        Merge(
            """
valid_gate_sets: [{
    name: 'test_set',
    valid_gates: [{
        id: 'x',
        number_of_qubits: 1,
        gate_duration_picos: 1000,
        valid_targets: ['1q_targets']
    }]
}],
valid_qubits: ['0_0', '1_1'],
valid_targets: [{
    name: '1q_targets',
    target_ordering: SYMMETRIC,
    targets: [{
        ids: ['0_0']
    }]
}]
""",
            v2.device_pb2.DeviceSpecification(),
        ))

    gate_set = cg.SerializableGateSet(
        gate_set_name='x_gate_set',
        serializers=[
            cg.GateOpSerializer(gate_type=cirq.XPowGate,
                                serialized_gate_id='x',
                                args=[])
        ],
        deserializers=[
            cg.GateOpDeserializer(serialized_gate_id='x',
                                  gate_constructor=cirq.XPowGate,
                                  args=[])
        ],
    )

    get_processor.return_value = qtypes.QuantumProcessor(
        device_spec=device_spec)
    device = cirq_google.get_engine_device('rainbow',
                                           'project',
                                           gatesets=[gate_set])
    assert set(device.qubits) == {cirq.GridQubit(0, 0), cirq.GridQubit(1, 1)}
    device.validate_operation(cirq.X(cirq.GridQubit(0, 0)))
    with pytest.raises(ValueError):
        device.validate_operation(cirq.X(cirq.GridQubit(1, 2)))
    with pytest.raises(ValueError):
        device.validate_operation(cirq.Y(cirq.GridQubit(0, 0)))
Beispiel #3
0
def test_get_engine_device(get_processor):
    device_spec = util.pack_any(
        Merge(
            """
valid_qubits: "0_0"
valid_qubits: "1_1"
valid_qubits: "2_2"
valid_targets {
  name: "2_qubit_targets"
  target_ordering: SYMMETRIC
  targets {
    ids: "0_0"
    ids: "1_1"
  }
}
valid_gates {
  gate_duration_picos: 1000
  cz {
  }
}
valid_gates {
  phased_xz {
  }
}
""",
            v2.device_pb2.DeviceSpecification(),
        ))

    get_processor.return_value = quantum.QuantumProcessor(
        device_spec=device_spec)
    device = cirq_google.get_engine_device('rainbow', 'project')
    assert device.metadata.qubit_set == frozenset(
        [cirq.GridQubit(0, 0),
         cirq.GridQubit(1, 1),
         cirq.GridQubit(2, 2)])
    device.validate_operation(cirq.X(cirq.GridQubit(2, 2)))
    device.validate_operation(
        cirq.CZ(cirq.GridQubit(0, 0), cirq.GridQubit(1, 1)))
    with pytest.raises(ValueError):
        device.validate_operation(cirq.X(cirq.GridQubit(1, 2)))
    with pytest.raises(ValueError):
        device.validate_operation(cirq.H(cirq.GridQubit(0, 0)))
    with pytest.raises(ValueError):
        device.validate_operation(
            cirq.CZ(cirq.GridQubit(1, 1), cirq.GridQubit(2, 2)))
Beispiel #4
0
def get_qcs_objects_for_notebook(
        project_id: Optional[str] = None,
        processor_id: Optional[str] = None) -> QCSObjectsForNotebook:
    """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.
    """

    # Converting empty strings to None for form field inputs
    if project_id == "":
        project_id = None
    if processor_id == "":
        processor_id = None

    google_cloud_signin_failed: bool = False
    if project_id is None:
        if 'GOOGLE_CLOUD_PROJECT' not in os.environ:
            print(
                "No project_id provided and environment variable GOOGLE_CLOUD_PROJECT not set."
            )
            google_cloud_signin_failed = True
    else:  # pragma: no cover
        os.environ['GOOGLE_CLOUD_PROJECT'] = project_id

        # Following code runs the user through the Colab OAuth process.

        # Checks for Google Application Default Credentials and runs
        # 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

        in_colab = False
        try:
            from IPython import get_ipython

            in_colab = 'google.colab' in str(get_ipython())

            if in_colab:
                from google.colab import auth

                print("Getting OAuth2 credentials.")
                print("Press enter after entering the verification code.")
                auth.authenticate_user(clear_output=False)
                print("Authentication complete.")
            else:
                print("Notebook isn't executed with Colab, assuming "
                      "Application Default Credentials are setup.")
        except:
            pass

        # End of Google Colab Authentication segment

    device: cirq.Device
    sampler: Union[PhasedFSimEngineSimulator, QuantumEngineSampler]
    if google_cloud_signin_failed or processor_id is None:
        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
    else:  # pragma: no cover
        device = get_engine_device(processor_id)
        sampler = get_engine_sampler(processor_id, gate_set_name="sqrt_iswap")
    return QCSObjectsForNotebook(
        device=device,
        sampler=sampler,
        signed_in=not google_cloud_signin_failed,
    )