[Feat] More specific Exception statements

This commit is contained in:
Fabian Joswig 2026-07-06 11:17:14 +02:00
commit 7b952f9548
14 changed files with 73 additions and 73 deletions

View file

@ -540,7 +540,7 @@ class Corr:
on the configurations in obs[i].idl. on the configurations in obs[i].idl.
""" """
if self.N != 1: if self.N != 1:
raise Exception("Reweighting only implemented for one-dimensional correlators.") raise ValueError("Reweighting only implemented for one-dimensional correlators.")
new_content = [] new_content = []
for t_slice in self.content: for t_slice in self.content:
if _check_for_none(self, t_slice): if _check_for_none(self, t_slice):
@ -560,11 +560,11 @@ class Corr:
Parity quantum number of the correlator, can be +1 or -1 Parity quantum number of the correlator, can be +1 or -1
""" """
if self.N != 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): 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]: 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_partner = parity * partner.reverse()
t_slices = [] t_slices = []
@ -723,7 +723,7 @@ class Corr:
guess for the root finder, only relevant for the root variant guess for the root finder, only relevant for the root variant
""" """
if self.N != 1: 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': if variant == 'log':
newcontent = [] newcontent = []
for t in range(self.T - 1): for t in range(self.T - 1):
@ -844,7 +844,7 @@ class Corr:
if self.prange: if self.prange:
plateau_range = self.prange plateau_range = self.prange
else: else:
raise Exception("no plateau range provided") raise ValueError("no plateau range provided")
if self.N != 1: if self.N != 1:
raise ValueError("Correlator must be projected before getting a plateau.") 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)])): if (all([self.content[t] is None for t in range(plateau_range[0], plateau_range[1] + 1)])):

View file

@ -22,17 +22,17 @@ class Covobs:
""" """
self._set_cov(cov) self._set_cov(cov)
if '|' in name: if '|' in name:
raise Exception("Covobs name must not contain replica separator '|'.") raise ValueError("Covobs name must not contain replica separator '|'.")
self.name = name self.name = name
if grad is None: if grad is None:
if pos is None: if pos is None:
if self.N == 1: if self.N == 1:
pos = 0 pos = 0
else: 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: else:
if pos > self.N: 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 = np.zeros((self.N, 1))
self._grad[pos] = 1. self._grad[pos] = 1.
else: else:
@ -65,19 +65,19 @@ class Covobs:
elif self._cov.ndim == 2: elif self._cov.ndim == 2:
self.N = self._cov.shape[0] self.N = self._cov.shape[0]
if self._cov.shape[1] != self.N: 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: 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 i in range(self.N):
for j in range(i): for j in range(i):
if not self._cov[i][j] == self._cov[j][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) evals = np.linalg.eigvalsh(self._cov)
for ev in evals: for ev in evals:
if ev < 0: if ev < 0:
raise Exception('Covariance matrix is not positive-semidefinite!') raise ValueError('Covariance matrix is not positive-semidefinite!')
def _set_grad(self, grad): def _set_grad(self, grad):
""" Set the gradient of the covobs """ Set the gradient of the covobs
@ -93,7 +93,7 @@ class Covobs:
if self._grad.ndim in [0, 1]: if self._grad.ndim in [0, 1]:
self._grad = np.reshape(self._grad, (self.N, 1)) self._grad = np.reshape(self._grad, (self.N, 1))
elif self._grad.ndim != 2: elif self._grad.ndim != 2:
raise Exception('Invalid dimension of grad!') raise ValueError('Invalid dimension of grad!')
@property @property
def cov(self): def cov(self):

View file

@ -638,7 +638,7 @@ def total_least_squares(x, y, func, silent=False, **kwargs):
if 'initial_guess' in kwargs: if 'initial_guess' in kwargs:
x0 = np.asarray(kwargs.get('initial_guess'), dtype=np.float64) x0 = np.asarray(kwargs.get('initial_guess'), dtype=np.float64)
if len(x0) != n_parms: 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: else:
x0 = np.ones(n_parms, dtype=np.float64) x0 = np.ones(n_parms, dtype=np.float64)

View file

