KiThe 0.3.22

A numerical suite for chemical kinetics and thermodynamics, combustion, heat and mass transfer,chemical equilibrium, chemical engeneering
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
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
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
//! # TGA data preprocessing pipeline
//!
//! Recommended order:
//! 1. Read raw data (CSV / TXT)
//! 2. Bind semantic columns (time, mass, temperature)
//! 3. Calibrate raw signals if needed
//! 4. Dimensionless transforms
//! 5. Smoothing / filtering
//! 6. Derivatives
//! 7. Trim invalid edges
//!
//! ## Русский ориентир
//! 1. Читаем сырые данные
//! 2. Привязываем смысловые колонки: время, масса, температура
//! 3. При необходимости калибруем сигналы
//! 4. Строим безразмерные величины
//! 5. Сглаживаем и фильтруем
//! 6. Считаем производные
//! 7. Обрезаем некорректные края
/// # Recommended TGA data processing pipeline
///
/// KiThe follows an explicit, step-by-step processing model.
/// KiThe использует явную пошаговую модель обработки данных.
/// No operation implicitly removes rows or modifies unrelated columns.
/// Ни одна операция не удаляет строки и не меняет посторонние колонки неявно.
///
/// ## General principles
///
/// 1. **All column operations preserve table length**
///    - rolling mean, differentiation, filtering produce `null`
///    - row removal is always explicit
///
/// 2. **`null` values are valid intermediate state**
///    - smoothing and differentiation naturally introduce `null`
///    - users must explicitly remove invalid edges
///
/// 3. **Row removal is explicit**
///    - use `trim_edges(left, right)` or `filter_rows(...)`
///    - no operation removes rows automatically
///
/// 4. **Raw experimental columns should be preserved**
///    - smoothing/filtering is usually applied to derived columns
///
/// ## Typical workflow
///
/// ```text
/// raw data (time, temperature, mass)
///     ↓
/// optional calibration / scaling
///     ↓
/// optional smoothing (rolling mean, Hampel, etc.)
///     ↓
/// trim_edges (to remove null introduced by smoothing)
///     ↓
/// relative mass α / conversion η
///     ↓
/// differentiation (rates)
///     ↓
/// trim_edges (to remove null from finite differences)
/// ```
///
/// ## Notes
///
/// - Hampel filter assumes the input column has no null values.
/// - It is recommended to call `trim_edges` before Hampel filtering.
/// - Smoothing and filtering do not modify column metadata (units, origin).
///
use polars::error::{PolarsError, PolarsResult};

use RustedSciThe::symbolic::symbolic_engine::Expr as SymbolicExpr;
use polars::prelude::LazyFrame;
use polars::prelude::*;
use polars::series::Series;

use crate::Kinetics::experimental_kinetics::column_provenance::{
    ColumnProvenance, ColumnTransformKind, QualityReference, QualityStatus, TransformCoverage,
    TransformQuality,
};
use log::info;
use std::collections::{HashMap, HashSet, VecDeque};
use std::fmt::Write as FmtWrite;
use std::io::Write;
use std::path::Path;
use std::sync::Arc;
use std::time::Instant;
//===============================================================
// One datafame plot data
#[derive(Clone, Debug)]
pub struct OneFramePlot {
    pub x: Option<String>,
    pub y: Option<String>,
}

//===========================================

pub struct UnaryOp {
    pub func: Box<dyn Fn(f64) -> f64 + Send + Sync>,
    pub output_unit: Unit,
    pub domain_check: Option<fn(&TGADataset, &str) -> Result<(), TGADomainError>>,
}
//=================================================================
// ERROR HANDLING
//=================================================================
#[derive(Debug, Clone)]
pub enum TGADomainError {
    PolarsError(PolarsError),
    InvalidFilterParameters {
        filter: String,
        details: String,
    },
    NonNumericColumn {
        column: String,
        actual_type: String,
    },
    InvalidColumnValues {
        column: String,
        details: String,
        indices: Vec<usize>,
    },
    IncompatibleUnits {
        operation: String,
        expected: String,
        actual: Unit,
    },
    NoConvergence {
        method: String,
        details: String,
    },
    InsufficientData {
        available: usize,
        required: usize,
    },
    DegenerateRegression {
        details: String,
    },
    FittingInputLengthMismatch {
        x_len: usize,
        y_len: usize,
    },
    InvalidFittingConfiguration {
        details: String,
    },
    InvalidFormula {
        expression: String,
        details: String,
    },
    FormulaEvaluationFailed {
        expression: String,
        row_index: usize,
        x_value: f64,
        result: f64,
    },
    FormulaEvaluationFailedForVariables {
        expression: String,
        row_index: usize,
        variable_values: Vec<(String, f64)>,
        result: f64,
    },
    ConversionRangeNotCovered {
        experiment_id: String,
        requested_min: f64,
        requested_max: f64,
        available_min: f64,
        available_max: f64,
    },
    OperationContext {
        experiment_id: Option<String>,
        column: Option<String>,
        operation: String,
        source: Box<TGADomainError>,
    },
    EmptyColumn(String),
    NonPositiveValues {
        column: String,
    },
    ColumnNotFound(String),
    AmbiguousColumnNature {
        nature: ColumnNature,
        columns: Vec<String>,
    },
    ExperimentDataLengthMismatch {
        experiment_id: String,
        column: String,
        expected: usize,
        actual: usize,
    },
    DatasetColumnLengthMismatch {
        column: String,
        expected: usize,
        actual: usize,
    },
    MassNotBound,
    TimeNotBound,
    NoDimensionless,
    AlphaNotFound,
    TemperatureNotBound,
    DtDtNotFound,
    DmDtNotFound,
    DalphaDtNotFound,

    EtaNotFound,
    DetaDtNotFound,

    UnsupportedRateUnit,
    InvalidReferenceMass,
    InvalidUnitForConversion,
    InvalidUnitForBinding {
        field: &'static str,
        unit: Unit,
    },
    ColumnAlreadyExists(String),
    DuplicateExperimentId(String),
    ExperimentNotFound(String),
    NotImplemented,
    InvalidOperation(String),
    OutOfRange,
    TimeNonMonotonic(String),
    InvalidConversionRange,
}

impl TGADomainError {
    pub fn with_context(
        self,
        operation: impl Into<String>,
        experiment_id: Option<&str>,
        column: Option<&str>,
    ) -> Self {
        Self::OperationContext {
            experiment_id: experiment_id.map(str::to_owned),
            column: column.map(str::to_owned),
            operation: operation.into(),
            source: Box::new(self),
        }
    }
}

impl std::fmt::Display for TGADomainError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::OperationContext {
                experiment_id,
                column,
                operation,
                source,
            } => {
                write!(f, "{operation} failed")?;
                if let Some(experiment_id) = experiment_id {
                    write!(f, " for experiment '{experiment_id}'")?;
                }
                if let Some(column) = column {
                    write!(f, " on column '{column}'")?;
                }
                write!(f, ": {source}")
            }
            Self::InvalidFilterParameters { filter, details } => {
                write!(f, "Invalid parameters for {filter}: {details}")
            }
            Self::InvalidColumnValues {
                column,
                details,
                indices,
            } => write!(
                f,
                "Invalid values in column '{column}': {details} (rows: {indices:?})"
            ),
            Self::NoConvergence { method, details } => {
                write!(f, "{method} did not produce a valid result: {details}")
            }
            Self::InsufficientData {
                available,
                required,
            } => write!(
                f,
                "Insufficient observations: {available} available, {required} required"
            ),
            Self::DegenerateRegression { details } => {
                write!(f, "Regression is degenerate: {details}")
            }
            Self::FittingInputLengthMismatch { x_len, y_len } => write!(
                f,
                "Fitting X/Y columns have different lengths ({x_len} vs {y_len})"
            ),
            Self::InvalidFittingConfiguration { details } => {
                write!(f, "Invalid fitting configuration: {details}")
            }
            Self::InvalidFormula {
                expression,
                details,
            } => write!(f, "Invalid formula '{expression}': {details}"),
            Self::FormulaEvaluationFailed {
                expression,
                row_index,
                x_value,
                result,
            } => write!(
                f,
                "Formula '{expression}' produced non-finite value {result} at row {row_index} (x={x_value})"
            ),
            Self::FormulaEvaluationFailedForVariables {
                expression,
                row_index,
                variable_values,
                result,
            } => write!(
                f,
                "Formula '{expression}' produced non-finite value {result} at row {row_index} with inputs {variable_values:?}"
            ),
            Self::ConversionRangeNotCovered {
                experiment_id,
                requested_min,
                requested_max,
                available_min,
                available_max,
            } => write!(
                f,
                "Experiment '{experiment_id}' covers conversion [{available_min}, {available_max}], but requested [{requested_min}, {requested_max}]"
            ),
            Self::DatasetColumnLengthMismatch {
                column,
                expected,
                actual,
            } => write!(
                f,
                "Column '{column}' has {actual} values, but the dataset has {expected} rows"
            ),
            Self::InvalidOperation(message) => write!(f, "{message}"),
            _ => write!(f, "{self:?}"),
        }
    }
}

impl std::error::Error for TGADomainError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::PolarsError(source) => Some(source),
            Self::OperationContext { source, .. } => Some(source.as_ref()),
            _ => None,
        }
    }
}

/// Detailed diagnostics for the active time column.
#[derive(Debug, Clone, PartialEq)]
pub struct TimeOrderViolation {
    pub index: usize,
    pub previous: f64,
    pub current: f64,
}

/// Structured report describing why the active time column is or is not monotonic.
#[derive(Debug, Clone, PartialEq)]
pub struct TimeMonotonicityReport {
    pub time_column: String,
    pub len: usize,
    pub null_indices: Vec<usize>,
    pub nan_indices: Vec<usize>,
    pub infinite_indices: Vec<usize>,
    pub duplicate_pairs: Vec<TimeOrderViolation>,
    pub decreasing_pairs: Vec<TimeOrderViolation>,
    pub is_strictly_increasing: bool,
    pub sortable_without_data_loss: bool,
}

impl TimeMonotonicityReport {
    pub fn has_invalid_values(&self) -> bool {
        !self.null_indices.is_empty()
            || !self.nan_indices.is_empty()
            || !self.infinite_indices.is_empty()
    }
}

impl From<PolarsError> for TGADomainError {
    fn from(err: PolarsError) -> Self {
        TGADomainError::PolarsError(err)
    }
}
//=================================================================
//UNITS
//=================================================================
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Unit {
    Second,
    Minute,
    Hour,

    Kelvin,
    Celsius,

    MilliVolt,
    Milligram,
    MolePerCubicMeter,
    MilligramPerSecond,
    MilligramPerMinute,
    MilligramPerHour,
    KelvinPerSecond,
    KelvinPerMinute,
    KelvinPerHour,
    CelsiusPerSecond,
    CelsiusPerMinute,
    CelsiusPerHour,
    PerSecond,
    PerMinute,
    PerHour,
    Gram,

    Dimensionless,
    Unknown,
}

impl Unit {
    fn is_valid_time_binding_unit(self) -> bool {
        matches!(self, Unit::Second | Unit::Minute | Unit::Hour)
    }

    fn is_valid_temperature_binding_unit(self) -> bool {
        matches!(self, Unit::Kelvin | Unit::Celsius)
    }

    fn is_valid_mass_binding_unit(self) -> bool {
        matches!(self, Unit::MilliVolt | Unit::Milligram | Unit::Gram)
    }

    /// Normalize a rate unit to the time base used by the time column.
    ///
    /// KiThe currently supports time in seconds or hours. The numeric derivative
    /// is computed against the stored time values, so this helper only adjusts the
    /// semantic unit label to match the time axis.
    pub fn for_time_base(self, time_unit: Unit) -> Result<Self, TGADomainError> {
        match time_unit {
            Unit::Second => match self {
                Unit::Milligram
                | Unit::MilligramPerSecond
                | Unit::MilligramPerMinute
                | Unit::MilligramPerHour => Ok(Unit::MilligramPerSecond),
                Unit::Kelvin
                | Unit::KelvinPerSecond
                | Unit::KelvinPerMinute
                | Unit::KelvinPerHour => Ok(Unit::KelvinPerSecond),
                Unit::Celsius
                | Unit::CelsiusPerSecond
                | Unit::CelsiusPerMinute
                | Unit::CelsiusPerHour => Ok(Unit::CelsiusPerSecond),
                Unit::Dimensionless | Unit::PerSecond | Unit::PerMinute | Unit::PerHour => {
                    Ok(Unit::PerSecond)
                }
                _ => Err(TGADomainError::UnsupportedRateUnit),
            },
            Unit::Minute => match self {
                Unit::Milligram
                | Unit::MilligramPerSecond
                | Unit::MilligramPerMinute
                | Unit::MilligramPerHour => Ok(Unit::MilligramPerMinute),
                Unit::Kelvin
                | Unit::KelvinPerSecond
                | Unit::KelvinPerMinute
                | Unit::KelvinPerHour => Ok(Unit::KelvinPerMinute),
                Unit::Celsius
                | Unit::CelsiusPerSecond
                | Unit::CelsiusPerMinute
                | Unit::CelsiusPerHour => Ok(Unit::CelsiusPerMinute),
                Unit::Dimensionless | Unit::PerSecond | Unit::PerMinute | Unit::PerHour => {
                    Ok(Unit::PerMinute)
                }
                _ => Err(TGADomainError::UnsupportedRateUnit),
            },
            Unit::Hour => match self {
                Unit::Milligram
                | Unit::MilligramPerSecond
                | Unit::MilligramPerMinute
                | Unit::MilligramPerHour => Ok(Unit::MilligramPerHour),
                Unit::Kelvin
                | Unit::KelvinPerSecond
                | Unit::KelvinPerMinute
                | Unit::KelvinPerHour => Ok(Unit::KelvinPerHour),
                Unit::Celsius
                | Unit::CelsiusPerSecond
                | Unit::CelsiusPerMinute
                | Unit::CelsiusPerHour => Ok(Unit::CelsiusPerHour),
                Unit::Dimensionless | Unit::PerSecond | Unit::PerMinute | Unit::PerHour => {
                    Ok(Unit::PerHour)
                }
                _ => Err(TGADomainError::UnsupportedRateUnit),
            },
            _ => Err(TGADomainError::UnsupportedRateUnit),
        }
    }

