Skip to content

Commit eb86038

Browse files
committed
Run ruff
1 parent a34f4d9 commit eb86038

File tree

7 files changed

+102
-117
lines changed

7 files changed

+102
-117
lines changed

mrestimator/__init__.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,15 @@
11
from importlib import metadata as importlib_metadata
22

3-
4-
53
from . import utility as ut
4+
65
ut.initialize()
76
log = ut.log
87

9-
from .utility import enable_progressbar, disable_progressbar
108
from .coefficients import CoefficientResult, coefficients
119
from .fit import *
1210
from .input_output import *
1311
from .simulate import *
12+
from .utility import disable_progressbar, enable_progressbar
1413
from .wrapper import *
1514

1615

mrestimator/coefficients.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
from collections import namedtuple
21
import logging
2+
from collections import namedtuple
33

44
import numpy as np
55

@@ -9,9 +9,11 @@
99
try:
1010
from tqdm import tqdm
1111
except ImportError:
12+
1213
def tqdm(*args, **kwargs):
1314
return args[0] if args else iter([])
1415

16+
1517
# set precision of temporary results for numpy and numba
1618
# ftype = np.longdouble # very slow, maybe float64 is enough
1719
ftype = np.float64
@@ -419,7 +421,7 @@ def __new__(
419421
bootstrapcrs = np.array([])
420422
if trialcrs is None:
421423
trialcrs = np.array([])
422-
424+
423425
# given attr check
424426
coefficients = np.asarray(coefficients)
425427
steps = np.asarray(steps)
@@ -687,9 +689,7 @@ def coefficients(
687689
+ "Steps greater than half the time series length cause problems. "
688690
+ "Proceeding nonetheless..."
689691
)
690-
log.debug(
691-
f"Using provided custom steps between {steps[0]} and {steps[-1]}"
692-
)
692+
log.debug(f"Using provided custom steps between {steps[0]} and {steps[-1]}")
693693

694694
# ------------------------------------------------------------------ #
695695
# Continue with trusted arguments
@@ -704,9 +704,7 @@ def coefficients(
704704
method,
705705
numtrials,
706706
numels,
707-
f" 'knownmean' provided: {knownmean}"
708-
if knownmean is not None
709-
else "",
707+
f" 'knownmean' provided: {knownmean}" if knownmean is not None else "",
710708
)
711709
)
712710

mrestimator/fit.py

Lines changed: 62 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ def f_two_timescales(k, tau1, A1, tau2, A2):
3434
# keep in mind to pick the tau with the bigger amplitude. see `tau_from_popt()`
3535
return np.abs(A1) * np.exp(-k / tau1) + np.abs(A2) * np.exp(-k / tau2)
3636

