diff --git a/pyproject.toml b/pyproject.toml index 190197c..2f3e8ee 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -33,5 +33,53 @@ package-data = {"*" = ["*.json"]} dependencies = {file = "requirements.txt"} optional-dependencies.test = { file = "requirements-test.txt" } -[tool.isort] -profile = "black" + +[tool.ruff] +target-version = "py39" +line-length = 100 +format.preview = true +format.docstring-code-line-length = 100 +lint.select = [ + "ALL", +] +lint.ignore = [ + "ANN101", # Missing type annotation for `self` in method + "ANN102", # Missing type annotation for `cls` in classmethod" + "ANN401", # Dynamically typed expressions (typing.Any) are disallowed in `arg`" + "BLE001", # This needs to be cleaned up later. + "COM812", # conflicts with formatter + "CPY", # No copyright header + "D", # ignore documentation for now + "D203", # `one-blank-line-before-class` (D203) and `no-blank-line-before-class` (D211) are incompatible + "D212", # `multi-line-summary-first-line` (D212) and `multi-line-summary-second-line` (D213) are incompatible + "DOC201", # no restructuredtext support yet + "DOC402", # no restructuredtext support yet + "DOC501", # broken with sphinx docs + "INP001", # no implicit namespaces here + "ISC001", # conflicts with formatter + "PLR0914", ## Too many local variables + "PLR0917", ## Too many positional arguments + "PLW0603", # Allow usage of global vars + "S104", # Possible binding to all interfaces + "S404", # Using subprocess is alright. + "S603", # Using subprocess is alright. +] +lint.per-file-ignores."tests/**/*.py" = [ + "D", # don't care about documentation in tests + "FBT", # don"t care about booleans as positional arguments in tests + "INP001", # no implicit namespace + "PLR2004", # Magic value used in comparison, consider replacing with a constant variable + "S101", # asserts allowed in tests... + "S603", # `subprocess` call: check for execution of untrusted input +] +lint.isort = { known-first-party = [ + "simulator_v2", + "tests", +] } +lint.preview = true + +[tool.ruff.lint.pydocstyle] +convention = "google" + +[tool.ruff.lint.flake8-annotations] +mypy-init-return = false diff --git a/requirements-test.txt b/requirements-test.txt index 5e32098..2a63665 100644 --- a/requirements-test.txt +++ b/requirements-test.txt @@ -1,10 +1,5 @@ amazon-braket-pennylane-plugin -black -flake8 -flake8-rst-docstrings -isort pre-commit -pylint pytest==7.1.2 pytest-benchmark pytest-cov @@ -14,7 +9,5 @@ pytest-xdist qiskit==1.2.0 qiskit-braket-provider==0.4.1 qiskit-algorithms -sphinx -sphinx-rtd-theme -sphinxcontrib-apidoc +ruff tox diff --git a/setup.cfg b/setup.cfg index 853c49e..688a3b8 100644 --- a/setup.cfg +++ b/setup.cfg @@ -7,23 +7,3 @@ addopts = --verbose -n auto --durations=0 --durations-min=1 --dist worksteal testpaths = test/unit_tests -[flake8] -ignore = - # not pep8, black adds whitespace before ':' - E203, - # not pep8, black adds line break before binary operator - W503, - # Google Python style is not RST until after processed by Napoleon - # See https://github.com/peterjc/flake8-rst-docstrings/issues/17 - RST201,RST203,RST301, -max_line_length = 100 -max-complexity = 10 -exclude = - __pycache__ - .tox - .git - bin - dist - examples - build - venv diff --git a/src/braket/simulator_v2/base_simulator_v2.py b/src/braket/simulator_v2/base_simulator_v2.py index faf0799..78975fb 100644 --- a/src/braket/simulator_v2/base_simulator_v2.py +++ b/src/braket/simulator_v2/base_simulator_v2.py @@ -1,47 +1,50 @@ +from __future__ import annotations + import atexit import json -from collections.abc import Sequence +import os +import sys +from itertools import starmap from multiprocessing.pool import Pool -from typing import Optional, Union +from typing import TYPE_CHECKING import numpy as np + from braket.default_simulator.simulator import BaseLocalSimulator from braket.ir.jaqcd import DensityMatrix, Probability, StateVector -from braket.ir.openqasm import Program as OpenQASMProgram -from braket.task_result import GateModelTaskResult - from braket.simulator_v2.julia_workers import ( - _handle_julia_error, + _handle_julia_error, # noqa: PLC2701 translate_and_run, translate_and_run_multiple, ) +from braket.task_result import GateModelTaskResult -__JULIA_POOL__ = None +if TYPE_CHECKING: + from collections.abc import Sequence + + from braket.ir.openqasm import Program as OpenQASMProgram +__JULIA_POOL__ = None -def setup_julia(): - import os - import sys +def setup_julia() -> None: # don't reimport if we don't have to if "juliacall" in sys.modules: os.environ["PYTHON_JULIACALL_HANDLE_SIGNALS"] = "yes" return - else: - for k, default in ( - ("PYTHON_JULIACALL_HANDLE_SIGNALS", "yes"), - ("PYTHON_JULIACALL_THREADS", "auto"), - ("PYTHON_JULIACALL_OPTLEVEL", "3"), - # let the user's Conda/Pip handle installing things - ("JULIA_CONDAPKG_BACKEND", "Null"), - ): - os.environ[k] = os.environ.get(k, default) - - import juliacall - - jl = juliacall.Main - jl.seval("using BraketSimulator, JSON3") - stock_oq3 = """ + import juliacall # noqa: PLC0415 + for k, default in ( + ("PYTHON_JULIACALL_HANDLE_SIGNALS", "yes"), + ("PYTHON_JULIACALL_THREADS", "auto"), + ("PYTHON_JULIACALL_OPTLEVEL", "3"), + # let the user's Conda/Pip handle installing things + ("JULIA_CONDAPKG_BACKEND", "Null"), + ): + os.environ[k] = os.environ.get(k, default) + + jl = juliacall.Main + jl.seval("using BraketSimulator, JSON3") + stock_oq3 = """ OPENQASM 3.0; qubit[2] q; h q[0]; @@ -52,20 +55,21 @@ def setup_julia(): #pragma braket result density_matrix q[0], q[1] #pragma braket result probability """ - jl.BraketSimulator.simulate("braket_dm_v2", stock_oq3, "{}", 0) - return + jl.BraketSimulator.simulate("braket_dm_v2", stock_oq3, "{}", 0) + return -def setup_pool(): +def setup_pool() -> None: global __JULIA_POOL__ __JULIA_POOL__ = Pool(processes=1) __JULIA_POOL__.apply(setup_julia) atexit.register(__JULIA_POOL__.join) atexit.register(__JULIA_POOL__.close) - return -def _handle_mmaped_result(raw_result, mmap_paths, obj_lengths): +def _handle_mmaped_result( + raw_result: dict, mmap_paths: list, obj_lengths: list +) -> GateModelTaskResult: result = GateModelTaskResult(**raw_result) if mmap_paths: mmap_files = mmap_paths @@ -89,20 +93,19 @@ def _handle_mmaped_result(raw_result, mmap_paths, obj_lengths): class BaseLocalSimulatorV2(BaseLocalSimulator): - def __init__(self, device: str): - global __JULIA_POOL__ + def __init__(self, device: str) -> None: if __JULIA_POOL__ is None: setup_pool() self._device = device - def initialize_simulation(self, **kwargs): - return + def initialize_simulation(self, **kwargs: dict) -> None: + pass def run_openqasm( self, openqasm_ir: OpenQASMProgram, shots: int = 0, - batch_size: int = 1, # unused + batch_size: int = 1, # noqa: ARG002 ) -> GateModelTaskResult: """Executes the circuit specified by the supplied `openqasm_ir` on the simulator. @@ -118,8 +121,7 @@ def run_openqasm( ValueError: If result types are not specified in the IR or sample is specified as a result type when shots=0. Or, if StateVector and Amplitude result types are requested when shots>0. - """ - global __JULIA_POOL__ + """ # noqa: DOC502 try: jl_result = __JULIA_POOL__.apply( translate_and_run, @@ -142,9 +144,9 @@ def run_openqasm( def run_multiple( self, programs: Sequence[OpenQASMProgram], - max_parallel: Optional[int] = -1, - shots: Optional[int] = 0, - inputs: Optional[Union[dict, Sequence[dict]]] = {}, + max_parallel: int = -1, # noqa: ARG002 + shots: int = 0, + inputs: dict | Sequence[dict] | None = None, ) -> list[GateModelTaskResult]: """ Run the tasks specified by the given IR programs. @@ -154,11 +156,13 @@ def run_multiple( programs (Sequence[OQ3Program]): The IR representations of the programs max_parallel (Optional[int]): The maximum number of programs to run in parallel. Default is the number of logical CPUs. + Returns: list[GateModelTaskResult]: A list of result objects, with the ith object being the result of the ith program. """ - global __JULIA_POOL__ + if inputs is None: + inputs = {} try: jl_results = __JULIA_POOL__.apply( translate_and_run_multiple, @@ -173,10 +177,7 @@ def run_multiple( (loaded_result[r_ix], paths_and_lens[r_ix][0], paths_and_lens[r_ix][1]) for r_ix in range(len(loaded_result)) ] - results = [ - _handle_mmaped_result(*result_path_len) - for result_path_len in results_paths_lens - ] + results = list(starmap(_handle_mmaped_result, results_paths_lens)) jl_results = None for p_ix, program in enumerate(programs): results[p_ix].additionalMetadata.action = program @@ -198,11 +199,10 @@ def _result_value_to_ndarray( with the pydantic specification for ResultTypeValues. """ - def reconstruct_complex(v): + def reconstruct_complex(v: list | float) -> complex | float: if isinstance(v, list): return complex(v[0], v[1]) - else: - return v + return v for result_ind, result_type in enumerate(task_result.resultTypes): # Amplitude @@ -211,7 +211,7 @@ def reconstruct_complex(v): task_result.resultTypes[result_ind].value = { k: reconstruct_complex(v) for (k, v) in val.items() } - if isinstance(result_type.type, StateVector): + elif isinstance(result_type.type, StateVector): val = task_result.resultTypes[result_ind].value if isinstance(val, list): fixed_val = [reconstruct_complex(v) for v in val] @@ -219,11 +219,9 @@ def reconstruct_complex(v): if isinstance(result_type.type, DensityMatrix): val = task_result.resultTypes[result_ind].value # complex are stored as tuples of reals - fixed_val = [ - [reconstruct_complex(v) for v in inner_val] for inner_val in val - ] + fixed_val = [[reconstruct_complex(v) for v in inner_val] for inner_val in val] task_result.resultTypes[result_ind].value = np.asarray(fixed_val) - if isinstance(result_type.type, Probability): + elif isinstance(result_type.type, Probability): val = task_result.resultTypes[result_ind].value task_result.resultTypes[result_ind].value = np.asarray(val) diff --git a/src/braket/simulator_v2/density_matrix_simulator_v2.py b/src/braket/simulator_v2/density_matrix_simulator_v2.py index 1a849a8..74dbc2c 100644 --- a/src/braket/simulator_v2/density_matrix_simulator_v2.py +++ b/src/braket/simulator_v2/density_matrix_simulator_v2.py @@ -4,7 +4,6 @@ GateModelSimulatorDeviceCapabilities, GateModelSimulatorDeviceParameters, ) - from braket.simulator_v2.base_simulator_v2 import BaseLocalSimulatorV2 @@ -17,7 +16,7 @@ class DensityMatrixSimulatorV2(BaseLocalSimulatorV2): DEVICE_ID = "braket_dm_v2" - def __init__(self): + def __init__(self) -> None: super().__init__(self.DEVICE_ID) @property @@ -25,154 +24,150 @@ def properties(self) -> GateModelSimulatorDeviceCapabilities: observables = ["x", "y", "z", "h", "i", "hermitian"] max_shots = sys.maxsize qubit_count = 16 - return GateModelSimulatorDeviceCapabilities.parse_obj( - { - "service": { - "executionWindows": [ + return GateModelSimulatorDeviceCapabilities.parse_obj({ + "service": { + "executionWindows": [ + { + "executionDay": "Everyday", + "windowStartHour": "00:00", + "windowEndHour": "23:59:59", + } + ], + "shotsRange": [0, max_shots], + }, + "action": { + "braket.ir.openqasm.program": { + "actionType": "braket.ir.openqasm.program", + "version": ["1"], + "supportedOperations": sorted([ + # OpenQASM primitives + "U", + "GPhase", + # builtin Braket gates + "ccnot", + "cnot", + "cphaseshift", + "cphaseshift00", + "cphaseshift01", + "cphaseshift10", + "cswap", + "cv", + "cy", + "cz", + "ecr", + "gpi", + "gpi2", + "h", + "i", + "iswap", + "ms", + "pswap", + "phaseshift", + "rx", + "ry", + "rz", + "s", + "si", + "swap", + "t", + "ti", + "unitary", + "v", + "vi", + "x", + "xx", + "xy", + "y", + "yy", + "z", + "zz", + # noise operations + "bit_flip", + "phase_flip", + "pauli_channel", + "depolarizing", + "two_qubit_depolarizing", + "two_qubit_dephasing", + "amplitude_damping", + "generalized_amplitude_damping", + "phase_damping", + "kraus", + ]), + "supportedModifiers": [ + { + "name": "ctrl", + }, + { + "name": "negctrl", + }, + { + "name": "pow", + "exponent_types": ["int", "float"], + }, { - "executionDay": "Everyday", - "windowStartHour": "00:00", - "windowEndHour": "23:59:59", - } + "name": "inv", + }, ], - "shotsRange": [0, max_shots], - }, - "action": { - "braket.ir.openqasm.program": { - "actionType": "braket.ir.openqasm.program", - "version": ["1"], - "supportedOperations": sorted( - [ - # OpenQASM primitives - "U", - "GPhase", - # builtin Braket gates - "ccnot", - "cnot", - "cphaseshift", - "cphaseshift00", - "cphaseshift01", - "cphaseshift10", - "cswap", - "cv", - "cy", - "cz", - "ecr", - "gpi", - "gpi2", - "h", - "i", - "iswap", - "ms", - "pswap", - "phaseshift", - "rx", - "ry", - "rz", - "s", - "si", - "swap", - "t", - "ti", - "unitary", - "v", - "vi", - "x", - "xx", - "xy", - "y", - "yy", - "z", - "zz", - # noise operations - "bit_flip", - "phase_flip", - "pauli_channel", - "depolarizing", - "two_qubit_depolarizing", - "two_qubit_dephasing", - "amplitude_damping", - "generalized_amplitude_damping", - "phase_damping", - "kraus", - ] - ), - "supportedModifiers": [ - { - "name": "ctrl", - }, - { - "name": "negctrl", - }, - { - "name": "pow", - "exponent_types": ["int", "float"], - }, - { - "name": "inv", - }, - ], - "supportedPragmas": [ - "braket_unitary_matrix", - "braket_result_type_density_matrix", - "braket_result_type_sample", - "braket_result_type_expectation", - "braket_result_type_variance", - "braket_result_type_probability", - "braket_result_type_amplitude", - "braket_noise_amplitude_damping", - "braket_noise_bit_flip", - "braket_noise_depolarizing", - "braket_noise_kraus", - "braket_noise_pauli_channel", - "braket_noise_generalized_amplitude_damping", - "braket_noise_phase_flip", - "braket_noise_phase_damping", - "braket_noise_two_qubit_dephasing", - "braket_noise_two_qubit_depolarizing", - ], - "forbiddenPragmas": [ - "braket_result_type_adjoint_gradient", - ], - "supportedResultTypes": [ - { - "name": "Sample", - "observables": observables, - "minShots": 1, - "maxShots": max_shots, - }, - { - "name": "Expectation", - "observables": observables, - "minShots": 0, - "maxShots": max_shots, - }, - { - "name": "Variance", - "observables": observables, - "minShots": 0, - "maxShots": max_shots, - }, - { - "name": "Probability", - "minShots": 0, - "maxShots": max_shots, - }, - { - "name": "DensityMatrix", - "minShots": 0, - "maxShots": 0, - }, - ], - "supportPhysicalQubits": False, - "supportsPartialVerbatimBox": False, - "requiresContiguousQubitIndices": True, - "requiresAllQubitsMeasurement": True, - "supportsUnassignedMeasurements": True, - "disabledQubitRewiringSupported": False, - }, + "supportedPragmas": [ + "braket_unitary_matrix", + "braket_result_type_density_matrix", + "braket_result_type_sample", + "braket_result_type_expectation", + "braket_result_type_variance", + "braket_result_type_probability", + "braket_result_type_amplitude", + "braket_noise_amplitude_damping", + "braket_noise_bit_flip", + "braket_noise_depolarizing", + "braket_noise_kraus", + "braket_noise_pauli_channel", + "braket_noise_generalized_amplitude_damping", + "braket_noise_phase_flip", + "braket_noise_phase_damping", + "braket_noise_two_qubit_dephasing", + "braket_noise_two_qubit_depolarizing", + ], + "forbiddenPragmas": [ + "braket_result_type_adjoint_gradient", + ], + "supportedResultTypes": [ + { + "name": "Sample", + "observables": observables, + "minShots": 1, + "maxShots": max_shots, + }, + { + "name": "Expectation", + "observables": observables, + "minShots": 0, + "maxShots": max_shots, + }, + { + "name": "Variance", + "observables": observables, + "minShots": 0, + "maxShots": max_shots, + }, + { + "name": "Probability", + "minShots": 0, + "maxShots": max_shots, + }, + { + "name": "DensityMatrix", + "minShots": 0, + "maxShots": 0, + }, + ], + "supportPhysicalQubits": False, + "supportsPartialVerbatimBox": False, + "requiresContiguousQubitIndices": True, + "requiresAllQubitsMeasurement": True, + "supportsUnassignedMeasurements": True, + "disabledQubitRewiringSupported": False, }, - "paradigm": {"qubitCount": qubit_count}, - "deviceParameters": GateModelSimulatorDeviceParameters.schema(), - } - ) + }, + "paradigm": {"qubitCount": qubit_count}, + "deviceParameters": GateModelSimulatorDeviceParameters.schema(), + }) diff --git a/src/braket/simulator_v2/julia_workers.py b/src/braket/simulator_v2/julia_workers.py index f85289e..187e58b 100644 --- a/src/braket/simulator_v2/julia_workers.py +++ b/src/braket/simulator_v2/julia_workers.py @@ -1,36 +1,35 @@ +from __future__ import annotations + import json import sys -from collections.abc import Sequence -from typing import List, Optional, Union +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Sequence -from braket.ir.openqasm import Program as OpenQASMProgram + from braket.ir.openqasm import Program as OpenQASMProgram -def _handle_julia_error(error): +def _handle_julia_error(error: str) -> None: # in case juliacall isn't loaded - print(error) if type(error).__name__ == "JuliaError": python_exception = getattr(error.exception, "alternate_type", None) if python_exception is None: # convert to RuntimeError as JuliaError can't be serialized py_error = RuntimeError( "Unable to unwrap internal Julia exception." - f"Exception message: {str(error.exception.message)}" + f"Exception message: {error.exception.message}" ) else: class_val = getattr(sys.modules["builtins"], str(python_exception)) py_error = class_val(str(error.exception.message)) raise py_error - else: - raise error - return + raise error -def translate_and_run( - device_id: str, openqasm_ir: OpenQASMProgram, shots: int = 0 -) -> str: +def translate_and_run(device_id: str, openqasm_ir: OpenQASMProgram, shots: int = 0) -> str: jl = sys.modules["juliacall"].Main - jl.GC.enable(False) + jl.GC.enable(False) # noqa: FBT003 jl_inputs = json.dumps(openqasm_ir.inputs) if openqasm_ir.inputs else "{}" try: result = jl.BraketSimulator.simulate( @@ -43,7 +42,7 @@ def translate_and_run( except Exception as e: _handle_julia_error(e) finally: - jl.GC.enable(True) + jl.GC.enable(True) # noqa: FBT003 return result @@ -52,8 +51,8 @@ def translate_and_run_multiple( device_id: str, programs: Sequence[OpenQASMProgram], shots: int = 0, - inputs: Optional[Union[dict, Sequence[dict]]] = None, -) -> List[str]: + inputs: dict | Sequence[dict] | None = None, +) -> list[str]: inputs = inputs or {} jl = sys.modules["juliacall"].Main irs = [program.source for program in programs] diff --git a/src/braket/simulator_v2/state_vector_simulator_v2.py b/src/braket/simulator_v2/state_vector_simulator_v2.py index 591d47e..e8acd49 100644 --- a/src/braket/simulator_v2/state_vector_simulator_v2.py +++ b/src/braket/simulator_v2/state_vector_simulator_v2.py @@ -4,7 +4,6 @@ GateModelSimulatorDeviceCapabilities, GateModelSimulatorDeviceParameters, ) - from braket.simulator_v2.base_simulator_v2 import BaseLocalSimulatorV2 @@ -17,7 +16,7 @@ class StateVectorSimulatorV2(BaseLocalSimulatorV2): DEVICE_ID = "braket_sv_v2" - def __init__(self): + def __init__(self) -> None: super().__init__(self.DEVICE_ID) @property @@ -31,152 +30,150 @@ def properties(self) -> GateModelSimulatorDeviceCapabilities: observables = ["x", "y", "z", "h", "i", "hermitian"] max_shots = sys.maxsize qubit_count = 32 - return GateModelSimulatorDeviceCapabilities.parse_obj( - { - "service": { - "executionWindows": [ + return GateModelSimulatorDeviceCapabilities.parse_obj({ + "service": { + "executionWindows": [ + { + "executionDay": "Everyday", + "windowStartHour": "00:00", + "windowEndHour": "23:59:59", + } + ], + "shotsRange": [0, max_shots], + }, + "action": { + "braket.ir.openqasm.program": { + "actionType": "braket.ir.openqasm.program", + "version": ["1"], + "supportedOperations": [ + # OpenQASM primitives + "U", + "GPhase", + # builtin Braket gates + "ccnot", + "cnot", + "cphaseshift", + "cphaseshift00", + "cphaseshift01", + "cphaseshift10", + "cswap", + "cv", + "cy", + "cz", + "ecr", + "gpi", + "gpi2", + "h", + "i", + "iswap", + "ms", + "pswap", + "phaseshift", + "rx", + "ry", + "rz", + "s", + "si", + "swap", + "t", + "ti", + "unitary", + "v", + "vi", + "x", + "xx", + "xy", + "y", + "yy", + "z", + "zz", + ], + "supportedModifiers": [ + { + "name": "ctrl", + }, + { + "name": "negctrl", + }, { - "executionDay": "Everyday", - "windowStartHour": "00:00", - "windowEndHour": "23:59:59", - } + "name": "pow", + "exponent_types": ["int", "float"], + }, + { + "name": "inv", + }, ], - "shotsRange": [0, max_shots], - }, - "action": { - "braket.ir.openqasm.program": { - "actionType": "braket.ir.openqasm.program", - "version": ["1"], - "supportedOperations": [ - # OpenQASM primitives - "U", - "GPhase", - # builtin Braket gates - "ccnot", - "cnot", - "cphaseshift", - "cphaseshift00", - "cphaseshift01", - "cphaseshift10", - "cswap", - "cv", - "cy", - "cz", - "ecr", - "gpi", - "gpi2", - "h", - "i", - "iswap", - "ms", - "pswap", - "phaseshift", - "rx", - "ry", - "rz", - "s", - "si", - "swap", - "t", - "ti", - "unitary", - "v", - "vi", - "x", - "xx", - "xy", - "y", - "yy", - "z", - "zz", - ], - "supportedModifiers": [ - { - "name": "ctrl", - }, - { - "name": "negctrl", - }, - { - "name": "pow", - "exponent_types": ["int", "float"], - }, - { - "name": "inv", - }, - ], - "supportedPragmas": [ - "braket_unitary_matrix", - "braket_result_type_state_vector", - "braket_result_type_density_matrix", - "braket_result_type_sample", - "braket_result_type_expectation", - "braket_result_type_variance", - "braket_result_type_probability", - "braket_result_type_amplitude", - ], - "forbiddenPragmas": [ - "braket_noise_amplitude_damping", - "braket_noise_bit_flip", - "braket_noise_depolarizing", - "braket_noise_kraus", - "braket_noise_pauli_channel", - "braket_noise_generalized_amplitude_damping", - "braket_noise_phase_flip", - "braket_noise_phase_damping", - "braket_noise_two_qubit_dephasing", - "braket_noise_two_qubit_depolarizing", - "braket_result_type_adjoint_gradient", - ], - "supportedResultTypes": [ - { - "name": "Sample", - "observables": observables, - "minShots": 1, - "maxShots": max_shots, - }, - { - "name": "Expectation", - "observables": observables, - "minShots": 0, - "maxShots": max_shots, - }, - { - "name": "Variance", - "observables": observables, - "minShots": 0, - "maxShots": max_shots, - }, - { - "name": "Probability", - "minShots": 0, - "maxShots": max_shots, - }, - { - "name": "StateVector", - "minShots": 0, - "maxShots": 0, - }, - { - "name": "DensityMatrix", - "minShots": 0, - "maxShots": 0, - }, - { - "name": "Amplitude", - "minShots": 0, - "maxShots": 0, - }, - ], - "supportPhysicalQubits": False, - "supportsPartialVerbatimBox": False, - "requiresContiguousQubitIndices": True, - "requiresAllQubitsMeasurement": True, - "supportsUnassignedMeasurements": True, - "disabledQubitRewiringSupported": False, - }, + "supportedPragmas": [ + "braket_unitary_matrix", + "braket_result_type_state_vector", + "braket_result_type_density_matrix", + "braket_result_type_sample", + "braket_result_type_expectation", + "braket_result_type_variance", + "braket_result_type_probability", + "braket_result_type_amplitude", + ], + "forbiddenPragmas": [ + "braket_noise_amplitude_damping", + "braket_noise_bit_flip", + "braket_noise_depolarizing", + "braket_noise_kraus", + "braket_noise_pauli_channel", + "braket_noise_generalized_amplitude_damping", + "braket_noise_phase_flip", + "braket_noise_phase_damping", + "braket_noise_two_qubit_dephasing", + "braket_noise_two_qubit_depolarizing", + "braket_result_type_adjoint_gradient", + ], + "supportedResultTypes": [ + { + "name": "Sample", + "observables": observables, + "minShots": 1, + "maxShots": max_shots, + }, + { + "name": "Expectation", + "observables": observables, + "minShots": 0, + "maxShots": max_shots, + }, + { + "name": "Variance", + "observables": observables, + "minShots": 0, + "maxShots": max_shots, + }, + { + "name": "Probability", + "minShots": 0, + "maxShots": max_shots, + }, + { + "name": "StateVector", + "minShots": 0, + "maxShots": 0, + }, + { + "name": "DensityMatrix", + "minShots": 0, + "maxShots": 0, + }, + { + "name": "Amplitude", + "minShots": 0, + "maxShots": 0, + }, + ], + "supportPhysicalQubits": False, + "supportsPartialVerbatimBox": False, + "requiresContiguousQubitIndices": True, + "requiresAllQubitsMeasurement": True, + "supportsUnassignedMeasurements": True, + "disabledQubitRewiringSupported": False, }, - "paradigm": {"qubitCount": qubit_count}, - "deviceParameters": GateModelSimulatorDeviceParameters.schema(), - } - ) + }, + "paradigm": {"qubitCount": qubit_count}, + "deviceParameters": GateModelSimulatorDeviceParameters.schema(), + }) diff --git a/test/integ_tests/braket/simulator_v2/gate_model_device_testing_utils.py b/test/integ_tests/braket/simulator_v2/gate_model_device_testing_utils.py index d48ee72..f7bf4ff 100644 --- a/test/integ_tests/braket/simulator_v2/gate_model_device_testing_utils.py +++ b/test/integ_tests/braket/simulator_v2/gate_model_device_testing_utils.py @@ -69,9 +69,7 @@ def no_result_types_bell_pair_testing(device: Device, run_kwargs: Dict[str, Any] no_result_types_testing(task, device, run_kwargs, {"00": 0.5, "11": 0.5}) -def result_types_observable_not_in_instructions( - device: Device, run_kwargs: Dict[str, Any] -): +def result_types_observable_not_in_instructions(device: Device, run_kwargs: Dict[str, Any]): shots = run_kwargs["shots"] tol = get_tol(shots) bell = ( @@ -110,9 +108,7 @@ def result_types_zero_shots_bell_pair_testing( assert len(result.result_types) == 3 if include_state_vector else 2 assert np.allclose( result.get_value_by_result_type( - ResultType.Expectation( - observable=Observable.H() @ Observable.X(), target=[0, 1] - ) + ResultType.Expectation(observable=Observable.H() @ Observable.X(), target=[0, 1]) ), 1 / np.sqrt(2), ) @@ -131,9 +127,7 @@ def result_types_zero_shots_bell_pair_testing( assert np.isclose(amplitude["11"], 1 / np.sqrt(2)) -def result_types_bell_pair_full_probability_testing( - device: Device, run_kwargs: Dict[str, Any] -): +def result_types_bell_pair_full_probability_testing(device: Device, run_kwargs: Dict[str, Any]): shots = run_kwargs["shots"] tol = get_tol(shots) circuit = Circuit().h(0).cnot(0, 1).probability() @@ -148,9 +142,7 @@ def result_types_bell_pair_full_probability_testing( ) -def result_types_bell_pair_marginal_probability_testing( - device: Device, run_kwargs: Dict[str, Any] -): +def result_types_bell_pair_marginal_probability_testing(device: Device, run_kwargs: Dict[str, Any]): shots = run_kwargs["shots"] tol = get_tol(shots) circuit = Circuit().h(0).cnot(0, 1).probability(0) @@ -165,9 +157,7 @@ def result_types_bell_pair_marginal_probability_testing( ) -def result_types_nonzero_shots_bell_pair_testing( - device: Device, run_kwargs: Dict[str, Any] -): +def result_types_nonzero_shots_bell_pair_testing(device: Device, run_kwargs: Dict[str, Any]): circuit = ( Circuit() .h(0) @@ -182,18 +172,14 @@ def result_types_nonzero_shots_bell_pair_testing( assert ( 0.6 < result.get_value_by_result_type( - ResultType.Expectation( - observable=Observable.H() @ Observable.X(), target=[0, 1] - ) + ResultType.Expectation(observable=Observable.H() @ Observable.X(), target=[0, 1]) ) < 0.8 ) assert ( len( result.get_value_by_result_type( - ResultType.Sample( - observable=Observable.H() @ Observable.X(), target=[0, 1] - ) + ResultType.Sample(observable=Observable.H() @ Observable.X(), target=[0, 1]) ) ) == run_kwargs["shots"] @@ -215,11 +201,7 @@ def result_types_hermitian_testing( ) if shots: circuit.add_result_type(ResultType.Sample(Observable.Hermitian(array), 0)) - tasks = ( - (circuit,) - if not test_program - else (circuit, circuit.to_ir(ir_type=IRType.OPENQASM)) - ) + tasks = (circuit,) if not test_program else (circuit, circuit.to_ir(ir_type=IRType.OPENQASM)) for task in tasks: result = device.run(task, **run_kwargs).result() @@ -248,11 +230,7 @@ def result_types_all_selected_testing( if shots: circuit.add_result_type(ResultType.Sample(Observable.Hermitian(array), 1)) - tasks = ( - (circuit,) - if not test_program - else (circuit, circuit.to_ir(ir_type=IRType.OPENQASM)) - ) + tasks = (circuit,) if not test_program else (circuit, circuit.to_ir(ir_type=IRType.OPENQASM)) for task in tasks: result = device.run(task, **run_kwargs).result() @@ -266,9 +244,7 @@ def result_types_all_selected_testing( ) -def get_result_types_three_qubit_circuit( - theta, phi, varphi, obs, obs_targets, shots -) -> Circuit: +def get_result_types_three_qubit_circuit(theta, phi, varphi, obs, obs_targets, shots) -> Circuit: circuit = ( Circuit() .rx(0, theta) @@ -310,9 +286,7 @@ def result_types_tensor_x_y_testing(device: Device, run_kwargs: Dict[str, Any]): varphi = -0.543 obs = Observable.X() @ Observable.Y() obs_targets = [0, 2] - circuit = get_result_types_three_qubit_circuit( - theta, phi, varphi, obs, obs_targets, shots - ) + circuit = get_result_types_three_qubit_circuit(theta, phi, varphi, obs, obs_targets, shots) tasks = (circuit, circuit.to_ir(ir_type=IRType.OPENQASM)) for task in tasks: result = device.run(task, **run_kwargs).result() @@ -340,9 +314,7 @@ def result_types_tensor_z_z_testing(device: Device, run_kwargs: Dict[str, Any]): varphi = -0.543 obs = Observable.Z() @ Observable.Z() obs_targets = [0, 2] - circuit = get_result_types_three_qubit_circuit( - theta, phi, varphi, obs, obs_targets, shots - ) + circuit = get_result_types_three_qubit_circuit(theta, phi, varphi, obs, obs_targets, shots) tasks = (circuit, circuit.to_ir(ir_type=IRType.OPENQASM)) for task in tasks: result = device.run(task, **run_kwargs).result() @@ -356,27 +328,21 @@ def result_types_tensor_z_z_testing(device: Device, run_kwargs: Dict[str, Any]): ) -def result_types_tensor_hermitian_hermitian_testing( - device: Device, run_kwargs: Dict[str, Any] -): +def result_types_tensor_hermitian_hermitian_testing(device: Device, run_kwargs: Dict[str, Any]): shots = run_kwargs["shots"] theta = 0.432 phi = 0.123 varphi = -0.543 matrix1 = np.array([[1, 2], [2, 4]]) - matrix2 = np.array( - [ - [-6, 2 + 1j, -3, -5 + 2j], - [2 - 1j, 0, 2 - 1j, -5 + 4j], - [-3, 2 + 1j, 0, -4 + 3j], - [-5 - 2j, -5 - 4j, -4 - 3j, -6], - ] - ) + matrix2 = np.array([ + [-6, 2 + 1j, -3, -5 + 2j], + [2 - 1j, 0, 2 - 1j, -5 + 4j], + [-3, 2 + 1j, 0, -4 + 3j], + [-5 - 2j, -5 - 4j, -4 - 3j, -6], + ]) obs = Observable.Hermitian(matrix1) @ Observable.Hermitian(matrix2) obs_targets = [0, 1, 2] - circuit = get_result_types_three_qubit_circuit( - theta, phi, varphi, obs, obs_targets, shots - ) + circuit = get_result_types_three_qubit_circuit(theta, phi, varphi, obs, obs_targets, shots) tasks = (circuit, circuit.to_ir(ir_type=IRType.OPENQASM)) for task in tasks: result = device.run(task, **run_kwargs).result() @@ -397,16 +363,14 @@ def result_types_tensor_z_h_y_testing(device: Device, run_kwargs: Dict[str, Any] varphi = -0.543 obs = Observable.Z() @ Observable.H() @ Observable.Y() obs_targets = [0, 1, 2] - circuit = get_result_types_three_qubit_circuit( - theta, phi, varphi, obs, obs_targets, shots - ) + circuit = get_result_types_three_qubit_circuit(theta, phi, varphi, obs, obs_targets, shots) tasks = (circuit, circuit.to_ir(ir_type=IRType.OPENQASM)) for task in tasks: result = device.run(task, **run_kwargs).result() - expected_mean = -( - np.cos(varphi) * np.sin(phi) + np.sin(varphi) * np.cos(theta) - ) / np.sqrt(2) + expected_mean = -(np.cos(varphi) * np.sin(phi) + np.sin(varphi) * np.cos(theta)) / np.sqrt( + 2 + ) expected_var = ( 3 + np.cos(2 * phi) * np.cos(varphi) ** 2 @@ -424,19 +388,15 @@ def result_types_tensor_z_hermitian_testing(device: Device, run_kwargs: Dict[str theta = 0.432 phi = 0.123 varphi = -0.543 - array = np.array( - [ - [-6, 2 + 1j, -3, -5 + 2j], - [2 - 1j, 0, 2 - 1j, -5 + 4j], - [-3, 2 + 1j, 0, -4 + 3j], - [-5 - 2j, -5 - 4j, -4 - 3j, -6], - ] - ) + array = np.array([ + [-6, 2 + 1j, -3, -5 + 2j], + [2 - 1j, 0, 2 - 1j, -5 + 4j], + [-3, 2 + 1j, 0, -4 + 3j], + [-5 - 2j, -5 - 4j, -4 - 3j, -6], + ]) obs = Observable.Z() @ Observable.Hermitian(array) obs_targets = [0, 1, 2] - circuit = get_result_types_three_qubit_circuit( - theta, phi, varphi, obs, obs_targets, shots - ) + circuit = get_result_types_three_qubit_circuit(theta, phi, varphi, obs, obs_targets, shots) tasks = (circuit, circuit.to_ir(ir_type=IRType.OPENQASM)) for task in tasks: result = device.run(task, **run_kwargs).result() @@ -451,10 +411,7 @@ def result_types_tensor_z_hermitian_testing(device: Device, run_kwargs: Dict[str 1057 - np.cos(2 * phi) + 12 * (27 + np.cos(2 * phi)) * np.cos(varphi) - - 2 - * np.cos(2 * varphi) - * np.sin(phi) - * (16 * np.cos(phi) + 21 * np.sin(phi)) + - 2 * np.cos(2 * varphi) * np.sin(phi) * (16 * np.cos(phi) + 21 * np.sin(phi)) + 16 * np.sin(2 * phi) - 8 * (-17 + np.cos(2 * phi) + 2 * np.sin(2 * phi)) * np.sin(varphi) - 8 * np.cos(2 * theta) * (3 + 3 * np.cos(varphi) + np.sin(varphi)) ** 2 @@ -493,19 +450,15 @@ def result_types_tensor_y_hermitian_testing(device: Device, run_kwargs: Dict[str theta = 0.432 phi = 0.123 varphi = -0.543 - array = np.array( - [ - [-6, 2 + 1j, -3, -5 + 2j], - [2 - 1j, 0, 2 - 1j, -5 + 4j], - [-3, 2 + 1j, 0, -4 + 3j], - [-5 - 2j, -5 - 4j, -4 - 3j, -6], - ] - ) + array = np.array([ + [-6, 2 + 1j, -3, -5 + 2j], + [2 - 1j, 0, 2 - 1j, -5 + 4j], + [-3, 2 + 1j, 0, -4 + 3j], + [-5 - 2j, -5 - 4j, -4 - 3j, -6], + ]) obs = Observable.Y() @ Observable.Hermitian(array) obs_targets = [0, 1, 2] - circuit = get_result_types_three_qubit_circuit( - theta, phi, varphi, obs, obs_targets, shots - ) + circuit = get_result_types_three_qubit_circuit(theta, phi, varphi, obs, obs_targets, shots) tasks = (circuit, circuit.to_ir(ir_type=IRType.OPENQASM)) for task in tasks: result = device.run(task, **run_kwargs).result() @@ -524,14 +477,12 @@ def result_types_noncommuting_testing(device: Device, run_kwargs: Dict[str, Any] theta = 0.432 phi = 0.123 varphi = -0.543 - array = np.array( - [ - [-6, 2 + 1j, -3, -5 + 2j], - [2 - 1j, 0, 2 - 1j, -5 + 4j], - [-3, 2 + 1j, 0, -4 + 3j], - [-5 - 2j, -5 - 4j, -4 - 3j, -6], - ] - ) + array = np.array([ + [-6, 2 + 1j, -3, -5 + 2j], + [2 - 1j, 0, 2 - 1j, -5 + 4j], + [-3, 2 + 1j, 0, -4 + 3j], + [-5 - 2j, -5 - 4j, -4 - 3j, -6], + ]) obs1 = Observable.X() @ Observable.Y() obs1_targets = [0, 2] obs2 = Observable.Z() @ Observable.Z() @@ -539,9 +490,7 @@ def result_types_noncommuting_testing(device: Device, run_kwargs: Dict[str, Any] obs3 = Observable.Y() @ Observable.Hermitian(array) obs3_targets = [0, 1, 2] circuit = ( - get_result_types_three_qubit_circuit( - theta, phi, varphi, obs1, obs1_targets, shots - ) + get_result_types_three_qubit_circuit(theta, phi, varphi, obs1, obs1_targets, shots) .expectation(obs2, obs2_targets) .expectation(obs3, obs3_targets) ) @@ -567,9 +516,7 @@ def result_types_noncommuting_testing(device: Device, run_kwargs: Dict[str, Any] assert np.allclose(result.values[3], expected_mean3) -def result_types_noncommuting_flipped_targets_testing( - device: Device, run_kwargs: Dict[str, Any] -): +def result_types_noncommuting_flipped_targets_testing(device: Device, run_kwargs: Dict[str, Any]): circuit = ( Circuit() .h(0) @@ -625,9 +572,7 @@ def run_circuit(circuit): assert len(result.measurements) == shots -def noisy_circuit_1qubit_noise_full_probability( - device: Device, run_kwargs: Dict[str, Any] -): +def noisy_circuit_1qubit_noise_full_probability(device: Device, run_kwargs: Dict[str, Any]): shots = run_kwargs["shots"] tol = get_tol(shots) circuit = Circuit().x(0).x(1).bit_flip(0, 0.1).probability() @@ -642,15 +587,13 @@ def noisy_circuit_1qubit_noise_full_probability( ) -def noisy_circuit_2qubit_noise_full_probability( - device: Device, run_kwargs: Dict[str, Any] -): +def noisy_circuit_2qubit_noise_full_probability(device: Device, run_kwargs: Dict[str, Any]): shots = run_kwargs["shots"] tol = get_tol(shots) K0 = np.eye(4) * np.sqrt(0.9) - K1 = np.kron( - np.array([[0.0, 1.0], [1.0, 0.0]]), np.array([[0.0, 1.0], [1.0, 0.0]]) - ) * np.sqrt(0.1) + K1 = np.kron(np.array([[0.0, 1.0], [1.0, 0.0]]), np.array([[0.0, 1.0], [1.0, 0.0]])) * np.sqrt( + 0.1 + ) circuit = Circuit().x(0).x(1).kraus((0, 1), [K0, K1]).probability() tasks = (circuit, circuit.to_ir(ir_type=IRType.OPENQASM)) for task in tasks: @@ -751,18 +694,14 @@ def openqasm_result_types_bell_pair_testing(device: Device, run_kwargs: Dict[str assert ( 0.6 < result.get_value_by_result_type( - ResultType.Expectation( - observable=Observable.H() @ Observable.X(), target=[0, 1] - ) + ResultType.Expectation(observable=Observable.H() @ Observable.X(), target=[0, 1]) ) < 0.8 ) assert ( len( result.get_value_by_result_type( - ResultType.Sample( - observable=Observable.H() @ Observable.X(), target=[0, 1] - ) + ResultType.Sample(observable=Observable.H() @ Observable.X(), target=[0, 1]) ) ) == run_kwargs["shots"] diff --git a/test/unit_tests/braket/simulator_v2/device_property_jsons.py b/test/unit_tests/braket/simulator_v2/device_property_jsons.py index bc3a755..24c4624 100644 --- a/test/unit_tests/braket/simulator_v2/device_property_jsons.py +++ b/test/unit_tests/braket/simulator_v2/device_property_jsons.py @@ -18,119 +18,157 @@ from braket.tasks import GateModelQuantumTaskResult ACTION_PROPERTIES = OpenQASMDeviceActionProperties.parse_raw( - json.dumps( - { - "actionType": "braket.ir.openqasm.program", - "version": ["1"], - "supportedOperations": ["rx", "ry", "h", "cy", "cnot", "unitary"], - "supportedResultTypes": [ - { - "name": "StateVector", - "observables": None, - "minShots": 0, - "maxShots": 0, - }, - { - "name": "AdjointGradient", - "observables": ["x", "y", "z", "h", "i"], - "minShots": 0, - "maxShots": 0, - }, - ], - } - ) + json.dumps({ + "actionType": "braket.ir.openqasm.program", + "version": ["1"], + "supportedOperations": ["rx", "ry", "h", "cy", "cnot", "unitary"], + "supportedResultTypes": [ + { + "name": "StateVector", + "observables": None, + "minShots": 0, + "maxShots": 0, + }, + { + "name": "AdjointGradient", + "observables": ["x", "y", "z", "h", "i"], + "minShots": 0, + "maxShots": 0, + }, + ], + }) ) ACTION_PROPERTIES_NO_ADJOINT = OpenQASMDeviceActionProperties.parse_raw( - json.dumps( - { - "actionType": "braket.ir.openqasm.program", - "version": ["1"], - "supportedOperations": ["rx", "ry", "h", "cy", "cnot", "unitary"], - "supportedResultTypes": [ - { - "name": "StateVector", - "observables": None, - "minShots": 0, - "maxShots": 0, - }, - ], - } - ) + json.dumps({ + "actionType": "braket.ir.openqasm.program", + "version": ["1"], + "supportedOperations": ["rx", "ry", "h", "cy", "cnot", "unitary"], + "supportedResultTypes": [ + { + "name": "StateVector", + "observables": None, + "minShots": 0, + "maxShots": 0, + }, + ], + }) ) ACTION_PROPERTIES_DM_DEVICE = OpenQASMDeviceActionProperties.parse_raw( - json.dumps( - { - "actionType": "braket.ir.openqasm.program", - "version": ["1"], - "supportedOperations": ["rx", "ry", "h", "cy", "cnot", "unitary"], - "supportedResultTypes": [ - { - "name": "StateVector", - "observables": None, - "minShots": 0, - "maxShots": 0, - }, - ], - "supportedPragmas": [ - "braket_noise_bit_flip", - "braket_noise_depolarizing", - "braket_noise_kraus", - "braket_noise_pauli_channel", - "braket_noise_generalized_amplitude_damping", - "braket_noise_amplitude_damping", - "braket_noise_phase_flip", - "braket_noise_phase_damping", - "braket_noise_two_qubit_dephasing", - "braket_noise_two_qubit_depolarizing", - "braket_unitary_matrix", - "braket_result_type_sample", - "braket_result_type_expectation", - "braket_result_type_variance", - "braket_result_type_probability", - "braket_result_type_density_matrix", - ], - } - ) + json.dumps({ + "actionType": "braket.ir.openqasm.program", + "version": ["1"], + "supportedOperations": ["rx", "ry", "h", "cy", "cnot", "unitary"], + "supportedResultTypes": [ + { + "name": "StateVector", + "observables": None, + "minShots": 0, + "maxShots": 0, + }, + ], + "supportedPragmas": [ + "braket_noise_bit_flip", + "braket_noise_depolarizing", + "braket_noise_kraus", + "braket_noise_pauli_channel", + "braket_noise_generalized_amplitude_damping", + "braket_noise_amplitude_damping", + "braket_noise_phase_flip", + "braket_noise_phase_damping", + "braket_noise_two_qubit_dephasing", + "braket_noise_two_qubit_depolarizing", + "braket_unitary_matrix", + "braket_result_type_sample", + "braket_result_type_expectation", + "braket_result_type_variance", + "braket_result_type_probability", + "braket_result_type_density_matrix", + ], + }) ) ACTION_PROPERTIES_NATIVE = OpenQASMDeviceActionProperties.parse_raw( - json.dumps( - { - "actionType": "braket.ir.openqasm.program", - "version": ["1"], - "supportedOperations": ["rx", "ry", "h", "cy", "cnot", "unitary"], - "supportedResultTypes": [ - { - "name": "StateVector", - "observables": None, - "minShots": 0, - "maxShots": 0, - }, - { - "name": "AdjointGradient", - "observables": ["x", "y", "z", "h", "i"], - "minShots": 0, - "maxShots": 0, - }, - ], - "supportedPragmas": ["verbatim"], - } - ) + json.dumps({ + "actionType": "braket.ir.openqasm.program", + "version": ["1"], + "supportedOperations": ["rx", "ry", "h", "cy", "cnot", "unitary"], + "supportedResultTypes": [ + { + "name": "StateVector", + "observables": None, + "minShots": 0, + "maxShots": 0, + }, + { + "name": "AdjointGradient", + "observables": ["x", "y", "z", "h", "i"], + "minShots": 0, + "maxShots": 0, + }, + ], + "supportedPragmas": ["verbatim"], + }) ) -GATE_MODEL_RESULT = GateModelTaskResult( - **{ - "measurements": [[0, 0], [0, 0], [0, 0], [1, 1]], - "measuredQubits": [0, 1], +GATE_MODEL_RESULT = GateModelTaskResult(**{ + "measurements": [[0, 0], [0, 0], [0, 0], [1, 1]], + "measuredQubits": [0, 1], + "taskMetadata": { + "braketSchemaHeader": { + "name": "braket.task_result.task_metadata", + "version": "1", + }, + "id": "task_arn", + "shots": 100, + "deviceId": "default", + }, + "additionalMetadata": { + "action": { + "braketSchemaHeader": { + "name": "braket.ir.openqasm.program", + "version": "1", + }, + "source": "qubit[2] q; cnot q[0], q[1]; measure q;", + }, + }, +}) + +RESULT = GateModelQuantumTaskResult.from_string( + json.dumps({ + "braketSchemaHeader": { + "name": "braket.task_result.gate_model_task_result", + "version": "1", + }, + "measurements": [[0, 0, 0, 0], [1, 1, 1, 1], [1, 1, 0, 0], [0, 0, 1, 1]], + "resultTypes": [ + {"type": {"targets": [0], "type": "probability"}, "value": [0.5, 0.5]}, + { + "type": { + "observable": ["x"], + "targets": [1], + "type": "expectation", + }, + "value": 0.0, + }, + { + "type": {"observable": ["y"], "targets": [2], "type": "variance"}, + "value": 0.1, + }, + { + "type": {"observable": ["z"], "targets": [3], "type": "sample"}, + "value": [1, -1, 1, 1], + }, + ], + "measuredQubits": [0, 1, 2, 3], "taskMetadata": { "braketSchemaHeader": { "name": "braket.task_result.task_metadata", "version": "1", }, "id": "task_arn", - "shots": 100, + "shots": 0, "deviceId": "default", }, "additionalMetadata": { @@ -142,318 +180,262 @@ "source": "qubit[2] q; cnot q[0], q[1]; measure q;", }, }, - } -) - -RESULT = GateModelQuantumTaskResult.from_string( - json.dumps( - { - "braketSchemaHeader": { - "name": "braket.task_result.gate_model_task_result", - "version": "1", - }, - "measurements": [[0, 0, 0, 0], [1, 1, 1, 1], [1, 1, 0, 0], [0, 0, 1, 1]], - "resultTypes": [ - {"type": {"targets": [0], "type": "probability"}, "value": [0.5, 0.5]}, - { - "type": { - "observable": ["x"], - "targets": [1], - "type": "expectation", - }, - "value": 0.0, - }, - { - "type": {"observable": ["y"], "targets": [2], "type": "variance"}, - "value": 0.1, - }, - { - "type": {"observable": ["z"], "targets": [3], "type": "sample"}, - "value": [1, -1, 1, 1], - }, - ], - "measuredQubits": [0, 1, 2, 3], - "taskMetadata": { - "braketSchemaHeader": { - "name": "braket.task_result.task_metadata", - "version": "1", - }, - "id": "task_arn", - "shots": 0, - "deviceId": "default", - }, - "additionalMetadata": { - "action": { - "braketSchemaHeader": { - "name": "braket.ir.openqasm.program", - "version": "1", - }, - "source": "qubit[2] q; cnot q[0], q[1]; measure q;", - }, - }, - } - ) + }) ) -OQC_PULSE_PROPERTIES_WITH_PORTS = json.dumps( - { - "braketSchemaHeader": { - "name": "braket.device_schema.pulse.pulse_device_action_properties", - "version": "1", +OQC_PULSE_PROPERTIES_WITH_PORTS = json.dumps({ + "braketSchemaHeader": { + "name": "braket.device_schema.pulse.pulse_device_action_properties", + "version": "1", + }, + "supportedQhpTemplateWaveforms": {}, + "ports": { + "channel_15": { + "portId": "channel_15", + "direction": "tx", + "portType": "port_type_1", + "dt": 5e-10, }, - "supportedQhpTemplateWaveforms": {}, - "ports": { - "channel_15": { - "portId": "channel_15", - "direction": "tx", - "portType": "port_type_1", - "dt": 5e-10, - }, - "channel_13": { - "portId": "channel_13", - "direction": "tx", - "portType": "port_type_1", - "dt": 5e-10, - }, + "channel_13": { + "portId": "channel_13", + "direction": "tx", + "portType": "port_type_1", + "dt": 5e-10, }, - "supportedFunctions": {}, - "frames": { - "q0_drive": { - "frameId": "q0_drive", - "portId": "channel_15", - "frequency": 4.6e9, - "centerFrequency": 4360000000.0, - "phase": 0.0, - "associatedGate": None, - "qubitMappings": [0], - "qhpSpecificProperties": None, - }, - "q1_drive": { - "frameId": "q1_drive", - "portId": "channel_13", - "frequency": 4.6e9, - "centerFrequency": 4360000000.0, - "phase": 0.0, - "associatedGate": None, - "qubitMappings": [0], - "qhpSpecificProperties": None, - }, + }, + "supportedFunctions": {}, + "frames": { + "q0_drive": { + "frameId": "q0_drive", + "portId": "channel_15", + "frequency": 4.6e9, + "centerFrequency": 4360000000.0, + "phase": 0.0, + "associatedGate": None, + "qubitMappings": [0], + "qhpSpecificProperties": None, }, - "supportsLocalPulseElements": False, - "supportsDynamicFrames": True, - "supportsNonNativeGatesWithPulses": True, - "validationParameters": { - "MAX_SCALE": 1.0, - "MAX_AMPLITUDE": 1.0, - "PERMITTED_FREQUENCY_DIFFERENCE": 1.0, - "MIN_PULSE_LENGTH": 8e-09, - "MAX_PULSE_LENGTH": 0.00012, + "q1_drive": { + "frameId": "q1_drive", + "portId": "channel_13", + "frequency": 4.6e9, + "centerFrequency": 4360000000.0, + "phase": 0.0, + "associatedGate": None, + "qubitMappings": [0], + "qhpSpecificProperties": None, }, - } -) + }, + "supportsLocalPulseElements": False, + "supportsDynamicFrames": True, + "supportsNonNativeGatesWithPulses": True, + "validationParameters": { + "MAX_SCALE": 1.0, + "MAX_AMPLITUDE": 1.0, + "PERMITTED_FREQUENCY_DIFFERENCE": 1.0, + "MIN_PULSE_LENGTH": 8e-09, + "MAX_PULSE_LENGTH": 0.00012, + }, +}) -OQC_PULSE_PROPERTIES_ALL_FRAMES = json.dumps( - { - "braketSchemaHeader": { - "name": "braket.device_schema.pulse.pulse_device_action_properties", - "version": "1", +OQC_PULSE_PROPERTIES_ALL_FRAMES = json.dumps({ + "braketSchemaHeader": { + "name": "braket.device_schema.pulse.pulse_device_action_properties", + "version": "1", + }, + "supportedQhpTemplateWaveforms": {}, + "ports": {}, + "supportedFunctions": {}, + "frames": { + "q0_drive": { + "frameId": "q0_drive", + "portId": "channel_15", + "frequency": 4.6e9, + "centerFrequency": 4360000000.0, + "phase": 0.0, + "associatedGate": None, + "qubitMappings": [0], + "qhpSpecificProperties": None, }, - "supportedQhpTemplateWaveforms": {}, - "ports": {}, - "supportedFunctions": {}, - "frames": { - "q0_drive": { - "frameId": "q0_drive", - "portId": "channel_15", - "frequency": 4.6e9, - "centerFrequency": 4360000000.0, - "phase": 0.0, - "associatedGate": None, - "qubitMappings": [0], - "qhpSpecificProperties": None, - }, - "q0_second_state": { - "frameId": "q0_second_state", - "portId": "channel_15", - "frequency": 4.5e9, - "centerFrequency": 4360000000.0, - "phase": 0.0, - "associatedGate": None, - "qubitMappings": [0], - "qhpSpecificProperties": None, - }, - "q1_drive": { - "frameId": "q1_drive", - "portId": "channel_15", - "frequency": 4.6e9, - "centerFrequency": 4360000000.0, - "phase": 0.0, - "associatedGate": None, - "qubitMappings": [0], - "qhpSpecificProperties": None, - }, - "q1_second_state": { - "frameId": "q1_second_state", - "portId": "channel_15", - "frequency": 4.5e9, - "centerFrequency": 4360000000.0, - "phase": 0.0, - "associatedGate": None, - "qubitMappings": [0], - "qhpSpecificProperties": None, - }, - "q2_drive": { - "frameId": "q2_drive", - "portId": "channel_15", - "frequency": 4.6e9, - "centerFrequency": 4360000000.0, - "phase": 0.0, - "associatedGate": None, - "qubitMappings": [0], - "qhpSpecificProperties": None, - }, - "q2_second_state": { - "frameId": "q2_second_state", - "portId": "channel_15", - "frequency": 4.5e9, - "centerFrequency": 4360000000.0, - "phase": 0.0, - "associatedGate": None, - "qubitMappings": [0], - "qhpSpecificProperties": None, - }, - "q3_drive": { - "frameId": "q3_drive", - "portId": "channel_15", - "frequency": 4.6e9, - "centerFrequency": 4360000000.0, - "phase": 0.0, - "associatedGate": None, - "qubitMappings": [0], - "qhpSpecificProperties": None, - }, - "q3_second_state": { - "frameId": "q3_second_state", - "portId": "channel_15", - "frequency": 4.5e9, - "centerFrequency": 4360000000.0, - "phase": 0.0, - "associatedGate": None, - "qubitMappings": [0], - "qhpSpecificProperties": None, - }, - "q4_drive": { - "frameId": "q4_drive", - "portId": "channel_15", - "frequency": 4.6e9, - "centerFrequency": 4360000000.0, - "phase": 0.0, - "associatedGate": None, - "qubitMappings": [0], - "qhpSpecificProperties": None, - }, - "q4_second_state": { - "frameId": "q4_second_state", - "portId": "channel_15", - "frequency": 4.5e9, - "centerFrequency": 4360000000.0, - "phase": 0.0, - "associatedGate": None, - "qubitMappings": [0], - "qhpSpecificProperties": None, - }, - "q5_drive": { - "frameId": "q5_drive", - "portId": "channel_15", - "frequency": 4.6e9, - "centerFrequency": 4360000000.0, - "phase": 0.0, - "associatedGate": None, - "qubitMappings": [0], - "qhpSpecificProperties": None, - }, - "q5_second_state": { - "frameId": "q5_second_state", - "portId": "channel_15", - "frequency": 4.5e9, - "centerFrequency": 4360000000.0, - "phase": 0.0, - "associatedGate": None, - "qubitMappings": [0], - "qhpSpecificProperties": None, - }, - "q6_drive": { - "frameId": "q6_drive", - "portId": "channel_15", - "frequency": 4.6e9, - "centerFrequency": 4360000000.0, - "phase": 0.0, - "associatedGate": None, - "qubitMappings": [0], - "qhpSpecificProperties": None, - }, - "q6_second_state": { - "frameId": "q6_second_state", - "portId": "channel_15", - "frequency": 4.5e9, - "centerFrequency": 4360000000.0, - "phase": 0.0, - "associatedGate": None, - "qubitMappings": [0], - "qhpSpecificProperties": None, - }, - "q7_drive": { - "frameId": "q7_drive", - "portId": "channel_15", - "frequency": 4.6e9, - "centerFrequency": 4360000000.0, - "phase": 0.0, - "associatedGate": None, - "qubitMappings": [0], - "qhpSpecificProperties": None, - }, - "q7_second_state": { - "frameId": "q7_second_state", - "portId": "channel_15", - "frequency": 4.5e9, - "centerFrequency": 4360000000.0, - "phase": 0.0, - "associatedGate": None, - "qubitMappings": [0], - "qhpSpecificProperties": None, - }, + "q0_second_state": { + "frameId": "q0_second_state", + "portId": "channel_15", + "frequency": 4.5e9, + "centerFrequency": 4360000000.0, + "phase": 0.0, + "associatedGate": None, + "qubitMappings": [0], + "qhpSpecificProperties": None, }, - "supportsLocalPulseElements": False, - "supportsDynamicFrames": True, - "supportsNonNativeGatesWithPulses": True, - "validationParameters": { - "MAX_SCALE": 1.0, - "MAX_AMPLITUDE": 1.0, - "PERMITTED_FREQUENCY_DIFFERENCE": 1.0, - "MIN_PULSE_LENGTH": 8e-09, - "MAX_PULSE_LENGTH": 0.00012, + "q1_drive": { + "frameId": "q1_drive", + "portId": "channel_15", + "frequency": 4.6e9, + "centerFrequency": 4360000000.0, + "phase": 0.0, + "associatedGate": None, + "qubitMappings": [0], + "qhpSpecificProperties": None, }, - } -) - -OQC_PARADIGM_PROPERTIES = json.dumps( - { - "braketSchemaHeader": { - "name": "braket.device_schema.gate_model_qpu_paradigm_properties", - "version": "1", + "q1_second_state": { + "frameId": "q1_second_state", + "portId": "channel_15", + "frequency": 4.5e9, + "centerFrequency": 4360000000.0, + "phase": 0.0, + "associatedGate": None, + "qubitMappings": [0], + "qhpSpecificProperties": None, }, - "connectivity": { - "fullyConnected": False, - "connectivityGraph": { - "0": ["1", "7"], - "1": ["2"], - "2": ["3"], - "4": ["3", "5"], - "6": ["5"], - "7": ["6"], - }, + "q2_drive": { + "frameId": "q2_drive", + "portId": "channel_15", + "frequency": 4.6e9, + "centerFrequency": 4360000000.0, + "phase": 0.0, + "associatedGate": None, + "qubitMappings": [0], + "qhpSpecificProperties": None, }, - "qubitCount": 8, - "nativeGateSet": ["ecr", "i", "rz", "v", "x"], - } -) + "q2_second_state": { + "frameId": "q2_second_state", + "portId": "channel_15", + "frequency": 4.5e9, + "centerFrequency": 4360000000.0, + "phase": 0.0, + "associatedGate": None, + "qubitMappings": [0], + "qhpSpecificProperties": None, + }, + "q3_drive": { + "frameId": "q3_drive", + "portId": "channel_15", + "frequency": 4.6e9, + "centerFrequency": 4360000000.0, + "phase": 0.0, + "associatedGate": None, + "qubitMappings": [0], + "qhpSpecificProperties": None, + }, + "q3_second_state": { + "frameId": "q3_second_state", + "portId": "channel_15", + "frequency": 4.5e9, + "centerFrequency": 4360000000.0, + "phase": 0.0, + "associatedGate": None, + "qubitMappings": [0], + "qhpSpecificProperties": None, + }, + "q4_drive": { + "frameId": "q4_drive", + "portId": "channel_15", + "frequency": 4.6e9, + "centerFrequency": 4360000000.0, + "phase": 0.0, + "associatedGate": None, + "qubitMappings": [0], + "qhpSpecificProperties": None, + }, + "q4_second_state": { + "frameId": "q4_second_state", + "portId": "channel_15", + "frequency": 4.5e9, + "centerFrequency": 4360000000.0, + "phase": 0.0, + "associatedGate": None, + "qubitMappings": [0], + "qhpSpecificProperties": None, + }, + "q5_drive": { + "frameId": "q5_drive", + "portId": "channel_15", + "frequency": 4.6e9, + "centerFrequency": 4360000000.0, + "phase": 0.0, + "associatedGate": None, + "qubitMappings": [0], + "qhpSpecificProperties": None, + }, + "q5_second_state": { + "frameId": "q5_second_state", + "portId": "channel_15", + "frequency": 4.5e9, + "centerFrequency": 4360000000.0, + "phase": 0.0, + "associatedGate": None, + "qubitMappings": [0], + "qhpSpecificProperties": None, + }, + "q6_drive": { + "frameId": "q6_drive", + "portId": "channel_15", + "frequency": 4.6e9, + "centerFrequency": 4360000000.0, + "phase": 0.0, + "associatedGate": None, + "qubitMappings": [0], + "qhpSpecificProperties": None, + }, + "q6_second_state": { + "frameId": "q6_second_state", + "portId": "channel_15", + "frequency": 4.5e9, + "centerFrequency": 4360000000.0, + "phase": 0.0, + "associatedGate": None, + "qubitMappings": [0], + "qhpSpecificProperties": None, + }, + "q7_drive": { + "frameId": "q7_drive", + "portId": "channel_15", + "frequency": 4.6e9, + "centerFrequency": 4360000000.0, + "phase": 0.0, + "associatedGate": None, + "qubitMappings": [0], + "qhpSpecificProperties": None, + }, + "q7_second_state": { + "frameId": "q7_second_state", + "portId": "channel_15", + "frequency": 4.5e9, + "centerFrequency": 4360000000.0, + "phase": 0.0, + "associatedGate": None, + "qubitMappings": [0], + "qhpSpecificProperties": None, + }, + }, + "supportsLocalPulseElements": False, + "supportsDynamicFrames": True, + "supportsNonNativeGatesWithPulses": True, + "validationParameters": { + "MAX_SCALE": 1.0, + "MAX_AMPLITUDE": 1.0, + "PERMITTED_FREQUENCY_DIFFERENCE": 1.0, + "MIN_PULSE_LENGTH": 8e-09, + "MAX_PULSE_LENGTH": 0.00012, + }, +}) + +OQC_PARADIGM_PROPERTIES = json.dumps({ + "braketSchemaHeader": { + "name": "braket.device_schema.gate_model_qpu_paradigm_properties", + "version": "1", + }, + "connectivity": { + "fullyConnected": False, + "connectivityGraph": { + "0": ["1", "7"], + "1": ["2"], + "2": ["3"], + "4": ["3", "5"], + "6": ["5"], + "7": ["6"], + }, + }, + "qubitCount": 8, + "nativeGateSet": ["ecr", "i", "rz", "v", "x"], +}) diff --git a/test/unit_tests/braket/simulator_v2/test_density_matrix_simulator_v2.py b/test/unit_tests/braket/simulator_v2/test_density_matrix_simulator_v2.py index 63458f8..df6ff02 100644 --- a/test/unit_tests/braket/simulator_v2/test_density_matrix_simulator_v2.py +++ b/test/unit_tests/braket/simulator_v2/test_density_matrix_simulator_v2.py @@ -77,9 +77,9 @@ def test_simulator_run_noisy_circuit(noisy_circuit_2_qubit, caplog): assert all([len(measurement) == 2] for measurement in result.measurements) assert len(result.measurements) == shots_count - counter = Counter( - ["".join([str(m) for m in measurement]) for measurement in result.measurements] - ) + counter = Counter([ + "".join([str(m) for m in measurement]) for measurement in result.measurements + ]) assert counter.keys() == {"10", "11"} assert 0.0 < counter["10"] / (counter["10"] + counter["11"]) < 0.2 assert 0.8 < counter["11"] / (counter["10"] + counter["11"]) < 1.0 @@ -99,9 +99,9 @@ def test_simulator_run_bell_pair(bell_ir, caplog): assert all([len(measurement) == 2] for measurement in result.measurements) assert len(result.measurements) == shots_count - counter = Counter( - ["".join([str(m) for m in measurement]) for measurement in result.measurements] - ) + counter = Counter([ + "".join([str(m) for m in measurement]) for measurement in result.measurements + ]) assert counter.keys() == {"00", "11"} assert 0.4 < counter["00"] / (counter["00"] + counter["11"]) < 0.6 assert 0.4 < counter["11"] / (counter["00"] + counter["11"]) < 0.6 @@ -124,9 +124,7 @@ def test_simulator_run_grcs_8(grcs_8_qubit): simulator = DensityMatrixSimulator() result = simulator.run(grcs_8_qubit.circuit_ir, shots=0) density_matrix = result.resultTypes[0].value - assert cmath.isclose( - density_matrix[0][0].real, grcs_8_qubit.probability_zero, abs_tol=1e-7 - ) + assert cmath.isclose(density_matrix[0][0].real, grcs_8_qubit.probability_zero, abs_tol=1e-7) def test_properties(): @@ -134,157 +132,153 @@ def test_properties(): observables = ["x", "y", "z", "h", "i", "hermitian"] max_shots = sys.maxsize qubit_count = 16 - expected_properties = GateModelSimulatorDeviceCapabilities.parse_obj( - { - "service": { - "executionWindows": [ + expected_properties = GateModelSimulatorDeviceCapabilities.parse_obj({ + "service": { + "executionWindows": [ + { + "executionDay": "Everyday", + "windowStartHour": "00:00", + "windowEndHour": "23:59:59", + } + ], + "shotsRange": [0, max_shots], + }, + "action": { + "braket.ir.openqasm.program": { + "actionType": "braket.ir.openqasm.program", + "version": ["1"], + "supportedOperations": sorted([ + # OpenQASM primitives + "U", + "GPhase", + # builtin Braket gates + "ccnot", + "cnot", + "cphaseshift", + "cphaseshift00", + "cphaseshift01", + "cphaseshift10", + "cswap", + "cv", + "cy", + "cz", + "ecr", + "gpi", + "gpi2", + "h", + "i", + "iswap", + "ms", + "pswap", + "phaseshift", + "rx", + "ry", + "rz", + "s", + "si", + "swap", + "t", + "ti", + "unitary", + "v", + "vi", + "x", + "xx", + "xy", + "y", + "yy", + "z", + "zz", + # noise operations + "bit_flip", + "phase_flip", + "pauli_channel", + "depolarizing", + "two_qubit_depolarizing", + "two_qubit_dephasing", + "amplitude_damping", + "generalized_amplitude_damping", + "phase_damping", + "kraus", + ]), + "supportedModifiers": [ + { + "name": "ctrl", + }, { - "executionDay": "Everyday", - "windowStartHour": "00:00", - "windowEndHour": "23:59:59", - } + "name": "negctrl", + }, + { + "name": "pow", + "exponent_types": ["int", "float"], + }, + { + "name": "inv", + }, ], - "shotsRange": [0, max_shots], - }, - "action": { - "braket.ir.openqasm.program": { - "actionType": "braket.ir.openqasm.program", - "version": ["1"], - "supportedOperations": sorted( - [ - # OpenQASM primitives - "U", - "GPhase", - # builtin Braket gates - "ccnot", - "cnot", - "cphaseshift", - "cphaseshift00", - "cphaseshift01", - "cphaseshift10", - "cswap", - "cv", - "cy", - "cz", - "ecr", - "gpi", - "gpi2", - "h", - "i", - "iswap", - "ms", - "pswap", - "phaseshift", - "rx", - "ry", - "rz", - "s", - "si", - "swap", - "t", - "ti", - "unitary", - "v", - "vi", - "x", - "xx", - "xy", - "y", - "yy", - "z", - "zz", - # noise operations - "bit_flip", - "phase_flip", - "pauli_channel", - "depolarizing", - "two_qubit_depolarizing", - "two_qubit_dephasing", - "amplitude_damping", - "generalized_amplitude_damping", - "phase_damping", - "kraus", - ] - ), - "supportedModifiers": [ - { - "name": "ctrl", - }, - { - "name": "negctrl", - }, - { - "name": "pow", - "exponent_types": ["int", "float"], - }, - { - "name": "inv", - }, - ], - "supportedPragmas": [ - "braket_unitary_matrix", - "braket_result_type_density_matrix", - "braket_result_type_sample", - "braket_result_type_expectation", - "braket_result_type_variance", - "braket_result_type_probability", - "braket_result_type_amplitude", - "braket_noise_amplitude_damping", - "braket_noise_bit_flip", - "braket_noise_depolarizing", - "braket_noise_kraus", - "braket_noise_pauli_channel", - "braket_noise_generalized_amplitude_damping", - "braket_noise_phase_flip", - "braket_noise_phase_damping", - "braket_noise_two_qubit_dephasing", - "braket_noise_two_qubit_depolarizing", - ], - "forbiddenPragmas": [ - "braket_result_type_adjoint_gradient", - ], - "supportedResultTypes": [ - { - "name": "Sample", - "observables": observables, - "minShots": 1, - "maxShots": max_shots, - }, - { - "name": "Expectation", - "observables": observables, - "minShots": 0, - "maxShots": max_shots, - }, - { - "name": "Variance", - "observables": observables, - "minShots": 0, - "maxShots": max_shots, - }, - { - "name": "Probability", - "minShots": 0, - "maxShots": max_shots, - }, - { - "name": "DensityMatrix", - "minShots": 0, - "maxShots": 0, - }, - ], - "supportPhysicalQubits": False, - "supportsPartialVerbatimBox": False, - "requiresContiguousQubitIndices": True, - "requiresAllQubitsMeasurement": True, - "supportsUnassignedMeasurements": True, - "disabledQubitRewiringSupported": False, - }, + "supportedPragmas": [ + "braket_unitary_matrix", + "braket_result_type_density_matrix", + "braket_result_type_sample", + "braket_result_type_expectation", + "braket_result_type_variance", + "braket_result_type_probability", + "braket_result_type_amplitude", + "braket_noise_amplitude_damping", + "braket_noise_bit_flip", + "braket_noise_depolarizing", + "braket_noise_kraus", + "braket_noise_pauli_channel", + "braket_noise_generalized_amplitude_damping", + "braket_noise_phase_flip", + "braket_noise_phase_damping", + "braket_noise_two_qubit_dephasing", + "braket_noise_two_qubit_depolarizing", + ], + "forbiddenPragmas": [ + "braket_result_type_adjoint_gradient", + ], + "supportedResultTypes": [ + { + "name": "Sample", + "observables": observables, + "minShots": 1, + "maxShots": max_shots, + }, + { + "name": "Expectation", + "observables": observables, + "minShots": 0, + "maxShots": max_shots, + }, + { + "name": "Variance", + "observables": observables, + "minShots": 0, + "maxShots": max_shots, + }, + { + "name": "Probability", + "minShots": 0, + "maxShots": max_shots, + }, + { + "name": "DensityMatrix", + "minShots": 0, + "maxShots": 0, + }, + ], + "supportPhysicalQubits": False, + "supportsPartialVerbatimBox": False, + "requiresContiguousQubitIndices": True, + "requiresAllQubitsMeasurement": True, + "supportsUnassignedMeasurements": True, + "disabledQubitRewiringSupported": False, }, - "paradigm": {"qubitCount": qubit_count}, - "deviceParameters": GateModelSimulatorDeviceParameters.schema(), - } - ) + }, + "paradigm": {"qubitCount": qubit_count}, + "deviceParameters": GateModelSimulatorDeviceParameters.schema(), + }) assert simulator.properties == expected_properties diff --git a/test/unit_tests/braket/simulator_v2/test_pennylane.py b/test/unit_tests/braket/simulator_v2/test_pennylane.py index f26e8ce..19f2fdc 100644 --- a/test/unit_tests/braket/simulator_v2/test_pennylane.py +++ b/test/unit_tests/braket/simulator_v2/test_pennylane.py @@ -36,9 +36,7 @@ TASK_BATCH.results.return_value = [RESULT, RESULT] type(TASK_BATCH).tasks = PropertyMock(return_value=[TASK, TASK]) SIM_TASK = Mock() -SIM_TASK.result.return_value.additional_metadata.simulatorMetadata.executionDuration = ( - 1234 -) +SIM_TASK.result.return_value.additional_metadata.simulatorMetadata.executionDuration = 1234 SIM_TASK.result.return_value.result_types = [] type(SIM_TASK).id = PropertyMock(return_value="task_arn") SIM_TASK.state.return_value = "COMPLETED" @@ -86,9 +84,7 @@ qml.RY(0.543, wires=0), ], measurements=[ - qml.expval( - 2 * qml.PauliX(0) @ qml.PauliY(1) + 0.75 * qml.PauliY(0) @ qml.PauliZ(1) - ), + qml.expval(2 * qml.PauliX(0) @ qml.PauliY(1) + 0.75 * qml.PauliY(0) @ qml.PauliZ(1)), ], ) CIRCUIT_3.trainable_params = [0, 1] @@ -192,9 +188,7 @@ def test_local_sim_batch_execute_parallel_tracker(mock_run_batch): """Asserts tracker updates during parallel execution for local simulators""" mock_run_batch.return_value = TASK_BATCH - dev = BraketLocalQubitDevice( - backend="braket_sv_v2", wires=1, shots=SHOTS, parallel=True - ) + dev = BraketLocalQubitDevice(backend="braket_sv_v2", wires=1, shots=SHOTS, parallel=True) type(TASK_BATCH).unsuccessful = PropertyMock(return_value={}) with QuantumTape() as circuit: @@ -304,35 +298,33 @@ def qnode(thetas, measure_type, observable): def get_test_result_object(rts=[], source="qubit[2] q; cnot q[0], q[1]; measure q;"): - json_str = json.dumps( - { + json_str = json.dumps({ + "braketSchemaHeader": { + "name": "braket.task_result.gate_model_task_result", + "version": "1", + }, + "measurements": [[0, 0, 0, 0], [1, 1, 1, 1], [1, 1, 0, 0], [0, 0, 1, 1]], + "resultTypes": rts, + "measuredQubits": [0, 1, 2, 3], + "taskMetadata": { "braketSchemaHeader": { - "name": "braket.task_result.gate_model_task_result", + "name": "braket.task_result.task_metadata", "version": "1", }, - "measurements": [[0, 0, 0, 0], [1, 1, 1, 1], [1, 1, 0, 0], [0, 0, 1, 1]], - "resultTypes": rts, - "measuredQubits": [0, 1, 2, 3], - "taskMetadata": { + "id": "task_arn", + "shots": 0, + "deviceId": "default", + }, + "additionalMetadata": { + "action": { "braketSchemaHeader": { - "name": "braket.task_result.task_metadata", + "name": "braket.ir.openqasm.program", "version": "1", }, - "id": "task_arn", - "shots": 0, - "deviceId": "default", + "source": source, }, - "additionalMetadata": { - "action": { - "braketSchemaHeader": { - "name": "braket.ir.openqasm.program", - "version": "1", - }, - "source": source, - }, - }, - } - ) + }, + }) return GateModelQuantumTaskResult.from_string(json_str) @@ -350,9 +342,7 @@ def test_valid_local_device_for_noise_model(backend, noise_model): dev = BraketLocalQubitDevice(wires=2, backend=backend, noise_model=noise_model) assert dev._noise_model.instructions == [ NoiseModelInstruction(Noise.BitFlip(0.05), GateCriteria(Gate.H)), - NoiseModelInstruction( - Noise.TwoQubitDepolarizing(0.10), GateCriteria(Gate.CNot) - ), + NoiseModelInstruction(Noise.TwoQubitDepolarizing(0.10), GateCriteria(Gate.CNot)), ] diff --git a/test/unit_tests/braket/simulator_v2/test_qiskit_provider.py b/test/unit_tests/braket/simulator_v2/test_qiskit_provider.py index c5a8830..ed217d3 100644 --- a/test/unit_tests/braket/simulator_v2/test_qiskit_provider.py +++ b/test/unit_tests/braket/simulator_v2/test_qiskit_provider.py @@ -16,15 +16,13 @@ @pytest.fixture def H2_op(): # Define the Hamiltonian operator for H2 in terms of Pauli spin operators - return SparsePauliOp.from_list( - [ - ("II", -1.052373245772859), - ("IZ", 0.39793742484318045), - ("ZI", -0.39793742484318045), - ("ZZ", -0.01128010425623538), - ("XX", 0.18093119978423156), - ] - ) + return SparsePauliOp.from_list([ + ("II", -1.052373245772859), + ("IZ", 0.39793742484318045), + ("ZI", -0.39793742484318045), + ("ZZ", -0.01128010425623538), + ("XX", 0.18093119978423156), + ]) @pytest.fixture diff --git a/test/unit_tests/braket/simulator_v2/test_state_vector_simulator_v2.py b/test/unit_tests/braket/simulator_v2/test_state_vector_simulator_v2.py index 4935f57..53b91f8 100644 --- a/test/unit_tests/braket/simulator_v2/test_state_vector_simulator_v2.py +++ b/test/unit_tests/braket/simulator_v2/test_state_vector_simulator_v2.py @@ -72,9 +72,7 @@ def test_simulator_run_grcs_16(grcs_16_qubit, batch_size): simulator = StateVectorSimulator() result = simulator.run(grcs_16_qubit.circuit_ir, shots=0, batch_size=batch_size) state_vector = result.resultTypes[0].value - assert cmath.isclose( - abs(state_vector[0]) ** 2, grcs_16_qubit.probability_zero, abs_tol=1e-7 - ) + assert cmath.isclose(abs(state_vector[0]) ** 2, grcs_16_qubit.probability_zero, abs_tol=1e-7) @pytest.mark.parametrize("batch_size", [1]) @@ -85,9 +83,9 @@ def test_simulator_run_bell_pair(bell_ir, batch_size, caplog): assert all([len(measurement) == 2] for measurement in result.measurements) assert len(result.measurements) == shots_count - counter = Counter( - ["".join([str(m) for m in measurement]) for measurement in result.measurements] - ) + counter = Counter([ + "".join([str(m) for m in measurement]) for measurement in result.measurements + ]) assert counter.keys() == {"00", "11"} assert 0.4 < counter["00"] / (counter["00"] + counter["11"]) < 0.6 assert 0.4 < counter["11"] / (counter["00"] + counter["11"]) < 0.6 @@ -105,147 +103,146 @@ def test_properties(): observables = ["x", "y", "z", "h", "i", "hermitian"] max_shots = sys.maxsize qubit_count = 32 - expected_properties = GateModelSimulatorDeviceCapabilities.parse_obj( - { - "service": { - "executionWindows": [ + + expected_properties = GateModelSimulatorDeviceCapabilities.parse_obj({ + "service": { + "executionWindows": [ + { + "executionDay": "Everyday", + "windowStartHour": "00:00", + "windowEndHour": "23:59:59", + } + ], + "shotsRange": [0, max_shots], + }, + "action": { + "braket.ir.openqasm.program": { + "actionType": "braket.ir.openqasm.program", + "version": ["1"], + "supportedOperations": [ + # OpenQASM primitives + "U", + "GPhase", + # builtin Braket gates + "ccnot", + "cnot", + "cphaseshift", + "cphaseshift00", + "cphaseshift01", + "cphaseshift10", + "cswap", + "cv", + "cy", + "cz", + "ecr", + "gpi", + "gpi2", + "h", + "i", + "iswap", + "ms", + "pswap", + "phaseshift", + "rx", + "ry", + "rz", + "s", + "si", + "swap", + "t", + "ti", + "unitary", + "v", + "vi", + "x", + "xx", + "xy", + "y", + "yy", + "z", + "zz", + ], + "supportedModifiers": [ + { + "name": "ctrl", + }, + { + "name": "negctrl", + }, { - "executionDay": "Everyday", - "windowStartHour": "00:00", - "windowEndHour": "23:59:59", - } + "name": "pow", + "exponent_types": ["int", "float"], + }, + { + "name": "inv", + }, ], - "shotsRange": [0, max_shots], - }, - "action": { - "braket.ir.openqasm.program": { - "actionType": "braket.ir.openqasm.program", - "version": ["1"], - "supportedOperations": [ - # OpenQASM primitives - "U", - "GPhase", - # builtin Braket gates - "ccnot", - "cnot", - "cphaseshift", - "cphaseshift00", - "cphaseshift01", - "cphaseshift10", - "cswap", - "cv", - "cy", - "cz", - "ecr", - "gpi", - "gpi2", - "h", - "i", - "iswap", - "ms", - "pswap", - "phaseshift", - "rx", - "ry", - "rz", - "s", - "si", - "swap", - "t", - "ti", - "unitary", - "v", - "vi", - "x", - "xx", - "xy", - "y", - "yy", - "z", - "zz", - ], - "supportedModifiers": [ - { - "name": "ctrl", - }, - { - "name": "negctrl", - }, - { - "name": "pow", - "exponent_types": ["int", "float"], - }, - { - "name": "inv", - }, - ], - "supportedPragmas": [ - "braket_unitary_matrix", - "braket_result_type_state_vector", - "braket_result_type_density_matrix", - "braket_result_type_sample", - "braket_result_type_expectation", - "braket_result_type_variance", - "braket_result_type_probability", - "braket_result_type_amplitude", - ], - "forbiddenPragmas": [ - "braket_noise_amplitude_damping", - "braket_noise_bit_flip", - "braket_noise_depolarizing", - "braket_noise_kraus", - "braket_noise_pauli_channel", - "braket_noise_generalized_amplitude_damping", - "braket_noise_phase_flip", - "braket_noise_phase_damping", - "braket_noise_two_qubit_dephasing", - "braket_noise_two_qubit_depolarizing", - "braket_result_type_adjoint_gradient", - ], - "supportedResultTypes": [ - { - "name": "Sample", - "observables": observables, - "minShots": 1, - "maxShots": max_shots, - }, - { - "name": "Expectation", - "observables": observables, - "minShots": 0, - "maxShots": max_shots, - }, - { - "name": "Variance", - "observables": observables, - "minShots": 0, - "maxShots": max_shots, - }, - { - "name": "Probability", - "minShots": 0, - "maxShots": max_shots, - }, - {"name": "StateVector", "minShots": 0, "maxShots": 0}, - { - "name": "DensityMatrix", - "minShots": 0, - "maxShots": 0, - }, - {"name": "Amplitude", "minShots": 0, "maxShots": 0}, - ], - "supportPhysicalQubits": False, - "supportsPartialVerbatimBox": False, - "requiresContiguousQubitIndices": True, - "requiresAllQubitsMeasurement": True, - "supportsUnassignedMeasurements": True, - "disabledQubitRewiringSupported": False, - }, + "supportedPragmas": [ + "braket_unitary_matrix", + "braket_result_type_state_vector", + "braket_result_type_density_matrix", + "braket_result_type_sample", + "braket_result_type_expectation", + "braket_result_type_variance", + "braket_result_type_probability", + "braket_result_type_amplitude", + ], + "forbiddenPragmas": [ + "braket_noise_amplitude_damping", + "braket_noise_bit_flip", + "braket_noise_depolarizing", + "braket_noise_kraus", + "braket_noise_pauli_channel", + "braket_noise_generalized_amplitude_damping", + "braket_noise_phase_flip", + "braket_noise_phase_damping", + "braket_noise_two_qubit_dephasing", + "braket_noise_two_qubit_depolarizing", + "braket_result_type_adjoint_gradient", + ], + "supportedResultTypes": [ + { + "name": "Sample", + "observables": observables, + "minShots": 1, + "maxShots": max_shots, + }, + { + "name": "Expectation", + "observables": observables, + "minShots": 0, + "maxShots": max_shots, + }, + { + "name": "Variance", + "observables": observables, + "minShots": 0, + "maxShots": max_shots, + }, + { + "name": "Probability", + "minShots": 0, + "maxShots": max_shots, + }, + {"name": "StateVector", "minShots": 0, "maxShots": 0}, + { + "name": "DensityMatrix", + "minShots": 0, + "maxShots": 0, + }, + {"name": "Amplitude", "minShots": 0, "maxShots": 0}, + ], + "supportPhysicalQubits": False, + "supportsPartialVerbatimBox": False, + "requiresContiguousQubitIndices": True, + "requiresAllQubitsMeasurement": True, + "supportsUnassignedMeasurements": True, + "disabledQubitRewiringSupported": False, }, - "paradigm": {"qubitCount": qubit_count}, - "deviceParameters": GateModelSimulatorDeviceParameters.schema(), - } - ) + }, + "paradigm": {"qubitCount": qubit_count}, + "deviceParameters": GateModelSimulatorDeviceParameters.schema(), + }) assert simulator.properties == expected_properties @@ -396,9 +393,7 @@ def test_result_types_analytic(): assert result_types[14].type == Expectation(observable=("z",), targets=(0,)) assert result_types[15].type == Expectation(observable=("x",)) assert result_types[16].type == Expectation(observable=("y",)) - assert result_types[17].type == Variance( - observable=("x", "z", "h"), targets=(0, 2, 1) - ) + assert result_types[17].type == Variance(observable=("x", "z", "h"), targets=(0, 2, 1)) assert result_types[18].type == Expectation( observable=([[[0, 0], [0, -1]], [[0, 1], [0, 0]]],), targets=(0,), @@ -587,12 +582,9 @@ def test_simulator_identity(caplog): program, shots=shots_count, ) - counter = Counter( - [ - "".join([str(m) for m in measurement]) - for measurement in result.measurements - ] - ) + counter = Counter([ + "".join([str(m) for m in measurement]) for measurement in result.measurements + ]) assert counter.keys() == {"00"} assert counter["00"] == shots_count assert not caplog.text @@ -718,9 +710,7 @@ def test_simulator_run_observable_references_invalid_qubit(ir, qubit_count): @pytest.mark.parametrize("batch_size", [1]) @pytest.mark.parametrize("targets", [(None), ([1]), ([0])]) -def test_simulator_bell_pair_result_types( - bell_ir_with_result, targets, batch_size, caplog -): +def test_simulator_bell_pair_result_types(bell_ir_with_result, targets, batch_size, caplog): simulator = StateVectorSimulator() ir = bell_ir_with_result(targets) result = simulator.run(ir, shots=0, batch_size=batch_size) @@ -811,13 +801,11 @@ def test_simulator_valid_observables_qasm(result_types, expected, caplog): def test_observable_hash_tensor_product(): matrix = np.eye(4) - obs = observables.TensorProduct( - [ - observables.PauliX([0]), - observables.Hermitian(matrix, [1, 2]), - observables.PauliY([1]), - ] - ) + obs = observables.TensorProduct([ + observables.PauliX([0]), + observables.Hermitian(matrix, [1, 2]), + observables.PauliY([1]), + ]) hash_dict = StateVectorSimulator._observable_hash(obs) matrix_hash = hash_dict[1] assert hash_dict == { @@ -1170,8 +1158,6 @@ def test_run_multiple_executor(): fs = {pool.submit(simulator.run_multiple, payloads): ix for ix in range(10)} for future in as_completed(fs): results = future.result() - assert np.allclose( - results[0].resultTypes[0].value, np.array([1, 1]) / np.sqrt(2) - ) + assert np.allclose(results[0].resultTypes[0].value, np.array([1, 1]) / np.sqrt(2)) assert np.allclose(results[1].resultTypes[0].value, np.array([1, 0])) assert np.allclose(results[2].resultTypes[0].value, np.array([0, 1])) diff --git a/tox.ini b/tox.ini index 8b95a6f..8eb7e87 100644 --- a/tox.ini +++ b/tox.ini @@ -18,69 +18,39 @@ extras = test [testenv:linters] basepython = python3 skip_install = true +# Remove this to check what versions are installed for the env. This stops running pip freeze. +list_dependencies_command = echo deps = - {[testenv:isort]deps} - {[testenv:black]deps} - {[testenv:flake8]deps} + {[testenv:ruff-format]deps} + {[testenv:ruff-check]deps} commands = - # isort MUST come before black as it will revert any changes made by black - {[testenv:isort]commands} - {[testenv:black]commands} - {[testenv:flake8]commands} + {[testenv:ruff-format]commands} + {[testenv:ruff-check]commands} # Read only linter env [testenv:linters_check] basepython = python3 skip_install = true deps = - {[testenv:isort_check]deps} - {[testenv:black_check]deps} - {[testenv:flake8]deps} + {[testenv:ruff-check]deps} commands = - {[testenv:isort_check]commands} - {[testenv:black_check]commands} - {[testenv:flake8]commands} + {[testenv:ruff-check]commands} -[testenv:flake8] +[testenv:ruff-check] basepython = python3 skip_install = true deps = - flake8 - flake8-rst-docstrings + ruff commands = - flake8 {posargs} + ruff check src {posargs} -[testenv:isort] +[testenv:ruff-format] basepython = python3 skip_install = true deps = - isort + ruff commands = - isort . {posargs} - -[testenv:isort_check] -basepython = python3 -skip_install = true -deps = - isort -commands = - isort . -rc {posargs} - -[testenv:black] -basepython = python3 -skip_install = true -deps = - black -commands = - black ./ {posargs} - -[testenv:black_check] -basepython = python3 -skip_install = true -deps = - black -commands = - black --check ./ {posargs} + ruff format . {posargs} #[testenv:docs] #basepython = python3