API reference

Model classes

The user-facing model classes. Each pairs a description of the transformation with an observation model that links the latent quantity (concentrations, a distribution, blend fractions) to the measured signal. See the role of spectra for how the observation models relate.

class kipetax.main_modules.reaction_model.ReactionModel(name=None, model=None, designation=None)[source]

Bases: object

Primary class for describing and solving kinetic reaction models.

Users define components, parameters, ODEs (and optionally algebraics and spectral data), then call simulate() or run_opt() to solve.

Example

>>> r1 = ReactionModel('my_model')
>>> k1 = r1.parameter('k1', value=2.0, bounds=(0, 10))
>>> A = r1.component('A', value=1.0)
>>> B = r1.component('B', value=0.0)
>>> r1.add_ode('A', -k1 * A)
>>> r1.add_ode('B',  k1 * A)
>>> r1.set_time(10.0)
>>> r1.simulate()
parameter(name, **kwargs)[source]

Define a kinetic parameter to be estimated.

Parameters:
  • name (str) – Parameter name.

  • value (float, optional) – Initial / nominal value.

  • bounds (tuple, optional) – (lb, ub).

  • fixed (bool, optional) – If True, parameter is held constant (not estimated).

  • variance (float, optional) – Known variance.

Returns:

Proxy object usable in ODE expressions.

Return type:

KipetProxy

component(name, **kwargs)[source]

Define a chemical species (concentration-based).

Parameters:
  • name (str)

  • value (float) – Initial concentration.

  • bounds (tuple, optional)

  • variance (float, optional)

  • absorbing (bool, optional) – Default True. Set False for non-absorbing species.

Return type:

KipetProxy

state(name, **kwargs)[source]

Define a non-concentration state variable (e.g. volume, temperature).

Return type:

KipetProxy

volume(**kwargs)[source]

Convenience method to define volume state named ‘V’.

constant(name, **kwargs)[source]

Define a fixed model constant (not estimated).

Return type:

KipetProxy

algebraic(name, **kwargs)[source]

Define a generic algebraic variable (no time derivative).

Return type:

KipetProxy

interaction(name, expr)[source]

Declare a non-additive (interaction) contribution to the spectra.

Beer-Lambert bilinearity assumes the measured spectrum is a concentration-weighted sum of fixed pure-component spectra. Real systems break that: an A.B adduct has a band whose intensity goes as c_A * c_B, and an environment-driven band shift contributes a derivative spectrum. Both are captured by adding a column to C whose value is an arbitrary expression of the states:

D(t, nu) = sum_k c_k(t) s_k(nu) + sum_j g_j(t) Gamma_j(nu)

The fitted Gamma_j is returned as an extra column of ResultsObject.S.

An interaction is an ALGEBRAIC function of the states, not a differential state. Do not give it an ODE via the product rule: that adds a spurious quadratic differential constraint to the collocation NLP, which is both slower and worse conditioned.

The augmented model is strictly more flexible than the additive one and can trade interaction spectra against the rate constants. Use set_spectral_regularization() to keep it identified, and decide that an interaction term is warranted from rank / structured-residual diagnostics before adding it.

Parameters:
  • name (str) – Label for the interaction spectrum (a column of S).

  • expr (pending expression) – Function of components/states, e.g. A * B or C ** 2.

Examples

>>> AB = r1.interaction('AB', A * B)   # A.B adduct band ~ c_A c_B
set_spectral_regularization(ridge=0.0)[source]

Ridge penalty on the interaction spectra (0 disables).

Adds ridge * sum(Gamma**2) to the objective. Interaction spectra are signed and unconstrained, so without a penalty an augmented model fit to data with little or no interaction becomes under-identified.

fixed_state(name, **kwargs)[source]

Define an algebraic variable with a fixed trajectory from data.

The ‘data’ keyword argument is required.

Return type:

KipetProxy

step(name, **kwargs)[source]

Define a step function variable.

Returns a KipetProxy that can be used in ODE expressions.

add_data(name=None, file=None, data=None, category=None, remove_negatives=False, time_scale=None)[source]

Add experimental data to the model.

Parameters:
  • name (str, optional)

  • file (str, optional) – Path to CSV file.

  • data (DataFrame, optional)

  • category (str, optional) – ‘spectral’ for D-matrix data.

  • remove_negatives (bool, optional)

  • time_scale (str, optional) – Unused (for API compatibility).

add_ode(ode_var, expr)[source]

Set the ODE for a component or state.

Parameters:
  • ode_var (str) – Name of the component or state variable.

  • expr (pending expression or numeric) – RHS of the ODE (dx/dt = expr).

Returns:

The expression (for chaining / display).

add_odes(ode_dict)[source]

Add multiple ODEs from a dictionary.

Parameters:

ode_dict (dict) – {var_name: expression}

add_expression(name, expr, **kwargs)[source]

Add a named algebraic expression.

Parameters:
  • name (str)

  • expr (pending expression)

Returns:

The expression.

add_reaction(name, expr, **kwargs)[source]

Declare a named reaction expression.

Returns the expression (usable in ODE RHS).

add_constraint(expr)[source]

Add a custom algebraic constraint (NLP constraint).

add_objective_from_algebraic(algebraic_var)[source]

Declare a custom objective using an algebraic variable (kipet API compat).

set_time(time_span=None)[source]

Set the simulation/estimation end time.

Parameters:

time_span (float) – Duration (t0=0 assumed).