@ -61,9 +61,9 @@ def _dict_to_xmlstring(d):
elif not d[k]: elif not d[k]:
return '\n' return '\n'
else: else:
raise Exception('Type', type(d[k]), 'not supported in export!') raise TypeError('Type', type(d[k]), 'not supported in export!')
else: else:
raise Exception('Type', type(d), 'not supported in export!') raise TypeError('Type', type(d), 'not supported in export!')
return iters 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] onames = [name.replace('|', '') for name in names]
for o in obsl: for o in obsl:
if len(o.e_names) != 1: 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: 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: if len(o.deltas.keys()) != nr:
raise Exception('Incompatible obses in list') raise ValueError('Incompatible obses in list')
od['observables'] = {} od['observables'] = {}
od['observables']['schema'] = {'name': 'lattobs', 'version': '1.0'} od['observables']['schema'] = {'name': 'lattobs', 'version': '1.0'}
od['observables']['origin'] = { od['observables']['origin'] = {
@ -143,7 +143,7 @@ def create_pobs_string(obsl, name, spec='', origin='', symbol=None, enstag=None)
pd['name'] = name pd['name'] = name
if enstag: if enstag:
if not isinstance(enstag, str): if not isinstance(enstag, str):
raise Exception('enstag has to be a string!') raise TypeError('enstag has to be a string!')
pd['enstag'] = enstag pd['enstag'] = enstag
else: else:
pd['enstag'] = ename pd['enstag'] = ename
@ -151,9 +151,9 @@ def create_pobs_string(obsl, name, spec='', origin='', symbol=None, enstag=None)
pd['array'] = [] pd['array'] = []
osymbol = 'cfg' osymbol = 'cfg'
if not isinstance(symbol, list): 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)): 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 lenght 0 or {len(obsl)}!')
for s in symbol: for s in symbol:
osymbol += f' {s}' osymbol += f' {s}'
for r in range(nr): 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): elif isinstance(separator_insertion, str):
name = name.replace(separator_insertion, f"|{separator_insertion}") name = name.replace(separator_insertion, f"|{separator_insertion}")
else: else:
raise Exception("separator_insertion has to be string or int, is ", type(separator_insertion)) raise TypeError("separator_insertion has to be string or int, is ", type(separator_insertion))
names.append(name) names.append(name)
idl.append(idx) idl.append(idx)
res = [Obs([d[i] for d in deltas], names, idl=idl) for i in range(len(deltas[0]))] 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): elif isinstance(separator_insertion, str):
rname = rname.replace(separator_insertion, f"|{separator_insertion}") rname = rname.replace(separator_insertion, f"|{separator_insertion}")
else: else:
raise Exception("separator_insertion has to be string or int, is ", type(separator_insertion)) raise TypeError("separator_insertion has to be string or int, is ", type(separator_insertion))
if '|' in rname: if '|' in rname:
new_ename = rname[:rname.index('|')] new_ename = rname[:rname.index('|')]
else: else:
@ -657,9 +657,9 @@ def _dobsdict_to_xmlstring(d):
elif not d[k]: elif not d[k]:
return '\n' return '\n'
else: else:
raise Exception('Type', type(d[k]), 'not supported in export!') raise TypeError('Type', type(d[k]), 'not supported in export!')
else: else:
raise Exception('Type', type(d), 'not supported in export!') raise TypeError('Type', type(d), 'not supported in export!')
return iters return iters
@ -752,9 +752,9 @@ def create_dobs_string(obsl, name, spec='dobs v1.0', origin='', symbol=None, who
osymbol = '' osymbol = ''
if symbol: if symbol:
if not isinstance(symbol, list): 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)): 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 lenght 0 or {len(obsl)}!')
osymbol = symbol[0] osymbol = symbol[0]
for s in symbol[1:]: for s in symbol[1:]:
osymbol += f' {s}' osymbol += f' {s}'

View file

@ -18,7 +18,7 @@ def _get_files(path, filestem, idl):
files = list(filter(lambda x: x.startswith(filestem + "."), ls)) files = list(filter(lambda x: x.startswith(filestem + "."), ls))
if not files: 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): 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. 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 n_file == 0:
if h5file["DistillationContraction/Metadata"].attrs.get("TimeSources")[0].decode() != "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] Nt = h5file["DistillationContraction/Metadata"].attrs.get("Nt")[0]

