Skip to content

Commit

Permalink
Update from qiskit-braket-provider main (#5)
Browse files Browse the repository at this point in the history
* [UnitaryHack] Enable qiskit transpilation discontinous qubit indices (qiskit-community#108)

* convert Rigetti Aspen qubit connectivity continous

* Add qiskit transpilation discountinous qubit indices

* Add more comments, cleanup

* Add more comments, cleanup

* Move in Rigetti branching since not require globally

* Fix lint

* Add better example

* Fix docstring

* Add mock for rigetti aspen m3

* Enable transpilation test

* Fix mypy

* [UnitaryHack] Gate Decomposition(qiskit-community#90) added and tested (qiskit-community#111)

* implement and test gate decomposition

* Implement and Test Gate Decomposition

* addressed comments in previous PR

* Adding separate QUEUED and RUNNING states to task status (qiskit-community#110)

* fix: Updates for Qiskit to Braket circuit conversion (qiskit-community#97)

* Probability to Sample result type

* passes tox lint

* updates toxlint

* fixes observable z error but not passses elint

* unit test added

* final commit with tests

fix: Fallback to JAQCD for device properties (qiskit-community#104)

* fix: Fallback to JAQCD for device properties

* fix: reformat

replacing AWSBraketJob with AmazonBraketTask

run the notebooks containing AmazonBraketTask

deprecation warning added for AWSBraketJob class

formatting fixed

re-add <JOB_ARN>

fix breaking changes on /provider/__init__.py and __init__.py

rename job_id to task_id argument for AmazonBraketTask()

rename braket_jobs_states to braket_tasks_states

add task_id method to access the task_id similar to the one we have in the JobV1 class

adding tests for new class 'AmazonBraketTask' and old class 'AWSBraketJob'

formatting test_braket_job.py

correcting definition of AWSBraketJob

rewriting line 184 in braket_job.py

adding class docstring to AWSBraketJob

standard import 'from warnings import warn'  placed before 'from braket.aws import AwsQuantumTask' (wrong-import-order)

docstring fix in test_braket_job.py

assert the job id in test_AWS_job() function in test_braket_job.py

running how to notebook #0

running how to notebook #1

running how to notebook #2

running how to notebook #3

running how to notebook number 5

running tutorial  notebook number 3

tutorial number 0

* add separate QUEUED and RUNNING states to task status (qiskit-community#46)

---------

Co-authored-by: Yuri Han <45699207+urihan@users.noreply.github.com>

---------

Co-authored-by: WingCode <smallstar1234@gmail.com>
Co-authored-by: Gmontes01 <118773601+Gmontes01@users.noreply.github.com>
Co-authored-by: Yuri Han <45699207+urihan@users.noreply.github.com>
  • Loading branch information
4 people authored Jun 19, 2023
1 parent 43f821f commit 02e7f89
Show file tree
Hide file tree
Showing 6 changed files with 397 additions and 38 deletions.
97 changes: 82 additions & 15 deletions qiskit_braket_provider/providers/adapter.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Util function for provider."""
from typing import Callable, Dict, Iterable, List, Optional, Tuple, Union
import warnings

from braket.aws import AwsDevice
from braket.circuits import (
Expand All @@ -24,8 +25,10 @@
GateModelSimulatorParadigmProperties,
)
from braket.devices import LocalSimulator

from numpy import pi
from qiskit import QuantumCircuit

from qiskit import QuantumCircuit, transpile
from qiskit.circuit import Instruction as QiskitInstruction
from qiskit.circuit import Measure, Parameter
from qiskit.circuit.library import (
Expand Down Expand Up @@ -60,8 +63,8 @@
YGate,
ZGate,
)
from qiskit.transpiler import InstructionProperties, Target

from qiskit.transpiler import InstructionProperties, Target
from qiskit_braket_provider.exception import QiskitBraketException

qiskit_to_braket_gate_names_mapping = {
Expand Down Expand Up @@ -97,23 +100,24 @@
"ecr": "ecr",
}

_EPS = 1e-10 # global variable used to chop very small numbers to zero

qiskit_gate_names_to_braket_gates: Dict[str, Callable] = {
"u": lambda theta, phi, lam: [
gates.Rz(lam),
gates.Rx(pi / 2),
gates.Rz(theta),
gates.Rx(-pi / 2),
gates.Rz(phi),
"u1": lambda lam: [gates.PhaseShift(lam)],
"u2": lambda phi, lam: [
gates.PhaseShift(lam),
gates.Ry(pi / 2),
gates.PhaseShift(phi),
],
"u1": lambda lam: [gates.Rz(lam)],
"u2": lambda phi, lam: [gates.Rz(lam), gates.Ry(pi / 2), gates.Rz(phi)],
"u3": lambda theta, phi, lam: [
gates.Rz(lam),
gates.Rx(pi / 2),
gates.Rz(theta),
gates.Rx(-pi / 2),
gates.Rz(phi),
gates.PhaseShift(lam),
gates.Ry(theta),
gates.PhaseShift(phi),
],
"u": lambda theta, phi, lam: [
gates.PhaseShift(lam),
gates.Ry(theta),
gates.PhaseShift(phi),
],
"p": lambda angle: [gates.PhaseShift(angle)],
"cp": lambda angle: [gates.CPhaseShift(angle)],
Expand Down Expand Up @@ -144,6 +148,10 @@
}


translatable_qiskit_gates = set(qiskit_gate_names_to_braket_gates.keys()).union(
{"measure", "barrier", "reset"}
)

qiskit_gate_name_to_braket_gate_mapping: Dict[str, Optional[QiskitInstruction]] = {
"u": UGate(Parameter("theta"), Parameter("phi"), Parameter("lam")),
"u1": U1Gate(Parameter("theta")),
Expand Down Expand Up @@ -293,6 +301,54 @@ def aws_device_to_target(device: AwsDevice) -> Target:
instruction_props[(dst, src)] = None
# building coupling map for device with connectivity graph
else:
if isinstance(properties, RigettiDeviceCapabilities):

def convert_continuous_qubit_indices(
connectivity_graph: dict,
) -> dict:
"""Aspen qubit indices are discontinuous (label between x0 and x7, x being
the number of the octagon) while the Qiskit transpiler creates and/or
handles coupling maps with continuous indices. This function converts the
discontinous connectivity graph from Aspen to a continuous one.
Args:
connectivity_graph (dict): connectivity graph from Aspen. For example
4 qubit system, the connectivity graph will be:
{"0": ["1", "2", "7"], "1": ["0","2","7"], "2": ["0","1","7"],
"7": ["0","1","2"]}
Returns:
dict: Connectivity graph with continuous indices. For example for an
input connectivity graph with discontinuous indices (qubit 0, 1, 2 and
then qubit 7) as shown here:
{"0": ["1", "2", "7"], "1": ["0","2","7"], "2": ["0","1","7"],
"7": ["0","1","2"]}
the qubit index 7 will be mapped to qubit index 3 for the qiskit
transpilation step. Thereby the resultant continous qubit indices
output will be:
{"0": ["1", "2", "3"], "1": ["0","2","3"], "2": ["0","1","3"],
"3": ["0","1","2"]}
"""
# Creates list of existing qubit indices which are discontinuous.
indices = [int(key) for key in connectivity_graph.keys()]
indices.sort()
# Creates a list of continuous indices for number of qubits.
map_list = list(range(len(indices)))
# Creates a dictionary to remap the discountinous indices to continuous.
mapper = dict(zip(indices, map_list))
# Performs the remapping from the discontinous to the continuous indices.
continous_connectivity_graph = {
mapper[int(k)]: [mapper[int(v)] for v in val]
for k, val in connectivity_graph.items()
}
return continous_connectivity_graph

connectivity.connectivityGraph = (
convert_continuous_qubit_indices(
connectivity.connectivityGraph
)
)

for src, connections in connectivity.connectivityGraph.items():
for dst in connections:
instruction_props[(int(src), int(dst))] = None
Expand Down Expand Up @@ -361,6 +417,13 @@ def convert_qiskit_to_braket_circuit(circuit: QuantumCircuit) -> Circuit:
Circuit: Braket circuit
"""
quantum_circuit = Circuit()
if not (
{gate.name for gate, _, _ in circuit.data}.issubset(translatable_qiskit_gates)
):
circuit = transpile(circuit, basis_gates=translatable_qiskit_gates)
if circuit.global_phase > _EPS:
warnings.warn("Circuit transpilation resulted in global phase shift")
# handle qiskit to braket conversion
for qiskit_gates in circuit.data:
name = qiskit_gates[0].name
if name == "measure":
Expand All @@ -379,6 +442,10 @@ def convert_qiskit_to_braket_circuit(circuit: QuantumCircuit) -> Circuit:
elif name == "barrier":
# This does not exist
pass
elif name == "reset":
raise NotImplementedError(
"reset operation not supported by qiskit to braket adapter"
)
else:
params = []
if hasattr(qiskit_gates[0], "params"):
Expand Down
2 changes: 1 addition & 1 deletion qiskit_braket_provider/providers/braket_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def run(
tasks = []
try:
for circuit in circuits:
task: Union[LocalQuantumTask] = self._aws_device.run(
task: LocalQuantumTask = self._aws_device.run(
task_specification=circuit, shots=shots
)
tasks.append(task)
Expand Down
31 changes: 31 additions & 0 deletions tests/providers/mocks.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""Mocks for testing."""

from collections import Counter
import copy
from typing import Dict

import uuid
import numpy as np
Expand All @@ -12,6 +14,7 @@


RIGETTI_ARN = "arn:aws:braket:::device/qpu/rigetti/Aspen-10"
RIGETTI_ASPEN_ARN = "arn:aws:braket:::device/qpu/rigetti/Aspen-M-3"
SV1_ARN = "arn:aws:braket:::device/quantum-simulator/amazon/sv1"
TN1_ARN = "arn:aws:braket:::device/quantum-simulator/amazon/tn1"
RIGETTI_REGION = "us-west-1"
Expand Down Expand Up @@ -64,6 +67,34 @@
"deviceCapabilities": RIGETTI_MOCK_GATE_MODEL_QPU_CAPABILITIES.json(),
}

RIGETTI_MOCK_M_3_QPU_CAPABILITIES_JSON: Dict = copy.deepcopy(
RIGETTI_MOCK_GATE_MODEL_QPU_CAPABILITIES_JSON
)
RIGETTI_MOCK_M_3_QPU_CAPABILITIES_JSON["action"]["braket.ir.openqasm.program"][
"supportedOperations"
] = ["RX", "RZ", "CP", "CZ", "XY"]
RIGETTI_MOCK_M_3_QPU_CAPABILITIES_JSON["paradigm"]["qubitCount"] = 4
RIGETTI_MOCK_M_3_QPU_CAPABILITIES_JSON["paradigm"]["connectivity"][
"connectivityGraph"
] = {
"0": ["1", "2", "7"],
"1": ["0", "2", "7"],
"2": ["0", "1", "7"],
"7": ["0", "1", "2"],
}
RIGETTI_MOCK_M_3_QPU_CAPABILITIES = RigettiDeviceCapabilities.parse_obj(
RIGETTI_MOCK_M_3_QPU_CAPABILITIES_JSON
)

MOCK_RIGETTI_GATE_MODEL_M_3_QPU = {
"deviceName": "Aspen-M-3",
"deviceType": "QPU",
"providerName": "provider1",
"deviceStatus": "ONLINE",
"deviceArn": RIGETTI_ASPEN_ARN,
"deviceCapabilities": RIGETTI_MOCK_M_3_QPU_CAPABILITIES.json(),
}

MOCK_GATE_MODEL_SIMULATOR_CAPABILITIES_JSON = {
"braketSchemaHeader": {
"name": "braket.device_schema.simulators.gate_model_simulator_device_capabilities",
Expand Down
Loading

0 comments on commit 02e7f89

Please sign in to comment.