Skip to content

Commit

Permalink
update pre-commit and fix some ruff errors
Browse files Browse the repository at this point in the history
  • Loading branch information
kjmeagher committed Oct 4, 2023
1 parent 6d76f04 commit 1c98b4d
Show file tree
Hide file tree
Showing 13 changed files with 114 additions and 89 deletions.
16 changes: 16 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# SPDX-FileCopyrightText: © 2023 The ehist authors
#
# SPDX-License-Identifier: BSD-2-Clause

root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.py]
indent_size = 4
7 changes: 5 additions & 2 deletions .github/workflows/unit_tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,11 @@ jobs:
strategy:
fail-fast: false
matrix:
python-version: ["3.7", "3.8", "3.9", "3.10", "3.11"]
os: [ubuntu-20.04, ubuntu-22.04, macos-11, macos-12]
python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"]
os: [ubuntu-22.04]
include:
- python-version: 3.12
os: macos-12
steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
Expand Down
19 changes: 12 additions & 7 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,36 +7,41 @@ ci:
autoupdate_schedule: quarterly
repos:
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v3.0.0-alpha.6
rev: v3.0.3
hooks:
- id: prettier
- repo: https://github.com/psf/black
rev: 23.3.0
rev: 23.9.1
hooks:
- id: black
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.261
rev: v0.0.292
hooks:
- id: ruff
args: [--fix]
- repo: https://github.com/pycqa/pylint
rev: v3.0.0a6
rev: v3.0.0
hooks:
- id: pylint
files: ehist
additional_dependencies: [numpy, matplotlib, scipy]
- repo: https://github.com/fsfe/reuse-tool
rev: v1.1.2
rev: v2.1.0
hooks:
- id: reuse
- repo: https://github.com/codespell-project/codespell
rev: v2.2.4
rev: v2.2.6
hooks:
- id: codespell
additional_dependencies:
- tomli
- repo: https://github.com/Lucas-C/pre-commit-hooks
rev: v1.5.1
rev: v1.5.4
hooks:
- id: forbid-crlf
- id: forbid-tabs
- repo: https://github.com/editorconfig-checker/editorconfig-checker.python
rev: "2.7.2"
hooks:
- id: editorconfig-checker
alias: ec
6 changes: 3 additions & 3 deletions COPYING
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
Expand Down
2 changes: 1 addition & 1 deletion LICENSES/BSD-2-Clause.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Copyright (c) <year> <owner>
Copyright (c) <year> <owner>

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Expand Down
4 changes: 2 additions & 2 deletions ehist/axis.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ def auto_axis(points, bins=None, span=None, t=None):


