Skip to content

Commit

Permalink
Merge pull request #386 from pybop-team/ruff-lint-changes
Browse files Browse the repository at this point in the history
Additions to ruff rules
  • Loading branch information
BradyPlanden authored Jul 11, 2024
2 parents d462f27 + bd3d59b commit 4638a60
Show file tree
Hide file tree
Showing 38 changed files with 182 additions and 153 deletions.
3 changes: 1 addition & 2 deletions benchmarks/benchmark_model.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import numpy as np

import pybop

from .benchmark_utils import set_random_seed
from benchmarks.benchmark_utils import set_random_seed


class BenchmarkModel:
Expand Down
3 changes: 1 addition & 2 deletions benchmarks/benchmark_optim_construction.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import numpy as np

import pybop

from .benchmark_utils import set_random_seed
from benchmarks.benchmark_utils import set_random_seed


class BenchmarkOptimisationConstruction:
Expand Down
3 changes: 1 addition & 2 deletions benchmarks/benchmark_parameterisation.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import numpy as np

import pybop

from .benchmark_utils import set_random_seed
from benchmarks.benchmark_utils import set_random_seed


class BenchmarkParameterisation:
Expand Down
3 changes: 1 addition & 2 deletions benchmarks/benchmark_track_parameterisation.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import numpy as np

import pybop

from .benchmark_utils import set_random_seed
from benchmarks.benchmark_utils import set_random_seed


class BenchmarkTrackParameterisation:
Expand Down
6 changes: 3 additions & 3 deletions docs/_extension/gallery_directive.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"""

from pathlib import Path
from typing import Any, Dict, List
from typing import Any

from docutils import nodes
from docutils.parsers.rst import directives
Expand Down Expand Up @@ -68,7 +68,7 @@ class GalleryGridDirective(SphinxDirective):
"class-card": directives.unchanged,
}

def run(self) -> List[nodes.Node]:
def run(self) -> list[nodes.Node]:
"""Create the gallery grid."""
if self.arguments:
# If an argument is given, assume it's a path to a YAML file
Expand Down Expand Up @@ -129,7 +129,7 @@ def run(self) -> List[nodes.Node]:
return [container.children[0]]


def setup(app: Sphinx) -> Dict[str, Any]:
def setup(app: Sphinx) -> dict[str, Any]:
"""Add custom configuration to sphinx app.
Args:
Expand Down
4 changes: 2 additions & 2 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@
from pathlib import Path

sys.path.append(str(Path(".").resolve()))
from pybop._version import __version__ # noqa: E402
from pybop._version import __version__

# -- Project information -----------------------------------------------------
project = "PyBOP"
copyright = "2023, The PyBOP Team"
copyright = "2023, The PyBOP Team" # noqa A001
author = "The PyBOP Team"
release = f"v{__version__}"