    pub fn parse(s: &str) -> Result<Self, PolarsError> {
        match s {
            "s" => Ok(Unit::Second),
            "min" => Ok(Unit::Minute),
            "h" => Ok(Unit::Hour),
            "C" => Ok(Unit::Celsius),
            "K" => Ok(Unit::Kelvin),
            "mV" => Ok(Unit::MilliVolt),
            "mg" => Ok(Unit::Milligram),
            "mol/m^3" => Ok(Unit::MolePerCubicMeter),
            "mg/s" => Ok(Unit::MilligramPerSecond),
            "mg/min" => Ok(Unit::MilligramPerMinute),
            "mg/h" => Ok(Unit::MilligramPerHour),
            "K/s" => Ok(Unit::KelvinPerSecond),
            "K/min" => Ok(Unit::KelvinPerMinute),
            "K/h" => Ok(Unit::KelvinPerHour),
            "C/s" => Ok(Unit::CelsiusPerSecond),
            "C/min" => Ok(Unit::CelsiusPerMinute),
            "C/h" => Ok(Unit::CelsiusPerHour),
            "/s" => Ok(Unit::PerSecond),
            "/min" => Ok(Unit::PerMinute),
            "1/s" => Ok(Unit::PerSecond),
            "1/min" => Ok(Unit::PerMinute),
            "/h" => Ok(Unit::PerHour),
            "1/h" => Ok(Unit::PerHour),
            "g" => Ok(Unit::Gram),
            "Dimensionless" => Ok(Unit::Dimensionless),
            "Unknown" => Ok(Unit::Unknown),
            "-" => Ok(Unit::Dimensionless),

            _ => Err(PolarsError::ComputeError(
                format!("Unknown unit: {}", s).into(),
            )),
        }
    }
    pub fn convert_to_string(&self) -> String {
        match self {
            Unit::Second => "s".to_string(),
            Unit::Minute => "min".to_string(),
            Unit::Hour => "h".to_string(),
            Unit::Kelvin => "K".to_string(),
            Unit::Celsius => "C".to_string(),
            Unit::MilliVolt => "mV".to_string(),
            Unit::Milligram => "mg".to_string(),
            Unit::MolePerCubicMeter => "mol/m^3".to_string(),
            Unit::MilligramPerSecond => "mg/s".to_string(),
            Unit::MilligramPerMinute => "mg/min".to_string(),
            Unit::MilligramPerHour => "mg/h".to_string(),
            Unit::KelvinPerSecond => "K/s".to_string(),
            Unit::KelvinPerMinute => "K/min".to_string(),
            Unit::KelvinPerHour => "K/h".to_string(),
            Unit::CelsiusPerSecond => "C/s".to_string(),
            Unit::CelsiusPerMinute => "C/min".to_string(),
            Unit::CelsiusPerHour => "C/h".to_string(),
            Unit::PerSecond => "/s".to_string(),
            Unit::PerMinute => "/min".to_string(),
            Unit::PerHour => "/h".to_string(),
            Unit::Gram => "g".to_string(),
            Unit::Dimensionless => "Dimensionless".to_string(),
            Unit::Unknown => "Unknown".to_string(),
        }
    }
}

impl std::fmt::Display for Unit {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Unit::Second => write!(f, "s"),
            Unit::Minute => write!(f, "min"),
            Unit::Hour => write!(f, "h"),
            Unit::Kelvin => write!(f, "K"),
            Unit::Celsius => write!(f, "C"),
            Unit::MilliVolt => write!(f, "mV"),
            Unit::Milligram => write!(f, "mg"),
            Unit::MolePerCubicMeter => write!(f, "mol/m^3"),
            Unit::MilligramPerSecond => write!(f, "mg/s"),
            Unit::MilligramPerMinute => write!(f, "mg/min"),
            Unit::MilligramPerHour => write!(f, "mg/h"),
            Unit::KelvinPerSecond => write!(f, "K/s"),
            Unit::KelvinPerMinute => write!(f, "K/min"),
            Unit::KelvinPerHour => write!(f, "K/h"),
            Unit::CelsiusPerSecond => write!(f, "C/s"),
            Unit::CelsiusPerMinute => write!(f, "C/min"),
            Unit::CelsiusPerHour => write!(f, "C/h"),
            Unit::PerSecond => write!(f, "/s"),
            Unit::PerMinute => write!(f, "/min"),
            Unit::PerHour => write!(f, "/h"),
            Unit::Gram => write!(f, "g"),
            Unit::Dimensionless => write!(f, "Dimensionless"),
            Unit::Unknown => write!(f, "Unknown"),
        }
    }
}

//=====================================================================
//              COLUMN METADATA
//====================================================================
#[derive(Debug, Clone)]
pub enum ColumnRole {
    Time,
    Temperature,
    Mass,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ColumnNature {
    Time,
    Temperature,
    Mass,
    Concentration,
    // alpha = relative mass m/m0
    Conversion,
    // eta = 1 - alpha
    DimensionlessMass,
    MassRate,
    ConversionRate,
    TemperatureRate,
    DimensionlessMassRate,
    Unknown,
    ActivationEnergy,
    PredexFactor,
    R2,
    FittedCurve,
}

/// Controls when a numerical derivative is withheld across a large time gap.
///
/// Derivatives use the bound time column's stored values, so `MaxInterval` is
/// expressed in that column's unit (for example, seconds or hours).
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TimeGapPolicy {
    /// Mark a derivative as null when either adjacent interval exceeds this
    /// multiple of the median positive sampling interval.
    MedianStepMultiple(f64),
    /// Mark a derivative as null when either adjacent interval exceeds this
    /// absolute duration in the bound time unit.
    MaxInterval(f64),
    /// Do not reject large intervals; still reject non-positive or non-finite
    /// intervals.
    Allow,
}

impl Default for TimeGapPolicy {
    fn default() -> Self {
        Self::MedianStepMultiple(5.0)
    }
}
/// Columns Origin
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ColumnOrigin {
    Raw,
    PolarsDerived,
    NumericDerived,
    Imported,
    Simulated,
}
/// Column  metadata
#[derive(Debug, Clone)]
pub struct ColumnMeta {
    pub name: String,
    pub unit: Unit,
    pub origin: ColumnOrigin,
    pub nature: ColumnNature,
    pub provenance: ColumnProvenance,
}

impl ColumnMeta {
    pub fn new(
        name: impl Into<String>,
        unit: Unit,
        origin: ColumnOrigin,
        nature: ColumnNature,
        provenance: ColumnProvenance,
    ) -> Self {
        Self {
            name: name.into(),
            unit,
            origin,
            nature,
            provenance,
        }
    }

    pub fn raw(name: impl Into<String>, unit: Unit, nature: ColumnNature) -> Self {
        let name = name.into();
        Self::new(
            name.clone(),
            unit,
            ColumnOrigin::Raw,
            nature,
            ColumnProvenance::raw(name),
        )
    }

    pub fn set_nature(&mut self, nature: ColumnNature) {
        self.nature = nature;
    }

    pub fn get_nature(&self) -> ColumnNature {
        self.nature
    }
}

/// Scheme of TGA dataset
#[derive(Debug, Clone)]
pub struct TGASchema {
    pub columns: HashMap<String, ColumnMeta>,
    pub time: Option<String>,
    pub temperature: Option<String>,
    pub mass: Option<String>,
    pub alpha: Option<String>,
    pub dm_dt: Option<String>,
    pub eta: Option<String>,
    pub deta_dt: Option<String>,
    pub dalpha_dt: Option<String>,
    pub dT_dt: Option<String>,
    pub E: Option<String>,
    pub R2: Option<String>,
}

#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
#[serde(default)]
struct CsvSchemaBindings {
    time: Option<String>,
    temperature: Option<String>,
    mass: Option<String>,
    alpha: Option<String>,
    dm_dt: Option<String>,
    eta: Option<String>,
    deta_dt: Option<String>,
    dalpha_dt: Option<String>,
    dT_dt: Option<String>,
    E: Option<String>,
    R2: Option<String>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct CsvColumnMetadata {
    name: String,
    nature: ColumnNature,
    origin: ColumnOrigin,
}

impl CsvColumnMetadata {
    fn from_schema(schema: &TGASchema, names: &[String]) -> Vec<Self> {
        names
            .iter()
            .map(|name| {
                let meta = schema.columns.get(name);
                Self {
                    name: name.clone(),
                    nature: meta
                        .map(|meta| meta.nature)
                        .unwrap_or(ColumnNature::Unknown),
                    origin: meta
                        .map(|meta| meta.origin)
                        .unwrap_or(ColumnOrigin::Imported),
                }
            })
            .collect()
    }

    fn apply_all(metadata: Vec<Self>, schema: &mut TGASchema) -> PolarsResult<()> {
        let mut seen = HashSet::with_capacity(metadata.len());
        for item in metadata {
            if !seen.insert(item.name.clone()) {
                return Err(PolarsError::ComputeError(
                    format!("CSV metadata repeats column '{}'", item.name).into(),
                ));
            }
            let meta = schema.columns.get_mut(&item.name).ok_or_else(|| {
                PolarsError::ComputeError(
                    format!("CSV metadata refers to missing column '{}'", item.name).into(),
                )
            })?;
            meta.nature = item.nature;
            meta.origin = item.origin;
        }
        Ok(())
    }
}

impl CsvSchemaBindings {
    fn from_schema(schema: &TGASchema, selected: Option<&[&str]>) -> Self {
        let keep = |name: &Option<String>| {
            name.as_ref()
                .filter(|name| selected.is_none_or(|selected| selected.contains(&name.as_str())))
                .cloned()
        };
        Self {
            time: keep(&schema.time),
            temperature: keep(&schema.temperature),
            mass: keep(&schema.mass),
            alpha: keep(&schema.alpha),
            dm_dt: keep(&schema.dm_dt),
            eta: keep(&schema.eta),
            deta_dt: keep(&schema.deta_dt),
            dalpha_dt: keep(&schema.dalpha_dt),
            dT_dt: keep(&schema.dT_dt),
            E: keep(&schema.E),
            R2: keep(&schema.R2),
        }
    }

    fn apply(self, schema: &mut TGASchema) -> PolarsResult<()> {
        for (field, name) in [
            ("time", &self.time),
            ("temperature", &self.temperature),
            ("mass", &self.mass),
            ("alpha", &self.alpha),
            ("dm_dt", &self.dm_dt),
            ("eta", &self.eta),
            ("deta_dt", &self.deta_dt),
            ("dalpha_dt", &self.dalpha_dt),
            ("dT_dt", &self.dT_dt),
            ("E", &self.E),
            ("R2", &self.R2),
        ] {
            if let Some(name) = name {
                let meta = schema.columns.get_mut(name).ok_or_else(|| {
                    PolarsError::ComputeError(
                        format!("CSV binding '{field}' refers to missing column '{name}'").into(),
                    )
                })?;
                meta.nature = match field {
                    "time" => ColumnNature::Time,
                    "temperature" => ColumnNature::Temperature,
                    "mass" => ColumnNature::Mass,
                    "alpha" => ColumnNature::DimensionlessMass,
                    "dm_dt" => ColumnNature::MassRate,
                    "eta" => ColumnNature::Conversion,
                    "deta_dt" => ColumnNature::ConversionRate,
                    "dalpha_dt" => ColumnNature::DimensionlessMassRate,
                    "dT_dt" => ColumnNature::TemperatureRate,
                    "E" => ColumnNature::ActivationEnergy,
                    "R2" => ColumnNature::R2,
                    _ => unreachable!(),
                };
            }
        }
        schema.time = self.time;
        schema.temperature = self.temperature;
        schema.mass = self.mass;
        schema.alpha = self.alpha;
        schema.dm_dt = self.dm_dt;
        schema.eta = self.eta;
        schema.deta_dt = self.deta_dt;
        schema.dalpha_dt = self.dalpha_dt;
        schema.dT_dt = self.dT_dt;
        schema.E = self.E;
        schema.R2 = self.R2;
        schema.refresh_active_column_natures()?;
        Ok(())
    }
}

impl Default for TGASchema {
    fn default() -> Self {
        Self {
            columns: HashMap::new(),
            time: None,
            temperature: None,
            mass: None,
            alpha: None,
            dm_dt: None,
            eta: None,
            deta_dt: None,
            dalpha_dt: None,
            dT_dt: None,
            E: None,
            R2: None,
        }
    }
}

impl TGASchema {
    pub(crate) fn bind_active_nature(&mut self, nature: ColumnNature, name: &str) {
        let binding = match nature {
            ColumnNature::Time => &mut self.time,
            ColumnNature::Temperature => &mut self.temperature,
            ColumnNature::Mass => &mut self.mass,
            ColumnNature::DimensionlessMass => &mut self.alpha,
            ColumnNature::MassRate => &mut self.dm_dt,
            ColumnNature::Conversion => &mut self.eta,
            ColumnNature::ConversionRate => &mut self.deta_dt,
            ColumnNature::DimensionlessMassRate => &mut self.dalpha_dt,
            ColumnNature::TemperatureRate => &mut self.dT_dt,
            ColumnNature::ActivationEnergy => &mut self.E,
            ColumnNature::R2 => &mut self.R2,
            ColumnNature::Concentration
            | ColumnNature::Unknown
            | ColumnNature::PredexFactor
            | ColumnNature::FittedCurve => return,
        };
        *binding = Some(name.to_string());
    }

    pub(crate) fn has_binding_for_nature(nature: ColumnNature) -> bool {
        matches!(
            nature,
            ColumnNature::Time
                | ColumnNature::Temperature
                | ColumnNature::Mass
                | ColumnNature::DimensionlessMass
                | ColumnNature::MassRate
                | ColumnNature::Conversion
                | ColumnNature::ConversionRate
                | ColumnNature::DimensionlessMassRate
                | ColumnNature::TemperatureRate
                | ColumnNature::ActivationEnergy
                | ColumnNature::R2
        )
    }

    fn get(&self, name: &str) -> Option<&ColumnMeta> {
        self.columns.get(name)
    }

    fn bind_primary_role(&mut self, role: &ColumnRole, name: &str) {
        for binding in [
            &mut self.time,
            &mut self.temperature,
            &mut self.mass,
            &mut self.alpha,
            &mut self.dm_dt,
            &mut self.eta,
            &mut self.deta_dt,
            &mut self.dalpha_dt,
            &mut self.dT_dt,
            &mut self.E,
            &mut self.R2,
        ] {
            if binding.as_deref() == Some(name) {
                *binding = None;
            }
        }
        match role {
            ColumnRole::Time => self.time = Some(name.to_string()),
            ColumnRole::Temperature => self.temperature = Some(name.to_string()),
            ColumnRole::Mass => self.mass = Some(name.to_string()),
        }
    }

    pub(crate) fn refresh_active_column_natures(&mut self) -> PolarsResult<()> {
        let bindings = [
            (&self.time, ColumnNature::Time, "time"),
            (&self.temperature, ColumnNature::Temperature, "temperature"),
            (&self.mass, ColumnNature::Mass, "mass"),
            (&self.alpha, ColumnNature::DimensionlessMass, "alpha"),
            (&self.dm_dt, ColumnNature::MassRate, "dm_dt"),
            (&self.eta, ColumnNature::Conversion, "eta"),
            (&self.deta_dt, ColumnNature::ConversionRate, "deta_dt"),
            (
                &self.dalpha_dt,
                ColumnNature::DimensionlessMassRate,
                "dalpha_dt",
            ),
            (&self.dT_dt, ColumnNature::TemperatureRate, "dT_dt"),
            (&self.E, ColumnNature::ActivationEnergy, "E"),
            (&self.R2, ColumnNature::R2, "R2"),
        ];
        let mut assigned = HashMap::<&str, (&str, ColumnNature)>::new();
        for (binding, nature, field) in bindings {
            let Some(name) = binding.as_deref() else {
                continue;
            };
            if !self.columns.contains_key(name) {
                return Err(PolarsError::ComputeError(
                    format!("Schema binding '{field}' refers to missing column '{name}'").into(),
                ));
            }
            if let Some((previous_field, previous_nature)) = assigned.insert(name, (field, nature))
                && previous_nature != nature
            {
                return Err(PolarsError::ComputeError(
                    format!(
                        "Column '{name}' cannot be active for both '{previous_field}' and '{field}'"
                    )
                    .into(),
                ));
            }
        }
        for (name, (_, nature)) in assigned {
            let metadata = self.columns.get_mut(name).ok_or_else(|| {
                PolarsError::ComputeError(
                    format!("Validated schema column '{name}' disappeared").into(),
                )
            })?;
            metadata.nature = nature;
        }
        Ok(())
    }

    fn nature_from_header(name: &str) -> ColumnNature {
        let label = name.split(['[', '(']).next().unwrap_or(name).trim();

        match label {
            "t" => return ColumnNature::Time,
            "T" => return ColumnNature::Temperature,
            "m" => return ColumnNature::Mass,
            _ => {}
        }

        match label.to_ascii_lowercase().as_str() {
            "time" => ColumnNature::Time,
            "temp" | "temperature" => ColumnNature::Temperature,
            "mass" | "weight" => ColumnNature::Mass,
            _ => ColumnNature::Unknown,
        }
    }