set_discretization(nfe=20, ncp=3, scheme='radau', element_boundaries=None)[source]

Configure the collocation discretization.

Parameters:
  • nfe (int) – Number of finite elements. Ignored when element_boundaries is given (it is then inferred as len(element_boundaries) - 1).

  • ncp (int) – Collocation points per element.

  • scheme (str) – ‘radau’ or ‘legendre’.

  • element_boundaries (array-like, optional) –

    Explicit, strictly increasing element boundaries – a GRADED mesh.

    A uniform mesh silently fails on a system with a fast initial transient. A free-radical moment model whose radicals relax to quasi-steady state in ~0.05 time units, observed over 10, converges to a wrong rate constant with status=’optimal’ at nfe=40, 80 and 160 alike, because refining uniformly never resolves the layer. Cluster elements where the solution moves:

    eb = np.concatenate([np.linspace(0, 0.5, 20),
                         np.linspace(0.5, 10.0, 21)[1:]])
    r.set_discretization(ncp=3, element_boundaries=eb)
    

set_non_absorbing_species(species_list)[source]

Mark species as non-absorbing (excluded from Beer-Lambert).

set_known_absorbing_species(species_list)[source]

Explicitly set which species appear in the Beer-Lambert relation.

fix_parameter(param_name)[source]

Fix a parameter at its current value (do not estimate).

bound_profile(var, bounds)[source]

Set bounds on a component or state (API compatibility).

initialize_from_trajectory(var_name, data)[source]

Initialize a variable from trajectory data (API compatibility).

simulate(parameters=None, solver_opts=None)[source]

Run a dynamic simulation.

Parameters:
  • parameters (dict, optional) – Override parameter values for this run.

  • solver_opts (dict, optional) – Options forwarded to POUNCE, e.g. {'max_iter': 200}. A simulation is a pure feasibility solve with no objective to guide it, so a stiff model can iterate for a very long time. Cap it and handle the resulting RuntimeError rather than waiting.

Returns:

None (results stored in results_dict[‘simulator’]).

Raises:

RuntimeError – If the collocation solve does not converge. The trajectory would otherwise be empty.

run_opt(variances=None, covariance=False, method='collocation', spectra_nonneg=True, **kwargs)[source]

Run parameter estimation.

Parameters:
  • variances (dict, optional) – Component variances. If not given, uses sigma_sq from self.variances.

  • covariance (bool, optional) – If True, compute confidence intervals.

  • spectra_nonneg (bool or float, optional) –

    Whether the recovered SPECIES spectra are pushed non-negative. True (default) is a hard S >= 0 bound under 'collocation' and a penalty of weight 2.0 under 'varpro'; False removes it from either. A float sets the varpro penalty weight directly and behaves as True/False under collocation according to whether it is positive.

    Set it to False (or a small weight) when the D-matrix has been baseline-corrected or scatter-corrected. Non-negativity is a statement about raw absorbance. MSC applies a per-spectrum affine map – subtract an intercept, divide by a slope – which is not Beer-Lambert-preserving, so the pure-component spectra of preprocessed data have genuinely negative regions; a minor component can easily carry ~10% of its band energy there. Imposing S >= 0 anyway is a false constraint, and it biases the kinetics, not just the spectra, because the fit trades rate constants against the forbidden negative lobes.

    Concentration bounds are unaffected: C >= 0 holds regardless of what was done to the spectra.

  • method ({'collocation', 'varpro'}, optional) –

    Solver strategy.

    • 'collocation' (default) – the SIMULTANEOUS problem: the ODEs are transcribed by orthogonal collocation and solved with POUNCE, with the pure-component spectra S as decision variables. Gives joint confidence intervals over S and the kinetics, and hard constraints on S, but its cost grows quadratically in the number of wavelengths.

    • 'varpro' – variable projection: S is eliminated analytically (S* = C^+ D) so the optimizer sees only the kinetic parameters, making the cost independent of the wavelength count. Integrates the ODEs by sequential shooting (differentiable RK4). This is the right tool for a wide spectral axis. Only available for spectral fits.

Returns:

None (results stored in results_dict[‘p_estimator’]).

run_variance_estimator(**kwargs)[source]

Run variance estimation (wraps VarianceEstimator).

Stores variances in self.variances.

plot(var='Z', filename=None, show=True)[source]

Plot simulation or estimation results.

Parameters:
  • var (str) – ‘Z’ (concentrations), ‘X’ (states), or ‘Y’ (algebraics).

  • filename (str, optional) – Save to file.

  • show (bool) – Display plot.

make_model()[source]

Build the discopt model (for compatibility with kipet API).

property all_params

Return dict of all parameter name -> value.

diagnostics()[source]

Print a summary of the model.

class kipetax.main_modules.reaction_set.ReactionSet(name='reaction_set')[source]

Bases: object

Container for multiple ReactionModel instances.

Supports combined parameter estimation where certain parameters are shared across experiments.

Parameters:

name (str, optional) – Name for the combined model.

add_model(model)[source]

Add a ReactionModel to the set.

Parameters:

model (ReactionModel)

set_shared_parameter(param_name, value=None, bounds=(None, None))[source]

Declare a parameter as shared across all experiments.

Parameters:
  • param_name (str)

  • value (float, optional)

  • bounds (tuple, optional)

run_opt(variances=None, solver_options=None, covariance=False, shared_spectra=False, spectra_nonneg=True)[source]

