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:
objectPrimary 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:
- Returns:
Proxy object usable in ODE expressions.
- Return type:
- state(name, **kwargs)[source]¶
Define a non-concentration state variable (e.g. volume, temperature).
- Return type:
- algebraic(name, **kwargs)[source]¶
Define a generic algebraic variable (no time derivative).
- Return type:
- 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 toCwhose 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_jis returned as an extra column ofResultsObject.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 * BorC ** 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:
- 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.
- 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_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_boundariesis given (it is then inferred aslen(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.
- 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 resultingRuntimeErrorrather 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 hardS >= 0bound under'collocation'and a penalty of weight 2.0 under'varpro';Falseremoves it from either. A float sets the varpro penalty weight directly and behaves asTrue/Falseunder 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. ImposingS >= 0anyway 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 >= 0holds 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 spectraSas decision variables. Gives joint confidence intervals overSand the kinetics, and hard constraints onS, but its cost grows quadratically in the number of wavelengths.'varpro'– variable projection:Sis 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.
- property all_params¶
Return dict of all parameter name -> value.
- class kipetax.main_modules.reaction_set.ReactionSet(name='reaction_set')[source]¶
Bases:
objectContainer 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)
Declare a parameter as shared across all experiments.
- 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
Sacross 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
Scosts real identifiability:(n_experiments - 1) * n_abs * n_lamfree 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 freeSper 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
ValueErrornames 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:
Pholds the shared parameters plus each experiment’s local ones (local names are prefixed<experiment>.).experimentsmaps each experiment name to its ownResultsObject(Z,X,Y,S,P), which is also stored on the member model’sresults_dict['p_estimator'].- Return type:
- class kipetax.main_modules.population_balance.PopulationBalanceModel(name='pbm')[source]¶
Bases:
objectA population balance over an internal coordinate, fit by sequential shooting.
The workflow mirrors
ReactionModelbut 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;pis a dict of all parameter and constant values.observe_fn(state_history, p)returns predicted spectra(n_obs, n_lambda)aligned withadd_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.
- set_observation(observe)[source]¶
Set the observation operator
observe(state_history, p) -> spectra.state_historyhas shape(nt + 1, state_dim). The returned array must align row-for-row withadd_data().
- simulate(parameters=None)[source]¶
Forward-integrate at the given (or initial) parameters.
- Return type:
- 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:
- 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.
- class kipetax.main_modules.population_balance.PopulationBalanceResults[source]¶
Bases:
objectContainer for a population-balance fit or simulation.
- 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
- class kipetax.main_modules.mixture_model.MixtureModel(n_components, interaction=True)[source]¶
Bases:
objectLinear-in-parameters blend-property model with pairwise interactions.
- Parameters:
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
- 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 bandGamma_ij(a vector).
Results¶
- class kipetax.estimator_tools.results_object.ResultsObject[source]¶
Bases:
objectContainer for kipetax estimation/simulation results.
- 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
- confidence_intervals¶
95% confidence intervals {param: (lower, upper)}. Unidentifiable parameters have
(-inf, inf)rather than a spurious finite interval.- Type:
- covariance¶
Parameter covariance matrix (rows/cols ordered as
P). Diagonal entries areinffor 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
- experiments¶
For a
ReactionSetfit,{experiment_name: ResultsObject}holding each experiment’s own trajectories and spectra. Empty for a single-model fit.- Type:
- 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.
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:
objectRuns a pure ODE/DAE simulation using discopt collocation.
- Parameters:
builder (DiscoptModelBuilder) – Populated builder object.
ParameterEstimator for kipetax.
Builds and solves the NLS parameter estimation problem using discopt.
- class kipetax.estimator_tools.parameter_estimator.ParameterEstimator(builder)[source]¶
Bases:
objectNLS 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:
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:
objectSeparable-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.
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:
objectEstimates component variances from residuals after parameter estimation.
- Parameters:
builder (DiscoptModelBuilder)
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:
objectBase 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:
ModelElementA kinetic parameter, estimated unless
fixed.With no
valuebut 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:
ModelElementA chemical species whose state is its concentration.
valueis the initial concentration.absorbingcontrols 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:
ModelElementA 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:
ModelElementAn 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:
ModelElementA 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:
objectElements of a single kind, keyed by name in declaration order.
Subclasses set
element_typeto 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:
ElementCollectionKinetic parameters (
r.parameters).- element_type¶
alias of
ModelParameter
- class kipetax.model_components.element_blocks.ComponentBlock[source]¶
Bases:
ElementCollectionChemical species (
r.components).- element_type¶
alias of
ModelComponent
- class kipetax.model_components.element_blocks.StateBlock[source]¶
Bases:
ElementCollectionNon-concentration differential states (
r.states).- element_type¶
alias of
ModelState
- class kipetax.model_components.element_blocks.AlgebraicBlock[source]¶
Bases:
ElementCollectionAlgebraic variables (
r.algebraics).- element_type¶
alias of
ModelAlgebraic
- class kipetax.model_components.element_blocks.ConstantBlock[source]¶
Bases:
ElementCollectionFixed 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:
objectOne named table of measurements.
- property shape¶
- class kipetax.model_components.data_component.DataBlock[source]¶
Bases:
objectThe datasets of one model, keyed by name in the order added.
- property names¶
Spectral data handler for kipetax (Pyomo-free).
Manages spectral (D-matrix) data with optional preprocessing methods.
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 seedx0at the user’s initial guesses (a far better start than the bound midpoint). Keys that do not match a variable, andNonevalues, 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
mto 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’sParametervalues between calls hits the cache.initial_guess (dict, optional) –
{variable_name: array}warm-start values for full variable blocks (e.g. the spectralS_matrix). A bilinear spectral fit started from the bound midpoint converges to a poor local minimum; seedingSfrom 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:
objectBuilds 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
- set_interactions(interactions)[source]¶
interactions: {name: pending_expression} -> extra absorbing columns.
- 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
Parameterobjects.Identical to
build_simulation_model()except the kinetic parameters enter the ODE as discoptParameterobjects 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 mutatingParameter.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_mapmaps each kinetic parameter name to its discoptParameterso callers can setparam_map[name].valuebetween solves.- Return type:
(discopt.Model, DAEBuilder, dict)
- build_parameter_estimation_model(variances=None)[source]¶
Build a discopt Model for parameter estimation with NLS objective.
- 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 throughdiscopt.solvers.nlp_pounce.solve_nlpand wraps the flat solution into a discoptSolveResultso 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 tosolve_local_nlp()(e.g. a seeded spectralS_matrix). Blocks not supplied fall back to the constant-trajectory seed fromconstant_state_guess().
- Return type:
discopt.modeling.core.SolveResult
- constant_state_guess()[source]¶
Seed every collocation state with its initial condition.
solve_local_nlpstarts at the midpoint of the clipped bounds, so a state declared with the defaultub=1e20starts 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 term2*kt*Y0**2evaluates 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_nlpotherwise starts at the midpoint of the clipped bounds. A concentration state declared with the defaultub=1e20clips to 100 and therefore starts at 50, while the true trajectory is O(1). Weighted by a small measurement variance (1/sigma^2is 2.5e5 atsigma^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^Tstarted from the bound midpoint converges to a poor local minimum, soSis seeded with the closed-formS = pinv(C) @ D.- Returns:
{variable_name: array}orNonewhen the simulation fails.- Return type:
dict or None
- spectral_initial_guess()[source]¶
Warm-start for a spectral fit’s
S_matrix/C_spectralblocks.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 aReactionSetmember.s_prefix (str, optional) – Prefix for the
S_matrixlookup alone. Defaults toprefix;ReactionSetpasses''when the species spectra are shared across experiments, since that block is declared once and unprefixed. Every member then reports the sameS, 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:
objectLightweight node representing a named model variable in a pending expression tree.
- class kipetax.model_tools.proxy_vars.PendingBinaryOp(op, left, right)[source]¶
Bases:
objectA binary operation node in a pending expression tree.
- class kipetax.model_tools.proxy_vars.PendingUnaryOp(op, operand)[source]¶
Bases:
objectA unary operation node in a pending expression tree.
- class kipetax.model_tools.proxy_vars.PendingFunctionCall(func_name, *args)[source]¶
Bases:
objectA function call node in a pending expression tree.
- 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’sjax.numpyfunctions 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:
- 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). WhenNone(default), the residual-estimated reduced chi-squareSSE / (n_meas - n_params)is used. Pass1.0to trust the suppliedvariancesas 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).