Skip to content

Commit

Permalink
Add ruff as a dev tool
Browse files Browse the repository at this point in the history
  • Loading branch information
MetinSa committed Jan 10, 2023
1 parent f1b76c4 commit 96fcd94
Show file tree
Hide file tree
Showing 14 changed files with 105 additions and 130 deletions.
11 changes: 10 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 19 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ pytest-cov = "^3.0.0"
mkdocs-material = "^9.0.1"
mkdocstrings = "^0.19.1"
mkdocstrings-python = "^0.8.2"
ruff = "^0.0.217"

[build-system]
requires = ["poetry-core>=1.0.0"]
Expand All @@ -50,4 +51,21 @@ overrides = [
filterwarnings = [
"ignore::UserWarning",
"ignore:.*overflow encountered in expm1.*",
]
]

[tool.isort]
profile = "black"

[tool.ruff]
select = ["F", "D", "E", "W", "C", "B", "I001"]
line-length = 100
ignore = [
"B905",
"D100",
"D107",
"D104",
"D105",
]

[tool.ruff.pydocstyle]
convention = "google"
14 changes: 5 additions & 9 deletions zodipy/_bandpass.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@
import numpy as np
import numpy.typing as npt

from zodipy._ipd_model import InterplanetaryDustModel
from zodipy._validators import validate_and_normalize_weights, validate_frequencies
from zodipy._source_funcs import get_blackbody_emission
from zodipy._constants import (
N_INTERPOLATION_POINTS,
MIN_INTERPOLATION_GRID_TEMPERATURE,
MAX_INTERPOLATION_GRID_TEMPERATURE,
MIN_INTERPOLATION_GRID_TEMPERATURE,
N_INTERPOLATION_POINTS,
)
from zodipy._ipd_model import InterplanetaryDustModel
from zodipy._source_funcs import get_blackbody_emission
from zodipy._types import FrequencyOrWavelength
from zodipy._validators import validate_and_normalize_weights, validate_frequencies


@dataclass
Expand All @@ -25,12 +25,10 @@ class Bandpass:

def integrate(self, quantity: npt.NDArray[np.float64]) -> npt.NDArray[np.float64]:
"""Integrate a quantity over the bandpass."""

return np.trapz(self.weights * quantity, self.frequencies.value, axis=-1)

def switch_convention(self) -> None:
"""Switched the bandpass from frequency to wavelength or vice versa."""