Run combined parameter estimation across all experiments.

Builds a single discopt model that aggregates the NLS objectives from all individual experiments, sharing specified parameters. Each experiment contributes whatever data it carries: a spectral D-matrix, a concentration table, or both.

Parameters:
  • variances (dict, optional) – Variance estimates. Flat entries apply to every experiment; a nested dict keyed by experiment name overrides them for that experiment. See _experiment_variances().

  • solver_options (dict, optional)

  • covariance (bool, optional) – Not implemented for combined estimation; a warning is emitted if requested.

  • shared_spectra (bool, optional) –

    Tie the pure-component spectra S across every experiment.

    Off by default, because it is only valid when the optical configuration is identical and the D-matrices are on a common absolute scale, and because band shapes drift with temperature – so it is a modelling choice, not a safe assumption.

    Turn it on when the members are the same chemistry at different conditions (an amplitude series, a feed series, a concentration series measured on one instrument). There the spectra are shared by construction, and giving each experiment its own S costs real identifiability: (n_experiments - 1) * n_abs * n_lam free parameters is enough for each experiment to explain away the very differences between conditions that identify the kinetics. A condition series where a rate constant varies by a fitted power law is the canonical case – with free S per experiment the exponent can be badly biased while the objective barely moves.

    Requires every experiment to carry spectral data on an identical wavelength grid with an identical list of absorbing species; a ValueError names the first mismatch otherwise.

  • spectra_nonneg (bool or float, optional) – As in ReactionModel.run_opt(). Relax it when the D-matrices have been baseline- or scatter-corrected, which makes the true pure-component spectra partly negative.

Returns:

P holds the shared parameters plus each experiment’s local ones (local names are prefixed <experiment>.). experiments maps each experiment name to its own ResultsObject (Z, X, Y, S, P), which is also stored on the member model’s results_dict['p_estimator'].

Return type:

ResultsObject

class kipetax.main_modules.population_balance.PopulationBalanceModel(name='pbm')[source]

Bases: object

A population balance over an internal coordinate, fit by sequential shooting.

The workflow mirrors ReactionModel but the moving parts are JAX functions rather than proxy expressions:

>>> import jax.numpy as jnp, numpy as np
>>> pbm = PopulationBalanceModel('growth')
>>> pbm.set_coordinate('r', np.linspace(0.8, 6.0, 45))
>>> pbm.parameter('kg', value=0.01, bounds=(1e-3, 0.1))
>>> pbm.constant('M0', 1.0)
>>> pbm.set_initial_state(jnp.zeros(45))
>>> pbm.set_dynamics(step_fn, t_end=40.0, nt=1600, scheme='euler')
>>> pbm.set_observation(observe_fn)
>>> pbm.add_data(A_data)             # (n_obs, n_lambda)
>>> res = pbm.run_opt()
>>> res.P['kg']

step_fn(state, t, p) returns the time derivative of the flat state vector; p is a dict of all parameter and constant values. observe_fn(state_history, p) returns predicted spectra (n_obs, n_lambda) aligned with add_data().

set_coordinate(name, grid)[source]

Set the internal coordinate (radius, chain length) and its grid.

property coordinate
parameter(name, value, bounds=(1e-08, 100000000.0))[source]

Declare a parameter to estimate. Fit in log space, so bounds must be strictly positive.

constant(name, value)[source]

Declare a fixed value available to the dynamics/observation.

set_initial_state(y0)[source]

Set the initial flat state vector (distribution, then any scalars).

set_dynamics(rhs, t_end, nt, scheme='rk4')[source]

Set the RHS and integrator.

Parameters:
  • rhs (callable) – rhs(state, t, p) -> dstate/dt, a JAX function.

  • t_end (float) – Final time (t0 = 0).

  • nt (int) – Number of fixed steps.

  • scheme ({'rk4', 'euler'}) – Explicit integrator. Use ‘euler’ for upwind advection (positivity), ‘rk4’ for smooth stiff systems.

set_observation(observe)[source]

Set the observation operator observe(state_history, p) -> spectra.

state_history has shape (nt + 1, state_dim). The returned array must align row-for-row with add_data().

add_data(spectra)[source]

Attach measured spectra, shape (n_obs, n_lambda).

simulate(parameters=None)[source]

Forward-integrate at the given (or initial) parameters.

Return type:

PopulationBalanceResults

run_opt(verbose=False)[source]

Fit the parameters to the data by sequential-shooting least squares.

Minimizes sum((observe(simulate(theta)) - data)^2) over the log parameters with L-BFGS-B, gradients by JAX autodiff through the integrator and observation.

Return type:

PopulationBalanceResults

static nnls_inversion(spectra, kernel)[source]

Per-spectrum non-negative inversion onto a known kernel.

The naive baseline: invert each spectrum independently onto the kernel with no mechanism tying the time points together. On an ill-posed Fredholm inversion this is exactly what the mechanism-constrained fit is meant to beat.

Parameters:
  • spectra (ndarray, shape (n_obs, n_lambda))

  • kernel (ndarray, shape (n_lambda, n_sections)) – The forward map from sections to wavelengths.

Return type:

ndarray, shape (n_obs, n_sections)

class kipetax.main_modules.population_balance.PopulationBalanceResults[source]

Bases: object

Container for a population-balance fit or simulation.

P

Estimated parameter values {name: value}.

Type:

dict

state_history

Full integrated state, shape (nt + 1, state_dim).

