KiThe 0.3.17

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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
//! Controller code for Kinetic Methods menu and sub-windows.
//!
//! Each menu item opens a dedicated popup window for a kinetic-analysis workflow.

use crate::Kinetics::experimental_kinetics::kinetic_methods::KineticMethod;
use crate::Kinetics::experimental_kinetics::kinetic_methods::Kissinger::Kissinger;
use crate::Kinetics::experimental_kinetics::kinetic_methods::combined::CombinedKineticAnalysis;
use crate::Kinetics::experimental_kinetics::kinetic_methods::is_this_a_sublimation::{
    IsThisASublimationResult, SublimationMethod,
};
use crate::Kinetics::experimental_kinetics::kinetic_methods::isoconversion::{
    IsoconversionalKineticMethod, IsoconversionalMethod,
};
use crate::Kinetics::experimental_kinetics::math::fitting::{
    FitColumnRequest, FitColumnResult, FitColumnSession, FitEvaluationMode, FittedEvaluationBatch,
    FittingModelName, evaluate_fit_batch,
};
use crate::gui::experimental_kinetics_gui::model::{PlotModel, TGAGUIError};
use eframe::egui;

/// State for which Kinetic Methods tool windows are currently open.
pub struct KineticMethodsWindowState {
    pub isoconversional_open: bool,
    pub isoconversional_method: IsoconversionalMethod,
    pub isoconversional_status: String,
    pub isoconversional_use_selected_experiments: bool,
    pub isoconversional_selected_experiments: Vec<String>,
    pub isoconversional_output_id: String,
    pub kissinger_open: bool,
    pub kissinger_status: String,
    pub kissinger_ea_kj: Option<f64>,
    pub kissinger_r2: Option<f64>,
    pub combined_kinetics_open: bool,
    pub combined_status: String,
    pub combined_n_min: f64,
    pub combined_n_max: f64,
    pub combined_n_steps: usize,
    pub combined_m_min: f64,
    pub combined_m_max: f64,
    pub combined_m_steps: usize,
    pub combined_eta_min: f64,
    pub combined_eta_max: f64,
    pub combined_refinement_steps: usize,
    pub combined_result_n: Option<f64>,
    pub combined_result_m: Option<f64>,
    pub combined_result_ea_kj: Option<f64>,
    pub combined_result_r2: Option<f64>,
    pub fit_model_open: bool,
    pub fit_model_experiment_id: String,
    pub fit_model_x_col: String,
    pub fit_model_y_col: String,
    pub fit_model_output_col: String,
    pub fit_model_model: FittingModelName,
    pub fit_model_polynomial_degree: usize,
    pub fit_model_initial_guess: String,
    pub fit_model_tolerance: f64,
    pub fit_model_max_iter: usize,
    pub fit_model_status: String,
    pub fit_model_result: Option<FitColumnResult>,
    pub fit_sessions: Vec<FitColumnSession>,
    pub fit_training_range_enabled: bool,
    pub fit_training_start: f64,
    pub fit_training_end: f64,
    pub fit_gap_enabled: bool,
    pub fit_gap_start: f64,
    pub fit_gap_end: f64,
    pub fit_evaluation_start: f64,
    pub fit_evaluation_end: f64,
    pub fit_evaluation_points: usize,
    pub fit_pending_batch: Option<FittedEvaluationBatch>,
    pub fit_reconstructed_experiment_id: String,
    pub sublimation_check_open: bool,
    pub sublimation_status: String,
    pub sublimation_mean_ea_kj: Option<f64>,
    pub sublimation_mean_k: Option<f64>,
    pub sublimation_verdict: Option<String>,
}

impl Default for KineticMethodsWindowState {
    fn default() -> Self {
        Self {
            isoconversional_open: false,
            isoconversional_method: IsoconversionalMethod::default(),
            isoconversional_status: String::new(),
            isoconversional_use_selected_experiments: false,
            isoconversional_selected_experiments: Vec::new(),
            isoconversional_output_id: "isoconversional_result".to_string(),
            kissinger_open: false,
            kissinger_status: String::new(),
            kissinger_ea_kj: None,
            kissinger_r2: None,
            combined_kinetics_open: false,
            combined_status: String::new(),
            combined_n_min: CombinedKineticAnalysis::default().n_min,
            combined_n_max: CombinedKineticAnalysis::default().n_max,
            combined_n_steps: CombinedKineticAnalysis::default().n_steps,
            combined_m_min: CombinedKineticAnalysis::default().m_min,
            combined_m_max: CombinedKineticAnalysis::default().m_max,
            combined_m_steps: CombinedKineticAnalysis::default().m_steps,
            combined_eta_min: CombinedKineticAnalysis::default().eta_min,
            combined_eta_max: CombinedKineticAnalysis::default().eta_max,
            combined_refinement_steps: CombinedKineticAnalysis::default().refinement_steps,
            combined_result_n: None,
            combined_result_m: None,
            combined_result_ea_kj: None,
            combined_result_r2: None,
            fit_model_open: false,
            fit_model_experiment_id: String::new(),
            fit_model_x_col: String::new(),
            fit_model_y_col: String::new(),
            fit_model_output_col: String::new(),
            fit_model_model: FittingModelName::DecExp,
            fit_model_polynomial_degree: 2,
            fit_model_initial_guess: String::new(),
            fit_model_tolerance: 1e-6,
            fit_model_max_iter: 300,
            fit_model_status: String::new(),
            fit_model_result: None,
            fit_sessions: Vec::new(),
            fit_training_range_enabled: false,
            fit_training_start: 0.0,
            fit_training_end: 1.0,
            fit_gap_enabled: false,
            fit_gap_start: 0.0,
            fit_gap_end: 1.0,
            fit_evaluation_start: 0.0,
            fit_evaluation_end: 1.0,
            fit_evaluation_points: 20,
            fit_pending_batch: None,
            fit_reconstructed_experiment_id: String::new(),
            sublimation_check_open: false,
            sublimation_status: String::new(),
            sublimation_mean_ea_kj: None,
            sublimation_mean_k: None,
            sublimation_verdict: None,
        }
    }
}