def print_axis(axis):
print(
return (
f"{axis.__class__.__name__}\n\tb: {axis.bins}\n\tw: {axis.widths}\n\te: {axis.edges}"
f"\n\tc: {axis.pcenters}\n\te: {axis.pedges}",
f"\n\tc: {axis.pcenters}\n\te: {axis.pedges}"
)
64 changes: 32 additions & 32 deletions ehist/bayesian_blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@

import numpy as np

# TODO: implement other fitness functions from appendix B of Scargle 2012
# TODO: implement other fitness functions from appendix B of Scargle 2012 # noqa: FIX002, TD002, TD003

# __all__ = ['FitnessFunc', 'Events', 'RegularEvents', 'PointMeasures',
# 'bayesian_blocks']
Expand All @@ -71,19 +71,19 @@ def bayesian_blocks(t, x=None, sigma=None, fitness="events", **kwargs):
If a string, the following options are supported:
- 'events' : binned or unbinned event data. Arguments are ``gamma``,
which gives the slope of the prior on the number of bins, or
``ncp_prior``, which is :math:`-\ln({\tt gamma})`.
which gives the slope of the prior on the number of bins, or
``ncp_prior``, which is :math:`-\ln({\tt gamma})`.
- 'regular_events' : non-overlapping events measured at multiples of a
fundamental tick rate, ``dt``, which must be specified as an
additional argument. Extra arguments are ``p0``, which gives the
false alarm probability to compute the prior, or ``gamma``, which
gives the slope of the prior on the number of bins, or ``ncp_prior``,
which is :math:`-\ln({\tt gamma})`.
fundamental tick rate, ``dt``, which must be specified as an
additional argument. Extra arguments are ``p0``, which gives the
false alarm probability to compute the prior, or ``gamma``, which
gives the slope of the prior on the number of bins, or ``ncp_prior``,
which is :math:`-\ln({\tt gamma})`.
- 'measures' : fitness for a measured sequence with Gaussian errors.
Extra arguments are ``p0``, which gives the false alarm probability
to compute the prior, or ``gamma``, which gives the slope of the
prior on the number of bins, or ``ncp_prior``, which is
:math:`-\ln({\tt gamma})`.
Extra arguments are ``p0``, which gives the false alarm probability
to compute the prior, or ``gamma``, which gives the slope of the
prior on the number of bins, or ``ncp_prior``, which is
:math:`-\ln({\tt gamma})`.
In all three cases, if more than one of ``p0``, ``gamma``, and
``ncp_prior`` is chosen, ``ncp_prior`` takes precedence over ``gamma``
Expand Down Expand Up @@ -137,7 +137,7 @@ def bayesian_blocks(t, x=None, sigma=None, fitness="events", **kwargs):
References
----------
.. [1] Scargle, J et al. (2012)
https://ui.adsabs.harvard.edu/abs/2013ApJ...764..167S
https://ui.adsabs.harvard.edu/abs/2013ApJ...764..167S
See Also
--------
Expand Down Expand Up @@ -166,35 +166,35 @@ class FitnessFunc:
Derived classes should overload the following method:
``fitness(self, **kwargs)``:
Compute the fitness given a set of named arguments.
Arguments accepted by fitness must be among ``[T_k, N_k, a_k, b_k, c_k]``
(See [1]_ for details on the meaning of these parameters).
Compute the fitness given a set of named arguments.
Arguments accepted by fitness must be among ``[T_k, N_k, a_k, b_k, c_k]``
(See [1]_ for details on the meaning of these parameters).
Additionally, other methods may be overloaded as well:
``__init__(self, **kwargs)``:
Initialize the fitness function with any parameters beyond the normal
``p0`` and ``gamma``.
Initialize the fitness function with any parameters beyond the normal
``p0`` and ``gamma``.
``validate_input(self, t, x, sigma)``:
Enable specific checks of the input data (``t``, ``x``, ``sigma``)
to be performed prior to the fit.
Enable specific checks of the input data (``t``, ``x``, ``sigma``)
to be performed prior to the fit.
``compute_ncp_prior(self, N)``: If ``ncp_prior`` is not defined explicitly,
this function is called in order to define it before fitting. This may be
calculated from ``gamma``, ``p0``, or whatever method you choose.
this function is called in order to define it before fitting. This may be
calculated from ``gamma``, ``p0``, or whatever method you choose.
``p0_prior(self, N)``:
Specify the form of the prior given the false-alarm probability ``p0``
(See [1]_ for details).
Specify the form of the prior given the false-alarm probability ``p0``
(See [1]_ for details).
For examples of implemented fitness functions, see :class:`Events`,
:class:`RegularEvents`, and :class:`PointMeasures`.
References
----------
.. [1] Scargle, J et al. (2012)
https://ui.adsabs.harvard.edu/abs/2013ApJ...764..167S
https://ui.adsabs.harvard.edu/abs/2013ApJ...764..167S
"""

def __init__(self, p0=0.05, gamma=None, ncp_prior=None) -> None:
Expand Down Expand Up @@ -241,7 +241,7 @@ def validate_input(self, t, x=None, sigma=None):

# if x is specified, then we need to simultaneously sort t and x
else:
# TODO: allow broadcasted x?
# TODO: allow broadcasted x? # noqa: FIX002, TD002, TD003
x = np.asarray(x, dtype=float)

if x.shape not in [(), (1,), (t.size,)]:
Expand Down Expand Up @@ -533,7 +533,7 @@ def scott_bin_width(data, return_bins=False):
References
----------
.. [1] Scott, David W. (1979). "On optimal and data-based histograms".
Biometricka 66 (3): 605-610
Biometricka 66 (3): 605-610
See Also
--------
knuth_bin_width
Expand Down Expand Up @@ -589,8 +589,8 @@ def freedman_bin_width(data, return_bins=False):
References
----------
.. [1] D. Freedman & P. Diaconis (1981)
"On the histogram as a density estimator: L2 theory".
Probability Theory and Related Fields 57 (4): 453-476
"On the histogram as a density estimator: L2 theory".
Probability Theory and Related Fields 57 (4): 453-476
See Also
--------
knuth_bin_width
Expand Down Expand Up @@ -618,9 +618,9 @@ def freedman_bin_width(data, return_bins=False):
if "Maximum allowed size exceeded" in str(e):
raise ValueError(
"The inter-quartile range of the data is too small: "
"failed to construct histogram with {} bins. "
f"failed to construct histogram with {Nbins + 1} bins. "
"Please use another bin method, such as "
'bins="scott"'.format(Nbins + 1),
'bins="scott"',
)
else: # Something else # pragma: no cover
raise
Expand Down Expand Up @@ -664,7 +664,7 @@ def knuth_bin_width(data, return_bins=False, quiet=True):
References
----------
.. [1] Knuth, K.H. "Optimal Data-Based Binning for Histograms".
arXiv:0605197, 2006
arXiv:0605197, 2006
See Also
--------
freedman_bin_width
Expand Down
6 changes: 2 additions & 4 deletions ehist/hist1d.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def __init__(
self,
points,
bins=None,
range=None,
range=None, # noqa: A002
norm=None,
logx=False,
t=None,
Expand Down Expand Up @@ -195,8 +195,6 @@ def vtext(self, logy=False, width=80):
def htext(self, show_area=False, show_count=True, logy=False, width=80):
y, min_y, max_y = self._get_yaxis_text(logy=logy)

print("YYY", y)

lowedges = self.x.bins.copy()[:-1]
highedges = self.x.bins.copy()[1:]
if type(self.x) in [LogIntAxis, IntAxis]:
Expand Down Expand Up @@ -382,7 +380,7 @@ def function_fit(self, func, p0, **kwargs):
def __str__(self) -> str:
return (
f"<{self.__class__.__name__} {self.x.__class__.__name__} "
f"bins={len(self.x.pcenters),} "
f"bins={len(self.x.pcenters)} "
f"range=[{self.x.edges[0]:0.2f},{self.x.edges[-1]:0.2f}]"
f"entries={self.entries}>"
)
14 changes: 11 additions & 3 deletions ehist/hist2d.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,15 @@


class Hist2D:
def __init__(self, x, y, bins=(60, 50), range=None, log=(False, False), weights=1.0) -> None:
def __init__(
self,
x,
y,
bins=(60, 50),
range=None, # noqa: A002
log=(False, False),
weights=1.0,
) -> None:
assert len(x) == len(
y,
), f"x and y must have the same dimensions: len(x) = {len(x)}, len(y) = {len(y)}"
Expand Down Expand Up @@ -46,7 +54,7 @@ def __init__(self, x, y, bins=(60, 50), range=None, log=(False, False), weights=
rangey = np.log10(rangey)

if range is not None:
range = (rangex, rangey)
range = (rangex, rangey) # noqa: A001

nancut = np.array(np.isfinite(x) & np.isfinite(y), dtype=bool)
self.entries = nancut.sum()
Expand Down Expand Up @@ -99,7 +107,7 @@ def plot_text(self):

def __str__(self) -> str:
return (
f"<{self.__class__.__name__,} "
f"<{self.__class__.__name__} "
f"bins=({len(self.xedges) - 1},{len(self.yedges) - 1})"
f"range=[[{self.xedges[0]:0.2f},{self.xedges[-1]:0.2f}],"
f"[{self.yedges[0]:0.2f},{self.yedges[-1]:0.2f}]]"
Expand Down
1 change: 0 additions & 1 deletion ehist/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,6 @@ def __init__(self, width=80, height=25) -> None:
self.height = height

def get_plot(self, y, min_y, max_y):
print(min_y, max_y)
rep = max(1, self.width // len(y))
bars = []
for yy in y:
Expand Down
26 changes: 13 additions & 13 deletions examples/plot_ehist.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,49 +31,49 @@ def main(d):
plt.show()


def Triangle():
def triangle():
x = stats.triang.ppf(np.linspace(0, 1, 1000, 1), 1)
return {"points": x, "bins": 120}, {"s": "steps,err"}


def PowerLaw():
def power_law():
e = np.geomspace(1e3, 1e6, 1000)
return {"points": e, "bins": 30, "t": "log"}, {"s": "err,marker,steps", "logy": True}


def Zenith():
def zenith():
cz = np.arccos(np.linspace(-1, 1, 1000))
return {"points": cz, "bins": 20, "t": np.cos}, {"s": "err,marker,steps"}


def Int():
X = np.linspace(0, 21, 106)[:-1].astype(int)
return {"points": X, "bins": 20, "t": int}, {"s": "err,marker,steps"}
def integer():
x = np.linspace(0, 21, 106)[:-1].astype(int)
return {"points": x, "bins": 20, "t": int}, {"s": "err,marker,steps"}


def LogInt():
N = 1001
x = [int(N / i) * [i] for i in range(1, N)]
def log_int():
n = 1001
x = [int(n / i) * [i] for i in range(1, n)]
p = [val for sublist in x for val in sublist]
return {"points": p, "t": "logint", "bins": 20}, {"s": "steps,marker,err", "logy": True}


def Freedman():
def freedman():
x = stats.norm.ppf(np.linspace(0, 1, 1002)[1:-1])
return {"points": x, "bins": "freedman"}, {}


def Scott():
def scott():
x = stats.norm.ppf(np.linspace(0, 1, 1002)[1:-1])
return {"points": x, "bins": "scott"}, {}


def Knuth():
def knuth():
x = stats.norm.ppf(np.linspace(0, 1, 1002)[1:-1])
return {"points": x, "bins": "knuth"}, {}


def Blocks():
def blocks():
x = stats.norm.ppf(np.linspace(0, 1, 1002)[1:-1])
return {"points": x, "bins": "blocks"}, {}

Expand Down
Loading

0 comments on commit 1c98b4d

Please sign in to comment.