KiThe 0.3.22

A numerical suite for chemical kinetics and thermodynamics, combustion, heat and mass transfer,chemical equilibrium, chemical engeneering
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! # Vyazovkin advanced isoconversional method
//!
//! ## What this module does
//! Implements the **Vyazovkin non-linear isoconversional method** for estimating
//! the activation energy Eα as a function of conversion α from non-isothermal
//! TGA experiments run at several heating rates.
//!
//! Unlike the linear integral methods (KAS, OFW, Starink) which approximate the
//! temperature integral analytically, Vyazovkin minimises a functional Φ(Eα) that
//! contains the *exact* numerical temperature integral, making it more accurate
//! especially when Eα varies strongly with α.
//!
//! ## Main data structures
//! - [`VyazovkinSolver`] — holds the search grid bounds (`e_min`, `e_max`, `steps`)
//!   and exposes `solve` / `solve_layer_optimized`.
//! - [`ConversionGrid`] (from `kinetic_methods`) — the pre-built isoconversional
//!   grid; **must** contain the `dt` matrix (time-step increments per experiment
//!   per α-layer), computed by `ConversionGridBuilder::with_dt_matrix()`.
//! - [`IsoconversionalResult`] / [`IsoLayerResult`] (re-exported from
//!   `integral_isoconversion`) — the output: one `IsoLayerResult` per α-layer
//!   carrying `eta`, `ea`, and a placeholder `LinearRegressionResult`.
//!
//! ## Algorithm
//! For each α-layer k the solver minimises:
//!
//! ```text
//! Φ(E) = Σᵢ Σⱼ≠ᵢ  J(E, Tᵢ) / J(E, Tⱼ)
//! ```
//!
//! where `J(E, Tᵢ) = exp(-E/RT_i) · Δtᵢ` is the trapezoidal approximation of
//! the temperature integral for experiment i at layer k.
//!
//! ## Non-trivial optimisation trick
//! The naive double-loop over all experiment pairs is O(n²).  
//! `solve_layer_optimized` rewrites the sum algebraically:
//!
//! ```text
//! Σᵢ Σⱼ≠ᵢ Jᵢ/Jⱼ  =  (Σ Jᵢ)(Σ 1/Jᵢ) − n
//! ```
//!
//! reducing the inner work to two O(n) passes — a significant speedup when many
//! experiments are used.  The search over E is a simple uniform grid scan
//! (`steps` points between `e_min` and `e_max`); no gradient information is
//! needed, which keeps the implementation robust against flat or noisy Φ landscapes.

use crate::Kinetics::experimental_kinetics::kinetic_methods::integral_isoconversion::IsoLayerResult;
use crate::Kinetics::experimental_kinetics::kinetic_methods::integral_isoconversion::IsoconversionalResult;
use crate::Kinetics::experimental_kinetics::kinetic_methods::kinetic_regression::LinearRegressionResult;
use crate::Kinetics::experimental_kinetics::kinetic_methods::*;

/// Solver for the Vyazovkin non-linear isoconversional method.
///
/// Searches for the activation energy Eα at each α-layer by minimising the
/// functional Φ(E) over a uniform grid of `steps` candidate values in
/// `[e_min, e_max]` (J/mol).
#[derive(Clone, Debug)]
pub struct VyazovkinSolver {
    /// Lower bound of the Eα search range (J/mol). Default: 40 000.
    pub e_min: f64,
    /// Upper bound of the Eα search range (J/mol). Default: 300 000.
    pub e_max: f64,
    /// Number of uniformly-spaced candidate E values to evaluate. Default: 200.
    pub steps: usize,
}

impl VyazovkinSolver {
    /// Run the Vyazovkin method over all α-layers in `grid`.
    ///
    /// Requires `grid.dt` to be populated (use `ConversionGridBuilder::with_dt_matrix()`).
    /// Returns one [`IsoLayerResult`] for each destination layer after the
    /// first. The interval ending at layer `k` is stored in `dt[:, k - 1]`.
    pub fn solve(&self, grid: &ConversionGrid) -> Result<IsoconversionalResult, TGADomainError> {
        self.validate_search()?;
        let dt = grid.dt.as_ref().ok_or(TGADomainError::InvalidOperation(
            "Vyazovkin requires dt matrix".into(),
        ))?;

        let n_eta = grid.eta.len();
        if n_eta < 2 {
            return Err(TGADomainError::InvalidOperation(
                "Vyazovkin requires at least two conversion layers".into(),
            ));
        }
        let mut layers = Vec::with_capacity(n_eta - 1);

        for k in 1..n_eta {
            let ea = self.solve_layer_optimized(grid, dt, k)?;

            layers.push(IsoLayerResult {
                eta: grid.eta[k],
                ea,
                k: None,
                regression: LinearRegressionResult::default(),
            });
        }

        Ok(IsoconversionalResult {
            method: "Vyazovkin",
            layers,
            warnings: Vec::new(),
        })
    }

