Skip to content

Commit

Permalink
Refactor: ruff format and linting + fix problems
Browse files Browse the repository at this point in the history
  • Loading branch information
op3 committed Jan 17, 2024
1 parent fc725fe commit 5633d24
Show file tree
Hide file tree
Showing 92 changed files with 614 additions and 691 deletions.
8 changes: 4 additions & 4 deletions .github/workflows/check-code-formatting.yml
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ jobs:
- uses: actions/setup-python@v2
with:
python-version: '3.x'
- name: Install black
run: pip install black && black --version
- name: Run black
run: black --check .
- name: Install ruff
run: pip install ruff && ruff --version
- name: Run ruff
run: ruff check
14 changes: 8 additions & 6 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
repos:
- repo: https://github.com/asottile/pyupgrade
rev: v3.3.1
rev: v3.15.0
hooks:
- id: pyupgrade
args: ["--py37-plus"]
args: ["--py38-plus"]

- repo: https://github.com/psf/black
rev: 23.1.0
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.13
hooks:
- id: black
- id: ruff
args: ["--fix"]
- id: ruff-format

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
rev: v4.5.0
hooks:
- id: check-added-large-files
- id: check-case-conflict
Expand Down
63 changes: 31 additions & 32 deletions hdtv/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,10 @@
This is the main HDTV application.
"""

import sys
import argparse
import os
import glob
import sys
from pathlib import Path
import argparse

if __name__ == "__main__":
project_dir = Path(__file__).absolute().parents[1].resolve()
Expand All @@ -52,32 +51,32 @@ def check_root_version():
exit(1)


def get_path(env: str, default: str) -> Path:
"""
Get path used for user config and data
"""
if user_path := os.environ.get("HDTV_USER_PATH"):
return Path(user_path)

legacy_path = Path.home() / ".hdtv"
if legacy_path.exists():
return legacy_path

if xdg_path := os.environ.get(env):
return Path(xdg_path) / "hdtv"

return Path.home() / default / "hdtv"


class App:
def __init__(self):
# Reset command line arguments so that ROOT does not stumble about them
hdtv_args = sys.argv[1:]
sys.argv = [sys.argv[0]]

# Get config and data directory
self.legacypath = Path.home() / ".hdtv"
self.configpath = Path(
os.getenv(
"HDTV_USER_PATH",
self.legacypath
if self.legacypath.is_dir()
else Path(os.getenv("XDG_CONFIG_HOME", Path.home() / ".config"))
/ "hdtv",
)
)
self.datapath = Path(
os.getenv(
"HDTV_USER_PATH",
self.legacypath
if self.legacypath.is_dir()
else Path(os.getenv("XDG_DATA_HOME", Path.home() / ".local/share"))
/ "hdtv",
)
)
self.configpath = get_path("XDG_CONFIG_HOME", ".config")
self.datapath = get_path("XDG_DATA_HOME", ".local/share")

for path in [self.datapath, self.configpath]:
try:
Expand Down Expand Up @@ -135,27 +134,27 @@ def __init__(self):
__main__.spectra = spectra

# Import core plugins
import hdtv.plugins.textInterface
import hdtv.plugins.ls
import hdtv.plugins.run
import hdtv.plugins.specInterface
import hdtv.plugins.fitInterface
import hdtv.plugins.calInterface
import hdtv.plugins.matInterface
import hdtv.plugins.rootInterface
import hdtv.plugins.config
import hdtv.plugins.dblookup
import hdtv.plugins.fitInterface
import hdtv.plugins.fitlist
import hdtv.plugins.fittex
import hdtv.plugins.fitmap
import hdtv.plugins.dblookup
import hdtv.plugins.fittex
import hdtv.plugins.ls
import hdtv.plugins.matInterface
import hdtv.plugins.peakfinder
import hdtv.plugins.printing
import hdtv.plugins.rootInterface
import hdtv.plugins.run
import hdtv.plugins.specInterface
import hdtv.plugins.textInterface

hdtv.ui.msg("HDTV - Nuclear Spectrum Analysis Tool")

# Execute startup.py for user configuration in python
try:
import startup
import startup # noqa: F401
except ImportError:
hdtv.ui.debug("No startup.py file")

Expand Down
4 changes: 2 additions & 2 deletions hdtv/backgroundmodels/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from .exponential import BackgroundModelExponential
from .polynomial import BackgroundModelPolynomial
from .interpolation import BackgroundModelInterpolation
from .polynomial import BackgroundModelPolynomial

# dictionary of available background models
BackgroundModels = dict()
BackgroundModels = {}
BackgroundModels["exponential"] = BackgroundModelExponential
BackgroundModels["polynomial"] = BackgroundModelPolynomial
BackgroundModels["interpolation"] = BackgroundModelInterpolation
8 changes: 2 additions & 6 deletions hdtv/backgroundmodels/background.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,6 @@
class to handle fitter setup and data transfer to the Python side
"""

import ROOT
import hdtv.rootext.display


# Base class for all background models
class BackgroundModel:
Expand All @@ -36,7 +33,7 @@ class BackgroundModel:
"""

def __init__(self):
self.fGlobalParams = dict()
self.fGlobalParams = {}
self.requiredBgRegions = 1

def ResetGlobalParams(self):
Expand Down Expand Up @@ -136,8 +133,7 @@ def SetParameter(self, parname, status):

if parname not in list(self.fValidParStatus.keys()):
raise ValueError(
"Invalid parameter name %s for background model %s"
% (parname, self.name)
f"Invalid parameter name {parname} for background model {self.name}"
)

self.fParStatus[parname] = self.ParseParamStatus(parname, status)
3 changes: 2 additions & 1 deletion hdtv/backgroundmodels/exponential.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA

import ROOT

from .background import BackgroundModel


Expand Down Expand Up @@ -55,7 +56,7 @@ def GetFitter(self, integrate, likelihood, nparams=None, nbg=None):
else:
msg = (
"Status specifier %s of background fitter is invalid."
% fParStatus["nparams"]
% self.fParStatus["nparams"]
)
raise ValueError(msg)

Expand Down
3 changes: 2 additions & 1 deletion hdtv/backgroundmodels/interpolation.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA

import ROOT

from .background import BackgroundModel


Expand Down Expand Up @@ -58,7 +59,7 @@ def GetFitter(self, integrate, likelihood, nparams=None, nbg=None):
else:
msg = (
"Status specifier %s of background fitter is invalid."
% fParStatus["nparams"]
% self.fParStatus["nparams"]
)
raise ValueError(msg)

Expand Down
3 changes: 2 additions & 1 deletion hdtv/backgroundmodels/polynomial.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA

import ROOT

from .background import BackgroundModel


Expand Down Expand Up @@ -69,7 +70,7 @@ def GetFitter(self, integrate, likelihood, nparams=None, nbg=None):
else:
msg = (
"Status specifier %s of background fitter is invalid."
% fParStatus["nparams"]
% self.fParStatus["nparams"]
)
raise ValueError(msg)

Expand Down
19 changes: 9 additions & 10 deletions hdtv/cal.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,16 @@
# along with HDTV; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA

import fnmatch
import re
from array import array
from html import escape
import re
import fnmatch

import ROOT
import hdtv.util
import hdtv.cal
import hdtv.options

import hdtv.options
import hdtv.rootext.calibration
import hdtv.util


class PositionCalibrationDict(dict):
Expand Down Expand Up @@ -236,7 +235,7 @@ def FitCal(self, degree, ignore_errors=False):

# Save the fit result
self.calib = MakeCalibration(
[self.__TF1.GetParameter(i) for i in range(0, degree + 1)]
[self.__TF1.GetParameter(i) for i in range(degree + 1)]
)
self.chi2 = self.__TF1.GetChisquare()

Expand All @@ -262,10 +261,10 @@ def ResultTable(self):

header = ["Channel", "E_given", "E_fit", "Residual"]
keys = "channel", "e_given", "e_fit", "residual"
tabledata = list()
tabledata = []

for ch, e_given in self.pairs:
tableline = dict()
tableline = {}
e_fit = self.calib.Ch2E(ch.nominal_value)
residual = e_given - e_fit

Expand Down Expand Up @@ -300,7 +299,7 @@ def DrawCalFit(self):

try:
graph.SetPoint(i, ch.nominal_value, e.nominal_value)
except BaseException:
except Exception:
graph.SetPoint(i, ch.nominal_value, e)
graph.SetPointError(i, ch.std_dev, 0)
i += 1
Expand Down Expand Up @@ -344,7 +343,7 @@ def DrawCalResidual(self):
try:
# energie may be ufloat
e = e.nominal_value
except BaseException:
except Exception:
pass

graph.SetPoint(i, ch.nominal_value, e - self.calib.Ch2E(ch.nominal_value))
Expand Down
Loading

0 comments on commit 5633d24

Please sign in to comment.