    // Infer a role only for unique header matches; ambiguous candidates stay
    // Unknown so later nature-based lookups cannot silently select one of them.
    fn infer_bindings_from_headers(&mut self, names: &[String]) {
        let mut time = Vec::new();
        let mut temperature = Vec::new();
        let mut mass = Vec::new();

        for name in names {
            let nature = Self::nature_from_header(name);
            match nature {
                ColumnNature::Time => time.push(name.clone()),
                ColumnNature::Temperature => temperature.push(name.clone()),
                ColumnNature::Mass => mass.push(name.clone()),
                _ => {}
            }
        }

        self.time = self.bind_unique_header_match(time, ColumnNature::Time);
        self.temperature = self.bind_unique_header_match(temperature, ColumnNature::Temperature);
        self.mass = self.bind_unique_header_match(mass, ColumnNature::Mass);
    }

    fn bind_unique_header_match(
        &mut self,
        mut matches: Vec<String>,
        nature: ColumnNature,
    ) -> Option<String> {
        if matches.len() == 1 {
            let name = matches.pop()?;
            if let Some(meta) = self.columns.get_mut(&name) {
                let has_compatible_unit = match nature {
                    ColumnNature::Time => meta.unit.is_valid_time_binding_unit(),
                    ColumnNature::Temperature => meta.unit.is_valid_temperature_binding_unit(),
                    ColumnNature::Mass => meta.unit.is_valid_mass_binding_unit(),
                    _ => false,
                };
                if !has_compatible_unit {
                    return None;
                }
                meta.nature = nature;
            } else {
                return None;
            }
            Some(name)
        } else {
            None
        }
    }

    fn from_columns(names: Vec<String>, units: Vec<Unit>) -> PolarsResult<Self> {
        if names.len() != units.len() {
            return Err(PolarsError::ComputeError(
                format!(
                    "Column metadata has {} names but {} units",
                    names.len(),
                    units.len()
                )
                .into(),
            ));
        }

        let mut columns = HashMap::new();
        for (name, unit) in names.iter().zip(units.iter()) {
            if name.trim().is_empty() {
                return Err(PolarsError::ComputeError(
                    "Column metadata contains an empty column name".into(),
                ));
            }
            if columns.contains_key(name) {
                return Err(PolarsError::ComputeError(
                    format!("Column metadata contains duplicate name '{name}'").into(),
                ));
            }
            columns.insert(
                name.clone(),
                ColumnMeta::new(
                    name.clone(),
                    *unit,
                    ColumnOrigin::Imported,
                    ColumnNature::Unknown,
                    ColumnProvenance::imported(name.clone(), name.clone()),
                ),
            );
        }
        let mut schema = Self {
            columns,
            ..Self::default()
        };
        schema.infer_bindings_from_headers(&names);
        Ok(schema)
    }

    /// Update schema when a column is renamed
    /// 1. Insert new column metadata with same unit/origin as old_name
    /// 2. Keep old column metadata unchanged
    /// 3. Update semantic fields (time, mass, etc.) if they reference old_name
    pub fn update_schema(&mut self, old_name: &str, new_name: &str) {
        // Clone the metadata of the old column if it exists
        if let Some(old_meta) = self.columns.get(old_name) {
            let mut provenance = old_meta.provenance.clone();
            provenance.rename_output(new_name);
            let new_meta = ColumnMeta::new(
                new_name.to_string(),
                old_meta.unit,
                old_meta.origin,
                old_meta.nature,
                provenance,
            );
            // Insert the new column metadata
            self.columns.insert(new_name.to_string(), new_meta);
        }

        for binding in [
            &mut self.time,
            &mut self.temperature,
            &mut self.mass,
            &mut self.alpha,
            &mut self.dm_dt,
            &mut self.eta,
            &mut self.deta_dt,
            &mut self.dalpha_dt,
            &mut self.dT_dt,
            &mut self.E,
            &mut self.R2,
        ] {
            if binding.as_deref() == Some(old_name) {
                *binding = Some(new_name.to_string());
            }
        }
    }

    /// Update the active binding after a numerical transform and mark its output
    /// as derived while retaining the source unit and semantic nature.
    pub fn update_schema_for_numeric_transform(&mut self, input: &str, output: &str) {
        self.update_schema(input, output);
        if let Some(metadata) = self.columns.get_mut(output) {
            metadata.origin = ColumnOrigin::NumericDerived;
        }
    }

    /// Adds derivative metadata without moving the source signal's semantic binding.
    /// A first derivative is bound to its matching rate role only when its source
    /// nature is known; higher derivatives remain explicitly untyped.
    pub fn add_derivative_column(&mut self, input: &str, output: &str, order: usize) {
        let Some(source) = self.columns.get(input).cloned() else {
            return;
        };
        let time_unit = self
            .time
            .as_deref()
            .and_then(|name| self.columns.get(name))
            .map(|metadata| metadata.unit);
        let rate_metadata = if order == 1 {
            let rate_nature = match source.nature {
                ColumnNature::Mass => Some((ColumnNature::MassRate, &mut self.dm_dt)),
                ColumnNature::Temperature => Some((ColumnNature::TemperatureRate, &mut self.dT_dt)),
                ColumnNature::Conversion => Some((ColumnNature::ConversionRate, &mut self.deta_dt)),
                ColumnNature::DimensionlessMass => {
                    Some((ColumnNature::DimensionlessMassRate, &mut self.dalpha_dt))
                }
                _ => None,
            };
            rate_nature.map(|(nature, binding)| {
                *binding = Some(output.to_string());
                (
                    nature,
                    time_unit
                        .and_then(|time_unit| source.unit.for_time_base(time_unit).ok())
                        .unwrap_or(Unit::Unknown),
                )
            })
        } else {
            None
        };

        let mut provenance = source.provenance.clone();
        provenance.rename_output(output);
        let metadata = ColumnMeta::new(
            output,
            rate_metadata.map_or(Unit::Unknown, |(_, unit)| unit),
            ColumnOrigin::NumericDerived,
            rate_metadata.map_or(ColumnNature::Unknown, |(nature, _)| nature),
            provenance,
        );
        self.columns.insert(output.to_string(), metadata);
    }

    pub fn drop_schema_record(&mut self, name: &str) {
        if let Some(_) = self.columns.get(name) {
            self.columns.remove(name);
        }

        for binding in [
            &mut self.time,
            &mut self.temperature,
            &mut self.mass,
            &mut self.alpha,
            &mut self.dm_dt,
            &mut self.eta,
            &mut self.deta_dt,
            &mut self.dalpha_dt,
            &mut self.dT_dt,
            &mut self.E,
            &mut self.R2,
        ] {
            if binding.as_deref() == Some(name) {
                *binding = None;
            }
        }
    }
}
//=============================================================================
//             HISTORY OF OPERATIONS
//===============================================================================
#[derive(Clone, Debug)]
pub struct History {
    pub vector_of_operations: Vec<OperationRecord>,
    pub columns_has_changed: Vec<Option<String>>,
}

impl Default for History {
    fn default() -> Self {
        Self::new()
    }
}
impl History {
    pub fn new() -> Self {
        Self {
            vector_of_operations: Vec::new(),
            columns_has_changed: Vec::new(),
        }
    }
    pub fn columns_has_changed(&self) -> Vec<Option<String>> {
        self.columns_has_changed.clone()
    }
    pub fn take_column(&mut self, column_name: &str) -> Option<String> {
        // Find the index of the column name in the columns_has_changed vector
        let column_number = self
            .columns_has_changed
            .iter()
            .position(|col| col.as_ref().map_or(false, |name| name == column_name));

        // If found, take the column name at that position
        if let Some(index) = column_number {
            self.columns_has_changed
                .get_mut(index)
                .and_then(|col| col.take())
        } else {
            None
        }
    }

    pub fn feed_lines(&self) -> Vec<String> {
        self.vector_of_operations
            .iter()
            .map(OperationRecord::feed_line)
            .collect()
    }

    pub fn feed_text(&self) -> String {
        let lines = self.feed_lines();
        if lines.is_empty() {
            "History is empty".to_string()
        } else {
            lines.join("\n")
        }
    }
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ColumnTypes {
    Time,
    Temperature,
    Mass,
    Alpha,
    Dmdt,
    Eta,
    Detadt,
    Dalphadt,
    DTdt,
    Undefined,
    All,
}

#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum AffectedColumns {
    Specific(Vec<String>),
    All,
    Semantic(Vec<ColumnTypes>),
}

impl std::fmt::Display for AffectedColumns {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AffectedColumns::Specific(cols) => write!(f, "specific({})", cols.join(", ")),
            AffectedColumns::All => write!(f, "all"),
            AffectedColumns::Semantic(types) => write!(f, "semantic({:?})", types),
        }
    }
}

#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct OperationRecord {
    pub timestamp: usize,
    pub operation_name: String,
    pub affected_columns: AffectedColumns,
    #[serde(skip)]
    pub expr: Option<Expr>,
    pub description: String,
    pub reversible: bool,
}

impl OperationRecord {
    pub fn feed_line(&self) -> String {
        format!(
            "[{}] {} | {} | affected: {} | reversible: {}",
            self.timestamp,
            self.operation_name,
            self.description,
            self.affected_columns,
            self.reversible
        )
    }
}

impl std::fmt::Display for OperationRecord {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.feed_line())
    }
}

#[derive(Clone, Debug)]
pub struct ColumnHistory {
    pub column_name: String,
    pub operations: Vec<OperationRecord>,
}

impl ColumnHistory {
    pub fn new(column_name: String) -> Self {
        Self {
            column_name,
            operations: Vec::new(),
        }
    }

    pub fn reversible_count(&self) -> usize {
        self.operations.iter().filter(|op| op.reversible).count()
    }

    pub fn irreversible_count(&self) -> usize {
        self.operations.iter().filter(|op| !op.reversible).count()
    }

    pub fn has_irreversible(&self) -> bool {
        self.operations.iter().any(|op| !op.reversible)
    }

    pub fn feed_text(&self) -> String {
        if self.operations.is_empty() {
            format!("Column '{}' has no history", self.column_name)
        } else {
            self.operations
                .iter()
                .map(OperationRecord::feed_line)
                .collect::<Vec<_>>()
                .join("\n")
        }
    }
}

#[derive(Clone)]
pub(crate) struct TGADatasetSnapshot {
    frame: LazyFrame,
    schema: TGASchema,
    oneframeplot: Option<OneFramePlot>,
    columns_has_changed: Vec<Option<String>>,
    operation_index: usize,
}

/// A bounded copy-on-write undo stack. Cloning a dataset shares old snapshots;
/// changing the stack copies only the small deque of `Arc` handles.
#[derive(Clone, Default)]
pub(crate) struct UndoStack {
    entries: Arc<VecDeque<Arc<TGADatasetSnapshot>>>,
}

impl UndoStack {
    const MAX_DEPTH: usize = 20;

    fn push(&mut self, snapshot: TGADatasetSnapshot) {
        let entries = Arc::make_mut(&mut self.entries);
        if entries.len() == Self::MAX_DEPTH {
            entries.pop_front();
        }
        entries.push_back(Arc::new(snapshot));
    }

    fn pop(&mut self) -> Option<TGADatasetSnapshot> {
        let snapshot = Arc::make_mut(&mut self.entries).pop_back()?;
        Some(Arc::try_unwrap(snapshot).unwrap_or_else(|shared| (*shared).clone()))
    }

    fn len(&self) -> usize {
        self.entries.len()
    }

    fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    pub(crate) fn clear(&mut self) {
        self.entries = Arc::new(VecDeque::new());
    }

    #[cfg(test)]
    pub(crate) fn shares_storage_with(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.entries, &other.entries)
    }
}

//================================================================================
//              TGADATASET - MAIN DATA STRUCTURE
//==================================================================================
/// Main entity Plolars-layer
#[derive(Clone)]
pub struct TGADataset {
    pub(crate) frame: LazyFrame,
    pub(crate) schema: TGASchema,
    pub oneframeplot: Option<OneFramePlot>,
    pub history_of_operations: History,
    pub(crate) undo_stack: UndoStack,
    pub(crate) undo_snapshot_latch: bool,
}

impl Default for TGADataset {
    fn default() -> Self {
        Self {
            frame: LazyFrame::default(),
            schema: TGASchema::default(),
            oneframeplot: None,
            history_of_operations: History::default(),
            undo_stack: UndoStack::default(),
            undo_snapshot_latch: false,
        }
    }
}

impl std::fmt::Debug for TGADataset {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TGADataset")
            .field("schema", &DebugSchema(&self.schema))
            .field("frame", &"<LazyFrame>")
            .finish()
    }
}

pub fn expr_into_str(expr: &Expr) -> Expr {
    expr.clone().reverse()
}
/// Helper struct to nicely format the TGASchema for debugging
struct DebugSchema<'a>(&'a TGASchema);

impl<'a> std::fmt::Debug for DebugSchema<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let schema = self.0;
        let mut builder = f.debug_struct("TGASchema");

        // Show all columns with their metadata
        builder.field("columns_count", &schema.columns.len());

        let mut columns_display: Vec<_> = schema
            .columns
            .values()
            .map(|m| format!("{}: {} ({})", m.name, m.unit, format!("{:?}", m.origin)))
            .collect();
        columns_display.sort();
        builder.field("columns", &columns_display);

        // Show bound semantic columns
        builder.field("time", &schema.time);
        builder.field("temperature", &schema.temperature);
        builder.field("mass", &schema.mass);
        builder.field("alpha", &schema.alpha);
        builder.field("dm_dt", &schema.dm_dt);
        builder.field("eta", &schema.eta);
        builder.field("deta_dt", &schema.deta_dt);
        builder.field("dalpha_dt", &schema.dalpha_dt);
        builder.field("dT_dt", &schema.dT_dt);

        builder.finish()
    }
}
impl TGADataset {
    /// Read-only access to the lazy data frame.
    ///
    /// Mutations must go through dataset operations so history and undo remain aligned.
    pub fn frame(&self) -> &LazyFrame {
        &self.frame
    }

    /// Read-only access to column metadata and active bindings.
    pub fn schema(&self) -> &TGASchema {
        &self.schema
    }

    fn ensure_column_is_bindable(&self, name: &str) -> Result<(), TGADomainError> {
        let frame_schema = self.frame.clone().collect_schema()?;
        let dtype = frame_schema
            .get(name)
            .ok_or_else(|| TGADomainError::ColumnNotFound(name.to_string()))?;
        if !self.schema.columns.contains_key(name) {
            return Err(TGADomainError::ColumnNotFound(name.to_string()));
        }
        if !matches!(
            dtype,
            DataType::Int8
                | DataType::Int16
                | DataType::Int32
                | DataType::Int64
                | DataType::UInt8
                | DataType::UInt16
                | DataType::UInt32
                | DataType::UInt64
                | DataType::Float32
                | DataType::Float64
        ) {
            return Err(TGADomainError::NonNumericColumn {
                column: name.to_string(),
                actual_type: dtype.to_string(),
            });
        }
        Ok(())
    }
    //=========================================================================
    // HISTORY HELPERS

    pub fn log_operation(
        &mut self,
        name: &str,
        affected: AffectedColumns,
        expr: Option<Expr>,
        description: String,
        reversible: bool,
    ) {
        let timestamp = self.history_of_operations.vector_of_operations.len();
        self.populate_columns_has_changed(&affected);
        self.history_of_operations
            .vector_of_operations
            .push(OperationRecord {
                timestamp,
                operation_name: name.to_string(),
                affected_columns: affected,
                expr,
                description,
                reversible,
            });
    }