37+
3738
def f_complex(k, tau, A, O, tauosc, B, gamma, nu, taugs, C):
3839
(
3940
""":math:`|A| e^{-k/\\tau} + B e^{-(k/\\tau_{osc})^\\gamma} """
@@ -50,18 +51,18 @@ def f_complex(k, tau, A, O, tauosc, B, gamma, nu, taugs, C):
5051

5152
def tau_from_popt(fitfunc, popt):
5253
"""
53-
Get the 'selected' tau from the fit parameters. This is necessary in particular
54-
for the two-timescale fit, where the chosen tau is not always the
55-
first element in popt.
56-
57-
Parameters
58-
----------
59-
fitfunc : callable, The fit function
60-
popt : ~numpy.ndarray, The fit parameters
61-
62-
Returns
63-
-------
64-
tau : float
54+
Get the 'selected' tau from the fit parameters. This is necessary in particular
55+
for the two-timescale fit, where the chosen tau is not always the
56+
first element in popt.
57+
58+
Parameters
59+
----------
60+
fitfunc : callable, The fit function
61+
popt : ~numpy.ndarray, The fit parameters
62+
63+
Returns
64+
-------
65+
tau : float
6566
"""
6667

6768
if fitfunc == f_linear:
@@ -118,16 +119,19 @@ def default_fitpars(fitfunc):
118119
elif fitfunc == f_exponential_offset:
119120
return np.array([(20, 1, 0), (200, 1, 0), (-20, 1, 0), (-50, 1, 0), (-1, 1, 0)])
120121
elif fitfunc == f_two_timescales:
121-
res = np.array([
122-
# tau1 A1 tau2 A2
123-
(0.1, 0.01, 10, 0.01 ),
124-
(0.1, 0.1 , 10, 0.01 ),
125-
(0.5, 0.01, 10, 0.001),
126-
(0.5, 0.1 , 10, 0.01 ),
127-
(0.1, 0.01, 10, 0 ),
128-
(0.1, 0.1 , 10, 0 ),
129-
(0.5, 0.01, 10, 0 ),
130-
(0.5, 0.1 , 10, 0 )])
122+
res = np.array(
123+
[
124+
# tau1 A1 tau2 A2
125+
(0.1, 0.01, 10, 0.01),
126+
(0.1, 0.1, 10, 0.01),
127+
(0.5, 0.01, 10, 0.001),
128+
(0.5, 0.1, 10, 0.01),
129+
(0.1, 0.01, 10, 0),
130+
(0.1, 0.1, 10, 0),
131+
(0.5, 0.01, 10, 0),
132+
(0.5, 0.1, 10, 0),
133+
]
134+
)
131135
return res
132136
elif fitfunc == f_complex:
133137
res = np.array(
@@ -233,23 +237,37 @@ def fitpars_check(pars, fitfunc):
233237

234238

235239
def fitfunc_check(f):
236-
if f is f_linear or \
237-
str(f).lower() in ['f_linear', 'linear', 'lin', 'l']:
238-
return f_linear
239-
elif f is f_exponential or \
240-
str(f).lower() in ['f_exponential', 'exponential', 'exp', 'e']:
241-
return f_exponential
242-
elif f is f_exponential_offset or \
243-
str(f).lower() in ['f_exponential_offset', 'exponentialoffset',
244-
'exponential_offset','offset', 'exp_off', 'exp_offset', 'exp_offs', 'eo']:
245-
return f_exponential_offset
246-
elif f is f_two_timescales or \
247-
str(f).lower() in ['f_two_timescales', 'two_ts', 'two_timescales', 'f_two_ts', 'double_exp']:
248-
return f_two_timescales
249-
elif f is f_complex or \
250-
str(f).lower() in ['f_complex', 'complex', 'cplx', 'c']:
251-
return f_complex
252-
elif callable(f) or hasattr(f, '__call__') :
240+
if f is f_linear or str(f).lower() in ["f_linear", "linear", "lin", "l"]:
241+
return f_linear
242+
elif f is f_exponential or str(f).lower() in [
243+
"f_exponential",
244+
"exponential",
245+
"exp",
246+
"e",
247+
]:
248+
return f_exponential
249+
elif f is f_exponential_offset or str(f).lower() in [
250+
"f_exponential_offset",
251+
"exponentialoffset",
252+
"exponential_offset",
253+
"offset",
254+
"exp_off",
255+
"exp_offset",
256+
"exp_offs",
257+
"eo",
258+
]:
259+
return f_exponential_offset
260+
elif f is f_two_timescales or str(f).lower() in [
261+
"f_two_timescales",
262+
"two_ts",
263+
"two_timescales",
264+
"f_two_ts",
265+
"double_exp",
266+
]:
267+
return f_two_timescales
268+
elif f is f_complex or str(f).lower() in ["f_complex", "complex", "cplx", "c"]:
269+
return f_complex
270+
elif callable(f) or callable(f):
253271
return f
254272
else:
255273
log.exception(f"{f} of type {type(f).__name__} is not a valid fit function.")
@@ -682,18 +700,15 @@ def fit(
682700
ic = (
683701
f"{a:<6} = {b:8.3f} in ({c:9.4f}, {d:9.4f})"
684702
for a, b, c, d in zip(
685-
ic, fitpars[0], fitbnds[0, :], fitbnds[1, :],
686-
strict=False
703+
ic, fitpars[0], fitbnds[0, :], fitbnds[1, :], strict=False
687704
)
688705
)
689706
log.debug("First parameters:\n" + "\n".join(ic))
690707
except Exception:
691708
log.debug("Exception when logging fitpars", exc_info=True)
692709

693710
if fitpars.shape[0] > 1:
694-
log.debug(
695-
f"Repeating fit with {fitpars.shape[0]} sets of initial parameters:"
696-
)
711+
log.debug(f"Repeating fit with {fitpars.shape[0]} sets of initial parameters:")
697712

698713
# ------------------------------------------------------------------ #
699714
# Fit via scipy.curve_fit
@@ -752,8 +767,7 @@ def fitloop(ftcoefficients, ftmaxfev, fitlog=True):
752767
pass
753768
else:
754769
log.warning(
755-
f"No fit converged after {maxfev} "
756-
+ "iterations. Increasing to 10000"
770+
f"No fit converged after {maxfev} " + "iterations. Increasing to 10000"
757771
)
758772
maxfev = 10000
759773
fulpopt, fulpcov, ssresmin = fitloop(
@@ -823,9 +837,7 @@ def fitloop(ftcoefficients, ftmaxfev, fitlog=True):
823837
if numboot == 0:
824838
log.debug("'numboot=0' skipping bootstrapping")
825839
else:
826-
log.info(
827-
f"Bootstrapping {numboot} replicas ({len(fitpars)} fits each)"
828-
)
840+
log.info(f"Bootstrapping {numboot} replicas ({len(fitpars)} fits each)")
829841

830842
log.debug(f"fit() seeding to {seed}")
831843
if seed is None:
@@ -869,7 +881,7 @@ def fitloop(ftcoefficients, ftmaxfev, fitlog=True):
869881
mrequantiles = np.nanpercentile(bsmre, quantiles * 100.0)
870882

871883
tau = tau_from_popt(fitfunc, fulpopt)
872-
mre = None if tau is None else np.exp(-1*dt/tau)
884+
mre = None if tau is None else np.exp(-1 * dt / tau)
873885

874886
fulres = FitResult(
875887
tau=tau,

mrestimator/input_output.py

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,8 @@
77

88
log = ut.log
99
import matplotlib
10-
import numpy as np
11-
1210
import matplotlib.pyplot as plt
11+
import numpy as np
1312

1413

1514
def input_handler(items, **kwargs):
@@ -95,9 +94,7 @@ def input_handler(items, **kwargs):
9594
for item in items.astype("U"):
9695
temp.update(glob.glob(os.path.expanduser(item)))
9796
if len(items) != len(temp):
98-
log.debug(
99-
f"{len(items) - len(temp)} duplicate files were excluded"
100-
)
97+
log.debug(f"{len(items) - len(temp)} duplicate files were excluded")
10198
items = temp
10299
else:
103100
log.exception("Numpy.ndarray is neither data nor file path.%s", invstr)
@@ -116,9 +113,7 @@ def input_handler(items, **kwargs):
116113
for item in items:
117114
temp.update(glob.glob(os.path.expanduser(item)))
118115
if len(items) != len(temp):
119-
log.debug(
120-
f"{len(items) - len(temp)} duplicate files were excluded"
121-
)
116+
log.debug(f"{len(items) - len(temp)} duplicate files were excluded")
122117
items = temp
123118
elif all(isinstance(item, np.ndarray) for item in items):
124119
log.info("input_handler() detected list of ndarrays")
@@ -541,9 +536,7 @@ def set_xdata(self, data=None, dt=1, dtunit=None):
541536
if self.dt == 1:
542537
newlabel = str(f"[{self.dtunit}]")
543538
else:
544-
newlabel = str(
545-
f"[{ut._printeger(self.dt)} {self.dtunit}]"
546-
)
539+
newlabel = str(f"[{ut._printeger(self.dt)} {self.dtunit}]")
547540
self.ax.set_xlabel(re.sub(regex, newlabel, oldlabel))
548541
self.xlabel = re.sub(regex, newlabel, self.xlabel)
549542
except TypeError:
@@ -660,9 +653,7 @@ def add_coefficients(self, data, **kwargs):
660653
self.ax.set_xlabel(f"k [{data.dtunit}]")
661654
else:
662655
self.xlabel = f"steps[{ut._printeger(data.dt, 5)} {data.dtunit}]"
663-
self.ax.set_xlabel(
664-
f"k [{ut._printeger(data.dt, 5)} {data.dtunit}]"
665-
)
656+
self.ax.set_xlabel(f"k [{ut._printeger(data.dt, 5)} {data.dtunit}]")
666657
self.ax.set_ylabel("$r_{k}$")
667658
self.ax.set_title("Correlation", fontweight="bold")
668659

mrestimator/utility.py

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,5 @@
1-
import os
21
import logging
32
import logging.handlers
4-
import stat
5-
import tempfile
6-
import platform
7-
import getpass
83
import math
94

105
import numpy as np
@@ -67,30 +62,26 @@ def _c_fits_consistent(fit1, fit2, quantile=0.125):
6762
"""
6863
# [.125, .25, .4, .5, .6, .75, .875]
6964
try:
70-
log.debug("Checking fits against each others {} quantiles".format(quantile))
65+
log.debug(f"Checking fits against each others {quantile} quantiles")
7166

7267
qmin = list(fit1.quantiles).index(quantile)
7368
qmax = list(fit1.quantiles).index(1 - quantile)
7469
log.debug(
75-
"{} < {} < {} ?".format(
76-
fit2.tauquantiles[qmin], fit1.tau, fit2.tauquantiles[qmax]
77-
)
70+
f"{fit2.tauquantiles[qmin]} < {fit1.tau} < {fit2.tauquantiles[qmax]} ?"
7871
)
7972
if fit1.tau > fit2.tauquantiles[qmax] or fit1.tau < fit2.tauquantiles[qmin]:
8073
return False
8174

8275
qmin = list(fit2.quantiles).index(quantile)
8376
qmax = list(fit2.quantiles).index(1 - quantile)
8477
log.debug(
85-
"{} < {} < {} ?".format(
86-
fit1.tauquantiles[qmin], fit2.tau, fit1.tauquantiles[qmax]
87-
)
78+
f"{fit1.tauquantiles[qmin]} < {fit2.tau} < {fit1.tauquantiles[qmax]} ?"
8879
)
8980
if fit2.tau > fit1.tauquantiles[qmax] or fit2.tau < fit1.tauquantiles[qmin]:
9081
return False
9182

9283
return True
93-
except Exception as e:
84+
except Exception:
9485
log.debug("Quantile not found in fit", exc_info=True)
9586

9687
return False
@@ -125,7 +116,7 @@ def _at_index(data, indices, keepdim=None, padding=np.nan):
125116
indices.size or data.size
126117
"""
127118
if not (keepdim is None or keepdim in ["data", "index"]):
128-
raise TypeError("unexpected argument keepdim={}".format(keepdim))
119+
raise TypeError(f"unexpected argument keepdim={keepdim}")
129120

130121
data = np.asarray(data)
131122
indices = np.asarray(indices)
@@ -167,10 +158,12 @@ def _prerror(f, ferr, errprec=2, maxprec=5):
167158
if ferr < 1:
168159
prec = math.ceil(-math.log10(math.fabs(ferr) - math.fabs(math.floor(ferr)))) - 1
169160
return str(
170-
"{:.{p}f}({:.0f})".format(f, ferr * 10 ** (prec + errprec), p=prec + errprec)
161+
"{:.{p}f}({:.0f})".format(
162+
f, ferr * 10 ** (prec + errprec), p=prec + errprec
163+
)
171164
)
172165
else:
173-
return str("{}({})".format(_printeger(f, errprec), _printeger(ferr, errprec)))
166+
return str(f"{_printeger(f, errprec)}({_printeger(ferr, errprec)})")
174167

175168

176169
def math_from_doc(fitfunc, maxlen=np.inf):
@@ -195,7 +188,7 @@ def math_from_doc(fitfunc, maxlen=np.inf):
195188
else:
196189
res = fitfunc.__name__
197190

198-
except Exception as e:
191+
except Exception:
199192
log.debug("Exception passed when casting function description", exc_info=True)
200193
res = fitfunc.__name__
201194

@@ -226,6 +219,7 @@ def enable_progressbar(leave=False):
226219
"""
227220
global tqdm
228221
from functools import partialmethod
222+
229223
try:
230224
tqdm.__init__ = partialmethod(tqdm.__init__, disable=False, leave=leave)
231225
except AttributeError:
@@ -239,6 +233,7 @@ def disable_progressbar():
239233
"""
240234
global tqdm
241235
from functools import partialmethod
236+
242237
try:
243238
tqdm.__init__ = partialmethod(tqdm.__init__, disable=True, leave=False)
244239
except AttributeError:

0 commit comments

Comments
 (0)