Skip to content

Commit

Permalink
updated black config file to match flake8 config and added changes by…
Browse files Browse the repository at this point in the history
… black autoformatter
  • Loading branch information
MitchiLaser authored and JohannesGaessler committed Oct 5, 2023
1 parent 7f08ab1 commit 5e0e2b8
Show file tree
Hide file tree
Showing 88 changed files with 1,057 additions and 3,375 deletions.
23 changes: 5 additions & 18 deletions kafe2/config/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,21 +25,16 @@ class ConfigError(Exception):

class ConfigLookupError(ConfigError):
def __init__(self, key_path, problematic_key_index):
self.message = "Error getting config key for '{}': no node under that path!".format(
", ".join(key_path)
)
self.message = "Error getting config key for '{}': no node under that path!".format(", ".join(key_path))
self.message = "Error getting config key for '{}': " "cannot find config node '{}'!".format(
", ".join(key_path), key_path[problematic_key_index]
)


class ConfigTypeError(ConfigError):
def __init__(self, key_path, problematic_key_index):
self.message = (
"Error getting config key for '{}': "
"scalar node '{}' encountered inside path!".format(
", ".join(key_path), key_path[problematic_key_index]
)
self.message = "Error getting config key for '{}': " "scalar node '{}' encountered inside path!".format(
", ".join(key_path), key_path[problematic_key_index]
)


Expand Down Expand Up @@ -97,11 +92,7 @@ def kc(*keys):
if mpl.__version__.startswith("2"):
kafe2_rc = mpl.rc_params_from_file(os.path.join(__path__[0], "kafe2.matplotlibrc.conf"))
try: # look for local config
kafe2_rc.update(
mpl.rc_params_from_file(
os.path.join(os.getcwd(), "kafe2.matplotlibrc.conf"), use_default_template=False
)
)
kafe2_rc.update(mpl.rc_params_from_file(os.path.join(os.getcwd(), "kafe2.matplotlibrc.conf"), use_default_template=False))
except IOError:
pass
elif mpl.__version__.startswith("3"):
Expand All @@ -114,11 +105,7 @@ def kc(*keys):
_temp_file.write("\n".encode())
kafe2_rc = mpl.rc_params_from_file(_temp_file.name)
try: # look for local config, assume correct mpl3 handling
kafe2_rc.update(
mpl.rc_params_from_file(
os.path.join(os.getcwd(), "kafe2.matplotlibrc.conf"), use_default_template=False
)
)
kafe2_rc.update(mpl.rc_params_from_file(os.path.join(os.getcwd(), "kafe2.matplotlibrc.conf"), use_default_template=False))
except IOError:
pass
_temp_file.close()
Expand Down
8 changes: 2 additions & 6 deletions kafe2/core/confidence.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,7 @@ def cl(self) -> float:
@cl.setter
def cl(self, new_cl: float):
if new_cl <= 0 or new_cl >= 1:
raise ValueError(
"Confidence level must be greater than 0 and less than 1. Got: %g" % (new_cl,)
)
raise ValueError("Confidence level must be greater than 0 and less than 1. Got: %g" % (new_cl,))
self._cl = float(new_cl)
self._sigma = None

Expand Down Expand Up @@ -87,9 +85,7 @@ def ndim(self):
@ndim.setter
def ndim(self, new_ndim):
if not isinstance(new_ndim, int):
raise ValueError(
"Number of dimensions must be of type int! Received type: %s" % type(new_ndim)
)
raise ValueError("Number of dimensions must be of type int! Received type: %s" % type(new_ndim))
if new_ndim <= 0:
raise ValueError("Number of dimensions must be greater 0! Received: %d" % (new_ndim,))
self._ndim = new_ndim
Expand Down
16 changes: 4 additions & 12 deletions kafe2/core/constraint.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,9 +121,7 @@ def cost(self, parameter_values):


class GaussianMatrixParameterConstraint(ParameterConstraint):
def __init__(
self, indices, values, matrix, matrix_type="cov", uncertainties=None, relative=False
):
def __init__(self, indices, values, matrix, matrix_type="cov", uncertainties=None, relative=False):
"""
Advanced class for applying correlated constraints to several parameters of a fit.
The order of ``indices``, ``values``, ``matrix``, and ``uncertainties`` must be aligned.
Expand Down Expand Up @@ -159,9 +157,7 @@ def __init__(
pass
elif matrix_type == "cor":
if np.any(np.diag(_matrix_array) != 1.0):
raise ValueError(
"The correlation matrix has diagonal elements that aren't equal to 1!"
)
raise ValueError("The correlation matrix has diagonal elements that aren't equal to 1!")
if np.any(_matrix_array > 1.0):
raise ValueError("The correlation matrix has elements greater than 1!")
if np.any(_matrix_array < -1.0):
Expand Down Expand Up @@ -229,9 +225,7 @@ def cov_mat_rel(self):
if self.matrix_type == "cov":
self._cov_mat_rel = self._cov_mat_abs / np.outer(self.values, self.values)
else:
self._cov_mat_rel = self._cor_mat * np.outer(
self.uncertainties_rel, self.uncertainties_rel
)
self._cov_mat_rel = self._cor_mat * np.outer(self.uncertainties_rel, self.uncertainties_rel)
return self._cov_mat_rel

@property
Expand All @@ -240,9 +234,7 @@ def cor_mat(self):
if self._cor_mat is None:
# if the originally specified cov mat was relative, calculate the cor mat based on that
if self._relative:
self._cor_mat = self.cov_mat_rel / np.outer(
self.uncertainties_rel, self.uncertainties_rel
)
self._cor_mat = self.cov_mat_rel / np.outer(self.uncertainties_rel, self.uncertainties_rel)
else:
self._cor_mat = self.cov_mat / np.outer(self.uncertainties, self.uncertainties)
return self._cor_mat
Expand Down
4 changes: 1 addition & 3 deletions kafe2/core/contour.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@ def create_xy_contour(xy_points, sigma):
xy_points = np.asarray(xy_points)
_shape = xy_points.shape
if len(_shape) != 2 or (_shape[0] != 2 and _shape[1] != 2):
raise ValueError(
"Explicit contours can only be created from iterables with shape (2,n) or (n,2)."
)
raise ValueError("Explicit contours can only be created from iterables with shape (2,n) or (n,2).")
if _shape[0] != 2:
xy_points = xy_points.T
return Contour(xy_points=xy_points, sigma=sigma)
Expand Down
77 changes: 18 additions & 59 deletions kafe2/core/error.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,7 @@ def __add__(self, other):
return _new

def __eq__(self, other):
return (
np.all(self._mat == other.mat)
if isinstance(other, CovMat)
else np.all(self._mat == other)
)
return np.all(self._mat == other.mat) if isinstance(other, CovMat) else np.all(self._mat == other)

def __len__(self):
return self._size
Expand Down Expand Up @@ -98,9 +94,7 @@ def mat(self, matrix):

self._mat = np.array(matrix)
if self._mat.ndim != 2 or self._mat.shape[0] != self._mat.shape[1]:
raise ValueError(
"Covariance matrix must be square matrix, shape %r given." % (self._mat.shape,)
)
raise ValueError("Covariance matrix must be square matrix, shape %r given." % (self._mat.shape,))
self._size = self._mat.shape[0]
self._cond = None

Expand Down Expand Up @@ -211,9 +205,7 @@ def reference(self, reference):
_ref = np.asarray(reference, dtype=float)
# check for zero-valued references if error is marked 'relative'
if self.relative and np.any(_ref == 0):
warnings.warn(
"Relative error has a reference that contains values equal to zero: %s" % _ref
)
warnings.warn("Relative error has a reference that contains values equal to zero: %s" % _ref)
self._reference = _ref

# invalidate error_structures opposite declared relativity type
Expand Down Expand Up @@ -314,9 +306,7 @@ def __init__(self, err_val, corr_coeff, relative=False, reference=None, fit_indi
raise ValueError("Correlation must be between 0 and 1, %g given," % (corr_coeff,))
err_val = np.asarray(err_val)
if err_val.ndim != 1:
raise ValueError(
f"Error must be one-dimensional but received array with {err_val.ndim} dimensions."
)
raise ValueError(f"Error must be one-dimensional but received array with {err_val.ndim} dimensions.")
self._corr_coeff = float(corr_coeff)
self._is_relative = relative
self.reference = reference
Expand Down Expand Up @@ -348,9 +338,7 @@ def _calculate_cov_mat(self):
"""Calculate absolute covariance matrix for error object."""
if self.relative:
if self.reference is None:
raise AttributeError(
"Requested 'absolute' errors for error object declared 'relative', but 'reference' not set!"
)
raise AttributeError("Requested 'absolute' errors for error object declared 'relative', but 'reference' not set!")
_abs_err = self.error_rel * self.reference
else:
_abs_err = self.error
Expand Down Expand Up @@ -387,9 +375,7 @@ def error(self):
# calculate relative error from absolute error (if 'reference' is set)
if self.relative:
if self.reference is None:
raise AttributeError(
"Requested 'absolute' errors for error object declared 'relative', but 'reference' not set!"
)
raise AttributeError("Requested 'absolute' errors for error object declared 'relative', but 'reference' not set!")
self._err = self._err_rel * np.abs(self.reference)
return self._err

Expand All @@ -400,9 +386,7 @@ def error(self, err_val):
raise ValueError("Error values must be >= 0. Received: %s" % err_val)
if self.relative:
if self.reference is None:
raise AttributeError(
"Setting 'absolute' errors for error object declared 'relative', but 'reference' not set!"
)
raise AttributeError("Setting 'absolute' errors for error object declared 'relative', but 'reference' not set!")

self._err = err_val
self._err_rel = err_val / np.abs(self.reference)
Expand Down Expand Up @@ -439,9 +423,7 @@ def error_rel(self):
# calculate relative error from absolute error (if 'reference' is set)
if not self.relative:
if self.reference is None:
raise AttributeError(
"Requested 'relative' errors for error object declared 'absolute', but 'reference' not set!"
)
raise AttributeError("Requested 'relative' errors for error object declared 'absolute', but 'reference' not set!")
self._err_rel = self._err / np.abs(self.reference)
return self._err_rel

Expand All @@ -455,9 +437,7 @@ def error_rel(self, err_val):
self._err_rel = err_val
else:
if self.reference is None:
raise AttributeError(
"Setting 'absolute' errors for error object declared 'relative', but 'reference' not set!"
)
raise AttributeError("Setting 'absolute' errors for error object declared 'relative', but 'reference' not set!")
self._err = err_val * self.reference
self._err_rel = err_val

Expand Down Expand Up @@ -558,15 +538,9 @@ def __init__(
err_matrix = np.asarray(err_matrix)
err_val = err_val if err_val is None else np.asarray(err_val)
if err_matrix.ndim != 2:
raise ValueError(
"Error matrix must be two-dimensional but received "
f"array with {err_matrix.ndim} dimensions."
)
raise ValueError("Error matrix must be two-dimensional but received " f"array with {err_matrix.ndim} dimensions.")
if err_val is not None and err_val.ndim > 1:
raise ValueError(
"Error array must be scalar or one-dimensional but received "
f"array with {err_val.ndim} dimensions."
)
raise ValueError("Error array must be scalar or one-dimensional but received " f"array with {err_val.ndim} dimensions.")
self._is_relative = relative
self.reference = reference
self._fit_indices = fit_indices
Expand All @@ -588,19 +562,14 @@ def __init__(
elif matrix_type.lower() in ("correlation", "correlations", "cor", "corr"):
self._matrix_type_at_construction = "correlation"
if err_val is None:
raise ValueError(
"Cannot construct matrix-type error from correlation matrix "
"without an array of error values!"
)
raise ValueError("Cannot construct matrix-type error from correlation matrix " "without an array of error values!")
_cm = self._calculate_cov_mat_from_cor_mat_and_error_array(err_val, err_matrix)
if self.relative:
self.cov_mat_rel = _cm
else:
self.cov_mat = _cm
else:
raise ValueError(
"Unknown matrix type '%s'. Expected one of: %r" % (matrix_type, ("cov", "cor"))
)
raise ValueError("Unknown matrix type '%s'. Expected one of: %r" % (matrix_type, ("cov", "cor")))

# -- static methods

Expand All @@ -613,8 +582,7 @@ def _calculate_cov_mat_from_cor_mat_and_error_array(error_array, corr_mat):
# TODO: check if corr_mat is symmetric and positive definite (?)
if error_array.ndim > 0 and error_array.shape[0] != corr_mat.shape[0]:
raise ValueError(
f"Error array has size {error_array.shape[0]} but "
f"correlation matrix has size {corr_mat.shape[0]}, must be the same."
f"Error array has size {error_array.shape[0]} but " f"correlation matrix has size {corr_mat.shape[0]}, must be the same."
)
cov_mat = np.asarray(np.outer(error_array, error_array)) * np.asarray(corr_mat)
return CovMat(cov_mat)
Expand Down Expand Up @@ -645,10 +613,7 @@ def cov_mat(self):
""""""
if self.relative:
if self.reference is None:
raise AttributeError(
"Requested 'absolute' covariance matrix for error object declared 'relative', "
"but 'reference' not set!"
)
raise AttributeError("Requested 'absolute' covariance matrix for error object declared 'relative', " "but 'reference' not set!")
self._cov_mat = self._calculate_cov_mat_from_cov_rel(self.cov_mat_rel, self.reference)
return self._cov_mat.mat

Expand All @@ -663,9 +628,7 @@ def cov_mat_rel(self):
""""""
if not self.relative:
if self.reference is None:
raise AttributeError(
"Requested 'relative' covariance matrix for error object declared 'absolute', but 'reference' not set!"
)
raise AttributeError("Requested 'relative' covariance matrix for error object declared 'absolute', but 'reference' not set!")
self._cov_mat_rel = self._calculate_cov_mat_rel_from_cov(self.cov_mat, self.reference)
return self._cov_mat_rel.mat

Expand All @@ -686,9 +649,7 @@ def error(self):
if self._err is None:
if self.relative:
if self.reference is None:
raise AttributeError(
"Requested 'absolute' error array for error object declared 'relative', but 'reference' not set!"
)
raise AttributeError("Requested 'absolute' error array for error object declared 'relative', but 'reference' not set!")
self._err = np.sqrt(np.diag(self.cov_mat))
return self._err

Expand All @@ -698,9 +659,7 @@ def error_rel(self):
if self._err_rel is None:
if not self.relative:
if self.reference is None:
raise AttributeError(
"Requested 'relative' error array for error object declared 'absolute', but 'reference' not set!"
)
raise AttributeError("Requested 'relative' error array for error object declared 'absolute', but 'reference' not set!")
self._err_rel = np.sqrt(np.diag(self.cov_mat_rel))
return self._err_rel

Expand Down
4 changes: 1 addition & 3 deletions kafe2/core/fitters/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@ def get_fitter(fitter_spec):
_fitter = AVAILABLE_FITTERS.get(fitter_spec, None)

if _fitter is None:
raise ValueError(
"Unknown fitter '{}'! Available: {}".format(fitter_spec, AVAILABLE_FITTERS.keys())
)
raise ValueError("Unknown fitter '{}'! Available: {}".format(fitter_spec, AVAILABLE_FITTERS.keys()))

return _fitter

Expand Down
Loading

0 comments on commit 5e0e2b8

Please sign in to comment.