Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions pyerrors/correlators.py
Original file line number Diff line number Diff line change
Expand Up @@ -540,7 +540,7 @@ def reweight(self, weight, **kwargs):
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):
Expand All @@ -560,11 +560,11 @@ def T_symmetry(self, partner, parity=+1):
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 = []
Expand Down Expand Up @@ -723,7 +723,7 @@ def m_eff(self, variant='log', guess=1.0):
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):
Expand Down Expand Up @@ -844,7 +844,7 @@ def plateau(self, plateau_range=None, method="fit", auto_gamma=False):
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)])):
Expand Down
16 changes: 8 additions & 8 deletions pyerrors/covobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,17 @@ def __init__(self, mean, cov, name, pos=None, grad=None):
"""
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:
Expand Down Expand Up @@ -65,19 +65,19 @@ def _set_cov(self, cov):
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
Expand All @@ -93,7 +93,7 @@ def _set_grad(self, grad):
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):
Expand Down
2 changes: 1 addition & 1 deletion pyerrors/fits.py
Original file line number Diff line number Diff line change
Expand Up @@ -638,7 +638,7 @@ def func(a, x):
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)

Expand Down
28 changes: 14 additions & 14 deletions pyerrors/input/dobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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'] = {
Expand All @@ -143,17 +143,17 @@ 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
pd['nr'] = f'{nr}'
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):
Expand Down Expand Up @@ -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]))]
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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}'
Expand Down
4 changes: 2 additions & 2 deletions pyerrors/input/hadrons.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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]

Expand Down
12 changes: 6 additions & 6 deletions pyerrors/input/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -588,7 +588,7 @@ def dict_replace_obs(d):
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

Expand All @@ -608,7 +608,7 @@ def list_replace_obs(li):
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

Expand Down Expand Up @@ -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 '
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -724,7 +724,7 @@ def list_replace_string(li):
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

Expand Down
6 changes: 3 additions & 3 deletions pyerrors/input/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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:
Expand All @@ -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

Expand Down
Loading
Loading