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.
14from typing import Any, Dict, Optional, Union
16import boto3
17from braket.annealing.problem import Problem
18from braket.aws.aws_qpu_arns import AwsQpuArns
19from braket.aws.aws_quantum_task import AwsQuantumTask
20from braket.aws.aws_session import AwsSession
21from braket.circuits import Circuit
22from braket.devices.device import Device
25class AwsQpu(Device):
26 """
27 Amazon Braket implementation of a Quantum Processing Unit (QPU).
28 Use this class to retrieve the latest metadata about the QPU, and to run a quantum task on the
29 QPU.
30 """
32 QPU_REGIONS = {
33 AwsQpuArns.RIGETTI: ["us-west-1"],
34 AwsQpuArns.IONQ: ["us-east-1"],
35 AwsQpuArns.DWAVE: ["us-west-2"],
36 }
38 def __init__(self, arn: str, aws_session=None):
39 """
40 Args:
41 arn (str): The ARN of the QPU, for example, "arn:aws:aqx:::qpu:ionq"
42 aws_session (AwsSession, optional) aws_session: An AWS session object. Default = None.
44 Raises:
45 ValueError: If an unknown `arn` is specified.
47 Note:
48 QPUs are physically located in specific AWS Regions. In some cases, the current
49 `aws_session` connects to a Region other than the Region in which the QPU is
50 physically located. When this occurs, a cloned `aws_session` is created for the Region
51 the QPU is located in.
53 See `braket.aws.aws_qpu.AwsQpu.QPU_REGIONS` for the AWS Regions the QPUs are located
54 in.
55 """
56 super().__init__(name=None, status=None, status_reason=None)
57 self._arn = arn
58 self._aws_session = self._aws_session_for_qpu(arn, aws_session)
59 self._properties = None
60 self.refresh_metadata()
62 def run(
63 self,
64 task_specification: Union[Circuit, Problem],
65 s3_destination_folder: AwsSession.S3DestinationFolder,
66 shots: Optional[int] = None,
67 *aws_quantum_task_args,
68 **aws_quantum_task_kwargs,
69 ) -> AwsQuantumTask:
70 """
71 Run a quantum task specification on this quantum device. A task can be a circuit or an
72 annealing problem.
74 Args:
75 task_specification (Union[Circuit, Problem]): Specification of task
76 (circuit or annealing problem) to run on device.
77 s3_destination_folder: The S3 location to save the task's results
78 shots (Optional[int]): The number of times to run the circuit or annealing problem
79 *aws_quantum_task_args: Variable length positional arguments for
80 `braket.aws.aws_quantum_task.AwsQuantumTask.create()`.
81 **aws_quantum_task_kwargs: Variable length keyword arguments for
82 `braket.aws.aws_quantum_task.AwsQuantumTask.create()`.
84 Returns:
85 AwsQuantumTask: An AwsQuantumTask that tracks the execution on the device.
87 Examples:
88 >>> circuit = Circuit().h(0).cnot(0, 1)
89 >>> device = AwsQpu("arn:aws:aqx:::qpu:rigetti")
90 >>> device.run(circuit, ("bucket-foo", "key-bar"))
92 >>> circuit = Circuit().h(0).cnot(0, 1)
93 >>> device = AwsQpu("arn:aws:aqx:::qpu:rigetti")
94 >>> device.run(task_specification=circuit,
95 >>> s3_destination_folder=("bucket-foo", "key-bar"))
97 >>> problem = Problem(
98 >>> ProblemType.ISING,
99 >>> linear={1: 3.14},
100 >>> quadratic={(1, 2): 10.08},
101 >>> )
102 >>> device = AwsQpu("arn:aws:aqx:::qpu:d-wave")
103 >>> device.run(problem, ("bucket-foo", "key-bar"),
104 >>> backend_parameters = {"dWaveParameters": {"postprocessingType": "SAMPLING"}})
106 See Also:
107 `braket.aws.aws_quantum_task.AwsQuantumTask.create()`
108 """
110 # TODO: Restrict execution to compatible task types
111 return AwsQuantumTask.create(
112 self._aws_session,
113 self._arn,
114 task_specification,
115 s3_destination_folder,
116 shots,
117 *aws_quantum_task_args,
118 **aws_quantum_task_kwargs,
119 )
121 def refresh_metadata(self) -> None:
122 """
123 Refresh the `AwsQpu` object with the most recent QPU metadata.
124 """
125 qpu_metadata = self._aws_session.get_qpu_metadata(self._arn)
126 self._name = qpu_metadata.get("name")
127 self._status = qpu_metadata.get("status")
128 self._status_reason = qpu_metadata.get("statusReason")
129 qpu_properties = qpu_metadata.get("properties")
130 self._properties = (
131 qpu_properties.get("annealingModelProperties", {}).get("dWaveProperties")
132 if "annealingModelProperties" in qpu_properties
133 else qpu_properties.get("gateModelProperties")
134 )
136 @property
137 def arn(self) -> str:
138 """str: Return the ARN of the QPU"""
139 return self._arn
141 @property
142 # TODO: Add a link to the boto3 docs
143 def properties(self) -> Dict[str, Any]:
144 """Dict[str, Any]: Return the QPU properties"""
145 return self._properties
147 def _aws_session_for_qpu(self, qpu_arn: str, aws_session: AwsSession) -> AwsSession:
148 """
149 Get an AwsSession for the QPU ARN. QPUs are physically located in specific AWS Regions.
150 The AWS sessions should connect to the Region that the QPU is located in.
152 See `braket.aws.aws_qpu.AwsQpu.QPU_REGIONS` for the AWS Regions the QPUs are located in.
153 """
155 qpu_regions = AwsQpu.QPU_REGIONS.get(qpu_arn, [])
156 if not qpu_regions:
157 raise ValueError(f"Unknown QPU {qpu_arn} was supplied.")
159 if aws_session:
160 if aws_session.boto_session.region_name in qpu_regions:
161 return aws_session
162 else:
163 creds = aws_session.boto_session.get_credentials()
164 boto_session = boto3.Session(
165 aws_access_key_id=creds.access_key,
166 aws_secret_access_key=creds.secret_key,
167 aws_session_token=creds.token,
168 region_name=qpu_regions[0],
169 )
170 return AwsSession(boto_session=boto_session)
171 else:
172 boto_session = boto3.Session(region_name=qpu_regions[0])
173 return AwsSession(boto_session=boto_session)
175 def __repr__(self):
176 return "QPU('name': {}, 'arn': {})".format(self.name, self.arn)
178 def __eq__(self, other):
179 if isinstance(other, AwsQpu):
180 return self.arn == other.arn
181 return NotImplemented