Coverage for src/braket/devices/local_simulator.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 functools import singledispatch
15from typing import Set, Union
17import pkg_resources
19from braket.annealing.problem import Problem
20from braket.circuits import Circuit
21from braket.devices.braket_simulator import BraketSimulator
22from braket.devices.device import Device
23from braket.tasks import AnnealingQuantumTaskResult, GateModelQuantumTaskResult
24from braket.tasks.local_quantum_task import LocalQuantumTask
26_simulator_devices = {
27 entry.name: entry for entry in pkg_resources.iter_entry_points("braket.simulators")
28}
31class LocalSimulator(Device):
32 """ A simulator meant to run directly on the user's machine.
34 This class wraps a BraketSimulator object so that it can be run and returns
35 results using constructs from the SDK rather than Braket IR.
36 """
38 def __init__(self, backend: Union[str, BraketSimulator]):
39 """
40 Args:
41 backend (Union[str, BraketSimulator]): The name of the simulator backend or
42 the actual simulator instance to use for simulation
43 """
44 delegate = _get_simulator(backend)
45 super().__init__(
46 name=delegate.__class__.__name__,
47 status="AVAILABLE",
48 status_reason="Local simulator loaded successfully",
49 )
50 self._delegate = delegate
52 def run(
53 self, task_specification: Union[Circuit, Problem], *args, **kwargs,
54 ) -> LocalQuantumTask:
55 """ Runs the given task with the wrapped local simulator.
57 Args:
58 task_specification (Union[Circuit, Problem]):
59 *args: Positional args to pass to the IR simulator
60 **kwargs: Keyword arguments to pass to the IR simulator
62 Returns:
63 LocalQuantumTask: A LocalQuantumTask object containing the results
64 of the simulation
66 Note:
67 If running a circuit, the number of qubits will be passed
68 to the backend as the argument after the circuit itself.
69 """
70 result = _run_internal(task_specification, self._delegate, *args, **kwargs)
71 return LocalQuantumTask(result)
73 @staticmethod
74 def registered_backends() -> Set[str]:
75 """ Gets the backends that have been registered as entry points
77 Returns:
78 Set[str]: The names of the available backends that can be passed
79 into LocalSimulator's constructor
80 """
81 return set(_simulator_devices.keys())
84@singledispatch
85def _get_simulator(simulator):
86 raise TypeError("Simulator must either be a string or a BraketSimulator instance")
89@_get_simulator.register
90def _(backend_name: str):
91 if backend_name in _simulator_devices:
92 device_class = _simulator_devices[backend_name].load()
93 return device_class()
94 else:
95 raise ValueError(f"Only the following devices are available {_simulator_devices.keys()}")
98@_get_simulator.register
99def _(backend_impl: BraketSimulator):
100 return backend_impl
103@singledispatch
104def _run_internal(task_specification, simulator: BraketSimulator, *args, **kwargs):
105 raise NotImplementedError("Unsupported task type")
108@_run_internal.register
109def _(circuit: Circuit, simulator: BraketSimulator, *args, **kwargs):
110 program = circuit.to_ir()
111 qubits = circuit.qubit_count
112 results_dict = simulator.run(program, qubits, *args, **kwargs)
113 return GateModelQuantumTaskResult.from_dict(results_dict)
116@_run_internal.register
117def _(problem: Problem, simulator: BraketSimulator, *args, **kwargs):
118 ir = problem.to_ir()
119 results_dict = simulator.run(ir, *args, *kwargs)
120 return AnnealingQuantumTaskResult.from_dict(results_dict)