    /// Store a pre-change snapshot so the last mutation can be reverted later.
    /// We keep the snapshot small enough for day-to-day use by limiting the stack depth.
    pub fn push_undo_snapshot(&mut self) {
        if self.undo_snapshot_latch {
            self.undo_snapshot_latch = false;
            return;
        }
        self.undo_stack.push(TGADatasetSnapshot {
            frame: self.frame.clone(),
            schema: self.schema.clone(),
            oneframeplot: self.oneframeplot.clone(),
            columns_has_changed: self.history_of_operations.columns_has_changed.clone(),
            operation_index: self.history_of_operations.vector_of_operations.len(),
        });
    }

    /// Returns `true` when a column name is already occupied in the schema.
    pub(crate) fn has_column_name(&self, name: &str) -> bool {
        self.schema.columns.contains_key(name)
    }

    /// Reject duplicate names before creating a new column.
    pub(crate) fn ensure_column_name_is_available(&self, name: &str) -> Result<(), TGADomainError> {
        if self.has_column_name(name) || self.frame.clone().collect_schema()?.get(name).is_some() {
            Err(TGADomainError::ColumnAlreadyExists(name.to_string()))
        } else {
            Ok(())
        }
    }

    /// Mark the next mutation as part of a composite operation.
    pub(crate) fn suppress_next_undo_snapshot(&mut self) {
        self.undo_snapshot_latch = true;
    }

    /// Seed provenance for columns that are already present in the dataset.
    ///
    /// This keeps older construction paths working while the new metadata model
    /// is being threaded through the codebase.
    pub(crate) fn initialize_column_provenance(&mut self) {
        for (name, meta) in self.schema.columns.iter_mut() {
            if meta.provenance.steps.is_empty() {
                meta.provenance = match meta.origin {
                    ColumnOrigin::Raw => ColumnProvenance::raw(name.clone()),
                    ColumnOrigin::Imported => {
                        ColumnProvenance::imported(name.clone(), name.clone())
                    }
                    ColumnOrigin::PolarsDerived
                    | ColumnOrigin::NumericDerived
                    | ColumnOrigin::Simulated => ColumnProvenance::manual(
                        name.clone(),
                        "initialize_column_provenance",
                        Some("backfilled provenance".to_string()),
                    ),
                };
            }
        }
    }

    /// Return provenance for a single column if we have recorded it.
    pub fn column_provenance(&self, column_name: &str) -> Option<&ColumnProvenance> {
        self.schema
            .columns
            .get(column_name)
            .map(|meta| &meta.provenance)
    }

    /// Human-readable provenance for GUI panels and debugging.
    pub fn column_provenance_text(&self, column_name: &str) -> Option<String> {
        self.column_provenance(column_name)
            .map(ColumnProvenance::feed_text)
    }

    /// Record one transformation step for a column.
    ///
    /// If `source_column` and `target_column` are different, provenance is cloned
    /// from the source and extended with the new step. If the column is modified
    /// in place, the step is appended to the existing chain.
    pub(crate) fn record_column_transform(
        &mut self,
        source_column: &str,
        target_column: &str,
        kind: ColumnTransformKind,
        reversible: bool,
        quality: Option<
            crate::Kinetics::experimental_kinetics::math::ndarray_statistics::FilterQualityReport,
        >,
    ) {
        self.record_column_transform_with_coverage(
            source_column,
            target_column,
            kind,
            reversible,
            quality,
            None,
        );
    }

    pub(crate) fn record_column_transform_with_coverage(
        &mut self,
        source_column: &str,
        target_column: &str,
        kind: ColumnTransformKind,
        reversible: bool,
        quality: Option<
            crate::Kinetics::experimental_kinetics::math::ndarray_statistics::FilterQualityReport,
        >,
        coverage: Option<TransformCoverage>,
    ) {
        self.record_column_transform_with_inputs_and_coverage(
            source_column,
            target_column,
            vec![source_column.to_string()],
            kind,
            reversible,
            quality,
            coverage,
        );
    }

    pub(crate) fn record_column_transform_with_inputs_and_coverage(
        &mut self,
        source_column: &str,
        target_column: &str,
        input_columns: Vec<String>,
        kind: ColumnTransformKind,
        reversible: bool,
        quality: Option<
            crate::Kinetics::experimental_kinetics::math::ndarray_statistics::FilterQualityReport,
        >,
        coverage: Option<TransformCoverage>,
    ) {
        let operation_id = Some(self.history_of_operations.vector_of_operations.len());
        let quality = Some(match quality {
            Some(report) => TransformQuality::computed(report, QualityReference::PreviousStep),
            None => match &kind {
                ColumnTransformKind::SavitzkyGolay { deriv, .. } if *deriv > 0 => {
                    TransformQuality {
                        compared_to: QualityReference::PreviousStep,
                        report: None,
                        status: QualityStatus::NotApplicable(
                            "derivative output is not directly comparable to its source signal"
                                .to_string(),
                        ),
                    }
                }
                _ => TransformQuality::unavailable(
                    QualityReference::PreviousStep,
                    "quality metrics could not be computed for this transformation",
                ),
            },
        });

        if source_column == target_column {
            let entry = self
                .schema
                .columns
                .entry(target_column.to_string())
                .or_insert_with(|| {
                    ColumnMeta::raw(
                        target_column.to_string(),
                        Unit::Unknown,
                        ColumnNature::Unknown,
                    )
                });
            entry.provenance.push_step(
                input_columns,
                target_column.to_string(),
                kind,
                quality,
                operation_id,
                reversible,
            );
            if let Some(step) = entry.provenance.steps.last_mut() {
                step.coverage = coverage;
            }
            return;
        }

        let mut provenance = self
            .schema
            .columns
            .get(source_column)
            .map(|meta| meta.provenance.clone())
            .unwrap_or_else(|| ColumnProvenance::raw(source_column));
        provenance.push_step(
            input_columns,
            target_column.to_string(),
            kind,
            quality,
            operation_id,
            reversible,
        );
        if let Some(step) = provenance.steps.last_mut() {
            step.coverage = coverage;
        }

        if let Some(target_meta) = self.schema.columns.get_mut(target_column) {
            target_meta.provenance = provenance;
        } else {
            self.schema.columns.insert(
                target_column.to_string(),
                ColumnMeta::new(
                    target_column.to_string(),
                    Unit::Unknown,
                    ColumnOrigin::NumericDerived,
                    ColumnNature::Unknown,
                    provenance,
                ),
            );
        }
    }

    /// Returns `true` if there is at least one saved state to undo to.
    pub fn can_undo(&self) -> bool {
        !self.undo_stack.is_empty()
    }

    /// Number of saved snapshots available for undo.
    pub fn undo_depth(&self) -> usize {
        self.undo_stack.len()
    }

    /// Restore the last saved state and add an `undo` record to the audit trail.
    pub fn undo_last(&mut self) -> Result<(), TGADomainError> {
        let Some(snapshot) = self.undo_stack.pop() else {
            return Err(TGADomainError::InvalidOperation(
                "No undo snapshot available".to_string(),
            ));
        };

        let undone = self
            .history_of_operations
            .vector_of_operations
            .get(snapshot.operation_index)
            .cloned();

        self.frame = snapshot.frame;
        self.schema = snapshot.schema;
        self.oneframeplot = snapshot.oneframeplot;
        self.history_of_operations.columns_has_changed = snapshot.columns_has_changed;

        let (affected, description) = if let Some(op) = undone {
            (
                op.affected_columns,
                format!("Reverted operation '{}'", op.operation_name),
            )
        } else {
            (AffectedColumns::All, "Reverted last operation".to_string())
        };

        self.log_operation("undo_last", affected, None, description, true);
        Ok(())
    }

    fn populate_columns_has_changed(&mut self, affected: &AffectedColumns) {
        let cols = match affected {
            AffectedColumns::Specific(cols) => cols.clone(),
            AffectedColumns::All => self.list_of_columns(),
            AffectedColumns::Semantic(types) => {
                let mut result = Vec::new();
                for col in self.list_of_columns() {
                    if types.iter().any(|ct| self.column_matches_type(&col, ct)) {
                        result.push(col);
                    }
                }
                result
            }
        };

        for col in cols {
            if !self
                .history_of_operations
                .columns_has_changed
                .contains(&Some(col.clone()))
            {
                self.history_of_operations
                    .columns_has_changed
                    .push(Some(col));
            }
        }
    }
    ///
    pub fn list_of_columns_to_recalc(&mut self) -> Vec<String> {
        let list_of_columns = self.list_of_columns();
        let mut list_of_columns_to_recalc = Vec::new();
        for col in list_of_columns {
            if let Some(col_to_recalc) = self.take_column(&col) {
                list_of_columns_to_recalc.push(col_to_recalc);
            }
        }
        list_of_columns_to_recalc
    }

    fn column_matches_type(&self, col: &str, ct: &ColumnTypes) -> bool {
        match ct {
            ColumnTypes::Time => self.schema.time.as_deref() == Some(col),
            ColumnTypes::Temperature => self.schema.temperature.as_deref() == Some(col),
            ColumnTypes::Mass => self.schema.mass.as_deref() == Some(col),
            ColumnTypes::Alpha => self.schema.alpha.as_deref() == Some(col),
            ColumnTypes::Dmdt => self.schema.dm_dt.as_deref() == Some(col),
            ColumnTypes::Eta => self.schema.eta.as_deref() == Some(col),
            ColumnTypes::Detadt => self.schema.deta_dt.as_deref() == Some(col),
            ColumnTypes::Dalphadt => self.schema.dalpha_dt.as_deref() == Some(col),
            ColumnTypes::DTdt => self.schema.dT_dt.as_deref() == Some(col),
            ColumnTypes::All => true,
            ColumnTypes::Undefined => false,
        }
    }

    pub fn operations_on_column(&self, col: &str) -> Vec<OperationRecord> {
        let h: Vec<&OperationRecord> = self
            .history_of_operations
            .vector_of_operations
            .iter()
            .filter(|op| match &op.affected_columns {
                AffectedColumns::Specific(cols) => cols.contains(&col.to_string()),
                AffectedColumns::All => true,
                AffectedColumns::Semantic(types) => {
                    types.iter().any(|ct| self.column_matches_type(col, ct))
                }
            })
            .collect();
        h.iter().map(|&op| op.clone()).collect()
    }

    pub fn get_column_history(&self, col: &str) -> ColumnHistory {
        let operations = self.operations_on_column(col).into_iter().collect();
        ColumnHistory {
            column_name: col.to_string(),
            operations,
        }
    }

    pub fn list_of_columns(&self) -> Vec<String> {
        self.schema.columns.keys().cloned().collect()
    }

    pub fn print_operation_history(&self) {
        println!("\n=== Operation History ===");
        for op in &self.history_of_operations.vector_of_operations {
            println!(
                "[{}] {} - {} (reversible: {})",
                op.timestamp, op.operation_name, op.description, op.reversible
            );
            match &op.affected_columns {
                AffectedColumns::Specific(cols) => println!("  Columns: {:?}", cols),
                AffectedColumns::All => println!("  Columns: ALL"),
                AffectedColumns::Semantic(types) => println!("  Semantic: {:?}", types),
            }
        }
    }

    pub fn print_column_history(&self, col: &str) {
        let history = self.get_column_history(col);
        println!("\n=== History for column '{}' ===", col);
        println!("Total operations: {}", history.operations.len());
        println!("Reversible: {}", history.reversible_count());
        println!("Irreversible: {}", history.irreversible_count());
        for op in &history.operations {
            println!(
                "  [{}] {} - {} (reversible: {})",
                op.timestamp, op.operation_name, op.description, op.reversible
            );
        }
    }

    pub fn columns_has_changed(&self) -> Vec<Option<String>> {
        self.history_of_operations.columns_has_changed()
    }
    pub fn take_column(&mut self, column_name: &str) -> Option<String> {
        self.history_of_operations.take_column(column_name)
    }

    //=========================================================================
    // INPUT/OUTPUT
    /// Normalize txt file to csv
    /// ?????????????? txt ????? ? csv ??????
    pub fn normalize_txt_to_csv(input: &Path, output: &Path) -> std::io::Result<()> {
        let input = std::fs::read_to_string(input)?;
        let mut out = String::new();

        for line in input.lines() {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }

            let cols: Vec<&str> = line.split_whitespace().collect();
            out.push_str(&cols.join(","));
            out.push('\n');
        }