Type:

ndarray

coordinate

The internal-coordinate grid, if one was set.

Type:

ndarray or None

status

'optimal', 'failed', or 'simulated'.

Type:

str

objective

Final least-squares objective (fits only).

Type:

float or None

n_iter

Optimizer iterations (fits only).

Type:

int or None

distribution(step=-1)[source]

The distribution part of the state at a step (default: final).

class kipetax.main_modules.mixture_model.MixtureModel(n_components, interaction=True)[source]

Bases: object

Linear-in-parameters blend-property model with pairwise interactions.

Parameters:
  • n_components (int) – Number of pure components.

  • interaction (bool) – If True (default) include the w_i w_j pairwise columns; if False the model is purely additive (Kay’s rule / ideal mixing).

Examples

>>> mm = MixtureModel(n_components=4)
>>> mm.fit(W_train, D_train)        # D_train: (n_blends, n_wavelengths)
>>> D_pred = mm.predict(W_test)
>>> mm.interaction_props            # (n_pairs, n_wavelengths): the Gamma_ij
>>> w = mm.infer_composition(a_spectrum)   # inverse: spectrum -> fractions
design(W)[source]

Blend-fraction design matrix [w_i | w_i w_j].

Parameters:

W (ndarray, shape (n_blends, n_components)) – Blend fractions (rows need not be normalized, but usually sum to 1).

Return type:

ndarray, shape (n_blends, n_components [+ n_pairs])

fit(W, Y)[source]

Least-squares calibration.

Parameters:
  • W (ndarray, shape (n_blends, n_components))

  • Y (ndarray, shape (n_blends,) or (n_blends, n_features)) – Measured blend property (a scalar per blend, or a spectrum).

Return type:

self

predict(W)[source]

Predict the blend property for new fractions.

interaction_parameter(i, j)[source]

The fitted interaction property for the pair (i, j).

For a scalar-property model this is the Grunberg-Nissan d_ij; for a spectral model it is the interaction band Gamma_ij (a vector).

infer_composition(y_target, normalize=True)[source]

Infer blend fractions from a measured property (the inverse problem).

Solves min_w || design(w) @ coef - y_target ||^2 subject to w >= 0 and sum(w) = 1. Only meaningful for a rich property such as a spectrum, where the fractions are identifiable.

Parameters:
  • y_target (ndarray, shape (n_features,)) – A single measured property vector.

  • normalize (bool) – Enforce the simplex constraint sum(w) = 1.

Returns:

The recovered blend fractions.

Return type:

ndarray, shape (n_components,)

Results

class kipetax.estimator_tools.results_object.ResultsObject[source]

Bases: object

Container for kipetax estimation/simulation results.

P

Estimated parameter values {name: value}.

Type:

dict

Z

Component concentration trajectories (time x components).

Type:

DataFrame

X

Non-concentration state trajectories (time x states).

Type:

DataFrame

Y

Algebraic variable trajectories (time x algebraics).

Type:

DataFrame

S

Molar absorptivity matrix (wavelengths x abs_components), if spectral.

Type:

DataFrame or None

sigma_sq

Variance estimates {component: sigma_sq}.

Type:

dict

confidence_intervals

95% confidence intervals {param: (lower, upper)}. Unidentifiable parameters have (-inf, inf) rather than a spurious finite interval.

Type:

dict

covariance

Parameter covariance matrix (rows/cols ordered as P). Diagonal entries are inf for structurally unidentifiable parameters.

Type:

numpy.ndarray or None

fim

Fisher Information Matrix at the solution.

Type:

numpy.ndarray or None

identifiability

Structural identifiability diagnostics (FIM rank, null space, per-parameter flags, warnings). See kipetax.calculation_tools.reduced_hessian.

Type:

IdentifiabilityReport or None

cov_source

How the covariance was produced: 'reduced_hessian', 'reduced_hessian(rank-deficient)', or 'finite_difference'.

Type:

str or None

status

Solver status string.

Type:

str

objective

Objective value at solution.

Type:

float or None

experiments

For a ReactionSet fit, {experiment_name: ResultsObject} holding each experiment’s own trajectories and spectra. Empty for a single-model fit.

Type:

dict

load_from_builder_result(builder_result, solve_result=None)[source]

Populate from the output of DiscoptModelBuilder.extract_results().

Parameters:
  • builder_result (dict) – Dict with keys ‘Z’, ‘X’, ‘Y’, ‘P’, ‘S’.

  • solve_result (discopt.SolveResult, optional) – The raw solver result for status/objective.

load_identifiability(cov_result, alpha=0.05)[source]

Populate covariance / identifiability fields and confidence intervals.

Parameters:
  • cov_result (dict) – Output of kipetax.calculation_tools.reduced_hessian.analytic_covariance(), with keys covariance, fim, report, param_names, cov_source.

  • alpha (float) – Significance level for the (two-sided normal) confidence intervals. 0.05 -> 95% intervals.

compute_var_norm(var_name, order=inf)[source]

Compute the norm of a trajectory variable (used in iterative variance estimation).

Parameters:
  • var_name (str) – One of ‘Z’, ‘X’, ‘Y’.

  • order (int or float) – Norm order.

Return type:

float

Estimators and simulator

DiscoptSimulator for kipetax.

Replaces PyomoSimulator. Builds a simulation discopt model and extracts the time-series trajectory.

class kipetax.estimator_tools.discopt_simulator.DiscoptSimulator(builder)[source]

