mirror of
https://github.com/fjosw/pyerrors.git
synced 2026-08-04 11:31:21 +02:00
[Feat] More specific Exception statements (#287)
* [Feat] More specific Exception statements * [Fix] Address copilot comments
This commit is contained in:
parent
e72949b69b
commit
470e2c57fc
14 changed files with 73 additions and 73 deletions
|
|
@ -540,7 +540,7 @@ class Corr:
|
|||
on the configurations in obs[i].idl.
|
||||
"""
|
||||
if self.N != 1:
|
||||
raise Exception("Reweighting only implemented for one-dimensional correlators.")
|
||||
raise ValueError("Reweighting only implemented for one-dimensional correlators.")
|
||||
new_content = []
|
||||
for t_slice in self.content:
|
||||
if _check_for_none(self, t_slice):
|
||||
|
|
@ -560,11 +560,11 @@ class Corr:
|
|||
Parity quantum number of the correlator, can be +1 or -1
|
||||
"""
|
||||
if self.N != 1:
|
||||
raise Exception("T_symmetry only implemented for one-dimensional correlators.")
|
||||
raise ValueError("T_symmetry only implemented for one-dimensional correlators.")
|
||||
if not isinstance(partner, Corr):
|
||||
raise Exception("T partner has to be a Corr object.")
|
||||
raise TypeError("T partner has to be a Corr object.")
|
||||
if parity not in [+1, -1]:
|
||||
raise Exception("Parity has to be +1 or -1.")
|
||||
raise ValueError("Parity has to be +1 or -1.")
|
||||
T_partner = parity * partner.reverse()
|
||||
|
||||
t_slices = []
|
||||
|
|
@ -723,7 +723,7 @@ class Corr:
|
|||
guess for the root finder, only relevant for the root variant
|
||||
"""
|
||||
if self.N != 1:
|
||||
raise Exception('Correlator must be projected before getting m_eff')
|
||||
raise ValueError('Correlator must be projected before getting m_eff')
|
||||
if variant == 'log':
|
||||
newcontent = []
|
||||
for t in range(self.T - 1):
|
||||
|
|
@ -844,7 +844,7 @@ class Corr:
|
|||
if self.prange:
|
||||
plateau_range = self.prange
|
||||
else:
|
||||
raise Exception("no plateau range provided")
|
||||
raise ValueError("no plateau range provided")
|
||||
if self.N != 1:
|
||||
raise ValueError("Correlator must be projected before getting a plateau.")
|
||||
if (all([self.content[t] is None for t in range(plateau_range[0], plateau_range[1] + 1)])):
|
||||
|
|
|
|||
|
|
@ -22,17 +22,17 @@ class Covobs:
|
|||
"""
|
||||
self._set_cov(cov)
|
||||
if '|' in name:
|
||||
raise Exception("Covobs name must not contain replica separator '|'.")
|
||||
raise ValueError("Covobs name must not contain replica separator '|'.")
|
||||
self.name = name
|
||||
if grad is None:
|
||||
if pos is None:
|
||||
if self.N == 1:
|
||||
pos = 0
|
||||
else:
|
||||
raise Exception('Have to specify position of cov-element belonging to mean!')
|
||||
raise ValueError('Have to specify position of cov-element belonging to mean!')
|
||||
else:
|
||||
if pos > self.N:
|
||||
raise Exception(f'pos {pos} too large for covariance matrix with dimension {self.N}x{self.N}!')
|
||||
raise ValueError(f'pos {pos} too large for covariance matrix with dimension {self.N}x{self.N}!')
|
||||
self._grad = np.zeros((self.N, 1))
|
||||
self._grad[pos] = 1.
|
||||
else:
|
||||
|
|
@ -65,19 +65,19 @@ class Covobs:
|
|||
elif self._cov.ndim == 2:
|
||||
self.N = self._cov.shape[0]
|
||||
if self._cov.shape[1] != self.N:
|
||||
raise Exception('Covariance matrix has to be a square matrix!')
|
||||
raise ValueError('Covariance matrix has to be a square matrix!')
|
||||
else:
|
||||
raise Exception('Covariance matrix has to be a 2 dimensional square matrix!')
|
||||
raise ValueError('Covariance matrix has to be a 2 dimensional square matrix!')
|
||||
|
||||
for i in range(self.N):
|
||||
for j in range(i):
|
||||
if not self._cov[i][j] == self._cov[j][i]:
|
||||
raise Exception(f'Covariance matrix is non-symmetric for ({i}, {j})')
|
||||
raise ValueError(f'Covariance matrix is non-symmetric for ({i}, {j})')
|
||||
|
||||
evals = np.linalg.eigvalsh(self._cov)
|
||||
for ev in evals:
|
||||
if ev < 0:
|
||||
raise Exception('Covariance matrix is not positive-semidefinite!')
|
||||
raise ValueError('Covariance matrix is not positive-semidefinite!')
|
||||
|
||||
def _set_grad(self, grad):
|
||||
""" Set the gradient of the covobs
|
||||
|
|
@ -93,7 +93,7 @@ class Covobs:
|
|||
if self._grad.ndim in [0, 1]:
|
||||
self._grad = np.reshape(self._grad, (self.N, 1))
|
||||
elif self._grad.ndim != 2:
|
||||
raise Exception('Invalid dimension of grad!')
|
||||
raise ValueError('Invalid dimension of grad!')
|
||||
|
||||
@property
|
||||
def cov(self):
|
||||
|
|
|
|||
|
|
@ -638,7 +638,7 @@ def total_least_squares(x, y, func, silent=False, **kwargs):
|
|||
if 'initial_guess' in kwargs:
|
||||
x0 = np.asarray(kwargs.get('initial_guess'), dtype=np.float64)
|
||||
if len(x0) != n_parms:
|
||||
raise Exception(f'Initial guess does not have the correct length: {len(x0)} vs. {n_parms}')
|
||||
raise ValueError(f'Initial guess does not have the correct length: {len(x0)} vs. {n_parms}')
|
||||
else:
|
||||
x0 = np.ones(n_parms, dtype=np.float64)
|
||||
|
||||
|
|
|
|||
|
|
@ -61,9 +61,9 @@ def _dict_to_xmlstring(d):
|
|||
elif not d[k]:
|
||||
return '\n'
|
||||
else:
|
||||
raise Exception('Type', type(d[k]), 'not supported in export!')
|
||||
raise TypeError(f'Type {type(d[k]).__name__} not supported in export!')
|
||||
else:
|
||||
raise Exception('Type', type(d), 'not supported in export!')
|
||||
raise TypeError(f'Type {type(d).__name__} not supported in export!')
|
||||
return iters
|
||||
|
||||
|
||||
|
|
@ -124,11 +124,11 @@ def create_pobs_string(obsl, name, spec='', origin='', symbol=None, enstag=None)
|
|||
onames = [name.replace('|', '') for name in names]
|
||||
for o in obsl:
|
||||
if len(o.e_names) != 1:
|
||||
raise Exception('You try to export dobs to obs!')
|
||||
raise ValueError('You try to export dobs to obs!')
|
||||
if o.e_names[0] != ename:
|
||||
raise Exception('You try to export dobs to obs!')
|
||||
raise ValueError('You try to export dobs to obs!')
|
||||
if len(o.deltas.keys()) != nr:
|
||||
raise Exception('Incompatible obses in list')
|
||||
raise ValueError('Incompatible obses in list')
|
||||
od['observables'] = {}
|
||||
od['observables']['schema'] = {'name': 'lattobs', 'version': '1.0'}
|
||||
od['observables']['origin'] = {
|
||||
|
|
@ -143,7 +143,7 @@ def create_pobs_string(obsl, name, spec='', origin='', symbol=None, enstag=None)
|
|||
pd['name'] = name
|
||||
if enstag:
|
||||
if not isinstance(enstag, str):
|
||||
raise Exception('enstag has to be a string!')
|
||||
raise TypeError('enstag has to be a string!')
|
||||
pd['enstag'] = enstag
|
||||
else:
|
||||
pd['enstag'] = ename
|
||||
|
|
@ -151,9 +151,9 @@ def create_pobs_string(obsl, name, spec='', origin='', symbol=None, enstag=None)
|
|||
pd['array'] = []
|
||||
osymbol = 'cfg'
|
||||
if not isinstance(symbol, list):
|
||||
raise Exception('Symbol has to be a list!')
|
||||
raise TypeError('Symbol has to be a list!')
|
||||
if not (len(symbol) == 0 or len(symbol) == len(obsl)):
|
||||
raise Exception(f'Symbol has to be a list of lenght 0 or {len(obsl)}!')
|
||||
raise ValueError(f'Symbol has to be a list of length 0 or {len(obsl)}!')
|
||||
for s in symbol:
|
||||
osymbol += f' {s}'
|
||||
for r in range(nr):
|
||||
|
|
@ -365,7 +365,7 @@ def read_pobs(fname, full_output=False, gz=True, separator_insertion=None):
|
|||
elif isinstance(separator_insertion, str):
|
||||
name = name.replace(separator_insertion, f"|{separator_insertion}")
|
||||
else:
|
||||
raise Exception("separator_insertion has to be string or int, is ", type(separator_insertion))
|
||||
raise TypeError(f"separator_insertion has to be string or int, is {type(separator_insertion).__name__}")
|
||||
names.append(name)
|
||||
idl.append(idx)
|
||||
res = [Obs([d[i] for d in deltas], names, idl=idl) for i in range(len(deltas[0]))]
|
||||
|
|
@ -485,7 +485,7 @@ def import_dobs_string(content, full_output=False, separator_insertion=True):
|
|||
elif isinstance(separator_insertion, str):
|
||||
rname = rname.replace(separator_insertion, f"|{separator_insertion}")
|
||||
else:
|
||||
raise Exception("separator_insertion has to be string or int, is ", type(separator_insertion))
|
||||
raise TypeError(f"separator_insertion has to be string or int, is {type(separator_insertion).__name__}")
|
||||
if '|' in rname:
|
||||
new_ename = rname[:rname.index('|')]
|
||||
else:
|
||||
|
|
@ -657,9 +657,9 @@ def _dobsdict_to_xmlstring(d):
|
|||
elif not d[k]:
|
||||
return '\n'
|
||||
else:
|
||||
raise Exception('Type', type(d[k]), 'not supported in export!')
|
||||
raise TypeError(f'Type {type(d[k]).__name__} not supported in export!')
|
||||
else:
|
||||
raise Exception('Type', type(d), 'not supported in export!')
|
||||
raise TypeError(f'Type {type(d).__name__} not supported in export!')
|
||||
return iters
|
||||
|
||||
|
||||
|
|
@ -752,9 +752,9 @@ def create_dobs_string(obsl, name, spec='dobs v1.0', origin='', symbol=None, who
|
|||
osymbol = ''
|
||||
if symbol:
|
||||
if not isinstance(symbol, list):
|
||||
raise Exception('Symbol has to be a list!')
|
||||
raise TypeError('Symbol has to be a list!')
|
||||
if not (len(symbol) == 0 or len(symbol) == len(obsl)):
|
||||
raise Exception(f'Symbol has to be a list of lenght 0 or {len(obsl)}!')
|
||||
raise ValueError(f'Symbol has to be a list of length 0 or {len(obsl)}!')
|
||||
osymbol = symbol[0]
|
||||
for s in symbol[1:]:
|
||||
osymbol += f' {s}'
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ def _get_files(path, filestem, idl):
|
|||
files = list(filter(lambda x: x.startswith(filestem + "."), ls))
|
||||
|
||||
if not files:
|
||||
raise Exception('No files starting with', filestem, 'in folder', path)
|
||||
raise FileNotFoundError(f'No files starting with {filestem} in folder {path}')
|
||||
|
||||
def get_cnfg_number(n):
|
||||
return int(n.replace(".h5", "")[len(filestem) + 1:]) # From python 3.9 onward the safer 'removesuffix' method can be used.
|
||||
|
|
@ -298,7 +298,7 @@ def read_DistillationContraction_hd5(path, ens_id, diagrams=None, idl=None):
|
|||
|
||||
if n_file == 0:
|
||||
if h5file["DistillationContraction/Metadata"].attrs.get("TimeSources")[0].decode() != "0...":
|
||||
raise Exception("Routine is only implemented for files containing inversions on all timeslices.")
|
||||
raise NotImplementedError("Routine is only implemented for files containing inversions on all timeslices.")
|
||||
|
||||
Nt = h5file["DistillationContraction/Metadata"].attrs.get("Nt")[0]
|
||||
|
||||
|
|
|
|||
|
|
@ -568,7 +568,7 @@ def _ol_from_dict(ind, reps='DICTOBS'):
|
|||
obstypes = (Obs, Corr, np.ndarray)
|
||||
|
||||
if not reps.isalnum():
|
||||
raise Exception('Placeholder string has to be alphanumeric!')
|
||||
raise ValueError('Placeholder string has to be alphanumeric!')
|
||||
ol = []
|
||||
counter = 0
|
||||
|
||||
|
|
@ -588,7 +588,7 @@ def _ol_from_dict(ind, reps='DICTOBS'):
|
|||
counter += 1
|
||||
elif isinstance(v, str):
|
||||
if bool(re.match(rf'{reps}[0-9]+', v)):
|
||||
raise Exception(f'Dict contains string {v} that matches the placeholder! {reps} Cannot be safely exported.')
|
||||
raise ValueError(f'Dict contains string {v} that matches the placeholder! {reps} Cannot be safely exported.')
|
||||
x[k] = v
|
||||
return x
|
||||
|
||||
|
|
@ -608,7 +608,7 @@ def _ol_from_dict(ind, reps='DICTOBS'):
|
|||
counter += 1
|
||||
elif isinstance(e, str):
|
||||
if bool(re.match(rf'{reps}[0-9]+', e)):
|
||||
raise Exception(f'Dict contains string {e} that matches the placeholder! {reps} Cannot be safely exported.')
|
||||
raise ValueError(f'Dict contains string {e} that matches the placeholder! {reps} Cannot be safely exported.')
|
||||
x.append(e)
|
||||
return x
|
||||
|
||||
|
|
@ -655,7 +655,7 @@ def dump_dict_to_json(od, fname, description='', indent=1, reps='DICTOBS', gz=Tr
|
|||
"""
|
||||
|
||||
if not isinstance(od, dict):
|
||||
raise Exception('od has to be a dictionary. Did you want to use dump_to_json?')
|
||||
raise TypeError('od has to be a dictionary. Did you want to use dump_to_json?')
|
||||
|
||||
infostring = ('This JSON file contains a python dictionary that has been parsed to a list of structures. '
|
||||
'OBSDICT contains the dictionary, where Obs or other structures have been replaced by '
|
||||
|
|
@ -687,7 +687,7 @@ def _od_from_list_and_dict(ol, ind, reps='DICTOBS'):
|
|||
Specify the structure of the placeholder in imported dict to be reps[0-9]+.
|
||||
"""
|
||||
if not reps.isalnum():
|
||||
raise Exception('Placeholder string has to be alphanumeric!')
|
||||
raise ValueError('Placeholder string has to be alphanumeric!')
|
||||
|
||||
counter = 0
|
||||
|
||||
|
|
@ -724,7 +724,7 @@ def _od_from_list_and_dict(ol, ind, reps='DICTOBS'):
|
|||
nd = dict_replace_string(ind)
|
||||
|
||||
if counter == 0:
|
||||
raise Exception('No placeholder has been replaced! Check if reps is set correctly.')
|
||||
raise ValueError('No placeholder has been replaced! Check if reps is set correctly.')
|
||||
|
||||
return nd
|
||||
|
||||
|
|
|
|||
|
|
@ -121,7 +121,7 @@ def read_pbp(path, prefix, **kwargs):
|
|||
break
|
||||
|
||||
if not ls:
|
||||
raise Exception('Error, directory not found')
|
||||
raise FileNotFoundError('Error, directory not found')
|
||||
|
||||
# Exclude files with different names
|
||||
for exc in ls:
|
||||
|
|
@ -134,7 +134,7 @@ def read_pbp(path, prefix, **kwargs):
|
|||
if 'r_start' in kwargs:
|
||||
r_start = kwargs.get('r_start')
|
||||
if len(r_start) != replica:
|
||||
raise Exception('r_start does not match number of replicas')
|
||||
raise ValueError('r_start does not match number of replicas')
|
||||
# Adjust Configuration numbering to python index
|
||||
r_start = [o - 1 if o else None for o in r_start]
|
||||
else:
|
||||
|
|
@ -143,7 +143,7 @@ def read_pbp(path, prefix, **kwargs):
|
|||
if 'r_stop' in kwargs:
|
||||
r_stop = kwargs.get('r_stop')
|
||||
if len(r_stop) != replica:
|
||||
raise Exception('r_stop does not match number of replicas')
|
||||
raise ValueError('r_stop does not match number of replicas')
|
||||
else:
|
||||
r_stop = [None] * replica
|
||||
|
||||
|
|
|
|||
|
|
@ -49,7 +49,7 @@ def read_rwms(path, prefix, version='2.0', names=None, **kwargs):
|
|||
"""
|
||||
known_oqcd_versions = ['1.4', '1.6', '2.0']
|
||||
if version not in known_oqcd_versions:
|
||||
raise Exception('Unknown openQCD version defined!')
|
||||
raise ValueError('Unknown openQCD version defined!')
|
||||
print("Working with openQCD version " + version)
|
||||
if 'postfix' in kwargs:
|
||||
postfix = kwargs.get('postfix')
|
||||
|
|
@ -68,7 +68,7 @@ def read_rwms(path, prefix, version='2.0', names=None, **kwargs):
|
|||
if 'r_start' in kwargs:
|
||||
r_start = kwargs.get('r_start')
|
||||
if len(r_start) != replica:
|
||||
raise Exception('r_start does not match number of replicas')
|
||||
raise ValueError('r_start does not match number of replicas')
|
||||
r_start = [o if o else None for o in r_start]
|
||||
else:
|
||||
r_start = [None] * replica
|
||||
|
|
@ -76,7 +76,7 @@ def read_rwms(path, prefix, version='2.0', names=None, **kwargs):
|
|||
if 'r_stop' in kwargs:
|
||||
r_stop = kwargs.get('r_stop')
|
||||
if len(r_stop) != replica:
|
||||
raise Exception('r_stop does not match number of replicas')
|
||||
raise ValueError('r_stop does not match number of replicas')
|
||||
else:
|
||||
r_stop = [None] * replica
|
||||
|
||||
|
|
@ -301,7 +301,7 @@ def _extract_flowed_energy_density(path, prefix, dtr_read, xmin, spatial_extent,
|
|||
if 'r_start' in kwargs:
|
||||
r_start = kwargs.get('r_start')
|
||||
if len(r_start) != replica:
|
||||
raise Exception('r_start does not match number of replicas')
|
||||
raise ValueError('r_start does not match number of replicas')
|
||||
r_start = [o if o else None for o in r_start]
|
||||
else:
|
||||
r_start = [None] * replica
|
||||
|
|
@ -309,7 +309,7 @@ def _extract_flowed_energy_density(path, prefix, dtr_read, xmin, spatial_extent,
|
|||
if 'r_stop' in kwargs:
|
||||
r_stop = kwargs.get('r_stop')
|
||||
if len(r_stop) != replica:
|
||||
raise Exception('r_stop does not match number of replicas')
|
||||
raise ValueError('r_stop does not match number of replicas')
|
||||
else:
|
||||
r_stop = [None] * replica
|
||||
|
||||
|
|
@ -641,7 +641,7 @@ def _find_files(path, prefix, postfix, ext, known_files=None):
|
|||
files.append(f)
|
||||
|
||||
if files == []:
|
||||
raise Exception("No files found after pattern filter!")
|
||||
raise FileNotFoundError("No files found after pattern filter!")
|
||||
|
||||
files = sort_names(files)
|
||||
return files
|
||||
|
|
@ -765,7 +765,7 @@ def read_gf_coupling(path, prefix, c, dtr_cnfg=1, Zeuthen_flow=True, **kwargs):
|
|||
"""
|
||||
|
||||
if c != 0.3:
|
||||
raise Exception("The required lattice norm is only implemented for c=0.3 at the moment.")
|
||||
raise NotImplementedError("The required lattice norm is only implemented for c=0.3 at the moment.")
|
||||
|
||||
plaq = _read_flow_obs(path, prefix, c, dtr_cnfg=dtr_cnfg, version="sfqcd", obspos=6, sum_t=False, Zeuthen_flow=Zeuthen_flow, integer_charge=False, **kwargs)
|
||||
C2x1 = _read_flow_obs(path, prefix, c, dtr_cnfg=dtr_cnfg, version="sfqcd", obspos=7, sum_t=False, Zeuthen_flow=Zeuthen_flow, integer_charge=False, **kwargs)
|
||||
|
|
@ -773,10 +773,10 @@ def read_gf_coupling(path, prefix, c, dtr_cnfg=1, Zeuthen_flow=True, **kwargs):
|
|||
T = plaq.tag["T"]
|
||||
|
||||
if T != L:
|
||||
raise Exception("The required lattice norm is only implemented for T=L at the moment.")
|
||||
raise NotImplementedError("The required lattice norm is only implemented for T=L at the moment.")
|
||||
|
||||
if Zeuthen_flow is not True:
|
||||
raise Exception("The required lattice norm is only implemented for the Zeuthen flow at the moment.")
|
||||
raise NotImplementedError("The required lattice norm is only implemented for the Zeuthen flow at the moment.")
|
||||
|
||||
t = (c * L) ** 2 / 8
|
||||
|
||||
|
|
@ -854,7 +854,7 @@ def _read_flow_obs(path, prefix, c, dtr_cnfg=1, version="openQCD", obspos=0, sum
|
|||
known_versions = ["openQCD", "sfqcd"]
|
||||
|
||||
if version not in known_versions:
|
||||
raise Exception("Unknown openQCD version.")
|
||||
raise ValueError("Unknown openQCD version.")
|
||||
if "steps" in kwargs:
|
||||
steps = kwargs.get("steps")
|
||||
if version == "sfqcd":
|
||||
|
|
@ -865,7 +865,7 @@ def _read_flow_obs(path, prefix, c, dtr_cnfg=1, version="openQCD", obspos=0, sum
|
|||
postfix = "gfms"
|
||||
else:
|
||||
if "L" not in kwargs:
|
||||
raise Exception("This version of openQCD needs you to provide the spatial length of the lattice as parameter 'L'.")
|
||||
raise ValueError("This version of openQCD needs you to provide the spatial length of the lattice as parameter 'L'.")
|
||||
else:
|
||||
L = kwargs.get("L")
|
||||
postfix = "ms"
|
||||
|
|
@ -883,7 +883,7 @@ def _read_flow_obs(path, prefix, c, dtr_cnfg=1, version="openQCD", obspos=0, sum
|
|||
if 'r_start' in kwargs:
|
||||
r_start = kwargs.get('r_start')
|
||||
if len(r_start) != len(files):
|
||||
raise Exception('r_start does not match number of replicas')
|
||||
raise ValueError('r_start does not match number of replicas')
|
||||
r_start = [o if o else None for o in r_start]
|
||||
else:
|
||||
r_start = [None] * len(files)
|
||||
|
|
@ -891,14 +891,14 @@ def _read_flow_obs(path, prefix, c, dtr_cnfg=1, version="openQCD", obspos=0, sum
|
|||
if 'r_stop' in kwargs:
|
||||
r_stop = kwargs.get('r_stop')
|
||||
if len(r_stop) != len(files):
|
||||
raise Exception('r_stop does not match number of replicas')
|
||||
raise ValueError('r_stop does not match number of replicas')
|
||||
else:
|
||||
r_stop = [None] * len(files)
|
||||
rep_names = []
|
||||
|
||||
zeuthen = kwargs.get('Zeuthen_flow', False)
|
||||
if zeuthen and version not in ['sfqcd']:
|
||||
raise Exception('Zeuthen flow can only be used for version==sfqcd')
|
||||
raise ValueError('Zeuthen flow can only be used for version==sfqcd')
|
||||
|
||||
r_start_index = []
|
||||
r_stop_index = []
|
||||
|
|
@ -1087,7 +1087,7 @@ def qtop_projection(qtop, target=0):
|
|||
projection to the topological charge sector defined by target
|
||||
"""
|
||||
if qtop.reweighted:
|
||||
raise Exception('You can not use a reweighted observable for reweighting!')
|
||||
raise ValueError('You can not use a reweighted observable for reweighting!')
|
||||
|
||||
proj_qtop = []
|
||||
for n in qtop.deltas:
|
||||
|
|
@ -1147,7 +1147,7 @@ def read_qtop_sector(path, prefix, c, target=0, **kwargs):
|
|||
"""
|
||||
|
||||
if not isinstance(target, int):
|
||||
raise Exception("'target' has to be an integer.")
|
||||
raise TypeError("'target' has to be an integer.")
|
||||
|
||||
kwargs['integer_charge'] = True
|
||||
qtop = read_qtop(path, prefix, c, **kwargs)
|
||||
|
|
@ -1203,10 +1203,10 @@ def read_ms5_xsf(path, prefix, qc, corr, sep="r", **kwargs):
|
|||
|
||||
# test if the input is correct
|
||||
if qc not in ['dd', 'ud', 'du', 'uu']:
|
||||
raise Exception("Unknown quark conbination!")
|
||||
raise ValueError("Unknown quark combination!")
|
||||
|
||||
if corr not in ["gS", "gP", "gA", "gV", "gVt", "lA", "lV", "lVt", "lT", "lTt", "g1", "l1"]:
|
||||
raise Exception("Unknown correlator!")
|
||||
raise ValueError("Unknown correlator!")
|
||||
|
||||
if "files" in kwargs:
|
||||
known_files = kwargs.get("files")
|
||||
|
|
|
|||
|
|
@ -163,7 +163,7 @@ def read_sfcf_multi(path, prefix, name_list, quarks_list=None, corr_type_list=No
|
|||
known_versions = ["0.0", "1.0", "2.0", "1.0c", "2.0c", "1.0a", "2.0a"]
|
||||
|
||||
if version not in known_versions:
|
||||
raise Exception("This version is not known!")
|
||||
raise ValueError("This version is not known!")
|
||||
if (version[-1] == "c"):
|
||||
appended = False
|
||||
compact = True
|
||||
|
|
@ -186,7 +186,7 @@ def read_sfcf_multi(path, prefix, name_list, quarks_list=None, corr_type_list=No
|
|||
ls.extend(filenames)
|
||||
break
|
||||
if not ls:
|
||||
raise Exception('Error, directory not found')
|
||||
raise FileNotFoundError('Error, directory not found')
|
||||
# Exclude folders with different names
|
||||
for exc in ls:
|
||||
if not fnmatch.fnmatch(exc, prefix + '*'):
|
||||
|
|
@ -199,16 +199,16 @@ def read_sfcf_multi(path, prefix, name_list, quarks_list=None, corr_type_list=No
|
|||
else:
|
||||
replica = len([file.split(".")[-1] for file in ls]) // len(set([file.split(".")[-1] for file in ls]))
|
||||
if replica == 0:
|
||||
raise Exception('No replica found in directory')
|
||||
raise FileNotFoundError('No replica found in directory')
|
||||
if not silent:
|
||||
print('Read', part, 'part of', name_list, 'from', prefix[:-1], ',', replica, 'replica')
|
||||
|
||||
if 'names' in kwargs:
|
||||
new_names = kwargs.get('names')
|
||||
if len(new_names) != len(set(new_names)):
|
||||
raise Exception("names are not unique!")
|
||||
raise ValueError("names are not unique!")
|
||||
if len(new_names) != replica:
|
||||
raise Exception('names should have the length', replica)
|
||||
raise ValueError(f'names should have the length {replica}')
|
||||
|
||||
else:
|
||||
ens_name = kwargs.get("ens_name")
|
||||
|
|
@ -388,7 +388,7 @@ def read_sfcf_multi(path, prefix, name_list, quarks_list=None, corr_type_list=No
|
|||
print("Checking for missing configs...")
|
||||
che = kwargs.get("check_configs")
|
||||
if not (len(che) == len(idl)):
|
||||
raise Exception("check_configs has to be the same length as replica!")
|
||||
raise ValueError("check_configs has to be the same length as replica!")
|
||||
for r in range(len(idl)):
|
||||
if not silent:
|
||||
print("checking " + new_names[r])
|
||||
|
|
|
|||
|
|
@ -108,7 +108,7 @@ def check_params(path, param_hash, prefix, param_prefix="parameters_"):
|
|||
ls.extend(dirnames)
|
||||
break
|
||||
if not ls:
|
||||
raise Exception('Error, directory not found')
|
||||
raise FileNotFoundError('Error, directory not found')
|
||||
# Exclude folders with different names
|
||||
for exc in ls:
|
||||
if not fnmatch.fnmatch(exc, prefix + '*'):
|
||||
|
|
|
|||
|
|
@ -203,7 +203,7 @@ def inv(x):
|
|||
def cholesky(x):
|
||||
"""Cholesky decomposition of Obs valued matrices."""
|
||||
if any(isinstance(o, CObs) for o in x.ravel()):
|
||||
raise Exception("Cholesky decomposition is not implemented for CObs.")
|
||||
raise NotImplementedError("Cholesky decomposition is not implemented for CObs.")
|
||||
return _mat_mat_op(anp.linalg.cholesky, x)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -160,7 +160,7 @@ def gen_correlated_data(means, cov, name, tau=0.5, samples=1000):
|
|||
assert len(means) == cov.shape[-1]
|
||||
tau = np.asarray(tau)
|
||||
if np.min(tau) < 0.5:
|
||||
raise Exception('All integrated autocorrelations have to be >= 0.5.')
|
||||
raise ValueError('All integrated autocorrelations have to be >= 0.5.')
|
||||
|
||||
a = (2 * tau - 1) / (2 * tau + 1)
|
||||
rand = np.random.multivariate_normal(np.zeros_like(means), cov * samples, samples) # noqa: NPY002
|
||||
|
|
@ -180,8 +180,8 @@ def _assert_equal_properties(ol, otype=Obs):
|
|||
otype = type(ol[0])
|
||||
for o in ol[1:]:
|
||||
if not isinstance(o, otype):
|
||||
raise Exception("Wrong data type in list.")
|
||||
raise TypeError("Wrong data type in list.")
|
||||
for attr in ["reweighted", "e_content", "idl"]:
|
||||
if hasattr(ol[0], attr):
|
||||
if not getattr(ol[0], attr) == getattr(o, attr):
|
||||
raise Exception(f"All Obs in list have to have the same state '{attr}'.")
|
||||
raise ValueError(f"All Obs in list have to have the same state '{attr}'.")
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ def matrix_pencil_method(corrs, k=1, p=None, **kwargs):
|
|||
|
||||
lengths = [len(d) for d in data]
|
||||
if lengths.count(lengths[0]) != len(lengths):
|
||||
raise Exception('All datasets have to have the same length.')
|
||||
raise ValueError('All datasets have to have the same length.')
|
||||
|
||||
data_sets = len(data)
|
||||
n_data = len(data[0])
|
||||
|
|
@ -43,9 +43,9 @@ def matrix_pencil_method(corrs, k=1, p=None, **kwargs):
|
|||
if p is None:
|
||||
p = max(n_data // 2, k)
|
||||
if n_data <= p:
|
||||
raise Exception('The pencil p has to be smaller than the number of data samples.')
|
||||
raise ValueError('The pencil p has to be smaller than the number of data samples.')
|
||||
if p < k or n_data - p < k:
|
||||
raise Exception('Cannot extract', k, 'energy levels with p=', p, 'and N-p=', n_data - p)
|
||||
raise ValueError(f'Cannot extract {k} energy levels with p={p} and N-p={n_data - p}')
|
||||
|
||||
# Construct the hankel matrices
|
||||
matrix = []
|
||||
|
|
|
|||
|
|
@ -1299,7 +1299,7 @@ def derived_observable(func, data, array_mode=False, **kwargs):
|
|||
raise ValueError('Manual derivative does not have correct shape.')
|
||||
elif kwargs.get('num_grad') is True:
|
||||
if multi > 0:
|
||||
raise Exception('Multi mode currently not supported for numerical derivative')
|
||||
raise NotImplementedError('Multi mode currently not supported for numerical derivative')
|
||||
options = {
|
||||
'base_step': 0.1,
|
||||
'step_ratio': 2.5}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue