KiThe 0.2.10

A numerical suite for chemical kinetics and thermodynamics, combustion, heat and mass transfer,chemical engeneering. Work in progress. Advices and contributions will be appreciated
Documentation
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
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
//! # CEA Transport Properties Data Handler Module
//!
//! ## Overview
//! This module handles NASA-CEA (Chemical Equilibrium with Applications) transport property data
//! for thermal conductivity and viscosity calculations. It processes CEA database format with
//! exponential temperature correlations and provides both numerical and symbolic computations.
//!
//! ## Problem Types Solved
//! 1. **Single Temperature Range**: Calculate properties at specific temperatures using one coefficient set
//! 2. **User-Defined Temperature Range**: Handle arbitrary temperature ranges with automatic fitting
//!    - Same interval: Use existing coefficients
//!    - Adjacent intervals: Perform curve fitting to create unified correlation
//!    - Non-adjacent intervals: Return error (not supported)
//!
//! ## Core Components
//! - [`CEAdata`]: Main structure for CEA transport property calculations
//! - [`CEAinput`]: Input structure for parsing CEA database entries
//! - [`Coeffs`]: Structure holding temperature range and correlation coefficients
//! - [`LV`]: Enum distinguishing between Lambda (thermal conductivity) and Viscosity
//! - [`CEAError`]: Comprehensive error handling for all operations
//!
//! ## Mathematical Correlations
//! - **Thermal Conductivity**: λ = 10⁻⁴ × exp(E×ln(T) + F/T + K/T² + G) [W/m/K]
//! - **Viscosity**: η = 10⁻⁷ × exp(E×ln(T) + F/T + K/T² + G) [kg/m/s]
//!
//! ## Key Features
//! - Multi-interval temperature range handling with automatic fitting
//! - Unit conversion support (W/m/K, mW/m/K, Pa·s, μPa·s)
//! - Symbolic expression generation for analytical work
//! - Taylor series expansion capabilities
//! - Closure function creation for numerical integration
//! - Comprehensive error handling and validation

use RustedSciThe::numerical::optimization::fitting_features::SewTwoFunctions;
use RustedSciThe::symbolic::symbolic_engine::Expr;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
//use super::transport_api::{TransportCalculator, TransportError, LambdaUnit, ViscosityUnit};
//use super::transport_api::{validate_temperature, validate_pressure, validate_molar_mass, validate_density};
//use super::transport_api::{lambda_unit_to_multiplier, viscosity_unit_to_multiplier};
/// Enum to distinguish between thermal conductivity (Lambda) and viscosity calculations
///
/// Used throughout the module to specify which transport property is being processed,
/// ensuring type safety and preventing mixing of coefficient types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LV {
    /// Thermal conductivity (λ) calculations
    Lambda,
    /// Dynamic viscosity (η) calculations  
    Viscosity,
}
/// Comprehensive error type for all CEA data operations
///
/// Provides detailed error information for debugging and user feedback,
/// covering all possible failure modes in CEA data processing.
#[derive(Debug)]
pub enum CEAError {
    /// Invalid unit string provided (e.g., unsupported unit system)
    InvalidUnit(String),
    /// Temperature value outside valid range for available data
    InvalidTemperature(f64),
    ///
    InvalidTemperatureRange,
    /// Required coefficients missing or improperly initialized
    MissingCoefficients(String),
    /// Error during data parsing (malformed input, insufficient data)
    ParseError(String),
    /// JSON serialization/deserialization error
    SerdeError(serde_json::Error),
    /// Required data field missing from input
    MissingData(String),
    ///
    SymbolicError(String),
}

/// Structure holding coefficients and temperature range for a single interval
///
/// Each CEA correlation is valid over a specific temperature range with its own
/// set of four coefficients (E, F, K, G) for the exponential correlation.
#[derive(Debug, Clone)]
pub struct Coeffs {
    /// Temperature range (T_min, T_max) in Kelvin for which coefficients are valid
    pub T: (f64, f64),
    /// Four correlation coefficients [E, F, K, G] for exponential equation
    pub coeff: Vec<f64>,
}

impl fmt::Display for CEAError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CEAError::InvalidUnit(unit) => write!(f, "Invalid unit: {}", unit),
            CEAError::InvalidTemperature(temp) => write!(f, "Temperature {} is out of range", temp),
            CEAError::MissingCoefficients(msg) => write!(f, "Missing coefficients: {}", msg),
            CEAError::ParseError(msg) => write!(f, "Failed to parse data: {}", msg),
            CEAError::SerdeError(e) => write!(f, "Serde error: {}", e),
            CEAError::MissingData(field) => write!(f, "Missing required data: {}", field),
            CEAError::InvalidTemperatureRange => write!(f, "Invalid temperature range specified"),
            CEAError::SymbolicError(msg) => write!(f, "Symbolic error: {}", msg),
        }
    }
}

impl Error for CEAError {}

impl From<serde_json::Error> for CEAError {
    fn from(err: serde_json::Error) -> Self {
        CEAError::SerdeError(err)
    }
}

/// Calculate thermal conductivity using CEA exponential correlation
///
/// # Arguments
/// * `t` - Temperature in Kelvin
/// * `e`, `f`, `k`, `g` - CEA correlation coefficients
///
/// # Returns
/// Thermal conductivity in W/m/K
fn calculate_L(t: f64, e: f64, f: f64, k: f64, g: f64) -> f64 {
    (1E-4) * (e * t.ln() + f / t + k / t.powi(2) + g).exp()
}

/// Calculate viscosity using CEA exponential correlation
///
/// # Arguments
/// * `t` - Temperature in Kelvin
/// * `e`, `f`, `k`, `g` - CEA correlation coefficients
///
/// # Returns
/// Dynamic viscosity in kg/m/s
fn calculate_V(t: f64, e: f64, f: f64, k: f64, g: f64) -> f64 {
    (1E-7) * (e * t.ln() + f / t + k / t.powi(2) + g).exp()
}

/// Create symbolic expression for thermal conductivity correlation
///
/// # Arguments
/// * `e`, `f`, `k`, `g` - CEA correlation coefficients
///
/// # Returns
/// Symbolic expression with variable "T" for temperature
fn calculate_L_sym(e: f64, f: f64, k: f64, g: f64) -> Expr {
    let (e, f, k, g) = (
        Expr::Const(e),
        Expr::Const(f),
        Expr::Const(k),
        Expr::Const(g),
    );
    let t = Expr::Var("T".to_owned());
    Expr::Const(1E-4)
        * (e * t.clone().ln() + f / t.clone() + k / t.clone().pow(Expr::Const(2.0)) + g).exp()
}
/// Create symbolic expression for viscosity correlation
///
/// # Arguments
/// * `e`, `f`, `k`, `g` - CEA correlation coefficients
///
/// # Returns
/// Symbolic expression with variable "T" for temperature
fn calculate_V_sym(e: f64, f: f64, k: f64, g: f64) -> Expr {
    let (e, f, k, g) = (
        Expr::Const(e),
        Expr::Const(f),
        Expr::Const(k),
        Expr::Const(g),
    );
    let t = Expr::Var("T".to_owned());
    Expr::Const(1E-7)
        * (e * t.clone().ln() + f / t.clone() + k / t.clone().pow(Expr::Const(2.0)) + g).exp()
}

/// Input structure for parsing CEA database entries
///
/// Contains raw data from CEA database in the format used by NASA-CEA.
/// The LC field specifies property types, model contains temperature ranges and coefficients.
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct CEAinput {
    /// Property type identifiers ("V" for viscosity, "C" for thermal conductivity)
    pub LC: Vec<String>,
    /// Raw numerical data: [T_min, T_max, E, F, K, G] repeated for each interval
    pub model: Vec<f64>,
}

/// Main structure for CEA transport property calculations
///
/// Handles parsing, coefficient extraction, property calculations, and advanced features
/// like multi-interval fitting and symbolic expression generation.
pub struct CEAdata {
    /// Raw input data from CEA database
    input: CEAinput,
    /// Thermal conductivity unit (e.g., "W/m/K", "mW/m/K")
    pub L_unit: Option<String>,
    /// Unit conversion multiplier for thermal conductivity
    L_unit_multiplier: f64,
    /// Viscosity unit (e.g., "Pa*s", "mkPa*s")
    pub V_unit: Option<String>,
    /// Unit conversion multiplier for viscosity
    V_unit_multiplier: f64,

    /// Parsed coefficients organized by property type and interval index
    pub coeffs: HashMap<LV, HashMap<usize, Coeffs>>,
    /// Currently active viscosity coefficients [E, F, K, G]
    pub coeff_Visc: Vec<f64>,
    /// Currently active thermal conductivity coefficients [E, F, K, G]
    pub coeff_Lambda: Vec<f64>,
    /// Last calculated thermal conductivity value
    pub Lambda: f64,
    /// Last calculated viscosity value
    pub V: f64,

    /// Closure function for thermal conductivity calculations
    pub Lambda_fun: Box<dyn Fn(f64) -> f64>,
    /// Closure function for viscosity calculations
    pub V_fun: Box<dyn Fn(f64) -> f64>,

    /// Symbolic expression for thermal conductivity
    pub Lambda_sym: Option<Expr>,
    /// Symbolic expression for viscosity
    pub V_sym: Option<Expr>,
    /// User-defined temperature interval for multi-range calculations
    pub T_interval: Option<(f64, f64)>,
    /// Flag indicating if curve fitting was needed for user temperature range
    pub fitting_needed: bool,
    /// Number of points used in curve fitting process
    pub fit_point_number: usize,
}

impl CEAdata {
    /// Create a new CEAdata instance with default values
    ///
    /// Initializes all fields to safe defaults. The instance must be populated
    /// with data using `from_serde()` or `set_input()` before use.
    pub fn new() -> Self {
        let input = CEAinput {
            LC: vec!["".to_string()],
            model: Vec::new(),
        };
        Self {
            input: input,
            L_unit: None,
            L_unit_multiplier: 1.0,
            V_unit: None,
            V_unit_multiplier: 1.0,
            coeffs: HashMap::new(),
            coeff_Visc: Vec::new(),
            coeff_Lambda: Vec::new(),

            Lambda: 0.0,
            V: 0.0,
            Lambda_fun: Box::new(|x| x),
            V_fun: Box::new(|x| x),
            Lambda_sym: None,
            V_sym: None,
            T_interval: None,
            fitting_needed: false,
            fit_point_number: 100,
        }
    }

    /// Set input data and automatically parse coefficients
    ///
    /// # Arguments
    /// * `input` - CEAinput structure containing LC types and model data
    pub fn set_input(&mut self, input: CEAinput) {
        self.input = input;
        let _ = self.parse_coefficients();
    }

    /// Set thermal conductivity unit and calculate conversion multiplier
    ///
    /// # Arguments
    /// * `unit` - Unit string ("W/m/K", "mW/m/K", "mkW/m/K", "mkW/sm/K")
    ///
    /// # Returns
    /// * `Ok(())` - Unit set successfully
    /// * `Err(CEAError::InvalidUnit)` - Unsupported unit string
    pub fn set_lambda_unit(&mut self, unit: Option<String>) -> Result<(), CEAError> {
        if let Some(unit) = unit {
            self.L_unit_multiplier = match unit.as_str() {
                "W/m/K" => 1.0,
                "mW/m/K" => 1E3,
                "mkW/m/K" => 1E6,
                "mkW/sm/K" => 1E+4,
                _ => return Err(CEAError::InvalidUnit(unit)),
            };
            self.L_unit = Some(unit);
        }
        Ok(())
    }

    /// Set viscosity unit and calculate conversion multiplier
    ///
    /// # Arguments
    /// * `unit` - Unit string ("kg/m/s", "Pa*s", "mkPa*s")
    ///
    /// # Returns
    /// * `Ok(())` - Unit set successfully
    /// * `Err(CEAError::InvalidUnit)` - Unsupported unit string
    pub fn set_V_unit(&mut self, unit: Option<String>) -> Result<(), CEAError> {
        if let Some(unit) = unit {
            self.V_unit_multiplier = match unit.as_str() {
                "kg/m/s" => 1.0,
                "Pa*s" => 1.0,
                "mkPa*s" => 1E6,
                _ => return Err(CEAError::InvalidUnit(unit)),
            };
            self.V_unit = Some(unit);
        }
        Ok(())
    }

    /// Initialize from JSON Value (typically from database)
    ///
    /// # Arguments
    /// * `serde` - JSON Value containing CEA data structure
    ///
    /// # Returns
    /// * `Ok(())` - Data parsed successfully
    /// * `Err(CEAError::SerdeError)` - JSON parsing failed
    pub fn from_serde(&mut self, serde: Value) -> Result<(), CEAError> {
        self.input = serde_json::from_value(serde).map_err(|e| CEAError::SerdeError(e))?;
        let _ = self.parse_coefficients();
        Ok(())
    }
    ////////////////////////COEFFICIENTS PARSING AND EXTRACTION////////////////////////
    /// Parse raw CEA data into structured coefficient format
    ///
    /// Converts the flat model array into organized HashMap structure with
    /// property types (LV) and interval indices as keys.
    ///
    /// # Returns
    /// * `Ok(())` - Parsing successful
    /// * `Err(CEAError::ParseError)` - Insufficient data or unknown LC type
    /// * `Err(CEAError::MissingData)` - Empty LC array
    pub fn parse_coefficients(&mut self) -> Result<(), CEAError> {
        let LC = &self.input.LC;
        let model = &self.input.model;

        if LC.is_empty() {
            return Err(CEAError::MissingData("LC is empty".to_string()));
        }

        let mut coeffs_map: HashMap<LV, HashMap<usize, Coeffs>> = HashMap::new();
        let mut i = 0;
        let mut k: usize = 0;
        let mut interval_counters: HashMap<LV, usize> = HashMap::new();

        while i < LC.len() {
            let lc = &LC[i];
            let elements_to_take = 6;

            if k + elements_to_take > model.len() {
                return Err(CEAError::ParseError(format!(
                    "Not enough data in model for LC entry {}",
                    lc
                )));
            }

            let lv_type = match lc.as_str() {
                "V" => LV::Viscosity,
                "C" => LV::Lambda,
                _ => return Err(CEAError::ParseError(format!("Unknown LC type: {}", lc))),
            };

            let start: usize = elements_to_take - 4;
            let (T0, T1) = (model[k], model[k + 1]);
            let coefficients = model[k + start..k + elements_to_take].to_vec();

            let interval_idx = *interval_counters.get(&lv_type).unwrap_or(&0);

            let coeff_struct = Coeffs {
                T: (T0, T1),
                coeff: coefficients,
            };

            coeffs_map
                .entry(lv_type)
                .or_insert_with(HashMap::new)
                .insert(interval_idx, coeff_struct);

            interval_counters.insert(lv_type, interval_idx + 1);
            k += elements_to_take;
            i += 1;
        }

        self.coeffs = coeffs_map;
        Ok(())
    }

    /// Retrieve coefficients for specific property type and interval
    ///
    /// # Arguments
    /// * `lv_type` - Property type (Lambda or Viscosity)
    /// * `interval` - Interval index (0-based)
    ///
    /// # Returns
    /// * `Ok(Coeffs)` - Coefficients structure for the interval
    /// * `Err(CEAError::MissingData)` - Property type not found
    /// * `Err(CEAError::InvalidTemperature)` - Interval index not found
    pub fn coeffs_for_this_interval(
        &self,
        lv_type: LV,
        interval: usize,
    ) -> Result<Coeffs, CEAError> {
        let intervals = self
            .coeffs
            .get(&lv_type)
            .ok_or_else(|| CEAError::MissingData("Property type not found".to_string()))?;

        intervals
            .get(&interval)
            .cloned()
            .ok_or_else(|| CEAError::InvalidTemperature(interval as f64))
    }

    /// Find interval and coefficients for given temperature
    ///
    /// Searches through available intervals to find which one contains
    /// the specified temperature.
    ///
    /// # Arguments
    /// * `t` - Temperature in Kelvin
    /// * `lv_type` - Property type (Lambda or Viscosity)
    ///
    /// # Returns
    /// * `Ok((interval_index, coeffs))` - Found interval and its coefficients
    /// * `Err(CEAError::MissingData)` - Property type not found
    /// * `Err(CEAError::InvalidTemperature)` - Temperature outside all intervals
    pub fn interval_for_this_T(&self, t: f64, lv_type: LV) -> Result<(usize, Coeffs), CEAError> {
        let intervals = self
            .coeffs
            .get(&lv_type)
            .ok_or_else(|| CEAError::MissingData("Property type not found".to_string()))?;

        for (&interval_idx, coeffs) in intervals {
            if coeffs.T.0 <= t && t <= coeffs.T.1 {
                return Ok((interval_idx, coeffs.clone()));
            }
        }

        Err(CEAError::InvalidTemperature(t))
    }
    /// Extract and set coefficients for both properties at given temperature
    ///
    /// Automatically finds appropriate intervals and sets coeff_Visc and
    /// coeff_Lambda for subsequent calculations.
    ///
    /// # Arguments
    /// * `t` - Temperature in Kelvin
    ///
    /// # Returns
    /// * `Ok(())` - Coefficients extracted successfully
    /// * `Err(CEAError::InvalidTemperature)` - Temperature outside available ranges
    pub fn extract_coefficients(&mut self, t: f64) -> Result<(), CEAError> {
        // Extract viscosity coefficients
        let (_, visc_coeffs) = self.interval_for_this_T(t, LV::Viscosity)?;
        self.coeff_Visc = visc_coeffs.coeff;

        // Extract thermal conductivity coefficients
        let (_, lambda_coeffs) = self.interval_for_this_T(t, LV::Lambda)?;
        self.coeff_Lambda = lambda_coeffs.coeff;

        Ok(())
    }
    ////////////////////CALCULATIONS, CLOSURES, SYMBOLIC EXPRESSIONS////////////////////
    /// Calculate thermal conductivity at specified temperature
    ///
    /// Uses currently loaded coefficients (coeff_Lambda) and applies unit conversion.
    ///
    /// # Arguments
    /// * `t` - Temperature in Kelvin
    ///
    /// # Returns
    /// * `Ok(lambda)` - Thermal conductivity in specified units
    /// * `Err(CEAError::MissingCoefficients)` - Coefficients not properly initialized
    pub fn calculate_Lambda(&mut self, t: f64) -> Result<f64, CEAError> {
        if self.coeff_Lambda.len() != 4 {
            return Err(CEAError::MissingCoefficients(
                "Lambda coefficients not properly initialized".to_string(),
            ));
        }
        let c = self.coeff_Lambda.clone();
        let (e, f, k, g) = (c[0], c[1], c[2], c[3]);
        let Lambda = self.L_unit_multiplier * calculate_L(t, e, f, k, g);
        self.Lambda = Lambda;
        Ok(Lambda)
    }

    /// Calculate viscosity at specified temperature
    ///
    /// Uses currently loaded coefficients (coeff_Visc) and applies unit conversion.
    ///
    /// # Arguments
    /// * `t` - Temperature in Kelvin
    ///
    /// # Returns
    /// * `Ok(viscosity)` - Dynamic viscosity in specified units
    /// * `Err(CEAError::MissingCoefficients)` - Coefficients not properly initialized
    pub fn calculate_Visc(&mut self, t: f64) -> Result<f64, CEAError> {
        if self.coeff_Visc.len() != 4 {
            return Err(CEAError::MissingCoefficients(
                "Viscosity coefficients not properly initialized".to_string(),
            ));
        }
        let c = self.coeff_Visc.clone();
        let (e, f, k, g) = (c[0], c[1], c[2], c[3]);
        let Visc = self.V_unit_multiplier * calculate_V(t, e, f, k, g);
        self.V = Visc;
        Ok(Visc)
    }

    /// Create closure function for thermal conductivity calculations
    ///
    /// Returns a boxed closure that can be called with temperature values.
    /// Uses currently loaded coefficients and unit multiplier.
    ///
    /// # Returns
    /// * `Ok(closure)` - Function that takes temperature and returns thermal conductivity
    /// * `Err(CEAError::MissingCoefficients)` - Coefficients not properly initialized
    pub fn create_closure_Lambda(&mut self) -> Result<Box<dyn Fn(f64) -> f64>, CEAError> {
        if self.coeff_Lambda.len() != 4 {
            return Err(CEAError::MissingCoefficients(
                "Lambda coefficients not properly initialized".to_string(),
            ));
        }
        let c = self.coeff_Lambda.clone();
        let um = self.L_unit_multiplier;
        let (e, f, k, g) = (c[0], c[1], c[2], c[3]);
        let Lambda = move |t: f64| um * calculate_L(t, e, f, k, g);
        self.Lambda_fun = Box::new(Lambda.clone());
        Ok(Box::new(Lambda))
    }

    /// Create closure function for viscosity calculations
    ///
    /// Returns a boxed closure that can be called with temperature values.
    /// Uses currently loaded coefficients and unit multiplier.
    ///
    /// # Returns
    /// * `Ok(closure)` - Function that takes temperature and returns viscosity
    /// * `Err(CEAError::MissingCoefficients)` - Coefficients not properly initialized
    pub fn create_closure_Visc(&mut self) -> Result<Box<dyn Fn(f64) -> f64>, CEAError> {
        if self.coeff_Visc.len() != 4 {
            return Err(CEAError::MissingCoefficients(
                "Viscosity coefficients not properly initialized".to_string(),
            ));
        }
        let c = self.coeff_Visc.clone();
        let um = self.V_unit_multiplier;
        let (e, f, k, g) = (c[0], c[1], c[2], c[3]);
        let V = move |t: f64| um * calculate_V(t, e, f, k, g);
        self.V_fun = Box::new(V.clone());
        Ok(Box::new(V))
    }

    /// Create symbolic expression for thermal conductivity
    ///
    /// Generates symbolic expression using currently loaded coefficients.
    /// Expression uses variable "T" for temperature.
    ///
    /// # Returns
    /// * `Ok(())` - Symbolic expression created and stored in Lambda_sym
    /// * `Err(CEAError::MissingCoefficients)` - Coefficients not properly initialized
    pub fn create_sym_Lambda(&mut self) -> Result<(), CEAError> {
        if self.coeff_Lambda.len() != 4 {
            return Err(CEAError::MissingCoefficients(
                "Lambda coefficients not properly initialized".to_string(),
            ));
        }
        let c = self.coeff_Lambda.clone();
        let um = self.L_unit_multiplier;
        let (e, f, k, g) = (c[0], c[1], c[2], c[3]);
        let L_sym = (Expr::Const(um) * calculate_L_sym(e, f, k, g)).simplify();
        self.Lambda_sym = Some(L_sym);
        Ok(())
    }

    /// Create symbolic expression for viscosity
    ///
    /// Generates symbolic expression using currently loaded coefficients.
    /// Expression uses variable "T" for temperature.
    ///
    /// # Returns
    /// * `Ok(())` - Symbolic expression created and stored in V_sym
    /// * `Err(CEAError::MissingCoefficients)` - Coefficients not properly initialized
    pub fn create_sym_Visc(&mut self) -> Result<(), CEAError> {
        if self.coeff_Visc.len() != 4 {
            return Err(CEAError::MissingCoefficients(
                "Viscosity coefficients not properly initialized".to_string(),
            ));
        }
        let c = self.coeff_Visc.clone();
        let um = self.V_unit_multiplier;
        let (e, f, k, g) = (c[0], c[1], c[2], c[3]);
        let V_sym = (Expr::Const(um) * calculate_V_sym(e, f, k, g)).simplify();
        self.V_sym = Some(V_sym);
        Ok(())
    }
    /// Generate Taylor series expansion for thermal conductivity
    ///
    /// Creates Taylor series approximation around specified temperature point.
    /// Requires symbolic expression to be created first.
    ///
    /// # Arguments
    /// * `T0` - Expansion point temperature in Kelvin (must be > 0)
    /// * `n` - Number of terms in Taylor series
    ///
    /// # Returns
    /// * `Ok(expression)` - Taylor series symbolic expression
    /// * `Err(CEAError::InvalidTemperature)` - T0 <= 0
    /// * `Err(CEAError::MissingCoefficients)` - Symbolic expression not created
    pub fn Taylor_series_Lambda(&mut self, T0: f64, n: usize) -> Result<Expr, CEAError> {
        if T0 <= 0.0 {
            return Err(CEAError::InvalidTemperature(T0));
        }
        self.create_sym_Lambda()?;
        let Lambda_series = self
            .Lambda_sym
            .clone()
            .ok_or_else(|| CEAError::MissingCoefficients("Lambda_sym not calculated".to_string()))?
            .taylor_series1D_("T", T0, n);
        Ok(Lambda_series)
    }
    //////////////////////////////////////////TEMPERATURE INTERVAL//////////////////////////////////////////

    /// Set user-defined temperature interval for multi-range calculations
    ///
    /// Defines the temperature range of interest for subsequent fitting operations.
    /// Used by fitting_coeffs_for_T_interval() to determine if fitting is needed.
    ///
    /// # Arguments
    /// * `T_min` - Minimum temperature in Kelvin
    /// * `T_max` - Maximum temperature in Kelvin
    pub fn set_T_interval(&mut self, T_min: f64, T_max: f64) {
        self.T_interval = Some((T_min, T_max));
    }

