Coverage for src/braket/aws/aws_qpu.py : 100%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Copyright 2019-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License"). You
4# may not use this file except in compliance with the License. A copy of
5# the License is located at
6#
7# http://aws.amazon.com/apache2.0/
8#
9# or in the "license" file accompanying this file. This file is
10# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11# ANY KIND, either express or implied. See the License for the specific
12# language governing permissions and limitations under the License.
13from typing import Any, Dict, Optional, Union
15import boto3
16from braket.annealing.problem import Problem
17from braket.aws.aws_qpu_arns import AwsQpuArns
18from braket.aws.aws_quantum_task import AwsQuantumTask
19from braket.aws.aws_session import AwsSession
20from braket.circuits import Circuit
21from braket.devices.device import Device
24class AwsQpu(Device):
25 """
26 Amazon Braket implementation of a Quantum Processing Unit (QPU).
27 Use this class to retrieve the latest metadata about the QPU, and to run a quantum task on the
28 QPU.
29 """
31 QPU_REGIONS = {
32 AwsQpuArns.RIGETTI: ["us-west-1"],
33 AwsQpuArns.IONQ: ["us-east-1"],
34 AwsQpuArns.DWAVE: ["us-west-2"],
35 }
37 def __init__(self, arn: str, aws_session=None):
38 """
39 Args:
40 arn (str): The ARN of the QPU, for example, "arn:aws:aqx:::qpu:ionq"
41 aws_session (AwsSession, optional) aws_session: An AWS session object. Default = None.
43 Raises:
44 ValueError: If an unknown `arn` is specified.
46 Note:
47 QPUs are physically located in specific AWS Regions. In some cases, the current
48 `aws_session` connects to a Region other than the Region in which the QPU is
49 physically located. When this occurs, a cloned `aws_session` is created for the Region
50 the QPU is located in.
52 See `braket.aws.aws_qpu.AwsQpu.QPU_REGIONS` for the AWS Regions the QPUs are located
53 in.
54 """
55 super().__init__(name=None, status=None, status_reason=None)
56 self._arn = arn
57 self._aws_session = self._aws_session_for_qpu(arn, aws_session)
58 self._properties = None
59 self.refresh_metadata()
61 def run(
62 self,
63 task_specification: Union[Circuit, Problem],
64 s3_destination_folder: AwsSession.S3DestinationFolder,
65 shots: Optional[int] = None,
66 *aws_quantum_task_args,
67 **aws_quantum_task_kwargs,
68 ) -> AwsQuantumTask:
69 """
70 Run a quantum task specification on this quantum device. A task can be a circuit or an
71 annealing problem. Currently, only circuits are supported in the Private Beta.
73 Args:
74 task_specification (Union[Circuit, Problem]): Specification of task
75 (circuit or annealing problem) to run on device.
76 s3_destination_folder: The S3 location to save the task's results
77 shots (Optional[int]): The number of times to run the circuit or annealing problem
78 *aws_quantum_task_args: Variable length positional arguments for
79 `braket.aws.aws_quantum_task.AwsQuantumTask.create()`.
80 **aws_quantum_task_kwargs: Variable length keyword arguments for
81 `braket.aws.aws_quantum_task.AwsQuantumTask.create()`.
83 Returns:
84 AwsQuantumTask: An AwsQuantumTask that tracks the execution on the device.
86 Examples:
87 >>> circuit = Circuit().h(0).cnot(0, 1)
88 >>> device = AwsQpu("arn:aws:aqx:::qpu:rigetti")
89 >>> device.run(circuit, ("bucket-foo", "key-bar"))
91 >>> circuit = Circuit().h(0).cnot(0, 1)
92 >>> device = AwsQpu("arn:aws:aqx:::qpu:rigetti")
93 >>> device.run(task_specification=circuit,
94 >>> s3_destination_folder=("bucket-foo", "key-bar"))
96 >>> problem = Problem(
97 >>> ProblemType.ISING,
98 >>> linear={1: 3.14},
99 >>> quadratic={(1, 2): 10.08},
100 >>> )
101 >>> device = AwsQpu("arn:aws:aqx:::qpu:d-wave")
102 >>> device.run(problem, ("bucket-foo", "key-bar"),
103 >>> backend_parameters = {"dWaveParameters": {"postprocessingType": "SAMPLING"}})
105 See Also:
106 `braket.aws.aws_quantum_task.AwsQuantumTask.create()`
107 """
109 # TODO: Restrict execution to compatible task types
110 return AwsQuantumTask.create(
111 self._aws_session,
112 self._arn,
113 task_specification,
114 s3_destination_folder,
115 shots,
116 *aws_quantum_task_args,
117 **aws_quantum_task_kwargs,
118 )
120 def refresh_metadata(self) -> None:
121 """
122 Refresh the `AwsQpu` object with the most recent QPU metadata.
123 """
124 qpu_metadata = self._aws_session.get_qpu_metadata(self._arn)
125 self._name = qpu_metadata.get("name")
126 self._status = qpu_metadata.get("status")
127 self._status_reason = qpu_metadata.get("statusReason")
128 qpu_properties = qpu_metadata.get("properties")
129 self._properties = (
130 qpu_properties.get("annealingModelProperties", {}).get("dWaveProperties")
131 if "annealingModelProperties" in qpu_properties
132 else qpu_properties.get("gateModelProperties")
133 )
135 @property
136 def arn(self) -> str:
137 """str: Return the ARN of the QPU"""
138 return self._arn
140 @property
141 # TODO: Add a link to the boto3 docs
142 def properties(self) -> Dict[str, Any]:
143 """Dict[str, Any]: Return the QPU properties"""
144 return self._properties
146 def _aws_session_for_qpu(self, qpu_arn: str, aws_session: AwsSession) -> AwsSession:
147 """
148 Get an AwsSession for the QPU ARN. QPUs are physically located in specific AWS Regions.
149 The AWS sessions should connect to the Region that the QPU is located in.
151 See `braket.aws.aws_qpu.AwsQpu.QPU_REGIONS` for the AWS Regions the QPUs are located in.
152 """
154 qpu_regions = AwsQpu.QPU_REGIONS.get(qpu_arn, [])
155 if not qpu_regions:
156 raise ValueError(f"Unknown QPU {qpu_arn} was supplied.")
158 if aws_session:
159 if aws_session.boto_session.region_name in qpu_regions:
160 return aws_session
161 else:
162 creds = aws_session.boto_session.get_credentials()
163 boto_session = boto3.Session(
164 aws_access_key_id=creds.access_key,
165 aws_secret_access_key=creds.secret_key,
166 aws_session_token=creds.token,
167 region_name=qpu_regions[0],
168 )
169 return AwsSession(boto_session=boto_session)
170 else:
171 boto_session = boto3.Session(region_name=qpu_regions[0])
172 return AwsSession(boto_session=boto_session)
174 def __repr__(self):
175 return "QPU('name': {}, 'arn': {})".format(self.name, self.arn)
177 def __eq__(self, other):
178 if isinstance(other, AwsQpu):
179 return self.arn == other.arn
180 return NotImplemented