Bases: object

Runs a pure ODE/DAE simulation using discopt collocation.

Parameters:

builder (DiscoptModelBuilder) – Populated builder object.

run_sim(parameters=None, solver_options=None)[source]

Run the simulation.

Parameters:
  • parameters (dict, optional) – Override parameter values {name: value} for this simulation.

  • solver_options (dict, optional) – Extra keyword arguments passed to the POUNCE solver.

Return type:

ResultsObject

ParameterEstimator for kipetax.

Builds and solves the NLS parameter estimation problem using discopt.

class kipetax.estimator_tools.parameter_estimator.ParameterEstimator(builder)[source]

Bases: object

NLS parameter estimation using discopt collocation.

Parameters:

builder (DiscoptModelBuilder) – Populated builder object.

run_opt(variances=None, solver_options=None, covariance=False, cov_method='analytic')[source]

Run parameter estimation.

The problem is always solved with a single local NLP solve (POUNCE interior point) – the right tool for a nonconvex least-squares estimation and tractable at collocation sizes.

Parameters:
  • variances (dict, optional) – Component variances {name: sigma_sq}. Defaults to 1.0 for all.

  • solver_options (dict, optional) – Extra keyword arguments forwarded to the POUNCE solver.

  • covariance (bool, optional) – If True, compute confidence intervals and identifiability diagnostics.

  • cov_method ({'analytic', 'pounce', 'auto', 'fd'}, optional) –

    Preferred covariance backend; each falls back to the next on failure so a covariance is still produced.

    • 'analytic' (default) – the Gauss-Newton reduced-Hessian / Fisher-Information-Matrix path (kipetax.calculation_tools.reduced_hessian), then FD. This is the statistically correct object for a parameter covariance: it is zero along a structurally unidentifiable direction, so the FIM eigendecomposition exposes that direction (infinite CI) instead of a spurious finite interval.

    • 'pounce' / 'auto' – POUNCE’s full reduced Hessian at the KKT point (the sIPOPT analog; reuses the solve’s factorization), then analytic, then FD. NOTE: the full Lagrangian Hessian includes a residual-curvature (second-order) term the FIM drops, which agrees with the FIM for well-identified fits but adds spurious finite curvature to unidentifiable directions – it can MASK structural unidentifiability. Prefer 'analytic' for identifiability diagnostics. (A Gauss-Newton Hessian from POUNCE would remove this caveat; see discopt#98.)

    • 'fd' – the finite-difference Jacobian only.

Return type:

ResultsObject

Variable-projection (VARPRO) estimator for spectral kinetic fits.

The default spectral path in DiscoptModelBuilder solves the SIMULTANEOUS problem: the pure-component spectra S (n_abs x n_lambda) are NLP decision variables alongside the collocated concentrations, and the bilinear objective ||D - C S^T||^2 couples them densely in the KKT system. Its cost grows roughly QUADRATICALLY in the number of wavelengths, because S alone contributes n_abs * n_lambda variables.

Variable projection removes S from the optimization entirely. For fixed kinetic parameters theta the concentrations C(theta) are determined, and the S that minimizes ||D - C S^T||^2 is the linear least-squares solution S* = C^+ D. Substituting it back leaves a residual that depends only on theta:

r(theta) = (I - C C^+) D (the projection of D off the column space of C)

so the optimizer sees only the two or three kinetic parameters, no matter how many wavelengths there are. S is recovered once, at the end. This is the classical Golub-Pereyra separable-least-squares method, and it is why the standalone demo fits 400 wavelengths in seconds.

Because S is never a collocation variable, this estimator does not use the collocation NLP at all. It integrates the ODEs SEQUENTIALLY with a differentiable fixed-step RK4 (jax.lax.scan) and optimizes theta with L-BFGS-B, gradients by jax.value_and_grad differentiating through both the integrator and the projection. Interaction columns (ReactionModel.interaction()) are handled for free: they are extra columns of C, projected out with the species.

class kipetax.estimator_tools.varpro_estimator.VarProEstimator(builder)[source]

Bases: object

Separable-least-squares spectral estimation by variable projection.

Parameters:

builder (DiscoptModelBuilder) – A populated builder (components, parameters, ODEs, spectral data).

run_opt(variances=None, covariance=False, spectra_nonneg=True)[source]

Fit the kinetic parameters by variable projection.

Parameters:

spectra_nonneg (bool or float, optional) – Strength of the non-negativity penalty on the species spectra. True (default) uses _NONNEG_WEIGHT, False disables it, and a float sets the weight directly. See ReactionModel.run_opt.

Return type:

ResultsObject

VarianceEstimator for kipetax.

Simplified variance estimation: runs parameter estimation with unit variances, then estimates component variances from the residuals.

class kipetax.estimator_tools.variance_estimator.VarianceEstimator(builder)[source]

Bases: object

Estimates component variances from residuals after parameter estimation.

Parameters:

builder (DiscoptModelBuilder)

run(tol=0.0001, max_iter=20, **kwargs)[source]

Run variance estimation.

Iterates: 1. Estimate parameters with current variances 2. Update variances from residuals Until convergence.

Parameters:
  • tol (float) – Convergence tolerance.

  • max_iter (int) – Maximum iterations.

Returns:

dict

Return type:

{component_name: estimated_variance}

Model components

Model elements: the named quantities a ReactionModel is built from.

Each element is a small record (name, value, bounds and a few kind-specific options) plus a KipetProxy that stands in for it inside ODE and algebraic expressions.

The kinds differ only in which options they carry and what those default to, so each subclass is described by a table (_options) rather than by its own constructor. Options not in the table are accepted and kept in extra so that keyword arguments meaningful elsewhere (units=..., for example) do not raise.

class kipetax.model_components.model_components.ModelElement(name, value=None, description=None, **options)[source]

Bases: object

Base class for all model elements.

Subclasses set kind (the proxy-variable kind) and _options (a mapping of option name to default value).

kind = None
property lb

Lower bound, or None if unbounded below.

property ub

Upper bound, or None if unbounded above.

class kipetax.model_components.model_components.ModelParameter(name, value=None, **options)[source]

Bases: ModelElement

A kinetic parameter, estimated unless fixed.

With no value but finite bounds, the starting value is the midpoint of the bounds.

kind = 'parameter'
class kipetax.model_components.model_components.ModelComponent(name, value=None, **options)[source]

Bases: ModelElement

A chemical species whose state is its concentration.

value is the initial concentration. absorbing controls whether the species contributes to a Beer-Lambert spectral model.

kind = 'component'
class kipetax.model_components.model_components.ModelState(name, value=None, description=None, **options)[source]

Bases: ModelElement

A differential state that is not a concentration (volume, temperature).

kind = 'state'
class kipetax.model_components.model_components.ModelAlgebraic(name, value=None, description=None, **options)[source]

Bases: ModelElement

An algebraic variable: no time derivative, optionally fixed to data.

kind = 'algebraic'
class kipetax.model_components.model_components.ModelConstant(name, value=None, description=None, **options)[source]

Bases: ModelElement

A fixed numeric constant used in expressions; never estimated.

kind = 'constant'

Ordered, name-keyed collections of model elements.

A ReactionModel keeps one collection per element kind (r.parameters, r.components, …). Each collection creates its elements, looks them up by name, and iterates over them in the order they were declared.

class kipetax.model_components.element_blocks.ElementCollection[source]

Bases: object

Elements of a single kind, keyed by name in declaration order.

Subclasses set element_type to the element class they hold.

element_type = None
add_element(name, **options)[source]

Create an element of this collection’s type and store it.

Re-declaring an existing name replaces the earlier element.

property names

Element names, in declaration order.

property values

{name: value} for every element.

class kipetax.model_components.element_blocks.ParameterBlock[source]

Bases: ElementCollection

Kinetic parameters (r.parameters).

element_type

alias of ModelParameter

class kipetax.model_components.element_blocks.ComponentBlock[source]

Bases: ElementCollection

Chemical species (r.components).

element_type

alias of ModelComponent

class kipetax.model_components.element_blocks.StateBlock[source]

Bases: ElementCollection

Non-concentration differential states (r.states).

element_type

alias of ModelState

class kipetax.model_components.element_blocks.AlgebraicBlock[source]

Bases: ElementCollection

Algebraic variables (r.algebraics).

element_type

alias of ModelAlgebraic

class kipetax.model_components.element_blocks.ConstantBlock[source]

Bases: ElementCollection

Fixed constants (r.constants).

element_type

alias of ModelConstant

Measured (non-spectral) datasets attached to a ReactionModel.

Each dataset is a DataFrame indexed by time with one column per measured variable. Spectral D-matrices are held separately by SpectralData.

class kipetax.model_components.data_component.DataSet(name, category=None, data=None, file=None)[source]

Bases: object

One named table of measurements.

property shape
class kipetax.model_components.data_component.DataBlock[source]

Bases: object

The datasets of one model, keyed by name in the order added.

add_dataset(dataset)[source]

Store dataset, replacing any earlier one with the same name.

property names

Spectral data handler for kipetax (Pyomo-free).

Manages spectral (D-matrix) data with optional preprocessing methods.

class kipetax.model_components.spectral_handler.SpectralData(name, file=None, remove_negatives=False)[source]

Bases: object

Handler for spectral absorption data (D matrix).

add_data(dataframe)[source]

Add a DataFrame as spectral data.

property times
property wavelengths
msc(reference=None)[source]

Multiplicative scatter correction.

snv()[source]

Standard normal variate normalization.

savitzky_golay(window_length=11, polyorder=2, deriv=0)[source]

Apply Savitzky-Golay filter.

Model tools

DiscoptModelBuilder for kipetax.

Replaces TemplateBuilder. Accumulates model spec and builds discopt models for simulation and parameter estimation.

kipetax.model_tools.discopt_model_builder.solve_local_nlp(m, parameter_values=None, solver_options=None, evaluator=None, initial_guess=None)[source]

Solve any discopt model with a single local NLP solve (POUNCE).

This is the single choke point through which every kipetax solve is routed, so discopt always uses POUNCE rather than falling back to its spatial branch-and-bound. discopt’s default m.solve() auto-detects nonconvexity and switches to branch-and-bound – correct but intractable for collocation-sized least-squares – so it must never be called directly in the kipetax pipeline.

Parameters:
  • m (discopt.Model) – A model with declared variables, constraints, and objective.

  • parameter_values (dict, optional) – {variable_name: value} used to seed x0 at the user’s initial guesses (a far better start than the bound midpoint). Keys that do not match a variable, and None values, are ignored.

  • solver_options (dict, optional) – Options forwarded to solve_nlp (e.g. max_iter, tol).

  • evaluator (discopt NLPEvaluator, optional) – A pre-built evaluator for m to reuse instead of compiling a fresh one. Pass this to re-solve the same model many times (e.g. across finite-difference parameter perturbations) without a new JAX compile; the evaluator’s XLA cache keys on shapes only, so mutating the model’s Parameter values between calls hits the cache.

  • initial_guess (dict, optional) – {variable_name: array} warm-start values for full variable blocks (e.g. the spectral S_matrix). A bilinear spectral fit started from the bound midpoint converges to a poor local minimum; seeding S from a forward simulation (S = pinv(C) @ D) lands it at the good optimum.

Return type:

discopt.modeling.core.SolveResult

class kipetax.model_tools.discopt_model_builder.DiscoptModelBuilder(name='kipetax_model')[source]

Bases: object

Builds discopt models from a ReactionModel specification.

Responsibilities: - Accumulate components, parameters, ODEs, algebraics, data - Build a discopt Model + DAEBuilder and discretize at solve time - Add measurement residuals as NLS objective - Add Beer-Lambert constraints for spectral data

add_component(comp)[source]
add_parameter(param)[source]
add_state(state)[source]
add_algebraic(alg)[source]
add_constant(const)[source]
set_odes(odes_dict)[source]

odes_dict: {var_name: pending_expression}

set_algebraics(algs_dict)[source]

algs_dict: {var_name: pending_expression}

set_datasets(datasets)[source]
set_spectral_data(spectral_data)[source]
set_interactions(interactions)[source]

interactions: {name: pending_expression} -> extra absorbing columns.

set_spectral_ridge(ridge)[source]

Ridge weight applied to the interaction spectra (0 disables).

set_times(start, end)[source]
set_discretization(nfe=20, ncp=3, scheme='radau', element_boundaries=None)[source]
build_simulation_model()[source]

Build a discopt Model for pure simulation (all parameters fixed to their values).

Returns:

(m, dae)

Return type:

(discopt.Model, DAEBuilder)

build_parametric_simulation_model()[source]

Simulation model with kinetic parameters as discopt Parameter objects.

Identical to build_simulation_model() except the kinetic parameters enter the ODE as discopt Parameter objects rather than baked-in float constants. The compiled evaluator keys its XLA cache on shapes only, so the resulting model can be re-solved at many parameter values by mutating Parameter.value – without a fresh JAX compile each time. This is what makes the finite-difference covariance (one re-solve per perturbed parameter) cheap.

Returns:

(m, dae, param_map) – param_map maps each kinetic parameter name to its discopt Parameter so callers can set param_map[name].value between solves.

Return type:

(discopt.Model, DAEBuilder, dict)

build_parameter_estimation_model(variances=None)[source]

Build a discopt Model for parameter estimation with NLS objective.

Parameters:

variances (dict or None) – Component variances {name: sigma_sq}. If None, uses 1.0 for all.

Returns:

(m, dae, dm_params) – dm_params maps parameter names to discopt Variable elements.

Return type:

(discopt.Model, DAEBuilder, dict)

solve_local(m, solver_options=None, initial_guess=None, evaluator=None)[source]

Solve a model with a single local NLP solve (POUNCE interior point).

The parameter-estimation objective is a nonconvex weighted least-squares, for which discopt’s default m.solve() falls back to spatial branch-and-bound – correct but intractable for collocation-sized problems. Parameter estimation only needs a local optimum, so this routes through discopt.solvers.nlp_pounce.solve_nlp and wraps the flat solution into a discopt SolveResult so the rest of the pipeline (extract_results, analytic covariance) is unchanged.

Parameters:
  • m (discopt.Model) – A model with declared variables, constraints, and objective.

  • solver_options (dict, optional) – Options forwarded to solve_nlp (e.g. max_iter, tol).

  • initial_guess (dict, optional) – {variable_name: array} warm-start values forwarded to solve_local_nlp() (e.g. a seeded spectral S_matrix). Blocks not supplied fall back to the constant-trajectory seed from constant_state_guess().

Return type:

discopt.modeling.core.SolveResult

constant_state_guess()[source]

Seed every collocation state with its initial condition.

solve_local_nlp starts at the midpoint of the clipped bounds, so a state declared with the default ub=1e20 starts at 50. For a stiff system that is catastrophic: a radical concentration whose true scale is 1e-3 starts at 50, and a quadratic termination term 2*kt*Y0**2 evaluates to 2.5e7 at the first iterate. A constant trajectory at the declared initial value costs nothing and is always in the right regime.

estimation_initial_guess()[source]

Warm-start every variable block of the parameter-estimation NLP.

solve_local_nlp otherwise starts at the midpoint of the clipped bounds. A concentration state declared with the default ub=1e20 clips to 100 and therefore starts at 50, while the true trajectory is O(1). Weighted by a small measurement variance (1/sigma^2 is 2.5e5 at sigma^2 = 4e-6) the solver diverges from there and POUNCE reports UNBOUNDED – on an objective that is a sum of squares and cannot be unbounded below. Seeding the collocation blocks from a forward solve at the initial parameters removes the failure.

Also seeds the bilinear spectral blocks: D = C(theta) S^T started from the bound midpoint converges to a poor local minimum, so S is seeded with the closed-form S = pinv(C) @ D.

Returns:

{variable_name: array} or None when the simulation fails.

Return type:

dict or None

spectral_initial_guess()[source]

Warm-start for a spectral fit’s S_matrix / C_spectral blocks.

Kept for backwards compatibility; prefer estimation_initial_guess(), which also seeds the collocation state blocks.

extract_results(result, dae, dm_params, prefix='', s_prefix=None)[source]

Extract solution from a discopt SolveResult.

Parameters:
  • prefix (str, optional) – Name prefix used when the states were declared. Empty for a single model; '<experiment>_' for a ReactionSet member.

  • s_prefix (str, optional) – Prefix for the S_matrix lookup alone. Defaults to prefix; ReactionSet passes '' when the species spectra are shared across experiments, since that block is declared once and unprefixed. Every member then reports the same S, which is the point.

Returns:

‘Z’: DataFrame of component trajectories (time x components) ‘X’: DataFrame of state trajectories (time x states) ‘Y’: DataFrame of algebraic trajectories (time x algebraics) ‘P’: dict of parameter values ‘S’: DataFrame of S matrix (wavelengths x abs_components), if spectral

Return type:

dict with keys

Proxy Variable System for kipetax.

Users write ODE right-hand sides using KipetProxy objects, which build pending expression trees. At solve time these trees are resolved into real discopt expressions via resolve_expression().

class kipetax.model_tools.proxy_vars.KipetProxy(name, kind)[source]

Bases: object

Lightweight node representing a named model variable in a pending expression tree.

class kipetax.model_tools.proxy_vars.PendingBinaryOp(op, left, right)[source]

Bases: object

A binary operation node in a pending expression tree.

class kipetax.model_tools.proxy_vars.PendingUnaryOp(op, operand)[source]

Bases: object

A unary operation node in a pending expression tree.

class kipetax.model_tools.proxy_vars.PendingFunctionCall(func_name, *args)[source]

Bases: object

A function call node in a pending expression tree.

kipetax.model_tools.proxy_vars.exp(x)[source]
kipetax.model_tools.proxy_vars.log(x)[source]
kipetax.model_tools.proxy_vars.log10(x)[source]
kipetax.model_tools.proxy_vars.sqrt(x)[source]
kipetax.model_tools.proxy_vars.sin(x)[source]
kipetax.model_tools.proxy_vars.cos(x)[source]
kipetax.model_tools.proxy_vars.tan(x)[source]
kipetax.model_tools.proxy_vars.abs_(x)[source]
kipetax.model_tools.proxy_vars.is_pending(expr)[source]

Return True if expr is any kind of pending expression node.

kipetax.model_tools.proxy_vars.resolve_expression(expr, subst, functions=None)[source]

Walk a pending expression tree and replace KipetProxy nodes with real values/discopt expressions from subst.

Parameters:
  • expr (pending tree node, int, or float) – The expression to resolve.

  • subst (dict) – Mapping from variable name to resolved value (discopt Variable element or float).

  • functions (dict, optional) – Override table for function-call nodes (exp, log, …). Pass JAX’s jax.numpy functions to evaluate the tree for sequential integration (variable projection), where the substituted values are traced JAX arrays rather than discopt Variables. When given it is used for every function call, bypassing the discopt/scalar dispatch.

Returns:

Resolved expression (discopt expression, JAX array, or float).

Calculation tools

Trajectory interpolation utilities for kipetax (pure numpy/scipy).

kipetax.calculation_tools.interpolation.interpolate_trajectory(df, t_new, kind='linear', axis=0)[source]

Interpolate a DataFrame trajectory to new time points.

Parameters:
  • df (DataFrame) – Time-indexed DataFrame (rows = times, columns = variables).

  • t_new (array-like) – New time points.

  • kind (str) – Interpolation type (‘linear’, ‘cubic’, etc.).

  • axis (int) – Axis along which to interpolate (0 = rows / time axis).

Returns:

Interpolated values at t_new.

Return type:

DataFrame

Covariance / confidence interval estimation for kipetax.

Uses finite-difference Jacobian to estimate Cov(P) after the NLS solve.

kipetax.calculation_tools.covariance.compute_covariance(builder, P_opt, variances, eps_rel=0.0001, eps_abs=1e-08, scale=None)[source]

Estimate the covariance matrix of the estimated parameters via finite-difference Jacobian of the residual vector.

For each parameter p_i, perturb by eps and re-solve, compute dR/dp_i. Then Cov(P) = scale * pinv(J^T @ J).

Parameters:
  • builder (DiscoptModelBuilder) – Builder with the problem specification.

  • P_opt (dict) – Optimal parameter values {name: value}.

  • variances (dict) – Component variances {name: sigma_sq}.

  • eps_rel (float) – Relative perturbation size.

  • eps_abs (float) – Absolute perturbation minimum.

  • scale (float, optional) – Variance scale applied to pinv(J^T J). When None (default), the residual-estimated reduced chi-square SSE / (n_meas - n_params) is used. Pass 1.0 to trust the supplied variances as the absolute measurement variance – this keeps the finite-difference covariance on the same scale convention as the analytic reduced-Hessian path.

Return type:

np.ndarray of shape (n_params, n_params) or None

Helper utilities for kipetax (pure Python, no Pyomo).

class kipetax.calculation_tools.helper.DosingPoint(component, time, concentration, volume)

Bases: tuple

component

Alias for field number 0

concentration

Alias for field number 2

time

Alias for field number 1

volume

Alias for field number 3

class kipetax.calculation_tools.helper.AttrDict[source]

Bases: dict

A dict that allows attribute-style access.