Skip to content

Commit 751cac7

Browse files
pre-commit-ci[bot]hammannrCopilot
authored
pre-commit autoupdate & fix/improve docstrings (#232)
* [pre-commit.ci] pre-commit autoupdate updates: - [github.com/pre-commit/pre-commit-hooks: v5.0.0 → v6.0.0](pre-commit/pre-commit-hooks@v5.0.0...v6.0.0) - https://github.com/psf/blackhttps://github.com/psf/black-pre-commit-mirror - [github.com/psf/black-pre-commit-mirror: 24.10.0 → 26.5.1](psf/black-pre-commit-mirror@24.10.0...26.5.1) - [github.com/pycqa/docformatter: v1.7.6 → v1.7.8](PyCQA/docformatter@v1.7.6...v1.7.8) - [github.com/pre-commit/mirrors-mypy: v1.11.2 → v2.1.0](pre-commit/mirrors-mypy@v1.11.2...v2.1.0) - [github.com/pycqa/doc8: v1.1.2 → v2.0.0](PyCQA/doc8@v1.1.2...v2.0.0) - [github.com/pycqa/flake8: 7.1.1 → 7.3.0](PyCQA/flake8@7.1.1...7.3.0) * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * fix and improve all docstrings Co-authored-by: Copilot <copilot@github.com> * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * try to please mypy --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Robert Hammann <robert.hammann@outlook.com> Co-authored-by: Copilot <copilot@github.com>
1 parent 1fe757d commit 751cac7

19 files changed

Lines changed: 231 additions & 218 deletions

.pre-commit-config.yaml

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,15 @@
22
# See https://pre-commit.com/hooks.html for more hooks
33
repos:
44
- repo: https://github.com/pre-commit/pre-commit-hooks
5-
rev: v5.0.0
5+
rev: v6.0.0
66
hooks:
77
- id: trailing-whitespace
88
- id: end-of-file-fixer
99
- id: check-yaml
1010
- id: check-added-large-files
1111

12-
- repo: https://github.com/psf/black
13-
rev: 24.10.0
12+
- repo: https://github.com/psf/black-pre-commit-mirror
13+
rev: 26.5.1
1414
hooks:
1515
- id: black
1616
args: [--safe, --line-length=100]
@@ -19,27 +19,27 @@ repos:
1919
language_version: python3.11
2020

2121
- repo: https://github.com/pycqa/docformatter
22-
rev: v1.7.6
22+
rev: v1.7.8
2323
hooks:
2424
- id: docformatter
2525
additional_dependencies: [tomli]
2626
args: [--config, pyproject.toml]
2727

2828
- repo: https://github.com/pre-commit/mirrors-mypy
29-
rev: v1.11.2
29+
rev: v2.1.0
3030
hooks:
3131
- id: mypy
3232
additional_dependencies: [types-PyYAML, types-tqdm]
3333

3434
- repo: https://github.com/pycqa/doc8
35-
rev: v1.1.2
35+
rev: v2.0.0
3636
hooks:
3737
- id: doc8
3838
files: ^docs/.*\.(rst|md)$
3939
args: [--ignore, D001]
4040

4141
- repo: https://github.com/pycqa/flake8
42-
rev: 7.1.1
42+
rev: 7.3.0
4343
hooks:
4444
- id: flake8
4545

alea/ces_source.py

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
from multihist import Hist1d
1111
from alea.ces_transformation import Transformation
1212

13-
1413
MINIMAL_ENERGY_RESOLUTION = 0.05
1514

1615

@@ -36,7 +35,7 @@ def new_lookup(self, *args):
3635

3736

3837
def safe_lookup(hist_obj):
39-
"A Wrapper to make sure the lookup function returns 0 for out-of-range values"
38+
"""Wrap a histogram's lookup function to return 0 for out-of-range values."""
4039
hist_obj.original_lookup = hist_obj.lookup
4140
hist_obj.lookup = new_lookup.__get__(hist_obj)
4241
return hist_obj
@@ -45,17 +44,12 @@ def safe_lookup(hist_obj):
4544
def rebin_interpolate_normalized(hist, new_edges):
4645
"""Rebin a normalized histogram using interpolation, preserving normalization.
4746
48-
Parameters:
49-
-----------
50-
hist : Hist1d
51-
Input histogram (assumed to be normalized)
52-
new_edges : array-like
53-
New bin edges
47+
Args:
48+
hist (Hist1d): Input histogram, assumed to be normalized.
49+
new_edges (array-like): New bin edges.
5450
5551
Returns:
56-
--------
57-
Hist1d
58-
New histogram with desired binning, properly normalized
52+
Hist1d: New histogram with the desired binning, properly normalized.
5953
6054
"""
6155
# First convert histogram values to density
@@ -156,11 +150,9 @@ def _check_histogram(self, h: Hist1d):
156150
histogram_max = np.max(h.bin_edges)
157151
histogram_min = np.min(h.bin_edges)
158152
if self.min_e > histogram_max or self.max_e < histogram_min:
159-
raise ValueError(
160-
f"The histogram edge ({histogram_min},{histogram_max}) \
153+
raise ValueError(f"The histogram edge ({histogram_min},{histogram_max}) \
161154
does not overlap with the analysis space ({self.min_e},{self.max_e}) \
162-
remove this background please:)"
163-
)
155+
remove this background please:)")
164156