impl KineticMethodsWindowState {
    pub(crate) fn close_window_on_layer(&mut self, layer: Option<egui::LayerId>) -> bool {
        let Some(layer) = layer else { return false };
        let windows = [
            ("Isoconversional", &mut self.isoconversional_open),
            ("Kissinger", &mut self.kissinger_open),
            (
                "Combined Kinetics Analysis",
                &mut self.combined_kinetics_open,
            ),
            ("Is this a sublimation?", &mut self.sublimation_check_open),
            ("Fit Model", &mut self.fit_model_open),
        ];
        for (title, is_open) in windows {
            if layer.id == egui::Id::unique(Some(title)) && *is_open {
                *is_open = false;
                return true;
            }
        }
        false
    }
}

pub struct KineticMethods;

impl KineticMethods {
    fn publish_status(model: &mut PlotModel, status: &str) {
        let _ = model.push_message(status);
    }

    /// Render the dropdown menu entries under the "Kinetic Methods" top menu.
    pub fn show_menu(ui: &mut egui::Ui, state: &mut KineticMethodsWindowState) {
        if ui.button("Isoconversional").on_hover_text("Non-isothermal activation-energy analysis over conversion; can create a result experiment.").clicked() {
            state.isoconversional_open = true;
        }
        if ui.button("Kissinger").on_hover_text("Non-isothermal peak-temperature method for one activation energy; updates results only.").clicked() {
            state.kissinger_open = true;
        }
        if ui.button("Combined Kinetics Analysis").on_hover_text("Non-isothermal model-parameter search; numeric search ranges are configured in its window.").clicked() {
            state.combined_kinetics_open = true;
        }
        ui.label("Criado Master Curve: unavailable pending scientific validation");
        if ui.button("Fit Model").on_hover_text("General single-experiment curve fitting, not a kinetic method; adds a fitted output column.").clicked() {
            state.fit_model_open = true;
        }
        if ui.button("Is this a sublimation?").on_hover_text("Non-isothermal diagnostic using conversion rate and temperature; adds fitted-rate columns.").clicked() {
            state.sublimation_check_open = true;
        }
    }
    //===========================================================================================================
    /// ISOCONVERSIONAL ANALYSIS
    ///===========================================================================================================
    /// Show the isoconversional analysis window.
    pub fn show_isoconversional_window(
        ui: &mut egui::Ui,
        model: &mut PlotModel,
        state: &mut KineticMethodsWindowState,
    ) -> Result<(), TGAGUIError> {
        if !state.isoconversional_open {
            return Ok(());
        }

        egui::Window::new("Isoconversional")
            .open(&mut state.isoconversional_open)
            .default_size([540.0, 360.0])
            .show(ui.ctx(), |ui| {
                ui.vertical(|ui| {
                    ui.label("Non-isothermal method: estimates activation energy versus conversion from experiments run at different heating rates. Choose the method and experiments; Calculate adds a result experiment using the Output ID.");
                    ui.add_space(4.0);
                    ui.horizontal(|ui| {
                        let label = ui.label("Method:");
                        let combo = egui::ComboBox::from_id_salt("isoconv_method")
                            .selected_text(state.isoconversional_method.display_name())
                            .show_ui(ui, |ui| {
                                for method in IsoconversionalMethod::all() {
                                    ui.selectable_value(
                                        &mut state.isoconversional_method,
                                        *method,
                                        method.display_name(),
                                    );
                                }
                            });
                        let _ = combo.response.labelled_by(label.id);
                    });

                    ui.add_space(6.0);

                    // Build a stable list of experiment ids for selection.
                    let exp_ids = model.list_of_experiments();
                    state
                        .isoconversional_selected_experiments
                        .retain(|id| exp_ids.iter().any(|exp| exp == id));

                    ui.horizontal(|ui| {
                        ui.label("Experiments:");
                        ui.checkbox(
                            &mut state.isoconversional_use_selected_experiments,
                            "Use selected only",
                        );
                    });

                    // When enabled, the user chooses a subset of experiments.
                    if state.isoconversional_use_selected_experiments {
                        if exp_ids.is_empty() {
                            ui.label("No experiments available.");
                        } else {
                            ui.vertical(|ui| {
                                for id in &exp_ids {
                                    let mut selected = state
                                        .isoconversional_selected_experiments
                                        .iter()
                                        .any(|v| v == id);
                                    if ui.checkbox(&mut selected, id).changed() {
                                        if selected {
                                            if !state
                                                .isoconversional_selected_experiments
                                                .contains(id)
                                            {
                                                state
                                                    .isoconversional_selected_experiments
                                                    .push(id.clone());
                                            }
                                        } else {
                                            state
                                                .isoconversional_selected_experiments
                                                .retain(|v| v != id);
                                        }
                                    }
                                }
                            });
                        }
                    }

                    ui.add_space(6.0);

                    ui.horizontal(|ui| {
                        let label = ui.label("Output ID:");
                        let input = ui.text_edit_singleline(&mut state.isoconversional_output_id);
                        let _ = input.labelled_by(label.id);
                    });

                    ui.add_space(6.0);

                    ui.horizontal(|ui| {
                        ui.label("Status:");
                        ui.label(&state.isoconversional_status);
                    });

                    ui.add_space(8.0);

                    // Run the chosen method and store the result as a new experiment.
                    if ui.button("Calculate").on_hover_text("Requires suitable non-isothermal experiments; optionally select a subset and set the result experiment ID. Adds a result experiment, not a source-data column.").clicked() {
                        let status = (|| -> Result<String, TGAGUIError> {
                            if exp_ids.is_empty() {
                                return Ok("No experiments to analyze.".to_string());
                            }

                            let selected_ids: Vec<&str> = state
                                .isoconversional_selected_experiments
                                .iter()
                                .map(|s| s.as_str())
                                .collect();

                            let what_exp_to_take = if state.isoconversional_use_selected_experiments
                            {
                                if selected_ids.is_empty() {
                                    return Ok("Select at least one experiment.".to_string());
                                }
                                Some(selected_ids.as_slice())
                            } else {
                                None
                            };

                            let output_id = if state.isoconversional_output_id.trim().is_empty() {
                                "isoconversional_result".to_string()
                            } else {
                                state.isoconversional_output_id.trim().to_string()
                            };

                            let view = model.create_kinetic_data_view_for_method(
                                what_exp_to_take,
                                &state.isoconversional_method,
                            )?;

                            let method = IsoconversionalKineticMethod {
                                method: state.isoconversional_method.clone(),
                            };

                            method.check_input(&view)?;
                            let result = method.compute(&view)?;
                            let warnings = result.warnings.clone();

                            model.push_isoconversional_result(&result, &output_id)?;

                            if warnings.is_empty() {
                                Ok(format!("Done. Result saved as '{}'.", output_id))
                            } else {
                                Ok(format!(
                                    "Result saved as '{}'; {} diagnostic warning(s): {}",
                                    output_id,
                                    warnings.len(),
                                    warnings.join(" | ")
                                ))
                            }
                        })();

                        state.isoconversional_status = match status {
                            Ok(msg) => msg,
                            Err(err) => format!("Error: {err}"),
                        };
                        Self::publish_status(model, &state.isoconversional_status);
                    }
                });
            });

        Ok(())
    }
    //===========================================================================================================
    /// KISSINGER ANALYSIS
    //===========================================================================================================
    /// Show the Kissinger analysis window.
    pub fn show_kissinger_window(
        ui: &mut egui::Ui,
        model: &mut PlotModel,
        state: &mut KineticMethodsWindowState,
    ) -> Result<(), TGAGUIError> {
        if !state.kissinger_open {
            return Ok(());
        }

        egui::Window::new("Kissinger")
            .open(&mut state.kissinger_open)
            .default_size([520.0, 300.0])
            .show(ui.ctx(), |ui| {
                ui.vertical(|ui| {
                    ui.label("Non-isothermal Kissinger peak method: estimates one activation energy from peak temperatures measured at different heating rates. No numeric or text input is required; results appear below and source data is unchanged.");
                    ui.add_space(4.0);
                    let ea_label = state
                        .kissinger_ea_kj
                        .map(|v| format!("{:.2}", v))
                        .unwrap_or_else(|| "-".to_string());
                    let r2_label = state
                        .kissinger_r2
                        .map(|v| format!("{:.4}", v))
                        .unwrap_or_else(|| "-".to_string());

                    ui.horizontal(|ui| {
                        ui.label("Ea (kJ/mol):");
                        ui.label(ea_label);
                    });

                    ui.horizontal(|ui| {
                        ui.label("R2:");
                        ui.label(r2_label);
                    });

                    ui.add_space(6.0);

                    ui.horizontal(|ui| {
                        ui.label("System messages:");
                        ui.label(&state.kissinger_status);
                    });

                    ui.add_space(8.0);

                    // Run the Kissinger calculation without creating new series data or curves.
                    if ui.button("Calculate").on_hover_text("Requires multiple non-isothermal experiments with different heating rates. Updates Ea/R2 labels only; no column or experiment is created.").clicked() {
                        let status = (|| -> Result<String, TGAGUIError> {
                            // Kissinger needs the same columns as non-isothermal isoconversional methods.
                            let view = model.create_kinetic_data_view_for_method(
                                None,
                                &IsoconversionalMethod::OFW,
                            )?;

                            let result = Kissinger.compute(&view)?;

                            let ea_kj = result.ea / 1000.0;
                            state.kissinger_ea_kj = Some(ea_kj);
                            state.kissinger_r2 = Some(result.regression.r2);

                            Ok("Done.".to_string())
                        })();

                        state.kissinger_status = match status {
                            Ok(msg) => msg,
                            Err(err) => format!("Error: {err}"),
                        };
                        Self::publish_status(model, &state.kissinger_status);
                    }
                });
            });

        Ok(())
    }
    //===========================================================================================================
    /// SUBLIMATION CHECK
    //===========================================================================================================
    /// Show the "Is this a sublimation?" window.
    pub fn show_sublimation_window(
        ui: &mut egui::Ui,
        model: &mut PlotModel,
        state: &mut KineticMethodsWindowState,
    ) -> Result<(), TGAGUIError> {
        if !state.sublimation_check_open {
            return Ok(());
        }

        egui::Window::new("Is this a sublimation?")
            .open(&mut state.sublimation_check_open)
            .default_size([560.0, 320.0])
            .show(ui.ctx(), |ui| {
                ui.vertical(|ui| {
                    ui.label("Non-isothermal diagnostic: evaluates conversion-rate behavior against temperature across experiments and reports whether it is consistent with sublimation. It also adds fitted-rate columns; source columns are retained.");
                    ui.add_space(4.0);
                    let ea_label = state
                        .sublimation_mean_ea_kj
                        .map(|v| format!("{:.2}", v))
                        .unwrap_or_else(|| "-".to_string());
                    let k_label = state
                        .sublimation_mean_k
                        .map(|v| format!("{:.4e}", v))
                        .unwrap_or_else(|| "-".to_string());
                    let verdict_label = state
                        .sublimation_verdict
                        .clone()
                        .unwrap_or_else(|| "-".to_string());

                    ui.horizontal(|ui| {
                        ui.label("Mean Ea (kJ/mol):");
                        ui.label(ea_label);
                    });

                    ui.horizontal(|ui| {
                        ui.label("Mean k:");
                        ui.label(k_label);
                    });

                    ui.horizontal(|ui| {
                        ui.label("Verdict:");
                        ui.label(verdict_label);
                    });

                    ui.add_space(6.0);

                    ui.horizontal(|ui| {
                        ui.label("System messages:");
                        ui.label(&state.sublimation_status);
                    });

                    ui.add_space(8.0);

                    // Run the solver, store mean values, and push fitted curves into the series.
                    if ui.button("Calculate").on_hover_text("Requires conversion, conversion rate and temperature data. Updates the verdict and adds fitted-rate columns; no input fields are required.").clicked() {
                        let status = (|| -> Result<String, TGAGUIError> {
                            let method = SublimationMethod::default();
                            let cols = method.required_columns_by_nature();
                            let view = model.create_kinetic_data_view(None, cols)?;

                            let results = method.compute(&view)?;
                            let (mean_ea, mean_k, verdict) =
                                SublimationMethod::mean_results(&results)?;

                            state.sublimation_mean_ea_kj = Some(mean_ea / 1000.0);
                            state.sublimation_mean_k = Some(mean_k);

                            let verdict_text = match verdict {
                                IsThisASublimationResult::Yes(r2) => {
                                    format!("Yes (R2={:.4})", r2)
                                }
                                IsThisASublimationResult::MayBe(r2) => {
                                    format!("Maybe (R2={:.4})", r2)
                                }
                                IsThisASublimationResult::No(r2) => {
                                    format!("No (R2={:.4})", r2)
                                }
                            };
                            state.sublimation_verdict = Some(verdict_text);

                            model.push_sublimation_fitted_rates(&results)?;

                            Ok("Done.".to_string())
                        })();

                        state.sublimation_status = match status {
                            Ok(msg) => msg,
                            Err(TGAGUIError::PostCommitWarning(warning)) => {
                                format!("Warning: {warning}")
                            }
                            Err(err) => format!("Error: {err}"),
                        };
                        Self::publish_status(model, &state.sublimation_status);
                    }
                });
            });

        Ok(())
    }
    //===========================================================================================================
    /// COMBINED KINETICS ANALYSIS
    //===========================================================================================================
    /// Show the Combined Kinetics Analysis window.
    pub fn show_combined_kinetics_window(
        ui: &mut egui::Ui,
        model: &mut PlotModel,
        state: &mut KineticMethodsWindowState,
    ) -> Result<(), TGAGUIError> {
        if !state.combined_kinetics_open {
            return Ok(());
        }

        egui::Window::new("Combined Kinetics Analysis")
            .open(&mut state.combined_kinetics_open)
            .default_size([560.0, 420.0])
            .show(ui.ctx(), |ui| {
                ui.vertical(|ui| {
                    ui.label("Non-isothermal combined analysis: searches model exponents and activation energy using conversion, conversion rate and temperature. Set the numeric search ranges below; calculation updates result labels without adding columns.");
                    ui.add_space(4.0);
                    // Manual parameter inputs for the analysis grid.
                    ui.horizontal(|ui| {
                        ui.label("n_min:");
                        ui.add(egui::DragValue::new(&mut state.combined_n_min).speed(0.1));
                        ui.label("n_max:");
                        ui.add(egui::DragValue::new(&mut state.combined_n_max).speed(0.1));
                        ui.label("n_steps:");
                        ui.add(egui::DragValue::new(&mut state.combined_n_steps).speed(1.0));
                    });

                    ui.horizontal(|ui| {
                        ui.label("m_min:");
                        ui.add(egui::DragValue::new(&mut state.combined_m_min).speed(0.1));
                        ui.label("m_max:");
                        ui.add(egui::DragValue::new(&mut state.combined_m_max).speed(0.1));
                        ui.label("m_steps:");
                        ui.add(egui::DragValue::new(&mut state.combined_m_steps).speed(1.0));
                    });

                    ui.horizontal(|ui| {
                        ui.label("alpha_min:");
                        ui.add(egui::DragValue::new(&mut state.combined_eta_min).speed(0.01));
                        ui.label("alpha_max:");
                        ui.add(egui::DragValue::new(&mut state.combined_eta_max).speed(0.01));
                        ui.label("refinement_steps:");
                        ui.add(
                            egui::DragValue::new(&mut state.combined_refinement_steps).speed(1.0),
                        );
                    });

                    ui.add_space(6.0);

                    let n_label = state
                        .combined_result_n
                        .map(|v| format!("{:.4}", v))
                        .unwrap_or_else(|| "-".to_string());
                    let m_label = state
                        .combined_result_m
                        .map(|v| format!("{:.4}", v))
                        .unwrap_or_else(|| "-".to_string());
                    let ea_label = state
                        .combined_result_ea_kj
                        .map(|v| format!("{:.2}", v))
                        .unwrap_or_else(|| "-".to_string());
                    let r2_label = state
                        .combined_result_r2
                        .map(|v| format!("{:.4}", v))
                        .unwrap_or_else(|| "-".to_string());

                    ui.horizontal(|ui| {
                        ui.label("n:");
                        ui.label(n_label);
                        ui.label("m:");
                        ui.label(m_label);
                    });

                    ui.horizontal(|ui| {
                        ui.label("Ea (kJ/mol):");
                        ui.label(ea_label);
                        ui.label("R2:");
                        ui.label(r2_label);
                    });

                    ui.add_space(6.0);

                    ui.horizontal(|ui| {
                        ui.label("System messages:");
                        ui.label(&state.combined_status);
                    });

                    ui.add_space(8.0);

                    // Run the analysis and update result labels.
                    if ui.button("Calculate").on_hover_text("Requires non-isothermal temperature, conversion and conversion-rate data. Uses the numeric search settings; updates result labels only, with no new column.").clicked() {
                        let status = (|| -> Result<String, TGAGUIError> {
                            let analysis = CombinedKineticAnalysis {
                                n_min: state.combined_n_min,
                                n_max: state.combined_n_max,
                                n_steps: state.combined_n_steps,
                                m_min: state.combined_m_min,
                                m_max: state.combined_m_max,
                                m_steps: state.combined_m_steps,
                                eta_min: state.combined_eta_min,
                                eta_max: state.combined_eta_max,
                                refinement_steps: state.combined_refinement_steps,
                            };

                            let cols = analysis.required_columns_by_nature();
                            let view = model.create_kinetic_data_view(None, cols)?;
                            let result = analysis.compute(&view)?;

                            state.combined_result_n = Some(result.n);
                            state.combined_result_m = Some(result.m);
                            state.combined_result_ea_kj = Some(result.ea / 1000.0);
                            state.combined_result_r2 = Some(result.regression.r2);

                            Ok("Done.".to_string())
                        })();

                        state.combined_status = match status {
                            Ok(msg) => msg,
                            Err(err) => format!("Error: {err}"),
                        };
                        Self::publish_status(model, &state.combined_status);
                    }
                });
            });

        Ok(())
    }

