Skip to content

Commit

Permalink
fix: onboard onto ruff (#277)
Browse files Browse the repository at this point in the history
Co-authored-by: Coull <[email protected]>
  • Loading branch information
AbeCoull and Coull authored Sep 18, 2024
1 parent 8ff880b commit 3f88ff3
Show file tree
Hide file tree
Showing 21 changed files with 448 additions and 195 deletions.
6 changes: 5 additions & 1 deletion example.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,11 @@
shots=0,
)
dev_qpu = qml.device(
"braket.rigetti", s3_destination_folder=s3, poll_timeout_seconds=1800, shots=10000, wires=2
"braket.rigetti",
s3_destination_folder=s3,
poll_timeout_seconds=1800,
shots=10000,
wires=2,
)


Expand Down
9 changes: 8 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,9 @@
[tool.black]
[tool.ruff]
target-version = "py39"
line-length = 100
lint.isort = { known-first-party = [
"braket",
] }
lint.extend-select = ["I"]
lint.preview = true

33 changes: 0 additions & 33 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -8,36 +8,3 @@ addopts =
--verbose -n auto --durations=0 --durations-min=1
testpaths = test/unit_tests

[isort]
line_length = 100
multi_line_output = 3
include_trailing_comma = true
profile = black

[flake8]
ignore =
# not pep8, black adds whitespace before ':'
E203,
# not pep8, https://www.python.org/dev/peps/pep-0008/#pet-peeves
E231,
# 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
build
venv

rst-roles =
# Python programming language:
py:func,py:mod,mod,class,attr