165157
def _get_transformations(self):
166158
"""Create and return all transformations to be applied."""
@@ -348,7 +340,7 @@ def _normalize_histogram(self, h: Hist1d):
348340
def build_histogram(self):
349341
"""Build the histogram of the source.
350342
351-
It's always called during the initialization of the source. So the attributes are set here.
343+
Always called during source initialization, so all attributes are set here.
352344
353345
"""
354346
# print("Building histogram")
@@ -488,8 +480,12 @@ def _load_true_histogram(self):
488480
return h
489481

490482
def _normalize_histogram(self, h: Hist1d):
491-
"""For mono-energetic source, fraction_in_range is simply 1 or 0 depending on whether the
492-
peak energy is within ROI."""
483+
"""Normalize the histogram for a mono-energetic source.
484+
485+
The fraction_in_range is set to 1 or 0 depending on whether the peak energy is within the
486+
ROI.
487+
488+
"""
493489
# Check if peak energy is in ROI
494490
if self.min_e <= self.mu <= self.max_e:
495491
self.fraction_in_range = 1.0

alea/ces_transformation.py

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,6 @@ def smearing_mono_gaussian(
4646
ValueError: If bins has less than 2 elements.
4747
4848
"""
49-
5049
if bins is None:
5150
bins = hist.bin_edges
5251
bin_centers = hist.bin_centers
@@ -155,18 +154,14 @@ def biasing_hist_arctan(hist, A: float, k: float, B: float):
155154
- bin_centers represent measured energy (E')
156155
- histogram is interpolated from corrected f(E)
157156
158-
Parameters
159-
----------
160-
hist : Hist1d
161-
Original histogram in true energy domain E
162-
A, k, B : float
163-
Bias function parameters:
164-
(E' - E) / E = A * arctan(kE) + B
165-
166-
Returns
167-
-------
168-
Hist1d
169-
New histogram with interpolated and corrected values, x-axis is E'
157+
Args:
158+
hist (Hist1d): Original histogram in true energy domain E.
159+
A (float): Bias function parameter A, in (E' - E) / E = A * arctan(kE) + B.
160+
k (float): Bias function parameter k.
161+
B (float): Bias function parameter B.
162+
163+
Returns:
164+
Hist1d: New histogram with interpolated and corrected values, x-axis is E'.
170165
171166
"""
172167
assert isinstance(hist, Hist1d), "Only Hist1d object is supported"

alea/examples/gaussian_model.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,10 @@
77

88

99
class GaussianModel(StatisticalModel):
10-
"""A model of a gaussian measurement, where the model has parameters mu and sigma. For
11-
illustration, we show how required nominal parameters can be added to the init sigma is fixed in
12-
this example.
10+
"""Gaussian measurement model with parameters mu and sigma.
11+
12+
Illustrates how required nominal parameters can be added to the initializer;
13+
sigma is fixed in this example.
1314
1415
Args:
1516
parameter_definition (dict or list, optional (default=None)):

alea/model.py

Lines changed: 34 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,13 @@
3030

3131

3232
class StatisticalModel:
33-
"""Class that defines a statistical model.
33+
"""Base class for defining a statistical model with a likelihood and data generation method.
3434
35-
- The statisical model contains two parts that you must define yourself:
35+
- The statistical model contains two parts that you must define yourself:
3636
- a likelihood function
3737
ll(self, parameter_1, parameter_2... parameter_n):
3838
A function of a set of named parameters which
39-
return a float expressing the loglikelihood for observed data given these parameters.
39+
return a float expressing the log-likelihood for observed data given these parameters.
4040
- a data generation function
4141
generate_data(self, parameter_1, parameter_2... parameter_n):
4242
A function of the same set of named parameters return a full data set.
@@ -154,7 +154,7 @@ def _check_ll_and_generate_data_signature(self):
154154
raise AssertionError("ll and generate_data must have the same signature (parameters)")
155155

156156
def _ll(self, **kwargs) -> float:
157-
"""Likelihood function, return the loglikelihood for the given parameters."""
157+
"""Likelihood function, return the log-likelihood for the given parameters."""
158158
raise NotImplementedError(
159159
"You must write a likelihood function (_ll) for your statistical model"
160160
" or use a subclass where it is written for you"
@@ -169,9 +169,10 @@ def _generate_data(self, **kwargs):
169169

170170
@_needs_data
171171
def ll(self, **kwargs) -> float:
172-
"""Likelihod function, returns the loglikelihood for the given parameters. The parameters
173-
are passed as keyword arguments, positional arguments are not possible. If a parameter is
174-
not given, the default value is used.
172+
"""Return the log-likelihood for the given parameters.
173+
174+
Parameters are passed as keyword arguments; positional arguments are not supported.
175+
If a parameter is not given, the default value is used.
175176
176177
Keyword Args:
177178
kwargs: keyword arguments for the parameters
@@ -184,9 +185,10 @@ def ll(self, **kwargs) -> float:
184185
return self._ll(**parameters)
185186

186187
def generate_data(self, **kwargs) -> Union[dict, list]:
187-
"""Generate data for the given parameters. The parameters are passed as keyword arguments,
188-
positional arguments are not possible. If a parameter is not given, the default value is
189-
used.
188+
"""Generate data for the given parameters.
189+
190+
Parameters are passed as keyword arguments; positional arguments are not supported.
191+
If a parameter is not given, the default value is used.
190192
191193
Raises:
192194
ValueError: If the parameters are not within the fit limits
@@ -205,10 +207,10 @@ def generate_data(self, **kwargs) -> Union[dict, list]:
205207

206208
@property
207209
def data(self):
208-
"""Simple getter for a data-set-- mainly here so it can be over-ridden for special needs.
210+
"""Return the dataset, overridable for special needs.
209211
210-
Data-sets are expected to be in the form of a list of one or more structured arrays,
211-
representing the data-sets of one or more likelihood terms.
212+
Datasets are expected to be in the form of a list of one or more structured arrays,
213+
representing the datasets of one or more likelihood terms.
212214
213215
"""
214216
if self._data is None:
@@ -228,10 +230,9 @@ def store_data(
228230
data_name_list: Optional[List[str]] = None,
229231
metadata: Optional[dict] = None,
230232
):
231-
"""
232-
Store a list of datasets.
233-
(each on the form of a list of one or more structured arrays or dicts)
234-
Using inference_interface, but included here to allow over-writing.
233+
"""Store a list of datasets to a file using inference_interface.
234+
235+
Each dataset is in the form of a list of one or more structured arrays or dicts.
235236
The structure would be: ``[[datasets1], [datasets2], ..., [datasetsn]]``,
236237
where each of datasets is a list of structured arrays.
237238
If you specify, it is set, if not it will read from ``self.get_likelihood_term_names``.
@@ -244,6 +245,7 @@ def store_data(
244245
If None, it will be read from self.get_likelihood_term_names
245246
metadata (dict, optional (default=None)): metadata to store with the data.
246247
If None, no metadata is stored.
248+
247249
"""
248250
if all([isinstance(d, dict) for d in data_list]) or all(
249251
[isinstance(d, ReadOnlyDict) for d in data_list]
@@ -337,10 +339,11 @@ def cost(args):
337339
def fit(
338340
self, verbose: Optional[bool] = False, fit_strategy: Optional[dict] = None, **kwargs
339341
) -> Tuple[dict, float]:
340-
"""Fit the model to the data by maximizing the likelihood. Return a dict containing best-fit
341-
values of each parameter, and the value of the likelihood evaluated there. While the
342-
optimization is a minimization, the likelihood returned is the __maximum__ of the
343-
likelihood.
342+
"""Fit the model to the data by maximizing the likelihood.
343+
344+
Returns a dict of best-fit parameter values and the maximum log-likelihood value.
345+
While the optimization is a minimization internally, the likelihood returned
346+
is the maximum.
344347
345348
Args:
346349
verbose (bool): if True, print the Minuit object
@@ -590,10 +593,13 @@ def confidence_interval(
590593
asymptotic_dof: Optional[int] = None,
591594
fit_strategy: Optional[dict] = None,
592595
) -> Tuple[float, float]:
593-
"""Uses self.fit to compute confidence intervals for a certain named parameter. If the
594-
parameter is a rate parameter, and the model has expectation values implemented, the bounds
595-
will be interpreted as bounds on the expectation value, so that the range in the fit is
596-
parameter_interval_bounds/mus. Otherwise the bound is taken as-is.
596+
"""Compute confidence intervals for the parameter of interest (POI).
597+
598+
Finds the intersection between the profile log-likelihood curve and the
599+
critical value curve to determine the confidence interval edges.
600+
If the parameter is a rate parameter and the model has expectation values implemented,
601+
the bounds will be interpreted as bounds on the expectation value, so that the range
602+
in the fit is parameter_interval_bounds/mus. Otherwise the bound is taken as-is.
597603
598604
Args:
599605
poi_name (str): name of the parameter of interest
@@ -720,8 +726,9 @@ def get_model_from_name(statistical_model: str):
720726

721727

722728
class MinuitWrap:
723-
"""Wrapper for functions to be called by Minuit. Initialized with a function f and a Parameters
724-
instance.
729+
"""Wrapper for functions to be called by Minuit.
730+
731+
Initialized with a function f and a Parameters instance.
725732
726733
Attributes:
727734
func: function wrapped

0 commit comments

Comments
 (0)