    fn validate_search(&self) -> Result<(), TGADomainError> {
        if self.steps < 2
            || !self.e_min.is_finite()
            || !self.e_max.is_finite()
            || self.e_min >= self.e_max
        {
            return Err(TGADomainError::InvalidOperation(
                "Vyazovkin requires finite increasing energy bounds and at least two search steps"
                    .into(),
            ));
        }
        Ok(())
    }

    /// Naive O(n²) reference implementation of the layer solver.
    ///
    /// Iterates over all ordered pairs (i, j) with i ≠ j and accumulates
    /// `J(E,T_i) / J(E,T_j)`.  Kept for correctness verification against
    /// `solve_layer_optimized`.
    #[allow(dead_code)]
    fn solve_layer(
        &self,
        grid: &ConversionGrid,
        dt: &Array2<f64>,
        k: usize,
    ) -> Result<f64, TGADomainError> {
        let inv_t_col = grid.inv_temperature.column(k);
        // dt[:, k - 1] spans conversion layers k-1 -> k; temperature is
        // evaluated at the destination layer k.
        let dt_col = dt.column(k - 1);

        let r = 8.314462618;

        self.validate_search()?;
        let mut best_e = None;
        let mut best_phi = f64::INFINITY;

        let n_exp = inv_t_col.len();

        let mut j = vec![0.0; n_exp];

        for s in 0..self.steps {
            let e = self.e_min + (self.e_max - self.e_min) * (s as f64) / (self.steps - 1) as f64;

            let mut valid = true;

            for i in 0..n_exp {
                let inv_t = inv_t_col[i];
                let dt_i = dt_col[i];

                let val = (-e * inv_t / r).exp() * dt_i;

                if !val.is_finite() {
                    valid = false;
                    break;
                }

                j[i] = val;
            }

            if !valid {
                continue;
            }

            let mut phi = 0.0;

            for i in 0..n_exp {
                let ji = j[i];

                if ji < 1e-300 {
                    continue;
                }

                for j2 in 0..n_exp {
                    if i == j2 {
                        continue;
                    }

                    let jj = j[j2];

                    if jj < 1e-300 {
                        continue;
                    }

                    phi += ji / jj;
                }
            }

            if phi < best_phi {
                best_phi = phi;
                best_e = Some(e);
            }
        }

        best_e.ok_or_else(|| {
            TGADomainError::InvalidOperation(format!(
                "Vyazovkin found no valid energy candidate at layer {}",
                k
            ))
        })
    }

    /// Optimised O(n) equivalent of `solve_layer`.
    ///
    /// Uses the algebraic identity  Σᵢ Σⱼ≠ᵢ Jᵢ/Jⱼ = (Σ Jᵢ)(Σ 1/Jᵢ) − n
    /// to replace the double loop with two single passes, then picks the E
    /// that minimises the result.
    pub fn solve_layer_optimized(
        &self,
        grid: &ConversionGrid,
        dt: &Array2<f64>,
        k: usize,
    ) -> Result<f64, TGADomainError> {
        self.validate_search()?;
        if k == 0 || k >= grid.eta.len() || dt.ncols() < k {
            return Err(TGADomainError::InvalidOperation(format!(
                "Vyazovkin layer {} has no corresponding preceding time interval",
                k
            )));
        }
        let inv_t_col = grid.inv_temperature.column(k);
        let dt_col = dt.column(k - 1);

        let r = 8.314462618;

        let n_exp = inv_t_col.len();

        let mut best_e = None;
        let mut best_phi = f64::INFINITY;

        for s in 0..self.steps {
            let e = self.e_min + (self.e_max - self.e_min) * (s as f64) / (self.steps - 1) as f64;

            let mut sum_j = 0.0;
            let mut sum_inv_j = 0.0;

            let mut valid = true;

            for (&inv_t, &dt_i) in inv_t_col.iter().zip(dt_col.iter()) {
                let j = (-e * inv_t / r).exp() * dt_i;

                if !j.is_finite() || j < 1e-300 {
                    valid = false;
                    break;
                }

                sum_j += j;
                sum_inv_j += 1.0 / j;
            }

            if !valid {
                continue;
            }

            let phi = sum_j * sum_inv_j - (n_exp as f64);

            if phi < best_phi {
                best_phi = phi;
                best_e = Some(e);
            }
        }

        best_e.ok_or_else(|| {
            TGADomainError::InvalidOperation(format!(
                "Vyazovkin found no valid energy candidate at layer {}",
                k
            ))
        })
    }
    /// Low-level functional Φ(E) evaluated at a single candidate energy `e`
    /// for layer `k`.  Used internally; exposed for debugging and plotting.
    #[allow(dead_code)]
    fn functional(&self, grid: &ConversionGrid, k: usize, e: f64) -> f64 {
        let r = 8.314;

        let n_exp = grid.temperature.nrows();

        let mut j = vec![0.0; n_exp];

        for i in 0..n_exp {
            let t = grid.temperature[[i, k]];
            let dt = grid.dt.as_ref().unwrap()[[i, k]];

            j[i] = (-e / (r * t)).exp() * dt;
        }

        let mut phi = 0.0;

        for i in 0..n_exp {
            for j2 in 0..n_exp {
                if i != j2 {
                    phi += j[i] / j[j2];
                }
            }
        }

        phi
    }
}