        std::fs::write(output, out)?;
        Ok(())
    }
    /// creation of TGA entity
    /// ???????? TGA ???????? ?? CSV ?????
    pub fn from_csv(
        path: &str,
        time_col: &str,
        temp_col: &str,
        mass_col: &str,
    ) -> PolarsResult<Self> {
        let requested_roles = [time_col, temp_col, mass_col]
            .into_iter()
            .collect::<HashSet<_>>();
        if requested_roles.len() != 3 {
            return Err(PolarsError::ComputeError(
                "Time, temperature, and mass must use distinct columns".into(),
            ));
        }
        println!("\n column: {} ", time_col);
        println!("\n column: {} ", temp_col);
        println!("\n column: {} ", mass_col);

        let plpath = PlRefPath::new(path);
        let frame = LazyCsvReader::new(plpath)
            .with_has_header(true)
            .finish()?
            .with_columns(vec![
                col(time_col).cast(DataType::Float64).alias(time_col),
                col(temp_col).cast(DataType::Float64).alias(temp_col),
                col(mass_col).cast(DataType::Float64).alias(mass_col),
            ]);

        let mut columns = HashMap::new();

        columns.insert(
            time_col.to_string(),
            ColumnMeta::raw(time_col, Unit::Second, ColumnNature::Time),
        );

        columns.insert(
            temp_col.into(),
            ColumnMeta::raw(temp_col, Unit::Celsius, ColumnNature::Temperature),
        );

        columns.insert(
            mass_col.to_string(),
            ColumnMeta::raw(mass_col, Unit::Milligram, ColumnNature::Mass),
        );

        let mut dataset = Self {
            frame,
            schema: TGASchema {
                columns,
                time: Some(time_col.into()),
                temperature: Some(temp_col.into()),
                mass: Some(mass_col.into()),
                ..TGASchema::default()
            },
            oneframeplot: None,
            history_of_operations: History::new(),
            undo_stack: UndoStack::default(),
            undo_snapshot_latch: false,
        };
        dataset.initialize_column_provenance();

        dataset.log_operation(
            "from_csv",
            AffectedColumns::Specific(vec![
                time_col.to_string(),
                temp_col.to_string(),
                mass_col.to_string(),
            ]),
            None,
            format!(
                "Imported CSV '{}' with bound columns time='{}', temperature='{}', mass='{}'",
                path, time_col, temp_col, mass_col
            ),
            false,
        );

        Ok(dataset)
    }

    /// Add a numeric column from a user-provided Vec<f64>.
    ///
    /// This is useful for fitted curves or any external numeric results.
    /// The function checks that the vector length matches the dataset height,
    /// then appends the column as `NumericDerived` and logs the operation.
    pub fn add_column_from_vec(
        mut self,
        name: &str,
        unit: Unit,
        nature: ColumnNature,
        data: Vec<f64>,
    ) -> Result<Self, TGADomainError> {
        self.ensure_column_name_is_available(name)?;
        let height = self.frame.clone().collect()?.height();
        if data.len() != height {
            return Err(TGADomainError::InvalidOperation(format!(
                "Column '{}' length {} does not match dataset height {}",
                name,
                data.len(),
                height
            )));
        }

        let series = Series::new(name.into(), data);
        self.push_undo_snapshot();
        self.frame = self.frame.with_column(lit(series));

        self.schema.columns.insert(
            name.to_string(),
            ColumnMeta::new(
                name.to_string(),
                unit,
                ColumnOrigin::NumericDerived,
                nature,
                ColumnProvenance::manual(
                    name,
                    "add_column_from_vec",
                    Some("external numeric data".to_string()),
                ),
            ),
        );

        self.log_operation(
            "add_column_from_vec",
            AffectedColumns::Specific(vec![name.to_string()]),
            None,
            format!("Added numeric column '{}' from Vec<f64>", name),
            true,
        );

        Ok(self)
    }

    /// Add a numeric column whose missing values remain aligned with source rows.
    ///
    /// This is used for derived curves evaluated where X exists while preserving
    /// rows where the source coordinate itself is null.
    pub fn add_optional_column_from_vec(
        mut self,
        name: &str,
        unit: Unit,
        nature: ColumnNature,
        data: Vec<Option<f64>>,
    ) -> Result<Self, TGADomainError> {
        self.ensure_column_name_is_available(name)?;
        let height = self.frame.clone().collect()?.height();
        if data.len() != height {
            return Err(TGADomainError::InvalidOperation(format!(
                "Column '{}' length {} does not match dataset height {}",
                name,
                data.len(),
                height
            )));
        }
        if data
            .iter()
            .flatten()
            .any(|value| !value.is_finite())
        {
            return Err(TGADomainError::InvalidColumnValues {
                column: name.to_string(),
                details: "derived values must be finite or null".to_string(),
                indices: data
                    .iter()
                    .enumerate()
                    .filter_map(|(index, value)| {
                        value.filter(|value| !value.is_finite()).map(|_| index)
                    })
                    .collect(),
            });
        }

        let series = Series::new(name.into(), data);
        self.push_undo_snapshot();
        self.frame = self.frame.with_column(lit(series));
        self.schema.columns.insert(
            name.to_string(),
            ColumnMeta::new(
                name.to_string(),
                unit,
                ColumnOrigin::NumericDerived,
                nature,
                ColumnProvenance::manual(
                    name,
                    "add_optional_column_from_vec",
                    Some("row-aligned numeric data with missing values".to_string()),
                ),
            ),
        );
        self.log_operation(
            "add_optional_column_from_vec",
            AffectedColumns::Specific(vec![name.to_string()]),
            None,
            format!("Added row-aligned numeric column '{}'", name),
            true,
        );
        Ok(self)
    }

    /// Evaluate a one-variable symbolic expression over a numeric source column
    /// and append the result without changing any existing data or bindings.
    pub fn add_formula_column(
        self,
        name: &str,
        x_column: &str,
        expression: &str,
        unit: Unit,
        nature: ColumnNature,
    ) -> Result<Self, TGADomainError> {
        self.add_formula_column_from_columns(
            name,
            &[("x".to_string(), x_column.to_string())],
            expression,
            unit,
            nature,
        )
    }

    /// Evaluate a symbolic expression over several source columns and append
    /// the result only after every input and output row has been validated.
    pub fn add_formula_column_from_columns(
        mut self,
        name: &str,
        variable_columns: &[(String, String)],
        expression: &str,
        unit: Unit,
        nature: ColumnNature,
    ) -> Result<Self, TGADomainError> {
        self.ensure_column_name_is_available(name)?;
        if variable_columns.is_empty() {
            return Err(TGADomainError::InvalidFormula {
                expression: expression.trim().to_string(),
                details: "declare at least one variable and bind it to a source column".to_string(),
            });
        }

        let mut declared_names = Vec::with_capacity(variable_columns.len());
        let mut source_columns = Vec::new();
        for (variable, column) in variable_columns {
            let variable = variable.trim();
            if variable.is_empty() {
                return Err(TGADomainError::InvalidFormula {
                    expression: expression.trim().to_string(),
                    details: "variable names cannot be empty".to_string(),
                });
            }
            if declared_names.iter().any(|existing| existing == variable) {
                return Err(TGADomainError::InvalidFormula {
                    expression: expression.trim().to_string(),
                    details: format!("variable '{variable}' is declared more than once"),
                });
            }
            self.ensure_column_is_bindable(column)?;
            declared_names.push(variable.to_string());
            if !source_columns.contains(column) {
                source_columns.push(column.clone());
            }
        }

        let required_unit = match nature {
            ColumnNature::Time if !unit.is_valid_time_binding_unit() => Some("s, min, or h"),
            ColumnNature::Temperature if !unit.is_valid_temperature_binding_unit() => {
                Some("K or C")
            }
            ColumnNature::Mass if !unit.is_valid_mass_binding_unit() => Some("mV, mg, or g"),
            _ => None,
        };
        if let Some(expected) = required_unit {
            return Err(TGADomainError::IncompatibleUnits {
                operation: "formula column".to_string(),
                expected: format!("{nature:?} output unit ({expected})"),
                actual: unit,
            });
        }

        let expression = expression.trim();
        let parsed = SymbolicExpr::try_parse_expression(expression).map_err(|details| {
            TGADomainError::InvalidFormula {
                expression: expression.to_string(),
                details,
            }
        })?;
        let expression_variables = parsed.all_arguments_are_variables();
        let undeclared = expression_variables
            .iter()
            .filter(|variable| !declared_names.iter().any(|declared| declared == *variable))
            .cloned()
            .collect::<Vec<_>>();
        let unused = declared_names
            .iter()
            .filter(|declared| !expression_variables.contains(declared))
            .cloned()
            .collect::<Vec<_>>();
        let constant_legacy_x = declared_names.len() == 1
            && declared_names[0] == "x"
            && expression_variables.is_empty();
        if !constant_legacy_x && (!undeclared.is_empty() || !unused.is_empty()) {
            return Err(TGADomainError::InvalidFormula {
                expression: expression.to_string(),
                details: format!(
                    "formula variables do not match declared bindings; variables without bindings: [{}]; declared but unused: [{}]",
                    undeclared.join(", "),
                    unused.join(", ")
                ),
            });
        }

        let projection = source_columns
            .iter()
            .map(|column| col(column.as_str()))
            .collect::<Vec<_>>();
        let source = self.frame.clone().select(projection).collect()?;
        let row_count = source.height();
        if row_count == 0 {
            return Err(TGADomainError::InsufficientData {
                available: 0,
                required: 1,
            });
        }

        let mut materialized = Vec::with_capacity(source_columns.len());
        for column_name in &source_columns {
            let column = source.column(column_name)?;
            let cast = column.cast(&DataType::Float64)?;
            let values = cast.f64()?;
            if values.len() != row_count {
                return Err(TGADomainError::DatasetColumnLengthMismatch {
                    column: column_name.clone(),
                    expected: row_count,
                    actual: values.len(),
                });
            }
            let mut values_vec = Vec::with_capacity(row_count);
            for row_index in 0..row_count {
                let Some(value) = values.get(row_index) else {
                    return Err(TGADomainError::InvalidColumnValues {
                        column: column_name.clone(),
                        details: "formula input contains a null value".to_string(),
                        indices: vec![row_index],
                    });
                };
                if !value.is_finite() {
                    return Err(TGADomainError::InvalidColumnValues {
                        column: column_name.clone(),
                        details: "formula input contains a non-finite value".to_string(),
                        indices: vec![row_index],
                    });
                }
                values_vec.push(value);
            }
            materialized.push(values_vec);
        }

        let variable_indices = variable_columns
            .iter()
            .map(|(_, column)| {
                source_columns
                    .iter()
                    .position(|source| source == column)
                    .ok_or_else(|| TGADomainError::ColumnNotFound(column.clone()))
            })
            .collect::<Result<Vec<_>, _>>()?;
        let variable_names = declared_names
            .iter()
            .map(String::as_str)
            .collect::<Vec<_>>();
        let evaluate = parsed.lambdify_borrowed_thread_safe(&variable_names);
        let mut result = Vec::with_capacity(row_count);
        let mut args = Vec::with_capacity(variable_columns.len());
        for row_index in 0..row_count {
            args.clear();
            args.extend(
                variable_indices
                    .iter()
                    .map(|column_index| materialized[*column_index][row_index]),
            );
            let y_value = evaluate(&args);
            if !y_value.is_finite() {
                if variable_columns.len() == 1 && variable_columns[0].0 == "x" {
                    return Err(TGADomainError::FormulaEvaluationFailed {
                        expression: expression.to_string(),
                        row_index,
                        x_value: args[0],
                        result: y_value,
                    });
                }
                let variable_values = declared_names
                    .iter()
                    .zip(&args)
                    .map(|(variable, value)| (variable.clone(), *value))
                    .collect();
                return Err(TGADomainError::FormulaEvaluationFailedForVariables {
                    expression: expression.to_string(),
                    row_index,
                    variable_values,
                    result: y_value,
                });
            }
            result.push(y_value);
        }

        self.push_undo_snapshot();
        self.frame = self
            .frame
            .with_column(lit(Series::new(name.into(), result)));
        let first_source = &variable_columns[0].1;
        let mut provenance = self
            .schema
            .columns
            .get(first_source)
            .map(|meta| meta.provenance.clone())
            .unwrap_or_else(|| ColumnProvenance::raw(first_source));
        provenance.rename_output(name);
        for (_, source_column) in variable_columns {
            if let Some(meta) = self.schema.columns.get(source_column) {
                for root in &meta.provenance.root_columns {
                    if !provenance.root_columns.contains(root) {
                        provenance.root_columns.push(root.clone());
                    }
                }
            } else if !provenance.root_columns.contains(source_column) {
                provenance.root_columns.push(source_column.clone());
            }
        }
        let kind = if variable_columns.len() == 1 && variable_columns[0].0 == "x" {
            ColumnTransformKind::Formula {
                x_column: first_source.clone(),
                expression: expression.to_string(),
            }
        } else {
            ColumnTransformKind::FormulaFromColumns {
                variable_columns: variable_columns.to_vec(),
                expression: expression.to_string(),
            }
        };
        provenance.push_step(
            variable_columns
                .iter()
                .map(|(_, column)| column.clone())
                .collect(),
            name,
            kind,
            Some(TransformQuality::unavailable(
                QualityReference::PreviousStep,
                "formula-derived values are not a filtering quality comparison",
            )),
            Some(self.history_of_operations.vector_of_operations.len()),
            true,
        );
        self.schema.columns.insert(
            name.to_string(),
            ColumnMeta::new(name, unit, ColumnOrigin::NumericDerived, nature, provenance),
        );
        self.log_operation(
            "formula_column",
            AffectedColumns::Specific(vec![name.to_string()]),
            None,
            format!(
                "Created '{name}' from [{}] using {expression}",
                variable_columns
                    .iter()
                    .map(|(variable, column)| format!("{variable}={column}"))
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
            true,
        );
        Ok(self)
    }

    /// Создание TGA сущности из необработанного CSV файла
    pub fn from_csv_raw(path: &Path) -> PolarsResult<Self> {
        let plpath = PlRefPath::try_from_path(path)?;

        let mut frame = LazyCsvReader::new(plpath).with_has_header(true).finish()?;

        let schema = frame.collect_schema()?;

        let mut columns = HashMap::new();
        for name in schema.iter_names() {
            columns.insert(
                name.to_string(),
                ColumnMeta::raw(name.to_string(), Unit::Unknown, ColumnNature::Unknown),
            );
        }

        let mut dataset = Self {
            frame,
            schema: TGASchema {
                columns,
                ..TGASchema::default()
            },
            oneframeplot: None,
            history_of_operations: History::new(),
            undo_stack: UndoStack::default(),
            undo_snapshot_latch: false,
        };
        dataset.initialize_column_provenance();

        dataset.log_operation(
            "from_csv_raw",
            AffectedColumns::All,
            None,
            format!(
                "Imported raw CSV '{}' with {} columns",
                path.display(),
                dataset.schema.columns.len()
            ),
            false,
        );

        Ok(dataset)
    }

    /// Привязка временной колонки с указанием единиц измерения
    /// Build an appended dataset while leaving both source datasets unchanged.
    /// The input schemas and time bindings must match. A time axis that already
    /// continues is preserved; a reset/overlapping axis is shifted by the median
    /// of the last ten target sample intervals.
    pub fn append_continuation(&self, next: &Self) -> Result<Self, TGADomainError> {
        let time_col = self
            .schema
            .time
            .as_deref()
            .ok_or(TGADomainError::TimeNotBound)?;
        let next_time_col = next
            .schema
            .time
            .as_deref()
            .ok_or(TGADomainError::TimeNotBound)?;
        if time_col != next_time_col {
            return Err(TGADomainError::InvalidOperation(format!(
                "Continuation time column '{}' does not match target time column '{}'",
                next_time_col, time_col
            )));
        }
        if self.schema.columns.get(time_col).map(|meta| meta.unit)
            != next.schema.columns.get(next_time_col).map(|meta| meta.unit)
        {
            return Err(TGADomainError::InvalidOperation(
                "Continuation time units must match the target experiment".into(),
            ));
        }

        let target_schema = self.frame.clone().collect_schema()?;
        let next_schema = next.frame.clone().collect_schema()?;
        let target_names = target_schema
            .iter_names()
            .map(|name| name.to_string())
            .collect::<Vec<_>>();
        let next_names = next_schema
            .iter_names()
            .map(|name| name.to_string())
            .collect::<Vec<_>>();
        if target_names != next_names {
            return Err(TGADomainError::InvalidOperation(
                "Continuation columns and their order must match the target experiment".into(),
            ));
        }
        for name in &target_names {
            if target_schema.get(name) != next_schema.get(name) {
                return Err(TGADomainError::InvalidOperation(format!(
                    "Continuation schema differs for column '{name}'"
                )));
            }
        }

        let read_time = |dataset: &Self| -> Result<Vec<f64>, TGADomainError> {
            let frame = dataset
                .frame
                .clone()
                .select([col(time_col).cast(DataType::Float64)])
                .collect()?;
            let time = frame.column(time_col)?.f64()?;
            let values = (0..time.len())
                .map(|index| {
                    time.get(index).filter(|value| value.is_finite()).ok_or_else(|| {
                    TGADomainError::InvalidOperation(format!(
                        "Time column '{time_col}' has null or non-finite value at row {index}"
                    ))
                })
                })
                .collect::<Result<Vec<_>, _>>()?;
            if values.len() < 2 || values.windows(2).any(|pair| pair[1] <= pair[0]) {
                return Err(TGADomainError::TimeNonMonotonic(time_col.to_string()));
            }
            Ok(values)
        };
        let target_time = read_time(self)?;
        let next_time = read_time(next)?;
        let mut steps = target_time
            .windows(2)
            .rev()
            .take(10)
            .map(|pair| pair[1] - pair[0])
            .collect::<Vec<_>>();
        steps.sort_by(f64::total_cmp);
        let step = steps[steps.len() / 2];
        let time_shift = if next_time[0] > target_time[target_time.len() - 1] {
            0.0
        } else {
            target_time[target_time.len() - 1] + step - next_time[0]
        };
        let next_frame = if time_shift == 0.0 {
            next.frame.clone()
        } else {
            next.frame.clone().with_column(
                (col(time_col).cast(DataType::Float64) + lit(time_shift)).alias(time_col),
            )
        };
        let mut result = self.clone();
        result.frame = concat([self.frame.clone(), next_frame], UnionArgs::default())?;
        result.log_operation(
            "append_continuation",
            AffectedColumns::All,
            None,
            format!("Appended continuation; time shift for '{time_col}' is {time_shift}"),
            false,
        );
        Ok(result)
    }

    pub fn bind_time_inplace(&mut self, col: &str, unit: Unit) -> Result<(), TGADomainError> {
        if !unit.is_valid_time_binding_unit() {
            return Err(TGADomainError::InvalidUnitForBinding {
                field: "time",
                unit,
            });
        }
        self.ensure_column_is_bindable(col)?;
        self.push_undo_snapshot();
        let meta = self
            .schema
            .columns
            .get_mut(col)
            .ok_or(TGADomainError::ColumnNotFound(col.into()))?;

        meta.unit = unit;
        meta.nature = ColumnNature::Time;
        self.schema.bind_primary_role(&ColumnRole::Time, col);
        self.record_column_transform(
            col,
            col,
            ColumnTransformKind::Binding {
                role: "time".to_string(),
                unit: format!("{:?}", unit),
            },
            true,
            None,
        );

        self.log_operation(
            "bind_time",
            AffectedColumns::Semantic(vec![ColumnTypes::Time]),
            None,
            format!("Bound time column '{}' with unit {:?}", col, unit),
            true,
        );

        Ok(())
    }

    pub fn bind_time(mut self, col: &str, unit: Unit) -> Result<Self, TGADomainError> {
        self.bind_time_inplace(col, unit)?;
        Ok(self)
    }

    /// Привязка температурной колонки с указанием единиц измерения
    pub fn bind_temperature_inplace(
        &mut self,
        col: &str,
        unit: Unit,
    ) -> Result<(), TGADomainError> {
        if !unit.is_valid_temperature_binding_unit() {
            return Err(TGADomainError::InvalidUnitForBinding {
                field: "temperature",
                unit,
            });
        }
        self.ensure_column_is_bindable(col)?;
        self.push_undo_snapshot();
        let meta = self
            .schema
            .columns
            .get_mut(col)
            .ok_or(TGADomainError::ColumnNotFound(col.into()))?;

        meta.unit = unit;
        meta.nature = ColumnNature::Temperature;
        self.schema.bind_primary_role(&ColumnRole::Temperature, col);
        self.record_column_transform(
            col,
            col,
            ColumnTransformKind::Binding {
                role: "temperature".to_string(),
                unit: format!("{:?}", unit),
            },
            true,
            None,
        );

        self.log_operation(
            "bind_temperature",
            AffectedColumns::Semantic(vec![ColumnTypes::Temperature]),
            None,
            format!("Bound temperature column '{}' with unit {:?}", col, unit),
            true,
        );

        Ok(())
    }

    pub fn bind_temperature(mut self, col: &str, unit: Unit) -> Result<Self, TGADomainError> {
        self.bind_temperature_inplace(col, unit)?;
        Ok(self)
    }

    /// Привязка массовой колонки с указанием единиц измерения
    pub fn bind_mass_inplace(&mut self, col: &str, unit: Unit) -> Result<(), TGADomainError> {
        if !unit.is_valid_mass_binding_unit() {
            return Err(TGADomainError::InvalidUnitForBinding {
                field: "mass",
                unit,
            });
        }
        self.ensure_column_is_bindable(col)?;
        self.push_undo_snapshot();
        let meta = self
            .schema
            .columns
            .get_mut(col)
            .ok_or(TGADomainError::ColumnNotFound(col.into()))?;

        meta.unit = unit;
        meta.nature = ColumnNature::Mass;
        self.schema.bind_primary_role(&ColumnRole::Mass, col);
        self.record_column_transform(
            col,
            col,
            ColumnTransformKind::Binding {
                role: "mass".to_string(),
                unit: format!("{:?}", unit),
            },
            true,
            None,
        );

        self.log_operation(
            "bind_mass",
            AffectedColumns::Semantic(vec![ColumnTypes::Mass]),
            None,
            format!("Bound mass column '{}' with unit {:?}", col, unit),
            true,
        );

        Ok(())
    }

    pub fn bind_mass(mut self, col: &str, unit: Unit) -> Result<Self, TGADomainError> {
        self.bind_mass_inplace(col, unit)?;
        Ok(self)
    }
    /// Привязка колонки с указанием роли, имени и единиц измерения
    pub fn bind_column_inplace(
        &mut self,
        role: ColumnRole,
        name: &str,
        unit: Unit,
    ) -> Result<(), TGADomainError> {
        let role_label = format!("{:?}", &role);
        let valid = match role {
            ColumnRole::Time => unit.is_valid_time_binding_unit(),
            ColumnRole::Temperature => unit.is_valid_temperature_binding_unit(),
            ColumnRole::Mass => unit.is_valid_mass_binding_unit(),
        };
        if !valid {
            let field = match role {
                ColumnRole::Time => "time",
                ColumnRole::Temperature => "temperature",
                ColumnRole::Mass => "mass",
            };
            return Err(TGADomainError::InvalidUnitForBinding { field, unit });
        }
        let nature = match role {
            ColumnRole::Time => ColumnNature::Time,
            ColumnRole::Temperature => ColumnNature::Temperature,
            ColumnRole::Mass => ColumnNature::Mass,
        };
        self.ensure_column_is_bindable(name)?;
        self.push_undo_snapshot();
        let meta = self
            .schema
            .columns
            .get_mut(name)
            .ok_or_else(|| TGADomainError::ColumnNotFound(name.to_string()))?;
        meta.unit = unit;
        meta.nature = nature;

        self.schema.bind_primary_role(&role, name);
        self.record_column_transform(
            name,
            name,
            ColumnTransformKind::Binding {
                role: role_label,
                unit: format!("{:?}", unit),
            },
            true,
            None,
        );

        let affected = match role {
            ColumnRole::Time => AffectedColumns::Semantic(vec![ColumnTypes::Time]),
            ColumnRole::Temperature => AffectedColumns::Semantic(vec![ColumnTypes::Temperature]),
            ColumnRole::Mass => AffectedColumns::Semantic(vec![ColumnTypes::Mass]),
        };

        self.log_operation(
            "bind_column",
            affected,
            None,
            format!("Bound {:?} column '{}' with unit {:?}", role, name, unit),
            true,
        );

        Ok(())
    }

    pub fn bind_column(
        mut self,
        role: ColumnRole,
        name: &str,
        unit: Unit,
    ) -> Result<Self, TGADomainError> {
        self.bind_column_inplace(role, name, unit)?;
        Ok(self)
    }

    /// Экспорт данных в CSV файл с указанием единиц измерения в заголовке
    pub fn to_csv_with_units(&self, path: &Path) -> PolarsResult<()> {
        let df = &mut self.frame.clone().collect()?;
        let mut file = std::fs::File::create(path)?;

        // Meta header
        let meta: Vec<String> = df
            .get_column_names()
            .iter()
            .map(|name| {
                let unit = self
                    .schema
                    .get(name)
                    .map(|m| m.unit.convert_to_string())
                    .unwrap_or("?".into());
                format!("{} [{}]", name, unit)
            })
            .collect();

        writeln!(file, "# KiThe TGA Dataset")?;
        writeln!(file, "# {}", meta.join(", "))?;
        let bindings = CsvSchemaBindings::from_schema(&self.schema, None);
        writeln!(
            file,
            "# Bindings: {}",
            serde_json::to_string(&bindings).map_err(|err| {
                PolarsError::ComputeError(format!("Failed to serialize CSV bindings: {err}").into())
            })?
        )?;
        let names = df
            .get_column_names()
            .iter()
            .map(|name| name.to_string())
            .collect::<Vec<_>>();
        let column_metadata = CsvColumnMetadata::from_schema(&self.schema, &names);
        writeln!(
            file,
            "# Column metadata: {}",
            serde_json::to_string(&column_metadata).map_err(|err| {
                PolarsError::ComputeError(
                    format!("Failed to serialize CSV column metadata: {err}").into(),
                )
            })?
        )?;

        CsvWriter::new(&mut file).include_header(true).finish(df)?;

        Ok(())
    }

    /// Export selected columns to CSV with units encoded in a metadata header, similar to `to_csv_with_units`.
    /// Only the specified columns are exported, and units are taken from the schema.
    /// ??????? ????????? ??????? ? CSV ???? ? ????????? ?????? ?????????.
    /// ??????? ????????? ??????? ? CSV ???? ? ????????? ?????? ?????????.
    /// Экспорт выбранных колонок в CSV файл с указанием единиц измерения
    pub fn to_csv_with_units_selected(&self, path: &Path, columns: &[&str]) -> PolarsResult<()> {
        if columns.is_empty() {
            // Nothing to export
            return Ok(());
        }

        // Validate that requested columns exist in the frame schema
        let schema = self.frame.clone().collect_schema()?;
        for &name in columns {
            if !schema.iter_names().any(|n| n == name) {
                return Err(PolarsError::ColumnNotFound(
                    format!("Column '{}' not found", name).into(),
                ));
            }
        }

        // Build selection in requested order
        let mut select_exprs: Vec<Expr> = Vec::with_capacity(columns.len());
        for &name in columns {
            select_exprs.push(col(name));
            println!("\n column: {} ", name);
        }

        let mut df = self.frame.clone().select(select_exprs).collect()?;

        // Construct metadata header line
        let header_meta: Vec<String> = columns
            .iter()
            .map(|&name| {
                let unit = self
                    .schema
                    .get(name)
                    .map(|m| m.unit.convert_to_string())
                    .unwrap_or_else(|| "?".to_string());
                format!("{} [{}]", name, unit)
            })
            .collect();

        let mut file = std::fs::File::create(path)?;
        writeln!(file, "# KiThe TGA Dataset (selected columns)")?;
        writeln!(file, "# {}", header_meta.join(", "))?;
        let bindings = CsvSchemaBindings::from_schema(&self.schema, Some(columns));
        writeln!(
            file,
            "# Bindings: {}",
            serde_json::to_string(&bindings).map_err(|err| {
                PolarsError::ComputeError(format!("Failed to serialize CSV bindings: {err}").into())
            })?
        )?;
        let column_names = columns
            .iter()
            .map(|name| (*name).to_string())
            .collect::<Vec<_>>();
        let column_metadata = CsvColumnMetadata::from_schema(&self.schema, &column_names);
        writeln!(
            file,
            "# Column metadata: {}",
            serde_json::to_string(&column_metadata).map_err(|err| {
                PolarsError::ComputeError(
                    format!("Failed to serialize CSV column metadata: {err}").into(),
                )
            })?
        )?;

        CsvWriter::new(&mut file)
            .include_header(true)
            .finish(&mut df)?;
        Ok(())
    }

    /// Создание TGA сущности из CSV файла с единицами измерения
    pub fn from_csv_with_units(path: &Path) -> PolarsResult<Self> {
        let text = std::fs::read_to_string(path)?;
        let mut lines = text.lines().peekable();

        lines.next(); // "# KiThe TGA Dataset"
        let meta_line = lines.next().ok_or_else(|| {
            PolarsError::ComputeError("Missing column metadata line in TGA CSV".into())
        })?;
        let meta_line = meta_line.strip_prefix("# ").ok_or_else(|| {
            PolarsError::ComputeError("Malformed column metadata line in TGA CSV".into())
        })?;

        let mut names = Vec::new();
        let mut units = Vec::new();

        for entry in meta_line.split(',') {
            let (name, unit_with_bracket) = entry.trim().split_once('[').ok_or_else(|| {
                PolarsError::ComputeError(
                    format!("Malformed column metadata entry '{entry}'").into(),
                )
            })?;
            let unit = unit_with_bracket.strip_suffix(']').ok_or_else(|| {
                PolarsError::ComputeError(
                    format!("Malformed unit in metadata entry '{entry}'").into(),
                )
            })?;
            names.push(name.trim().to_string());
            units.push(Unit::parse(unit)?);
        }

        let mut bindings = None;
        let mut column_metadata = None;
        while let Some(line) = lines.peek().copied() {
            if let Some(json) = line.strip_prefix("# Bindings: ") {
                lines.next();
                bindings = Some(serde_json::from_str::<CsvSchemaBindings>(json).map_err(
                    |err| {
                        PolarsError::ComputeError(format!("Malformed CSV bindings: {err}").into())
                    },
                )?);
            } else if let Some(json) = line.strip_prefix("# Column metadata: ") {
                lines.next();
                column_metadata = Some(
                    serde_json::from_str::<Vec<CsvColumnMetadata>>(json).map_err(|err| {
                        PolarsError::ComputeError(
                            format!("Malformed CSV column metadata: {err}").into(),
                        )
                    })?,
                );
            } else {
                break;
            }
        }

        let data = lines.collect::<Vec<_>>().join("\n");
        let tmp = tempfile::NamedTempFile::new()?;
        std::fs::write(tmp.path(), data)?;

        let plpath = PlRefPath::try_from_path(tmp.path())?;
        // Materialize while the temporary CSV still exists, then release the
        // file normally; the returned lazy frame owns the in-memory data.
        let frame = LazyCsvReader::new(plpath)
            .with_has_header(true)
            .finish()?
            .collect()?
            .lazy();

        let mut schema = TGASchema::from_columns(names, units)?;
        if let Some(column_metadata) = column_metadata {
            CsvColumnMetadata::apply_all(column_metadata, &mut schema)?;
        }
        if let Some(bindings) = bindings {
            bindings.apply(&mut schema)?;
        }

        let mut dataset = Self {
            frame,
            schema,
            oneframeplot: None,
            history_of_operations: History::new(),
            undo_stack: UndoStack::default(),
            undo_snapshot_latch: false,
        };
        dataset.initialize_column_provenance();

        dataset.log_operation(
            "from_csv_with_units",
            AffectedColumns::All,
            None,
            format!(
                "Imported CSV '{}' with explicit units in header",
                path.display()
            ),
            false,
        );

        Ok(dataset)
    }
    /// There are 2 functions to read and parse from_csv_raw a function to read raw files with no metadata and headers and
    /// from_csv_with_units. This is a wrapper function from_csv_universal which recognizes if there in the file headers and call
    /// from_csv_with_units otherwise from_csv_raw
    /// Универсальная функция чтения CSV файлов (с или без единиц измерения)
    pub fn from_csv_universal(path: &Path) -> PolarsResult<Self> {
        let extension = path.extension().and_then(|ext| ext.to_str()).unwrap_or("");

        // If it's a txt file, normalize it to CSV first
        if extension.eq_ignore_ascii_case("txt") {
            let temp_file = tempfile::NamedTempFile::new()?;
            let temp_path = temp_file.path().to_path_buf();

            // Normalize TXT to CSV
            Self::normalize_txt_to_csv(path, &temp_path)?;

            // Process the normalized CSV file
            let result = Self::from_csv_universal_inner(&temp_path)?;

            // Keep temp file alive until processing is done
            std::mem::forget(temp_file);
            return Ok(result);
        }

        // For non-TXT files, proceed with original logic
        Self::from_csv_universal_inner(path)
    }

    /// Inner function that contains the original logic from from_csv_universal
    fn from_csv_universal_inner(path: &Path) -> PolarsResult<Self> {
        let text = std::fs::read_to_string(path)?;
        let mut lines = text.lines().map(str::trim).filter(|l| !l.is_empty());

        let first = lines.next().unwrap_or_default();
        let second = lines.next().unwrap_or_default();

        let has_units_header = first.starts_with("# KiThe TGA Dataset")
            && second.starts_with("# ")
            && second.contains('[')
            && second.contains(']');

        if has_units_header {
            Self::from_csv_with_units(path)
        } else {
            Self::from_csv_raw(path)
        }
    }

    //==============================================================
    // RATES
    /// Вычисление производной с заданными параметрами
    pub fn derive_rate0(
        self,
        source_col: &str,
        new_col: &str,
        out_meta: ColumnMeta,
    ) -> Result<Self, TGADomainError> {
        self.derive_rate0_with_gap_policy(source_col, new_col, out_meta, TimeGapPolicy::default())
    }

    /// Derive a column with an explicit policy for large gaps in the bound time axis.
    pub fn derive_rate0_with_gap_policy(
        mut self,
        source_col: &str,
        new_col: &str,
        out_meta: ColumnMeta,
        gap_policy: TimeGapPolicy,
    ) -> Result<Self, TGADomainError> {
        self.ensure_column_name_is_available(new_col)?;
        let time = self
            .schema
            .time
            .as_ref()
            .ok_or(TGADomainError::TimeNotBound)?
            .clone();
        let time_unit = self
            .schema
            .columns
            .get(&time)
            .map(|meta| meta.unit)
            .ok_or(TGADomainError::ColumnNotFound(time.clone()))?;

        self.schema
            .columns
            .get(source_col)
            .ok_or(TGADomainError::ColumnNotFound(source_col.into()))?;
        let rate_expr = self.derivative_expr(source_col, &time, new_col, gap_policy)?;
        self.push_undo_snapshot();
        self.frame = self.frame.with_column(rate_expr.clone());

        let out_unit = out_meta.unit.for_time_base(time_unit)?;
        let mut out_meta = out_meta;
        out_meta.unit = out_unit;
        self.schema.columns.insert(new_col.into(), out_meta);

        self.log_operation(
            "derive_rate0",
            AffectedColumns::Specific(vec![new_col.to_string()]),
            Some(rate_expr),
            format!(
                "Computed rate {} from {} with unit {:?}; time-gap policy {:?}",
                new_col, source_col, out_unit, gap_policy
            ),
            true,
        );

        Ok(self)
    }
    /// Вычисление производной с автоматическим определением единиц измерения
    pub fn derive_rate(
        self,
        source_col: &str,
        new_col: &str,
        new_col_nature: ColumnNature,
    ) -> Result<Self, TGADomainError> {
        self.derive_rate_with_gap_policy(
            source_col,
            new_col,
            new_col_nature,
            TimeGapPolicy::default(),
        )
    }

    /// Derive a rate with an explicit policy for large gaps in the bound time axis.
    pub fn derive_rate_with_gap_policy(
        mut self,
        source_col: &str,
        new_col: &str,
        new_col_nature: ColumnNature,
        gap_policy: TimeGapPolicy,
    ) -> Result<Self, TGADomainError> {
        self.ensure_column_name_is_available(new_col)?;
        let time = self
            .schema
            .time
            .as_ref()
            .ok_or(TGADomainError::TimeNotBound)?
            .clone();
        let time_unit = self
            .schema
            .columns
            .get(&time)
            .map(|meta| meta.unit)
            .ok_or(TGADomainError::ColumnNotFound(time.clone()))?;

        let src_meta = self
            .schema
            .columns
            .get(source_col)
            .ok_or(TGADomainError::ColumnNotFound(source_col.into()))?;

        let out_unit = src_meta.unit.for_time_base(time_unit)?;
        let rate_expr = self.derivative_expr(source_col, &time, new_col, gap_policy)?;
        self.push_undo_snapshot();
        self.frame = self.frame.with_column(rate_expr.clone());

        self.schema.columns.insert(
            new_col.into(),
            ColumnMeta::new(
                new_col.to_string(),
                out_unit,
                ColumnOrigin::PolarsDerived,
                new_col_nature,
                ColumnProvenance::manual(
                    new_col,
                    "derive_rate",
                    Some(format!("derived from {}", source_col)),
                ),
            ),
        );

        match new_col_nature {
            ColumnNature::MassRate => self.schema.dm_dt = Some(new_col.to_string()),
            ColumnNature::TemperatureRate => self.schema.dT_dt = Some(new_col.to_string()),
            ColumnNature::ConversionRate => self.schema.deta_dt = Some(new_col.to_string()),
            ColumnNature::DimensionlessMassRate => {
                self.schema.dalpha_dt = Some(new_col.to_string())
            }
            _ => {}
        }

        self.log_operation(
            "derive_rate",
            AffectedColumns::Specific(vec![new_col.to_string()]),
            Some(rate_expr),
            format!(
                "Computed rate {} from {} with unit {:?}; time-gap policy {:?}",
                new_col, source_col, out_unit, gap_policy
            ),
            true,
        );

        Ok(self)
    }

    /// Build a nonuniform three-point derivative expression without dropping rows.
    fn derivative_expr(
        &self,
        source_col: &str,
        time_col: &str,
        new_col: &str,
        gap_policy: TimeGapPolicy,
    ) -> Result<Expr, TGADomainError> {
        let max_interval = match gap_policy {
            TimeGapPolicy::MedianStepMultiple(factor) => {
                if !factor.is_finite() || factor <= 0.0 {
                    return Err(TGADomainError::InvalidFilterParameters {
                        filter: "time derivative".into(),
                        details: "median-step gap factor must be finite and positive".into(),
                    });
                }
                let limit = self.median_time_step(time_col)? * factor;
                if !limit.is_finite() || limit <= 0.0 {
                    return Err(TGADomainError::InvalidFilterParameters {
                        filter: "time derivative".into(),
                        details: "computed maximum time interval is not finite and positive".into(),
                    });
                }
                Some(limit)
            }
            TimeGapPolicy::MaxInterval(interval) => {
                if !interval.is_finite() || interval <= 0.0 {
                    return Err(TGADomainError::InvalidFilterParameters {
                        filter: "time derivative".into(),
                        details: "maximum time interval must be finite and positive".into(),
                    });
                }
                Some(interval)
            }
            TimeGapPolicy::Allow => None,
        };

        let previous_step = col(time_col) - col(time_col).shift(lit(1));
        let next_step = col(time_col).shift(lit(-1)) - col(time_col);
        let previous_value = col(source_col).shift(lit(1));
        let current_value = col(source_col);
        let next_value = col(source_col).shift(lit(-1));
        let sum_steps = previous_step.clone() + next_step.clone();

        let mut valid = previous_step
            .clone()
            .gt(lit(0.0))
            .and(previous_step.clone().lt(lit(f64::INFINITY)))
            .and(next_step.clone().gt(lit(0.0)))
            .and(next_step.clone().lt(lit(f64::INFINITY)));
        if let Some(max_interval) = max_interval {
            valid = valid
                .and(previous_step.clone().lt_eq(lit(max_interval)))
                .and(next_step.clone().lt_eq(lit(max_interval)));
        }
        valid = valid
            .and(sum_steps.clone().gt(lit(0.0)))
            .and(sum_steps.clone().lt(lit(f64::INFINITY)));

        let first_weight = -next_step.clone() / (previous_step.clone() * sum_steps.clone());
        let center_weight = (next_step.clone() - previous_step.clone())
            / (previous_step.clone() * next_step.clone());
        let last_weight = previous_step.clone() / (next_step.clone() * sum_steps);
        let derivative = first_weight * previous_value
            + center_weight * current_value
            + last_weight * next_value;
        valid = valid
            .and(derivative.clone().gt(lit(-f64::MAX)))
            .and(derivative.clone().lt(lit(f64::MAX)));

        Ok(when(valid)
            .then(derivative)
            .otherwise(lit(NULL))
            .alias(new_col))
    }

    /// Median positive interval between adjacent finite time values.
    fn median_time_step(&self, time_col: &str) -> Result<f64, TGADomainError> {
        let frame = self
            .frame
            .clone()
            .select([col(time_col).cast(DataType::Float64)])
            .collect()?;
        let values = frame.column(time_col)?.f64()?;
        let mut intervals = Vec::with_capacity(values.len().saturating_sub(1));
        let mut previous: Option<f64> = None;
        for index in 0..values.len() {
            match values.get(index).filter(|value| value.is_finite()) {
                Some(current) => {
                    if let Some(previous) = previous {
                        let interval = current - previous;
                        if interval.is_finite() && interval > 0.0 {
                            intervals.push(interval);
                        }
                    }
                    previous = Some(current);
                }
                None => previous = None,
            }
        }

        if intervals.is_empty() {
            return Err(TGADomainError::InvalidOperation(format!(
                "Cannot infer typical sampling interval from time column '{time_col}'"
            )));
        }
        let middle = intervals.len() / 2;
        intervals.select_nth_unstable_by(middle, f64::total_cmp);
        Ok(intervals[middle])
    }

    /// Вычисление скорости изменения массы
    pub fn derive_mass_rate_from_column(
        self,
        source_col: &str,
        new_col: &str,
    ) -> Result<Self, TGADomainError> {
        let mut updated = self.derive_rate(source_col, new_col, ColumnNature::MassRate)?;
        updated.schema.dm_dt = Some(new_col.to_string());
        Ok(updated)
    }

    /// Вычисление скорости изменения массы
    pub fn derive_mass_rate(self, new_col: &str) -> Result<Self, TGADomainError> {
        let mass = self
            .schema
            .mass
            .as_ref()
            .ok_or(TGADomainError::MassNotBound)?
            .clone();
        self.derive_mass_rate_from_column(&mass, new_col)
    }

    /// Вычисление скорости изменения температуры
    pub fn derive_temperature_rate_from_column(
        self,
        source_col: &str,
        new_col: &str,
    ) -> Result<Self, TGADomainError> {
        let start = std::time::Instant::now();
        let mut updated = self.derive_rate(source_col, new_col, ColumnNature::TemperatureRate)?;
        updated.schema.dT_dt = Some(new_col.to_string());
        info!(
            "Derived temperature rate in {:?} ms",
            start.elapsed().as_millis()
        );
        Ok(updated)
    }

    /// Вычисление скорости изменения температуры
    pub fn derive_temperature_rate(self, new_col: &str) -> Result<Self, TGADomainError> {
        let temp = self
            .schema
            .temperature
            .as_ref()
            .ok_or(TGADomainError::TemperatureNotBound)?
            .clone();
        self.derive_temperature_rate_from_column(&temp, new_col)
    }
    /// Вычисление безразмерной скорости изменения
    pub fn derive_dimensionless_rate(
        self,
        col_name: &str,
        out_name: &str,
    ) -> Result<Self, TGADomainError> {
        let out_meta = ColumnMeta::new(
            out_name.to_string(),
            Unit::PerSecond,
            ColumnOrigin::PolarsDerived,
            ColumnNature::DimensionlessMassRate,
            ColumnProvenance::manual(
                out_name,
                "derive_dimensionless_rate",
                Some(format!("derived from {}", col_name)),
            ),
        );
        let (mut updated, is_conversion_rate) = if self.schema.eta.is_some() {
            (self.derive_rate0(col_name, out_name, out_meta)?, true)
        } else if self.schema.alpha.is_some() {
            (self.derive_rate0(col_name, out_name, out_meta)?, false)
        } else {
            return Err(TGADomainError::NoDimensionless);
        };
        if is_conversion_rate {
            updated.schema.deta_dt = Some(out_name.to_string());
        } else {
            updated.schema.dalpha_dt = Some(out_name.to_string());
        }
        Ok(updated)
    }

    /// `deta/dt` for conversion `eta = 1 - alpha`.
    pub fn derive_deta_dt(self, out_name: &str) -> Result<Self, TGADomainError> {
        let start = Instant::now();
        let out_meta = ColumnMeta::new(
            out_name.to_string(),
            Unit::PerSecond,
            ColumnOrigin::PolarsDerived,
            ColumnNature::ConversionRate,
            ColumnProvenance::manual(
                out_name,
                "derive_deta_dt",
                Some("derived from eta".to_string()),
            ),
        );
        let eta_col = self
            .schema
            .eta
            .as_ref()
            .ok_or(TGADomainError::EtaNotFound)?
            .clone();
        let mut updated = self.derive_rate0(&eta_col, out_name, out_meta)?;
        updated.schema.deta_dt = Some(out_name.to_string());
        info!("Derived deta_dt in {:?} ms", start.elapsed().as_millis());
        Ok(updated)
    }

    /// `dalpha/dt` for relative mass `alpha = m / m0`.
    pub fn derive_dalpha_dt(self, out_name: &str) -> Result<Self, TGADomainError> {
        let start = Instant::now();
        let out_meta = ColumnMeta::new(
            out_name.to_string(),
            Unit::PerSecond,
            ColumnOrigin::PolarsDerived,
            ColumnNature::DimensionlessMassRate,
            ColumnProvenance::manual(
                out_name,
                "derive_dalpha_dt",
                Some("derived from alpha".to_string()),
            ),
        );
        let alpha_col = self
            .schema
            .alpha
            .as_ref()
            .ok_or(TGADomainError::AlphaNotFound)?
            .clone();
        let mut updated = self.derive_rate0(&alpha_col, out_name, out_meta)?;
        updated.schema.dalpha_dt = Some(out_name.to_string());
        info!("Derived dalpha_dt in {:?} ms", start.elapsed().as_millis());
        Ok(updated)
    }

    pub fn drop_nulls(&mut self) -> Result<(), TGADomainError> {
        self.push_undo_snapshot();
        self.frame = self.frame.clone().drop_nulls(None);
        self.log_operation(
            "drop_nulls",
            AffectedColumns::All,
            None,
            "Dropped null rows from the dataset".to_string(),
            true,
        );
        Ok(())
    }

    pub fn get_column_by_nature(
        &self,
        nature: ColumnNature,
    ) -> Result<Option<String>, TGADomainError> {
        let schema_binding = match nature {
            ColumnNature::Time => Some(self.schema.time.as_deref()),
            ColumnNature::Temperature => Some(self.schema.temperature.as_deref()),
            ColumnNature::Mass => Some(self.schema.mass.as_deref()),
            ColumnNature::Concentration => None,
            ColumnNature::DimensionlessMass => Some(self.schema.alpha.as_deref()),
            ColumnNature::Conversion => Some(self.schema.eta.as_deref()),
            ColumnNature::MassRate => Some(self.schema.dm_dt.as_deref()),
            ColumnNature::ConversionRate => Some(self.schema.deta_dt.as_deref()),
            ColumnNature::TemperatureRate => Some(self.schema.dT_dt.as_deref()),
            ColumnNature::DimensionlessMassRate => Some(self.schema.dalpha_dt.as_deref()),
            ColumnNature::ActivationEnergy => Some(self.schema.E.as_deref()),
            ColumnNature::R2 => Some(self.schema.R2.as_deref()),
            ColumnNature::PredexFactor | ColumnNature::FittedCurve | ColumnNature::Unknown => None,
        };

        if let Some(binding) = schema_binding {
            return Ok(binding.map(str::to_owned));
        }

        let matches = self
            .schema
            .columns
            .values()
            .filter(|meta| meta.nature == nature)
            .map(|meta| meta.name.clone())
            .collect::<Vec<_>>();
        match matches.as_slice() {
            [] => Ok(None),
            [name] => Ok(Some(name.clone())),
            _ => Err(TGADomainError::AmbiguousColumnNature {
                nature,
                columns: matches,
            }),
        }
    }
    pub fn get_columns_by_nature(
        &self,
        nature: Vec<ColumnNature>,
    ) -> Result<Vec<Option<String>>, TGADomainError> {
        nature
            .into_iter()
            .map(|nature| self.get_column_by_nature(nature))
            .collect()
    }
}