rst-directives =
autosummary,currentmodule
5 changes: 1 addition & 4 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,8 @@
},
extras_require={
"test": [
"black",
"docutils>=0.19",
"flake8",
"flake8-rst-docstrings",
"flaky",
"isort",
"pre-commit",
"pylint>=3.1.0",
"pytest",
Expand All @@ -67,6 +63,7 @@
"pytest-mock",
"pytest-rerunfailures",
"pytest-xdist",
"ruff",
"sphinx",
"sphinx-automodapi",
"sphinx-rtd-theme",
Expand Down
2 changes: 1 addition & 1 deletion src/braket/pennylane_plugin/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
# language governing permissions and limitations under the License.

"""Version information.
Version number (major.minor.patch[-label])
Version number (major.minor.patch[-label])
"""

__version__ = "1.30.1.dev0"
10 changes: 6 additions & 4 deletions src/braket/pennylane_plugin/ahs_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,23 +32,25 @@
Code details
~~~~~~~~~~~~
"""

from collections.abc import Iterable
from enum import Enum, auto
from typing import Optional, Union

import numpy as np
import pennylane as qml
from braket.ahs.analog_hamiltonian_simulation import AnalogHamiltonianSimulation
from braket.aws import AwsDevice, AwsQuantumTask, AwsSession
from braket.devices import Device, LocalSimulator
from braket.tasks.local_quantum_task import LocalQuantumTask
from pennylane import QubitDevice
from pennylane._version import __version__
from pennylane.measurements import MeasurementProcess, SampleMeasurement
from pennylane.ops import CompositeOp, Hamiltonian
from pennylane.pulse import ParametrizedEvolution
from pennylane.pulse.hardware_hamiltonian import HardwareHamiltonian, HardwarePulse

from braket.ahs.analog_hamiltonian_simulation import AnalogHamiltonianSimulation
from braket.aws import AwsDevice, AwsQuantumTask, AwsSession
from braket.devices import Device, LocalSimulator
from braket.tasks.local_quantum_task import LocalQuantumTask

from .ahs_translation import (
_create_register,
_create_valid_local_detunings,
Expand Down
7 changes: 4 additions & 3 deletions src/braket/pennylane_plugin/ahs_translation.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,17 @@
from typing import Union

import numpy as np
from numpy.typing import ArrayLike
from pennylane.pulse import ParametrizedEvolution
from pennylane.pulse.hardware_hamiltonian import HardwarePulse

from braket.ahs.atom_arrangement import AtomArrangement
from braket.ahs.driving_field import DrivingField
from braket.ahs.field import Field
from braket.ahs.pattern import Pattern
from braket.ahs.shifting_field import ShiftingField
from braket.tasks.analog_hamiltonian_simulation_quantum_task_result import ShotResult
from braket.timings.time_series import TimeSeries
from numpy.typing import ArrayLike
from pennylane.pulse import ParametrizedEvolution
from pennylane.pulse.hardware_hamiltonian import HardwarePulse

ANGULAR_AND_M_SCALING_FACTOR = 2 * np.pi * 1e6

Expand Down
34 changes: 23 additions & 11 deletions src/braket/pennylane_plugin/braket_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,6 @@

import numpy as onp
import pennylane as qml
from braket.aws import AwsDevice, AwsDeviceType, AwsQuantumTask, AwsQuantumTaskBatch, AwsSession
from braket.circuits import Circuit, Instruction
from braket.circuits.noise_model import NoiseModel
from braket.device_schema import DeviceActionType
from braket.devices import Device, LocalSimulator
from braket.simulator import BraketSimulator
from braket.tasks import GateModelQuantumTaskResult, QuantumTask
from braket.tasks.local_quantum_task_batch import LocalQuantumTaskBatch
from pennylane import QuantumFunctionError, QubitDevice
from pennylane import numpy as np
from pennylane.gradients import param_shift
Expand All @@ -70,6 +62,17 @@
from pennylane.ops import Hamiltonian, Sum
from pennylane.tape import QuantumTape

from braket.aws import (
AwsDevice,
AwsDeviceType,
AwsQuantumTask,
AwsQuantumTaskBatch,
AwsSession,
)
from braket.circuits import Circuit, Instruction
from braket.circuits.noise_model import NoiseModel
from braket.device_schema import DeviceActionType
from braket.devices import Device, LocalSimulator
from braket.pennylane_plugin.translation import (
get_adjoint_gradient_result_type,
supported_observables,
Expand All @@ -78,6 +81,9 @@
translate_result,
translate_result_type,
)
from braket.simulator import BraketSimulator
from braket.tasks import GateModelQuantumTaskResult, QuantumTask
from braket.tasks.local_quantum_task_batch import LocalQuantumTaskBatch

from ._version import __version__

Expand Down Expand Up @@ -253,7 +259,9 @@ def _pl_to_braket_circuit(
elif not isinstance(circuit.measurements[0], MeasurementTransform):
for measurement in circuit.measurements:
translated = translate_result_type(
measurement.map_wires(self.wire_map), None, self._braket_result_types
measurement.map_wires(self.wire_map),
None,
self._braket_result_types,
)
if isinstance(translated, tuple):
for result_type in translated:
Expand Down Expand Up @@ -294,7 +302,9 @@ def _apply_gradient_result_type(self, circuit, braket_circuit):
return braket_circuit

def _update_tracker_for_batch(
self, task_batch: Union[AwsQuantumTaskBatch, LocalQuantumTaskBatch], batch_shots: int
self,
task_batch: Union[AwsQuantumTaskBatch, LocalQuantumTaskBatch],
batch_shots: int,
):
for task in task_batch.tasks:
tracking_data = self._tracking_data(task)
Expand All @@ -305,7 +315,9 @@ def _update_tracker_for_batch(
self.tracker.record()

def statistics(
self, braket_result: GateModelQuantumTaskResult, measurements: Sequence[MeasurementProcess]
self,
braket_result: GateModelQuantumTaskResult,
measurements: Sequence[MeasurementProcess],
) -> list[float]:
"""Processes measurement results from a Braket task result and returns statistics.
Expand Down
28 changes: 24 additions & 4 deletions src/braket/pennylane_plugin/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -533,10 +533,30 @@ def compute_matrix(phi_0, phi_1, theta):

return np.array(
[
[np.cos(theta / 2), 0, 0, -1j * np.exp(-1j * (phi_0 + phi_1)) * np.sin(theta / 2)],
[0, np.cos(theta / 2), -1j * np.exp(-1j * (phi_0 - phi_1)) * np.sin(theta / 2), 0],
[0, -1j * np.exp(1j * (phi_0 - phi_1)) * np.sin(theta / 2), np.cos(theta / 2), 0],
[-1j * np.exp(1j * (phi_0 + phi_1)) * np.sin(theta / 2), 0, 0, np.cos(theta / 2)],
[
np.cos(theta / 2),
0,
0,
-1j * np.exp(-1j * (phi_0 + phi_1)) * np.sin(theta / 2),
],
[
0,
np.cos(theta / 2),
-1j * np.exp(-1j * (phi_0 - phi_1)) * np.sin(theta / 2),
0,
],
[
0,
-1j * np.exp(1j * (phi_0 - phi_1)) * np.sin(theta / 2),
np.cos(theta / 2),
0,
],
[
-1j * np.exp(1j * (phi_0 + phi_1)) * np.sin(theta / 2),
0,
0,
np.cos(theta / 2),
],
]
)

Expand Down
14 changes: 7 additions & 7 deletions src/braket/pennylane_plugin/translation.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@

import numpy as onp
import pennylane as qml
from pennylane import numpy as np
from pennylane.measurements import MeasurementProcess, ObservableReturnTypes
from pennylane.operation import Observable, Operation
from pennylane.pulse import ParametrizedEvolution

from braket.aws import AwsDevice
from braket.circuits import FreeParameter, Gate, ResultType, gates, noises, observables
from braket.circuits.result_types import (
Expand All @@ -30,13 +35,6 @@
)
from braket.device_schema import DeviceActionType
from braket.devices import Device
from braket.pulse import ArbitraryWaveform, ConstantWaveform, PulseSequence
from braket.tasks import GateModelQuantumTaskResult
from pennylane import numpy as np
from pennylane.measurements import MeasurementProcess, ObservableReturnTypes
from pennylane.operation import Observable, Operation
from pennylane.pulse import ParametrizedEvolution

from braket.pennylane_plugin.ops import (
AAMS,
MS,
Expand All @@ -48,6 +46,8 @@
GPi2,
PRx,
)
from braket.pulse import ArbitraryWaveform, ConstantWaveform, PulseSequence
from braket.tasks import GateModelQuantumTaskResult

_BRAKET_TO_PENNYLANE_OPERATIONS = {
"i": "Identity",
Expand Down
8 changes: 6 additions & 2 deletions test/integ_tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,10 @@
shortname_and_backends = [(d.short_name, backend) for (d, backend) in devices]

# List of local devices
local_devices = [(BraketLocalQubitDevice, "braket_sv"), (BraketLocalQubitDevice, "braket_dm")]
local_devices = [
(BraketLocalQubitDevice, "braket_sv"),
(BraketLocalQubitDevice, "braket_dm"),
]

# ==========================================================
# AWS resources
Expand All @@ -78,7 +81,8 @@
error_code = e.response["Error"]["Code"]
if error_code == "404":
s3_bucket.create(
ACL="private", CreateBucketConfiguration={"LocationConstraint": session.region_name}
ACL="private",
CreateBucketConfiguration={"LocationConstraint": session.region_name},
)


Expand Down
7 changes: 6 additions & 1 deletion test/integ_tests/test_adjoint_gradient.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,12 @@ def circuit(x):
qml.RZ(rand_param, wires=i)
if random.randint(0, 3) == 0:
# cnot i with some random other qubit
qml.CNOT(wires=[i, random.choice([j for j in range(num_qubits) if i != j])])
qml.CNOT(
wires=[
i,
random.choice([j for j in range(num_qubits) if i != j]),
]
)

# use every parameter at least once
for i in range(num_params):
Expand Down
3 changes: 2 additions & 1 deletion test/integ_tests/test_batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@ def func(weights):
@pytest.mark.parametrize("shots", [None])
def test_batch_execution_of_gradient_torch(device, shots, mocker):
"""Test that the output of a parallelized execution of batch circuits to evaluate the
gradient is correct in comparison to default.qubit when using the torch interface."""
gradient is correct in comparison to default.qubit when using the torch interface.
"""
try:
import torch
except ImportError:
Expand Down
5 changes: 4 additions & 1 deletion test/integ_tests/test_expval.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,10 @@ def circuit():
return [qml.expval(qml.Hadamard(i)) for i in range(2)]

expected = np.array(
[np.sin(theta) * np.sin(phi) + np.cos(theta), np.cos(theta) * np.cos(phi) + np.sin(phi)]
[
np.sin(theta) * np.sin(phi) + np.cos(theta),
np.cos(theta) * np.cos(phi) + np.sin(phi),
]
) / np.sqrt(2)
assert np.allclose(circuit(), expected, **tol)

Expand Down
5 changes: 4 additions & 1 deletion test/integ_tests/test_tracking.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@
import pytest
from pennylane import numpy as np

from braket.pennylane_plugin.braket_device import MIN_SIMULATOR_BILLED_MS, BraketAwsQubitDevice
from braket.pennylane_plugin.braket_device import (
MIN_SIMULATOR_BILLED_MS,
BraketAwsQubitDevice,
)


@pytest.mark.parametrize("shots", [100])
Expand Down
Loading

0 comments on commit 3f88ff3

Please sign in to comment.