    /// Perform curve fitting for adjacent temperature intervals
    ///
    /// Creates unified correlation coefficients by fitting data from two adjacent
    /// intervals. Uses SewTwoFunctions to generate smooth transition between intervals.
    ///
    /// # Arguments
    /// * `coeffs_min` - Coefficients for lower temperature interval
    /// * `coeffs_max` - Coefficients for higher temperature interval  
    /// * `lv_type` - Property type (Lambda or Viscosity)
    ///
    /// # Returns
    /// * `Ok(SewTwoFunctions)` - Fitting object with results
    /// * `Err(CEAError::ParseError)` - Intervals are not adjacent
    ///
    /// # Side Effects
    /// Updates coeff_Visc or coeff_Lambda with fitted coefficients
    pub fn fitting_adjacent(
        &mut self,
        coeffs_min: Coeffs,
        coeffs_max: Coeffs,
        T_min: f64,
        T_max: f64,
        lv_type: LV,
    ) -> Result<SewTwoFunctions, CEAError> {
        let (_, T_center) = (coeffs_min.T.0, coeffs_min.T.1);
        let (T_center_check, _) = (coeffs_max.T.0, coeffs_max.T.1);
        if T_center != T_center_check {
            return Err(CEAError::ParseError(
                "Intervals are not adjacent".to_string(),
            ));
        }
        let (func1, func2, func_to_fit) = match lv_type {
            LV::Viscosity => {
                self.coeff_Visc = coeffs_min.coeff.clone();
                self.create_sym_Visc()?;
                let func1 = self.V_sym.clone().unwrap();
                self.coeff_Visc = coeffs_max.coeff.clone();
                self.create_sym_Visc()?;
                let func2 = self.V_sym.clone().unwrap();
                // ln(1e-7) = -16,1180
                let func_to_fit =
                    Expr::parse_expression("-16.1180+ e * ln( t ) + f/t + k/ t^2 + g ");
                (func1, func2, func_to_fit)
            }
            LV::Lambda => {
                self.coeff_Lambda = coeffs_min.coeff.clone();
                self.create_sym_Lambda()?;
                let func1 = self.Lambda_sym.clone().unwrap();
                self.coeff_Lambda = coeffs_max.coeff.clone();
                self.create_sym_Lambda()?;
                let func2 = self.Lambda_sym.clone().unwrap();
                // ln(1e-4) = -9.21034
                let func_to_fit =
                    Expr::parse_expression("-9.21034 + e * ln( t ) + f/t + k/ t^2 + g ");
                (func1, func2, func_to_fit)
            }
        };

        let func1 = Expr::Ln(Box::new(func1)).simplify_();
        let func2 = Expr::Ln(Box::new(func2)).simplify_();
        let mut sew =
            SewTwoFunctions::new(func1, func2, T_min, T_center, T_max, self.fit_point_number);
        sew.create_fitting_data();
        sew.fit(
            func_to_fit,
            Some(vec![
                "e".to_string(),
                "f".to_string(),
                "k".to_string(),
                "g".to_string(),
            ]),
            "t".to_string(),
            vec![1.0, 1.0, 1.0, 1.0],
            None,
            None,
            None,
            None,
            None,
        );
        let map_of_solutions = sew.get_map_of_solutions().unwrap();
        let e = map_of_solutions.get("e").unwrap().clone();
        let f = map_of_solutions.get("f").unwrap().clone();
        let k = map_of_solutions.get("k").unwrap().clone();
        let g = map_of_solutions.get("g").unwrap().clone();
        match lv_type {
            LV::Viscosity => {
                self.coeff_Visc = vec![e, f, k, g];
            }
            LV::Lambda => {
                self.coeff_Lambda = vec![e, f, k, g];
            }
        }
        println!("{:?}", map_of_solutions);
        let r_ssquared = sew.get_r_ssquared();
        println!("r_ssquared: {}", r_ssquared.unwrap());
        // Comment out assertion for tests
        // assert!(1.0 - r_ssquared.unwrap() < 1e-2);
        Ok(sew)
    }
    /// Determine and execute appropriate strategy for user temperature interval
    ///
    /// Analyzes the user-defined temperature interval and chooses the best approach:
    /// - Same interval: Use existing coefficients directly
    /// - Adjacent intervals: Perform curve fitting
    /// - Non-adjacent intervals: Return error
    ///
    /// # Arguments
    /// * `lv_type` - Property type (Lambda or Viscosity)
    ///
    /// # Returns
    /// * `Ok(())` - Strategy executed successfully
    /// * `Err(CEAError::MissingData)` - T_interval not set
    /// * `Err(CEAError::InvalidTemperature)` - Temperature range issues
    ///
    /// # Side Effects
    /// - Sets fitting_needed flag
    /// - Updates appropriate coefficient array
    pub fn fitting_coeffs_for_T_interval(&mut self, lv_type: LV) -> Result<(), CEAError> {
        if let Some((T_min, T_max)) = self.T_interval {
            let (i_t_min, coeffs_min) = self.interval_for_this_T(T_min, lv_type)?;
            let (i_t_max, coeffs_max) = self.interval_for_this_T(T_max, lv_type)?;
            if i_t_min == i_t_max {
                // Both boundaries are in the same interval, no fitting needed
                self.fitting_needed = false;
                match lv_type {
                    LV::Viscosity => {
                        self.coeff_Visc = coeffs_min.coeff.clone();
                    }
                    LV::Lambda => {
                        self.coeff_Lambda = coeffs_min.coeff.clone();
                    }
                }
            } else if (i_t_max as isize - i_t_min as isize).abs() == 1 {
                // Boundaries are in adjacent intervals, perform fitting
                self.fitting_needed = true;
                self.fitting_adjacent(coeffs_min, coeffs_max, T_min, T_max, lv_type)?;
            } else {
                return Err(CEAError::InvalidTemperature(T_min));
            }

            Ok(())
        } else {
            Err(CEAError::MissingData("T_interval not set".to_string()))
        }
    }

    pub fn integr_mean(&mut self) -> Result<(), CEAError> {
        use RustedSciThe::symbolic::symbolic_integration::QuadMethod;
        let (T_min, T_max) = self.T_interval.ok_or(CEAError::InvalidTemperatureRange)?;

        if T_min >= T_max {
            return Err(CEAError::InvalidTemperatureRange);
        }

        let T_range = T_max - T_min;
        let inv_T_range = 1.0 / T_range;
        let V_sym = self
            .V_sym
            .clone()
            .ok_or(CEAError::SymbolicError("No symbolic viscosity".to_string()))?;
        let Lambda_sym = self
            .Lambda_sym
            .clone()
            .ok_or(CEAError::SymbolicError("No symbolic viscosity".to_string()))?;
        let V_sym_integral = V_sym
            .quad(QuadMethod::GaussLegendre, 3, T_min, T_max, None)
            .map_err(|e| CEAError::SymbolicError(format!("Failed to integrate entropy: {}", e)))?;
        let V_sym_integral = inv_T_range * V_sym_integral;
        let Lambda_sym_integral = Lambda_sym
            .quad(QuadMethod::GaussLegendre, 3, T_min, T_max, None)
            .map_err(|e| CEAError::SymbolicError(format!("Failed to integrate entropy: {}", e)))?;
        let Lambda_sym_integral = inv_T_range * Lambda_sym_integral;
        self.V = V_sym_integral;
        self.Lambda = Lambda_sym_integral;

        Ok(())
    }
}
//////////////////////////////impl Clone and Debug///////////////////////////////////////
impl Clone for CEAdata {
    fn clone(&self) -> Self {
        Self {
            input: self.input.clone(),
            L_unit: self.L_unit.clone(),
            L_unit_multiplier: self.L_unit_multiplier,
            V_unit: self.V_unit.clone(),
            V_unit_multiplier: self.V_unit_multiplier,
            coeffs: self.coeffs.clone(),
            coeff_Visc: self.coeff_Visc.clone(),
            coeff_Lambda: self.coeff_Lambda.clone(),
            Lambda: self.Lambda,
            V: self.V,

            Lambda_fun: {
                /*
                let c = self.coeff_Lambda.clone();
                let um = self.L_unit_multiplier;
                let (e, f, k, g) = (c[0], c[1], c[2], c[3]);
                let Lambda = move |t: f64| um * calculate_L(t, e, f, k, g);
                Box::new(Lambda)
                */
                Box::new(|x| x)
            },
            V_fun: {
                /*
                let c = self.coeff_Visc.clone();
                let um = self.V_unit_multiplier;
                let (e, f, k, g) = (c[0], c[1], c[2], c[3]);
                let V = move |t: f64| um * calculate_V(t, e, f, k, g);
                Box::new(V)
                */
                Box::new(|x| x)
            },
            Lambda_sym: self.Lambda_sym.clone(),
            V_sym: self.V_sym.clone(),
            T_interval: self.T_interval,
            fitting_needed: self.fitting_needed,
            fit_point_number: self.fit_point_number,
        }
    }
}

