Skip to content

Commit 3eac921

Browse files
authored
[Fix] Ruff rules and more precise Excpetion types (#248)
* [Fix] Fix test for membership should be 'not in' (E713) * [Fix] Fix module imported but unused (F401) * [Fix] More precise Exception types in dirac, obs and correlator
1 parent d908508 commit 3eac921

File tree

11 files changed

+144
-144
lines changed

11 files changed

+144
-144
lines changed

pyerrors/__init__.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -481,12 +481,12 @@ def func(a, x):
481481
from .correlators import *
482482
from .fits import *
483483
from .misc import *
484-
from . import dirac
485-
from . import input
486-
from . import linalg
487-
from . import mpm
488-
from . import roots
489-
from . import integrate
490-
from . import special
491-
492-
from .version import __version__
484+
from . import dirac as dirac
485+
from . import input as input
486+
from . import linalg as linalg
487+
from . import mpm as mpm
488+
from . import roots as roots
489+
from . import integrate as integrate
490+
from . import special as special
491+
492+
from .version import __version__ as __version__

pyerrors/correlators.py

Lines changed: 71 additions & 71 deletions
Large diffs are not rendered by default.

pyerrors/dirac.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ def epsilon_tensor(i, j, k):
3434
"""
3535
test_set = set((i, j, k))
3636
if not (test_set <= set((1, 2, 3)) or test_set <= set((0, 1, 2))):
37-
raise Exception("Unexpected input", i, j, k)
37+
raise ValueError("Unexpected input", i, j, k)
3838

3939
return (i - j) * (j - k) * (k - i) / 2
4040

@@ -52,7 +52,7 @@ def epsilon_tensor_rank4(i, j, k, o):
5252
"""
5353
test_set = set((i, j, k, o))
5454
if not (test_set <= set((1, 2, 3, 4)) or test_set <= set((0, 1, 2, 3))):
55-
raise Exception("Unexpected input", i, j, k, o)
55+
raise ValueError("Unexpected input", i, j, k, o)
5656

5757
return (i - j) * (j - k) * (k - i) * (i - o) * (j - o) * (o - k) / 12
5858

@@ -92,5 +92,5 @@ def Grid_gamma(gamma_tag):
9292
elif gamma_tag == 'SigmaZT':
9393
g = 0.5 * (gamma[2] @ gamma[3] - gamma[3] @ gamma[2])
9494
else:
95-
raise Exception('Unkown gamma structure', gamma_tag)
95+
raise ValueError('Unkown gamma structure', gamma_tag)
9696
return g

pyerrors/input/__init__.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,11 @@
55
For comparison with other analysis workflows `pyerrors` can also generate jackknife samples from an `Obs` object or import jackknife samples into an `Obs` object.
66
See `pyerrors.obs.Obs.export_jackknife` and `pyerrors.obs.import_jackknife` for details.
77
'''
8-
from . import bdio
9-
from . import dobs
10-
from . import hadrons
11-
from . import json
12-
from . import misc
13-
from . import openQCD
14-
from . import pandas
15-
from . import sfcf
8+
from . import bdio as bdio
9+
from . import dobs as dobs
10+
from . import hadrons as hadrons
11+
from . import json as json
12+
from . import misc as misc
13+
from . import openQCD as openQCD
14+
from . import pandas as pandas
15+
from . import sfcf as sfcf

pyerrors/input/dobs.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ def _dict_to_xmlstring_spaces(d, space=' '):
7979
o += space
8080
o += li + '\n'
8181
if li.startswith('<') and not cm:
82-
if not '<%s' % ('/') in li:
82+
if '<%s' % ('/') not in li:
8383
c += 1
8484
cm = False
8585
return o
@@ -671,7 +671,7 @@ def _dobsdict_to_xmlstring_spaces(d, space=' '):
671671
o += space
672672
o += li + '\n'
673673
if li.startswith('<') and not cm:
674-
if not '<%s' % ('/') in li:
674+
if '<%s' % ('/') not in li:
675675
c += 1
676676
cm = False
677677
return o

pyerrors/input/hadrons.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ def read_hd5(filestem, ens_id, group, attrs=None, idl=None, part="real"):
113113
infos = []
114114
for hd5_file in files:
115115
h5file = h5py.File(path + '/' + hd5_file, "r")
116-
if not group + '/' + entry in h5file:
116+
if group + '/' + entry not in h5file:
117117
raise Exception("Entry '" + entry + "' not contained in the files.")
118118
raw_data = h5file[group + '/' + entry + '/corr']
119119
real_data = raw_data[:].view("complex")
@@ -186,7 +186,7 @@ def _extract_real_arrays(path, files, tree, keys):
186186
for hd5_file in files:
187187
h5file = h5py.File(path + '/' + hd5_file, "r")
188188
for key in keys:
189-
if not tree + '/' + key in h5file:
189+
if tree + '/' + key not in h5file:
190190
raise Exception("Entry '" + key + "' not contained in the files.")
191191
raw_data = h5file[tree + '/' + key + '/data']
192192
real_data = raw_data[:].astype(np.double)

pyerrors/input/openQCD.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ def read_rwms(path, prefix, version='2.0', names=None, **kwargs):
4747
Reweighting factors read
4848
"""
4949
known_oqcd_versions = ['1.4', '1.6', '2.0']
50-
if not (version in known_oqcd_versions):
50+
if version not in known_oqcd_versions:
5151
raise Exception('Unknown openQCD version defined!')
5252
print("Working with openQCD version " + version)
5353
if 'postfix' in kwargs:

pyerrors/obs.py

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ def _parse_kwarg(kwarg_name):
222222
tmp = kwargs.get(kwarg_name)
223223
if isinstance(tmp, (int, float)):
224224
if tmp < 0:
225-
raise Exception(kwarg_name + ' has to be larger or equal to 0.')
225+
raise ValueError(kwarg_name + ' has to be larger or equal to 0.')
226226
for e, e_name in enumerate(self.e_names):
227227
getattr(self, kwarg_name)[e_name] = tmp
228228
else:
@@ -291,7 +291,7 @@ def _compute_drho(i):
291291
texp = self.tau_exp[e_name]
292292
# Critical slowing down analysis
293293
if w_max // 2 <= 1:
294-
raise Exception("Need at least 8 samples for tau_exp error analysis")
294+
raise ValueError("Need at least 8 samples for tau_exp error analysis")
295295
for n in range(1, w_max // 2):
296296
_compute_drho(n + 1)
297297
if (self.e_rho[e_name][n] - self.N_sigma[e_name] * self.e_drho[e_name][n]) < 0 or n >= w_max // 2 - 2:
@@ -620,7 +620,7 @@ def plot_piechart(self, save=None):
620620
if not hasattr(self, 'e_dvalue'):
621621
raise Exception('Run the gamma method first.')
622622
if np.isclose(0.0, self._dvalue, atol=1e-15):
623-
raise Exception('Error is 0.0')
623+
raise ValueError('Error is 0.0')
624624
labels = self.e_names
625625
sizes = [self.e_dvalue[name] ** 2 for name in labels] / self._dvalue ** 2
626626
fig1, ax1 = plt.subplots()
@@ -659,7 +659,7 @@ def dump(self, filename, datatype="json.gz", description="", **kwargs):
659659
with open(file_name + '.p', 'wb') as fb:
660660
pickle.dump(self, fb)
661661
else:
662-
raise Exception("Unknown datatype " + str(datatype))
662+
raise TypeError("Unknown datatype " + str(datatype))
663663

664664
def export_jackknife(self):
665665
"""Export jackknife samples from the Obs
@@ -676,7 +676,7 @@ def export_jackknife(self):
676676
"""
677677

678678
if len(self.names) != 1:
679-
raise Exception("'export_jackknife' is only implemented for Obs defined on one ensemble and replicum.")
679+
raise ValueError("'export_jackknife' is only implemented for Obs defined on one ensemble and replicum.")
680680

681681
name = self.names[0]
682682
full_data = self.deltas[name] + self.r_values[name]
@@ -711,7 +711,7 @@ def export_bootstrap(self, samples=500, random_numbers=None, save_rng=None):
711711
should agree with samples from a full bootstrap analysis up to O(1/N).
712712
"""
713713
if len(self.names) != 1:
714-
raise Exception("'export_boostrap' is only implemented for Obs defined on one ensemble and replicum.")
714+
raise ValueError("'export_boostrap' is only implemented for Obs defined on one ensemble and replicum.")
715715

716716
name = self.names[0]
717717
length = self.N
@@ -1267,7 +1267,7 @@ def _compute_scalefactor_missing_rep(obs):
12671267
if 'man_grad' in kwargs:
12681268
deriv = np.asarray(kwargs.get('man_grad'))
12691269
if new_values.shape + data.shape != deriv.shape:
1270-
raise Exception('Manual derivative does not have correct shape.')
1270+
raise ValueError('Manual derivative does not have correct shape.')
12711271
elif kwargs.get('num_grad') is True:
12721272
if multi > 0:
12731273
raise Exception('Multi mode currently not supported for numerical derivative')
@@ -1333,7 +1333,7 @@ def __init__(self, N):
13331333
new_covobs = {name: Covobs(0, allcov[name], name, grad=new_grad[name]) for name in new_grad}
13341334

13351335
if not set(new_covobs.keys()).isdisjoint(new_deltas.keys()):
1336-
raise Exception('The same name has been used for deltas and covobs!')
1336+
raise ValueError('The same name has been used for deltas and covobs!')
13371337
new_samples = []
13381338
new_means = []
13391339
new_idl = []
@@ -1374,15 +1374,15 @@ def _reduce_deltas(deltas, idx_old, idx_new):
13741374
Has to be a subset of idx_old.
13751375
"""
13761376
if not len(deltas) == len(idx_old):
1377-
raise Exception('Length of deltas and idx_old have to be the same: %d != %d' % (len(deltas), len(idx_old)))
1377+
raise ValueError('Length of deltas and idx_old have to be the same: %d != %d' % (len(deltas), len(idx_old)))
13781378
if type(idx_old) is range and type(idx_new) is range:
13791379
if idx_old == idx_new:
13801380
return deltas
13811381
if _check_lists_equal([idx_old, idx_new]):
13821382
return deltas
13831383
indices = np.intersect1d(idx_old, idx_new, assume_unique=True, return_indices=True)[1]
13841384
if len(indices) < len(idx_new):
1385-
raise Exception('Error in _reduce_deltas: Config of idx_new not in idx_old')
1385+
raise ValueError('Error in _reduce_deltas: Config of idx_new not in idx_old')
13861386
return np.array(deltas)[indices]
13871387

13881388

@@ -1404,12 +1404,12 @@ def reweight(weight, obs, **kwargs):
14041404
result = []
14051405
for i in range(len(obs)):
14061406
if len(obs[i].cov_names):
1407-
raise Exception('Error: Not possible to reweight an Obs that contains covobs!')
1407+
raise ValueError('Error: Not possible to reweight an Obs that contains covobs!')
14081408
if not set(obs[i].names).issubset(weight.names):
1409-
raise Exception('Error: Ensembles do not fit')
1409+
raise ValueError('Error: Ensembles do not fit')
14101410
for name in obs[i].names:
14111411
if not set(obs[i].idl[name]).issubset(weight.idl[name]):
1412-
raise Exception('obs[%d] has to be defined on a subset of the configs in weight.idl[%s]!' % (i, name))
1412+
raise ValueError('obs[%d] has to be defined on a subset of the configs in weight.idl[%s]!' % (i, name))
14131413
new_samples = []
14141414
w_deltas = {}
14151415
for name in sorted(obs[i].names):
@@ -1446,14 +1446,14 @@ def correlate(obs_a, obs_b):
14461446
"""
14471447

14481448
if sorted(obs_a.names) != sorted(obs_b.names):
1449-
raise Exception(f"Ensembles do not fit {set(sorted(obs_a.names)) ^ set(sorted(obs_b.names))}")
1449+
raise ValueError(f"Ensembles do not fit {set(sorted(obs_a.names)) ^ set(sorted(obs_b.names))}")
14501450
if len(obs_a.cov_names) or len(obs_b.cov_names):
1451-
raise Exception('Error: Not possible to correlate Obs that contain covobs!')
1451+
raise ValueError('Error: Not possible to correlate Obs that contain covobs!')
14521452
for name in obs_a.names:
14531453
if obs_a.shape[name] != obs_b.shape[name]:
1454-
raise Exception('Shapes of ensemble', name, 'do not fit')
1454+
raise ValueError('Shapes of ensemble', name, 'do not fit')
14551455
if obs_a.idl[name] != obs_b.idl[name]:
1456-
raise Exception('idl of ensemble', name, 'do not fit')
1456+
raise ValueError('idl of ensemble', name, 'do not fit')
14571457

14581458
if obs_a.reweighted is True:
14591459
warnings.warn("The first observable is already reweighted.", RuntimeWarning)
@@ -1555,7 +1555,7 @@ def invert_corr_cov_cholesky(corr, inverrdiag):
15551555

15561556
condn = np.linalg.cond(corr)
15571557
if condn > 0.1 / np.finfo(float).eps:
1558-
raise Exception(f"Cannot invert correlation matrix as its condition number exceeds machine precision ({condn:1.2e})")
1558+
raise ValueError(f"Cannot invert correlation matrix as its condition number exceeds machine precision ({condn:1.2e})")
15591559
if condn > 1e13:
15601560
warnings.warn("Correlation matrix may be ill-conditioned, condition number: {%1.2e}" % (condn), RuntimeWarning)
15611561
chol = np.linalg.cholesky(corr)
@@ -1636,7 +1636,7 @@ def _smooth_eigenvalues(corr, E):
16361636
Number of eigenvalues to be left substantially unchanged
16371637
"""
16381638
if not (2 < E < corr.shape[0] - 1):
1639-
raise Exception(f"'E' has to be between 2 and the dimension of the correlation matrix minus 1 ({corr.shape[0] - 1}).")
1639+
raise ValueError(f"'E' has to be between 2 and the dimension of the correlation matrix minus 1 ({corr.shape[0] - 1}).")
16401640
vals, vec = np.linalg.eigh(corr)
16411641
lambda_min = np.mean(vals[:-E])
16421642
vals[vals < lambda_min] = lambda_min
@@ -1768,9 +1768,9 @@ def merge_obs(list_of_obs):
17681768
"""
17691769
replist = [item for obs in list_of_obs for item in obs.names]
17701770
if (len(replist) == len(set(replist))) is False:
1771-
raise Exception('list_of_obs contains duplicate replica: %s' % (str(replist)))
1771+
raise ValueError('list_of_obs contains duplicate replica: %s' % (str(replist)))
17721772
if any([len(o.cov_names) for o in list_of_obs]):
1773-
raise Exception('Not possible to merge data that contains covobs!')
1773+
raise ValueError('Not possible to merge data that contains covobs!')
17741774
new_dict = {}
17751775
idl_dict = {}
17761776
for o in list_of_obs:
@@ -1821,7 +1821,7 @@ def covobs_to_obs(co):
18211821
for i in range(len(means)):
18221822
ol.append(covobs_to_obs(Covobs(means[i], cov, name, pos=i, grad=grad)))
18231823
if ol[0].covobs[name].N != len(means):
1824-
raise Exception('You have to provide %d mean values!' % (ol[0].N))
1824+
raise ValueError('You have to provide %d mean values!' % (ol[0].N))
18251825
if len(ol) == 1:
18261826
return ol[0]
18271827
return ol
@@ -1837,7 +1837,7 @@ def _determine_gap(o, e_content, e_name):
18371837

18381838
gap = min(gaps)
18391839
if not np.all([gi % gap == 0 for gi in gaps]):
1840-
raise Exception(f"Replica for ensemble {e_name} do not have a common spacing.", gaps)
1840+
raise ValueError(f"Replica for ensemble {e_name} do not have a common spacing.", gaps)
18411841

18421842
return gap
18431843

tests/correlators_test.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ def test_m_eff():
129129
with pytest.warns(RuntimeWarning):
130130
my_corr.m_eff('sinh')
131131

132-
with pytest.raises(Exception):
132+
with pytest.raises(ValueError):
133133
my_corr.m_eff('unkown_variant')
134134

135135

@@ -140,7 +140,7 @@ def test_m_eff_negative_values():
140140
assert m_eff_log[padding + 1] is None
141141
m_eff_cosh = my_corr.m_eff('cosh')
142142
assert m_eff_cosh[padding + 1] is None
143-
with pytest.raises(Exception):
143+
with pytest.raises(ValueError):
144144
my_corr.m_eff('logsym')
145145

146146

@@ -155,7 +155,7 @@ def test_correlate():
155155
my_corr = pe.correlators.Corr([pe.pseudo_Obs(10, 0.1, 't'), pe.pseudo_Obs(0, 0.05, 't')])
156156
corr1 = my_corr.correlate(my_corr)
157157
corr2 = my_corr.correlate(my_corr[0])
158-
with pytest.raises(Exception):
158+
with pytest.raises(TypeError):
159159
corr3 = my_corr.correlate(7.3)
160160

161161

@@ -176,9 +176,9 @@ def f(a, x):
176176
assert fit_res[0] == my_corr[0]
177177
assert fit_res[1] == my_corr[1] - my_corr[0]
178178

179-
with pytest.raises(Exception):
179+
with pytest.raises(TypeError):
180180
my_corr.fit(f, "from 0 to 3")
181-
with pytest.raises(Exception):
181+
with pytest.raises(ValueError):
182182
my_corr.fit(f, [0, 2, 3])
183183

184184

@@ -256,11 +256,11 @@ def test_prange():
256256
corr = pe.correlators.Corr(corr_content)
257257

258258
corr.set_prange([2, 4])
259-
with pytest.raises(Exception):
259+
with pytest.raises(ValueError):
260260
corr.set_prange([2])
261-
with pytest.raises(Exception):
261+
with pytest.raises(TypeError):
262262
corr.set_prange([2, 2.3])
263-
with pytest.raises(Exception):
263+
with pytest.raises(ValueError):
264264
corr.set_prange([4, 1])
265265

266266

tests/dirac_test.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def test_grid_dirac():
3030
'SigmaYZ',
3131
'SigmaZT']:
3232
pe.dirac.Grid_gamma(gamma)
33-
with pytest.raises(Exception):
33+
with pytest.raises(ValueError):
3434
pe.dirac.Grid_gamma('Not a gamma matrix')
3535

3636

@@ -44,7 +44,7 @@ def test_epsilon_tensor():
4444
(1, 1, 3) : 0.0}
4545
for key, value in check.items():
4646
assert pe.dirac.epsilon_tensor(*key) == value
47-
with pytest.raises(Exception):
47+
with pytest.raises(ValueError):
4848
pe.dirac.epsilon_tensor(0, 1, 3)
4949

5050

@@ -59,5 +59,5 @@ def test_epsilon_tensor_rank4():
5959
(1, 2, 3, 1) : 0.0}
6060
for key, value in check.items():
6161
assert pe.dirac.epsilon_tensor_rank4(*key) == value
62-
with pytest.raises(Exception):
62+
with pytest.raises(ValueError):
6363
pe.dirac.epsilon_tensor_rank4(0, 1, 3, 4)

0 commit comments

Comments
 (0)