View file

@ -568,7 +568,7 @@ def _ol_from_dict(ind, reps='DICTOBS'):
obstypes = (Obs, Corr, np.ndarray) obstypes = (Obs, Corr, np.ndarray)
if not reps.isalnum(): if not reps.isalnum():
raise Exception('Placeholder string has to be alphanumeric!') raise ValueError('Placeholder string has to be alphanumeric!')
ol = [] ol = []
counter = 0 counter = 0
@ -588,7 +588,7 @@ def _ol_from_dict(ind, reps='DICTOBS'):
counter += 1 counter += 1
elif isinstance(v, str): elif isinstance(v, str):
if bool(re.match(rf'{reps}[0-9]+', v)): 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 x[k] = v
return x return x
@ -608,7 +608,7 @@ def _ol_from_dict(ind, reps='DICTOBS'):
counter += 1 counter += 1
elif isinstance(e, str): elif isinstance(e, str):
if bool(re.match(rf'{reps}[0-9]+', e)): 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) x.append(e)
return x 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): 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. ' 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 ' '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]+. Specify the structure of the placeholder in imported dict to be reps[0-9]+.
""" """
if not reps.isalnum(): if not reps.isalnum():
raise Exception('Placeholder string has to be alphanumeric!') raise ValueError('Placeholder string has to be alphanumeric!')
counter = 0 counter = 0
@ -724,7 +724,7 @@ def _od_from_list_and_dict(ol, ind, reps='DICTOBS'):
nd = dict_replace_string(ind) nd = dict_replace_string(ind)
if counter == 0: 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 return nd

View file

@ -121,7 +121,7 @@ def read_pbp(path, prefix, **kwargs):
break break
if not ls: if not ls:
raise Exception('Error, directory not found') raise FileNotFoundError('Error, directory not found')
# Exclude files with different names # Exclude files with different names
for exc in ls: for exc in ls:
@ -134,7 +134,7 @@ def read_pbp(path, prefix, **kwargs):
if 'r_start' in kwargs: if 'r_start' in kwargs:
r_start = kwargs.get('r_start') r_start = kwargs.get('r_start')
if len(r_start) != replica: 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 # Adjust Configuration numbering to python index
r_start = [o - 1 if o else None for o in r_start] r_start = [o - 1 if o else None for o in r_start]
else: else:
@ -143,7 +143,7 @@ def read_pbp(path, prefix, **kwargs):
if 'r_stop' in kwargs: if 'r_stop' in kwargs:
r_stop = kwargs.get('r_stop') r_stop = kwargs.get('r_stop')
if len(r_stop) != replica: 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: else:
r_stop = [None] * replica r_stop = [None] * replica

View file