impl Default for VyazovkinSolver {
    fn default() -> Self {
        Self {
            e_min: 40_000.0,
            e_max: 300_000.0,
            steps: 200,
        }
    }
}

/// Marker struct that wires `VyazovkinSolver` into the `KineticMethod` trait
/// (used by the unified dispatcher in `isoconversion.rs`).
pub struct Vyzaovkin;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Kinetics::experimental_kinetics::experiment_series_main::ExperimentMeta;
    use crate::Kinetics::experimental_kinetics::kinetic_methods::integral_isoconversion_tests::tests::simulate_tga_first_order_with_dt;

    use crate::Kinetics::experimental_kinetics::kinetic_methods::integral_isoconversion::VyazovkinMethod;
    use crate::Kinetics::experimental_kinetics::kinetic_methods_tests::tests::build_view_from_cfg_exact_m0;
    use crate::Kinetics::experimental_kinetics::testing_mod::tests_afvanced_config::base_advanced_config_non_isothermal;
    use ndarray::{Array1, Array2, array};

    #[test]
    fn optimized_solver_matches_pairwise_reference_on_nonuniform_time_steps() {
        let time = array![[0.0, 1.0, 4.0, 10.0], [0.0, 2.0, 8.0, 20.0]];
        let temperature = array![[480.0, 510.0, 550.0, 600.0], [500.0, 530.0, 570.0, 620.0]];
        let inv_temperature = temperature.mapv(|value| 1.0 / value);
        let dt = ConversionGridBuilder::compute_dt_matrix(&time).unwrap();
        let grid = ConversionGrid {
            eta: Array1::from_vec(vec![0.1, 0.3, 0.6, 0.9]),
            temperature,
            inv_temperature,
            time,
            conversion_rate: Array2::ones((2, 4)),
            dt: Some(dt),
            meta: vec![ExperimentMeta::new(), ExperimentMeta::new()],
        };
        let solver = VyazovkinSolver {
            e_min: 20_000.0,
            e_max: 250_000.0,
            steps: 701,
        };
        let dt = grid.dt.as_ref().unwrap();

        for layer in 1..grid.eta.len() {
            let pairwise = solver.solve_layer(&grid, dt, layer).unwrap();
            let optimized = solver.solve_layer_optimized(&grid, dt, layer).unwrap();
            assert_eq!(optimized, pairwise, "energy mismatch at layer {layer}");
        }
    }

    #[test]
    fn vyazovkin_compute_with_mock_non_isothermal_data() {
        // similar to ofw_compute_with_mock_non_isothermal_data2 but using Vyazovkin pipeline
        let cfg = base_advanced_config_non_isothermal(
            420.0,
            1e6,
            100_000.0,
            1.0, // seconds
            30_000,
            vec![0.5, 0.75, 1.0, 1.5],
        );
        let view = build_view_from_cfg_exact_m0(&cfg).unwrap();

        // use method adapter that builds dt-matrix internally
        let result = VyazovkinMethod {}.compute(&view).unwrap();
        result.pretty_print_and_assert(0.05, 0.95, 100, None);
        assert!(result.layers.len() > 0);
        for layer in &result.layers {
            assert!(layer.ea.is_finite());
        }
    }

    #[test]
    fn vyazovkin_mock_grid_basic() {
        // generate a synthetic grid that includes dt matrix via builder in method compute
        let grid = simulate_tga_first_order_with_dt(
            500.0,
            1e6,
            120_000.0,
            &[0.5, 1.0, 1.5, 2.0],
            0.5,
            50_000,
            Some(vec![0.1, 0.3, 0.5, 0.7, 0.9]),
        );
        // Build a new grid with dt via the production builder path by wrapping into a view is complex here,
        // instead directly call solver expecting dt to be absent -> we check method path on real pipeline in previous test.
        // Here we only assert solver refuses grids without dt to avoid silent misuse.
        let result = VyazovkinSolver::default().solve(&grid).unwrap();
        result.pretty_print_and_assert(0.05, 0.95, 100, None);
    }

    #[test]
    fn vyazovkin_rejects_invalid_search_grid() {
        assert!(
            VyazovkinSolver {
                steps: 1,
                ..Default::default()
            }
            .validate_search()
            .is_err()
        );
        assert!(
            VyazovkinSolver {
                e_min: 300_000.0,
                e_max: 40_000.0,
                ..Default::default()
            }
            .validate_search()
            .is_err()
        );
    }
}