Skip to content

Commit

Permalink
Replace pycodestyle with Ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
Eric-Arellano committed Oct 23, 2024
1 parent 5175a7c commit f1be40e
Show file tree
Hide file tree
Showing 20 changed files with 58 additions and 97 deletions.
6 changes: 3 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,9 @@ style = [
]
lint = [
"qiskit-addon-cutting[style]",
"pydocstyle==6.3.0",
"mypy==1.11.2",
"reno>=3.4.0",
"pylint==3.3.1",
# pydocstyle prefers to parse our pyproject.toml, hence the following line
"toml",
]
docs = [
"Sphinx>=3.0.0",
Expand Down Expand Up @@ -112,6 +109,9 @@ ignore = [
"E402", # module level import not at top of file
]

[tool.ruff.lint.pydocstyle]
convention = "google"

[tool.pylint.main]
py-version = "3.8"
disable = "all"
Expand Down
3 changes: 1 addition & 2 deletions qiskit_addon_cutting/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

"""
Circuit Cutting (:mod:`qiskit_addon_cutting`).
"""Circuit Cutting (:mod:`qiskit_addon_cutting`).
.. currentmodule:: qiskit_addon_cutting
Expand Down
3 changes: 1 addition & 2 deletions qiskit_addon_cutting/cut_finding/cutting_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,7 @@ def next_state_primitive(
def get_cost_params(
gate_spec: GateSpec,
) -> tuple[float | None, int, float | None]:
"""
Get the cost parameters for gate cuts.
"""Get the cost parameters for gate cuts.
This method returns a tuple of the form:
(<gamma_lower_bound>, <num_bell_pairs>, <gamma_upper_bound>)
Expand Down
21 changes: 8 additions & 13 deletions qiskit_addon_cutting/cut_finding/lo_cuts_optimizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,21 +90,16 @@ def optimize(
"""Optimize the cutting of a circuit by calling :meth:`CutOptimization.optimization_pass`.
Args:
``circuit_interface``: defines the circuit to be
cut. This object is then updated with the optimized cuts that
were identified.
``optimization_settings``: defines the settings
to be used for the optimization.
``device_constraints``: the capabilties of
the target quantum hardware.
circuit_interface: defines the circuit to be cut. This object is then updated
with the optimized cuts that were identified.
optimization_settings: defines the settings to be used for the optimization.
device_constraints: the capabilties of the target quantum hardware.
Returns:
The lowest-cost instance of :class:`DisjointSubcircuitsState`
identified in the search, or None if no solution could be found.
In case of the former, the circuit_interface object is also
updated as a side effect to incorporate the cuts found.
The lowest-cost instance of :class:`DisjointSubcircuitsState`
identified in the search, or None if no solution could be found.
In case of the former, the circuit_interface object is also
updated as a side effect to incorporate the cuts found.
"""
if circuit_interface is not None:
self.circuit_interface = circuit_interface
Expand Down
12 changes: 4 additions & 8 deletions qiskit_addon_cutting/cutting_decomposition.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,7 @@ class PartitionedCuttingProblem(NamedTuple):
def partition_circuit_qubits(
circuit: QuantumCircuit, partition_labels: Sequence[Hashable], inplace: bool = False
) -> QuantumCircuit:
r"""
Replace all nonlocal gates belonging to more than one partition with instances of :class:`.TwoQubitQPDGate`.
r"""Replace all nonlocal gates belonging to more than one partition with instances of :class:`.TwoQubitQPDGate`.
:class:`.TwoQubitQPDGate`\ s belonging to a single partition will not be affected.
Expand Down Expand Up @@ -104,8 +103,7 @@ def partition_circuit_qubits(
def cut_gates(
circuit: QuantumCircuit, gate_ids: Sequence[int], inplace: bool = False
) -> tuple[QuantumCircuit, list[QPDBasis]]:
r"""
Transform specified gates into :class:`.TwoQubitQPDGate`\ s.
r"""Transform specified gates into :class:`.TwoQubitQPDGate`\ s.
Args:
circuit: The circuit containing gates to be decomposed
Expand Down Expand Up @@ -143,8 +141,7 @@ def partition_problem(
partition_labels: Sequence[Hashable] | None = None,
observables: PauliList | None = None,
) -> PartitionedCuttingProblem:
r"""
Separate an input circuit and observable(s).
r"""Separate an input circuit and observable(s).
If ``partition_labels`` is provided, then qubits with matching partition
labels will be grouped together, and non-local gates spanning more than one
Expand Down Expand Up @@ -240,8 +237,7 @@ def partition_problem(
def decompose_observables(
observables: PauliList, partition_labels: Sequence[Hashable]
) -> dict[Hashable, PauliList]:
"""
Decompose a list of observables with respect to some qubit partition labels.
"""Decompose a list of observables with respect to some qubit partition labels.
Args:
observables: A list of observables to decompose
Expand Down
4 changes: 2 additions & 2 deletions qiskit_addon_cutting/cutting_experiments.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,7 @@ def generate_cutting_experiments(
list[QuantumCircuit] | dict[Hashable, list[QuantumCircuit]],
list[tuple[float, WeightType]],
]:
r"""
Generate cutting subexperiments and their associated coefficients.
r"""Generate cutting subexperiments and their associated coefficients.
If the input, ``circuits``, is a :class:`QuantumCircuit` instance, the
output subexperiments will be contained within a 1D array, and ``observables`` is
Expand All @@ -64,6 +63,7 @@ def generate_cutting_experiments(
num_samples: The number of samples to draw from the quasi-probability distribution. If set
to infinity, the weights will be generated rigorously rather than by sampling from
the distribution.
Returns:
A tuple containing the cutting experiments and their associated coefficients.
If the input circuits is a :class:`QuantumCircuit` instance, the output subexperiments
Expand Down
9 changes: 3 additions & 6 deletions qiskit_addon_cutting/cutting_reconstruction.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,7 @@ def reconstruct_expectation_values(
coefficients: Sequence[tuple[float, WeightType]],
observables: PauliList | dict[Hashable, PauliList],
) -> list[float]:
r"""
Reconstruct an expectation value from the results of the sub-experiments.
r"""Reconstruct an expectation value from the results of the sub-experiments.
Args:
results: The results from running the cutting subexperiments. If the cut circuit
Expand Down Expand Up @@ -174,8 +173,7 @@ def reconstruct_expectation_values(
def _process_outcome(
cog: CommutingObservableGroup, outcome: int | str, /
) -> np.typing.NDArray[np.float64]:
"""
Process a single outcome of a QPD experiment with observables.
"""Process a single outcome of a QPD experiment with observables.
Args:
cog: The observable set being measured by the current experiment
Expand All @@ -198,8 +196,7 @@ def _process_outcome(
def _process_outcome_v2(
cog: CommutingObservableGroup, obs_outcomes: int, qpd_outcomes: int, /
) -> np.typing.NDArray[np.float64]:
"""
Process a single outcome of a QPD experiment with observables.
"""Process a single outcome of a QPD experiment with observables.
Args:
cog: The observable set being measured by the current experiment
Expand Down
7 changes: 3 additions & 4 deletions qiskit_addon_cutting/qpd/decompose.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ def decompose_qpd_instructions(
*,
inplace: bool = False,
) -> QuantumCircuit:
r"""
Replace all QPD instructions in the circuit with local Qiskit operations and measurements.
r"""Replace all QPD instructions in the circuit with local Qiskit operations and measurements.
Args:
circuit: The circuit containing QPD instructions
Expand All @@ -43,6 +42,7 @@ def decompose_qpd_instructions(
map_ids: Indices to a specific linear mapping to be applied to the decompositions
in the circuit. If no map IDs are provided, the circuit will be decomposed randomly
according to the decompositions' joint probability distribution.
inplace: TODO
Returns:
Circuit which has had all its :class:`BaseQPDGate` instances decomposed into local operations.
Expand Down Expand Up @@ -127,8 +127,7 @@ def _validate_qpd_instructions(
def _decompose_qpd_measurements(
circuit: QuantumCircuit, inplace: bool = True
) -> QuantumCircuit:
"""
Create mid-circuit measurements.
"""Create mid-circuit measurements.
Convert all QPDMeasure instances to Measure instructions. Add any newly created
classical bits to a new "qpd_measurements" register.
Expand Down
12 changes: 4 additions & 8 deletions qiskit_addon_cutting/qpd/decompositions.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,7 @@ def g(f):


def qpdbasis_from_instruction(gate: Instruction, /) -> QPDBasis:
"""
Generate a :class:`.QPDBasis` object, given a supported operation.
"""Generate a :class:`.QPDBasis` object, given a supported operation.
All two-qubit gates which implement the :meth:`~qiskit.circuit.Gate.to_matrix` method are
supported. This should include the vast majority of gates with no unbound
Expand Down Expand Up @@ -127,8 +126,7 @@ def qpdbasis_from_instruction(gate: Instruction, /) -> QPDBasis:


def _explicitly_supported_instructions() -> set[str]:
"""
Return a set of instruction names with explicit support for automatic decomposition.
"""Return a set of instruction names with explicit support for automatic decomposition.
These instructions are *explicitly* supported by :func:`qpdbasis_from_instruction`.
Other instructions may be supported too, via a KAK decomposition.
Expand All @@ -140,8 +138,7 @@ def _explicitly_supported_instructions() -> set[str]:


def _copy_unique_sublists(lsts: tuple[list, ...], /) -> tuple[list, ...]:
"""
Copy each list in a sequence of lists while preserving uniqueness.
"""Copy each list in a sequence of lists while preserving uniqueness.
This is useful to ensure that the two sets of ``maps`` in a
:class:`QPDBasis` will be independent of each other. This enables one to
Expand All @@ -158,8 +155,7 @@ def _copy_unique_sublists(lsts: tuple[list, ...], /) -> tuple[list, ...]:
def _u_from_thetavec(
theta: np.typing.NDArray[np.float64] | Sequence[float], /
) -> np.typing.NDArray[np.complex128]:
r"""
Exponentiate the non-local portion of a KAK decomposition.
r"""Exponentiate the non-local portion of a KAK decomposition.
This implements Eq. (6) of https://arxiv.org/abs/2006.11174v2:
Expand Down
24 changes: 10 additions & 14 deletions qiskit_addon_cutting/qpd/instructions/qpd_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@ def __init__(
basis_id: int | None = None,
label: str | None = None,
):
"""
Initialize the instruction, and assign member variables.
"""Initialize the instruction, and assign member variables.
Args:
name: Name of the QPD gate.
Expand All @@ -51,8 +50,7 @@ def __init__(

@property
def basis(self) -> QPDBasis:
"""
Quasiprobability decomposition basis.
"""Quasiprobability decomposition basis.
Returns:
The basis to which the gate should be decomposed
Expand All @@ -64,8 +62,7 @@ def _set_basis(self, basis: QPDBasis) -> None:

@property
def basis_id(self) -> int | None:
"""
Index to basis used to decompose this gate.
"""Index to basis used to decompose this gate.
If set to None, a random basis will be chosen during decomposition.
Expand All @@ -76,8 +73,7 @@ def basis_id(self) -> int | None:

@basis_id.setter
def basis_id(self, basis_id: int | None) -> None:
"""
Set the index to the basis to which this gate should decompose.
"""Set the index to the basis to which this gate should decompose.
The index corresponds to self.basis.maps.
Expand Down Expand Up @@ -110,8 +106,7 @@ def __init__(
basis_id: int | None = None,
label: str | None = None,
):
"""
Initialize the two qubit QPD gate.
"""Initialize the two qubit QPD gate.
Raises:
ValueError: The :class:`QPDBasis` acts on a number of qubits not equal to 2.
Expand Down Expand Up @@ -145,8 +140,7 @@ def from_instruction(cls, instruction: Instruction, /):


class SingleQubitQPDGate(BaseQPDGate):
"""
Single qubit gate to be decomposed using quasiprobability decomposition.
"""Single qubit gate to be decomposed using quasiprobability decomposition.
This gate could be part of a larger decomposition on many qubits, or it
could be a standalone single gate decomposition.
Expand All @@ -160,13 +154,15 @@ def __init__(
basis_id: int | None = None,
label: str | None = None,
):
"""
Initialize the single qubit QPD gate, and assign member variables.
"""Initialize the single qubit QPD gate, and assign member variables.
Args:
basis: TODO
qubit_id: This gate's relative index to the decomposition which it belongs.
Single qubit QPDGates should have qubit_id 0 if they describe a local
decomposition, such as a wire cut.
basis_id: TODO
label: TODO
Raises:
ValueError: qubit_id is out of range
Expand Down
12 changes: 4 additions & 8 deletions qiskit_addon_cutting/qpd/qpd_basis.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@ def __init__(
maps: Sequence[tuple[Sequence[Instruction], ...]],
coeffs: Sequence[float],
):
"""
Assign member variables.
"""Assign member variables.
Args:
maps: A sequence of tuples describing the noisy operations probabilistically
Expand Down Expand Up @@ -97,26 +96,23 @@ def probabilities(self) -> Sequence[float]:

@property
def kappa(self) -> float:
"""
Get the square root of the sampling overhead.
"""Get the square root of the sampling overhead.
This quantity is the sum of the magnitude of the coefficients.
"""
return self._kappa

@property
def overhead(self) -> float:
"""
Get the sampling overhead.
"""Get the sampling overhead.
The sampling overhead is the square of the sum of the magnitude of the coefficients.
"""
return self._kappa**2

@staticmethod
def from_instruction(gate: Instruction, /) -> QPDBasis:
"""
Generate a :class:`.QPDBasis` object, given a supported operation.
"""Generate a :class:`.QPDBasis` object, given a supported operation.
This static method is provided for convenience; it simply
calls :func:`~qpd.decompositions.qpdbasis_from_instruction` under the hood.
Expand Down
15 changes: 5 additions & 10 deletions qiskit_addon_cutting/qpd/weights.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,7 @@ def __update_running_product_after_increment(
state: Sequence[int],
coeff_probabilities: Sequence[npt.NDArray[np.float64]],
):
"""
Update the ``running_product`` list after the ``state`` has been incremented.
"""Update the ``running_product`` list after the ``state`` has been incremented.
This snippet is used twice in
:func:`_generate_exact_weights_and_conditional_probabilities_assume_sorted`;
Expand All @@ -71,8 +70,7 @@ def __update_running_product_after_increment(
def _generate_exact_weights_and_conditional_probabilities_assume_sorted(
coeff_probabilities: Sequence[npt.NDArray[np.float64]], threshold: float
):
r"""
Determine all exact weights above ``threshold`` and the conditional probabilities necessary to sample efficiently from all other weights.
r"""Determine all exact weights above ``threshold`` and the conditional probabilities necessary to sample efficiently from all other weights.
Each yielded element will be a 2-tuple, the first element of which will be
a ``state``, represented by a tuple of ``int``\ s.
Expand Down Expand Up @@ -190,8 +188,7 @@ def _invert_permutation(p):
def _generate_exact_weights_and_conditional_probabilities(
coeff_probabilities: Sequence[npt.NDArray[np.float64]], threshold: float
):
"""
Generate exact weights and conditional probabilities.
"""Generate exact weights and conditional probabilities.
This is identical in behavior to
:func:`_generate_exact_weights_and_conditional_probabilities_assume_sorted`,
Expand Down Expand Up @@ -221,8 +218,7 @@ def _generate_exact_weights_and_conditional_probabilities(
def generate_qpd_weights(
qpd_bases: Sequence[QPDBasis], num_samples: float = 1000
) -> dict[tuple[int, ...], tuple[float, WeightType]]:
"""
Generate weights from the joint quasiprobability distribution.
"""Generate weights from the joint quasiprobability distribution.
Each weight whose absolute value is above a threshold of ``1 /
num_samples`` will be evaluated exactly. The remaining weights -- those in
Expand Down Expand Up @@ -384,8 +380,7 @@ def _populate_samples(
conditional_probabilities: dict[tuple[int, ...], npt.NDArray[np.float64]],
running_state: tuple[int, ...] = (),
) -> None:
"""
Generate random samples from the conditional probabilitity distributions.
"""Generate random samples from the conditional probabilitity distributions.
Items get populated into the ``random_samples`` dict, rather than returned.
Expand Down
Loading

0 comments on commit f1be40e

Please sign in to comment.