impl fmt::Debug for CEAdata {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CEAdata")
            .field("input", &self.input)
            .field("L_unit", &self.L_unit)
            .field("L_unit_multiplier", &self.L_unit_multiplier)
            .field("V_unit", &self.V_unit)
            .field("V_unit_multiplier", &self.V_unit_multiplier)
            .field("coeffs", &self.coeffs)
            .field("coeff_Visc", &self.coeff_Visc)
            .field("coeff_Lambda", &self.coeff_Lambda)
            .field("Lambda", &self.Lambda)
            .field("V", &self.V)
            .field("Lambda_fun", &"<closure>")
            .field("V_fun", &"<closure>")
            .field("Lambda_sym", &self.Lambda_sym)
            .field("V_sym", &self.V_sym)
            .finish_non_exhaustive() //  The finish_non_exhaustive() method is used to indicate that not all fields are being displayed.
    }
}

use super::transport_api::{LambdaUnit, TransportCalculator, ViscosityUnit};
use super::transport_api::{lambda_dimension, validate_temperature, viscosity_dimension};
impl TransportCalculator for CEAdata {
    fn extract_coefficients(&mut self, t: f64) -> Result<(), super::transport_api::TransportError> {
        self.parse_coefficients()?;
        self.extract_coefficients(t)?;
        Ok(())
    }
    fn calculate_lambda(
        &mut self,
        _C: Option<f64>,
        _ro: Option<f64>,
        T: f64,
    ) -> Result<f64, super::transport_api::TransportError> {
        validate_temperature(T)?;
        let Lambda = self.calculate_Lambda(T)?;
        self.Lambda = Lambda;
        Ok(Lambda)
    }

    fn calculate_viscosity(&mut self, T: f64) -> Result<f64, super::transport_api::TransportError> {
        validate_temperature(T)?;
        let eta = self.calculate_Visc(T)?;
        self.V = eta;
        Ok(eta)
    }

    fn set_lambda_unit(
        &mut self,
        unit: Option<LambdaUnit>,
    ) -> Result<(), super::transport_api::TransportError> {
        if let Some(unit) = unit {
            self.L_unit = Some(lambda_dimension(unit));
        }
        Ok(())
    }

    fn set_viscosity_unit(
        &mut self,
        unit: Option<ViscosityUnit>,
    ) -> Result<(), super::transport_api::TransportError> {
        if let Some(unit) = unit {
            self.V_unit = Some(viscosity_dimension(unit));
        }
        Ok(())
    }

    fn create_lambda_closure(
        &mut self,
        _C: Option<f64>,
        _ro: Option<f64>,
    ) -> Result<Box<dyn Fn(f64) -> f64>, super::transport_api::TransportError> {
        let Lambda_fun = self.create_closure_Lambda()?;
        Ok(Lambda_fun)
    }

    fn create_viscosity_closure(
        &mut self,
    ) -> Result<Box<dyn Fn(f64) -> f64>, super::transport_api::TransportError> {
        let visc = self.create_closure_Visc()?;

        Ok(visc)
    }

    fn create_symbolic_lambda(
        &mut self,
        _C: Option<Expr>,
        _ro: Option<Expr>,
    ) -> Result<(), super::transport_api::TransportError> {
        self.create_sym_Lambda()?;
        Ok(())
    }

    fn create_symbolic_viscosity(&mut self) -> Result<(), super::transport_api::TransportError> {
        self.create_sym_Visc()?;
        Ok(())
    }

    fn taylor_series_lambda(
        &mut self,
        _C: Option<Expr>,
        _ro: Option<Expr>,
        t0: f64,
        n: usize,
    ) -> Result<Expr, super::transport_api::TransportError> {
        validate_temperature(t0)?;
        let Lambda_series = self.Taylor_series_Lambda(t0, n)?;
        Ok(Lambda_series)
    }

    fn from_serde(
        &mut self,
        data: serde_json::Value,
    ) -> Result<(), super::transport_api::TransportError> {
        self.input = serde_json::from_value(data).map_err(|e| CEAError::SerdeError(e))?;
        Ok(())
    }

    fn set_M(
        &mut self,
        _M: f64,
        _M_unit: Option<String>,
    ) -> Result<(), super::transport_api::TransportError> {
        Ok(())
    }
    fn set_P(
        &mut self,
        _P: f64,
        _P_unit: Option<String>,
    ) -> Result<(), super::transport_api::TransportError> {
        Ok(())
    }
    fn print_instance(&self) -> Result<(), super::transport_api::TransportError> {
        println!("{:?}", &self);
        Ok(())
    }
    fn get_lambda_sym(&self) -> Result<Expr, super::transport_api::TransportError> {
        match &self.Lambda_sym {
            Some(lambda_sym) => Ok(lambda_sym.clone()),
            None => Err(super::transport_api::TransportError::CalculationError(
                "Lambda_sym not calculated".to_string(),
            )),
        }
    }
    fn get_viscosity_sym(&self) -> Result<Expr, super::transport_api::TransportError> {
        match &self.V_sym {
            Some(viscosity_sym) => Ok(viscosity_sym.clone()),
            None => Err(super::transport_api::TransportError::CalculationError(
                "V_sym not calculated".to_string(),
            )),
        }
    }
    fn get_lambda_fun(
        &self,
    ) -> Result<Box<dyn Fn(f64) -> f64>, super::transport_api::TransportError> {
        Ok(self.clone().Lambda_fun)
    }
    fn get_viscosity_fun(
        &self,
    ) -> Result<Box<dyn Fn(f64) -> f64>, super::transport_api::TransportError> {
        Ok(self.clone().V_fun)
    }