    /// Show the column-fitting window.
    pub fn show_fit_model_window(
        ui: &mut egui::Ui,
        model: &mut PlotModel,
        state: &mut KineticMethodsWindowState,
    ) -> Result<(), TGAGUIError> {
        if !state.fit_model_open {
            return Ok(());
        }

        egui::Window::new("Fit Model")
            .open(&mut state.fit_model_open)
            .default_size([620.0, 430.0])
            .show(ui.ctx(), |ui| {
                ui.vertical(|ui| {
                    ui.label("General curve fitting, not a kinetic method (isothermal classification: not applicable). Choose one experiment, X/Y columns, model and optional fit settings. Fit adds a fitted-Y column; an existing output name is replaced.");
                    ui.add_space(4.0);
                    let exp_ids = model.list_of_experiments();
                    if state.fit_model_experiment_id.is_empty()
                        || !exp_ids
                            .iter()
                            .any(|id| id == &state.fit_model_experiment_id)
                    {
                        state.fit_model_experiment_id = model
                            .get_experiment_by_selected_curve()
                            .ok()
                            .filter(|id| exp_ids.is_empty() || exp_ids.contains(id))
                            .or_else(|| exp_ids.first().cloned())
                            .unwrap_or_default();
                    }

                    ui.horizontal(|ui| {
                        let label = ui.label("Experiment:");
                        let combo = egui::ComboBox::from_id_salt("fit_model_experiment")
                            .selected_text(if state.fit_model_experiment_id.is_empty() {
                                "-"
                            } else {
                                &state.fit_model_experiment_id
                            })
                            .show_ui(ui, |ui| {
                                for id in &exp_ids {
                                    ui.selectable_value(
                                        &mut state.fit_model_experiment_id,
                                        id.clone(),
                                        id,
                                    );
                                }
                            });
                        let _ = combo.response.labelled_by(label.id);
                    });

                    let columns = if state.fit_model_experiment_id.is_empty() {
                        Ok(Vec::new())
                    } else {
                        model.list_of_columns(&state.fit_model_experiment_id)
                    };
                    let selected_curve_axes = model
                        .get_experiment_by_selected_curve()
                        .ok()
                        .filter(|id| id == &state.fit_model_experiment_id)
                        .and_then(|_| Some((model.this_is_x().ok()?, model.this_is_y().ok()?)));

                    match columns {
                        Ok(columns) => {
                            if state.fit_model_x_col.is_empty()
                                || !columns.iter().any(|col| col == &state.fit_model_x_col)
                            {
                                state.fit_model_x_col = selected_curve_axes
                                    .as_ref()
                                    .map(|(x, _)| x)
                                    .filter(|x| columns.contains(x))
                                    .cloned()
                                    .or_else(|| {
                                        columns.iter().find(|c| c.as_str() == "time").cloned()
                                    })
                                    .or_else(|| columns.iter().min().cloned())
                                    .unwrap_or_default();
                            }
                            if state.fit_model_y_col.is_empty()
                                || !columns.iter().any(|col| col == &state.fit_model_y_col)
                            {
                                state.fit_model_y_col = selected_curve_axes
                                    .as_ref()
                                    .map(|(_, y)| y)
                                    .filter(|y| **y != state.fit_model_x_col && columns.contains(y))
                                    .cloned()
                                    .or_else(|| {
                                        columns
                                            .iter()
                                            .find(|c| {
                                                c.as_str() == "mass" && **c != state.fit_model_x_col
                                            })
                                            .cloned()
                                    })
                                    .or_else(|| {
                                        columns
                                            .iter()
                                            .filter(|c| c.as_str() != state.fit_model_x_col)
                                            .min()
                                            .cloned()
                                    })
                                    .or_else(|| columns.iter().min().cloned())
                                    .unwrap_or_default();
                            }

                            ui.horizontal(|ui| {
                                let label = ui.label("X:");
                                let combo = egui::ComboBox::from_id_salt("fit_model_x")
                                    .selected_text(if state.fit_model_x_col.is_empty() {
                                        "-"
                                    } else {
                                        &state.fit_model_x_col
                                    })
                                    .show_ui(ui, |ui| {
                                        for col in &columns {
                                            ui.selectable_value(
                                                &mut state.fit_model_x_col,
                                                col.clone(),
                                                col,
                                            );
                                        }
                                    });
                                let _ = combo.response.labelled_by(label.id);

                                let label = ui.label("Y:");
                                let combo = egui::ComboBox::from_id_salt("fit_model_y")
                                    .selected_text(if state.fit_model_y_col.is_empty() {
                                        "-"
                                    } else {
                                        &state.fit_model_y_col
                                    })
                                    .show_ui(ui, |ui| {
                                        for col in &columns {
                                            ui.selectable_value(
                                                &mut state.fit_model_y_col,
                                                col.clone(),
                                                col,
                                            );
                                        }
                                    });
                                let _ = combo.response.labelled_by(label.id);
                            });

                            ui.horizontal(|ui| {
                                let label = ui.label("Model:");
                                let combo = egui::ComboBox::from_id_salt("fit_model_kind")
                                    .selected_text(state.fit_model_model.display_name())
                                    .show_ui(ui, |ui| {
                                        for fit_model in FittingModelName::all_for_gui() {
                                            let changed = ui
                                                .selectable_value(
                                                    &mut state.fit_model_model,
                                                    fit_model,
                                                    fit_model.display_name(),
                                                )
                                                .changed();
                                            if changed {
                                                if let Some(n) = fit_model.polynomial_degree() {
                                                    state.fit_model_polynomial_degree = n;
                                                }
                                            }
                                        }
                                    });
                                let _ = combo.response.labelled_by(label.id);
                            });

                            if state.fit_model_model.polynomial_degree().is_some() {
                                ui.horizontal(|ui| {
                                    let label = ui.label("Polynomial degree:");
                                    let response = ui.add(
                                        egui::DragValue::new(
                                            &mut state.fit_model_polynomial_degree,
                                        )
                                        .speed(1.0)
                                        .range(1..=12),
                                    );
                                    let changed = response.changed();
                                    let _ = response.labelled_by(label.id);
                                    if changed
                                        || state.fit_model_model.polynomial_degree()
                                            != Some(state.fit_model_polynomial_degree)
                                    {
                                        state.fit_model_model = FittingModelName::Polynom {
                                            n: state.fit_model_polynomial_degree,
                                        };
                                    }
                                });
                            }

                            ui.horizontal(|ui| {
                                ui.label("Formula:");
                                ui.monospace(state.fit_model_model.equation_str());
                            });

                            egui::CollapsingHeader::new("Model equations")
                                .default_open(false)
                                .show(ui, |ui| {
                                    egui::Grid::new("fit_model_equation_table")
                                        .striped(true)
                                        .show(ui, |ui| {
                                            ui.strong("Model");
                                            ui.strong("Formula");
                                            ui.end_row();

                                            for mut fit_model in FittingModelName::all_for_gui() {
                                                if fit_model.polynomial_degree().is_some() {
                                                    fit_model = FittingModelName::Polynom {
                                                        n: state.fit_model_polynomial_degree,
                                                    };
                                                }
                                                ui.label(fit_model.display_name());
                                                ui.monospace(fit_model.equation_str());
                                                ui.end_row();
                                            }
                                        });
                                });

                            ui.horizontal(|ui| {
                                let label = ui.label("Output column:");
                                let input =
                                    ui.text_edit_singleline(&mut state.fit_model_output_col);
                                let _ = input.labelled_by(label.id);
                            });

                            ui.horizontal(|ui| {
                                let label = ui.label("Tolerance:");
                                let input = ui.add(
                                    egui::DragValue::new(&mut state.fit_model_tolerance)
                                        .speed(1e-7)
                                        .range(1e-12..=1e-1),
                                );
                                let _ = input.labelled_by(label.id);
                                let label = ui.label("Max iter:");
                                let input = ui.add(
                                    egui::DragValue::new(&mut state.fit_model_max_iter)
                                        .speed(10.0)
                                        .range(1..=100_000),
                                );
                                let _ = input.labelled_by(label.id);
                            });

                            ui.horizontal(|ui| {
                                let label = ui.label("Initial guess:");
                                let input =
                                    ui.text_edit_singleline(&mut state.fit_model_initial_guess);
                                let _ = input.labelled_by(label.id);
                            });

                            ui.horizontal(|ui| {
                                ui.label("Status:");
                                ui.label(&state.fit_model_status);
                            });

                            ui.add_space(8.0);
                            if ui.button("Fit").on_hover_text("Requires an experiment and X/Y columns. Polynomial degree is required for polynomial models; initial guess is optional. Fits and stores a reusable model; it does not change any experiment or add a column.").clicked() {
                                let status = (|| -> Result<String, TGAGUIError> {
                                    if state.fit_model_experiment_id.is_empty()
                                        || state.fit_model_x_col.is_empty()
                                        || state.fit_model_y_col.is_empty()
                                    {
                                        return Err(TGAGUIError::BindingError(
                                            "Choose experiment, X and Y columns first.".to_string(),
                                        ));
                                    }

                                    let mut request = FitColumnRequest::new(
                                        state.fit_model_experiment_id.clone(),
                                        state.fit_model_x_col.clone(),
                                        state.fit_model_y_col.clone(),
                                        state.fit_model_model,
                                    )
                                    .with_tolerance(state.fit_model_tolerance)
                                    .with_max_iterations(state.fit_model_max_iter);

                                    if state.fit_training_range_enabled {
                                        request = request.with_training_range(
                                            state.fit_training_start,
                                            state.fit_training_end,
                                        );
                                    }

                                    if state.fit_gap_enabled {
                                        request = request.excluding_range(
                                            state.fit_gap_start,
                                            state.fit_gap_end,
                                        );
                                    }

                                    let output = state.fit_model_output_col.trim();
                                    if !output.is_empty() {
                                        request = request.with_output_col(output.to_string());
                                    }

                                    if let Some(initial_guess) =
                                        parse_fit_initial_guess(&state.fit_model_initial_guess)?
                                    {
                                        request = request.with_initial_guess(initial_guess);
                                    }

                                    let session = model.fit_column_for_evaluation(request)?;
                                    let result = session.result.clone();
                                    state.fit_model_result = Some(result.clone());
                                    state.fit_sessions.retain(|existing| {
                                        existing.result.y_col != result.y_col
                                            || existing.result.x_col != result.x_col
                                    });
                                    state.fit_sessions.push(session);
                                    state.fit_pending_batch = None;
                                    Ok(format!("Fit stored. R2={:.6}; no source data changed.", result.r2))
                                })();

                                state.fit_model_status = match status {
                                    Ok(msg) => msg,
                                    Err(err) => format!("Error: {err}"),
                                };
                                Self::publish_status(model, &state.fit_model_status);
                            }

                            if !state.fit_sessions.is_empty() {
                                ui.separator();
                                ui.strong("Stored fits");
                                egui::Grid::new("fit_model_session_results")
                                    .striped(true)
                                    .show(ui, |ui| {
                                        ui.strong("Y");
                                        ui.strong("Model");
                                        ui.strong("R2");
                                        ui.strong("Coefficients");
                                        ui.strong("Side RMSE");
                                        ui.end_row();
                                        for session in &state.fit_sessions {
                                            let result = &session.result;
                                            let coefficients = result.coefficients.iter()
                                                .map(|(name, value)| format!("{name}={value:.5e}"))
                                                .collect::<Vec<_>>().join(", ");
                                            let residuals = match (session.left_rmse, session.right_rmse) {
                                                (Some(left), Some(right)) => format!("{left:.3e} / {right:.3e}"),
                                                _ => "-".to_string(),
                                            };
                                            ui.label(&result.y_col);
                                            ui.label(result.kinetic_model.display_name());
                                            ui.label(format!("{:.6}", result.r2));
                                            ui.monospace(coefficients);
                                            ui.label(residuals);
                                            ui.end_row();
                                        }
                                    });
                            }

                            ui.separator();
                            ui.strong("Evaluation");
                            ui.horizontal(|ui| {
                                ui.checkbox(&mut state.fit_training_range_enabled, "Limit fit range");
                                if state.fit_training_range_enabled {
                                    let label = ui.label("Fit X start:");
                                    let response = ui.add(egui::DragValue::new(&mut state.fit_training_start).speed(0.1));
                                    let _ = response.labelled_by(label.id);
                                    let label = ui.label("end:");
                                    let response = ui.add(egui::DragValue::new(&mut state.fit_training_end).speed(0.1));
                                    let _ = response.labelled_by(label.id);
                                }
                            });
                            ui.horizontal(|ui| {
                                ui.checkbox(&mut state.fit_gap_enabled, "Reconstruct an internal gap");
                                if state.fit_gap_enabled {
                                    let label = ui.label("Gap start:");
                                    let response = ui.add(egui::DragValue::new(&mut state.fit_gap_start).speed(0.1));
                                    let _ = response.labelled_by(label.id);
                                    let label = ui.label("end:");
                                    let response = ui.add(egui::DragValue::new(&mut state.fit_gap_end).speed(0.1));
                                    let _ = response.labelled_by(label.id);
                                } else {
                                    let label = ui.label("Extrapolation X start:");
                                    let response = ui.add(egui::DragValue::new(&mut state.fit_evaluation_start).speed(0.1));
                                    let _ = response.labelled_by(label.id);
                                    let label = ui.label("end:");
                                    let response = ui.add(egui::DragValue::new(&mut state.fit_evaluation_end).speed(0.1));
                                    let _ = response.labelled_by(label.id);
                                }
                                let label = ui.label("Points:");
                                let response = ui.add(egui::DragValue::new(&mut state.fit_evaluation_points).range(1..=100_000));
                                let _ = response.labelled_by(label.id);
                            });
                            ui.horizontal(|ui| {
                                if ui.button("Evaluate fitted columns")
                                    .on_hover_text("Evaluates every stored fit on one shared X grid. The result remains a preview until explicitly added from Column Manager.")
                                    .clicked()
                                {
                                    let mode = if state.fit_gap_enabled {
                                        FitEvaluationMode::FillGap {
                                            start: state.fit_gap_start,
                                            end: state.fit_gap_end,
                                            missing_points: state.fit_evaluation_points,
                                        }
                                    } else {
                                        FitEvaluationMode::Extrapolate {
                                            start: state.fit_evaluation_start,
                                            end: state.fit_evaluation_end,
                                            points: state.fit_evaluation_points,
                                        }
                                    };
                                    match evaluate_fit_batch(&state.fit_sessions, mode) {
                                        Ok(batch) => {
                                            state.fit_reconstructed_experiment_id = format!(
                                                "{}_reconstructed", batch.source_experiment_id
                                            );
                                            state.fit_pending_batch = Some(batch);
                                            state.fit_model_status = "Evaluation ready. Review and commit it in Column Manager.".to_string();
                                        }
                                        Err(error) => state.fit_model_status = format!("Evaluation failed: {error}"),
                                    }
                                }
                                if ui.button("Clear fit sessions").clicked() {
                                    state.fit_sessions.clear();
                                    state.fit_model_result = None;
                                    state.fit_pending_batch = None;
                                }
                                ui.label(format!("{} fitted column(s)", state.fit_sessions.len()));
                            });
                        }
                        Err(err) => {
                            ui.label(format!("Cannot read columns: {err}"));
                        }
                    }
                });
            });

        Ok(())
    }

