Model and Parameter¶
The Model and Parameter classes are the core data structures in ezfit.
Model¶
- class ezfit.model.Model(func: Callable, params: dict[str, Parameter] | None = None, residuals: ndarray | None = None, cov: ndarray | None = None, cor: ndarray | None = None, χ2: float | None = None, rχ2: float | None = None, x_min: float | None = None, x_max: float | None = None, r_squared: float | None = None, pearson_r: float | None = None, rmse: float | None = None, rmsd: float | None = None, bic: float | None = None, aic: float | None = None, sampler_chain: ndarray | None = None)[source]¶
Bases:
objectData class for a model function and its parameters.
- __call__(x: ndarray | None = None, *, start: float | None = None, stop: float | None = None, num: int = 500, endpoint: bool = True, spacing: Literal['lin', 'log'] = 'lin') ndarray[source]¶
Evaluate the model at the given x values or generate a smooth array.
If x is provided (positional argument), it is used directly for backward compatibility. Otherwise, generates a smooth array using start/stop or stored x_bounds from fitting.
- Parameters:
x (np.ndarray | None, optional) – Direct x values to evaluate. If provided, other parameters are ignored. For backward compatibility, by default None.
start (float | None, optional) – Start value for generating x array. If None, uses stored x_min from fitting. By default None.
stop (float | None, optional) – Stop value for generating x array. If None, uses stored x_max from fitting. By default None.
num (int, optional) – Number of points to generate, by default 500.
endpoint (bool, optional) – Whether to include the stop value, by default True.
spacing (Literal["lin", "log"], optional) – Spacing type: “lin” for linear (np.linspace) or “log” for logarithmic (np.logspace), by default “lin”.
- Returns:
Model evaluation at the specified x values.
- Return type:
np.ndarray
- Raises:
ValueError – If parameters have not been initialized, or if bounds are not available and not provided.
- __setitem__(key: str, value: tuple[float, float]) None[source]¶
Set the parameter with the given key to the given value.
- bounds() tuple[list[float], list[float]][source]¶
Yield the model parameter bounds as a tuple of lists.
- get_posterior_samples(discard: int | None = None, thin: int | None = None) ndarray[source]¶
Get posterior samples from MCMC chain.
- Parameters:
- Returns:
Array of posterior samples with shape (n_samples, n_params).
- Return type:
np.ndarray
- Raises:
ValueError – If no MCMC chain is available.
- plot(x: ndarray | None = None, *, start: float | None = None, stop: float | None = None, num: int = 500, endpoint: bool = True, spacing: Literal['lin', 'log'] = 'lin', ax: Axes | None = None, **kwargs: Any) Axes[source]¶
Plot the model curve.
- Parameters:
x (np.ndarray | None, optional) – X values to evaluate and plot the model at. If provided, start, stop, num, endpoint, and spacing are ignored. By default None.
start (float | None, optional) – Start value for generating x array. If None, uses stored x_min from fitting. By default None.
stop (float | None, optional) – Stop value for generating x array. If None, uses stored x_max from fitting. By default None.
num (int, optional) – Number of points to generate, by default 500.
endpoint (bool, optional) – Whether to include the stop value, by default True.
spacing (Literal["lin", "log"], optional) – Spacing type: “lin” for linear (np.linspace) or “log” for logarithmic (np.logspace), by default “lin”.
ax (Axes | None, optional) – Matplotlib axes to plot on. If None, creates a new figure and axes. By default None.
**kwargs (Any) – All additional keyword arguments are passed directly to matplotlib’s plot() function for styling (e.g., color, linestyle, label, marker).
- Returns:
The matplotlib axes object.
- Return type:
Axes
- Raises:
ValueError – If parameters have not been initialized, or if bounds are not available and not provided.
Examples
>>> import numpy as np >>> from ezfit.functions import linear >>> model = Model( ... linear, {"m": Parameter(value=2.0), "b": Parameter(value=1.0)} ... ) >>> ax = model.plot(start=0, stop=10) >>> # Custom styling >>> ax = model.plot( ... start=0, stop=10, color="blue", linestyle="--", label="My Model" ... ) >>> # Use specific x values >>> x_vals = np.linspace(0, 10, 100) >>> ax = model.plot(x=x_vals, color="red")
- plot_corner(**kwargs: dict[str, Any]) tuple[Any, Any][source]¶
Create a corner plot from MCMC chain if available.
- Parameters:
**kwargs (dict[str, Any]) – Additional keyword arguments passed to plot_corner.
- Returns:
Tuple of (figure, axes_array).
- Return type:
tuple[Any, Any]
- Raises:
ValueError – If no MCMC chain is available.
- plot_trace(**kwargs: dict[str, Any]) tuple[Any, Any][source]¶
Create trace plots from MCMC chain if available.
- Parameters:
**kwargs (dict[str, Any]) – Additional keyword arguments passed to plot_trace.
- Returns:
Tuple of (figure, axes_array).
- Return type:
tuple[Any, Any]
- Raises:
ValueError – If no MCMC chain is available.
Parameter¶
- class ezfit.model.Parameter(value: float = 1, fixed: bool = False, min: float = -inf, max: float = inf, err: float = 0, constraint: Callable[[dict[str, float]], bool] | None = None, distribution: Literal['uniform', 'normal', 'loguniform'] | str | None = None, prior_args: dict[str, Any] | None = None)[source]
Bases:
objectData class for a parameter and its bounds.
- value
Initial/default value of the parameter.
- Type:
- fixed
Whether the parameter is fixed (not varied during fitting).
- Type:
- min
Minimum allowed value (lower bound).
- Type:
- max
Maximum allowed value (upper bound).
- Type:
- err
Error/uncertainty on the parameter value.
- Type:
- constraint
Optional constraint function that takes a dict of all parameter values and returns True if constraint is satisfied, False otherwise. Example: lambda p: p[“param1”] + p[“param2”] < 1.0
- distribution
Prior distribution type for MCMC sampling. Options: “uniform”, “normal”, “loguniform”. Default is None (uses bounds).
- Type:
Literal[“uniform”, “normal”, “loguniform”] | str | None
- prior_args
Additional arguments for the prior distribution. For “normal”: {“loc”: mean, “scale”: std} For “uniform”: {“low”: min, “high”: max} (usually same as min/max) For “loguniform”: {“low”: min, “high”: max}
- err: float = 0
- fixed: bool = False
- max: float = inf
- min: float = -inf
- value: float = 1
Examples¶
Creating a Model¶
from ezfit import Model, Parameter
def line(x, m, b):
return m * x + b
# Create model with parameters
model = Model(
func=line,
params={
"m": Parameter(value=1.0, min=0, max=10),
"b": Parameter(value=0.0, min=-5, max=5)
}
)
# Evaluate model
x = np.linspace(0, 10, 100)
y = model(x)
Accessing Parameters¶
# After fitting
print(model["m"].value) # Parameter value
print(model["m"].err) # Parameter uncertainty
print(model["m"].min) # Lower bound
print(model["m"].max) # Upper bound
MCMC Visualization¶
# After MCMC fit
model.plot_corner() # Corner plot
model.plot_trace() # Trace plots
model.summary() # Print diagnostics