@ -49,7 +49,7 @@ def read_rwms(path, prefix, version='2.0', names=None, **kwargs):
""" """
known_oqcd_versions = ['1.4', '1.6', '2.0'] known_oqcd_versions = ['1.4', '1.6', '2.0']
if version not in known_oqcd_versions: 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) print("Working with openQCD version " + version)
if 'postfix' in kwargs: if 'postfix' in kwargs:
postfix = kwargs.get('postfix') postfix = kwargs.get('postfix')
@ -68,7 +68,7 @@ def read_rwms(path, prefix, version='2.0', names=None, **kwargs):
if 'r_start' in kwargs: if 'r_start' in kwargs:
r_start = kwargs.get('r_start') r_start = kwargs.get('r_start')
if len(r_start) != replica: 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] r_start = [o if o else None for o in r_start]
else: else:
r_start = [None] * replica r_start = [None] * replica
@ -76,7 +76,7 @@ def read_rwms(path, prefix, version='2.0', names=None, **kwargs):
if 'r_stop' in kwargs: if 'r_stop' in kwargs:
r_stop = kwargs.get('r_stop') r_stop = kwargs.get('r_stop')
if len(r_stop) != replica: 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: else:
r_stop = [None] * replica 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: if 'r_start' in kwargs:
r_start = kwargs.get('r_start') r_start = kwargs.get('r_start')
if len(r_start) != replica: 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] r_start = [o if o else None for o in r_start]
else: else:
r_start = [None] * replica 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: if 'r_stop' in kwargs:
r_stop = kwargs.get('r_stop') r_stop = kwargs.get('r_stop')
if len(r_stop) != replica: 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: else:
r_stop = [None] * replica r_stop = [None] * replica
@ -641,7 +641,7 @@ def _find_files(path, prefix, postfix, ext, known_files=None):
files.append(f) files.append(f)
if files == []: if files == []:
raise Exception("No files found after pattern filter!") raise FileNotFoundError("No files found after pattern filter!")
files = sort_names(files) files = sort_names(files)
return 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: 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) 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) 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"] T = plaq.tag["T"]
if T != L: 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: 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 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"] known_versions = ["openQCD", "sfqcd"]
if version not in known_versions: if version not in known_versions:
raise Exception("Unknown openQCD version.") raise ValueError("Unknown openQCD version.")
if "steps" in kwargs: if "steps" in kwargs:
steps = kwargs.get("steps") steps = kwargs.get("steps")
if version == "sfqcd": if version == "sfqcd":
@ -865,7 +865,7 @@ def _read_flow_obs(path, prefix, c, dtr_cnfg=1, version="openQCD", obspos=0, sum
postfix = "gfms" postfix = "gfms"
else: else:
if "L" not in kwargs: 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: else:
L = kwargs.get("L") L = kwargs.get("L")
postfix = "ms" 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: if 'r_start' in kwargs:
r_start = kwargs.get('r_start') r_start = kwargs.get('r_start')
if len(r_start) != len(files): 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] r_start = [o if o else None for o in r_start]
else: else:
r_start = [None] * len(files) 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: if 'r_stop' in kwargs:
r_stop = kwargs.get('r_stop') r_stop = kwargs.get('r_stop')
if len(r_stop) != len(files): 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: else:
r_stop = [None] * len(files) r_stop = [None] * len(files)
rep_names = [] rep_names = []
zeuthen = kwargs.get('Zeuthen_flow', False) zeuthen = kwargs.get('Zeuthen_flow', False)
if zeuthen and version not in ['sfqcd']: 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_start_index = []
r_stop_index = [] r_stop_index = []
@ -1087,7 +1087,7 @@ def qtop_projection(qtop, target=0):
projection to the topological charge sector defined by target projection to the topological charge sector defined by target
""" """
if qtop.reweighted: 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 = [] proj_qtop = []
for n in qtop.deltas: for n in qtop.deltas:
@ -1147,7 +1147,7 @@ def read_qtop_sector(path, prefix, c, target=0, **kwargs):
""" """
if not isinstance(target, int): 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 kwargs['integer_charge'] = True
qtop = read_qtop(path, prefix, c, **kwargs) 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 # test if the input is correct
if qc not in ['dd', 'ud', 'du', 'uu']: if qc not in ['dd', 'ud', 'du', 'uu']:
raise Exception("Unknown quark conbination!") raise ValueError("Unknown quark conbination!")
if corr not in ["gS", "gP", "gA", "gV", "gVt", "lA", "lV", "lVt", "lT", "lTt", "g1", "l1"]: 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: if "files" in kwargs:
known_files = kwargs.get("files") known_files = kwargs.get("files")

View file