Expand Down
2 changes: 1 addition & 1 deletion examples/standalone/problem.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def __init__(
self._dataset = dataset.data

# Check that the dataset contains time and current
for name in ["Time [s]"] + self.signal:
for name in ["Time [s]", *self.signal]:
if name not in self._dataset:
raise ValueError(f"expected {name} in list of dataset")

Expand Down
28 changes: 5 additions & 23 deletions pybop/_dataset.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import numpy as np
from pybamm import Interpolant, solvers
from pybamm import t as pybamm_t
from pybamm import solvers


class Dataset:
Expand Down Expand Up @@ -77,26 +76,7 @@ def __getitem__(self, key):

return self.data[key]

def Interpolant(self):
"""
Create an interpolation function of the dataset based on the independent variable.
Currently, only time-based interpolation is supported. This method modifies
the instance's Interpolant attribute to be an interpolation function that
can be evaluated at different points in time.
Raises
------
NotImplementedError
If the independent variable for interpolation is not supported.
"""

if self.variable == "time":
self.Interpolant = Interpolant(self.x, self.y, pybamm_t)
else:
NotImplementedError("Only time interpolation is supported")

def check(self, signal=["Voltage [V]"]):
def check(self, signal=None):
"""
Check the consistency of a PyBOP Dataset against the expected format.
Expand All @@ -110,11 +90,13 @@ def check(self, signal=["Voltage [V]"]):
ValueError
If the time series and the data series are not consistent.
"""
if signal is None:
signal = ["Voltage [V]"]
if isinstance(signal, str):
signal = [signal]

# Check that the dataset contains time and chosen signal
for name in ["Time [s]"] + signal:
for name in ["Time [s]", *signal]:
if name not in self.names:
raise ValueError(f"expected {name} in list of dataset")

Expand Down
26 changes: 13 additions & 13 deletions pybop/costs/_likelihoods.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import List, Tuple, Union
from typing import Union

import numpy as np

Expand All @@ -14,7 +14,7 @@ class BaseLikelihood(BaseCost):
"""

def __init__(self, problem: BaseProblem):
super(BaseLikelihood, self).__init__(problem)
super().__init__(problem)
self.n_time_data = problem.n_time_data


Expand All @@ -32,8 +32,8 @@ class GaussianLogLikelihoodKnownSigma(BaseLikelihood):
per dimension.
"""

def __init__(self, problem: BaseProblem, sigma0: Union[List[float], float]):
super(GaussianLogLikelihoodKnownSigma, self).__init__(problem)
def __init__(self, problem: BaseProblem, sigma0: Union[list[float], float]):
super().__init__(problem)
sigma0 = self.check_sigma0(sigma0)
self.sigma2 = sigma0**2.0
self._offset = -0.5 * self.n_time_data * np.log(2 * np.pi * self.sigma2)
Expand Down Expand Up @@ -62,7 +62,7 @@ def _evaluate(self, inputs: Inputs, grad: Union[None, np.ndarray] = None) -> flo

return e if self.n_outputs != 1 else e.item()

def _evaluateS1(self, inputs: Inputs) -> Tuple[float, np.ndarray]:
def _evaluateS1(self, inputs: Inputs) -> tuple[float, np.ndarray]:
"""
Calls the problem.evaluateS1 method and calculates the log-likelihood and gradient.
"""
Expand Down Expand Up @@ -90,7 +90,7 @@ def check_sigma0(self, sigma0: Union[np.ndarray, float]):
if np.shape(sigma0) not in [(), (1,), (self.n_outputs,)]:
raise ValueError(
"sigma0 must be either a scalar value (one standard deviation for "
+ "all coordinates) or an array with one entry per dimension."
"all coordinates) or an array with one entry per dimension."
)
return sigma0

Expand All @@ -115,10 +115,10 @@ class GaussianLogLikelihood(BaseLikelihood):
def __init__(
self,
problem: BaseProblem,
sigma0: Union[float, List[float], List[Parameter]] = 0.002,
sigma0: Union[float, list[float], list[Parameter]] = 0.002,
dsigma_scale: float = 1.0,
):
super(GaussianLogLikelihood, self).__init__(problem)
super().__init__(problem)
self._dsigma_scale = dsigma_scale
self._logpi = -0.5 * self.n_time_data * np.log(2 * np.pi)

Expand All @@ -128,7 +128,7 @@ def __init__(
self._dl = np.ones(self.n_parameters)

def _add_sigma_parameters(self, sigma0):
sigma0 = [sigma0] if not isinstance(sigma0, List) else sigma0
sigma0 = [sigma0] if not isinstance(sigma0, list) else sigma0
sigma0 = self._pad_sigma0(sigma0)

for i, value in enumerate(sigma0):
Expand Down Expand Up @@ -214,7 +214,7 @@ def _evaluate(self, inputs: Inputs, grad: Union[None, np.ndarray] = None) -> flo

return e if self.n_outputs != 1 else e.item()

def _evaluateS1(self, inputs: Inputs) -> Tuple[float, np.ndarray]:
def _evaluateS1(self, inputs: Inputs) -> tuple[float, np.ndarray]:
"""
Calls the problem.evaluateS1 method and calculates the log-likelihood.
Expand Down Expand Up @@ -265,7 +265,7 @@ class MAP(BaseLikelihood):
"""

def __init__(self, problem, likelihood, sigma0=None, gradient_step=1e-3):
super(MAP, self).__init__(problem)
super().__init__(problem)
self.sigma0 = sigma0
self.gradient_step = gradient_step
if self.sigma0 is None:
Expand All @@ -278,7 +278,7 @@ def __init__(self, problem, likelihood, sigma0=None, gradient_step=1e-3):
except Exception as e:
raise ValueError(
f"An error occurred when constructing the Likelihood class: {e}"
)
) from e

if hasattr(self, "likelihood") and not isinstance(
self.likelihood, BaseLikelihood
Expand Down Expand Up @@ -310,7 +310,7 @@ def _evaluate(self, inputs: Inputs, grad=None) -> float:
posterior = log_likelihood + log_prior
return posterior

def _evaluateS1(self, inputs: Inputs) -> Tuple[float, np.ndarray]:
def _evaluateS1(self, inputs: Inputs) -> tuple[float, np.ndarray]:
"""
Compute the maximum a posteriori with respect to the parameters.
The method passes the likelihood gradient to the optimiser without modification.
Expand Down
4 changes: 2 additions & 2 deletions pybop/costs/base_cost.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def evaluate(self, x, grad=None):
raise e

except Exception as e:
raise ValueError(f"Error in cost calculation: {e}")
raise ValueError(f"Error in cost calculation: {e}") from e

def _evaluate(self, inputs: Inputs, grad=None):
"""
Expand Down Expand Up @@ -129,7 +129,7 @@ def evaluateS1(self, x):
raise e

except Exception as e:
raise ValueError(f"Error in cost calculation: {e}")
raise ValueError(f"Error in cost calculation: {e}") from e

def _evaluateS1(self, inputs: Inputs):
"""
Expand Down
8 changes: 4 additions & 4 deletions pybop/costs/design_costs.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def __init__(self, problem, update_capacity=False):
problem : object
The problem instance containing the model and data.
"""
super(DesignCost, self).__init__(problem)
super().__init__(problem)
self.problem = problem
if update_capacity is True:
nominal_capacity_warning = (
Expand All @@ -41,7 +41,7 @@ def __init__(self, problem, update_capacity=False):
nominal_capacity_warning = (
"The nominal capacity is fixed at the initial model value."
)
warnings.warn(nominal_capacity_warning, UserWarning)
warnings.warn(nominal_capacity_warning, UserWarning, stacklevel=2)
self.update_capacity = update_capacity
self.parameter_set = problem.model.parameter_set
self.update_simulation_data(self.parameters.as_dict("initial"))
Expand Down Expand Up @@ -97,7 +97,7 @@ class GravimetricEnergyDensity(DesignCost):
"""

def __init__(self, problem, update_capacity=False):
super(GravimetricEnergyDensity, self).__init__(problem, update_capacity)
super().__init__(problem, update_capacity)

def _evaluate(self, inputs: Inputs, grad=None):
"""
Expand Down Expand Up @@ -153,7 +153,7 @@ class VolumetricEnergyDensity(DesignCost):
"""

def __init__(self, problem, update_capacity=False):
super(VolumetricEnergyDensity, self).__init__(problem, update_capacity)
super().__init__(problem, update_capacity)

def _evaluate(self, inputs: Inputs, grad=None):
"""
Expand Down
6 changes: 3 additions & 3 deletions pybop/costs/fitting_costs.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class RootMeanSquaredError(BaseCost):
"""

def __init__(self, problem):
super(RootMeanSquaredError, self).__init__(problem)
super().__init__(problem)

# Default fail gradient
self._de = 1.0
Expand Down Expand Up @@ -131,7 +131,7 @@ class SumSquaredError(BaseCost):
"""

def __init__(self, problem):
super(SumSquaredError, self).__init__(problem)
super().__init__(problem)

# Default fail gradient
self._de = 1.0
Expand Down Expand Up @@ -161,7 +161,7 @@ def _evaluate(self, inputs: Inputs, grad=None):

e = np.asarray(
[
np.sum(((prediction[signal] - self._target[signal]) ** 2))
np.sum((prediction[signal] - self._target[signal]) ** 2)
for signal in self.signal
]
)
Expand Down
Loading

0 comments on commit 4638a60

Please sign in to comment.