Skip to content

Commit

Permalink
next batch of fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Abe Coull committed Nov 2, 2023
1 parent d104691 commit 4b3d6a8
Show file tree
Hide file tree
Showing 21 changed files with 70 additions and 66 deletions.
6 changes: 5 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,13 @@ ignore = [
# Ignore complexity
"PLR0911", "PLR0912", "PLR0913",
# Uppercase function names are fine in some cases
"N802", "N803", "N806",
"N801", "N802", "N803", "N806", "N815",
# Allow Optional return types
"RUF013",
# Use of pickle is known
"S301",
# Could cause formatting issues
"ISC001",
]

[tool.ruff.pydocstyle]
Expand Down
6 changes: 3 additions & 3 deletions src/braket/circuits/gates.py
Original file line number Diff line number Diff line change
Expand Up @@ -1560,7 +1560,7 @@ def cphaseshift(


class CPhaseShift00(AngledGate):
"""Controlled phase shift gate for phasing the \\|00> state.
r"""Controlled phase shift gate for phasing the \\|00> state.
Args:
angle (Union[FreeParameterExpression, float]): angle in radians.
Expand Down Expand Up @@ -2764,7 +2764,7 @@ def adjoint(self) -> list[Gate]:

def _to_jaqcd(self, target: QubitSet) -> Any:
return ir.Unitary.construct(
targets=[qubit for qubit in target],
targets=list(target),
matrix=Unitary._transform_matrix_to_ir(self._matrix),
)

Expand All @@ -2781,7 +2781,7 @@ def _to_openqasm(

return f"#pragma braket unitary({formatted_matrix}) {', '.join(qubits)}"

def __eq__(self, other):
def __eq__(self, other: Unitary):
if isinstance(other, Unitary):
return self.matrix_equivalence(other)
return False
Expand Down
21 changes: 10 additions & 11 deletions src/braket/circuits/noise_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,17 +218,16 @@ def _apply_noise_to_gates_helper(
noise_index += 1
new_noise_instruction.append((Instruction(noise_channel, qubit), noise_index))
noise_applied = True
else:
# only apply noise to the gates that have the same qubit_count as the noise.
if (
instruction.operator.qubit_count == noise_channel.qubit_count
and instruction.target.issubset(target_qubits)
):
noise_index += 1
new_noise_instruction.append(
(Instruction(noise_channel, instruction.target), noise_index)
)
noise_applied = True
# only apply noise to the gates that have the same qubit_count as the noise.
elif (
instruction.operator.qubit_count == noise_channel.qubit_count
and instruction.target.issubset(target_qubits)
):
noise_index += 1
new_noise_instruction.append(
(Instruction(noise_channel, instruction.target), noise_index)
)
noise_applied = True

return new_noise_instruction, noise_index, noise_applied

Expand Down
24 changes: 12 additions & 12 deletions src/braket/circuits/noises.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@


class BitFlip(SingleProbabilisticNoise):
"""Bit flip noise channel which transforms a density matrix :math:`\\rho` according to:
r"""Bit flip noise channel which transforms a density matrix :math:`\\rho` according to:
.. math:: \\rho \\Rightarrow (1-p) \\rho + p X \\rho X^{\\dagger}
Expand Down Expand Up @@ -156,7 +156,7 @@ def from_dict(cls, noise: dict) -> Noise:


class PhaseFlip(SingleProbabilisticNoise):
"""Phase flip noise channel which transforms a density matrix :math:`\\rho` according to:
r"""Phase flip noise channel which transforms a density matrix :math:`\\rho` according to:
.. math:: \\rho \\Rightarrow (1-p) \\rho + p X \\rho X^{\\dagger}
Expand Down Expand Up @@ -261,7 +261,7 @@ def from_dict(cls, noise: dict) -> Noise:


class PauliChannel(PauliNoise):
"""Pauli noise channel which transforms a density matrix :math:`\\rho` according to:
r"""Pauli noise channel which transforms a density matrix :math:`\\rho` according to:
.. math::
\\rho \\Rightarrow (1-probX-probY-probZ) \\rho
Expand Down Expand Up @@ -414,7 +414,7 @@ def from_dict(cls, noise: dict) -> Noise:


class Depolarizing(SingleProbabilisticNoise_34):
"""Depolarizing noise channel which transforms a density matrix :math:`\\rho` according to:
r"""Depolarizing noise channel which transforms a density matrix :math:`\\rho` according to:
.. math::
\\rho \\Rightarrow (1-p) \\rho
Expand Down Expand Up @@ -536,7 +536,7 @@ def from_dict(cls, noise: dict) -> Noise:


class TwoQubitDepolarizing(SingleProbabilisticNoise_1516):
"""Two-Qubit Depolarizing noise channel which transforms a
r"""Two-Qubit Depolarizing noise channel which transforms a
density matrix :math:`\\rho` according to:
.. math::
Expand Down Expand Up @@ -679,7 +679,7 @@ def from_dict(cls, noise: dict) -> Noise:


class TwoQubitDephasing(SingleProbabilisticNoise_34):
"""Two-Qubit Dephasing noise channel which transforms a
r"""Two-Qubit Dephasing noise channel which transforms a
density matrix :math:`\\rho` according to:
.. math::
Expand Down Expand Up @@ -797,7 +797,7 @@ def from_dict(cls, noise: dict) -> Noise:


class TwoQubitPauliChannel(MultiQubitPauliNoise):
"""Two-Qubit Pauli noise channel which transforms a
r"""Two-Qubit Pauli noise channel which transforms a
density matrix :math:`\\rho` according to:
.. math::
Expand Down Expand Up @@ -952,7 +952,7 @@ def from_dict(cls, noise: dict) -> Noise:
Returns:
Noise: A Noise object that represents the passed in dictionary.
"""
probabilities = dict()
probabilities = {}
for pauli_string, prob in noise["probabilities"].items():
probabilities[pauli_string] = _parameter_from_dict(prob)
return TwoQubitPauliChannel(probabilities=probabilities)
Expand All @@ -962,7 +962,7 @@ def from_dict(cls, noise: dict) -> Noise:


class AmplitudeDamping(DampingNoise):
"""AmplitudeDamping noise channel which transforms a density matrix :math:`\\rho` according to:
r"""AmplitudeDamping noise channel which transforms a density matrix :math:`\\rho` according to:
.. math:: \\rho \\Rightarrow E_0 \\rho E_0^{\\dagger} + E_1 \\rho E_1^{\\dagger}
Expand Down Expand Up @@ -1062,7 +1062,7 @@ def from_dict(cls, noise: dict) -> Noise:


class GeneralizedAmplitudeDamping(GeneralizedAmplitudeDampingNoise):
"""Generalized AmplitudeDamping noise channel which transforms a
r"""Generalized AmplitudeDamping noise channel which transforms a
density matrix :math:`\\rho` according to:
.. math:: \\rho \\Rightarrow E_0 \\rho E_0^{\\dagger} + E_1 \\rho E_1^{\\dagger}
Expand Down Expand Up @@ -1203,7 +1203,7 @@ def from_dict(cls, noise: dict) -> Noise:


class PhaseDamping(DampingNoise):
"""Phase damping noise channel which transforms a density matrix :math:`\\rho` according to:
r"""Phase damping noise channel which transforms a density matrix :math:`\\rho` according to:
.. math:: \\rho \\Rightarrow E_0 \\rho E_0^{\\dagger} + E_1 \\rho E_1^{\\dagger}
Expand Down Expand Up @@ -1350,7 +1350,7 @@ def to_matrix(self) -> Iterable[np.ndarray]:

def _to_jaqcd(self, target: QubitSet) -> Any:
return ir.Kraus.construct(
targets=[qubit for qubit in target],
targets=list(target),
matrices=Kraus._transform_matrix_to_ir(self._matrices),
)

Expand Down
12 changes: 6 additions & 6 deletions src/braket/circuits/observable.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,30 +150,30 @@ def register_observable(cls, observable: Observable) -> None:
"""
setattr(cls, observable.__name__, observable)

def __matmul__(self, other) -> Observable.TensorProduct:
def __matmul__(self, other: Observable) -> Observable.TensorProduct:
if isinstance(other, Observable):
return Observable.TensorProduct([self, other])

raise ValueError("Can only perform tensor products between observables.")

def __mul__(self, other) -> Observable:
def __mul__(self, other: Observable) -> Observable:
"""Scalar multiplication"""
if isinstance(other, numbers.Number):
observable_copy = deepcopy(self)
observable_copy._coef *= other
return observable_copy
raise TypeError("Observable coefficients must be numbers.")

def __rmul__(self, other) -> Observable:
def __rmul__(self, other: Observable) -> Observable:
return self * other

def __add__(self, other):
def __add__(self, other: Observable):
if not isinstance(other, Observable):
raise ValueError("Can only perform addition between observables.")

return Observable.Sum([self, other])

def __sub__(self, other):
def __sub__(self, other: Observable):
if not isinstance(other, Observable):
raise ValueError("Can only perform subtraction between observables.")

Expand All @@ -182,7 +182,7 @@ def __sub__(self, other):
def __repr__(self) -> str:
return f"{self.name}('qubit_count': {self.qubit_count})"

def __eq__(self, other) -> bool:
def __eq__(self, other: Observable) -> bool:
if isinstance(other, Observable):
return self.name == other.name
return NotImplemented
Expand Down
1 change: 0 additions & 1 deletion src/braket/jobs/image_uris.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import os
from enum import Enum
from functools import cache
from typing import Dict, Set


class Framework(str, Enum):
Expand Down
1 change: 0 additions & 1 deletion src/braket/jobs/local/local_job_container.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import subprocess
from logging import Logger, getLogger
from pathlib import PurePosixPath
from typing import Dict, List

from braket.aws.aws_session import AwsSession

Expand Down
2 changes: 1 addition & 1 deletion src/braket/jobs/local/local_job_container_setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from collections.abc import Iterable
from logging import Logger, getLogger
from pathlib import Path
from typing import Any, Dict
from typing import Any

from braket.aws.aws_session import AwsSession
from braket.jobs.local.local_job_container import _LocalJobContainer
Expand Down
7 changes: 3 additions & 4 deletions src/braket/jobs/logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
# Support for reading logs
#
##############################################################################
from typing import Dict, List, Tuple
from typing import ClassVar

from botocore.exceptions import ClientError
from braket.aws.aws_session import AwsSession
Expand All @@ -33,7 +33,7 @@ class ColorWrap:

# For what color each number represents, see
# https://misc.flogisoft.com/bash/tip_colors_and_formatting#colors
_stream_colors = [34, 35, 32, 36, 33]
_stream_colors: ClassVar = [34, 35, 32, 36, 33]

def __init__(self, force: bool = False):
"""Initialize a `ColorWrap`.
Expand Down Expand Up @@ -149,8 +149,7 @@ def log_stream(
else:
skip = skip - event_count
events = []
for ev in events:
yield ev
yield from events


def flush_log_streams(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

import time
from logging import Logger, getLogger
from typing import Any, Dict, List, Optional, Union
from typing import Any, Optional, Union

from braket.aws.aws_session import AwsSession
from braket.jobs.metrics_data.definitions import MetricStatistic, MetricType
Expand Down
2 changes: 1 addition & 1 deletion src/braket/jobs/metrics_data/cwl_metrics_fetcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

import time
from logging import Logger, getLogger
from typing import Dict, List, Union
from typing import Union

from braket.aws.aws_session import AwsSession
from braket.jobs.metrics_data.definitions import MetricStatistic, MetricType
Expand Down
2 changes: 1 addition & 1 deletion src/braket/jobs/metrics_data/log_metrics_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import re
from collections.abc import Iterator
from logging import Logger, getLogger
from typing import Dict, List, Optional, Tuple, Union
from typing import Optional, Union

from braket.jobs.metrics_data.definitions import MetricStatistic, MetricType

Expand Down
2 changes: 1 addition & 1 deletion src/braket/jobs/quantum_job.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
from abc import ABC, abstractmethod
from typing import Any, Dict, List
from typing import Any

from braket.jobs.metrics_data.definitions import MetricStatistic, MetricType

Expand Down
15 changes: 7 additions & 8 deletions src/braket/jobs/quantum_job_creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,15 +249,14 @@ def _generate_default_job_name(image_uri: str = None, func: Callable = None) ->
warnings.warn(
f"Job name exceeded {max_length} characters. Truncating name to {name}-{timestamp}."
)
elif not image_uri:
name = "braket-job-default"
else:
if not image_uri:
name = "braket-job-default"
else:
job_type_match = re.search("/amazon-braket-(.*)-jobs:", image_uri) or re.search(
"/amazon-braket-([^:/]*)", image_uri
)
container = f"-{job_type_match.groups()[0]}" if job_type_match else ""
name = f"braket-job{container}"
job_type_match = re.search("/amazon-braket-(.*)-jobs:", image_uri) or re.search(
"/amazon-braket-([^:/]*)", image_uri
)
container = f"-{job_type_match.groups()[0]}" if job_type_match else ""
name = f"braket-job{container}"
return f"{name}-{timestamp}"


Expand Down
2 changes: 1 addition & 1 deletion src/braket/jobs/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

import codecs
import pickle
from typing import Any, Dict
from typing import Any

from braket.jobs_data import PersistedJobDataFormat

Expand Down
2 changes: 1 addition & 1 deletion src/braket/parametric/free_parameter.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def __str__(self):
def __hash__(self) -> int:
return hash(tuple(self.name))

def __eq__(self, other):
def __eq__(self, other: FreeParameter):
if isinstance(other, FreeParameter):
return self._name == other._name
return super().__eq__(other)
Expand Down
4 changes: 2 additions & 2 deletions src/braket/parametric/free_parameter_expression.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def subs(
Union[FreeParameterExpression, Number, Expr]: A numerical value if there are no
symbols left in the expression otherwise returns a new FreeParameterExpression.
"""
new_parameter_values = dict()
new_parameter_values = {}
for key, val in parameter_values.items():
if issubclass(type(key), FreeParameterExpression):
new_parameter_values[key.expression] = val
Expand Down Expand Up @@ -146,7 +146,7 @@ def __mul__(self, other: FreeParameterExpression):
def __rmul__(self, other: FreeParameterExpression):
return FreeParameterExpression(other * self.expression)

def __pow__(self, other: FreeParameterExpression, modulo=None):
def __pow__(self, other: FreeParameterExpression, modulo: float = None):
if issubclass(type(other), FreeParameterExpression):
return FreeParameterExpression(self.expression**other.expression)
else:
Expand Down
Loading

0 comments on commit 4b3d6a8

Please sign in to comment.