Source code for sysvar.uncertainties
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Iterable, List
from sysvar.utils import SavableAttributesObject
import numpy as np
[docs]
def get_uncertainty_types():
return {
"fully_correlated": FullyCorrelatedUncertainty,
"uncorrelated": UncorrelatedUncertainty,
"explicitly_correlated": ExplicitlyCorrelatedUncertainty,
"fully_correlated_in_parts": FullyCorrelatedUncertaintyInParts,
}
[docs]
class NotAnArrayError(Exception):
pass
[docs]
class MultiDimArrayError(Exception):
pass
[docs]
class EmptyArrayError(Exception):
pass
[docs]
class ValueError(Exception):
pass
[docs]
class Uncertainty(ABC, SavableAttributesObject):
"""
Abstract base class for representing uncertainties with a name and error values.
Args:
name (str): The name of the uncertainty.
errors (np.ndarray): An array containing the error values.
Attributes:
name (str): The name of the uncertainty.
errors (np.ndarray): An array containing the error values.
cov_matrix (np.ndarray): The covariance matrix of the uncertainty.
"""
def __init__(self, name: str, errors: np.ndarray, string_boundaries: List):
"""
Initialize an Uncertainty instance with a name and error values.
Args:
name (str): The name of the uncertainty.
errors (np.ndarray): An array containing the error values.
Raises:
NotAnArrayError: If errors is not an instance of np.ndarray.
MultiDimArrayError: If errors is not a 1D array.
NonMatchingCorrections: If the length of errors and corrections
are unequal.
"""
self.name = name
if self._is_valid_input_errors(errors):
self.errors = errors
self.string_boundaries = string_boundaries
self.cov_matrix = self.build_covariance()
super().__init__()
[docs]
@abstractmethod
def build_covariance(self) -> np.ndarray:
"""
Abstract method to build the covariance matrix of the uncertainty.
Returns:
np.ndarray: The covariance matrix of the uncertainty.
"""
pass
def _is_valid_input_errors(self, errors) -> None | bool:
"""
Validate the input errors.
Args:
errors: The input error values.
Returns:
None | bool: True if the errors are valid, otherwise None.
Raises:
NotAnArrayError: If errors is not an instance of np.ndarray.
MultiDimArrayError: If errors is not a 1D array.
EmptyArrayError: If errors is an empty array.
NonMatchingCorrections: If the length of errors and corrections
are unequal.
"""
if not isinstance(errors, (np.ndarray, list)):
raise NotAnArrayError("The errors must be provided as np arrays")
elif np.array(errors).ndim > 1:
raise MultiDimArrayError("The errors must be provided as a 1D array")
elif len(errors) == 0:
raise EmptyArrayError("The errors array cannot be empty")
if not np.isfinite(errors).all():
raise ValueError("The errors array contains invalid values")
else:
return True