    //==============================================================================================
    // END OF KINETIC METHODS WINDOWS
    //==============================================================================================
    // COMBINED KINETICS ANALYSIS
    //===================================================================================================
    /// Render any open method windows.
    pub fn show_windows(
        ui: &mut egui::Ui,
        model: &mut PlotModel,
        state: &mut KineticMethodsWindowState,
    ) -> Result<(), TGAGUIError> {
        // Separate helper functions keep each window small and focused.
        Self::show_isoconversional_window(ui, model, state)?;
        Self::show_kissinger_window(ui, model, state)?;
        Self::show_combined_kinetics_window(ui, model, state)?;
        Self::show_sublimation_window(ui, model, state)?;
        Self::show_fit_model_window(ui, model, state)?;

        Ok(())
    }
}

fn parse_fit_initial_guess(raw: &str) -> Result<Option<Vec<f64>>, TGAGUIError> {
    let raw = raw.trim();
    if raw.is_empty() {
        return Ok(None);
    }

    let mut values = Vec::new();
    for token in raw
        .split(|ch: char| ch == ',' || ch == ';' || ch.is_whitespace())
        .filter(|token| !token.trim().is_empty())
    {
        let value = token.trim().parse::<f64>().map_err(|err| {
            TGAGUIError::BindingError(format!(
                "Cannot parse initial guess value '{}': {}",
                token, err
            ))
        })?;
        values.push(value);
    }

    Ok(Some(values))
}