    fn fitting_coeffs_for_T_interval(
        &mut self,
    ) -> Result<(), super::transport_api::TransportError> {
        self.fitting_coeffs_for_T_interval(LV::Viscosity)?;
        self.fitting_coeffs_for_T_interval(LV::Lambda)?;
        Ok(())
    }
    fn integr_mean(&mut self) -> Result<(), super::transport_api::TransportError> {
        self.integr_mean()?;
        Ok(())
    }
    fn set_T_interval(
        &mut self,
        T_min: f64,
        T_max: f64,
    ) -> Result<(), super::transport_api::TransportError> {
        self.set_T_interval(T_min, T_max);
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Thermodynamics::thermo_lib_api::ThermoData;
    use approx::assert_relative_eq;

    fn setup_cea_data() -> CEAdata {
        let mut CEA = CEAdata::new();
        let input = CEAinput {
            LC: vec![
                "V".to_string(),
                "V".to_string(),
                "C".to_string(),
                "C".to_string(),
            ],
            model: vec![
                200.0,
                1000.0,
                0.62526577,
                -31.779652,
                -1640.7983,
                1.7454992,
                1000.0,
                5000.0,
                0.87395209,
                561.52222,
                -173948.09,
                -0.39335958,
                200.0,
                1000.0,
                0.85439436,
                105.73224,
                -12347.848,
                0.47793128,
                1000.0,
                5000.0,
                0.88407146,
                133.57293,
                -11429.64,
                0.24417019,
            ],
        };
        CEA.set_input(input);
        CEA
    }

    #[test]
    fn test_parse_coefficients() {
        let mut CEA = setup_cea_data();
        assert!(CEA.parse_coefficients().is_ok());
        CEA.extract_coefficients(400.0).unwrap();
        println!(
            " coeffs {:?} \n {:?} \n {:?}",
            CEA.coeffs, CEA.coeff_Lambda, CEA.coeff_Visc
        );
        let v_intervals = CEA.coeffs.get(&LV::Viscosity).unwrap();
        let interval_0 = v_intervals.get(&0).unwrap();
        let interval_1 = v_intervals.get(&1).unwrap();

        assert_eq!(interval_0.T, (200.0, 1000.0));
        assert_eq!(
            interval_0.coeff,
            vec![0.62526577, -31.779652, -1640.7983, 1.7454992]
        );
        assert_eq!(interval_1.T, (1000.0, 5000.0));
        assert_eq!(
            interval_1.coeff,
            vec![0.87395209, 561.52222, -173948.09, -0.39335958]
        );

        // Test error case
        let mut CEA = CEAdata::new();
        let input = CEAinput {
            LC: vec!["V".to_string()],
            model: vec![1.0], // Not enough data
        };
        CEA.set_input(input);
        assert!(matches!(
            CEA.parse_coefficients(),
            Err(CEAError::ParseError(_))
        ));
    }

    #[test]
    fn test_extract_coefficients() {
        let mut CEA = setup_cea_data();

        // Test valid temperature
        assert!(CEA.extract_coefficients(500.0).is_ok());
        assert_eq!(
            CEA.coeff_Visc,
            vec![0.62526577, -31.779652, -1640.7983, 1.7454992]
        );
        assert_eq!(
            CEA.coeff_Lambda,
            vec![0.85439436, 105.73224, -12347.848, 0.47793128]
        );

        // Test temperature out of range
        assert!(matches!(
            CEA.extract_coefficients(100.0),
            Err(CEAError::InvalidTemperature(_))
        ));
    }

    #[test]
    fn test_calculate_lambda_and_visc() {
        let mut CEA = setup_cea_data();
        CEA.extract_coefficients(500.0).unwrap();
        CEA.set_lambda_unit(Some("mW/m/K".to_string())).unwrap();
        CEA.set_V_unit(Some("mkPa*s".to_string())).unwrap();

        let lambda = CEA.calculate_Lambda(500.0).unwrap();
        let visc = CEA.calculate_Visc(500.0).unwrap();

        assert_relative_eq!(lambda, 39.2, epsilon = 1.0);
        assert_relative_eq!(visc, 25.8, epsilon = 1.0);

        // Test invalid units
        assert!(matches!(
            CEA.set_lambda_unit(Some("invalid".to_string())),
            Err(CEAError::InvalidUnit(_))
        ));
        assert!(matches!(
            CEA.set_V_unit(Some("invalid".to_string())),
            Err(CEAError::InvalidUnit(_))
        ));
    }

    #[test]
    fn test_create_closures() {
        let mut CEA = setup_cea_data();
        CEA.extract_coefficients(500.0).unwrap();
        CEA.set_lambda_unit(Some("mW/m/K".to_string())).unwrap();
        CEA.set_V_unit(Some("mkPa*s".to_string())).unwrap();

        let lambda_closure = CEA.create_closure_Lambda().unwrap();
        let visc_closure = CEA.create_closure_Visc().unwrap();

        assert_relative_eq!(lambda_closure(500.0), 39.2, epsilon = 1.);
        assert_relative_eq!(visc_closure(500.0), 25.8, epsilon = 1.0);

        // Test error case when coefficients are not initialized
        let mut CEA = CEAdata::new();
        assert!(matches!(
            CEA.create_closure_Lambda(),
            Err(CEAError::MissingCoefficients(_))
        ));
        assert!(matches!(
            CEA.create_closure_Visc(),
            Err(CEAError::MissingCoefficients(_))
        ));
    }

    #[test]
    fn test_create_symbolic_expressions() {
        let mut CEA = setup_cea_data();
        CEA.extract_coefficients(500.0).unwrap();
        CEA.set_lambda_unit(Some("mW/m/K".to_string())).unwrap();
        CEA.set_V_unit(Some("mkPa*s".to_string())).unwrap();

        assert!(CEA.create_sym_Lambda().is_ok());
        assert!(CEA.create_sym_Visc().is_ok());

        let lambda_sym = CEA.Lambda_sym.as_ref().unwrap();
        let lambda_val = lambda_sym.lambdify1D()(500.0);
        let visc_sym = CEA.V_sym.as_ref().unwrap();
        let visc_val = visc_sym.lambdify1D()(500.0);

        assert_relative_eq!(lambda_val, 39.2, epsilon = 1.);
        assert_relative_eq!(visc_val, 25.8, epsilon = 1.0);

        // Test error case when coefficients are not initialized
        let mut CEA = CEAdata::new();
        assert!(matches!(
            CEA.create_sym_Lambda(),
            Err(CEAError::MissingCoefficients(_))
        ));
        assert!(matches!(
            CEA.create_sym_Visc(),
            Err(CEAError::MissingCoefficients(_))
        ));
    }

    #[test]
    fn test_with_real_data() {
        let thermo_data = ThermoData::new();
        let sublib = thermo_data.LibThermoData.get("CEA").unwrap();
        let CO_data = sublib.get("CO").unwrap();
        let mut CEA = CEAdata::new();
        CEA.from_serde(CO_data.clone()).unwrap();
        CEA.set_lambda_unit(Some("mW/m/K".to_string())).unwrap();
        CEA.set_V_unit(Some("mkPa*s".to_string())).unwrap();
        CEA.parse_coefficients().unwrap();
        CEA.extract_coefficients(500.0).unwrap();
        let lambda = CEA.calculate_Lambda(500.0).unwrap();
        let visc = CEA.calculate_Visc(500.0).unwrap();
        println!("Lambda, mW/m/K: {:?}, Visc: {:?}", lambda, visc);
    }
    /*
    #[test]
    fn test_clone_ceadata() {
        let mut original = setup_cea_data();
        original.extract_coefficients(500.0).unwrap();
        original
            .set_lambda_unit(Some("mW/m/K".to_string()))
            .unwrap();
        original.set_V_unit(Some("mkPa*s".to_string())).unwrap();

        // Calculate some values to populate the instance
        original.calculate_Lambda(500.0).unwrap();
        original.calculate_Visc(500.0).unwrap();
        original.create_sym_Lambda().unwrap();
        original.create_sym_Visc().unwrap();

        // Clone the instance
        let cloned = original.clone();

        // Verify basic fields are cloned correctly
        assert_eq!(cloned.L_unit, original.L_unit);
        assert_eq!(cloned.V_unit, original.V_unit);
        assert_eq!(cloned.L_unit_multiplier, original.L_unit_multiplier);
        assert_eq!(cloned.V_unit_multiplier, original.V_unit_multiplier);
        assert_eq!(cloned.Lambda, original.Lambda);
        assert_eq!(cloned.V, original.V);
        assert_eq!(cloned.coeffs, original.coeffs);
        assert_eq!(cloned.coeff_Visc, original.coeff_Visc);

        // Test that cloned functions work correctly
        let lambda_val = (cloned.Lambda_fun)(500.0);
        let visc_val = (cloned.V_fun)(500.0);

        assert_relative_eq!(lambda_val, original.Lambda, epsilon = 1e-6);
        assert_relative_eq!(visc_val, original.V, epsilon = 1e-6);

        // Test symbolic expressions are cloned
        assert!(cloned.Lambda_sym.is_some());
        assert!(cloned.V_sym.is_some());
    }
    */

    #[test]
    fn test_set_T_interval() {
        let mut CEA = setup_cea_data();
        CEA.set_T_interval(300.0, 800.0);
        assert_eq!(CEA.T_interval, Some((300.0, 800.0)));
    }

    #[test]
    fn test_coeffs_for_this_interval() {
        let CEA = setup_cea_data();

        // Test valid interval
        let coeffs = CEA.coeffs_for_this_interval(LV::Viscosity, 0).unwrap();
        assert_eq!(coeffs.T, (200.0, 1000.0));
        assert_eq!(
            coeffs.coeff,
            vec![0.62526577, -31.779652, -1640.7983, 1.7454992]
        );

        // Test invalid interval
        assert!(matches!(
            CEA.coeffs_for_this_interval(LV::Viscosity, 99),
            Err(CEAError::InvalidTemperature(_))
        ));
    }

    #[test]
    fn test_fitting_coeffs_for_T_interval_same_interval() {
        let mut CEA = setup_cea_data();
        CEA.set_T_interval(300.0, 800.0); // Both in same interval [200-1000]

        assert!(CEA.fitting_coeffs_for_T_interval(LV::Viscosity).is_ok());
        assert!(!CEA.fitting_needed);
        assert_eq!(
            CEA.coeff_Visc,
            vec![0.62526577, -31.779652, -1640.7983, 1.7454992]
        );
    }

    #[test]
    fn test_fitting_coeffs_for_T_interval_no_interval_set() {
        let mut CEA = setup_cea_data();
        let l = "T_interval not set".to_string();
        assert!(matches!(
            CEA.fitting_coeffs_for_T_interval(LV::Viscosity),
            Err(CEAError::MissingData(l))
        ));
    }

    #[test]
    fn test_fitting_coeffs_for_T_interval_invalid_range() {
        let mut CEA = setup_cea_data();
        CEA.set_T_interval(100.0, 150.0); // Out of range

        assert!(matches!(
            CEA.fitting_coeffs_for_T_interval(LV::Viscosity),
            Err(CEAError::InvalidTemperature(_))
        ));
    }

    #[test]
    fn test_fitting_adjacent() {
        let mut CEA = setup_cea_data();

        let coeffs_min = Coeffs {
            T: (200.0, 1000.0),
            coeff: vec![0.62526577, -31.779652, -1640.7983, 1.7454992],
        };
        let coeffs_max = Coeffs {
            T: (1000.0, 5000.0),
            coeff: vec![0.87395209, 561.52222, -173948.09, -0.39335958],
        };

        let result = CEA.fitting_adjacent(coeffs_min, coeffs_max, 800.0, 1200.0, LV::Viscosity);
        assert!(result.is_ok());
        assert_eq!(CEA.coeff_Visc.len(), 4); // Should have fitted coefficients
    }

    #[test]
    fn test_fitting_adjacent_non_adjacent() {
        let mut CEA = setup_cea_data();

        let coeffs_min = Coeffs {
            T: (200.0, 800.0), // Non-adjacent
            coeff: vec![0.62526577, -31.779652, -1640.7983, 1.7454992],
        };
        let coeffs_max = Coeffs {
            T: (1000.0, 5000.0),
            coeff: vec![0.87395209, 561.52222, -173948.09, -0.39335958],
        };

        assert!(matches!(
            CEA.fitting_adjacent(coeffs_min, coeffs_max, 700.0, 1200.0, LV::Viscosity),
            Err(CEAError::ParseError(_))
        ));
    }

    #[test]
    fn test_fitting_coeffs_for_T_interval_adjacent() {
        let mut CEA = setup_cea_data();
        CEA.set_T_interval(800.0, 1200.0); // Spans intervals [200-1000] and [1000-5000]

        assert!(CEA.fitting_coeffs_for_T_interval(LV::Viscosity).is_ok());
        assert!(CEA.fitting_needed);
        assert_eq!(CEA.coeff_Visc.len(), 4); // Should have fitted coefficients
    }
}