#[cfg(test)]
mod schema_constructor_tests {
    use super::{ColumnNature, ColumnOrigin, TGASchema, Unit};

    #[test]
    fn from_columns_rejects_mismatched_name_and_unit_counts() {
        let err = TGASchema::from_columns(vec!["time".into()], Vec::<Unit>::new())
            .err()
            .unwrap();
        assert!(err.to_string().contains("1 names but 0 units"));
    }

    #[test]
    fn from_columns_infers_unique_roles_from_headers_not_positions() {
        let schema = TGASchema::from_columns(
            vec!["mass".into(), "aux".into(), "T".into(), "time".into()],
            vec![Unit::Milligram, Unit::Unknown, Unit::Celsius, Unit::Second],
        )
        .unwrap();

        assert_eq!(schema.time.as_deref(), Some("time"));
        assert_eq!(schema.temperature.as_deref(), Some("T"));
        assert_eq!(schema.mass.as_deref(), Some("mass"));
        assert_eq!(schema.columns["mass"].nature, ColumnNature::Mass);
        assert_eq!(schema.columns["T"].nature, ColumnNature::Temperature);
        assert_eq!(schema.columns["aux"].nature, ColumnNature::Unknown);
        assert!(
            schema
                .columns
                .values()
                .all(|meta| meta.origin == ColumnOrigin::Imported)
        );
    }