@ -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"] known_versions = ["0.0", "1.0", "2.0", "1.0c", "2.0c", "1.0a", "2.0a"]
if version not in known_versions: if version not in known_versions:
raise Exception("This version is not known!") raise ValueError("This version is not known!")
if (version[-1] == "c"): if (version[-1] == "c"):
appended = False appended = False
compact = True compact = True
@ -186,7 +186,7 @@ def read_sfcf_multi(path, prefix, name_list, quarks_list=None, corr_type_list=No
ls.extend(filenames) ls.extend(filenames)
break break
if not ls: if not ls:
raise Exception('Error, directory not found') raise FileNotFoundError('Error, directory not found')
# Exclude folders with different names # Exclude folders with different names
for exc in ls: for exc in ls:
if not fnmatch.fnmatch(exc, prefix + '*'): 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: else:
replica = len([file.split(".")[-1] for file in ls]) // len(set([file.split(".")[-1] for file in ls])) replica = len([file.split(".")[-1] for file in ls]) // len(set([file.split(".")[-1] for file in ls]))
if replica == 0: if replica == 0:
raise Exception('No replica found in directory') raise FileNotFoundError('No replica found in directory')
if not silent: if not silent:
print('Read', part, 'part of', name_list, 'from', prefix[:-1], ',', replica, 'replica') print('Read', part, 'part of', name_list, 'from', prefix[:-1], ',', replica, 'replica')
if 'names' in kwargs: if 'names' in kwargs:
new_names = kwargs.get('names') new_names = kwargs.get('names')
if len(new_names) != len(set(new_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: if len(new_names) != replica:
raise Exception('names should have the length', replica) raise ValueError('names should have the length', replica)
else: else:
ens_name = kwargs.get("ens_name") 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...") print("Checking for missing configs...")
che = kwargs.get("check_configs") che = kwargs.get("check_configs")
if not (len(che) == len(idl)): 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)): for r in range(len(idl)):
if not silent: if not silent:
print("checking " + new_names[r]) print("checking " + new_names[r])

View file

@ -108,7 +108,7 @@ def check_params(path, param_hash, prefix, param_prefix="parameters_"):
ls.extend(dirnames) ls.extend(dirnames)
break break
if not ls: if not ls:
raise Exception('Error, directory not found') raise FileNotFoundError('Error, directory not found')
# Exclude folders with different names # Exclude folders with different names
for exc in ls: for exc in ls:
if not fnmatch.fnmatch(exc, prefix + '*'): if not fnmatch.fnmatch(exc, prefix + '*'):

View file

@ -203,7 +203,7 @@ def inv(x):
def cholesky(x): def cholesky(x):
"""Cholesky decomposition of Obs valued matrices.""" """Cholesky decomposition of Obs valued matrices."""
if any(isinstance(o, CObs) for o in x.ravel()): 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) return _mat_mat_op(anp.linalg.cholesky, x)

View file

@ -160,7 +160,7 @@ def gen_correlated_data(means, cov, name, tau=0.5, samples=1000):
assert len(means) == cov.shape[-1] assert len(means) == cov.shape[-1]
tau = np.asarray(tau) tau = np.asarray(tau)
if np.min(tau) < 0.5: 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) a = (2 * tau - 1) / (2 * tau + 1)
rand = np.random.multivariate_normal(np.zeros_like(means), cov * samples, samples) # noqa: NPY002 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]) otype = type(ol[0])
for o in ol[1:]: for o in ol[1:]:
if not isinstance(o, otype): 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"]: for attr in ["reweighted", "e_content", "idl"]:
if hasattr(ol[0], attr): if hasattr(ol[0], attr):
if not getattr(ol[0], attr) == getattr(o, 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}'.")

View file

@ -35,7 +35,7 @@ def matrix_pencil_method(corrs, k=1, p=None, **kwargs):
lengths = [len(d) for d in data] lengths = [len(d) for d in data]
if lengths.count(lengths[0]) != len(lengths): 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) data_sets = len(data)
n_data = len(data[0]) n_data = len(data[0])
@ -43,9 +43,9 @@ def matrix_pencil_method(corrs, k=1, p=None, **kwargs):
if p is None: if p is None:
p = max(n_data // 2, k) p = max(n_data // 2, k)
if n_data <= p: 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: 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('Cannot extract', k, 'energy levels with p=', p, 'and N-p=', n_data - p)
# Construct the hankel matrices # Construct the hankel matrices
matrix = [] matrix = []

View file

@ -1299,7 +1299,7 @@ def derived_observable(func, data, array_mode=False, **kwargs):
raise ValueError('Manual derivative does not have correct shape.') raise ValueError('Manual derivative does not have correct shape.')
elif kwargs.get('num_grad') is True: elif kwargs.get('num_grad') is True:
if multi > 0: if multi > 0:
raise Exception('Multi mode currently not supported for numerical derivative') raise NotImplementedError('Multi mode currently not supported for numerical derivative')
options = { options = {
'base_step': 0.1, 'base_step': 0.1,
'step_ratio': 2.5} 'step_ratio': 2.5}