self.frequencies = self.frequencies.to(
u.micron if self.frequencies.unit.is_equivalent(u.Hz) else u.Hz,
equivalencies=u.spectral(),
Expand All @@ -48,7 +46,6 @@ def validate_and_get_bandpass(
extrapolate: bool,
) -> Bandpass:
"""Validate user inputted bandpass and return a Bandpass object."""

validate_frequencies(freq, model, extrapolate)
normalized_weights = validate_and_normalize_weights(weights, freq)

Expand All @@ -62,7 +59,6 @@ def get_bandpass_interpolation_table(
max_temp: float = MAX_INTERPOLATION_GRID_TEMPERATURE,
) -> npt.NDArray[np.float64]:
"""Pre-compute the bandpass integrated blackbody emission for a grid of temperatures."""

# Prepare bandpass to be integrated in power units and in frequency convention.
if not bandpass.frequencies.unit.is_equivalent(u.Hz):
bandpass.switch_convention()
Expand Down
3 changes: 1 addition & 2 deletions zodipy/_contour.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,11 @@ def tabulate_density(
earth_pos
Position of the Earth in AU.
Returns
Returns:
-------
density_grid
The tabulated zodiacal component densities.
"""

ipd_model = model_registry.get_model(model)

if not isinstance(grid, np.ndarray):
Expand Down
2 changes: 0 additions & 2 deletions zodipy/_emission.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ def kelsall(
bp_interpolation_table: npt.NDArray[np.float64],
) -> npt.NDArray[np.float64]:
"""Kelsall uses common line of sight grid from obs to 5.2 AU."""

# Convert the quadrature range from [-1, 1] to the true ecliptic positions
R_los = ((stop - start) / 2) * r + (stop + start) / 2
X_los = R_los * u_los
Expand Down Expand Up @@ -70,7 +69,6 @@ def rrm(
bp_interpolation_table: npt.NDArray[np.float64],
) -> npt.NDArray[np.float64]:
"""RRM has component specific line of sight grids."""

# Convert the quadrature range from [-1, 1] to the true ecliptic positions
R_los = ((stop - start) / 2) * r + (stop + start) / 2
X_los = R_los * u_los
Expand Down
5 changes: 3 additions & 2 deletions zodipy/_interpolate_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,15 @@

from zodipy._bandpass import Bandpass
from zodipy._constants import SPECIFIC_INTENSITY_UNITS
from zodipy._ipd_model import RRM, InterplanetaryDustModel, Kelsall
from zodipy._ipd_comps import ComponentLabel
from zodipy._ipd_model import RRM, InterplanetaryDustModel, Kelsall

InterplanetaryDustModelT = TypeVar(
"InterplanetaryDustModelT", bound=InterplanetaryDustModel
)

"""Returns the source parameters for a given bandpass and model. Must match arguments in the emission fns."""
"""Returns the source parameters for a given bandpass and model.
Must match arguments in the emission fns."""
GetSourceParametersFn = Callable[
[Bandpass, InterplanetaryDustModelT], Dict[Union[ComponentLabel, str], Any]
]
Expand Down
95 changes: 38 additions & 57 deletions zodipy/_ipd_dens_funcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from dataclasses import asdict
from functools import partial
from typing import Any, Callable, Mapping, Protocol, Sequence

import numpy as np
import numpy.typing as npt

Expand All @@ -13,6 +14,7 @@
Cloud,
Comet,
Component,
ComponentLabel,
Fan,
Feature,
FeatureRRM,
Expand All @@ -21,7 +23,6 @@
Ring,
RingRRM,
)
from zodipy._ipd_comps import ComponentLabel

"""The density functions for the different types of components. Common for all of these
is that the first argument will be `X_helio` (the line of sight from the observer towards
Expand All @@ -47,7 +48,6 @@ def compute_cloud_density(
gamma: float,
) -> npt.NDArray[np.float64]:
"""Density of the diffuse cloud (see Eq (6). in K98)."""

X_cloud = X_helio - X_0
R_cloud = np.sqrt(X_cloud[0] ** 2 + X_cloud[1] ** 2 + X_cloud[2] ** 2)

Expand Down Expand Up @@ -78,7 +78,6 @@ def compute_band_density(
delta_r: float,
) -> npt.NDArray[np.float64]:
"""Density of the dust bands (see Eq. (8) in K98)."""

X_band = X_helio - X_0
R_band = np.sqrt(X_band[0] ** 2 + X_band[1] ** 2 + X_band[2] ** 2)

Expand Down Expand Up @@ -115,7 +114,6 @@ def compute_ring_density(
sigma_z: float,
) -> npt.NDArray[np.float64]:
"""Density of the circum-solar ring (see Eq. (9) in K98)."""

X_ring = X_helio - X_0
R_ring = np.sqrt(X_ring[0] ** 2 + X_ring[1] ** 2 + X_ring[2] ** 2)

Expand Down Expand Up @@ -148,7 +146,6 @@ def compute_feature_density(
sigma_theta_rad: float,
) -> npt.NDArray[np.float64]:
"""Density of the Earth-trailing feature (see Eq. (9) in K98)."""

X_feature = X_helio - X_0
R_feature = np.sqrt(X_feature[0] ** 2 + X_feature[1] ** 2 + X_feature[2] ** 2)

Expand Down Expand Up @@ -190,7 +187,6 @@ def compute_fan_density( # *
R_outer: float,
) -> npt.NDArray[np.float64]:
"""Density of the fan (see Eq (3). in RRM)."""

X_fan = X_helio - X_0
R_fan = np.sqrt(X_fan[0] ** 2 + X_fan[1] ** 2 + X_fan[2] ** 2)

Expand Down Expand Up @@ -228,7 +224,6 @@ def compute_comet_density(
R_outer: float,
) -> npt.NDArray[np.float64]:
"""Density of the fan (see Eq (3). in RRM)."""

X_comet = X_helio - X_0
R_comet = np.sqrt(X_comet[0] ** 2 + X_comet[1] ** 2 + X_comet[2] ** 2)

Expand Down Expand Up @@ -272,7 +267,6 @@ def compute_narrow_band_density(
R_outer: float,
) -> npt.NDArray[np.float64]:
"""Density of the fan (see Eq (4). in RRM)."""

X_nb = X_helio - X_0
R_nb = np.sqrt(X_nb[0] ** 2 + X_nb[1] ** 2 + X_nb[2] ** 2)

Expand Down Expand Up @@ -314,7 +308,6 @@ def compute_broad_band_density(
R_outer: float,
) -> npt.NDArray[np.float64]:
"""Density of the fan (see Eq (5). in RRM)."""

X_bb = X_helio - X_0
R_bb = np.sqrt(X_bb[0] ** 2 + X_bb[1] ** 2 + X_bb[2] ** 2)

Expand Down Expand Up @@ -350,22 +343,17 @@ def compute_ring_density_rmm(
sigma_z: float,
A: float,
) -> npt.NDArray[np.float64]:
return (
A
* compute_ring_density(
X_helio=X_helio,
X_0=X_0,
sin_Omega_rad=sin_Omega_rad,
cos_Omega_rad=cos_Omega_rad,
sin_i_rad=sin_i_rad,
cos_i_rad=cos_i_rad,
n_0=1,
R=R,
sigma_r=sigma_r,
sigma_z=sigma_z,
)
# * 1e-6
# / (1 * u.cm).to_value(u.AU)
return A * compute_ring_density(
X_helio=X_helio,
X_0=X_0,
sin_Omega_rad=sin_Omega_rad,
cos_Omega_rad=cos_Omega_rad,
sin_i_rad=sin_i_rad,
cos_i_rad=cos_i_rad,
n_0=n_0,
R=R,
sigma_r=sigma_r,
sigma_z=sigma_z,
)


Expand All @@ -385,25 +373,20 @@ def compute_feature_density_rmm(
sigma_theta_rad: float,
A: float,
) -> npt.NDArray[np.float64]:
return (
A
* compute_feature_density(
X_helio=X_helio,
X_0=X_0,
sin_Omega_rad=sin_Omega_rad,
cos_Omega_rad=cos_Omega_rad,
sin_i_rad=sin_i_rad,
cos_i_rad=cos_i_rad,
n_0=1,
R=R,
sigma_r=sigma_r,
sigma_z=sigma_z,
X_earth=X_earth,
sigma_theta_rad=sigma_theta_rad,
theta_rad=theta_rad,
)
# * 1e-6
# / (1 * u.cm).to_value(u.AU)
return A * compute_feature_density(
X_helio=X_helio,
X_0=X_0,
sin_Omega_rad=sin_Omega_rad,
cos_Omega_rad=cos_Omega_rad,
sin_i_rad=sin_i_rad,
cos_i_rad=cos_i_rad,
n_0=n_0,
R=R,
sigma_r=sigma_r,
sigma_z=sigma_z,
X_earth=X_earth,
sigma_theta_rad=sigma_theta_rad,
theta_rad=theta_rad,
)


Expand Down Expand Up @@ -432,24 +415,23 @@ def construct_density_partials(
comps: Sequence[Component],
dynamic_params: dict[str, Any],
) -> tuple[ComponentDensityFn, ...]:
"""
Return a tuple of the density expressions above which has been prepopulated with model and
configuration parameters, leaving only the `X_helio` argument to be supplied.
"""Return density partials for the components.
Return a tuple of the density expressions above which has been prepopulated with
model and configuration parameters, leaving only the `X_helio` argument to be supplied.
Raises exception for incorrectly defined components or component density functions.
"""

partial_density_funcs: list[ComponentDensityFn] = []
for comp in comps:
comp_dict = asdict(comp)
func_params = inspect.signature(DENSITY_FUNCS[type(comp)]).parameters.keys()
residual_params = [key for key in func_params if key not in comp_dict.keys()]
try:
residual_params.remove("X_helio")
except ValueError:
except ValueError as err:
raise ValueError(
"X_helio must be be the first argument to the density function of a component."
)
) from err

if residual_params:
if residual_params - dynamic_params.keys():
Expand All @@ -474,24 +456,23 @@ def construct_density_partials_comps(
comps: Mapping[ComponentLabel, Component],
dynamic_params: dict[str, Any],
) -> dict[ComponentLabel, ComponentDensityFn]:
"""
Return a tuple of the density expressions above which has been prepopulated with model and
configuration parameters, leaving only the `X_helio` argument to be supplied.
"""Construct density partials for components.
Raises exception for incorrectly defined components or component density functions.
Return a tuple of the density expressions above which has been prepopulated with model and
configuration parameters, leaving only the `X_helio` argument to be supplied. Raises exception
for incorrectly defined components or component density functions.
"""

partial_density_funcs: dict[ComponentLabel, ComponentDensityFn] = {}
for comp_label, comp in comps.items():
comp_dict = asdict(comp)
func_params = inspect.signature(DENSITY_FUNCS[type(comp)]).parameters.keys()
residual_params = [key for key in func_params if key not in comp_dict.keys()]
try:
residual_params.remove("X_helio")
except ValueError:
except ValueError as err:
raise ValueError(
"X_helio must be be the first argument to the density function of a component."
)
) from err

if residual_params:
if residual_params - dynamic_params.keys():
Expand Down
Loading

0 comments on commit 96fcd94

Please sign in to comment.