    #[test]
    fn from_columns_leaves_ambiguous_roles_unbound() {
        let schema = TGASchema::from_columns(
            vec![
                "time".into(),
                "t".into(),
                "temperature".into(),
                "mass".into(),
            ],
            vec![Unit::Second, Unit::Second, Unit::Celsius, Unit::Milligram],
        )
        .unwrap();

        assert_eq!(schema.time, None);
        assert_eq!(schema.columns["time"].nature, ColumnNature::Unknown);
        assert_eq!(schema.columns["t"].nature, ColumnNature::Unknown);
        assert_eq!(schema.temperature.as_deref(), Some("temperature"));
        assert_eq!(schema.mass.as_deref(), Some("mass"));
    }
}
//==============================================================
//numerical layer
#[derive(Debug)]
pub struct NumericBlock {
    pub grid: Arc<Vec<f64>>, // time or temperature
    pub columns: HashMap<String, Arc<Vec<f64>>>,
}

/// A row-aligned, nullable preview for UI tables. Unlike `materialize`, this
/// preserves source row indices and does not discard incomplete rows.
#[derive(Debug, Clone, PartialEq)]
pub struct PreviewRows {
    pub row_indices: Vec<usize>,
    pub columns: HashMap<String, Vec<Option<f64>>>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RowSearchDirection {
    Forward,
    Backward,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct NumericRowMatch {
    pub row_index: usize,
    pub value: f64,
}

#[derive(Debug, Clone, PartialEq)]
pub struct TimeOrderSummary {
    pub duplicate_count: usize,
    pub decreasing_count: usize,
    pub duplicate_examples: Vec<TimeOrderViolation>,
    pub decreasing_examples: Vec<TimeOrderViolation>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ColumnDataQualityReport {
    pub column: String,
    pub row_count: usize,
    pub finite_count: usize,
    pub null_count: usize,
    pub nan_count: usize,
    pub infinite_count: usize,
    pub finite_min: Option<f64>,
    pub finite_max: Option<f64>,
    pub time_order: Option<TimeOrderSummary>,
}

fn escape_tsv_field(value: &str) -> String {
    if value.contains(['\t', '\n', '\r', '"']) {
        format!("\"{}\"", value.replace('"', "\"\""))
    } else {
        value.to_string()
    }
}

impl TGADataset {
    /// Finds one finite numeric value in a column without materializing the full column.
    /// Forward search returns the first match after `from_row`; backward search returns
    /// the last match before it. With no starting row, search begins at the relevant end.
    pub fn find_numeric_row(
        &self,
        column: &str,
        target: f64,
        tolerance: f64,
        from_row: Option<usize>,
        direction: RowSearchDirection,
    ) -> PolarsResult<Option<NumericRowMatch>> {
        if !target.is_finite() || !tolerance.is_finite() || tolerance < 0.0 {
            return Err(PolarsError::ComputeError(
                "Search target must be finite and tolerance must be finite and non-negative".into(),
            ));
        }
        let from_row = from_row.map(u64::try_from).transpose().map_err(|_| {
            PolarsError::ComputeError("Search row index exceeds UInt64 range".into())
        })?;

        let mut row_index_name = "__column_manager_source_row".to_string();
        while self.schema.columns.contains_key(&row_index_name) {
            row_index_name.push('_');
        }

        let row_index = col(&row_index_name).cast(DataType::UInt64);
        let mut query = self
            .frame
            .clone()
            .select([col(column)])
            .with_row_index(row_index_name.clone(), None);
        let matches_target = col(column)
            .is_finite()
            .and(col(column).gt_eq(lit(target - tolerance)))
            .and(col(column).lt_eq(lit(target + tolerance)));
        let row_index_u64 = row_index.clone();
        let matches_from = match (direction, from_row) {
            (RowSearchDirection::Forward, Some(index)) => row_index_u64.gt(lit(index)),
            (RowSearchDirection::Backward, Some(index)) => row_index_u64.lt(lit(index)),
            (_, None) => lit(true),
        };
        query = query.filter(matches_target.and(matches_from));

        let (row_aggregate, value_aggregate) = match direction {
            RowSearchDirection::Forward => (row_index.first(), col(column).first()),
            RowSearchDirection::Backward => (row_index.last(), col(column).last()),
        };
        let result = query
            .select([
                row_aggregate.alias("source_row"),
                value_aggregate.alias("matched_value"),
            ])
            .collect()?;
        let rows = result.column("source_row")?.u64()?;
        let values = result.column("matched_value")?.f64()?;
        match (rows.get(0), values.get(0)) {
            (Some(row_index), Some(value)) => Ok(Some(NumericRowMatch {
                row_index: usize::try_from(row_index).map_err(|_| {
                    PolarsError::ComputeError("Matched row index exceeds usize range".into())
                })?,
                value,
            })),
            _ => Ok(None),
        }
    }

    /// Reads a bounded range of original rows without collecting the rest of the frame.
    /// Nulls and row alignment are preserved for every requested column.
    pub fn preview_rows_page(
        &self,
        columns: &[&str],
        offset: usize,
        limit: usize,
    ) -> PolarsResult<PreviewRows> {
        let offset = i64::try_from(offset).map_err(|_| {
            PolarsError::ComputeError("Preview row offset exceeds the supported range".into())
        })?;
        let limit = u32::try_from(limit).map_err(|_| {
            PolarsError::ComputeError("Preview page size exceeds the supported range".into())
        })?;
        let expressions: Vec<_> = columns.iter().map(|name| col(*name)).collect();
        let df = self
            .frame
            .clone()
            .select(expressions)
            .slice(offset, limit)
            .collect()?;
        let row_indices = (0..df.height())
            .map(|index| offset as usize + index)
            .collect();
        let mut page = HashMap::with_capacity(columns.len());
        for name in columns {
            let series = df.column(name)?.f64()?;
            page.insert(
                (*name).to_string(),
                (0..df.height()).map(|row| series.get(row)).collect(),
            );
        }
        Ok(PreviewRows {
            row_indices,
            columns: page,
        })
    }

    /// Exports one complete numeric column as TSV, preserving null rows and source indices.
    pub fn numeric_column_tsv(&self, column: &str) -> PolarsResult<(String, usize)> {
        let metadata = self
            .schema
            .columns
            .get(column)
            .ok_or_else(|| PolarsError::ColumnNotFound(column.to_string().into()))?;
        let frame = self.frame.clone().select([col(column)]).collect()?;
        let values = frame.column(column)?.f64()?;
        let mut output = String::with_capacity(frame.height().saturating_mul(24));
        let escaped_name = escape_tsv_field(column);
        let _ = writeln!(output, "source_row\t{escaped_name} [{:?}]", metadata.unit);
        for row in 0..frame.height() {
            let value = values
                .get(row)
                .map(|value| value.to_string())
                .unwrap_or_else(|| "null".to_string());
            let _ = writeln!(output, "{row}\t{value}");
        }
        Ok((output, frame.height()))
    }

    /// Scans one numeric column once and returns compact diagnostics without retaining all bad rows.
    pub fn numeric_column_diagnostics(
        &self,
        column: &str,
    ) -> PolarsResult<ColumnDataQualityReport> {
        const MAX_ORDER_EXAMPLES: usize = 3;

        let frame = self.frame.clone().select([col(column)]).collect()?;
        let values = frame.column(column)?.f64()?;
        let is_time_column = self.schema.time.as_deref() == Some(column);
        let mut finite_count = 0usize;
        let mut null_count = 0usize;
        let mut nan_count = 0usize;
        let mut infinite_count = 0usize;
        let mut finite_min: Option<f64> = None;
        let mut finite_max: Option<f64> = None;
        let mut previous_time: Option<(usize, f64)> = None;
        let mut time_order = is_time_column.then_some(TimeOrderSummary {
            duplicate_count: 0,
            decreasing_count: 0,
            duplicate_examples: Vec::new(),
            decreasing_examples: Vec::new(),
        });

        for (row, value) in values.iter().enumerate() {
            let Some(value) = value else {
                null_count = null_count.saturating_add(1);
                continue;
            };
            if value.is_nan() {
                nan_count = nan_count.saturating_add(1);
                continue;
            }
            if !value.is_finite() {
                infinite_count = infinite_count.saturating_add(1);
                continue;
            }

            finite_count = finite_count.saturating_add(1);
            finite_min = Some(finite_min.map_or(value, |current| current.min(value)));
            finite_max = Some(finite_max.map_or(value, |current| current.max(value)));

            if let (Some((_, previous)), Some(summary)) = (previous_time, time_order.as_mut()) {
                let examples = if value == previous {
                    summary.duplicate_count = summary.duplicate_count.saturating_add(1);
                    Some(&mut summary.duplicate_examples)
                } else if value < previous {
                    summary.decreasing_count = summary.decreasing_count.saturating_add(1);
                    Some(&mut summary.decreasing_examples)
                } else {
                    None
                };
                if let Some(examples) = examples {
                    if examples.len() < MAX_ORDER_EXAMPLES {
                        examples.push(TimeOrderViolation {
                            index: row,
                            previous,
                            current: value,
                        });
                    }
                }
            }
            if is_time_column {
                previous_time = Some((row, value));
            }
        }

        Ok(ColumnDataQualityReport {
            column: column.to_string(),
            row_count: frame.height(),
            finite_count,
            null_count,
            nan_count,
            infinite_count,
            finite_min,
            finite_max,
            time_order,
        })
    }

    /// Samples the same source rows from every requested column for display.
    pub fn preview_rows(&self, columns: &[&str], max_rows: usize) -> PolarsResult<PreviewRows> {
        let expressions: Vec<_> = columns.iter().map(|name| col(*name)).collect();
        let df = self.frame.clone().select(expressions).collect()?;
        let row_count = df.height();
        let step = if max_rows == 0 {
            row_count.max(1)
        } else {
            (row_count as f64 / max_rows as f64).ceil().max(1.0) as usize
        };
        let row_indices: Vec<_> = (0..row_count).step_by(step).collect();
        let mut sampled = HashMap::with_capacity(columns.len());
        for name in columns {
            let series = df.column(name)?.f64()?;
            let values = row_indices.iter().map(|&row| series.get(row)).collect();
            sampled.insert((*name).to_string(), values);
        }
        Ok(PreviewRows {
            row_indices,
            columns: sampled,
        })
    }

    /// Collects one numeric column while preserving null rows and source order.
    /// Unlike a table preview, this does not allocate a parallel row-index vector.
    pub fn numeric_column_values_with_nulls(&self, column: &str) -> PolarsResult<Vec<Option<f64>>> {
        let frame = self.frame.clone().select([col(column)]).collect()?;
        let values = frame.column(column)?.f64()?;
        Ok((0..frame.height()).map(|row| values.get(row)).collect())
    }

    /// Reads one numeric cell without materializing the remaining column or frame.
    pub fn numeric_value_at_row(&self, column: &str, row: usize) -> PolarsResult<Option<f64>> {
        let offset = i64::try_from(row).map_err(|_| {
            PolarsError::ComputeError("Numeric cell row exceeds the supported range".into())
        })?;
        let frame = self
            .frame
            .clone()
            .select([col(column)])
            .slice(offset, 1)
            .collect()?;
        let values = frame.column(column)?.f64()?;
        Ok(values.get(0))
    }

    /// Преобразование данных в численный формат для дальнейшей обработки
    pub fn materialize(&self, grid_col: &str, cols: &[&str]) -> PolarsResult<NumericBlock> {
        let mut requested = HashSet::with_capacity(cols.len() + 1);
        requested.insert(grid_col);
        for name in cols {
            if !requested.insert(*name) {
                return Err(PolarsError::ComputeError(
                    format!("Column '{name}' was requested more than once for materialization")
                        .into(),
                ));
            }
        }

        let mut select_exprs = Vec::with_capacity(cols.len() + 1);
        select_exprs.push(col(grid_col));
        select_exprs.extend(cols.iter().map(|name| col(*name)));

        let df = self.frame.clone().select(select_exprs).collect()?;
        let grid_values = df.column(grid_col)?.f64()?;
        let value_series = cols
            .iter()
            .map(|name| Ok((*name, df.column(name)?.f64()?)))
            .collect::<PolarsResult<Vec<_>>>()?;
        let mut grid = Vec::with_capacity(df.height());
        let mut columns = cols
            .iter()
            .map(|name| (name.to_string(), Vec::with_capacity(df.height())))
            .collect::<HashMap<_, _>>();
        let mut row_values = Vec::with_capacity(cols.len());
        let mut previous_time = None;

        // Apply one complete-case mask to the grid and every requested column.
        for row in 0..df.height() {
            let Some(x) = grid_values.get(row) else {
                continue;
            };
            row_values.clear();
            let mut complete = true;
            for (_, series) in &value_series {
                match series.get(row) {
                    Some(value) => row_values.push(value),
                    None => {
                        complete = false;
                        break;
                    }
                }
            }
            if !complete {
                continue;
            }

            if !x.is_finite() {
                return Err(PolarsError::ComputeError(
                    format!("Grid column '{grid_col}' has a non-finite value at row {row}").into(),
                ));
            }
            for ((name, _), value) in value_series.iter().zip(&row_values) {
                if !value.is_finite() {
                    return Err(PolarsError::ComputeError(
                        format!("Column '{name}' has a non-finite value at row {row}").into(),
                    ));
                }
            }

            if self.schema.time.as_deref() == Some(grid_col) {
                if let Some((previous_row, previous_x)) = previous_time {
                    if x <= previous_x {
                        return Err(PolarsError::ComputeError(
                            format!(
                                "Bound time column '{grid_col}' must be strictly increasing after null rows are omitted; rows {previous_row} and {row} contain {previous_x} then {x}"
                            )
                            .into(),
                        ));
                    }
                }
                previous_time = Some((row, x));
            }

            grid.push(x);
            for ((name, _), value) in value_series.iter().zip(&row_values) {
                columns
                    .get_mut(*name)
                    .ok_or_else(|| {
                        PolarsError::ComputeError(
                            format!("Missing output buffer for column '{name}'").into(),
                        )
                    })?
                    .push(*value);
            }
        }

        Ok(NumericBlock {
            grid: Arc::new(grid),
            columns: columns
                .into_iter()
                .map(|(name, data)| (name, Arc::new(data)))
                .collect(),
        })
    }
}
//======================================================================
/// numeical column representation
pub struct NumericColumn {
    pub data: Arc<Vec<f64>>,
}

impl NumericColumn {
    /*
    /// Преобразование в ndarray представление
    pub fn as_ndarray(&self) -> ArrayView1<f64> {
        ArrayView1::from(self.data.as_slice())
    }

    /// Преобразование в DVector представление
    pub fn as_dvector(&self) -> DVectorView<f64> {
        DVectorView::from_slice(self.data.as_slice(), self.data.len())
    }
    */
}
/// return data back to Polars
impl TGADataset {
    /// Добавление числовой колонки в набор данных
    pub fn add_numeric_column(
        mut self,
        name: &str,
        unit: Unit,
        data: Arc<Vec<f64>>,
        nature: ColumnNature,
    ) -> PolarsResult<Self> {
        self.ensure_column_name_is_available(name)
            .map_err(|err| PolarsError::ComputeError(format!("{:?}", err).into()))?;
        let series = Series::new(name.into(), data.as_ref());
        self.push_undo_snapshot();
        self.frame = self.frame.with_column(lit(series));

        self.schema.columns.insert(
            name.into(),
            ColumnMeta::new(
                name.to_string(),
                unit,
                ColumnOrigin::NumericDerived,
                nature,
                ColumnProvenance::manual(
                    name,
                    "add_numeric_column",
                    Some("external numeric data".to_string()),
                ),
            ),
        );

        self.log_operation(
            "add_numeric_column",
            AffectedColumns::Specific(vec![name.to_string()]),
            None,
            format!("Added numeric column {} with unit {:?}", name, unit),
            true,
        );

        Ok(self)
    }
}