Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace pydocstyle with Ruff #87

Merged
merged 2 commits into from
Oct 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ style = [
]
lint = [
"qiskit-addon-sqd[style]",
"pydocstyle==6.3.0",
"mypy==1.11.2",
"pylint==3.3.1",
"reno>=4.1",
Expand Down Expand Up @@ -134,6 +133,7 @@ select = [
"I", # isort
"E", # pycodestyle
"W", # pycodestyle
"D", # pydocstyle
"F", # pyflakes
"RUF", # ruff
"UP", # pyupgrade
Expand All @@ -149,8 +149,12 @@ ignore = [
max-args = 6

[tool.ruff.lint.extend-per-file-ignores]
"test/**.py" = [
"D", # pydocstyle
]
"docs/**/*" = [
"E402", # module level import not at top of file
"D", # pydocstyle
]

[tool.ruff.lint.flake8-copyright]
Expand All @@ -167,3 +171,6 @@ notice-rgx = """
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals\\.
"""

[tool.ruff.lint.pydocstyle]
convention = "google"
3 changes: 1 addition & 2 deletions qiskit_addon_sqd/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

"""
Primary SQD functionality.
"""Primary SQD functionality.

.. currentmodule:: qiskit_addon_sqd

Expand Down
23 changes: 11 additions & 12 deletions qiskit_addon_sqd/configuration_recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

"""
Functions for performing self-consistent configuration recovery.
"""Functions for performing self-consistent configuration recovery.

.. currentmodule:: qiskit_addon_sqd.configuration_recovery

Expand All @@ -34,8 +33,7 @@
def post_select_by_hamming_weight(
bitstring_matrix: np.ndarray, *, hamming_right: int, hamming_left: int
) -> np.ndarray:
"""
Post-select bitstrings based on the hamming weight of each half.
"""Post-select bitstrings based on the hamming weight of each half.

Args:
bitstring_matrix: A 2D array of ``bool`` representations of bit
Expand All @@ -45,6 +43,7 @@ def post_select_by_hamming_weight(

Returns:
A mask signifying which samples (rows) were selected from the input matrix.

"""
if hamming_left < 0 or hamming_right < 0:
raise ValueError("Hamming weights must be non-negative integers.")
Expand All @@ -66,8 +65,7 @@ def recover_configurations(
num_elec_b: int,
rand_seed: int | None = None,
) -> tuple[np.ndarray, np.ndarray]:
"""
Refine bitstrings based on average orbital occupancy and a target hamming weight.
"""Refine bitstrings based on average orbital occupancy and a target hamming weight.

This function refines each bit in isolation in an attempt to transform the Hilbert space
represented by the input ``bitstring_matrix`` into a space closer to that which supports
Expand Down Expand Up @@ -101,6 +99,7 @@ def recover_configurations(
References:
[1]: J. Robledo-Moreno, et al., `Chemistry Beyond Exact Solutions on a Quantum-Centric Supercomputer <https://arxiv.org/abs/2405.05068>`_,
arXiv:2405.05068 [quant-ph].

"""
if num_elec_a < 0 or num_elec_b < 0:
raise ValueError("The numbers of electrons must be specified as non-negative integers.")
Expand All @@ -126,8 +125,7 @@ def recover_configurations(


def _p_flip_0_to_1(ratio_exp: float, occ: float, eps: float = 0.01) -> float: # pragma: no cover
"""
Calculate the probability of flipping a bit from 0 to 1.
"""Calculate the probability of flipping a bit from 0 to 1.

This function will more aggressively flip bits which are in disagreement
with the occupation information.
Expand All @@ -140,6 +138,7 @@ def _p_flip_0_to_1(ratio_exp: float, occ: float, eps: float = 0.01) -> float: #

Returns:
The probability with which to flip the bit

"""
# Occupancy is < than naive expectation.
# Flip 0s to 1 with small (~eps) probability in this case
Expand All @@ -157,8 +156,7 @@ def _p_flip_0_to_1(ratio_exp: float, occ: float, eps: float = 0.01) -> float: #


def _p_flip_1_to_0(ratio_exp: float, occ: float, eps: float = 0.01) -> float: # pragma: no cover
"""
Calculate the probability of flipping a bit from 1 to 0.
"""Calculate the probability of flipping a bit from 1 to 0.

This function will more aggressively flip bits which are in disagreement
with the occupation information.
Expand All @@ -171,6 +169,7 @@ def _p_flip_1_to_0(ratio_exp: float, occ: float, eps: float = 0.01) -> float: #

Returns:
The probability with which to flip the bit

"""
# Occupancy is < naive expectation.
# The probability to flip the bit increases linearly from ``eps`` to
Expand All @@ -195,8 +194,7 @@ def _bipartite_bitstring_correcting(
hamming_left: int,
rand_seed: int | None = None,
) -> np.ndarray:
"""
Use occupancy information and target hamming weight to correct a bitstring.
"""Use occupancy information and target hamming weight to correct a bitstring.

Args:
bit_array: A 1D array of ``bool`` representations of bit values
Expand All @@ -207,6 +205,7 @@ def _bipartite_bitstring_correcting(

Returns:
A corrected bitstring

"""
# This function must not mutate the input arrays.
bit_array = bit_array.copy()
Expand Down
15 changes: 7 additions & 8 deletions qiskit_addon_sqd/counts.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

"""
Functions for transforming counts dictionaries.
"""Functions for transforming counts dictionaries.

.. currentmodule:: qiskit_addon_sqd.counts

Expand All @@ -31,8 +30,7 @@


def counts_to_arrays(counts: dict[str, float | int]) -> tuple[np.ndarray, np.ndarray]:
"""
Convert a counts dictionary into a bitstring matrix and a probability array.
"""Convert a counts dictionary into a bitstring matrix and a probability array.

Args:
counts: The counts dictionary to convert
Expand All @@ -43,6 +41,7 @@ def counts_to_arrays(counts: dict[str, float | int]) -> tuple[np.ndarray, np.nda
bitstring, and each element is a ``bool`` representation of the
bit's value
- A 1D array containing the probability with which each bitstring was sampled

"""
if not counts:
return np.array([]), np.array([])
Expand All @@ -56,8 +55,7 @@ def counts_to_arrays(counts: dict[str, float | int]) -> tuple[np.ndarray, np.nda
def generate_counts_uniform(
num_samples: int, num_bits: int, rand_seed: None | int = None
) -> dict[str, int]:
"""
Generate a bitstring counts dictionary of samples drawn from the uniform distribution.
"""Generate a bitstring counts dictionary of samples drawn from the uniform distribution.

Args:
num_samples: The number of samples to draw
Expand All @@ -70,6 +68,7 @@ def generate_counts_uniform(

Raises:
ValueError: ``num_samples`` and ``num_bits`` must be positive integers.

"""
if num_samples < 1:
raise ValueError("The number of samples must be specified with a positive integer.")
Expand All @@ -96,8 +95,7 @@ def generate_counts_bipartite_hamming(
hamming_left: int,
rand_seed: None | int = None,
) -> dict[str, int]:
"""
Generate a bitstring counts dictionary with specified bipartite hamming weight.
"""Generate a bitstring counts dictionary with specified bipartite hamming weight.

Args:
num_samples: The number of samples to draw
Expand All @@ -115,6 +113,7 @@ def generate_counts_bipartite_hamming(
ValueError: ``num_bits`` and ``num_samples`` must be positive integers.
ValueError: Hamming weights must be specified as non-negative integers.
ValueError: ``num_bits`` must be even.

"""
if num_bits % 2 != 0:
raise ValueError("The number of bits must be specified with an even integer.")
Expand Down
40 changes: 18 additions & 22 deletions qiskit_addon_sqd/fermion.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

"""
Functions for the study of fermionic systems.
"""Functions for the study of fermionic systems.

.. currentmodule:: qiskit_addon_sqd.fermion

Expand Down Expand Up @@ -54,8 +53,7 @@ def solve_fermion(
max_davidson: int = 100,
verbose: int | None = None,
) -> tuple[float, np.ndarray, list[np.ndarray], float]:
"""
Approximate the ground state given molecular integrals and a set of electronic configurations.
"""Approximate the ground state given molecular integrals and a set of electronic configurations.

Args:
bitstring_matrix: A set of configurations defining the subspace onto which the Hamiltonian
Expand Down Expand Up @@ -85,6 +83,7 @@ def solve_fermion(
- SCI coefficients
- Average orbital occupancy
- Expectation value of spin-squared

"""
if isinstance(bitstring_matrix, tuple):
warnings.warn(
Expand Down Expand Up @@ -141,8 +140,7 @@ def optimize_orbitals(
learning_rate: float = 0.01,
max_davidson: int = 100,
) -> tuple[float, np.ndarray, list[np.ndarray]]:
"""
Optimize orbitals to produce a minimal ground state.
"""Optimize orbitals to produce a minimal ground state.

The process involves iterating over 3 steps:

Expand Down Expand Up @@ -188,6 +186,7 @@ def optimize_orbitals(
- The groundstate energy found during the last optimization iteration
- An optimized 1D array defining the orbital transform
- Average orbital occupancy

"""
if isinstance(bitstring_matrix, tuple):
warnings.warn(
Expand Down Expand Up @@ -244,8 +243,7 @@ def optimize_orbitals(
def rotate_integrals(
hcore: np.ndarray, eri: np.ndarray, k_flat: np.ndarray
) -> tuple[np.ndarray, np.ndarray]:
r"""
Perform a similarity transform on the integrals.
r"""Perform a similarity transform on the integrals.

The transformation is described as:

Expand All @@ -265,6 +263,7 @@ def rotate_integrals(
Returns:
- The rotated core Hamiltonian matrix
- The rotated ERI matrix

"""
num_orbitals = hcore.shape[0]
p = np.reshape(k_flat, (num_orbitals, num_orbitals))
Expand All @@ -277,8 +276,7 @@ def rotate_integrals(


def flip_orbital_occupancies(occupancies: np.ndarray) -> np.ndarray:
"""
Flip an orbital occupancy array to match the indexing of a bitstring.
"""Flip an orbital occupancy array to match the indexing of a bitstring.

This function reformats a 1D array of spin-orbital occupancies formatted like:

Expand Down Expand Up @@ -309,8 +307,7 @@ def flip_orbital_occupancies(occupancies: np.ndarray) -> np.ndarray:
def bitstring_matrix_to_sorted_addresses(
bitstring_matrix: np.ndarray, open_shell: bool = False
) -> tuple[np.ndarray, np.ndarray]:
"""
Convert a bitstring matrix into a sorted array of unique, unsigned integers.
"""Convert a bitstring matrix into a sorted array of unique, unsigned integers.

This function separates each bitstring in ``bitstring_matrix`` in half, flips the
bits and translates them into integer representations, and finally appends them to
Expand All @@ -329,6 +326,7 @@ def bitstring_matrix_to_sorted_addresses(
Returns:
A length-2 tuple of sorted, unique determinants representing the left (spin-down) and
right (spin-up) halves of the bitstrings, respectively.

"""
num_orbitals = bitstring_matrix.shape[1] // 2
num_configs = bitstring_matrix.shape[0]
Expand Down Expand Up @@ -356,8 +354,7 @@ def bitstring_matrix_to_sorted_addresses(
def bitstring_matrix_to_ci_strs(
bitstring_matrix: np.ndarray, open_shell: bool = False
) -> tuple[np.ndarray, np.ndarray]:
"""
Convert bitstrings (rows) in a ``bitstring_matrix`` into integer representations of determinants.
"""Convert bitstrings (rows) in a ``bitstring_matrix`` into integer representations of determinants.

This function separates each bitstring in ``bitstring_matrix`` in half, flips the
bits and translates them into integer representations, and finally appends them to
Expand All @@ -376,6 +373,7 @@ def bitstring_matrix_to_ci_strs(
Returns:
A length-2 tuple of determinant lists representing the right (spin-up) and left (spin-down)
halves of the bitstrings, respectively.

"""
num_orbitals = bitstring_matrix.shape[1] // 2
num_configs = bitstring_matrix.shape[0]
Expand Down Expand Up @@ -403,8 +401,7 @@ def bitstring_matrix_to_ci_strs(
def enlarge_batch_from_transitions(
bitstring_matrix: np.ndarray, transition_operators: np.ndarray
) -> np.ndarray:
"""
Apply the set of transition operators to the configurations represented in ``bitstring_matrix``.
"""Apply the set of transition operators to the configurations represented in ``bitstring_matrix``.

Args:
bitstring_matrix: A 2D array of ``bool`` representations of bit
Expand All @@ -416,6 +413,7 @@ def enlarge_batch_from_transitions(
Returns:
Bitstring matrix representing the augmented set of electronic configurations after applying
the excitation operators.

"""
diag, create, annihilate = _transition_str_to_bool(transition_operators)

Expand Down Expand Up @@ -461,8 +459,7 @@ def _optimize_orbitals_sci(
hcore: np.ndarray,
eri: np.ndarray,
) -> None:
"""
Optimize orbital rotation parameters in-place using gradient descent.
"""Optimize orbital rotation parameters in-place using gradient descent.

This procedure is described in `Sec. II A 4 <https://arxiv.org/pdf/2405.05068>`_.
"""
Expand All @@ -482,8 +479,7 @@ def _SCISCF_Energy_contract(
num_orbitals: int,
k_flat: np.ndarray,
) -> Array:
"""
Calculate gradient.
"""Calculate gradient.

The gradient can be calculated by contracting the bare one and two-body
reduced density matrices with the gradients of the of the one and two-body
Expand Down Expand Up @@ -522,8 +518,7 @@ def _apply_excitation_single(


def _transition_str_to_bool(string_rep: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Transform string representations of a transition operator into bool representation.
"""Transform string representations of a transition operator into bool representation.

Transform sequences of identity ("I"), creation ("+"), annihilation ("-"), and number ("n")
characters into the internal representation used to apply the transitions into electronic
Expand All @@ -538,6 +533,7 @@ def _transition_str_to_bool(string_rep: np.ndarray) -> tuple[np.ndarray, np.ndar
- A mask signifying the diagonal terms (I).
- A mask signifying whether there is a creation operator (+).
- A mask signifying whether there is an annihilation operator (-).

"""
diag = np.logical_or(string_rep == "I", string_rep == "n")
create = np.logical_or(string_rep == "+", string_rep == "n")
Expand Down
Loading