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: object

Data 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.

__getitem__(key) Parameter[source]

Return the parameter with the given key.

__iter__() Generator[Any, Any, Any][source]

Iterate over the model parameters.

__post_init__() None[source]

Generate a list of parameters from the function signature.

__repr__() str[source]

Return a compact string representation of the model.

__setitem__(key: str, value: tuple[float, float]) None[source]

Set the parameter with the given key to the given value.

aic: float | None = None
bic: float | None = None
bounds() tuple[list[float], list[float]][source]

Yield the model parameter bounds as a tuple of lists.

cor: ndarray | None = None
cov: ndarray | None = None
describe() str[source]

Return a string description of the model and its parameters.

fit_result_details: FitResult | None = None
func: Callable
get_posterior_samples(discard: int | None = None, thin: int | None = None) ndarray[source]

Get posterior samples from MCMC chain.

Parameters:
  • discard (int | None, optional) – Number of samples to discard as burn-in. If None, uses automatic detection, by default None.

  • thin (int | None, optional) – Thinning factor. If None, uses automatic thinning, by default None.

Returns:

Array of posterior samples with shape (n_samples, n_params).

Return type:

np.ndarray

Raises:

ValueError – If no MCMC chain is available.

kwargs() dict[source]

Return the model parameters as a dictionary.

params: dict[str, Parameter] | None = None
pearson_r: float | None = None
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.

r_squared: float | None = None
random(x)[source]

Return a valid random value within the bounds.

residuals: ndarray | None = None
rmsd: float | None = None
rmse: float | None = None
rχ2: float | None = None
sampler_chain: ndarray | None = None
summary() str[source]

Print a summary of the fit including diagnostics.

Returns:

String summary of the fit including model description, parameters, chi-squared statistics, and MCMC diagnostics if available.

Return type:

str

values() list[float][source]

Yield the model parameters as a list.

x_max: float | None = None
x_min: float | None = None
χ2: float | None = None

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: object

Data class for a parameter and its bounds.

value

Initial/default value of the parameter.

Type:

float

fixed

Whether the parameter is fixed (not varied during fitting).

Type:

bool

min

Minimum allowed value (lower bound).

Type:

float

max

Maximum allowed value (upper bound).

Type:

float

err

Error/uncertainty on the parameter value.

Type:

float

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

Type:

Callable[[dict[str, float]], bool] | None

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}

Type:

dict[str, Any] | None

__call__() float[source]

Return the value of the parameter.

__post_init__() None[source]

Check the parameter values and bounds.

__repr__() str[source]

Return a string representation of the parameter.

constraint: Callable[[dict[str, float]], bool] | None = None
distribution: Literal['uniform', 'normal', 'loguniform'] | str | None = None
err: float = 0
fixed: bool = False
max: float = inf
min: float = -inf
prior_args: dict[str, Any] | None = None
random() float[source]

Return a valid random value within the bounds.

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