diff --git a/docs/pyerrors.html b/docs/pyerrors.html index b2967e43..9598a9ac 100644 --- a/docs/pyerrors.html +++ b/docs/pyerrors.html @@ -1155,15 +1155,15 @@ The following entries are optional: 481from .correlators import * 482from .fits import * 483from .misc import * -484from . import dirac -485from . import input -486from . import linalg -487from . import mpm -488from . import roots -489from . import integrate -490from . import special +484from . import dirac as dirac +485from . import input as input +486from . import linalg as linalg +487from . import mpm as mpm +488from . import roots as roots +489from . import integrate as integrate +490from . import special as special 491 -492from .version import __version__ +492from .version import __version__ as __version__ diff --git a/docs/pyerrors/correlators.html b/docs/pyerrors/correlators.html index 4f8ca29b..602f733c 100644 --- a/docs/pyerrors/correlators.html +++ b/docs/pyerrors/correlators.html @@ -344,7 +344,7 @@ 101 self.N = 1 102 elif all([isinstance(item, np.ndarray) or item is None for item in data_input]) and any([isinstance(item, np.ndarray) for item in data_input]): 103 self.content = data_input - 104 noNull = [a for a in self.content if not (a is None)] # To check if the matrices are correct for all undefined elements + 104 noNull = [a for a in self.content if a is not None] # To check if the matrices are correct for all undefined elements 105 self.N = noNull[0].shape[0] 106 if self.N > 1 and noNull[0].shape[0] != noNull[0].shape[1]: 107 raise ValueError("Smearing matrices are not NxN.") @@ -384,7 +384,7 @@ 141 def gamma_method(self, **kwargs): 142 """Apply the gamma method to the content of the Corr.""" 143 for item in self.content: - 144 if not (item is None): + 144 if item is not None: 145 if self.N == 1: 146 item[0].gamma_method(**kwargs) 147 else: @@ -402,7 +402,7 @@ 159 By default it will return the lowest source, which usually means unsmeared-unsmeared (0,0), but it does not have to 160 """ 161 if self.N == 1: - 162 raise Exception("Trying to project a Corr, that already has N=1.") + 162 raise ValueError("Trying to project a Corr, that already has N=1.") 163 164 if vector_l is None: 165 vector_l, vector_r = np.asarray([1.] + (self.N - 1) * [0.]), np.asarray([1.] + (self.N - 1) * [0.]) @@ -410,16 +410,16 @@ 167 vector_r = vector_l 168 if isinstance(vector_l, list) and not isinstance(vector_r, list): 169 if len(vector_l) != self.T: - 170 raise Exception("Length of vector list must be equal to T") + 170 raise ValueError("Length of vector list must be equal to T") 171 vector_r = [vector_r] * self.T 172 if isinstance(vector_r, list) and not isinstance(vector_l, list): 173 if len(vector_r) != self.T: - 174 raise Exception("Length of vector list must be equal to T") + 174 raise ValueError("Length of vector list must be equal to T") 175 vector_l = [vector_l] * self.T 176 177 if not isinstance(vector_l, list): 178 if not vector_l.shape == vector_r.shape == (self.N,): - 179 raise Exception("Vectors are of wrong shape!") + 179 raise ValueError("Vectors are of wrong shape!") 180 if normalize: 181 vector_l, vector_r = vector_l / np.sqrt((vector_l @ vector_l)), vector_r / np.sqrt(vector_r @ vector_r) 182 newcontent = [None if _check_for_none(self, item) else np.asarray([vector_l.T @ item @ vector_r]) for item in self.content] @@ -444,7 +444,7 @@ 201 Second index to be picked. 202 """ 203 if self.N == 1: - 204 raise Exception("Trying to pick item from projected Corr") + 204 raise ValueError("Trying to pick item from projected Corr") 205 newcontent = [None if (item is None) else item[i, j] for item in self.content] 206 return Corr(newcontent) 207 @@ -455,8 +455,8 @@ 212 timeslice and the error on each timeslice. 213 """ 214 if self.N != 1: - 215 raise Exception("Can only make Corr[N=1] plottable") - 216 x_list = [x for x in range(self.T) if not self.content[x] is None] + 215 raise ValueError("Can only make Corr[N=1] plottable") + 216 x_list = [x for x in range(self.T) if self.content[x] is not None] 217 y_list = [y[0].value for y in self.content if y is not None] 218 y_err_list = [y[0].dvalue for y in self.content if y is not None] 219 @@ -465,9 +465,9 @@ 222 def symmetric(self): 223 """ Symmetrize the correlator around x0=0.""" 224 if self.N != 1: - 225 raise Exception('symmetric cannot be safely applied to multi-dimensional correlators.') + 225 raise ValueError('symmetric cannot be safely applied to multi-dimensional correlators.') 226 if self.T % 2 != 0: - 227 raise Exception("Can not symmetrize odd T") + 227 raise ValueError("Can not symmetrize odd T") 228 229 if self.content[0] is not None: 230 if np.argmax(np.abs([o[0].value if o is not None else 0 for o in self.content])) != 0: @@ -480,7 +480,7 @@ 237 else: 238 newcontent.append(0.5 * (self.content[t] + self.content[self.T - t])) 239 if (all([x is None for x in newcontent])): - 240 raise Exception("Corr could not be symmetrized: No redundant values") + 240 raise ValueError("Corr could not be symmetrized: No redundant values") 241 return Corr(newcontent, prange=self.prange) 242 243 def anti_symmetric(self): @@ -488,7 +488,7 @@ 245 if self.N != 1: 246 raise TypeError('anti_symmetric cannot be safely applied to multi-dimensional correlators.') 247 if self.T % 2 != 0: - 248 raise Exception("Can not symmetrize odd T") + 248 raise ValueError("Can not symmetrize odd T") 249 250 test = 1 * self 251 test.gamma_method() @@ -502,7 +502,7 @@ 259 else: 260 newcontent.append(0.5 * (self.content[t] - self.content[self.T - t])) 261 if (all([x is None for x in newcontent])): - 262 raise Exception("Corr could not be symmetrized: No redundant values") + 262 raise ValueError("Corr could not be symmetrized: No redundant values") 263 return Corr(newcontent, prange=self.prange) 264 265 def is_matrix_symmetric(self): @@ -535,7 +535,7 @@ 292 def matrix_symmetric(self): 293 """Symmetrizes the correlator matrices on every timeslice.""" 294 if self.N == 1: - 295 raise Exception("Trying to symmetrize a correlator matrix, that already has N=1.") + 295 raise ValueError("Trying to symmetrize a correlator matrix, that already has N=1.") 296 if self.is_matrix_symmetric(): 297 return 1.0 * self 298 else: @@ -579,10 +579,10 @@ 336 ''' 337 338 if self.N == 1: - 339 raise Exception("GEVP methods only works on correlator matrices and not single correlators.") + 339 raise ValueError("GEVP methods only works on correlator matrices and not single correlators.") 340 if ts is not None: 341 if (ts <= t0): - 342 raise Exception("ts has to be larger than t0.") + 342 raise ValueError("ts has to be larger than t0.") 343 344 if "sorted_list" in kwargs: 345 warnings.warn("Argument 'sorted_list' is deprecated, use 'sort' instead.", DeprecationWarning) @@ -614,9 +614,9 @@ 371 372 if sort is None: 373 if (ts is None): - 374 raise Exception("ts is required if sort=None.") + 374 raise ValueError("ts is required if sort=None.") 375 if (self.content[t0] is None) or (self.content[ts] is None): - 376 raise Exception("Corr not defined at t0/ts.") + 376 raise ValueError("Corr not defined at t0/ts.") 377 Gt = _get_mat_at_t(ts) 378 reordered_vecs = _GEVP_solver(Gt, G0, method=method, chol_inv=chol_inv) 379 if kwargs.get('auto_gamma', False) and vector_obs: @@ -634,14 +634,14 @@ 391 all_vecs.append(None) 392 if sort == "Eigenvector": 393 if ts is None: - 394 raise Exception("ts is required for the Eigenvector sorting method.") + 394 raise ValueError("ts is required for the Eigenvector sorting method.") 395 all_vecs = _sort_vectors(all_vecs, ts) 396 397 reordered_vecs = [[v[s] if v is not None else None for v in all_vecs] for s in range(self.N)] 398 if kwargs.get('auto_gamma', False) and vector_obs: 399 [[[o.gm() for o in evn] for evn in ev if evn is not None] for ev in reordered_vecs] 400 else: - 401 raise Exception("Unknown value for 'sort'. Choose 'Eigenvalue', 'Eigenvector' or None.") + 401 raise ValueError("Unknown value for 'sort'. Choose 'Eigenvalue', 'Eigenvector' or None.") 402 403 if "state" in kwargs: 404 return reordered_vecs[kwargs.get("state")] @@ -678,7 +678,7 @@ 435 """ 436 437 if self.N != 1: - 438 raise Exception("Multi-operator Prony not implemented!") + 438 raise NotImplementedError("Multi-operator Prony not implemented!") 439 440 array = np.empty([N, N], dtype="object") 441 new_content = [] @@ -745,7 +745,7 @@ 502 correlator or a Corr of same length. 503 """ 504 if self.N != 1: - 505 raise Exception("Only one-dimensional correlators can be safely correlated.") + 505 raise ValueError("Only one-dimensional correlators can be safely correlated.") 506 new_content = [] 507 for x0, t_slice in enumerate(self.content): 508 if _check_for_none(self, t_slice): @@ -759,7 +759,7 @@ 516 elif isinstance(partner, Obs): # Should this include CObs? 517 new_content.append(np.array([correlate(o, partner) for o in t_slice])) 518 else: - 519 raise Exception("Can only correlate with an Obs or a Corr.") + 519 raise TypeError("Can only correlate with an Obs or a Corr.") 520 521 return Corr(new_content) 522 @@ -826,7 +826,7 @@ 583 Available choice: symmetric, forward, backward, improved, log, default: symmetric 584 """ 585 if self.N != 1: - 586 raise Exception("deriv only implemented for one-dimensional correlators.") + 586 raise ValueError("deriv only implemented for one-dimensional correlators.") 587 if variant == "symmetric": 588 newcontent = [] 589 for t in range(1, self.T - 1): @@ -835,7 +835,7 @@ 592 else: 593 newcontent.append(0.5 * (self.content[t + 1] - self.content[t - 1])) 594 if (all([x is None for x in newcontent])): - 595 raise Exception('Derivative is undefined at all timeslices') + 595 raise ValueError('Derivative is undefined at all timeslices') 596 return Corr(newcontent, padding=[1, 1]) 597 elif variant == "forward": 598 newcontent = [] @@ -845,7 +845,7 @@ 602 else: 603 newcontent.append(self.content[t + 1] - self.content[t]) 604 if (all([x is None for x in newcontent])): - 605 raise Exception("Derivative is undefined at all timeslices") + 605 raise ValueError("Derivative is undefined at all timeslices") 606 return Corr(newcontent, padding=[0, 1]) 607 elif variant == "backward": 608 newcontent = [] @@ -855,7 +855,7 @@ 612 else: 613 newcontent.append(self.content[t] - self.content[t - 1]) 614 if (all([x is None for x in newcontent])): - 615 raise Exception("Derivative is undefined at all timeslices") + 615 raise ValueError("Derivative is undefined at all timeslices") 616 return Corr(newcontent, padding=[1, 0]) 617 elif variant == "improved": 618 newcontent = [] @@ -865,7 +865,7 @@ 622 else: 623 newcontent.append((1 / 12) * (self.content[t - 2] - 8 * self.content[t - 1] + 8 * self.content[t + 1] - self.content[t + 2])) 624 if (all([x is None for x in newcontent])): - 625 raise Exception('Derivative is undefined at all timeslices') + 625 raise ValueError('Derivative is undefined at all timeslices') 626 return Corr(newcontent, padding=[2, 2]) 627 elif variant == 'log': 628 newcontent = [] @@ -875,11 +875,11 @@ 632 else: 633 newcontent.append(np.log(self.content[t])) 634 if (all([x is None for x in newcontent])): - 635 raise Exception("Log is undefined at all timeslices") + 635 raise ValueError("Log is undefined at all timeslices") 636 logcorr = Corr(newcontent) 637 return self * logcorr.deriv('symmetric') 638 else: - 639 raise Exception("Unknown variant.") + 639 raise ValueError("Unknown variant.") 640 641 def second_deriv(self, variant="symmetric"): 642 r"""Return the second derivative of the correlator with respect to x0. @@ -899,7 +899,7 @@ 656 $$f(x) = \tilde{\partial}^2_0 log(f(x_0))+(\tilde{\partial}_0 log(f(x_0)))^2$$ 657 """ 658 if self.N != 1: - 659 raise Exception("second_deriv only implemented for one-dimensional correlators.") + 659 raise ValueError("second_deriv only implemented for one-dimensional correlators.") 660 if variant == "symmetric": 661 newcontent = [] 662 for t in range(1, self.T - 1): @@ -908,7 +908,7 @@ 665 else: 666 newcontent.append((self.content[t + 1] - 2 * self.content[t] + self.content[t - 1])) 667 if (all([x is None for x in newcontent])): - 668 raise Exception("Derivative is undefined at all timeslices") + 668 raise ValueError("Derivative is undefined at all timeslices") 669 return Corr(newcontent, padding=[1, 1]) 670 elif variant == "big_symmetric": 671 newcontent = [] @@ -918,7 +918,7 @@ 675 else: 676 newcontent.append((self.content[t + 2] - 2 * self.content[t] + self.content[t - 2]) / 4) 677 if (all([x is None for x in newcontent])): - 678 raise Exception("Derivative is undefined at all timeslices") + 678 raise ValueError("Derivative is undefined at all timeslices") 679 return Corr(newcontent, padding=[2, 2]) 680 elif variant == "improved": 681 newcontent = [] @@ -928,7 +928,7 @@ 685 else: 686 newcontent.append((1 / 12) * (-self.content[t + 2] + 16 * self.content[t + 1] - 30 * self.content[t] + 16 * self.content[t - 1] - self.content[t - 2])) 687 if (all([x is None for x in newcontent])): - 688 raise Exception("Derivative is undefined at all timeslices") + 688 raise ValueError("Derivative is undefined at all timeslices") 689 return Corr(newcontent, padding=[2, 2]) 690 elif variant == 'log': 691 newcontent = [] @@ -938,11 +938,11 @@ 695 else: 696 newcontent.append(np.log(self.content[t])) 697 if (all([x is None for x in newcontent])): - 698 raise Exception("Log is undefined at all timeslices") + 698 raise ValueError("Log is undefined at all timeslices") 699 logcorr = Corr(newcontent) 700 return self * (logcorr.second_deriv('symmetric') + (logcorr.deriv('symmetric'))**2) 701 else: - 702 raise Exception("Unknown variant.") + 702 raise ValueError("Unknown variant.") 703 704 def m_eff(self, variant='log', guess=1.0): 705 """Returns the effective mass of the correlator as correlator object @@ -971,7 +971,7 @@ 728 else: 729 newcontent.append(self.content[t] / self.content[t + 1]) 730 if (all([x is None for x in newcontent])): - 731 raise Exception('m_eff is undefined at all timeslices') + 731 raise ValueError('m_eff is undefined at all timeslices') 732 733 return np.log(Corr(newcontent, padding=[0, 1])) 734 @@ -985,7 +985,7 @@ 742 else: 743 newcontent.append(self.content[t - 1] / self.content[t + 1]) 744 if (all([x is None for x in newcontent])): - 745 raise Exception('m_eff is undefined at all timeslices') + 745 raise ValueError('m_eff is undefined at all timeslices') 746 747 return np.log(Corr(newcontent, padding=[1, 1])) / 2 748 @@ -1010,7 +1010,7 @@ 767 else: 768 newcontent.append(np.abs(find_root(self.content[t][0] / self.content[t + 1][0], root_function, guess=guess))) 769 if (all([x is None for x in newcontent])): - 770 raise Exception('m_eff is undefined at all timeslices') + 770 raise ValueError('m_eff is undefined at all timeslices') 771 772 return Corr(newcontent, padding=[0, 1]) 773 @@ -1022,11 +1022,11 @@ 779 else: 780 newcontent.append((self.content[t + 1] + self.content[t - 1]) / (2 * self.content[t])) 781 if (all([x is None for x in newcontent])): - 782 raise Exception("m_eff is undefined at all timeslices") + 782 raise ValueError("m_eff is undefined at all timeslices") 783 return np.arccosh(Corr(newcontent, padding=[1, 1])) 784 785 else: - 786 raise Exception('Unknown variant.') + 786 raise ValueError('Unknown variant.') 787 788 def fit(self, function, fitrange=None, silent=False, **kwargs): 789 r'''Fits function to the data @@ -1044,7 +1044,7 @@ 801 Decides whether output is printed to the standard output. 802 ''' 803 if self.N != 1: - 804 raise Exception("Correlator must be projected before fitting") + 804 raise ValueError("Correlator must be projected before fitting") 805 806 if fitrange is None: 807 if self.prange: @@ -1053,12 +1053,12 @@ 810 fitrange = [0, self.T - 1] 811 else: 812 if not isinstance(fitrange, list): - 813 raise Exception("fitrange has to be a list with two elements") + 813 raise TypeError("fitrange has to be a list with two elements") 814 if len(fitrange) != 2: - 815 raise Exception("fitrange has to have exactly two elements [fit_start, fit_stop]") + 815 raise ValueError("fitrange has to have exactly two elements [fit_start, fit_stop]") 816 - 817 xs = np.array([x for x in range(fitrange[0], fitrange[1] + 1) if not self.content[x] is None]) - 818 ys = np.array([self.content[x][0] for x in range(fitrange[0], fitrange[1] + 1) if not self.content[x] is None]) + 817 xs = np.array([x for x in range(fitrange[0], fitrange[1] + 1) if self.content[x] is not None]) + 818 ys = np.array([self.content[x][0] for x in range(fitrange[0], fitrange[1] + 1) if self.content[x] is not None]) 819 result = least_squares(xs, ys, function, silent=silent, **kwargs) 820 return result 821 @@ -1083,9 +1083,9 @@ 840 else: 841 raise Exception("no plateau range provided") 842 if self.N != 1: - 843 raise Exception("Correlator must be projected before getting a plateau.") + 843 raise ValueError("Correlator must be projected before getting a plateau.") 844 if (all([self.content[t] is None for t in range(plateau_range[0], plateau_range[1] + 1)])): - 845 raise Exception("plateau is undefined at all timeslices in plateaurange.") + 845 raise ValueError("plateau is undefined at all timeslices in plateaurange.") 846 if auto_gamma: 847 self.gamma_method() 848 if method == "fit": @@ -1097,16 +1097,16 @@ 854 return returnvalue 855 856 else: - 857 raise Exception("Unsupported plateau method: " + method) + 857 raise ValueError("Unsupported plateau method: " + method) 858 859 def set_prange(self, prange): 860 """Sets the attribute prange of the Corr object.""" 861 if not len(prange) == 2: - 862 raise Exception("prange must be a list or array with two values") + 862 raise ValueError("prange must be a list or array with two values") 863 if not ((isinstance(prange[0], int)) and (isinstance(prange[1], int))): - 864 raise Exception("Start and end point must be integers") + 864 raise TypeError("Start and end point must be integers") 865 if not (0 <= prange[0] <= self.T and 0 <= prange[1] <= self.T and prange[0] <= prange[1]): - 866 raise Exception("Start and end point must define a range in the interval 0,T") + 866 raise ValueError("Start and end point must define a range in the interval 0,T") 867 868 self.prange = prange 869 return @@ -1143,7 +1143,7 @@ 900 Optional title of the figure. 901 """ 902 if self.N != 1: - 903 raise Exception("Correlator must be projected before plotting") + 903 raise ValueError("Correlator must be projected before plotting") 904 905 if auto_gamma: 906 self.gamma_method() @@ -1184,7 +1184,7 @@ 941 hide_from = None 942 ax1.errorbar(x[:hide_from], y[:hide_from], y_err[:hide_from], label=corr.tag, mfc=plt.rcParams['axes.facecolor']) 943 else: - 944 raise Exception("'comp' must be a correlator or a list of correlators.") + 944 raise TypeError("'comp' must be a correlator or a list of correlators.") 945 946 if plateau: 947 if isinstance(plateau, Obs): @@ -1193,14 +1193,14 @@ 950 ax1.axhline(y=plateau.value, linewidth=2, color=plt.rcParams['text.color'], alpha=0.6, marker=',', ls='--', label=str(plateau)) 951 ax1.axhspan(plateau.value - plateau.dvalue, plateau.value + plateau.dvalue, alpha=0.25, color=plt.rcParams['text.color'], ls='-') 952 else: - 953 raise Exception("'plateau' must be an Obs") + 953 raise TypeError("'plateau' must be an Obs") 954 955 if references: 956 if isinstance(references, list): 957 for ref in references: 958 ax1.axhline(y=ref, linewidth=1, color=plt.rcParams['text.color'], alpha=0.6, marker=',', ls='--') 959 else: - 960 raise Exception("'references' must be a list of floating pint values.") + 960 raise TypeError("'references' must be a list of floating pint values.") 961 962 if self.prange: 963 ax1.axvline(self.prange[0], 0, 1, ls='-', marker=',', color="black", zorder=0) @@ -1234,7 +1234,7 @@ 991 if isinstance(save, str): 992 fig.savefig(save, bbox_inches='tight') 993 else: - 994 raise Exception("'save' has to be a string.") + 994 raise TypeError("'save' has to be a string.") 995 996 def spaghetti_plot(self, logscale=True): 997 """Produces a spaghetti plot of the correlator suited to monitor exceptional configurations. @@ -1245,7 +1245,7 @@ 1002 Determines whether the scale of the y-axis is logarithmic or standard. 1003 """ 1004 if self.N != 1: -1005 raise Exception("Correlator needs to be projected first.") +1005 raise ValueError("Correlator needs to be projected first.") 1006 1007 mc_names = list(set([item for sublist in [sum(map(o[0].e_content.get, o[0].mc_names), []) for o in self.content if o is not None] for item in sublist])) 1008 x0_vals = [n for (n, o) in zip(np.arange(self.T), self.content) if o is not None] @@ -1287,7 +1287,7 @@ 1044 elif datatype == "pickle": 1045 dump_object(self, filename, **kwargs) 1046 else: -1047 raise Exception("Unknown datatype " + str(datatype)) +1047 raise ValueError("Unknown datatype " + str(datatype)) 1048 1049 def print(self, print_range=None): 1050 print(self.__repr__(print_range)) @@ -1337,7 +1337,7 @@ 1094 def __add__(self, y): 1095 if isinstance(y, Corr): 1096 if ((self.N != y.N) or (self.T != y.T)): -1097 raise Exception("Addition of Corrs with different shape") +1097 raise ValueError("Addition of Corrs with different shape") 1098 newcontent = [] 1099 for t in range(self.T): 1100 if _check_for_none(self, self.content[t]) or _check_for_none(y, y.content[t]): @@ -1365,7 +1365,7 @@ 1122 def __mul__(self, y): 1123 if isinstance(y, Corr): 1124 if not ((self.N == 1 or y.N == 1 or self.N == y.N) and self.T == y.T): -1125 raise Exception("Multiplication of Corr object requires N=N or N=1 and T=T") +1125 raise ValueError("Multiplication of Corr object requires N=N or N=1 and T=T") 1126 newcontent = [] 1127 for t in range(self.T): 1128 if _check_for_none(self, self.content[t]) or _check_for_none(y, y.content[t]): @@ -1436,7 +1436,7 @@ 1193 def __truediv__(self, y): 1194 if isinstance(y, Corr): 1195 if not ((self.N == 1 or y.N == 1 or self.N == y.N) and self.T == y.T): -1196 raise Exception("Multiplication of Corr object requires N=N or N=1 and T=T") +1196 raise ValueError("Multiplication of Corr object requires N=N or N=1 and T=T") 1197 newcontent = [] 1198 for t in range(self.T): 1199 if _check_for_none(self, self.content[t]) or _check_for_none(y, y.content[t]): @@ -1450,16 +1450,16 @@ 1207 newcontent[t] = None 1208 1209 if all([item is None for item in newcontent]): -1210 raise Exception("Division returns completely undefined correlator") +1210 raise ValueError("Division returns completely undefined correlator") 1211 return Corr(newcontent) 1212 1213 elif isinstance(y, (Obs, CObs)): 1214 if isinstance(y, Obs): 1215 if y.value == 0: -1216 raise Exception('Division by zero will return undefined correlator') +1216 raise ValueError('Division by zero will return undefined correlator') 1217 if isinstance(y, CObs): 1218 if y.is_zero(): -1219 raise Exception('Division by zero will return undefined correlator') +1219 raise ValueError('Division by zero will return undefined correlator') 1220 1221 newcontent = [] 1222 for t in range(self.T): @@ -1471,7 +1471,7 @@ 1228 1229 elif isinstance(y, (int, float)): 1230 if y == 0: -1231 raise Exception('Division by zero will return undefined correlator') +1231 raise ValueError('Division by zero will return undefined correlator') 1232 newcontent = [] 1233 for t in range(self.T): 1234 if _check_for_none(self, self.content[t]): @@ -1527,7 +1527,7 @@ 1284 if np.isnan(tmp_sum.value): 1285 newcontent[t] = None 1286 if all([item is None for item in newcontent]): -1287 raise Exception('Operation returns undefined correlator') +1287 raise ValueError('Operation returns undefined correlator') 1288 return Corr(newcontent) 1289 1290 def sin(self): @@ -1635,13 +1635,13 @@ 1392 ''' 1393 1394 if self.N == 1: -1395 raise Exception('Method cannot be applied to one-dimensional correlators.') +1395 raise ValueError('Method cannot be applied to one-dimensional correlators.') 1396 if basematrix is None: 1397 basematrix = self 1398 if Ntrunc >= basematrix.N: -1399 raise Exception('Cannot truncate using Ntrunc <= %d' % (basematrix.N)) +1399 raise ValueError('Cannot truncate using Ntrunc <= %d' % (basematrix.N)) 1400 if basematrix.N != self.N: -1401 raise Exception('basematrix and targetmatrix have to be of the same size.') +1401 raise ValueError('basematrix and targetmatrix have to be of the same size.') 1402 1403 evecs = basematrix.GEVP(t0proj, tproj, sort=None)[:Ntrunc] 1404 @@ -1859,7 +1859,7 @@ 102 self.N = 1 103 elif all([isinstance(item, np.ndarray) or item is None for item in data_input]) and any([isinstance(item, np.ndarray) for item in data_input]): 104 self.content = data_input - 105 noNull = [a for a in self.content if not (a is None)] # To check if the matrices are correct for all undefined elements + 105 noNull = [a for a in self.content if a is not None] # To check if the matrices are correct for all undefined elements 106 self.N = noNull[0].shape[0] 107 if self.N > 1 and noNull[0].shape[0] != noNull[0].shape[1]: 108 raise ValueError("Smearing matrices are not NxN.") @@ -1899,7 +1899,7 @@ 142 def gamma_method(self, **kwargs): 143 """Apply the gamma method to the content of the Corr.""" 144 for item in self.content: - 145 if not (item is None): + 145 if item is not None: 146 if self.N == 1: 147 item[0].gamma_method(**kwargs) 148 else: @@ -1917,7 +1917,7 @@ 160 By default it will return the lowest source, which usually means unsmeared-unsmeared (0,0), but it does not have to 161 """ 162 if self.N == 1: - 163 raise Exception("Trying to project a Corr, that already has N=1.") + 163 raise ValueError("Trying to project a Corr, that already has N=1.") 164 165 if vector_l is None: 166 vector_l, vector_r = np.asarray([1.] + (self.N - 1) * [0.]), np.asarray([1.] + (self.N - 1) * [0.]) @@ -1925,16 +1925,16 @@ 168 vector_r = vector_l 169 if isinstance(vector_l, list) and not isinstance(vector_r, list): 170 if len(vector_l) != self.T: - 171 raise Exception("Length of vector list must be equal to T") + 171 raise ValueError("Length of vector list must be equal to T") 172 vector_r = [vector_r] * self.T 173 if isinstance(vector_r, list) and not isinstance(vector_l, list): 174 if len(vector_r) != self.T: - 175 raise Exception("Length of vector list must be equal to T") + 175 raise ValueError("Length of vector list must be equal to T") 176 vector_l = [vector_l] * self.T 177 178 if not isinstance(vector_l, list): 179 if not vector_l.shape == vector_r.shape == (self.N,): - 180 raise Exception("Vectors are of wrong shape!") + 180 raise ValueError("Vectors are of wrong shape!") 181 if normalize: 182 vector_l, vector_r = vector_l / np.sqrt((vector_l @ vector_l)), vector_r / np.sqrt(vector_r @ vector_r) 183 newcontent = [None if _check_for_none(self, item) else np.asarray([vector_l.T @ item @ vector_r]) for item in self.content] @@ -1959,7 +1959,7 @@ 202 Second index to be picked. 203 """ 204 if self.N == 1: - 205 raise Exception("Trying to pick item from projected Corr") + 205 raise ValueError("Trying to pick item from projected Corr") 206 newcontent = [None if (item is None) else item[i, j] for item in self.content] 207 return Corr(newcontent) 208 @@ -1970,8 +1970,8 @@ 213 timeslice and the error on each timeslice. 214 """ 215 if self.N != 1: - 216 raise Exception("Can only make Corr[N=1] plottable") - 217 x_list = [x for x in range(self.T) if not self.content[x] is None] + 216 raise ValueError("Can only make Corr[N=1] plottable") + 217 x_list = [x for x in range(self.T) if self.content[x] is not None] 218 y_list = [y[0].value for y in self.content if y is not None] 219 y_err_list = [y[0].dvalue for y in self.content if y is not None] 220 @@ -1980,9 +1980,9 @@ 223 def symmetric(self): 224 """ Symmetrize the correlator around x0=0.""" 225 if self.N != 1: - 226 raise Exception('symmetric cannot be safely applied to multi-dimensional correlators.') + 226 raise ValueError('symmetric cannot be safely applied to multi-dimensional correlators.') 227 if self.T % 2 != 0: - 228 raise Exception("Can not symmetrize odd T") + 228 raise ValueError("Can not symmetrize odd T") 229 230 if self.content[0] is not None: 231 if np.argmax(np.abs([o[0].value if o is not None else 0 for o in self.content])) != 0: @@ -1995,7 +1995,7 @@ 238 else: 239 newcontent.append(0.5 * (self.content[t] + self.content[self.T - t])) 240 if (all([x is None for x in newcontent])): - 241 raise Exception("Corr could not be symmetrized: No redundant values") + 241 raise ValueError("Corr could not be symmetrized: No redundant values") 242 return Corr(newcontent, prange=self.prange) 243 244 def anti_symmetric(self): @@ -2003,7 +2003,7 @@ 246 if self.N != 1: 247 raise TypeError('anti_symmetric cannot be safely applied to multi-dimensional correlators.') 248 if self.T % 2 != 0: - 249 raise Exception("Can not symmetrize odd T") + 249 raise ValueError("Can not symmetrize odd T") 250 251 test = 1 * self 252 test.gamma_method() @@ -2017,7 +2017,7 @@ 260 else: 261 newcontent.append(0.5 * (self.content[t] - self.content[self.T - t])) 262 if (all([x is None for x in newcontent])): - 263 raise Exception("Corr could not be symmetrized: No redundant values") + 263 raise ValueError("Corr could not be symmetrized: No redundant values") 264 return Corr(newcontent, prange=self.prange) 265 266 def is_matrix_symmetric(self): @@ -2050,7 +2050,7 @@ 293 def matrix_symmetric(self): 294 """Symmetrizes the correlator matrices on every timeslice.""" 295 if self.N == 1: - 296 raise Exception("Trying to symmetrize a correlator matrix, that already has N=1.") + 296 raise ValueError("Trying to symmetrize a correlator matrix, that already has N=1.") 297 if self.is_matrix_symmetric(): 298 return 1.0 * self 299 else: @@ -2094,10 +2094,10 @@ 337 ''' 338 339 if self.N == 1: - 340 raise Exception("GEVP methods only works on correlator matrices and not single correlators.") + 340 raise ValueError("GEVP methods only works on correlator matrices and not single correlators.") 341 if ts is not None: 342 if (ts <= t0): - 343 raise Exception("ts has to be larger than t0.") + 343 raise ValueError("ts has to be larger than t0.") 344 345 if "sorted_list" in kwargs: 346 warnings.warn("Argument 'sorted_list' is deprecated, use 'sort' instead.", DeprecationWarning) @@ -2129,9 +2129,9 @@ 372 373 if sort is None: 374 if (ts is None): - 375 raise Exception("ts is required if sort=None.") + 375 raise ValueError("ts is required if sort=None.") 376 if (self.content[t0] is None) or (self.content[ts] is None): - 377 raise Exception("Corr not defined at t0/ts.") + 377 raise ValueError("Corr not defined at t0/ts.") 378 Gt = _get_mat_at_t(ts) 379 reordered_vecs = _GEVP_solver(Gt, G0, method=method, chol_inv=chol_inv) 380 if kwargs.get('auto_gamma', False) and vector_obs: @@ -2149,14 +2149,14 @@ 392 all_vecs.append(None) 393 if sort == "Eigenvector": 394 if ts is None: - 395 raise Exception("ts is required for the Eigenvector sorting method.") + 395 raise ValueError("ts is required for the Eigenvector sorting method.") 396 all_vecs = _sort_vectors(all_vecs, ts) 397 398 reordered_vecs = [[v[s] if v is not None else None for v in all_vecs] for s in range(self.N)] 399 if kwargs.get('auto_gamma', False) and vector_obs: 400 [[[o.gm() for o in evn] for evn in ev if evn is not None] for ev in reordered_vecs] 401 else: - 402 raise Exception("Unknown value for 'sort'. Choose 'Eigenvalue', 'Eigenvector' or None.") + 402 raise ValueError("Unknown value for 'sort'. Choose 'Eigenvalue', 'Eigenvector' or None.") 403 404 if "state" in kwargs: 405 return reordered_vecs[kwargs.get("state")] @@ -2193,7 +2193,7 @@ 436 """ 437 438 if self.N != 1: - 439 raise Exception("Multi-operator Prony not implemented!") + 439 raise NotImplementedError("Multi-operator Prony not implemented!") 440 441 array = np.empty([N, N], dtype="object") 442 new_content = [] @@ -2260,7 +2260,7 @@ 503 correlator or a Corr of same length. 504 """ 505 if self.N != 1: - 506 raise Exception("Only one-dimensional correlators can be safely correlated.") + 506 raise ValueError("Only one-dimensional correlators can be safely correlated.") 507 new_content = [] 508 for x0, t_slice in enumerate(self.content): 509 if _check_for_none(self, t_slice): @@ -2274,7 +2274,7 @@ 517 elif isinstance(partner, Obs): # Should this include CObs? 518 new_content.append(np.array([correlate(o, partner) for o in t_slice])) 519 else: - 520 raise Exception("Can only correlate with an Obs or a Corr.") + 520 raise TypeError("Can only correlate with an Obs or a Corr.") 521 522 return Corr(new_content) 523 @@ -2341,7 +2341,7 @@ 584 Available choice: symmetric, forward, backward, improved, log, default: symmetric 585 """ 586 if self.N != 1: - 587 raise Exception("deriv only implemented for one-dimensional correlators.") + 587 raise ValueError("deriv only implemented for one-dimensional correlators.") 588 if variant == "symmetric": 589 newcontent = [] 590 for t in range(1, self.T - 1): @@ -2350,7 +2350,7 @@ 593 else: 594 newcontent.append(0.5 * (self.content[t + 1] - self.content[t - 1])) 595 if (all([x is None for x in newcontent])): - 596 raise Exception('Derivative is undefined at all timeslices') + 596 raise ValueError('Derivative is undefined at all timeslices') 597 return Corr(newcontent, padding=[1, 1]) 598 elif variant == "forward": 599 newcontent = [] @@ -2360,7 +2360,7 @@ 603 else: 604 newcontent.append(self.content[t + 1] - self.content[t]) 605 if (all([x is None for x in newcontent])): - 606 raise Exception("Derivative is undefined at all timeslices") + 606 raise ValueError("Derivative is undefined at all timeslices") 607 return Corr(newcontent, padding=[0, 1]) 608 elif variant == "backward": 609 newcontent = [] @@ -2370,7 +2370,7 @@ 613 else: 614 newcontent.append(self.content[t] - self.content[t - 1]) 615 if (all([x is None for x in newcontent])): - 616 raise Exception("Derivative is undefined at all timeslices") + 616 raise ValueError("Derivative is undefined at all timeslices") 617 return Corr(newcontent, padding=[1, 0]) 618 elif variant == "improved": 619 newcontent = [] @@ -2380,7 +2380,7 @@ 623 else: 624 newcontent.append((1 / 12) * (self.content[t - 2] - 8 * self.content[t - 1] + 8 * self.content[t + 1] - self.content[t + 2])) 625 if (all([x is None for x in newcontent])): - 626 raise Exception('Derivative is undefined at all timeslices') + 626 raise ValueError('Derivative is undefined at all timeslices') 627 return Corr(newcontent, padding=[2, 2]) 628 elif variant == 'log': 629 newcontent = [] @@ -2390,11 +2390,11 @@ 633 else: 634 newcontent.append(np.log(self.content[t])) 635 if (all([x is None for x in newcontent])): - 636 raise Exception("Log is undefined at all timeslices") + 636 raise ValueError("Log is undefined at all timeslices") 637 logcorr = Corr(newcontent) 638 return self * logcorr.deriv('symmetric') 639 else: - 640 raise Exception("Unknown variant.") + 640 raise ValueError("Unknown variant.") 641 642 def second_deriv(self, variant="symmetric"): 643 r"""Return the second derivative of the correlator with respect to x0. @@ -2414,7 +2414,7 @@ 657 $$f(x) = \tilde{\partial}^2_0 log(f(x_0))+(\tilde{\partial}_0 log(f(x_0)))^2$$ 658 """ 659 if self.N != 1: - 660 raise Exception("second_deriv only implemented for one-dimensional correlators.") + 660 raise ValueError("second_deriv only implemented for one-dimensional correlators.") 661 if variant == "symmetric": 662 newcontent = [] 663 for t in range(1, self.T - 1): @@ -2423,7 +2423,7 @@ 666 else: 667 newcontent.append((self.content[t + 1] - 2 * self.content[t] + self.content[t - 1])) 668 if (all([x is None for x in newcontent])): - 669 raise Exception("Derivative is undefined at all timeslices") + 669 raise ValueError("Derivative is undefined at all timeslices") 670 return Corr(newcontent, padding=[1, 1]) 671 elif variant == "big_symmetric": 672 newcontent = [] @@ -2433,7 +2433,7 @@ 676 else: 677 newcontent.append((self.content[t + 2] - 2 * self.content[t] + self.content[t - 2]) / 4) 678 if (all([x is None for x in newcontent])): - 679 raise Exception("Derivative is undefined at all timeslices") + 679 raise ValueError("Derivative is undefined at all timeslices") 680 return Corr(newcontent, padding=[2, 2]) 681 elif variant == "improved": 682 newcontent = [] @@ -2443,7 +2443,7 @@ 686 else: 687 newcontent.append((1 / 12) * (-self.content[t + 2] + 16 * self.content[t + 1] - 30 * self.content[t] + 16 * self.content[t - 1] - self.content[t - 2])) 688 if (all([x is None for x in newcontent])): - 689 raise Exception("Derivative is undefined at all timeslices") + 689 raise ValueError("Derivative is undefined at all timeslices") 690 return Corr(newcontent, padding=[2, 2]) 691 elif variant == 'log': 692 newcontent = [] @@ -2453,11 +2453,11 @@ 696 else: 697 newcontent.append(np.log(self.content[t])) 698 if (all([x is None for x in newcontent])): - 699 raise Exception("Log is undefined at all timeslices") + 699 raise ValueError("Log is undefined at all timeslices") 700 logcorr = Corr(newcontent) 701 return self * (logcorr.second_deriv('symmetric') + (logcorr.deriv('symmetric'))**2) 702 else: - 703 raise Exception("Unknown variant.") + 703 raise ValueError("Unknown variant.") 704 705 def m_eff(self, variant='log', guess=1.0): 706 """Returns the effective mass of the correlator as correlator object @@ -2486,7 +2486,7 @@ 729 else: 730 newcontent.append(self.content[t] / self.content[t + 1]) 731 if (all([x is None for x in newcontent])): - 732 raise Exception('m_eff is undefined at all timeslices') + 732 raise ValueError('m_eff is undefined at all timeslices') 733 734 return np.log(Corr(newcontent, padding=[0, 1])) 735 @@ -2500,7 +2500,7 @@ 743 else: 744 newcontent.append(self.content[t - 1] / self.content[t + 1]) 745 if (all([x is None for x in newcontent])): - 746 raise Exception('m_eff is undefined at all timeslices') + 746 raise ValueError('m_eff is undefined at all timeslices') 747 748 return np.log(Corr(newcontent, padding=[1, 1])) / 2 749 @@ -2525,7 +2525,7 @@ 768 else: 769 newcontent.append(np.abs(find_root(self.content[t][0] / self.content[t + 1][0], root_function, guess=guess))) 770 if (all([x is None for x in newcontent])): - 771 raise Exception('m_eff is undefined at all timeslices') + 771 raise ValueError('m_eff is undefined at all timeslices') 772 773 return Corr(newcontent, padding=[0, 1]) 774 @@ -2537,11 +2537,11 @@ 780 else: 781 newcontent.append((self.content[t + 1] + self.content[t - 1]) / (2 * self.content[t])) 782 if (all([x is None for x in newcontent])): - 783 raise Exception("m_eff is undefined at all timeslices") + 783 raise ValueError("m_eff is undefined at all timeslices") 784 return np.arccosh(Corr(newcontent, padding=[1, 1])) 785 786 else: - 787 raise Exception('Unknown variant.') + 787 raise ValueError('Unknown variant.') 788 789 def fit(self, function, fitrange=None, silent=False, **kwargs): 790 r'''Fits function to the data @@ -2559,7 +2559,7 @@ 802 Decides whether output is printed to the standard output. 803 ''' 804 if self.N != 1: - 805 raise Exception("Correlator must be projected before fitting") + 805 raise ValueError("Correlator must be projected before fitting") 806 807 if fitrange is None: 808 if self.prange: @@ -2568,12 +2568,12 @@ 811 fitrange = [0, self.T - 1] 812 else: 813 if not isinstance(fitrange, list): - 814 raise Exception("fitrange has to be a list with two elements") + 814 raise TypeError("fitrange has to be a list with two elements") 815 if len(fitrange) != 2: - 816 raise Exception("fitrange has to have exactly two elements [fit_start, fit_stop]") + 816 raise ValueError("fitrange has to have exactly two elements [fit_start, fit_stop]") 817 - 818 xs = np.array([x for x in range(fitrange[0], fitrange[1] + 1) if not self.content[x] is None]) - 819 ys = np.array([self.content[x][0] for x in range(fitrange[0], fitrange[1] + 1) if not self.content[x] is None]) + 818 xs = np.array([x for x in range(fitrange[0], fitrange[1] + 1) if self.content[x] is not None]) + 819 ys = np.array([self.content[x][0] for x in range(fitrange[0], fitrange[1] + 1) if self.content[x] is not None]) 820 result = least_squares(xs, ys, function, silent=silent, **kwargs) 821 return result 822 @@ -2598,9 +2598,9 @@ 841 else: 842 raise Exception("no plateau range provided") 843 if self.N != 1: - 844 raise Exception("Correlator must be projected before getting a plateau.") + 844 raise ValueError("Correlator must be projected before getting a plateau.") 845 if (all([self.content[t] is None for t in range(plateau_range[0], plateau_range[1] + 1)])): - 846 raise Exception("plateau is undefined at all timeslices in plateaurange.") + 846 raise ValueError("plateau is undefined at all timeslices in plateaurange.") 847 if auto_gamma: 848 self.gamma_method() 849 if method == "fit": @@ -2612,16 +2612,16 @@ 855 return returnvalue 856 857 else: - 858 raise Exception("Unsupported plateau method: " + method) + 858 raise ValueError("Unsupported plateau method: " + method) 859 860 def set_prange(self, prange): 861 """Sets the attribute prange of the Corr object.""" 862 if not len(prange) == 2: - 863 raise Exception("prange must be a list or array with two values") + 863 raise ValueError("prange must be a list or array with two values") 864 if not ((isinstance(prange[0], int)) and (isinstance(prange[1], int))): - 865 raise Exception("Start and end point must be integers") + 865 raise TypeError("Start and end point must be integers") 866 if not (0 <= prange[0] <= self.T and 0 <= prange[1] <= self.T and prange[0] <= prange[1]): - 867 raise Exception("Start and end point must define a range in the interval 0,T") + 867 raise ValueError("Start and end point must define a range in the interval 0,T") 868 869 self.prange = prange 870 return @@ -2658,7 +2658,7 @@ 901 Optional title of the figure. 902 """ 903 if self.N != 1: - 904 raise Exception("Correlator must be projected before plotting") + 904 raise ValueError("Correlator must be projected before plotting") 905 906 if auto_gamma: 907 self.gamma_method() @@ -2699,7 +2699,7 @@ 942 hide_from = None 943 ax1.errorbar(x[:hide_from], y[:hide_from], y_err[:hide_from], label=corr.tag, mfc=plt.rcParams['axes.facecolor']) 944 else: - 945 raise Exception("'comp' must be a correlator or a list of correlators.") + 945 raise TypeError("'comp' must be a correlator or a list of correlators.") 946 947 if plateau: 948 if isinstance(plateau, Obs): @@ -2708,14 +2708,14 @@ 951 ax1.axhline(y=plateau.value, linewidth=2, color=plt.rcParams['text.color'], alpha=0.6, marker=',', ls='--', label=str(plateau)) 952 ax1.axhspan(plateau.value - plateau.dvalue, plateau.value + plateau.dvalue, alpha=0.25, color=plt.rcParams['text.color'], ls='-') 953 else: - 954 raise Exception("'plateau' must be an Obs") + 954 raise TypeError("'plateau' must be an Obs") 955 956 if references: 957 if isinstance(references, list): 958 for ref in references: 959 ax1.axhline(y=ref, linewidth=1, color=plt.rcParams['text.color'], alpha=0.6, marker=',', ls='--') 960 else: - 961 raise Exception("'references' must be a list of floating pint values.") + 961 raise TypeError("'references' must be a list of floating pint values.") 962 963 if self.prange: 964 ax1.axvline(self.prange[0], 0, 1, ls='-', marker=',', color="black", zorder=0) @@ -2749,7 +2749,7 @@ 992 if isinstance(save, str): 993 fig.savefig(save, bbox_inches='tight') 994 else: - 995 raise Exception("'save' has to be a string.") + 995 raise TypeError("'save' has to be a string.") 996 997 def spaghetti_plot(self, logscale=True): 998 """Produces a spaghetti plot of the correlator suited to monitor exceptional configurations. @@ -2760,7 +2760,7 @@ 1003 Determines whether the scale of the y-axis is logarithmic or standard. 1004 """ 1005 if self.N != 1: -1006 raise Exception("Correlator needs to be projected first.") +1006 raise ValueError("Correlator needs to be projected first.") 1007 1008 mc_names = list(set([item for sublist in [sum(map(o[0].e_content.get, o[0].mc_names), []) for o in self.content if o is not None] for item in sublist])) 1009 x0_vals = [n for (n, o) in zip(np.arange(self.T), self.content) if o is not None] @@ -2802,7 +2802,7 @@ 1045 elif datatype == "pickle": 1046 dump_object(self, filename, **kwargs) 1047 else: -1048 raise Exception("Unknown datatype " + str(datatype)) +1048 raise ValueError("Unknown datatype " + str(datatype)) 1049 1050 def print(self, print_range=None): 1051 print(self.__repr__(print_range)) @@ -2852,7 +2852,7 @@ 1095 def __add__(self, y): 1096 if isinstance(y, Corr): 1097 if ((self.N != y.N) or (self.T != y.T)): -1098 raise Exception("Addition of Corrs with different shape") +1098 raise ValueError("Addition of Corrs with different shape") 1099 newcontent = [] 1100 for t in range(self.T): 1101 if _check_for_none(self, self.content[t]) or _check_for_none(y, y.content[t]): @@ -2880,7 +2880,7 @@ 1123 def __mul__(self, y): 1124 if isinstance(y, Corr): 1125 if not ((self.N == 1 or y.N == 1 or self.N == y.N) and self.T == y.T): -1126 raise Exception("Multiplication of Corr object requires N=N or N=1 and T=T") +1126 raise ValueError("Multiplication of Corr object requires N=N or N=1 and T=T") 1127 newcontent = [] 1128 for t in range(self.T): 1129 if _check_for_none(self, self.content[t]) or _check_for_none(y, y.content[t]): @@ -2951,7 +2951,7 @@ 1194 def __truediv__(self, y): 1195 if isinstance(y, Corr): 1196 if not ((self.N == 1 or y.N == 1 or self.N == y.N) and self.T == y.T): -1197 raise Exception("Multiplication of Corr object requires N=N or N=1 and T=T") +1197 raise ValueError("Multiplication of Corr object requires N=N or N=1 and T=T") 1198 newcontent = [] 1199 for t in range(self.T): 1200 if _check_for_none(self, self.content[t]) or _check_for_none(y, y.content[t]): @@ -2965,16 +2965,16 @@ 1208 newcontent[t] = None 1209 1210 if all([item is None for item in newcontent]): -1211 raise Exception("Division returns completely undefined correlator") +1211 raise ValueError("Division returns completely undefined correlator") 1212 return Corr(newcontent) 1213 1214 elif isinstance(y, (Obs, CObs)): 1215 if isinstance(y, Obs): 1216 if y.value == 0: -1217 raise Exception('Division by zero will return undefined correlator') +1217 raise ValueError('Division by zero will return undefined correlator') 1218 if isinstance(y, CObs): 1219 if y.is_zero(): -1220 raise Exception('Division by zero will return undefined correlator') +1220 raise ValueError('Division by zero will return undefined correlator') 1221 1222 newcontent = [] 1223 for t in range(self.T): @@ -2986,7 +2986,7 @@ 1229 1230 elif isinstance(y, (int, float)): 1231 if y == 0: -1232 raise Exception('Division by zero will return undefined correlator') +1232 raise ValueError('Division by zero will return undefined correlator') 1233 newcontent = [] 1234 for t in range(self.T): 1235 if _check_for_none(self, self.content[t]): @@ -3042,7 +3042,7 @@ 1285 if np.isnan(tmp_sum.value): 1286 newcontent[t] = None 1287 if all([item is None for item in newcontent]): -1288 raise Exception('Operation returns undefined correlator') +1288 raise ValueError('Operation returns undefined correlator') 1289 return Corr(newcontent) 1290 1291 def sin(self): @@ -3150,13 +3150,13 @@ 1393 ''' 1394 1395 if self.N == 1: -1396 raise Exception('Method cannot be applied to one-dimensional correlators.') +1396 raise ValueError('Method cannot be applied to one-dimensional correlators.') 1397 if basematrix is None: 1398 basematrix = self 1399 if Ntrunc >= basematrix.N: -1400 raise Exception('Cannot truncate using Ntrunc <= %d' % (basematrix.N)) +1400 raise ValueError('Cannot truncate using Ntrunc <= %d' % (basematrix.N)) 1401 if basematrix.N != self.N: -1402 raise Exception('basematrix and targetmatrix have to be of the same size.') +1402 raise ValueError('basematrix and targetmatrix have to be of the same size.') 1403 1404 evecs = basematrix.GEVP(t0proj, tproj, sort=None)[:Ntrunc] 1405 @@ -3277,7 +3277,7 @@ the temporal extent of the correlator and N is the dimension of the matrix.
102 self.N = 1 103 elif all([isinstance(item, np.ndarray) or item is None for item in data_input]) and any([isinstance(item, np.ndarray) for item in data_input]): 104 self.content = data_input -105 noNull = [a for a in self.content if not (a is None)] # To check if the matrices are correct for all undefined elements +105 noNull = [a for a in self.content if a is not None] # To check if the matrices are correct for all undefined elements 106 self.N = noNull[0].shape[0] 107 if self.N > 1 and noNull[0].shape[0] != noNull[0].shape[1]: 108 raise ValueError("Smearing matrices are not NxN.") @@ -3398,7 +3398,7 @@ region identified for this correlator.142 def gamma_method(self, **kwargs): 143 """Apply the gamma method to the content of the Corr.""" 144 for item in self.content: -145 if not (item is None): +145 if item is not None: 146 if self.N == 1: 147 item[0].gamma_method(**kwargs) 148 else: @@ -3427,7 +3427,7 @@ region identified for this correlator.@@ -3563,8 +3563,8 @@ Second index to be picked. 213 timeslice and the error on each timeslice. 214 """ 215 if self.N != 1: -216 raise Exception("Can only make Corr[N=1] plottable") -217 x_list = [x for x in range(self.T) if not self.content[x] is None] +216 raise ValueError("Can only make Corr[N=1] plottable") +217 x_list = [x for x in range(self.T) if self.content[x] is not None] 218 y_list = [y[0].value for y in self.content if y is not None] 219 y_err_list = [y[0].dvalue for y in self.content if y is not None] 220 @@ -3594,9 +3594,9 @@ timeslice and the error on each timeslice.142 def gamma_method(self, **kwargs): 143 """Apply the gamma method to the content of the Corr.""" 144 for item in self.content: -145 if not (item is None): +145 if item is not None: 146 if self.N == 1: 147 item[0].gamma_method(**kwargs) 148 else: @@ -3461,7 +3461,7 @@ region identified for this correlator. 160 By default it will return the lowest source, which usually means unsmeared-unsmeared (0,0), but it does not have to 161 """ 162 if self.N == 1: -163 raise Exception("Trying to project a Corr, that already has N=1.") +163 raise ValueError("Trying to project a Corr, that already has N=1.") 164 165 if vector_l is None: 166 vector_l, vector_r = np.asarray([1.] + (self.N - 1) * [0.]), np.asarray([1.] + (self.N - 1) * [0.]) @@ -3469,16 +3469,16 @@ region identified for this correlator. 168 vector_r = vector_l 169 if isinstance(vector_l, list) and not isinstance(vector_r, list): 170 if len(vector_l) != self.T: -171 raise Exception("Length of vector list must be equal to T") +171 raise ValueError("Length of vector list must be equal to T") 172 vector_r = [vector_r] * self.T 173 if isinstance(vector_r, list) and not isinstance(vector_l, list): 174 if len(vector_r) != self.T: -175 raise Exception("Length of vector list must be equal to T") +175 raise ValueError("Length of vector list must be equal to T") 176 vector_l = [vector_l] * self.T 177 178 if not isinstance(vector_l, list): 179 if not vector_l.shape == vector_r.shape == (self.N,): -180 raise Exception("Vectors are of wrong shape!") +180 raise ValueError("Vectors are of wrong shape!") 181 if normalize: 182 vector_l, vector_r = vector_l / np.sqrt((vector_l @ vector_l)), vector_r / np.sqrt(vector_r @ vector_r) 183 newcontent = [None if _check_for_none(self, item) else np.asarray([vector_l.T @ item @ vector_r]) for item in self.content] @@ -3525,7 +3525,7 @@ By default it will return the lowest source, which usually means unsmeared-unsme 202 Second index to be picked. 203 """ 204 if self.N == 1: -205 raise Exception("Trying to pick item from projected Corr") +205 raise ValueError("Trying to pick item from projected Corr") 206 newcontent = [None if (item is None) else item[i, j] for item in self.content] 207 return Corr(newcontent)@@ -3635,7 +3635,7 @@ timeslice and the error on each timeslice. 246 if self.N != 1: 247 raise TypeError('anti_symmetric cannot be safely applied to multi-dimensional correlators.') 248 if self.T % 2 != 0: -249 raise Exception("Can not symmetrize odd T") +249 raise ValueError("Can not symmetrize odd T") 250 251 test = 1 * self 252 test.gamma_method() @@ -3649,7 +3649,7 @@ timeslice and the error on each timeslice. 260 else: 261 newcontent.append(0.5 * (self.content[t] - self.content[self.T - t])) 262 if (all([x is None for x in newcontent])): -263 raise Exception("Corr could not be symmetrized: No redundant values") +263 raise ValueError("Corr could not be symmetrized: No redundant values") 264 return Corr(newcontent, prange=self.prange)223 def symmetric(self): 224 """ Symmetrize the correlator around x0=0.""" 225 if self.N != 1: -226 raise Exception('symmetric cannot be safely applied to multi-dimensional correlators.') +226 raise ValueError('symmetric cannot be safely applied to multi-dimensional correlators.') 227 if self.T % 2 != 0: -228 raise Exception("Can not symmetrize odd T") +228 raise ValueError("Can not symmetrize odd T") 229 230 if self.content[0] is not None: 231 if np.argmax(np.abs([o[0].value if o is not None else 0 for o in self.content])) != 0: @@ -3609,7 +3609,7 @@ timeslice and the error on each timeslice. 238 else: 239 newcontent.append(0.5 * (self.content[t] + self.content[self.T - t])) 240 if (all([x is None for x in newcontent])): -241 raise Exception("Corr could not be symmetrized: No redundant values") +241 raise ValueError("Corr could not be symmetrized: No redundant values") 242 return Corr(newcontent, prange=self.prange)
293 def matrix_symmetric(self): 294 """Symmetrizes the correlator matrices on every timeslice.""" 295 if self.N == 1: -296 raise Exception("Trying to symmetrize a correlator matrix, that already has N=1.") +296 raise ValueError("Trying to symmetrize a correlator matrix, that already has N=1.") 297 if self.is_matrix_symmetric(): 298 return 1.0 * self 299 else: @@ -3798,10 +3798,10 @@ timeslice and the error on each timeslice. 337 ''' 338 339 if self.N == 1: -340 raise Exception("GEVP methods only works on correlator matrices and not single correlators.") +340 raise ValueError("GEVP methods only works on correlator matrices and not single correlators.") 341 if ts is not None: 342 if (ts <= t0): -343 raise Exception("ts has to be larger than t0.") +343 raise ValueError("ts has to be larger than t0.") 344 345 if "sorted_list" in kwargs: 346 warnings.warn("Argument 'sorted_list' is deprecated, use 'sort' instead.", DeprecationWarning) @@ -3833,9 +3833,9 @@ timeslice and the error on each timeslice. 372 373 if sort is None: 374 if (ts is None): -375 raise Exception("ts is required if sort=None.") +375 raise ValueError("ts is required if sort=None.") 376 if (self.content[t0] is None) or (self.content[ts] is None): -377 raise Exception("Corr not defined at t0/ts.") +377 raise ValueError("Corr not defined at t0/ts.") 378 Gt = _get_mat_at_t(ts) 379 reordered_vecs = _GEVP_solver(Gt, G0, method=method, chol_inv=chol_inv) 380 if kwargs.get('auto_gamma', False) and vector_obs: @@ -3853,14 +3853,14 @@ timeslice and the error on each timeslice. 392 all_vecs.append(None) 393 if sort == "Eigenvector": 394 if ts is None: -395 raise Exception("ts is required for the Eigenvector sorting method.") +395 raise ValueError("ts is required for the Eigenvector sorting method.") 396 all_vecs = _sort_vectors(all_vecs, ts) 397 398 reordered_vecs = [[v[s] if v is not None else None for v in all_vecs] for s in range(self.N)] 399 if kwargs.get('auto_gamma', False) and vector_obs: 400 [[[o.gm() for o in evn] for evn in ev if evn is not None] for ev in reordered_vecs] 401 else: -402 raise Exception("Unknown value for 'sort'. Choose 'Eigenvalue', 'Eigenvector' or None.") +402 raise ValueError("Unknown value for 'sort'. Choose 'Eigenvalue', 'Eigenvector' or None.") 403 404 if "state" in kwargs: 405 return reordered_vecs[kwargs.get("state")] @@ -3983,7 +3983,7 @@ The state one is interested in ordered by energy. The lowest state is zero. 436 """ 437 438 if self.N != 1: -439 raise Exception("Multi-operator Prony not implemented!") +439 raise NotImplementedError("Multi-operator Prony not implemented!") 440 441 array = np.empty([N, N], dtype="object") 442 new_content = [] @@ -4152,7 +4152,7 @@ Offset the equal spacing 503 correlator or a Corr of same length. 504 """ 505 if self.N != 1: -506 raise Exception("Only one-dimensional correlators can be safely correlated.") +506 raise ValueError("Only one-dimensional correlators can be safely correlated.") 507 new_content = [] 508 for x0, t_slice in enumerate(self.content): 509 if _check_for_none(self, t_slice): @@ -4166,7 +4166,7 @@ Offset the equal spacing 517 elif isinstance(partner, Obs): # Should this include CObs? 518 new_content.append(np.array([correlate(o, partner) for o in t_slice])) 519 else: -520 raise Exception("Can only correlate with an Obs or a Corr.") +520 raise TypeError("Can only correlate with an Obs or a Corr.") 521 522 return Corr(new_content)
860 def set_prange(self, prange): 861 """Sets the attribute prange of the Corr object.""" 862 if not len(prange) == 2: -863 raise Exception("prange must be a list or array with two values") +863 raise ValueError("prange must be a list or array with two values") 864 if not ((isinstance(prange[0], int)) and (isinstance(prange[1], int))): -865 raise Exception("Start and end point must be integers") +865 raise TypeError("Start and end point must be integers") 866 if not (0 <= prange[0] <= self.T and 0 <= prange[1] <= self.T and prange[0] <= prange[1]): -867 raise Exception("Start and end point must define a range in the interval 0,T") +867 raise ValueError("Start and end point must define a range in the interval 0,T") 868 869 self.prange = prange 870 return @@ -4808,7 +4808,7 @@ apply gamma_method with default parameters to the Corr. Defaults to None 901 Optional title of the figure. 902 """ 903 if self.N != 1: -904 raise Exception("Correlator must be projected before plotting") +904 raise ValueError("Correlator must be projected before plotting") 905 906 if auto_gamma: 907 self.gamma_method() @@ -4849,7 +4849,7 @@ apply gamma_method with default parameters to the Corr. Defaults to None 942 hide_from = None 943 ax1.errorbar(x[:hide_from], y[:hide_from], y_err[:hide_from], label=corr.tag, mfc=plt.rcParams['axes.facecolor']) 944 else: -945 raise Exception("'comp' must be a correlator or a list of correlators.") +945 raise TypeError("'comp' must be a correlator or a list of correlators.") 946 947 if plateau: 948 if isinstance(plateau, Obs): @@ -4858,14 +4858,14 @@ apply gamma_method with default parameters to the Corr. Defaults to None 951 ax1.axhline(y=plateau.value, linewidth=2, color=plt.rcParams['text.color'], alpha=0.6, marker=',', ls='--', label=str(plateau)) 952 ax1.axhspan(plateau.value - plateau.dvalue, plateau.value + plateau.dvalue, alpha=0.25, color=plt.rcParams['text.color'], ls='-') 953 else: -954 raise Exception("'plateau' must be an Obs") +954 raise TypeError("'plateau' must be an Obs") 955 956 if references: 957 if isinstance(references, list): 958 for ref in references: 959 ax1.axhline(y=ref, linewidth=1, color=plt.rcParams['text.color'], alpha=0.6, marker=',', ls='--') 960 else: -961 raise Exception("'references' must be a list of floating pint values.") +961 raise TypeError("'references' must be a list of floating pint values.") 962 963 if self.prange: 964 ax1.axvline(self.prange[0], 0, 1, ls='-', marker=',', color="black", zorder=0) @@ -4899,7 +4899,7 @@ apply gamma_method with default parameters to the Corr. Defaults to None 992 if isinstance(save, str): 993 fig.savefig(save, bbox_inches='tight') 994 else: -995 raise Exception("'save' has to be a string.") +995 raise TypeError("'save' has to be a string.")
pyerrors.obs.Obs.export_jackkn
5For comparison with other analysis workflows `pyerrors` can also generate jackknife samples from an `Obs` object or import jackknife samples into an `Obs` object.
6See `pyerrors.obs.Obs.export_jackknife` and `pyerrors.obs.import_jackknife` for details.
7'''
- 8from . import bdio
- 9from . import dobs
-10from . import hadrons
-11from . import json
-12from . import misc
-13from . import openQCD
-14from . import pandas
-15from . import sfcf
+ 8from . import bdio as bdio
+ 9from . import dobs as dobs
+10from . import hadrons as hadrons
+11from . import json as json
+12from . import misc as misc
+13from . import openQCD as openQCD
+14from . import pandas as pandas
+15from . import sfcf as sfcf
diff --git a/docs/pyerrors/input/dobs.html b/docs/pyerrors/input/dobs.html
index 6f4dbbcb..b2a872be 100644
--- a/docs/pyerrors/input/dobs.html
+++ b/docs/pyerrors/input/dobs.html
@@ -175,7 +175,7 @@
79 o += space
80 o += li + '\n'
81 if li.startswith('<') and not cm:
- 82 if not '<%s' % ('/') in li:
+ 82 if '<%s' % ('/') not in li:
83 c += 1
84 cm = False
85 return o
@@ -767,7 +767,7 @@
671 o += space
672 o += li + '\n'
673 if li.startswith('<') and not cm:
-674 if not '<%s' % ('/') in li:
+674 if '<%s' % ('/') not in li:
675 c += 1
676 cm = False
677 return o
diff --git a/docs/pyerrors/input/hadrons.html b/docs/pyerrors/input/hadrons.html
index 92219b4d..7512c1f8 100644
--- a/docs/pyerrors/input/hadrons.html
+++ b/docs/pyerrors/input/hadrons.html
@@ -218,7 +218,7 @@
113 infos = []
114 for hd5_file in files:
115 h5file = h5py.File(path + '/' + hd5_file, "r")
-116 if not group + '/' + entry in h5file:
+116 if group + '/' + entry not in h5file:
117 raise Exception("Entry '" + entry + "' not contained in the files.")
118 raw_data = h5file[group + '/' + entry + '/corr']
119 real_data = raw_data[:].view("complex")
@@ -291,7 +291,7 @@
186 for hd5_file in files:
187 h5file = h5py.File(path + '/' + hd5_file, "r")
188 for key in keys:
-189 if not tree + '/' + key in h5file:
+189 if tree + '/' + key not in h5file:
190 raise Exception("Entry '" + key + "' not contained in the files.")
191 raw_data = h5file[tree + '/' + key + '/data']
192 real_data = raw_data[:].astype(np.double)
@@ -792,7 +792,7 @@
114 infos = []
115 for hd5_file in files:
116 h5file = h5py.File(path + '/' + hd5_file, "r")
-117 if not group + '/' + entry in h5file:
+117 if group + '/' + entry not in h5file:
118 raise Exception("Entry '" + entry + "' not contained in the files.")
119 raw_data = h5file[group + '/' + entry + '/corr']
120 real_data = raw_data[:].view("complex")
diff --git a/docs/pyerrors/input/openQCD.html b/docs/pyerrors/input/openQCD.html
index f57e2b3a..0a73c540 100644
--- a/docs/pyerrors/input/openQCD.html
+++ b/docs/pyerrors/input/openQCD.html
@@ -146,7 +146,7 @@
47 Reweighting factors read
48 """
49 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:
51 raise Exception('Unknown openQCD version defined!')
52 print("Working with openQCD version " + version)
53 if 'postfix' in kwargs:
@@ -1460,7 +1460,7 @@
48 Reweighting factors read
49 """
50 known_oqcd_versions = ['1.4', '1.6', '2.0']
- 51 if not (version in known_oqcd_versions):
+ 51 if version not in known_oqcd_versions:
52 raise Exception('Unknown openQCD version defined!')
53 print("Working with openQCD version " + version)
54 if 'postfix' in kwargs:
diff --git a/docs/pyerrors/obs.html b/docs/pyerrors/obs.html
index c68d54d4..cebdb983 100644
--- a/docs/pyerrors/obs.html
+++ b/docs/pyerrors/obs.html
@@ -558,7 +558,7 @@
222 tmp = kwargs.get(kwarg_name)
223 if isinstance(tmp, (int, float)):
224 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.')
226 for e, e_name in enumerate(self.e_names):
227 getattr(self, kwarg_name)[e_name] = tmp
228 else:
@@ -627,7 +627,7 @@
291 texp = self.tau_exp[e_name]
292 # Critical slowing down analysis
293 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")
295 for n in range(1, w_max // 2):
296 _compute_drho(n + 1)
297 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:
@@ -956,7 +956,7 @@
620 if not hasattr(self, 'e_dvalue'):
621 raise Exception('Run the gamma method first.')
622 if np.isclose(0.0, self._dvalue, atol=1e-15):
- 623 raise Exception('Error is 0.0')
+ 623 raise ValueError('Error is 0.0')
624 labels = self.e_names
625 sizes = [self.e_dvalue[name] ** 2 for name in labels] / self._dvalue ** 2
626 fig1, ax1 = plt.subplots()
@@ -995,7 +995,7 @@
659 with open(file_name + '.p', 'wb') as fb:
660 pickle.dump(self, fb)
661 else:
- 662 raise Exception("Unknown datatype " + str(datatype))
+ 662 raise TypeError("Unknown datatype " + str(datatype))
663
664 def export_jackknife(self):
665 """Export jackknife samples from the Obs
@@ -1012,7 +1012,7 @@
676 """
677
678 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.")
680
681 name = self.names[0]
682 full_data = self.deltas[name] + self.r_values[name]
@@ -1047,7 +1047,7 @@
711 should agree with samples from a full bootstrap analysis up to O(1/N).
712 """
713 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.")
715
716 name = self.names[0]
717 length = self.N
@@ -1603,7 +1603,7 @@
1267 if 'man_grad' in kwargs:
1268 deriv = np.asarray(kwargs.get('man_grad'))
1269 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.')
1271 elif kwargs.get('num_grad') is True:
1272 if multi > 0:
1273 raise Exception('Multi mode currently not supported for numerical derivative')
@@ -1669,7 +1669,7 @@
1333 new_covobs = {name: Covobs(0, allcov[name], name, grad=new_grad[name]) for name in new_grad}
1334
1335 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!')
1337 new_samples = []
1338 new_means = []
1339 new_idl = []
@@ -1710,7 +1710,7 @@
1374 Has to be a subset of idx_old.
1375 """
1376 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)))
1378 if type(idx_old) is range and type(idx_new) is range:
1379 if idx_old == idx_new:
1380 return deltas
@@ -1718,7 +1718,7 @@
1382 return deltas
1383 indices = np.intersect1d(idx_old, idx_new, assume_unique=True, return_indices=True)[1]
1384 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')
1386 return np.array(deltas)[indices]
1387
1388
@@ -1740,12 +1740,12 @@
1404 result = []
1405 for i in range(len(obs)):
1406 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!')
1408 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')
1410 for name in obs[i].names:
1411 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))
1413 new_samples = []
1414 w_deltas = {}
1415 for name in sorted(obs[i].names):
@@ -1782,14 +1782,14 @@
1446 """
1447
1448 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))}")
1450 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!')
1452 for name in obs_a.names:
1453 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')
1455 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')
1457
1458 if obs_a.reweighted is True:
1459 warnings.warn("The first observable is already reweighted.", RuntimeWarning)
@@ -1891,7 +1891,7 @@
1555
1556 condn = np.linalg.cond(corr)
1557 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})")
1559 if condn > 1e13:
1560 warnings.warn("Correlation matrix may be ill-conditioned, condition number: {%1.2e}" % (condn), RuntimeWarning)
1561 chol = np.linalg.cholesky(corr)
@@ -1972,7 +1972,7 @@
1636 Number of eigenvalues to be left substantially unchanged
1637 """
1638 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}).")
1640 vals, vec = np.linalg.eigh(corr)
1641 lambda_min = np.mean(vals[:-E])
1642 vals[vals < lambda_min] = lambda_min
@@ -2104,9 +2104,9 @@
1768 """
1769 replist = [item for obs in list_of_obs for item in obs.names]
1770 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)))
1772 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!')
1774 new_dict = {}
1775 idl_dict = {}
1776 for o in list_of_obs:
@@ -2157,7 +2157,7 @@
1821 for i in range(len(means)):
1822 ol.append(covobs_to_obs(Covobs(means[i], cov, name, pos=i, grad=grad)))
1823 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))
1825 if len(ol) == 1:
1826 return ol[0]
1827 return ol
@@ -2173,7 +2173,7 @@
1837
1838 gap = min(gaps)
1839 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)
1841
1842 return gap
1843
@@ -2413,7 +2413,7 @@
223 tmp = kwargs.get(kwarg_name)
224 if isinstance(tmp, (int, float)):
225 if tmp < 0:
-226 raise Exception(kwarg_name + ' has to be larger or equal to 0.')
+226 raise ValueError(kwarg_name + ' has to be larger or equal to 0.')
227 for e, e_name in enumerate(self.e_names):
228 getattr(self, kwarg_name)[e_name] = tmp
229 else:
@@ -2482,7 +2482,7 @@
292 texp = self.tau_exp[e_name]
293 # Critical slowing down analysis
294 if w_max // 2 <= 1:
-295 raise Exception("Need at least 8 samples for tau_exp error analysis")
+295 raise ValueError("Need at least 8 samples for tau_exp error analysis")
296 for n in range(1, w_max // 2):
297 _compute_drho(n + 1)
298 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:
@@ -2811,7 +2811,7 @@
621 if not hasattr(self, 'e_dvalue'):
622 raise Exception('Run the gamma method first.')
623 if np.isclose(0.0, self._dvalue, atol=1e-15):
-624 raise Exception('Error is 0.0')
+624 raise ValueError('Error is 0.0')
625 labels = self.e_names
626 sizes = [self.e_dvalue[name] ** 2 for name in labels] / self._dvalue ** 2
627 fig1, ax1 = plt.subplots()
@@ -2850,7 +2850,7 @@
660 with open(file_name + '.p', 'wb') as fb:
661 pickle.dump(self, fb)
662 else:
-663 raise Exception("Unknown datatype " + str(datatype))
+663 raise TypeError("Unknown datatype " + str(datatype))
664
665 def export_jackknife(self):
666 """Export jackknife samples from the Obs
@@ -2867,7 +2867,7 @@
677 """
678
679 if len(self.names) != 1:
-680 raise Exception("'export_jackknife' is only implemented for Obs defined on one ensemble and replicum.")
+680 raise ValueError("'export_jackknife' is only implemented for Obs defined on one ensemble and replicum.")
681
682 name = self.names[0]
683 full_data = self.deltas[name] + self.r_values[name]
@@ -2902,7 +2902,7 @@
712 should agree with samples from a full bootstrap analysis up to O(1/N).
713 """
714 if len(self.names) != 1:
-715 raise Exception("'export_boostrap' is only implemented for Obs defined on one ensemble and replicum.")
+715 raise ValueError("'export_boostrap' is only implemented for Obs defined on one ensemble and replicum.")
716
717 name = self.names[0]
718 length = self.N
@@ -3610,7 +3610,7 @@ list of ranges or lists on which the samples are defined
223 tmp = kwargs.get(kwarg_name)
224 if isinstance(tmp, (int, float)):
225 if tmp < 0:
-226 raise Exception(kwarg_name + ' has to be larger or equal to 0.')
+226 raise ValueError(kwarg_name + ' has to be larger or equal to 0.')
227 for e, e_name in enumerate(self.e_names):
228 getattr(self, kwarg_name)[e_name] = tmp
229 else:
@@ -3679,7 +3679,7 @@ list of ranges or lists on which the samples are defined
292 texp = self.tau_exp[e_name]
293 # Critical slowing down analysis
294 if w_max // 2 <= 1:
-295 raise Exception("Need at least 8 samples for tau_exp error analysis")
+295 raise ValueError("Need at least 8 samples for tau_exp error analysis")
296 for n in range(1, w_max // 2):
297 _compute_drho(n + 1)
298 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:
@@ -3813,7 +3813,7 @@ of the autocorrelation function (default True)
223 tmp = kwargs.get(kwarg_name)
224 if isinstance(tmp, (int, float)):
225 if tmp < 0:
-226 raise Exception(kwarg_name + ' has to be larger or equal to 0.')
+226 raise ValueError(kwarg_name + ' has to be larger or equal to 0.')
227 for e, e_name in enumerate(self.e_names):
228 getattr(self, kwarg_name)[e_name] = tmp
229 else:
@@ -3882,7 +3882,7 @@ of the autocorrelation function (default True)
292 texp = self.tau_exp[e_name]
293 # Critical slowing down analysis
294 if w_max // 2 <= 1:
-295 raise Exception("Need at least 8 samples for tau_exp error analysis")
+295 raise ValueError("Need at least 8 samples for tau_exp error analysis")
296 for n in range(1, w_max // 2):
297 _compute_drho(n + 1)
298 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:
@@ -4409,7 +4409,7 @@ show expanded history for irregular Monte Carlo chains (default: True).
621 if not hasattr(self, 'e_dvalue'):
622 raise Exception('Run the gamma method first.')
623 if np.isclose(0.0, self._dvalue, atol=1e-15):
-624 raise Exception('Error is 0.0')
+624 raise ValueError('Error is 0.0')
625 labels = self.e_names
626 sizes = [self.e_dvalue[name] ** 2 for name in labels] / self._dvalue ** 2
627 fig1, ax1 = plt.subplots()
@@ -4474,7 +4474,7 @@ saves the figure to a file named 'save' if.
660 with open(file_name + '.p', 'wb') as fb:
661 pickle.dump(self, fb)
662 else:
-663 raise Exception("Unknown datatype " + str(datatype))
+663 raise TypeError("Unknown datatype " + str(datatype))
@@ -4523,7 +4523,7 @@ specifies a custom path for the file (default '.')
677 """
678
679 if len(self.names) != 1:
-680 raise Exception("'export_jackknife' is only implemented for Obs defined on one ensemble and replicum.")
+680 raise ValueError("'export_jackknife' is only implemented for Obs defined on one ensemble and replicum.")
681
682 name = self.names[0]
683 full_data = self.deltas[name] + self.r_values[name]
@@ -4587,7 +4587,7 @@ should agree with samples from a full jackknife analysis up to O(1/N).
712 should agree with samples from a full bootstrap analysis up to O(1/N).
713 """
714 if len(self.names) != 1:
-715 raise Exception("'export_boostrap' is only implemented for Obs defined on one ensemble and replicum.")
+715 raise ValueError("'export_boostrap' is only implemented for Obs defined on one ensemble and replicum.")
716
717 name = self.names[0]
718 length = self.N
@@ -5488,7 +5488,7 @@ should agree with samples from a full bootstrap analysis up to O(1/N).
1268 if 'man_grad' in kwargs:
1269 deriv = np.asarray(kwargs.get('man_grad'))
1270 if new_values.shape + data.shape != deriv.shape:
-1271 raise Exception('Manual derivative does not have correct shape.')
+1271 raise ValueError('Manual derivative does not have correct shape.')
1272 elif kwargs.get('num_grad') is True:
1273 if multi > 0:
1274 raise Exception('Multi mode currently not supported for numerical derivative')
@@ -5554,7 +5554,7 @@ should agree with samples from a full bootstrap analysis up to O(1/N).
1334 new_covobs = {name: Covobs(0, allcov[name], name, grad=new_grad[name]) for name in new_grad}
1335
1336 if not set(new_covobs.keys()).isdisjoint(new_deltas.keys()):
-1337 raise Exception('The same name has been used for deltas and covobs!')
+1337 raise ValueError('The same name has been used for deltas and covobs!')
1338 new_samples = []
1339 new_means = []
1340 new_idl = []
@@ -5640,12 +5640,12 @@ functions. For the ratio of two observables one can e.g. use
1405 result = []
1406 for i in range(len(obs)):
1407 if len(obs[i].cov_names):
-1408 raise Exception('Error: Not possible to reweight an Obs that contains covobs!')
+1408 raise ValueError('Error: Not possible to reweight an Obs that contains covobs!')
1409 if not set(obs[i].names).issubset(weight.names):
-1410 raise Exception('Error: Ensembles do not fit')
+1410 raise ValueError('Error: Ensembles do not fit')
1411 for name in obs[i].names:
1412 if not set(obs[i].idl[name]).issubset(weight.idl[name]):
-1413 raise Exception('obs[%d] has to be defined on a subset of the configs in weight.idl[%s]!' % (i, name))
+1413 raise ValueError('obs[%d] has to be defined on a subset of the configs in weight.idl[%s]!' % (i, name))
1414 new_samples = []
1415 w_deltas = {}
1416 for name in sorted(obs[i].names):
@@ -5713,14 +5713,14 @@ on the configurations in obs[i].idl. Default False.
1447 """
1448
1449 if sorted(obs_a.names) != sorted(obs_b.names):
-1450 raise Exception(f"Ensembles do not fit {set(sorted(obs_a.names)) ^ set(sorted(obs_b.names))}")
+1450 raise ValueError(f"Ensembles do not fit {set(sorted(obs_a.names)) ^ set(sorted(obs_b.names))}")
1451 if len(obs_a.cov_names) or len(obs_b.cov_names):
-1452 raise Exception('Error: Not possible to correlate Obs that contain covobs!')
+1452 raise ValueError('Error: Not possible to correlate Obs that contain covobs!')
1453 for name in obs_a.names:
1454 if obs_a.shape[name] != obs_b.shape[name]:
-1455 raise Exception('Shapes of ensemble', name, 'do not fit')
+1455 raise ValueError('Shapes of ensemble', name, 'do not fit')
1456 if obs_a.idl[name] != obs_b.idl[name]:
-1457 raise Exception('idl of ensemble', name, 'do not fit')
+1457 raise ValueError('idl of ensemble', name, 'do not fit')
1458
1459 if obs_a.reweighted is True:
1460 warnings.warn("The first observable is already reweighted.", RuntimeWarning)
@@ -5903,7 +5903,7 @@ This construction ensures that the estimated covariance matrix is positive semi-
1556
1557 condn = np.linalg.cond(corr)
1558 if condn > 0.1 / np.finfo(float).eps:
-1559 raise Exception(f"Cannot invert correlation matrix as its condition number exceeds machine precision ({condn:1.2e})")
+1559 raise ValueError(f"Cannot invert correlation matrix as its condition number exceeds machine precision ({condn:1.2e})")
1560 if condn > 1e13:
1561 warnings.warn("Correlation matrix may be ill-conditioned, condition number: {%1.2e}" % (condn), RuntimeWarning)
1562 chol = np.linalg.cholesky(corr)
@@ -6185,9 +6185,9 @@ chain to be reconstructed.
1769 """
1770 replist = [item for obs in list_of_obs for item in obs.names]
1771 if (len(replist) == len(set(replist))) is False:
-1772 raise Exception('list_of_obs contains duplicate replica: %s' % (str(replist)))
+1772 raise ValueError('list_of_obs contains duplicate replica: %s' % (str(replist)))
1773 if any([len(o.cov_names) for o in list_of_obs]):
-1774 raise Exception('Not possible to merge data that contains covobs!')
+1774 raise ValueError('Not possible to merge data that contains covobs!')
1775 new_dict = {}
1776 idl_dict = {}
1777 for o in list_of_obs:
@@ -6266,7 +6266,7 @@ list of the Obs object to be combined
1822 for i in range(len(means)):
1823 ol.append(covobs_to_obs(Covobs(means[i], cov, name, pos=i, grad=grad)))
1824 if ol[0].covobs[name].N != len(means):
-1825 raise Exception('You have to provide %d mean values!' % (ol[0].N))
+1825 raise ValueError('You have to provide %d mean values!' % (ol[0].N))
1826 if len(ol) == 1:
1827 return ol[0]
1828 return ol