Modules
API for function classes.
MaximaAPI
¶
Bases: BaseModel
Maxima API for optimization functions.
Source code in umf/meta/api.py
class MaximaAPI(BaseModel):
"""Maxima API for optimization functions."""
model_config = ConfigDict(arbitrary_types_allowed=True)
f_x: float | UniversalArray = Field(
...,
description="Value of the function at the maximum or maxima.",
)
x: UniversalArrayTuple | UniversalFloatTuple = Field(
...,
description="Input data, where the maximum or maxima is located.",
)
MinimaAPI
¶
Bases: BaseModel
Minima API for optimization functions.
Source code in umf/meta/api.py
class MinimaAPI(BaseModel):
"""Minima API for optimization functions."""
model_config = ConfigDict(arbitrary_types_allowed=True)
f_x: float | UniversalArray = Field(
...,
description="Value of the function at the minimum or minima.",
)
x: UniversalArrayTuple | UniversalFloatTuple = Field(
...,
description="Input data, where the minimum or minima is located.",
)
ResultsChaoticOscillatorAPI
¶
Bases: BaseModel
Results API for chaotic oscillator functions.
Source code in umf/meta/api.py
class ResultsChaoticOscillatorAPI(BaseModel):
"""Results API for chaotic oscillator functions."""
model_config = ConfigDict(arbitrary_types_allowed=True)
t: UniversalArrayTuple = Field(
...,
description="Time array for the chaotic oscillator.",
)
initial_state: dict[str, UniversalArray] = Field(
default=...,
description="Initial conditions for the chaotic pendulum.",
)
result: UniversalArray = Field(
default=...,
description="Result of the chaotic oscillator.",
)
doc: str | None = Field(
default=...,
description="Function documentation string.",
)
ResultsDistributionAPI
¶
Bases: BaseModel
Results API for distribution functions.
Source code in umf/meta/api.py
class ResultsDistributionAPI(BaseModel):
"""Results API for distribution functions."""
model_config = ConfigDict(arbitrary_types_allowed=True)
x: UniversalArrayTuple = Field(
...,
description="Input data, which can be one, two, three, or higher dimensional.",
)
result: UniversalArray | MeshArray = Field(
...,
description="Function value as numpy array or numpy mesh grid array.",
)
summary: SummaryStatisticsAPI = Field(
...,
description="Summary statistics of the data.",
)
doc: str | None = Field(..., description="Function documentation string.")
ResultsFractalAPI
¶
Bases: BaseModel
Results API for fractal functions.
This class provides a standardized structure for returning fractal data, including the input parameters, resulting fractal representation, and metadata.
Attributes:
Name | Type | Description |
---|---|---|
x | UniversalArrayTuple | Input data for the fractal generation. |
result | UniversalArray | MeshArray | list | dict | Fractal data, which may be iteration counts, coordinates, or other representations. |
parameters | dict | None | Parameters used to generate the fractal. |
dimension | float | None | Fractal dimension, if calculated. |
doc | str | None | Function documentation string. |
Source code in umf/meta/api.py
class ResultsFractalAPI(BaseModel):
"""Results API for fractal functions.
This class provides a standardized structure for returning fractal data,
including the input parameters, resulting fractal representation, and metadata.
Attributes:
x (UniversalArrayTuple): Input data for the fractal generation.
result (UniversalArray | MeshArray | list | dict): Fractal data, which may
be iteration counts, coordinates, or other representations.
parameters (dict | None): Parameters used to generate the fractal.
dimension (float | None): Fractal dimension, if calculated.
doc (str | None): Function documentation string.
"""
model_config = ConfigDict(arbitrary_types_allowed=True)
x: UniversalArrayTuple = Field(
...,
description="Input data for the fractal generation.",
)
result: UniversalArray | MeshArray | list | dict = Field(
...,
description="Fractal data, which may be iteration counts, coordinates,"
" or other representations.",
)
parameters: dict | None = Field(
default=None,
description="Parameters used to generate the fractal.",
)
dimension: float | None = Field(
default=None,
description="Fractal dimension, if calculated.",
)
doc: str | None = Field(..., description="Function documentation string.")
@model_validator(mode="after")
def validate_dimension(self) -> ResultsFractalAPI:
"""Validate the fractal dimension.
Checks that the provided fractal dimension is within a reasonable range
(between 0 and 3 for most fractals).
Returns:
ResultsFractalAPI: The validated model instance
"""
if self.dimension is not None and not (0 <= self.dimension <= __3d__):
warnings.warn(
message=f"Unusual fractal dimension: {self.dimension}. "
f"Most fractals have dimensions between 0 and 3.",
category=UserWarning,
stacklevel=1,
)
return self
validate_dimension()
¶
Validate the fractal dimension.
Checks that the provided fractal dimension is within a reasonable range (between 0 and 3 for most fractals).
Returns:
Name | Type | Description |
---|---|---|
ResultsFractalAPI | ResultsFractalAPI | The validated model instance |
Source code in umf/meta/api.py
@model_validator(mode="after")
def validate_dimension(self) -> ResultsFractalAPI:
"""Validate the fractal dimension.
Checks that the provided fractal dimension is within a reasonable range
(between 0 and 3 for most fractals).
Returns:
ResultsFractalAPI: The validated model instance
"""
if self.dimension is not None and not (0 <= self.dimension <= __3d__):
warnings.warn(
message=f"Unusual fractal dimension: {self.dimension}. "
f"Most fractals have dimensions between 0 and 3.",
category=UserWarning,
stacklevel=1,
)
return self
ResultsFunctionAPI
¶
Bases: BaseModel
Results API for optimization functions.
Source code in umf/meta/api.py
class ResultsFunctionAPI(BaseModel):
"""Results API for optimization functions."""
model_config = ConfigDict(arbitrary_types_allowed=True)
x: UniversalArrayTuple = Field(
...,
description="Input data, which can be one, two, three, or higher dimensional.",
)
result: UniversalArray | MeshArray = Field(
...,
description="Function value as numpy array or numpy mesh grid array.",
)
minima: MinimaAPI | None = Field(
default=None,
description="Tuple of minima as numpy arrays.",
)
maxima: MaximaAPI | None = Field(
default=None,
description="Tuple of maxima as numpy arrays.",
)
doc: str | None = Field(..., description="Function documentation string.")
ResultsHyperbolicAPI
¶
Bases: BaseModel
Results API for hyperbolic functions.
Source code in umf/meta/api.py
class ResultsHyperbolicAPI(BaseModel):
"""Results API for hyperbolic functions."""
model_config = ConfigDict(arbitrary_types_allowed=True)
x: UniversalArrayTuple = Field(
...,
description="Input data, which can be one, two, three, or higher dimensional.",
)
result: UniversalArray | MeshArray = Field(
...,
description="Function value as numpy array or numpy mesh grid array.",
)
doc: str | None = Field(..., description="Function documentation string.")
ResultsPathologicalAPI
¶
Bases: BaseModel
Results API for pathological functions.
Source code in umf/meta/api.py
class ResultsPathologicalAPI(BaseModel):
"""Results API for pathological functions."""
model_config = ConfigDict(arbitrary_types_allowed=True)
x: UniversalArrayTuple = Field(
...,
description="Input data, which can be one, two, three, or higher dimensional.",
)
result: UniversalArray | MeshArray = Field(
...,
description="Function value as numpy array or numpy mesh grid array.",
)
doc: str | None = Field(..., description="Function documentation string.")
SummaryStatisticsAPI
¶
Bases: BaseModel
API for summary statistics.
Source code in umf/meta/api.py
class SummaryStatisticsAPI(BaseModel):
"""API for summary statistics."""
model_config = ConfigDict(arbitrary_types_allowed=True)
mean: float | None = Field(
default=...,
description="Mean value of the data.",
)
variance: float | None = Field(
default=...,
description="Variance of the data.",
)
mode: float | UniversalFloatTuple | None = Field(
default=...,
description="Mode or modes of the data.",
)
doc: str | None = Field(
default=...,
description="Documentation string for the summary statistics.",
)
Reference class for functions to generate data for benchmarking.
ComplexFractalFunction
¶
Bases: FractalFunction
Base class for complex fractal functions.
This class extends the FractalFunction to handle complex numbers in the input data. It provides common functionality for fractals like the Mandelbrot set and Julia set.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*x | UniversalArray | Input data, which can vary depending on the specific fractal. | () |
max_iter | int | Maximum number of iterations. Defaults to 100. | 100 |
escape_radius | float | Escape radius. Defaults to 2.0. | 2.0 |
Raises:
Type | Description |
---|---|
MissingXError | If no input data is specified. |
Source code in umf/meta/functions.py
class ComplexFractalFunction(FractalFunction):
"""Base class for complex fractal functions.
This class extends the FractalFunction to handle complex numbers in the input data.
It provides common functionality for fractals like the Mandelbrot set and Julia set.
Args:
*x (UniversalArray): Input data, which can vary depending on the specific
fractal.
max_iter (int, optional): Maximum number of iterations. Defaults to 100.
escape_radius (float, optional): Escape radius. Defaults to 2.0.
Raises:
MissingXError: If no input data is specified.
"""
def __init__(
self, *x: UniversalArray, max_iter: int = 100, escape_radius: float = 2.0
) -> None:
"""Initialize the complex fractal function."""
super().__init__(*x, max_iter=max_iter)
self.escape_radius = escape_radius
def iterate_complex_function(
self, z_start: np.ndarray, c: np.ndarray | complex, shape: tuple
) -> np.ndarray:
"""Common iteration method for complex fractals.
Implements the $z = z^2 + c$ iteration common to both Mandelbrot and Julia sets.
Args:
z_start (np.ndarray): Starting z values
c (np.ndarray | complex): Parameter c values
shape (tuple): Original shape of the array
Returns:
np.ndarray: Iteration counts
"""
z = z_start.flatten()
if isinstance(c, np.ndarray):
c = c.flatten()
iterations = np.zeros(z.shape, dtype=int)
escape_radius_squared = self.escape_radius**2
# Points still iterating
mask = np.full(shape=z.shape, fill_value=True, dtype=bool)
for i in range(self.max_iter):
# Update z for points still iterating
z[mask] = (
z[mask] ** 2 + c[mask]
if isinstance(c, np.ndarray)
else z[mask] ** 2 + c
)
# Find points that escape
escaped = np.abs(z) ** 2 > escape_radius_squared
# Update iterations for newly escaped points
iterations[mask & escaped] = i + 1
# Update mask to exclude escaped points
mask[escaped] = False
# If all points have escaped, break
if not np.any(mask):
break
return iterations.reshape(shape)
__init__(*x, max_iter=100, escape_radius=2.0)
¶
Initialize the complex fractal function.
iterate_complex_function(z_start, c, shape)
¶
Common iteration method for complex fractals.
Implements the \(z = z^2 + c\) iteration common to both Mandelbrot and Julia sets.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
z_start | ndarray | Starting z values | required |
c | ndarray | complex | Parameter c values | required |
shape | tuple | Original shape of the array | required |
Returns:
Type | Description |
---|---|
ndarray | np.ndarray: Iteration counts |
Source code in umf/meta/functions.py
def iterate_complex_function(
self, z_start: np.ndarray, c: np.ndarray | complex, shape: tuple
) -> np.ndarray:
"""Common iteration method for complex fractals.
Implements the $z = z^2 + c$ iteration common to both Mandelbrot and Julia sets.
Args:
z_start (np.ndarray): Starting z values
c (np.ndarray | complex): Parameter c values
shape (tuple): Original shape of the array
Returns:
np.ndarray: Iteration counts
"""
z = z_start.flatten()
if isinstance(c, np.ndarray):
c = c.flatten()
iterations = np.zeros(z.shape, dtype=int)
escape_radius_squared = self.escape_radius**2
# Points still iterating
mask = np.full(shape=z.shape, fill_value=True, dtype=bool)
for i in range(self.max_iter):
# Update z for points still iterating
z[mask] = (
z[mask] ** 2 + c[mask]
if isinstance(c, np.ndarray)
else z[mask] ** 2 + c
)
# Find points that escape
escaped = np.abs(z) ** 2 > escape_radius_squared
# Update iterations for newly escaped points
iterations[mask & escaped] = i + 1
# Update mask to exclude escaped points
mask[escaped] = False
# If all points have escaped, break
if not np.any(mask):
break
return iterations.reshape(shape)
ContinousAsymmetricPseudo
¶
Bases: ContinousPseudo
Base class for continuous distributions for asym. pseudo Voigt like functions.
Note
In terms of pseudo Voigt like functions, the \(\gamma\) parameter is used to provide an asymetric line shape. The \(\gamma\) parameter is defined as the ratio of the Lorentzian contribution to the Gaussian contribution. In case of XPS and XAS, these type of functions are popular to model the line shape of the photoemission and absorption spectra.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x | UniversalArray | Input data, which currently must be one dimensional. | () |
mu | float | Mean of the distribution. Defaults to 0. | 0 |
sigma | float | Standard deviation of the distribution. Defaults to 1. | 1 |
eta | float | Shape parameter of the distribution. Defaults to 0.5. | 0.5 |
gamma | float | Asymmetry parameter of the distribution. Defaults to 0.0. | 0.0 |
cumulative | bool | Whether to return the cumulative distribution function. Defaults to False. | required |
Raises:
Type | Description |
---|---|
MissingXError | If no input data is specified. |
OutOfDimensionError | If the input data has more than one dimension. |
OutOfRangeError | If the input data is not in the interval \([0, 1]\). |
Source code in umf/meta/functions.py
class ContinousAsymmetricPseudo(ContinousPseudo):
r"""Base class for continuous distributions for asym. pseudo Voigt like functions.
Note:
In terms of pseudo Voigt like functions, the $\gamma$ parameter is used to
provide an asymetric line shape. The $\gamma$ parameter is defined as the ratio
of the Lorentzian contribution to the Gaussian contribution. In case of
**XPS** and **XAS**, these type of functions are popular to model the line shape
of the photoemission and absorption spectra.
Args:
x (UniversalArray): Input data, which currently must be one dimensional.
mu (float): Mean of the distribution. Defaults to 0.
sigma (float): Standard deviation of the distribution. Defaults to 1.
eta (float): Shape parameter of the distribution. Defaults to 0.5.
gamma (float): Asymmetry parameter of the distribution. Defaults to 0.0.
cumulative (bool): Whether to return the cumulative distribution function.
Defaults to False.
Raises:
MissingXError: If no input data is specified.
OutOfDimensionError: If the input data has more than one dimension.
OutOfRangeError: If the input data is not in the interval $[0, 1]$.
"""
def __init__(
self,
*x: UniversalArray,
mu: float = 0,
sigma: float = 1,
eta: float = 0.5,
gamma: float = 0.0,
) -> None:
"""Initialize the function."""
super().__init__(*x, mu=mu, sigma=sigma, eta=eta, cumulative=False)
self.gamma = gamma
__init__(*x, mu=0, sigma=1, eta=0.5, gamma=0.0)
¶
Initialize the function.
ContinousPseudo
¶
Bases: ContinuousWSigma
Base class for continuous distributions for pseudo Voigt like functions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x | UniversalArray | Input data, which currently must be one dimensional. | () |
mu | float | Mean of the distribution. Defaults to 0. | 0 |
sigma | float | Standard deviation of the distribution. Defaults to 1. | 1 |
eta | float | Shape parameter of the distribution. Defaults to 0.5. | 0.5 |
cumulative | bool | Whether to return the cumulative distribution function. Defaults to False. | False |
Raises:
Type | Description |
---|---|
MissingXError | If no input data is specified. |
OutOfDimensionError | If the input data has more than one dimension. |
OutOfRangeError | If the input data is not in the interval \([0, 1]\). |
Source code in umf/meta/functions.py
class ContinousPseudo(ContinuousWSigma):
"""Base class for continuous distributions for pseudo Voigt like functions.
Args:
x (UniversalArray): Input data, which currently must be one dimensional.
mu (float): Mean of the distribution. Defaults to 0.
sigma (float): Standard deviation of the distribution. Defaults to 1.
eta (float): Shape parameter of the distribution. Defaults to 0.5.
cumulative (bool): Whether to return the cumulative distribution function.
Defaults to False.
Raises:
MissingXError: If no input data is specified.
OutOfDimensionError: If the input data has more than one dimension.
OutOfRangeError: If the input data is not in the interval $[0, 1]$.
"""
def __init__(
self,
*x: UniversalArray,
mu: float = 0,
sigma: float = 1,
eta: float = 0.5,
cumulative: bool = False,
) -> None:
"""Initialize the function."""
super().__init__(*x, mu=mu, sigma=sigma, cumulative=cumulative)
if eta < 0 or eta > 1:
raise OutOfRangeError(
function_name=self.__class__.__name__,
start_range=0,
end_range=1,
)
self.eta = eta
__init__(*x, mu=0, sigma=1, eta=0.5, cumulative=False)
¶
Initialize the function.
Source code in umf/meta/functions.py
def __init__(
self,
*x: UniversalArray,
mu: float = 0,
sigma: float = 1,
eta: float = 0.5,
cumulative: bool = False,
) -> None:
"""Initialize the function."""
super().__init__(*x, mu=mu, sigma=sigma, cumulative=cumulative)
if eta < 0 or eta > 1:
raise OutOfRangeError(
function_name=self.__class__.__name__,
start_range=0,
end_range=1,
)
self.eta = eta
Continuous2PiInterval
¶
Bases: ContinuousDistributionBase
Base class for continuous distributions with fixed interval of \(2\pi\).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*x | UniversalArray | Input data, which currently must be one dimensional. | () |
mu | float | Mean of the distribution. Defaults to 0. | 0 |
cumulative | bool | Whether to return the cumulative distribution function. Defaults to False. | False |
Raises:
Type | Description |
---|---|
OutOfRangeError | If the input data is not in the interval \([-\pi, \pi]\). |
MissingXError | If no input data is specified. |
Source code in umf/meta/functions.py
class Continuous2PiInterval(ContinuousDistributionBase):
r"""Base class for continuous distributions with fixed interval of $2\pi$.
Args:
*x (UniversalArray): Input data, which currently must be one dimensional.
mu (float): Mean of the distribution. Defaults to 0.
cumulative (bool): Whether to return the cumulative distribution function.
Defaults to False.
Raises:
OutOfRangeError: If the input data is not in the interval $[-\pi, \pi]$.
MissingXError: If no input data is specified.
"""
def __init__(
self,
*x: UniversalArray,
mu: float = 0,
kappa: float = 1,
cumulative: bool = False,
) -> None:
"""Initialize the function."""
if np.min(x) < -np.pi or np.max(x) > np.pi:
raise OutOfRangeError(
function_name=self.__class__.__name__,
start_range=-np.pi,
end_range=np.pi,
)
super().__init__(*x, mu=mu, cumulative=cumulative)
self.kappa = kappa
__init__(*x, mu=0, kappa=1, cumulative=False)
¶
Initialize the function.
Source code in umf/meta/functions.py
def __init__(
self,
*x: UniversalArray,
mu: float = 0,
kappa: float = 1,
cumulative: bool = False,
) -> None:
"""Initialize the function."""
if np.min(x) < -np.pi or np.max(x) > np.pi:
raise OutOfRangeError(
function_name=self.__class__.__name__,
start_range=-np.pi,
end_range=np.pi,
)
super().__init__(*x, mu=mu, cumulative=cumulative)
self.kappa = kappa
ContinuousBoundedInterval
¶
Bases: ContinuousDistributionBase
Base class for continuous distributions with a bounded interval.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*x | UniversalArray | Input data, which currently must be one dimensional. | () |
start | float | Start of the interval. Defaults to 0. | 0 |
end | float | End of the interval. Defaults to 1. | 1 |
cumulative | bool | Whether to return the cumulative distribution function. Defaults to False. | False |
Raises:
Type | Description |
---|---|
OutOfRangeError | If the input data is not in the interval \([start, end]\). |
MissingXError | If no input data is specified. |
Source code in umf/meta/functions.py
class ContinuousBoundedInterval(ContinuousDistributionBase):
"""Base class for continuous distributions with a bounded interval.
Args:
*x (UniversalArray): Input data, which currently must be one dimensional.
start (float): Start of the interval. Defaults to 0.
end (float): End of the interval. Defaults to 1.
cumulative (bool): Whether to return the cumulative distribution function.
Defaults to False.
Raises:
OutOfRangeError: If the input data is not in the interval $[start, end]$.
MissingXError: If no input data is specified.
"""
def __init__(
self,
*x: UniversalArray,
start: float = 0,
end: float = 1,
cumulative: bool = False,
) -> None:
"""Initialize the function."""
if np.min(x) < start or np.max(x) > end:
raise OutOfRangeError(
function_name=self.__class__.__name__,
start_range=start,
end_range=end,
)
super().__init__(*x, cumulative=cumulative)
__init__(*x, start=0, end=1, cumulative=False)
¶
Initialize the function.
Source code in umf/meta/functions.py
def __init__(
self,
*x: UniversalArray,
start: float = 0,
end: float = 1,
cumulative: bool = False,
) -> None:
"""Initialize the function."""
if np.min(x) < start or np.max(x) > end:
raise OutOfRangeError(
function_name=self.__class__.__name__,
start_range=start,
end_range=end,
)
super().__init__(*x, cumulative=cumulative)
ContinuousDistributionBase
¶
Bases: ABC
Base class for distributions with a standard deviation and beta parameter.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x | UniversalArray | Input data, which currently must be one dimensional. | () |
mu | float | Mean of the distribution. Defaults to 0. | 0 |
beta | float | Shape parameter of the distribution. Defaults to 1. | required |
cumulative | bool | Whether to return the cumulative distribution function. Defaults to False. | False |
Raises:
Type | Description |
---|---|
MissingXError | If no input data is specified. |
OutOfDimensionError | If the input data has more than one dimension. |
Source code in umf/meta/functions.py
class ContinuousDistributionBase(ABC, metaclass=CoreElements):
"""Base class for distributions with a standard deviation and beta parameter.
Args:
x (UniversalArray): Input data, which currently must be one dimensional.
mu (float ): Mean of the distribution. Defaults to 0.
beta (float): Shape parameter of the distribution. Defaults to 1.
cumulative (bool): Whether to return the cumulative distribution function.
Defaults to False.
Raises:
MissingXError: If no input data is specified.
OutOfDimensionError: If the input data has more than one dimension.
"""
def __init__(
self,
*x: UniversalArray,
mu: float = 0,
cumulative: bool = False,
) -> None:
"""Initialize the function."""
if x[0] is None:
raise MissingXError
if len(x) != __1d__:
raise OutOfDimensionError(
function_name=self.__class__.__name__,
dimension=__1d__,
)
self._x = x[0]
self.mu = mu
self.cumulative = cumulative
@property
def __input__(self) -> UniversalArrayTuple:
"""Return the input data."""
return (np.array(self._x),)
@property
def __eval__(self) -> UniversalArray:
"""Evaluate the function."""
return (
self.cumulative_distribution_function()
if self.cumulative
else self.probability_density_function()
)
@abstractmethod
def probability_density_function(self) -> UniversalArray:
"""Return the probability density function."""
@property
@abstractmethod
def __summary__(self) -> SummaryStatisticsAPI:
"""Return the summary statistics."""
def cumulative_distribution_function(self) -> UniversalArray:
"""Return the cumulative distribution function."""
raise NoCumulativeError
def __call__(self) -> ResultsDistributionAPI:
"""Return the results of the function."""
return ResultsDistributionAPI(
x=self.__input__,
result=self.__eval__,
summary=self.__summary__,
doc=self.__doc__,
)
__eval__
property
¶
Evaluate the function.
__input__
property
¶
Return the input data.
__summary__
abstractmethod
property
¶
Return the summary statistics.
__call__()
¶
__init__(*x, mu=0, cumulative=False)
¶
Initialize the function.
Source code in umf/meta/functions.py
def __init__(
self,
*x: UniversalArray,
mu: float = 0,
cumulative: bool = False,
) -> None:
"""Initialize the function."""
if x[0] is None:
raise MissingXError
if len(x) != __1d__:
raise OutOfDimensionError(
function_name=self.__class__.__name__,
dimension=__1d__,
)
self._x = x[0]
self.mu = mu
self.cumulative = cumulative
cumulative_distribution_function()
¶
probability_density_function()
abstractmethod
¶
ContinuousMixed
¶
Bases: ContinuousWSigma
Base class for continuous distributions with mixed parameters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x | UniversalArray | Input data, which can be one, two, three, or higher dimensional. | () |
mu | float | Mean of the distribution. Defaults to 0. | 0 |
sigma | float | Standard deviation of the distribution. Defaults to 1. | 1 |
zeta | float | Shape parameter of the distribution. Defaults to 0.0. | 0.0 |
cumulative | bool | Whether to return the cumulative distribution function. Defaults to False. | False |
Raises:
Type | Description |
---|---|
MissingXError | If no input data is specified. |
OutOfDimensionError | If the input data has more than one dimension. |
Source code in umf/meta/functions.py
class ContinuousMixed(ContinuousWSigma):
r"""Base class for continuous distributions with mixed parameters.
Args:
x (UniversalArray): Input data, which can be one, two, three, or higher
dimensional.
mu (float): Mean of the distribution. Defaults to 0.
sigma (float): Standard deviation of the distribution. Defaults to 1.
zeta (float): Shape parameter of the distribution. Defaults to 0.0.
cumulative (bool): Whether to return the cumulative distribution function.
Defaults to False.
Raises:
MissingXError: If no input data is specified.
OutOfDimensionError: If the input data has more than one dimension.
"""
def __init__(
self,
*x: UniversalArray,
mu: float = 0,
sigma: float = 1,
zeta: float = 0.0,
cumulative: bool = False,
) -> None:
"""Initialize the function."""
super().__init__(*x, mu=mu, sigma=sigma, cumulative=cumulative)
self.zeta = zeta
__init__(*x, mu=0, sigma=1, zeta=0.0, cumulative=False)
¶
Initialize the function.
ContinuousPure
¶
Bases: ContinuousDistributionBase
Base class for continuous distributions with a standard deviation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x | UniversalArray | Input data, which currently must be one dimensional. | () |
mu | float | Mean of the distribution. Defaults to 0. | 0 |
cumulative | bool | Whether to return the cumulative distribution function. Defaults to False. | False |
Raises:
Type | Description |
---|---|
MissingXError | If no input data is specified. |
OutOfDimensionError | If the input data has more than one dimension. |
Source code in umf/meta/functions.py
class ContinuousPure(ContinuousDistributionBase):
"""Base class for continuous distributions with a standard deviation.
Args:
x (UniversalArray): Input data, which currently must be one dimensional.
mu (float): Mean of the distribution. Defaults to 0.
cumulative (bool): Whether to return the cumulative distribution function.
Defaults to False.
Raises:
MissingXError: If no input data is specified.
OutOfDimensionError: If the input data has more than one dimension.
"""
ContinuousWBeta
¶
Bases: ContinuousDistributionBase
Base class for continuous distributions with beta parameter.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x | UniversalArray | Input data, which currently must be one dimensional. | () |
mu | float | Mean of the distribution. Defaults to 0. | 0 |
beta | float | Shape parameter of the distribution. Defaults to 1. | 1 |
cumulative | bool | Whether to return the cumulative distribution function. Defaults to False. | False |
Raises:
Type | Description |
---|---|
NotAPositiveNumberError | If the beta parameter is not a positive number. |
Source code in umf/meta/functions.py
class ContinuousWBeta(ContinuousDistributionBase):
"""Base class for continuous distributions with beta parameter.
Args:
x (UniversalArray): Input data, which currently must be one dimensional.
mu (float): Mean of the distribution. Defaults to 0.
beta (float): Shape parameter of the distribution. Defaults to 1.
cumulative (bool): Whether to return the cumulative distribution function.
Defaults to False.
Raises:
NotAPositiveNumberError: If the beta parameter is not a positive number.
"""
def __init__(
self,
*x: UniversalArray,
mu: float = 0,
beta: float = 1,
cumulative: bool = False,
) -> None:
"""Initialize the function."""
super().__init__(*x, mu=mu, cumulative=cumulative)
if beta <= 0:
raise NotAPositiveNumberError(var_number="beta", number=beta)
self.beta = beta
__init__(*x, mu=0, beta=1, cumulative=False)
¶
Initialize the function.
Source code in umf/meta/functions.py
ContinuousWLambda
¶
Bases: ContinuousDistributionBase
Base class for continuous distributions with beta parameter.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x | UniversalArray | Input data, which currently must be one dimensional. | () |
mu | float | Mean of the distribution. Defaults to 0. | required |
beta | float | Shape parameter of the distribution. Defaults to 1. | required |
cumulative | bool | Whether to return the cumulative distribution function. Defaults to False. | False |
Raises:
Type | Description |
---|---|
MissingXError | If no input data is specified. |
OutOfDimensionError | If the input data has more than one dimension. |
Source code in umf/meta/functions.py
class ContinuousWLambda(ContinuousDistributionBase):
"""Base class for continuous distributions with beta parameter.
Args:
x (UniversalArray): Input data, which currently must be one dimensional.
mu (float): Mean of the distribution. Defaults to 0.
beta (float): Shape parameter of the distribution. Defaults to 1.
cumulative (bool): Whether to return the cumulative distribution function.
Defaults to False.
Raises:
MissingXError: If no input data is specified.
OutOfDimensionError: If the input data has more than one dimension.
"""
def __init__(
self,
*x: UniversalArray,
lambda_: float = 1,
cumulative: bool = False,
) -> None:
"""Initialize the function."""
super().__init__(*x, cumulative=cumulative)
if lambda_ <= 0:
raise NotAPositiveNumberError(var_number="lambda_", number=lambda_)
self.lambda_ = lambda_
__init__(*x, lambda_=1, cumulative=False)
¶
Initialize the function.
Source code in umf/meta/functions.py
ContinuousWSigma
¶
Bases: ContinuousDistributionBase
Base class for continuous distributions with a standard deviation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x | UniversalArray | Input data, which can be one, two, three, or higher dimensional. | () |
mu | float | Mean of the distribution. Defaults to 0. | 0 |
sigma | float | Standard deviation of the distribution. Defaults to 1. | 1 |
cumulative | bool | Whether to return the cumulative distribution function. Defaults to False. | False |
Raises:
Type | Description |
---|---|
MissingXError | If no input data is specified. |
OutOfDimensionError | If the input data has more than one dimension. |
Source code in umf/meta/functions.py
class ContinuousWSigma(ContinuousDistributionBase):
"""Base class for continuous distributions with a standard deviation.
Args:
x (UniversalArray): Input data, which can be one, two, three, or higher
dimensional.
mu (float): Mean of the distribution. Defaults to 0.
sigma (float): Standard deviation of the distribution. Defaults to 1.
cumulative (bool): Whether to return the cumulative distribution function.
Defaults to False.
Raises:
MissingXError: If no input data is specified.
OutOfDimensionError: If the input data has more than one dimension.
"""
def __init__(
self,
*x: UniversalArray,
mu: float = 0,
sigma: float = 1,
cumulative: bool = False,
) -> None:
"""Initialize the function."""
super().__init__(*x, mu=mu, cumulative=cumulative)
self.sigma = sigma
__init__(*x, mu=0, sigma=1, cumulative=False)
¶
CoreElements
¶
Bases: ABCMeta
Metaclass for functions.
Source code in umf/meta/functions.py
CurveFractalFunction
¶
Bases: FractalFunction
Base class for curve-based fractals.
This class extends FractalFunction to handle fractals based on iterative curve generation, like the Cantor set, Dragon curve, and space-filling curves.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*x | UniversalArray | Input points defining the curve space | () |
max_iter | int | Maximum number of iterations. Defaults to 100. | 100 |
scale_factor | float | Scale factor between iterations. Defaults to 0.5. | 0.5 |
fractal_dimension | float | Fractal dimension of the curve. Defaults to 2.0. | 2.0 |
Source code in umf/meta/functions.py
class CurveFractalFunction(FractalFunction):
"""Base class for curve-based fractals.
This class extends FractalFunction to handle fractals based on iterative curve
generation, like the Cantor set, Dragon curve, and space-filling curves.
Args:
*x (UniversalArray): Input points defining the curve space
max_iter (int, optional): Maximum number of iterations. Defaults to 100.
scale_factor (float, optional): Scale factor between iterations.
Defaults to 0.5.
fractal_dimension (float, optional): Fractal dimension of the curve.
Defaults to 2.0.
"""
def __init__(
self,
*x: UniversalArray,
max_iter: int = 100,
scale_factor: float = 0.5,
fractal_dimension: float = 2.0,
) -> None:
"""Initialize the curve fractal function."""
super().__init__(*x, max_iter=max_iter)
self.scale_factor = scale_factor
self.fractal_dimension = fractal_dimension
def generate_points(self) -> np.ndarray:
"""Generate points for the curve at the current iteration.
Returns:
np.ndarray: Array of points defining the curve
"""
raise NotImplementedError
__init__(*x, max_iter=100, scale_factor=0.5, fractal_dimension=2.0)
¶
Initialize the curve fractal function.
Source code in umf/meta/functions.py
generate_points()
¶
Generate points for the curve at the current iteration.
Returns:
Type | Description |
---|---|
ndarray | np.ndarray: Array of points defining the curve |
DiscreteDistributionBase
¶
Bases: ABC
Base class for discrete distributions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x | UniversalArray | Input data, which currently must be one dimensional. | () |
mu | float | Mean of the distribution. Defaults to 0. | required |
cumulative | bool | Whether to return the cumulative distribution function. Defaults to False. | False |
Raises:
Type | Description |
---|---|
MissingXError | If no input data is specified. |
OutOfDimensionError | If the input data has more than one dimension. |
Source code in umf/meta/functions.py
class DiscreteDistributionBase(ABC, metaclass=CoreElements):
"""Base class for discrete distributions.
Args:
x (UniversalArray): Input data, which currently must be one dimensional.
mu (float): Mean of the distribution. Defaults to 0.
cumulative (bool): Whether to return the cumulative distribution function.
Defaults to False.
Raises:
MissingXError: If no input data is specified.
OutOfDimensionError: If the input data has more than one dimension.
"""
def __init__(
self,
*x: UniversalArray,
cumulative: bool = False,
) -> None:
"""Initialize the function."""
if x is None:
raise MissingXError
if len(x) != __1d__:
raise OutOfDimensionError(
function_name=self.__class__.__name__,
dimension=__1d__,
)
self._x = x[0]
self.cumulative = cumulative
@property
def __input__(self) -> UniversalArrayTuple:
"""Return the input data."""
return (np.array(self._x),)
@property
def __eval__(self) -> UniversalArray:
"""Evaluate the function."""
return (
self.cumulative_distribution_function()
if self.cumulative
else self.probability_mass_function()
)
@abstractmethod
def probability_mass_function(self) -> UniversalArray:
"""Return the probability mass function."""
@property
@abstractmethod
def __summary__(self) -> SummaryStatisticsAPI:
"""Return the summary statistics."""
def cumulative_distribution_function(self) -> UniversalArray:
"""Return the cumulative distribution function."""
raise NoCumulativeError
def __call__(self) -> ResultsDistributionAPI:
"""Return the results of the function."""
return ResultsDistributionAPI(
x=self.__input__,
result=self.__eval__,
summary=self.__summary__,
doc=self.__doc__,
)
__eval__
property
¶
Evaluate the function.
__input__
property
¶
Return the input data.
__summary__
abstractmethod
property
¶
Return the summary statistics.
__call__()
¶
__init__(*x, cumulative=False)
¶
Initialize the function.
Source code in umf/meta/functions.py
cumulative_distribution_function()
¶
probability_mass_function()
abstractmethod
¶
DiscreteP
¶
Bases: DiscreteDistributionBase
Base class for discrete distributions with a probability parameter.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x | UniversalArray | Input data, which currently must be one dimensional. | () |
p | float | Probability parameter of the distribution. Defaults to 0.5. | 0.5 |
cumulative | bool | Whether to return the cumulative distribution function. Defaults to False. | False |
Raises:
Type | Description |
---|---|
MissingXError | If no input data is specified. |
Source code in umf/meta/functions.py
class DiscreteP(DiscreteDistributionBase):
"""Base class for discrete distributions with a probability parameter.
Args:
x (UniversalArray): Input data, which currently must be one dimensional.
p (float): Probability parameter of the distribution. Defaults to 0.5.
cumulative (bool): Whether to return the cumulative distribution function.
Defaults to False.
Raises:
MissingXError: If no input data is specified.
"""
def __init__(
self,
*x: UniversalArray,
p: float = 0.5,
cumulative: bool = False,
) -> None:
"""Initialize the function."""
super().__init__(*x, cumulative=cumulative)
if p < 0 or p > 1:
raise OutOfRangeError(
function_name=self.__class__.__name__,
start_range=0,
end_range=1,
)
self.p = p
self.q = 1 - p
__init__(*x, p=0.5, cumulative=False)
¶
Initialize the function.
Source code in umf/meta/functions.py
def __init__(
self,
*x: UniversalArray,
p: float = 0.5,
cumulative: bool = False,
) -> None:
"""Initialize the function."""
super().__init__(*x, cumulative=cumulative)
if p < 0 or p > 1:
raise OutOfRangeError(
function_name=self.__class__.__name__,
start_range=0,
end_range=1,
)
self.p = p
self.q = 1 - p
DiscretePure
¶
Bases: DiscreteDistributionBase
Base class for discrete distributions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x | UniversalArray | Input data, which currently must be one dimensional. | () |
mu | float | Mean of the distribution. Defaults to 0. | required |
cumulative | bool | Whether to return the cumulative distribution function. Defaults to False. | False |
Raises:
Type | Description |
---|---|
MissingXError | If no input data is specified. |
OutOfDimensionError | If the input data has more than one dimension. |
Source code in umf/meta/functions.py
class DiscretePure(DiscreteDistributionBase):
"""Base class for discrete distributions.
Args:
x (UniversalArray): Input data, which currently must be one dimensional.
mu (float): Mean of the distribution. Defaults to 0.
cumulative (bool): Whether to return the cumulative distribution function.
Defaults to False.
Raises:
MissingXError: If no input data is specified.
OutOfDimensionError: If the input data has more than one dimension.
"""
DynamicFractalFunction
¶
Bases: FractalFunction
Base class for fractals generated by dynamic systems.
This class handles fractals that emerge from iterating dynamic systems, like attractors and percolation models.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*x | UniversalArray | Input data, which can vary depending on the specific fractal. | () |
max_iter | int | Maximum number of iterations. Defaults to 1000. | 1000 |
transient_steps | int | Initial steps to discard. Defaults to 100. | 100 |
fractal_dimension | float | Fractal dimension of the system. Defaults to 2.0. | 2.0 |
Source code in umf/meta/functions.py
class DynamicFractalFunction(FractalFunction):
"""Base class for fractals generated by dynamic systems.
This class handles fractals that emerge from iterating dynamic systems,
like attractors and percolation models.
Args:
*x (UniversalArray): Input data, which can vary depending on the specific
fractal.
max_iter (int, optional): Maximum number of iterations. Defaults to 1000.
transient_steps (int, optional): Initial steps to discard. Defaults to 100.
fractal_dimension (float, optional): Fractal dimension of the system.
Defaults to 2.0.
"""
def __init__(
self,
*x: UniversalArray,
max_iter: int = 1000,
transient_steps: int = 100,
fractal_dimension: float = 2.0,
) -> None:
"""Initialize the dynamic fractal function."""
super().__init__(*x, max_iter=max_iter)
self.transient_steps = transient_steps
self.fractal_dimension: float = fractal_dimension
def iterate_system(self, initial_state: np.ndarray) -> np.ndarray:
"""Iterate the dynamic system.
Args:
initial_state (np.ndarray): Starting state of the system
Returns:
np.ndarray: Array of system states
"""
raise NotImplementedError
__init__(*x, max_iter=1000, transient_steps=100, fractal_dimension=2.0)
¶
Initialize the dynamic fractal function.
Source code in umf/meta/functions.py
def __init__(
self,
*x: UniversalArray,
max_iter: int = 1000,
transient_steps: int = 100,
fractal_dimension: float = 2.0,
) -> None:
"""Initialize the dynamic fractal function."""
super().__init__(*x, max_iter=max_iter)
self.transient_steps = transient_steps
self.fractal_dimension: float = fractal_dimension
iterate_system(initial_state)
¶
Iterate the dynamic system.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
initial_state | ndarray | Starting state of the system | required |
Returns:
Type | Description |
---|---|
ndarray | np.ndarray: Array of system states |
FractalFunction
¶
Bases: ABC
Base class for fractal functions.
This class provides a template for implementing fractal generation algorithms. It defines the basic interface for all fractal functions including inputs, iteration control, and evaluation methods.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*x | UniversalArray | Input parameters for the fractal (coordinates, complex values, etc.) | () |
max_iter | int | Maximum number of iterations for the fractal generation. | 100 |
scale_factor | float | Scaling factor for certain fractals. | None |
Source code in umf/meta/functions.py
class FractalFunction(ABC, metaclass=CoreElements):
"""Base class for fractal functions.
This class provides a template for implementing fractal generation algorithms.
It defines the basic interface for all fractal functions including inputs,
iteration control, and evaluation methods.
Args:
*x (UniversalArray): Input parameters for the fractal (coordinates,
complex values, etc.)
max_iter (int): Maximum number of iterations for the fractal generation.
scale_factor (float, optional): Scaling factor for certain fractals.
"""
def __init__(
self,
*x: UniversalArray,
max_iter: int = 100,
scale_factor: float | None = None,
) -> None:
"""Initialize the fractal function."""
if x[0] is None:
raise MissingXError
# Store input as a tuple of UniversalArray objects
self._x: tuple[UniversalArray, ...] = x
self.max_iter = max_iter
self.scale_factor = scale_factor
self.fractal_dimension = 0.0 # Default dimension, to be overridden
@property
def __input__(self) -> UniversalArrayTuple:
"""Return the input data.
Returns:
UniversalArrayTuple: Tuple of input arrays
"""
return self._x
@property
@abstractmethod
def __eval__(self) -> UniversalArray | list | dict:
"""Generate the fractal.
This method should implement the actual fractal generation algorithm.
Returns:
UniversalArray | list | dict: Fractal representation, which could be:
- Array of iteration counts (e.g., for Mandelbrot set)
- List of coordinates (e.g., for Koch curve)
- Dictionary of parameters and values (e.g., for L-systems)
"""
def calculate_dimension(self) -> float | None:
"""Calculate the fractal dimension.
For many fractals, this is a fixed value that can be calculated analytically.
For others, it may require box-counting or other numerical methods.
Returns:
float | None: Fractal dimension if available, otherwise None
"""
return getattr(self, "fractal_dimension", None)
def __call__(self) -> ResultsFractalAPI:
"""Return the results of the fractal function.
Returns:
ResultsFractalAPI: Object containing the fractal data and metadata
"""
parameters = {
"max_iter": self.max_iter,
}
if self.scale_factor is not None:
parameters["scale_factor"] = self.scale_factor
return ResultsFractalAPI(
x=self.__input__,
result=self.__eval__,
parameters=parameters,
dimension=self.calculate_dimension(),
doc=self.__doc__,
)
__eval__
abstractmethod
property
¶
Generate the fractal.
This method should implement the actual fractal generation algorithm.
Returns:
Type | Description |
---|---|
UniversalArray | list | dict | UniversalArray | list | dict: Fractal representation, which could be: - Array of iteration counts (e.g., for Mandelbrot set) - List of coordinates (e.g., for Koch curve) - Dictionary of parameters and values (e.g., for L-systems) |
__input__
property
¶
Return the input data.
Returns:
Name | Type | Description |
---|---|---|
UniversalArrayTuple | UniversalArrayTuple | Tuple of input arrays |
__call__()
¶
Return the results of the fractal function.
Returns:
Name | Type | Description |
---|---|---|
ResultsFractalAPI | ResultsFractalAPI | Object containing the fractal data and metadata |
Source code in umf/meta/functions.py
def __call__(self) -> ResultsFractalAPI:
"""Return the results of the fractal function.
Returns:
ResultsFractalAPI: Object containing the fractal data and metadata
"""
parameters = {
"max_iter": self.max_iter,
}
if self.scale_factor is not None:
parameters["scale_factor"] = self.scale_factor
return ResultsFractalAPI(
x=self.__input__,
result=self.__eval__,
parameters=parameters,
dimension=self.calculate_dimension(),
doc=self.__doc__,
)
__init__(*x, max_iter=100, scale_factor=None)
¶
Initialize the fractal function.
Source code in umf/meta/functions.py
def __init__(
self,
*x: UniversalArray,
max_iter: int = 100,
scale_factor: float | None = None,
) -> None:
"""Initialize the fractal function."""
if x[0] is None:
raise MissingXError
# Store input as a tuple of UniversalArray objects
self._x: tuple[UniversalArray, ...] = x
self.max_iter = max_iter
self.scale_factor = scale_factor
self.fractal_dimension = 0.0 # Default dimension, to be overridden
calculate_dimension()
¶
Calculate the fractal dimension.
For many fractals, this is a fixed value that can be calculated analytically. For others, it may require box-counting or other numerical methods.
Returns:
Type | Description |
---|---|
float | None | float | None: Fractal dimension if available, otherwise None |
Source code in umf/meta/functions.py
def calculate_dimension(self) -> float | None:
"""Calculate the fractal dimension.
For many fractals, this is a fixed value that can be calculated analytically.
For others, it may require box-counting or other numerical methods.
Returns:
float | None: Fractal dimension if available, otherwise None
"""
return getattr(self, "fractal_dimension", None)
GeometricFractalFunction
¶
Bases: FractalFunction
Base class for fractals based on geometric transformations.
This class handles self-similar fractals generated through geometric transformations, like the Sierpinski triangle and Koch snowflake.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*x | UniversalArray | Initial geometric shape vertices | () |
max_iter | int | Maximum number of iterations. Defaults to 6. | 6 |
scale_factor | float | Scale factor for transformations. Defaults to 0.5. | 0.5 |
fractal_dimension | float | Fractal dimension of the shape. Defaults to 2.0. | 2.0 |
Source code in umf/meta/functions.py
class GeometricFractalFunction(FractalFunction):
"""Base class for fractals based on geometric transformations.
This class handles self-similar fractals generated through geometric
transformations, like the Sierpinski triangle and Koch snowflake.
Args:
*x (UniversalArray): Initial geometric shape vertices
max_iter (int, optional): Maximum number of iterations. Defaults to 6.
scale_factor (float, optional): Scale factor for transformations. Defaults
to 0.5.
fractal_dimension (float, optional): Fractal dimension of the shape.
Defaults to 2.0.
"""
def __init__(
self,
*x: UniversalArray,
max_iter: int = 6,
scale_factor: float = 0.5,
fractal_dimension: float = 2.0,
) -> None:
"""Initialize the geometric fractal function."""
super().__init__(*x, max_iter=max_iter)
self.scale_factor = scale_factor
self.fractal_dimension = fractal_dimension
def transform_points(self, points: np.ndarray) -> list[np.ndarray]:
"""Apply geometric transformations to points.
Args:
points (np.ndarray): Array of points to transform
Returns:
list[np.ndarray]: List of transformed point arrays
"""
raise NotImplementedError
__init__(*x, max_iter=6, scale_factor=0.5, fractal_dimension=2.0)
¶
Initialize the geometric fractal function.
Source code in umf/meta/functions.py
transform_points(points)
¶
Apply geometric transformations to points.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
points | ndarray | Array of points to transform | required |
Returns:
Type | Description |
---|---|
list[ndarray] | list[np.ndarray]: List of transformed point arrays |
Source code in umf/meta/functions.py
HyperbolicFunction
¶
Bases: ABC
Class for hyperbolic functions.
Source code in umf/meta/functions.py
class HyperbolicFunction(ABC, metaclass=CoreElements):
"""Class for hyperbolic functions."""
def __init__(self, *args: UniversalArray) -> None:
"""Initialize the hyperbolic function."""
if args[0] is None:
raise MissingXError
self._x: tuple[UniversalArray, ...] = args
self.dimension: int = len(args)
@property
def __input__(self) -> UniversalArrayTuple:
"""Return the input data for the hyperbolic function."""
return self._x
@property
@abstractmethod
def __eval__(self) -> UniversalArray:
"""Evaluate the hyperbolic function."""
def __call__(self) -> ResultsHyperbolicAPI:
"""Return the results of the hyperbolic function."""
return ResultsHyperbolicAPI(
x=self.__input__,
result=np.asarray(self.__eval__),
doc=self.__doc__,
)
OptFunction
¶
Bases: ABC
Base class for functions for optimization.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x | UniversalArray | Input data, which can be one, two, three, or higher dimensional. | () |
kwargs | Keyword arguments for the function. | required |
Raises:
Type | Description |
---|---|
MissingXError | If no input data is specified. |
Source code in umf/meta/functions.py
class OptFunction(ABC, metaclass=CoreElements):
"""Base class for functions for optimization.
Args:
x: Input data, which can be one, two, three, or higher dimensional.
kwargs: Keyword arguments for the function.
Raises:
MissingXError: If no input data is specified.
"""
def __init__(self, *x: UniversalArray) -> None:
"""Initialize the function."""
if x[0] is None:
raise MissingXError
if isinstance(x, tuple):
for i in x:
if not isinstance(i, np.ndarray):
raise NotTupleArrayError
self._x: tuple[UniversalArray, ...] = x
self.dimension: int = len(x)
@property
def __input__(self) -> UniversalArrayTuple:
"""Return the input data."""
return self._x
@property
@abstractmethod
def __eval__(self) -> UniversalArray:
"""Evaluate the function."""
@property
@abstractmethod
def __minima__(self) -> MinimaAPI:
"""Return the zero function."""
def __call__(self) -> ResultsFunctionAPI:
"""Return the results of the function."""
return ResultsFunctionAPI(
x=self.__input__,
result=self.__eval__,
minima=self.__minima__,
doc=self.__doc__,
)
OscillatorsFunc2D
¶
Bases: OscillatorsFuncBase
Base class for two-dimensional chaotic oscillators.
Source code in umf/meta/functions.py
class OscillatorsFunc2D(OscillatorsFuncBase):
"""Base class for two-dimensional chaotic oscillators."""
@property
def to_position(self) -> UniversalArrayTuple:
"""Return the position of the oscillator."""
y = self.solve()
return y[:, 0], y[:, 2]
@property
def to_velocity(self) -> UniversalArrayTuple:
"""Return the velocity of the oscillator."""
y = self.solve()
return y[:, 1], y[:, 3]
OscillatorsFunc3D
¶
Bases: OscillatorsFuncBase
Base class for three-dimensional chaotic oscillators.
Source code in umf/meta/functions.py
class OscillatorsFunc3D(OscillatorsFuncBase):
"""Base class for three-dimensional chaotic oscillators."""
@property
def to_position(self) -> UniversalArrayTuple:
"""Return the position of the oscillator."""
y = self.solve()
return y[:, 0], y[:, 1], y[:, 2]
@property
def to_velocity(self) -> UniversalArrayTuple:
"""Return the velocity of the oscillator."""
y = self.solve()
return y[:, 3], y[:, 4], y[:, 5]
OscillatorsFuncBase
¶
Bases: ABC
Base class for chaotic oscillators.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*time_points | UniversalArray | The array of time points at which the oscillator's state is evaluated. | required |
time_format | str | The format of the time data. Defaults to "seconds". | 'seconds' |
velocity | bool | Whether to return the velocity of the oscillator. Defaults to False. | False |
Raises:
Type | Description |
---|---|
MissingXError | If no input data is specified. |
OutOfDimensionError | If the input data has more than one dimension. |
TimeFormatError | If the time format is not valid. |
Source code in umf/meta/functions.py
class OscillatorsFuncBase(ABC, metaclass=CoreElements):
"""Base class for chaotic oscillators.
Args:
*time_points (UniversalArray): The array of time points at which the
oscillator's state is evaluated.
time_format (str): The format of the time data. Defaults to "seconds".
velocity (bool): Whether to return the velocity of the oscillator.
Defaults to False.
Raises:
MissingXError: If no input data is specified.
OutOfDimensionError: If the input data has more than one dimension.
TimeFormatError: If the time format is not valid.
"""
def __init__(
self,
*t: UniversalArray,
time_format: str = "seconds",
velocity: bool = False,
) -> None:
"""Initialize the function."""
if t[0] is None:
raise MissingXError
if len(t) != __1d__:
raise OutOfDimensionError(
function_name=self.__class__.__name__,
dimension=__1d__,
)
self.time_format = time_format
self.t = self.convert2sec(t[0])
self.velocity = velocity
def convert2sec(self, t: UniversalArray) -> UniversalArray:
"""Convert the time data to seconds.
Args:
t (UniversalArray): The initial time data as input.
Returns:
UniversalArray: The time data converted to seconds.
"""
conversion_factors = {"seconds": 1, "minutes": 60, "hours": 3600, "days": 86400}
if self.time_format in conversion_factors:
return t * conversion_factors[self.time_format]
raise TimeFormatError(
time_format=self.time_format,
valid_formats=list(conversion_factors.keys()),
)
@property
def __input__(self) -> UniversalArrayTuple:
"""Return the input data."""
return (self.t,)
def setup_initial_state(self) -> UniversalArray:
"""Setup the initial state of the oscillator."""
raise NotImplementedError
@property
@abstractmethod
def __initial_configuration__(self) -> dict[str, UniversalArray]:
"""Initialize the state of the oscillator."""
@property
@abstractmethod
def initial_state(self) -> list[float]:
"""Return the initial state of the oscillator."""
@abstractmethod
def equation_of_motion(self, initial_state: list[float], t: float) -> tuple:
"""Return the equation of motion of the oscillator."""
def solve(self, **kwargs: dict[str, Any]) -> UniversalArrayTuple:
"""Solve the equation of motion of the oscillator."""
return odeint(
func=self.equation_of_motion,
y0=self.initial_state,
t=self.t,
**kwargs,
)
@property
@abstractmethod
def to_position(self) -> UniversalArray:
"""Return the position of the oscillator."""
@property
@abstractmethod
def to_velocity(self) -> UniversalArray:
"""Return the velocity of the oscillator."""
@property
def __eval__(self) -> UniversalArray:
"""Evaluate the function."""
return self.to_velocity if self.velocity else self.to_position
def __call__(self) -> ResultsChaoticOscillatorAPI:
"""Return the results of the function."""
return ResultsChaoticOscillatorAPI(
t=self.__input__,
result=self.__eval__,
initial_state=self.__initial_configuration__,
doc=self.__doc__,
)
__eval__
property
¶
Evaluate the function.
__initial_configuration__
abstractmethod
property
¶
Initialize the state of the oscillator.
__input__
property
¶
Return the input data.
initial_state
abstractmethod
property
¶
Return the initial state of the oscillator.
to_position
abstractmethod
property
¶
Return the position of the oscillator.
to_velocity
abstractmethod
property
¶
Return the velocity of the oscillator.
__call__()
¶
Return the results of the function.
__init__(*t, time_format='seconds', velocity=False)
¶
Initialize the function.
Source code in umf/meta/functions.py
def __init__(
self,
*t: UniversalArray,
time_format: str = "seconds",
velocity: bool = False,
) -> None:
"""Initialize the function."""
if t[0] is None:
raise MissingXError
if len(t) != __1d__:
raise OutOfDimensionError(
function_name=self.__class__.__name__,
dimension=__1d__,
)
self.time_format = time_format
self.t = self.convert2sec(t[0])
self.velocity = velocity
convert2sec(t)
¶
Convert the time data to seconds.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
t | UniversalArray | The initial time data as input. | required |
Returns:
Name | Type | Description |
---|---|---|
UniversalArray | UniversalArray | The time data converted to seconds. |
Source code in umf/meta/functions.py
def convert2sec(self, t: UniversalArray) -> UniversalArray:
"""Convert the time data to seconds.
Args:
t (UniversalArray): The initial time data as input.
Returns:
UniversalArray: The time data converted to seconds.
"""
conversion_factors = {"seconds": 1, "minutes": 60, "hours": 3600, "days": 86400}
if self.time_format in conversion_factors:
return t * conversion_factors[self.time_format]
raise TimeFormatError(
time_format=self.time_format,
valid_formats=list(conversion_factors.keys()),
)
equation_of_motion(initial_state, t)
abstractmethod
¶
setup_initial_state()
¶
solve(**kwargs)
¶
Solve the equation of motion of the oscillator.
PathologicalBase
¶
Bases: ABC
Base class for pathological functions.
This class serves as a template for creating objects that represent pathological functions. These functions are defined over a specific interval and are characterized by their shape parameters. The class provides the structure for handling input data, defining the interval of interest, and specifying the shape parameters of the function.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x | UniversalArray | Input data, which currently must be one-dimensional. | () |
n_0 | int | Start of the interval. Defaults to 0. | 0 |
n_1 | int | End of the interval. Defaults to 100. | 100 |
max_safe_exponent | int | float | Maximum safe exponent. Defaults to 200. | 200 |
Raises:
Type | Description |
---|---|
MissingXError | If no input data (x) is specified. This error is raised to ensure that the function has the necessary data to operate on. |
OutOfDimensionError | If the input data (x) has more than one dimension. This error is raised because the function is designed to work with one-dimensional data only. |
Source code in umf/meta/functions.py
class PathologicalBase(ABC, metaclass=CoreElements):
"""Base class for pathological functions.
This class serves as a template for creating objects that represent pathological
functions. These functions are defined over a specific interval and are
characterized by their shape parameters. The class provides the structure
for handling input data, defining the interval of interest, and specifying
the shape parameters of the function.
Args:
x (UniversalArray): Input data, which currently must be one-dimensional.
n_0 (int): Start of the interval. Defaults to 0.
n_1 (int): End of the interval. Defaults to 100.
max_safe_exponent (int | float): Maximum safe exponent. Defaults to 200.
Raises:
MissingXError: If no input data (x) is specified. This error is raised to ensure
that the function has the necessary data to operate on.
OutOfDimensionError: If the input data (x) has more than one dimension.
This error is raised because the function is designed to work with
one-dimensional data only.
"""
def __init__(
self,
*x: UniversalArray,
n_0: int = 0,
n_1: int = 100,
max_safe_exponent: float = 200,
) -> None:
"""Initialize the function."""
if x[0] is None:
raise MissingXError
if len(x) != __1d__:
raise OutOfDimensionError(
function_name=self.__class__.__name__,
dimension=__1d__,
)
if np.abs(n_1) > max_safe_exponent:
raise ExcessiveExponentError(
max_exponent=max_safe_exponent,
current_exponent=n_1,
)
self._x = x[0]
self.n_0 = n_0
self.n_1 = n_1
@property
def __input__(self) -> UniversalArrayTuple:
"""Return the input data."""
return (np.array(self._x),)
@property
@abstractmethod
def __eval__(self) -> UniversalArray:
"""Evaluate the function."""
def __call__(self) -> ResultsPathologicalAPI:
"""Return the results of the function."""
return ResultsPathologicalAPI(
x=self.__input__,
result=self.__eval__,
doc=self.__doc__,
)
__eval__
abstractmethod
property
¶
Evaluate the function.
__input__
property
¶
Return the input data.
__call__()
¶
__init__(*x, n_0=0, n_1=100, max_safe_exponent=200)
¶
Initialize the function.
Source code in umf/meta/functions.py
def __init__(
self,
*x: UniversalArray,
n_0: int = 0,
n_1: int = 100,
max_safe_exponent: float = 200,
) -> None:
"""Initialize the function."""
if x[0] is None:
raise MissingXError
if len(x) != __1d__:
raise OutOfDimensionError(
function_name=self.__class__.__name__,
dimension=__1d__,
)
if np.abs(n_1) > max_safe_exponent:
raise ExcessiveExponentError(
max_exponent=max_safe_exponent,
current_exponent=n_1,
)
self._x = x[0]
self.n_0 = n_0
self.n_1 = n_1
PathologicalPure
¶
Bases: PathologicalBase
Base class for pathological functions with a standard deviation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x | UniversalArray | Input data, which currently must be one-dimensional. | () |
n_0 | int | Start of the interval. Defaults to 0. | 0 |
n_1 | int | End of the interval. Defaults to 100. | 100 |
Source code in umf/meta/functions.py
class PathologicalPure(PathologicalBase):
"""Base class for pathological functions with a standard deviation.
Args:
x (UniversalArray): Input data, which currently must be one-dimensional.
n_0 (int): Start of the interval. Defaults to 0.
n_1 (int): End of the interval. Defaults to 100.
"""
def __init__(
self,
*x: UniversalArray,
n_0: int = 0,
n_1: int = 100,
) -> None:
"""Initialize the function."""
super().__init__(*x, n_0=n_0, n_1=n_1)
__init__(*x, n_0=0, n_1=100)
¶
PathologicalWithCoefficients
¶
Bases: PathologicalBase
Base class for pathological functions with coefficients.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x | UniversalArray | Input data, which currently must be one-dimensional. | () |
n_1 | int | End of the interval. Defaults to 100. | 100 |
a | float | First shape parameter of the function. | required |
b | float | Second shape parameter of the function. | required |
Source code in umf/meta/functions.py
class PathologicalWithCoefficients(PathologicalBase):
"""Base class for pathological functions with coefficients.
Args:
x (UniversalArray): Input data, which currently must be one-dimensional.
n_1 (int): End of the interval. Defaults to 100.
a (float): First shape parameter of the function.
b (float): Second shape parameter of the function.
"""
def __init__(
self,
*x: UniversalArray,
n_0: int = 0,
n_1: int = 100,
a: float,
b: float,
) -> None:
"""Initialize the function."""
super().__init__(*x, n_0=n_0, n_1=n_1)
self.a = a
self.b = b
__init__(*x, n_0=0, n_1=100, a, b)
¶
SemiContinuous
¶
Bases: ContinuousDistributionBase
Base class for semi continuous distributions with a standard deviation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x | UniversalArray | Input data, which currently must be one dimensional. | () |
mu | float | Mean of the distribution. Defaults to 0. | 0 |
cumulative | bool | Whether to return the cumulative distribution function. Defaults to False. | False |
Raises:
Type | Description |
---|---|
MissingXError | If no input data is specified. |
OutOfDimensionError | If the input data has more than one dimension. |
Source code in umf/meta/functions.py
class SemiContinuous(ContinuousDistributionBase):
"""Base class for semi continuous distributions with a standard deviation.
Args:
x (UniversalArray): Input data, which currently must be one dimensional.
mu (float): Mean of the distribution. Defaults to 0.
cumulative (bool): Whether to return the cumulative distribution function.
Defaults to False.
Raises:
MissingXError: If no input data is specified.
OutOfDimensionError: If the input data has more than one dimension.
"""
SemiContinuousWBeta
¶
Bases: ContinuousDistributionBase
Base class for continuous distributions with beta parameter.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x | UniversalArray | Input data, which currently must be one dimensional. | () |
mu | float | Mean of the distribution. Defaults to 0. | 0 |
beta | float | Shape parameter of the distribution. Defaults to 1. | 1 |
cumulative | bool | Whether to return the cumulative distribution function. Defaults to False. | False |
Raises:
Type | Description |
---|---|
MissingXError | If no input data is specified. |
OutOfDimensionError | If the input data has more than one dimension. |
Source code in umf/meta/functions.py
class SemiContinuousWBeta(ContinuousDistributionBase):
"""Base class for continuous distributions with beta parameter.
Args:
x (UniversalArray): Input data, which currently must be one dimensional.
mu (float): Mean of the distribution. Defaults to 0.
beta (float): Shape parameter of the distribution. Defaults to 1.
cumulative (bool): Whether to return the cumulative distribution function.
Defaults to False.
Raises:
MissingXError: If no input data is specified.
OutOfDimensionError: If the input data has more than one dimension.
"""
def __init__(
self,
*x: UniversalArray,
mu: float = 0,
beta: float = 1,
cumulative: bool = False,
) -> None:
"""Initialize the function."""
if (min_x := np.min(x)) < 0:
raise NotAPositiveNumberError(var_number="*x", number=float(min_x))
super().__init__(*x, mu=mu, cumulative=cumulative)
if beta <= 0:
raise NotAPositiveNumberError(var_number="beta", number=beta)
self.beta = beta
__init__(*x, mu=0, beta=1, cumulative=False)
¶
Initialize the function.
Source code in umf/meta/functions.py
def __init__(
self,
*x: UniversalArray,
mu: float = 0,
beta: float = 1,
cumulative: bool = False,
) -> None:
"""Initialize the function."""
if (min_x := np.min(x)) < 0:
raise NotAPositiveNumberError(var_number="*x", number=float(min_x))
super().__init__(*x, mu=mu, cumulative=cumulative)
if beta <= 0:
raise NotAPositiveNumberError(var_number="beta", number=beta)
self.beta = beta
SemiContinuousWSigma
¶
Bases: ContinuousDistributionBase
Base class for continuous distributions with a standard deviation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x | UniversalArray | Input data, which currently must be one dimensional. | () |
mu | float | Mean of the distribution. Defaults to 0. | 0 |
sigma | float | Standard deviation of the distribution. Defaults to 1. | 1 |
cumulative | bool | Whether to return the cumulative distribution function. Defaults to False. | False |
Raises:
Type | Description |
---|---|
MissingXError | If no input data is specified. |
OutOfDimensionError | If the input data has more than one dimension. |
Source code in umf/meta/functions.py
class SemiContinuousWSigma(ContinuousDistributionBase):
"""Base class for continuous distributions with a standard deviation.
Args:
x (UniversalArray): Input data, which currently must be one dimensional.
mu (float): Mean of the distribution. Defaults to 0.
sigma (float): Standard deviation of the distribution. Defaults to 1.
cumulative (bool): Whether to return the cumulative distribution function.
Defaults to False.
Raises:
MissingXError: If no input data is specified.
OutOfDimensionError: If the input data has more than one dimension.
"""
def __init__(
self,
*x: UniversalArray,
mu: float = 0,
sigma: float = 1,
cumulative: bool = False,
) -> None:
"""Initialize the function."""
if np.min(x) < 0:
raise NotAPositiveNumberError(var_number="*x", number=float(np.min(x)))
super().__init__(*x, mu=mu, cumulative=cumulative)
self.sigma = sigma
__init__(*x, mu=0, sigma=1, cumulative=False)
¶
Initialize the function.
Source code in umf/meta/functions.py
def __init__(
self,
*x: UniversalArray,
mu: float = 0,
sigma: float = 1,
cumulative: bool = False,
) -> None:
"""Initialize the function."""
if np.min(x) < 0:
raise NotAPositiveNumberError(var_number="*x", number=float(np.min(x)))
super().__init__(*x, mu=mu, cumulative=cumulative)
self.sigma = sigma
Abstract class for plotting functions.
About
This module defines an abstract class Plot
and a named tuple GraphSettings
for plotting functions.
GraphSettings
: A class for named tuples which defines the settings for the graph, such as size, dpi, axis labels, title, color, colormap, and alpha value.Plot
: An abstract class that defines methods for plotting data in 2D, 3D, contour, surface, and dashboard formats, as well as animating the plot. It also defines abstract methods for showing and saving the plot.
AnimationSettings
¶
Bases: NamedTuple
A named tuple representing the settings for the animation of a 2D and 3D plot.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
frames | int | The number of frames in the animation. Defaults to 40. | required |
interval | int | The delay between frames in milliseconds. Defaults to 30. | required |
dpi | int | The resolution of the output animation in dots per inch. Defaults to 100. | required |
steps | int | The number of steps in the animation. Defaults to 100. | required |
transperent | bool | Whether or not to make the background of the animation transparent. Defaults to False. | required |
Source code in umf/meta/plots.py
class AnimationSettings(NamedTuple):
"""A named tuple representing the settings for the animation of a 2D and 3D plot.
Args:
frames (int, optional): The number of frames in the animation. Defaults to 40.
interval (int, optional): The delay between frames in milliseconds. Defaults
to 30.
dpi (int, optional): The resolution of the output animation in dots per inch.
Defaults to 100.
steps (int, optional): The number of steps in the animation. Defaults to 100.
transperent (bool, optional): Whether or not to make the background of the
animation transparent. Defaults to False.
"""
frames: int = 40
interval: int = 30
dpi: int = 100
steps: int = 100
transperent: bool = False
GIFSettings
¶
Bases: NamedTuple
A named tuple representing the settings for the GIF animation of a 3D plot.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dpi | int | The resolution of the output GIF in dots per inch. Defaults to 100. | required |
zoom | bool | Whether or not to include a zoom effect in the animation. Defaults to True. | required |
zoom_start | float | The starting zoom level for the zoom effect. Defaults to 0.5. | required |
zoom_stop | float | The ending zoom level for the zoom effect. Defaults to 1.5. | required |
rotate | bool | Whether or not to include a rotation effect in the animation. Defaults to True. | required |
elev | int | The elevation angle of the plot in degrees. Defaults to 30. | required |
azim | int | The azimuth angle of the plot in degrees. Defaults to 5. | required |
frames | int | The number of frames in the animation. Defaults to 72. | required |
interval | int | The delay between frames in milliseconds. Defaults to 50. | required |
transperent | bool | Whether or not to make the background of the GIF transparent. Defaults to False. | required |
Source code in umf/meta/plots.py
class GIFSettings(NamedTuple):
"""A named tuple representing the settings for the GIF animation of a 3D plot.
Args:
dpi (int, optional): The resolution of the output GIF in dots per inch.
Defaults to 100.
zoom (bool, optional): Whether or not to include a zoom effect in the animation.
Defaults to True.
zoom_start (float, optional): The starting zoom level for the zoom effect.
Defaults to 0.5.
zoom_stop (float, optional): The ending zoom level for the zoom effect.
Defaults to 1.5.
rotate (bool, optional): Whether or not to include a rotation effect in the
animation. Defaults to True.
elev (int, optional): The elevation angle of the plot in degrees. Defaults to
30.
azim (int, optional): The azimuth angle of the plot in degrees. Defaults to 5.
frames (int, optional): The number of frames in the animation. Defaults to 72.
interval (int, optional): The delay between frames in milliseconds. Defaults to
50.
transperent (bool, optional): Whether or not to make the background of the GIF
transparent. Defaults to False.
"""
dpi: int = 100
zoom: bool = True
zoom_start: float = 0.5
zoom_stop: float = 1.5
rotate: bool = True
elev: int = 30
azim: int = 5
frames: int = 72
interval: int = 50
transperent: bool = False
GraphSettings
¶
Bases: NamedTuple
Settings for the graph.
Attributes:
Name | Type | Description |
---|---|---|
size | tuple[int, int] | The size of the plot. Defaults to (5, 5). |
dpi | int | The DPI of the plot. Defaults to 200. |
axis | list[str] | The labels for the axes of the plot. Defaults to None. |
title | str | The title of the plot. Defaults to None. |
color | str | The color of the plot. Defaults to None. |
cmap | str | The colormap of the plot. Defaults to "YlGnBu_r". |
alpha | float | The alpha value of the plot. Defaults to None. |
Source code in umf/meta/plots.py
class GraphSettings(NamedTuple):
"""Settings for the graph.
Attributes:
size (tuple[int, int]): The size of the plot. Defaults to (5, 5).
dpi (int, optional): The DPI of the plot. Defaults to 200.
axis (list[str], optional): The labels for the axes of the plot. Defaults to
None.
title (str, optional): The title of the plot. Defaults to None.
color (str, optional): The color of the plot. Defaults to None.
cmap (str, optional): The colormap of the plot. Defaults to "YlGnBu_r".
alpha (float, optional): The alpha value of the plot. Defaults to None.
"""
size: tuple[int, int] = (5, 5)
dpi: int = 200
axis: list[str] | None = None
title: str | None = None
color: str | None = None
cmap: str = "viridis_r"
alpha: float | None = None
Plot
¶
Bases: ABC
Abstract class for plotting functions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*x | UniversalArray | Input data, which can be one, two, three, or higher dimensional. | () |
**kwargs | dict[str, Any] | Additional keyword arguments to pass to the plot function. | {} |
Source code in umf/meta/plots.py
class Plot(ABC):
"""Abstract class for plotting functions.
Args:
*x (UniversalArray): Input data, which can be one, two, three, or higher
dimensional.
**kwargs (dict[str, Any]): Additional keyword arguments to pass to the plot
function.
"""
def __init__(
self,
*x: UniversalArray,
settings: GraphSettings = None,
**kwargs: dict[str, Any],
) -> None:
"""Initialize the function."""
if x is None:
msg = "x has to be specified."
raise ValueError(msg)
if settings is None:
settings = GraphSettings()
self._x = x
self.dimension = len(x)
self.title = settings.title
self.axis = (
settings.axis
if settings.axis is not None
else [f"x_{i}" for i in range(self.dimension)]
)
self.color = settings.color
self.cmap = settings.cmap
self.alpha = settings.alpha
self.size = settings.size
self.dpi = settings.dpi
self._kwargs = kwargs
def plot_2d(self) -> None:
"""Plot the data in 2D."""
raise NotImplementedError
def plot_series(self) -> None:
"""Plot the data in 2D as a series."""
raise NotImplementedError
def plot_3d(self) -> None:
"""Plot the data in 3D."""
raise NotImplementedError
def plot_contour(self) -> None:
"""Plot the data as a contour plot."""
raise NotImplementedError
def plot_surface(self) -> None:
"""Plot the data as a surface plot."""
raise NotImplementedError
def plot_dashboard(self) -> None:
"""Plot the data as a dashboard."""
raise NotImplementedError
def animate(self) -> None:
"""Animate the plot."""
raise NotImplementedError
@abstractmethod
def plot_show(self) -> None:
"""Show the plot."""
@property
@abstractmethod
def plot_return(self) -> plt.figure | go.Figure:
"""Return the plot."""
@staticmethod
def ax_return() -> plt.Figure:
"""Return the Figure."""
raise NotImplementedError
@staticmethod
@abstractmethod
def plot_save(
fig: plt.Figure | go.Figure,
fname: Path,
fformat: str = "png",
**kwargs: dict[str, Any],
) -> None:
"""Saves the given plot to a file.
Args:
fig (plt.Figure | go.Figure): The figure to save as an image file.
fname (Path): The file path to save the plot to.
fformat (str, optional): The format to save the plot as. Defaults to "png".
**kwargs (dict[str, Any]): Additional keyword arguments to pass to the save
function.
"""
@staticmethod
def plot_save_gif(
fig: plt.Figure,
ax_fig: plt.Figure,
fname: Path,
settings: GIFSettings,
**kwargs: dict[str, Any],
) -> None:
"""Saves the given plot to a file.
Notes:
This function can currently only be implemented for matplotlib plots and
not for plotly plots.
Args:
fig (plt.figure): The figure to save as an image file.
ax_fig (plt.Figure): The figure to save as an image file.
fname (Path): The file path to save the plot to.
settings (GIFSettings): The settings for the GIF animation.
**kwargs (dict[str, Any]): Additional keyword arguments to pass to the save
function.
Raises:
NotImplementedError: This function is not yet implemented.
"""
raise NotImplementedError
plot_return
abstractmethod
property
¶
Return the plot.
__init__(*x, settings=None, **kwargs)
¶
Initialize the function.
Source code in umf/meta/plots.py
def __init__(
self,
*x: UniversalArray,
settings: GraphSettings = None,
**kwargs: dict[str, Any],
) -> None:
"""Initialize the function."""
if x is None:
msg = "x has to be specified."
raise ValueError(msg)
if settings is None:
settings = GraphSettings()
self._x = x
self.dimension = len(x)
self.title = settings.title
self.axis = (
settings.axis
if settings.axis is not None
else [f"x_{i}" for i in range(self.dimension)]
)
self.color = settings.color
self.cmap = settings.cmap
self.alpha = settings.alpha
self.size = settings.size
self.dpi = settings.dpi
self._kwargs = kwargs
animate()
¶
ax_return()
staticmethod
¶
plot_2d()
¶
plot_3d()
¶
plot_contour()
¶
plot_dashboard()
¶
plot_save(fig, fname, fformat='png', **kwargs)
abstractmethod
staticmethod
¶
Saves the given plot to a file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fig | Figure | Figure | The figure to save as an image file. | required |
fname | Path | The file path to save the plot to. | required |
fformat | str | The format to save the plot as. Defaults to "png". | 'png' |
**kwargs | dict[str, Any] | Additional keyword arguments to pass to the save function. | {} |
Source code in umf/meta/plots.py
@staticmethod
@abstractmethod
def plot_save(
fig: plt.Figure | go.Figure,
fname: Path,
fformat: str = "png",
**kwargs: dict[str, Any],
) -> None:
"""Saves the given plot to a file.
Args:
fig (plt.Figure | go.Figure): The figure to save as an image file.
fname (Path): The file path to save the plot to.
fformat (str, optional): The format to save the plot as. Defaults to "png".
**kwargs (dict[str, Any]): Additional keyword arguments to pass to the save
function.
"""
plot_save_gif(fig, ax_fig, fname, settings, **kwargs)
staticmethod
¶
Saves the given plot to a file.
Notes
This function can currently only be implemented for matplotlib plots and not for plotly plots.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fig | figure | The figure to save as an image file. | required |
ax_fig | Figure | The figure to save as an image file. | required |
fname | Path | The file path to save the plot to. | required |
settings | GIFSettings | The settings for the GIF animation. | required |
**kwargs | dict[str, Any] | Additional keyword arguments to pass to the save function. | {} |
Raises:
Type | Description |
---|---|
NotImplementedError | This function is not yet implemented. |
Source code in umf/meta/plots.py
@staticmethod
def plot_save_gif(
fig: plt.Figure,
ax_fig: plt.Figure,
fname: Path,
settings: GIFSettings,
**kwargs: dict[str, Any],
) -> None:
"""Saves the given plot to a file.
Notes:
This function can currently only be implemented for matplotlib plots and
not for plotly plots.
Args:
fig (plt.figure): The figure to save as an image file.
ax_fig (plt.Figure): The figure to save as an image file.
fname (Path): The file path to save the plot to.
settings (GIFSettings): The settings for the GIF animation.
**kwargs (dict[str, Any]): Additional keyword arguments to pass to the save
function.
Raises:
NotImplementedError: This function is not yet implemented.
"""
raise NotImplementedError