pmmlruntime 0.1.0

PMML 4.4 runtime — session-based execution, Arrow batch, hardened XML
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
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
//! Optimized, post-lower intermediate representation for PMML 4.4.
//!
//! Optimized, post-lower intermediate representation for PMML 4.4.
//!
//! The hot path (session + engine) reads only [`Ir`] and its
//! child structs. Cold-path parsing (`xml` → [`crate::xml::RawPmml`]) is
//! lowered once via [`crate::ir::lower::lower()`] into this representation.
//!
//! Key design choices:
//! - Stable [`crate::base::FieldId`] / [`crate::base::SymbolId`] assigned by [`crate::ir::Interner`].
//! - `TreeModel` nodes flattened to `Vec<NodeIr>` with root at index 0.
//! - `DerivedField` / `TransformationDictionary` sorted topologically.
//! - `DerivedFieldIr.bytecode` holds a `Vec<Op>` evaluated by `engine::transform::vm`.
//! - All types are `Clone` and `Send + Sync` (via `Arc<Ir>` in `session`).

use crate::base::field::{DataType, OpType, ResultFeature};
use crate::base::{FieldId, SymbolId};
use smallvec::SmallVec;

/// Field metadata after `DataDictionary` + `MiningSchema` lowering.
///
/// One [`FieldMeta`] corresponds to a `DataField` entry, possibly enriched by
/// the model's `MiningField`. Synthetic fields created during lowering (for
/// example, an output of a [`DerivedFieldIr`] or a MiningModel synthetic
/// probability field) also produce a `FieldMeta` via
/// `lower::get_or_intern_field`.
///
/// # Examples
///
/// ```
/// use pmmlruntime::base::{FieldId, DataType, OpType};
/// use pmmlruntime::ir::{FieldMeta, OutlierTreatment, InvalidValueTreatment, MissingValueTreatment};
///
/// let meta = FieldMeta {
///     field_id: FieldId(0),
///     name: "age".into(),
///     data_type: DataType::Double,
///     op_type: OpType::Continuous,
///     values: vec![],
///     invalid_value_treatment: InvalidValueTreatment::ReturnInvalid,
///     invalid_value_replacement: None,
///     missing_value_replacement: None,
///     missing_value_treatment: MissingValueTreatment::AsIs,
///     outlier_treatment: OutlierTreatment::AsIs,
///     low_value: Some(0.0),
///     high_value: Some(120.0),
/// };
/// assert_eq!(meta.name, "age");
/// ```
#[derive(Debug, Clone)]
pub struct FieldMeta {
    /// Stable numeric identity for this field, dense per [`crate::ir::Interner`].
    ///
    /// Used as index into the hot-path `&[crate::base::Value]` array. See
    /// [`Ir::num_fields`] and `pmml-session` layout.
    pub field_id: FieldId,
    /// Original PMML `DataField/@name` or `DerivedField/@name`.
    pub name: String,
    /// Declared `DataDictionary/DataField/@dataType` (case-sensitive per `pmml.xsd`).
    ///
    /// Determines whether a value is stored as [`crate::base::Value::Discrete`]
    /// or [`crate::base::Value::Continuous`] on the hot path. See [`DataType`].
    pub data_type: DataType,
    /// Declared `DataField/@opType` (`categorical` / `ordinal` / `continuous`).
    ///
    /// Controls predicate semantics and outlier handling. See [`OpType`].
    pub op_type: OpType,
    /// Allowed discrete values from `DataField/Value` (for validation).
    ///
    /// Each entry is an interned [`SymbolId`]; empty when the field is continuous
    /// or when the PMML lists no restriction.
    pub values: Vec<SymbolId>,
    /// How to handle a value that violates `DataType` or `values` list.
    ///
    /// From `MiningField/@invalidValueTreatment`. See [`InvalidValueTreatment`].
    pub invalid_value_treatment: InvalidValueTreatment,
    /// Replacement string when `invalid_value_treatment` is `AsValue`.
    ///
    /// `None` when the treatment is not `asValue` or no replacement was specified.
    pub invalid_value_replacement: Option<String>,
    /// Replacement string when `missing_value_treatment` is `AsValue`.
    ///
    /// From `MiningField/@missingValueReplacement`.
    pub missing_value_replacement: Option<String>,
    /// How to handle `Missing` values for this field.
    ///
    /// From `MiningField/@missingValueTreatment`. See [`MissingValueTreatment`].
    pub missing_value_treatment: MissingValueTreatment,
    /// How to handle outliers for continuous fields.
    ///
    /// From `MiningField/@outliers`. See [`OutlierTreatment`].
    pub outlier_treatment: OutlierTreatment,
    /// Inclusive lower bound for outlier detection (`MiningField/@lowValue`).
    ///
    /// `None` when no bound was specified. Parsed as `f64` during lowering;
    /// `None` if the PMML string failed to parse.
    pub low_value: Option<f64>,
    /// Inclusive upper bound for outlier detection (`MiningField/@highValue`).
    pub high_value: Option<f64>,
}

impl Default for FieldMeta {
    fn default() -> Self {
        Self {
            field_id: FieldId(0),
            name: String::new(),
            data_type: DataType::String,
            op_type: OpType::Categorical,
            values: vec![],
            invalid_value_treatment: InvalidValueTreatment::ReturnInvalid,
            invalid_value_replacement: None,
            missing_value_replacement: None,
            missing_value_treatment: MissingValueTreatment::AsIs,
            outlier_treatment: OutlierTreatment::AsIs,
            low_value: None,
            high_value: None,
        }
    }
}

/// Outlier handling for continuous fields, per `MiningField/@outliers`.
///
/// Mirrors PMML XSD `OUTLIER-TREATMENT-METHOD`. Used by the engine before
/// scoring to rewrite a value that lies outside `[low_value, high_value]`.
///
/// See [`FieldMeta::outlier_treatment`], [`FieldMeta::low_value`], [`FieldMeta::high_value`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutlierTreatment {
    /// Leave the value unchanged (`asIs`).
    AsIs,
    /// Treat outlying values as [`crate::base::Value::Missing`] (`asMissingValues`).
    AsMissingValues,
    /// Clamp to the nearer bound (`asExtremeValues`).
    AsExtremeValues,
}

/// How to handle a value that fails type or domain validation, per `MiningField/@invalidValueTreatment`.
///
/// Mirrors PMML XSD `INVALID-VALUE-TREATMENT-METHOD`. Lowering parses the
/// string via `parse_invalid_treatment` in [`mod@crate::ir::lower`]; default is
/// `ReturnInvalid` when absent.
///
/// See [`FieldMeta::invalid_value_treatment`] and
/// [`FieldMeta::invalid_value_replacement`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InvalidValueTreatment {
    /// Return an invalid result (score as missing / return error) (`returnInvalid`).
    ReturnInvalid,
    /// Use the value as-is despite validation (`asIs`).
    AsIs,
    /// Treat the value as missing (`asMissing`).
    AsMissing,
    /// Replace with [`FieldMeta::invalid_value_replacement`] (`asValue`).
    AsValue,
}

/// How to handle missing input values, per `MiningField/@missingValueTreatment`.
///
/// Mirrors PMML XSD `MISSING-VALUE-TREATMENT-METHOD`. When `AsValue`, the
/// replacement comes from [`FieldMeta::missing_value_replacement`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MissingValueTreatment {
    /// Propagate `Missing` unchanged (`asIs`).
    AsIs,
    /// Replace with mean of training column (`asMean`).
    AsMean,
    /// Replace with mode of training column (`asMode`).
    AsMode,
    /// Replace with median of training column (`asMedian`).
    AsMedian,
    /// Replace with [`FieldMeta::missing_value_replacement`] (`asValue`).
    AsValue,
    /// Fail scoring and return missing/invalid (`returnInvalid`).
    ReturnInvalid,
}

/// Role of a field in a `MiningSchema` (`MiningField/@usageType`).
///
/// `Active` fields are model inputs; `Predicted`/`Target` identify the output;
/// the others affect weighting or display but are not scored directly.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MiningFieldUsageType {
    /// Input feature (`active`).
    Active,
    /// Model output (`predicted`).
    Predicted,
    /// Alias for `Predicted` (`target` in PMML 4.4 `MiningSchema`).
    Target,
    /// Auxiliary column not used in scoring (`supplementary`).
    Supplementary,
    /// Grouping key for `MiningModel` (`group`).
    Group,
    /// Ordering key (`order`).
    Order,
    /// Per-row frequency weight (`frequencyWeight`).
    FrequencyWeight,
    /// Per-row analysis weight (`analysisWeight`).
    AnalysisWeight,
}

/// Flat mining schema after lowering.
///
/// Contains the active input fields (usage `active`) and at most one target,
/// plus per-field treatments already folded into each [`FieldMeta`]. Every
/// [`FieldId`] in `active_fields` / `target_field` / `field_metas` is present
/// in [`Ir::field_names`].
#[derive(Debug, Clone)]
pub struct MiningSchemaIr {
    /// Ordered active inputs (`usageType != target`). Scoring order follows this vec.
    pub active_fields: Vec<FieldId>,
    /// Predicted / target field, if declared (`usageType = target | predicted`).
    pub target_field: Option<FieldId>,
    /// Per-field metadata in `MiningField` order, with `MiningField` treatments folded in.
    pub field_metas: Vec<FieldMeta>,
    /// Global `missingValueReplacement` for backward compatibility.
    ///
    /// Set to the first field's `missing_value_replacement` if any. New code
    /// should read [`FieldMeta::missing_value_replacement`] instead.
    pub missing_value_replacement: Option<String>,
}

/// Derived field compiled to bytecode.
///
/// `TransformationDictionary/DerivedField` and model-local `DerivedField`s are
/// pooled, topologically sorted, and lowered to [`Op`] sequences. Evaluation
/// order follows the sorted `Ir.derived_fields` vector.
///
/// # Examples
///
/// ```
/// use pmmlruntime::base::{FieldId, DataType, OpType};
/// use pmmlruntime::ir::{DerivedFieldIr, Op};
/// let derived = DerivedFieldIr {
///     field_id: FieldId(2),
///     name: "log_age".into(),
///     data_type: DataType::Double,
///     op_type: OpType::Continuous,
///     bytecode: vec![Op::PushField(FieldId(0))],
/// };
/// assert_eq!(derived.name, "log_age");
/// ```
#[derive(Debug, Clone)]
pub struct DerivedFieldIr {
    /// Stable id assigned to the derived field itself.
    pub field_id: FieldId,
    /// `DerivedField/@name`.
    pub name: String,
    /// `DerivedField/@dataType`.
    pub data_type: DataType,
    /// `DerivedField/@optype`.
    pub op_type: OpType,
    /// Bytecode evaluated by `engine::transform::vm::eval` in sorted order.
    pub bytecode: Vec<Op>,
}

/// Aggregate function for `Lag` (last `n` rows).
///
/// `None` returns a scalar lag; the others reduce a window of `n` values.
/// See [`Op::Lag`] and `PMML Lag` extension.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LagAggregate {
    /// No aggregation — return the single lagged value.
    None,
    /// Arithmetic mean over the window.
    Avg,
    /// Minimum over the window.
    Min,
    /// Maximum over the window.
    Max,
    /// Sum over the window.
    Sum,
    /// Product over the window.
    Product,
    /// Median over the window.
    Median,
    /// Standard deviation over the window.
    Stddev,
}

/// Bytecode for `Apply` / `MapValues` / `Discretize` and related expressions.
///
/// Evaluated by `engine::transform::vm::eval`. Operands refer to
/// [`FieldId`] / [`SymbolId`] interned during lowering.
#[derive(Debug, Clone)]
pub enum Op {
    /// Push value of field `0` (`FieldRef` / implicit field) onto stack.
    PushField(FieldId),
    /// Push a constant (`Constant`): discrete symbol, continuous `f64`, or Missing.
    PushConst(SymbolIdOrContinuous),
    /// Call a pure builtin `function` with `arity` stack arguments.
    ///
    /// Arguments are popped in order produced by lowering; result is pushed.
    /// See [`BuiltinId`].
    CallBuiltin(BuiltinId, u8),
    /// Conditional jump when top-of-stack is `Missing` (for `IF` optimization).
    JumpIfMissing {
        /// Bytecode index to jump to when Missing.
        target: usize,
    },
    /// Single-input map-values table (`MapValues` with one `FieldColumnPair`).
    ///
    /// Evaluated via engine hash lookup on the input symbol.
    MapValues {
        /// Sorted map from input symbol to output symbol.
        table: Vec<(SymbolId, SymbolId)>,
        /// Value when no key matches; `None` yields Missing.
        default: Option<SymbolId>,
    },
    /// Multi-input map-values (`MapValues` with ≥2 inputs).
    MapValuesMulti {
        /// Input fields in table column order.
        inputs: Vec<FieldId>,
        /// Each row is `(Vec<input_symbols>, output_symbol)`.
        table: Vec<(Vec<SymbolId>, SymbolId)>,
        /// Default when no row matches.
        default: Option<SymbolId>,
    },
    /// Bin continuous value into discrete bins (`Discretize`).
    Discretize {
        /// Closed/open intervals sorted as in PMML; evaluated top-to-bottom.
        bins: Vec<DiscretizeBin>,
        /// Value when no bin matches and input is not missing.
        default_value: Option<SymbolId>,
        /// Value when input is Missing.
        map_missing_to: Option<SymbolId>,
    },
    /// Piecewise-linear normalization (`NormContinuous`).
    NormContinuous {
        /// Input field.
        field: FieldId,
        /// Ordered `LinearNorm` breakpoints.
        linear_norms: Vec<LinearNorm>,
    },
    /// Discrete indicator (`NormDiscrete`): `field == value ? 1 : 0`.
    NormDiscrete {
        /// Input field.
        field: FieldId,
        /// Value to compare.
        value: SymbolId,
        /// Replacement when input is Missing (typically `None` → Missing).
        map_missing_to: Option<f64>,
    },
    /// Temporal lag (`Lag`): value of `field` `n` rows ago, optionally aggregated.
    Lag {
        /// Input field.
        field: FieldId,
        /// Number of rows to look back.
        n: usize,
        /// Window aggregate.
        aggregate: LagAggregate,
    },
    /// Call a user-defined function from `TransformationDictionary/DefineFunction`.
    CallDefine {
        /// `DefineFunction/@name`.
        name: String,
        /// Declared arity.
        arity: u8,
    },
}

/// Constant or missing value pushed by [`Op::PushConst`].
///
/// `Continuous(f64)` carries an already-parsed `f64`; `Symbol(SymbolId)` is an
/// interned discrete string; `Missing` is PMML `Missing`.
#[derive(Debug, Clone, Copy)]
pub enum SymbolIdOrContinuous {
    /// Discrete constant (interned).
    Symbol(SymbolId),
    /// Numeric constant.
    Continuous(f64),
    /// PMML `Missing` (`Constant` with empty value or failed expression).
    Missing,
}

/// Single bin for [`Op::Discretize`].
///
/// PMML `Interval/@closure` controls inclusiveness of the bounds.
#[derive(Debug, Clone)]
pub struct DiscretizeBin {
    /// Output symbol for this bin (`DiscretizeBin/@binValue`).
    pub bin_value: SymbolId,
    /// Lower bound; `-inf` when omitted (`Interval/@leftMargin` absent).
    pub interval_low: f64,
    /// Upper bound; `+inf` when omitted.
    pub interval_high: f64,
    /// Whether `interval_low` is inclusive (closed).
    pub left_closed: bool,
    /// Whether `interval_high` is inclusive (closed).
    pub right_closed: bool,
}

/// Breakpoint for [`Op::NormContinuous`].
///
/// Two consecutive `LinearNorm`s define a line segment `norm = a*orig + b`.
#[derive(Debug, Clone, Copy)]
pub struct LinearNorm {
    /// Original value at breakpoint (`LinearNorm/@orig`).
    pub orig: f64,
    /// Normalized value at breakpoint (`LinearNorm/@norm`).
    pub norm: f64,
}

/// Pure builtin functions callable via `Apply` or dedicated PMML elements.
///
/// Lowering normalizes function names to canonical `fn` strings (for example,
/// `"add" | "+" → Add`) via `resolve_builtin` in [`mod@crate::ir::lower`].
/// Grouping below mirrors the PMML function registry for discoverability.
///
/// # Examples
///
/// ```
/// use pmmlruntime::ir::BuiltinId;
/// let id = BuiltinId::Add;
/// assert_eq!(id as u8, BuiltinId::Add as u8);
/// // evaluators dispatch via match on BuiltinId
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BuiltinId {
    // ── Arithmetic ──────────────────────────────────────────────
    /// `add` / `+`: sum of all arguments.
    Add,
    /// `subtract` / `-`: first minus remaining.
    Sub,
    /// `multiply` / `*`: product.
    Mul,
    /// `divide` / `/`: first divided by second.
    Div,
    /// `pow`: `pow(base, exp)`.
    Pow,
    /// `log` / `ln`: natural logarithm.
    Log,
    /// `log10`: base-10 logarithm.
    Log10,
    /// Alias for `Log` (natural log).
    Ln,
    /// `exp`: `e^x`.
    Exp,
    /// `sqrt`: square root.
    Sqrt,
    /// `abs`: absolute value.
    Abs,
    /// `floor`: round down.
    Floor,
    /// `ceil`: round up.
    Ceil,
    /// `round`: to nearest integer (ties away from zero).
    Round,
    /// `remainder`: IEEE remainder.
    Remainder,
    // ── Trigonometry & hyperbolic ───────────────────────────────
    /// `sin`.
    Sin,
    /// `cos`.
    Cos,
    /// `tan`.
    Tan,
    /// `asin`.
    Asin,
    /// `acos`.
    Acos,
    /// `atan`.
    Atan,
    /// `sinh`.
    Sinh,
    /// `cosh`.
    Cosh,
    /// `tanh`.
    Tanh,
    // ── Minimum / maximum & aggregates ──────────────────────────
    /// `min`: minimum of arguments.
    Min,
    /// `max`: maximum of arguments.
    Max,
    /// `median`: median of arguments / table column.
    Median,
    /// `product`: product of arguments (distinct from [`Self::Mul`] which lower handles as variadic add-like).
    ProductOp,
    /// `sum`: sum of arguments.
    SumOp,
    /// `avg` / `average`: arithmetic mean.
    AvgOp,
    /// `mean`: alias for average.
    Mean,
    /// `stddev`: population standard deviation.
    StdDev,
    /// `variance`: population variance.
    Variance,
    // ── Modulo / rounding & C math ──────────────────────────────
    /// `modulo`: `a mod b`.
    Modulo,
    /// `rint`: round to nearest even.
    Rint,
    /// `expm1`: `exp(x) - 1` with high accuracy near 0.
    Expm1,
    /// `hypot`: `sqrt(x^2 + y^2)`.
    Hypot,
    /// `ln1p`: `ln(1 + x)` with high accuracy near 0.
    Ln1p,
    /// `atan2`: `atan2(y, x)`.
    Atan2,
    /// `cbrt`: cube root.
    Cbrt,
    /// `sign`: signum (-1, 0, 1).
    Sign,
    // ── String ──────────────────────────────────────────────────
    /// `uppercase` / `upperCase`.
    Uppercase,
    /// `lowercase` / `lowerCase`.
    Lowercase,
    /// `substring(string, pos, len)`.
    Substring,
    /// `trimBlanks`: trim leading/trailing blanks.
    TrimBlanks,
    /// `normalizeSpace`: trim + collapse whitespace.
    NormalizeSpace,
    /// `concat`: concatenate all arguments.
    Concat,
    /// `stringLength`: `len(s)`.
    StringLength,
    /// `replace(string, pattern, replacement)`.
    Replace,
    /// `matches(string, pattern)`: regex match.
    Matches,
    /// `formatNumber(number, pattern)`.
    FormatNumber,
    /// `formatDatetime(datetime, pattern)`.
    FormatDatetime,
    // ── Text index ──────────────────────────────────────────────
    /// `textIndex` / `TextIndex`: substring search index (1-based, 0 when not found).
    TextIndex,
    // ── Aggregate ───────────────────────────────────────────────
    /// `count` / `aggregateCount` over an inline table or batch.
    AggregateCount,
    /// `sum` / `aggregateSum`.
    AggregateSum,
    /// `average` / `avg` / `aggregateAverage`.
    AggregateAvg,
    /// `aggregateMin`.
    AggregateMin,
    /// `aggregateMax`.
    AggregateMax,
    /// `aggregateMultiset` (unique-count, not yet lowered as builtin).
    AggregateMultiset,
    // ── Temporal / Lag ──────────────────────────────────────────
    /// `lag`: previous row(s) value.
    Lag,
    // ── Date / time (chrono) ───────────────────────────────────
    /// `dateDaysSinceYear`.
    DateDaysSinceYear,
    /// `dateSecondsSinceYear`.
    DateSecondsSinceYear,
    /// `dateSecondsSinceMidnight`.
    DateSecondsSinceMidnight,
    /// `dateDaysSince[1960]` / `DataType::DateDaysSince1960` helper.
    DateDaysSince1960,
    /// `dateDaysSince[1970]`.
    DateDaysSince1970,
    /// `dateDaysSince[1980]`.
    DateDaysSince1980,
    /// `dateTimeSecondsSince[1960]`.
    DateTimeSecondsSince1960,
    /// `dateTimeSecondsSince[1970]`.
    DateTimeSecondsSince1970,
    /// `dateTimeSecondsSince[1980]`.
    DateTimeSecondsSince1980,
    /// `dateTimeSecondsSince[0]` (unsupported per PMML, rejected in lower).
    DateTimeSecondsSince0,
    /// `timeSeconds`.
    TimeSeconds,
    // ── Distribution (statrs / libm) ────────────────────────────
    /// `normalCDF`.
    NormalCdf,
    /// `normalPDF`.
    NormalPdf,
    /// `normalIDF` (inverse CDF / quantile).
    NormalIdf,
    /// `stdNormalCDF`.
    StdNormalCdf,
    /// `stdNormalPDF`.
    StdNormalPdf,
    /// `stdNormalIDF`.
    StdNormalIdf,
    /// `erf`.
    ErfOp,
    // ── PMML Norm pseudo-builtins ───────────────────────────────
    /// `normContinuous` lowered as dedicated [`Op::NormContinuous`].
    NormContinuousOp,
    /// `normDiscrete` lowered as dedicated [`Op::NormDiscrete`].
    NormDiscreteOp,
    // ── Comparison / logical ────────────────────────────────────
    /// `equal`: `a == b`.
    Equal,
    /// `notEqual`: `a != b`.
    NotEqual,
    /// `lessThan`: `a < b`.
    LessThan,
    /// `lessOrEqual`: `a <= b`.
    LessOrEqual,
    /// `greaterThan`: `a > b`.
    GreaterThan,
    /// `greaterOrEqual`: `a >= b`.
    GreaterOrEqual,
    /// `and`: logical conjunction (all true).
    And,
    /// `or`: logical disjunction (any true).
    Or,
    /// `not`: logical negation.
    Not,
    /// `isMissing`: `value is Missing`.
    IsMissing,
    /// `isNotMissing`: `value is not Missing`.
    IsNotMissing,
    /// `isValid`: not missing and not outlier/invalid.
    IsValid,
    /// `isNotValid`: complement of `isValid`.
    IsNotValid,
    /// `isIn`: membership test (`x in {...}`).
    IsIn,
    /// `isNotIn`: negated membership.
    IsNotIn,
    // ── Conditional ─────────────────────────────────────────────
    /// `if`: `if(condition, then, else)`.
    If,
    // ── Misc ────────────────────────────────────────────────────
    /// `threshold(y, v)`: `y > v ? y : 0` helper for scorecard.
    Threshold,
    /// Unknown function → lowering emits `Missing` at runtime.
    Unknown,
}

/// Lowered PMML model — the sole scoring path selected per PMML file.
///
/// `RawPmml` contains at most one top-level model (plus optional Segmentation
/// segments). Lowering picks the present model and returns `MissingField` or
/// `UnsupportedMarkup` when none matches.
///
/// See each variant's struct for model-specific semantics and PMML
/// comparability notes.
#[derive(Debug, Clone)]
pub enum ModelIr {
    /// `TreeModel` (classification or regression).
    Tree(TreeIr),
    /// `RegressionModel` (linear / logistic with normalization).
    Regression(RegressionIr),
    /// `MiningModel` (segmented / chained models).
    Mining(MiningIr),
    /// `Scorecard` (characteristics + attributes, reason codes).
    Scorecard(ScorecardIr),
    /// `ClusteringModel` (center-based, clusters + comparison measure).
    Clustering(ClusteringIr),
    /// `NaiveBayesModel` (BayesInputs / BayesOutput).
    NaiveBayes(NaiveBayesIr),
    /// `NearestNeighborModel` (k-NN with `InlineTable` instances).
    NearestNeighbor(NearestNeighborIr),
    /// `SupportVectorMachineModel` (vector fields + support vectors + kernels).
    SupportVectorMachine(SupportVectorMachineIr),
    /// `NeuralNetwork` (inputs → layers → neurons).
    NeuralNetwork(NeuralNetworkIr),
    /// `GeneralRegressionModel` (PPMatrix / ParamMatrix / factors / covariates).
    GeneralRegression(GeneralRegressionIr),
    /// `AssociationModel` (items / itemsets / rules).
    Association(AssociationIr),
    /// `RuleSetModel` (`RuleSet` with ordered simple rules).
    RuleSet(RuleSetIr),
    /// `AnomalyDetectionModel` (wrapper over any model with `MeanClusterDistances`).
    AnomalyDetection(AnomalyDetectionIr),
    /// `BaselineModel` (change-detection / hypothesis testing via `TestDistributions`).
    Baseline(BaselineIr),
    /// `TimeSeriesModel` (ARIMA / ExponentialSmoothing / GARCH / StateSpace / Spectral).
    TimeSeries(TimeSeriesIr),
    /// `GaussianProcessModel` (kernel-based regression with `TrainingInstances`).
    GaussianProcess(GaussianProcessIr),
    /// `TextModel` (bag-of-words / TF-IDF with `DocumentTermMatrix`).
    Text(TextIr),
    /// `SequenceModel` (ordered itemsets / set predicates with sequence rules).
    Sequence(SequenceModelIr),
    /// `BayesianNetworkModel` (directed acyclic graph with discrete/continuous nodes).
    BayesianNetwork(BayesianNetworkIr),
}

/// Lowered `RegressionModel`.
///
/// Computes `y = intercept + Σ coeff * field^exponent` per `RegressionTable`,
/// then applies [`RegressionNormalizationMethod`].
#[derive(Debug, Clone)]
pub struct RegressionIr {
    /// `RegressionModel/@functionName` (`regression` / `classification`).
    pub function_name: String,
    /// Mining schema for this model (active fields + target).
    pub mining_schema: MiningSchemaIr,
    /// One table per target category (`targetCategory` discriminates multinomial).
    pub regression_tables: Vec<RegressionTableIr>,
    /// `RegressionModel/@normalizationMethod` (default `None`).
    pub normalization_method: RegressionNormalizationMethod,
    /// `Targets` rescaling / casting metadata.
    pub targets: Vec<TargetIr>,
    /// `Output` fields requested by the PMML.
    pub output: Vec<OutputFieldIr>,
}

/// One `RegressionTable` inside a [`RegressionIr`].
#[derive(Debug, Clone)]
pub struct RegressionTableIr {
    /// `RegressionTable/@intercept`.
    pub intercept: f64,
    /// `RegressionTable/@targetCategory` (interned when present, e.g., for softmax).
    pub target_category: Option<SymbolId>,
    /// Numeric predictors: `NumericPredictor/@name, exponent, coefficient`.
    pub numeric_predictors: Vec<NumericPredictorIr>,
    /// Categorical predictors: `CategoricalPredictor/@field, value, coefficient`.
    pub categorical_predictors: Vec<CategoricalPredictorIr>,
}

/// Numeric predictor contribution `coeff * field^exponent`.
#[derive(Debug, Clone)]
pub struct NumericPredictorIr {
    /// Input field.
    pub field: FieldId,
    /// `NumericPredictor/@coefficient`.
    pub coefficient: f64,
    /// `NumericPredictor/@exponent` (default 1).
    pub exponent: i32,
}

/// Categorical predictor contribution active when `field == value`.
#[derive(Debug, Clone)]
pub struct CategoricalPredictorIr {
    /// Input field.
    pub field: FieldId,
    /// Value that activates this predictor (interned).
    pub value: SymbolId,
    /// `CategoricalPredictor/@coefficient`.
    pub coefficient: f64,
}

/// Normalization applied after raw regression scores, per `RegressionModel/@normalizationMethod`.
///
/// Mirrors `REGRESSIONNORMALIZATIONMETHOD`. `None` returns raw scores directly.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RegressionNormalizationMethod {
    /// No normalization (`none`).
    None,
    /// Divide by maximum (`simpleMax`): `x / max(x)`.
    SimpleMax,
    /// Softmax (`softmax`): `exp(x)/sum(exp(x))`.
    Softmax,
    /// Logit (`logit`): `1 / (1 + exp(-x))` (binary).
    Logit,
    /// Probit (`probit`): `Φ(x)` standard normal CDF.
    Probit,
    /// Complementary log-log (`cloglog`): `1 - exp(-exp(x))`.
    ClogLog,
    /// Exponential (`exp`): `exp(x)`.
    Exp,
    /// Double exponential (`loglog`): `exp(exp(x))`.
    Loglog,
    /// Cauchy (`cauchit`): `0.5 + atan(x)/π`.
    Cauchit,
}

/// Lowered `MiningModel` (segmented ensemble / `modelChain`).
#[derive(Debug, Clone)]
pub struct MiningIr {
    /// `MiningModel/@functionName`.
    pub function_name: String,
    /// Top-level mining schema.
    pub mining_schema: MiningSchemaIr,
    /// Segmentation defining how segment models are combined.
    pub segmentation: SegmentationIr,
    /// Targets for rescaling / casting.
    pub targets: Vec<TargetIr>,
    /// Output fields.
    pub output: Vec<OutputFieldIr>,
}

/// Segmentation of a [`MiningIr`].
#[derive(Debug, Clone)]
pub struct SegmentationIr {
    /// `Segmentation/@multipleModelMethod`.
    pub multiple_model_method: MultipleModelMethod,
    /// `Segmentation/@missingPredictionTreatment`.
    pub missing_prediction_treatment: MissingPredictionTreatment,
    /// Ordered segments; each has a predicate and a boxed model.
    pub segments: Vec<SegmentIr>,
}

/// Single segment inside a [`SegmentationIr`].
#[derive(Debug, Clone)]
pub struct SegmentIr {
    /// `Segment/@id` (may be `None` in older PMML).
    pub id: Option<String>,
    /// Predicate that selects this segment (`True` for the default segment).
    pub predicate: PredicateIr,
    /// `Segment/@weight` (default 1.0).
    pub weight: f64,
    /// Boxed sub-model (`Tree` or `Regression` currently).
    pub model: Box<ModelIr>,
}

/// How to combine predictions from multiple `MiningModel` segments.
///
/// Mirrors `MULTIPLE-MODEL-METHOD` in `pmml.xsd`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MultipleModelMethod {
    /// `majorityVote`.
    MajorityVote,
    /// `weightedMajorityVote`.
    WeightedMajorityVote,
    /// `average`.
    Average,
    /// `weightedAverage`.
    WeightedAverage,
    /// `median`.
    Median,
    /// `weightedMedian`.
    WeightedMedian,
    /// `max`.
    Max,
    /// `sum`.
    Sum,
    /// `weightedSum`.
    WeightedSum,
    /// `selectFirst`.
    SelectFirst,
    /// `selectAll`.
    SelectAll,
    /// `modelChain` — chain outputs as extra fields for later segments.
    ModelChain,
}

/// How a `MiningModel` handles a missing prediction from a segment.
///
/// Mirrors `MISSING-PREDICTION-TREATMENT`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MissingPredictionTreatment {
    /// Propagate missing (`returnMissing`).
    ReturnMissing,
    /// Skip the segment (`skipSegment`).
    SkipSegment,
    /// Continue to next segment (`continue`).
    Continue,
}

/// Lowered `Scorecard` model.
#[derive(Debug, Clone)]
pub struct ScorecardIr {
    /// `Scorecard/@functionName`.
    pub function_name: String,
    /// `Scorecard/@initialScore` (starting points).
    pub initial_score: f64,
    /// `Scorecard/@useReasonCodes`.
    pub use_reason_codes: bool,
    /// `Scorecard/@reasonCodeAlgorithm` (`pointsAbove` or `pointsBelow` etc.).
    pub reason_code_algorithm: String,
    /// Mining schema for inputs.
    pub mining_schema: MiningSchemaIr,
    /// Ordered characteristics.
    pub characteristics: Vec<CharacteristicIr>,
    /// Output fields (often `predictedValue` + `reasonCode`).
    pub output: Vec<OutputFieldIr>,
}

/// One `Characteristic` inside a [`ScorecardIr`].
#[derive(Debug, Clone)]
pub struct CharacteristicIr {
    /// `Characteristic/@name`.
    pub name: String,
    /// `Characteristic/@reasonCode` (when `useReasonCodes`).
    pub reason_code: Option<String>,
    /// `Characteristic/@baselineScore` (default 0.0).
    pub baseline_score: f64,
    /// Ordered attributes; first matching predicate contributes `partialScore`.
    pub attributes: Vec<AttributeIr>,
}

/// One `Attribute` inside a [`CharacteristicIr`].
#[derive(Debug, Clone)]
pub struct AttributeIr {
    /// `Attribute/@partialScore`.
    pub partial_score: f64,
    /// Predicate selecting this attribute.
    pub predicate: PredicateIr,
    /// `Attribute/@reasonCode` (overrides characteristic code when matched).
    pub reason_code: Option<String>,
}

/// Lowered `ClusteringModel`.
#[derive(Debug, Clone)]
pub struct ClusteringIr {
    /// `ClusteringModel/@functionName` (typically `clustering`).
    pub function_name: String,
    /// `ClusteringModel/@modelClass` (`centerBased` / `distributionBased`).
    pub model_class: String,
    /// `ClusteringModel/@numberOfClusters` (fallback to `clusters.len()`).
    pub number_of_clusters: usize,
    /// Mining schema (active fields must match `clusteringFields` subset).
    pub mining_schema: MiningSchemaIr,
    /// `ComparisonMeasure` kind (e.g., `euclidean`, `squaredEuclidean`).
    pub comparison_measure: String,
    /// Fields that define cluster coordinates.
    pub clustering_fields: Vec<FieldId>,
    /// Clusters with centroid / array.
    pub clusters: Vec<ClusterIr>,
    /// Output fields.
    pub output: Vec<OutputFieldIr>,
}

/// Single `Cluster` inside a [`ClusteringIr`].
#[derive(Debug, Clone)]
pub struct ClusterIr {
    /// Interned `Cluster/@name`.
    pub name: SymbolId,
    /// Display name (`Cluster/@name` raw string).
    pub name_str: String,
    /// Coordinate array aligned with `ClusteringIr.clustering_fields`.
    pub array: Vec<f64>,
}

/// Count of a single discrete target value, used in [`PairCountsIr`] and NaiveBayes.
#[derive(Debug, Clone)]
pub struct TargetValueCountIr {
    /// Interned `TargetValueCount/@value`.
    pub value: SymbolId,
    /// `TargetValueCount/@count`.
    pub count: f64,
}

/// Joint counts for one discrete input value vs all target values.
#[derive(Debug, Clone)]
pub struct PairCountsIr {
    /// Input value (e.g., `"sunny"`, interned).
    pub value: SymbolId,
    /// Per-target counts for this input value.
    pub target_counts: Vec<TargetValueCountIr>,
}

/// Gaussian statistics for a continuous input per target value.
///
/// Used when the Bayes input is continuous: `GaussianDistribution` per class.
#[derive(Debug, Clone)]
pub struct TargetValueStatIr {
    /// Target class value (interned).
    pub value: SymbolId,
    /// Mean `μ` (`GaussianDistribution/@mean`), if present.
    pub mean: Option<f64>,
    /// Variance `σ²` (`GaussianDistribution/@variance`), if present.
    pub variance: Option<f64>,
}

/// One `BayesInput` inside a [`NaiveBayesIr`].
#[derive(Debug, Clone)]
pub struct BayesInputIr {
    /// Input field.
    pub field: FieldId,
    /// Continuous per-class Gaussian stats (empty for discrete fields).
    pub target_value_stats: Vec<TargetValueStatIr>,
    /// Discrete joint counts (empty for continuous fields).
    pub pair_counts: Vec<PairCountsIr>,
}

/// Lowered `NaiveBayesModel`.
#[derive(Debug, Clone)]
pub struct NaiveBayesIr {
    /// `NaiveBayesModel/@functionName`.
    pub function_name: String,
    /// `NaiveBayesModel/@threshold` (count threshold for smoothing).
    pub threshold: f64,
    /// Mining schema.
    pub mining_schema: MiningSchemaIr,
    /// Output fields.
    pub output: Vec<OutputFieldIr>,
    /// Bayes inputs (one per field, mixed discrete / continuous).
    pub bayes_inputs: Vec<BayesInputIr>,
    /// Prior counts per target class.
    pub bayes_output_counts: Vec<TargetValueCountIr>,
}

/// Lowered `NearestNeighborModel` (k-NN).
#[derive(Debug, Clone)]
pub struct NearestNeighborIr {
    /// `NearestNeighborModel/@functionName`.
    pub function_name: String,
    /// `NearestNeighborModel/@numberOfNeighbors` (`k`).
    pub number_of_neighbors: usize,
    /// Mining schema.
    pub mining_schema: MiningSchemaIr,
    /// Output fields.
    pub output: Vec<OutputFieldIr>,
    /// `KNNInputs` fields (distance inputs).
    pub knn_inputs: Vec<FieldId>,
    /// Per-instance field values (`InlineTable` rows, as `FieldId → Value`).
    pub instances: Vec<std::collections::HashMap<crate::base::FieldId, crate::base::Value>>,
    /// Raw instance ids in row order (for entity id output).
    pub instance_ids: Vec<String>,
}

/// Lowered `SupportVectorMachineModel`.
#[derive(Debug, Clone)]
pub struct SupportVectorMachineIr {
    /// `SupportVectorMachineModel/@functionName`.
    pub function_name: String,
    /// Mining schema.
    pub mining_schema: MiningSchemaIr,
    /// Output fields.
    pub output: Vec<OutputFieldIr>,
    /// Ordered vector fields (`VectorDictionary/VectorFields/@field`).
    pub vector_fields: Vec<FieldId>,
    /// `(id, array)` pairs from `VectorDictionary` (id + dense vector).
    pub vector_instances: Vec<(String, Vec<f64>)>,
    /// `SupportVector/@vectorId` references in definition order.
    pub support_vectors: Vec<String>,
    /// `Coefficients/@value` in definition order.
    pub coefficients: Vec<f64>,
    /// Absolute value bias (`SupportVectorMachine/@absoluteValue` or `Coefficients` sum).
    pub absolute_value: f64,
    /// `Kernel/@gamma` (RBF `exp(-γ‖x-sv‖²)`).
    pub kernel_gamma: f64,
}

/// Single neural input (`NeuralInput/@id` → `FieldId`).
#[derive(Debug, Clone)]
pub struct NeuralInputIr {
    /// `NeuralInput/@id`.
    pub id: String,
    /// Backing field.
    pub field: FieldId,
}

/// Single neuron with bias and inbound weighted connections.
#[derive(Debug, Clone)]
pub struct NeuronIr {
    /// `Neuron/@id`.
    pub id: String,
    /// `Neuron/@bias` (default 0.0).
    pub bias: f64,
    /// Inbound `Con/@from → @weight`.
    pub cons: Vec<(String, f64)>,
}

/// One layer of neurons with a shared activation function.
#[derive(Debug, Clone)]
pub struct NeuralLayerIr {
    /// `NeuralLayer/@numberOfNeurons` (or `neurons.len()` fallback).
    pub number_of_neurons: usize,
    /// `NeuralLayer/@activationFunction` (e.g., `logistic`, `tanh`, `identity`).
    pub activation_function: String,
    /// Neurons in layer order.
    pub neurons: Vec<NeuronIr>,
}

/// Lowered `NeuralNetwork`.
#[derive(Debug, Clone)]
pub struct NeuralNetworkIr {
    /// `NeuralNetwork/@functionName`.
    pub function_name: String,
    /// Mining schema.
    pub mining_schema: MiningSchemaIr,
    /// Output fields.
    pub output: Vec<OutputFieldIr>,
    /// External inputs (`NeuralInputs`).
    pub neural_inputs: Vec<NeuralInputIr>,
    /// Layers from input-most to output-most.
    pub neural_layers: Vec<NeuralLayerIr>,
    /// `NeuralNetwork/@activationFunction` top-level default.
    pub activation_function: String,
}

/// Parameter of a [`GeneralRegressionIr`] (`Parameter/@name`, optional `@label`).
#[derive(Debug, Clone)]
pub struct ParameterIr {
    /// `Parameter/@name`.
    pub name: String,
    /// `Parameter/@label` (human-readable).
    pub label: Option<String>,
}

/// Factor (categorical covariate) for [`GeneralRegressionIr`].
#[derive(Debug, Clone)]
pub struct FactorIr {
    /// Field id for the factor (`Factor/@name`).
    pub name: FieldId,
    /// Ordered categories (`Factor/@categories` resolved to symbols).
    pub categories: Vec<SymbolId>,
    /// Contrast matrix `rows=categories, cols=parameters`.
    pub matrix: Vec<Vec<f64>>,
}

/// Cell in the predictor-to-parameter matrix (`PPCell`).
#[derive(Debug, Clone)]
pub struct PPCellIr {
    /// `PPCell/@value` (category value, interned).
    pub value: SymbolId,
    /// `PPCell/@predictorName`.
    pub predictor_name: String,
    /// `PPCell/@parameterName`.
    pub parameter_name: String,
}

/// Cell in the parameter matrix (`PCell`).
#[derive(Debug, Clone)]
pub struct PCellIr {
    /// `PCell/@targetCategory` (interned when present).
    pub target_category: Option<SymbolId>,
    /// `PCell/@parameterName`.
    pub parameter_name: String,
    /// `PCell/@beta`.
    pub beta: f64,
}

/// Lowered `GeneralRegressionModel` (GLM / multinomial logistic).
#[derive(Debug, Clone)]
pub struct GeneralRegressionIr {
    /// `GeneralRegressionModel/@functionName`.
    pub function_name: String,
    /// Mining schema.
    pub mining_schema: MiningSchemaIr,
    /// Output fields.
    pub output: Vec<OutputFieldIr>,
    /// `GeneralRegressionModel/@modelType` (`regression`, `generalLinear`, `multinomialLogistic`, …).
    pub model_type: Option<String>,
    /// `GeneralRegressionModel/@targetVariableName`.
    pub target_variable_name: Option<String>,
    /// `GeneralRegressionModel/@targetReferenceCategory`.
    pub target_reference_category: Option<SymbolId>,
    /// `ParameterList` in order.
    pub parameters: Vec<ParameterIr>,
    /// `FactorList`.
    pub factors: Vec<FactorIr>,
    /// `CovariateList` (continuous predictors) as field ids.
    pub covariates: Vec<FieldId>,
    /// `PPMatrix` cells.
    pub pp_matrix: Vec<PPCellIr>,
    /// `ParamMatrix` cells (betas).
    pub param_matrix: Vec<PCellIr>,
}

/// Item in an [`AssociationIr`] (`Item/@id` and category value).
#[derive(Debug, Clone)]
pub struct ItemIr {
    /// `Item/@id`.
    pub id: String,
    /// `Item/@value` category (interned).
    pub value: SymbolId,
}

/// Itemset (`Itemset/@id` with item refs) in an [`AssociationIr`].
#[derive(Debug, Clone)]
pub struct ItemsetIr {
    /// `Itemset/@id`.
    pub id: String,
    /// `Itemset/ItemRef/@itemRef` in order.
    pub item_ids: Vec<String>,
}

/// Association rule: `antecedent => consequent` with support/confidence/lift.
#[derive(Debug, Clone)]
pub struct AssociationRuleIr {
    /// `AssociationRule/@antecedent` (itemset id).
    pub antecedent: String,
    /// `AssociationRule/@consequent` (itemset id).
    pub consequent: String,
    /// `AssociationRule/@support`.
    pub support: f64,
    /// `AssociationRule/@confidence`.
    pub confidence: f64,
    /// `AssociationRule/@lift`.
    pub lift: f64,
}

/// Lowered `AssociationModel` (association rules).
#[derive(Debug, Clone)]
pub struct AssociationIr {
    /// `AssociationModel/@functionName` (typically `associationRules`).
    pub function_name: String,
    /// Mining schema.
    pub mining_schema: MiningSchemaIr,
    /// Output fields.
    pub output: Vec<OutputFieldIr>,
    /// `AssociationModel/Item`s.
    pub items: Vec<ItemIr>,
    /// `AssociationModel/Itemset`s.
    pub itemsets: Vec<ItemsetIr>,
    /// `AssociationModel/AssociationRule`s.
    pub rules: Vec<AssociationRuleIr>,
}

/// Single simple rule (`SimpleRule/@id, @score` with predicate).
#[derive(Debug, Clone)]
pub struct SimpleRuleIr {
    /// `SimpleRule/@id` (may be `None`).
    pub id: Option<String>,
    /// `SimpleRule/@score` (interned category or numeric string).
    pub score: SymbolId,
    /// Predicate that activates the rule.
    pub predicate: PredicateIr,
}

/// Lowered `RuleSetModel` (ordered rules + optional default).
#[derive(Debug, Clone)]
pub struct RuleSetIr {
    /// `RuleSetModel/@functionName`.
    pub function_name: String,
    /// Mining schema.
    pub mining_schema: MiningSchemaIr,
    /// Output fields.
    pub output: Vec<OutputFieldIr>,
    /// `RuleSet/@defaultScore` (interned) when no rule fires.
    pub default_score: Option<SymbolId>,
    /// Rules in PMML order (first match wins in evaluator).
    pub rules: Vec<SimpleRuleIr>,
}

/// Lowered `AnomalyDetectionModel` — wrapper around an embedded model.
///
/// Mirrors `pmml.xsd:AnomalyDetectionModel` (`1718-1737`). The embedded `MODEL-ELEMENT`
/// (`Tree`, `Regression`, `Mining`, `Clustering`, `SVM`, …) is scored first; the outer
/// model then maps the raw score to an anomaly value per `algorithm_type`.
///
/// - `iforest` → `2^(-avg_path / c(n))` where `c(n)=2*H(n-1)-2*(n-1)/n`, `H(k)=ln(k)+γ`.
/// - `clusterMeanDist` → `distance_to_cluster / mean_cluster_distances[cluster]`.
/// - otherwise → raw embedded score.
#[derive(Debug, Clone)]
pub struct AnomalyDetectionIr {
    /// `AnomalyDetectionModel/@functionName`.
    pub function_name: String,
    /// `AnomalyDetectionModel/@algorithmType` (`iforest`, `ocsvm`, `clusterMeanDist`, `other`).
    pub algorithm_type: String,
    /// `AnomalyDetectionModel/@sampleDataSize` parsed as `f64` if present.
    pub sample_data_size: Option<f64>,
    /// Mining schema for the outer model.
    pub mining_schema: MiningSchemaIr,
    /// Output fields.
    pub output: Vec<OutputFieldIr>,
    /// `Targets` (rare for anomaly, but preserved).
    pub targets: Vec<TargetIr>,
    /// Embedded model (`MODEL-ELEMENT`).
    pub model: Box<ModelIr>,
    /// `MeanClusterDistances/Array` values, one per cluster (for `clusterMeanDist`).
    pub mean_cluster_distances: Option<Vec<f64>>,
}

/// Test statistic for `BaselineModel/TestDistributions/@testStatistic`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BaselineTestStatistic {
    /// `zValue` — `(x-mean)/sqrt(var)`.
    ZValue,
    /// `chiSquareIndependence`.
    ChiSquareIndependence,
    /// `chiSquareDistribution`.
    ChiSquareDistribution,
    /// `CUSUM` — `max(reset, prev + log(f1/f0))`.
    Cusum,
    /// `scalarProduct`.
    ScalarProduct,
}

/// Continuous baseline distribution.
#[derive(Debug, Clone)]
pub enum ContinuousDistributionIr {
    /// `AnyDistribution` with `mean`/`variance`.
    Any { mean: f64, variance: f64 },
    /// `GaussianDistribution` with `mean`/`variance`.
    Gaussian { mean: f64, variance: f64 },
    /// `PoissonDistribution` with `mean`.
    Poisson { mean: f64 },
    /// `UniformDistribution` with `lower`/`upper`.
    Uniform { lower: f64, upper: f64 },
}

/// Single `FieldValueCount` inside a `CountTable`.
#[derive(Debug, Clone)]
pub struct FieldValueCountIr {
    /// Field id (`FieldValueCount/@field`).
    pub field: FieldId,
    /// Value symbol (`@value` interned).
    pub value: SymbolId,
    /// Count (`@count`).
    pub count: f64,
}

/// Discrete `CountTable` (or `NormalizedCountTable`).
#[derive(Debug, Clone)]
pub struct CountTableIr {
    /// `CountTable/@sample` if present.
    pub sample: Option<f64>,
    /// Flat `FieldValueCount` entries.
    pub entries: Vec<FieldValueCountIr>,
}

/// Discrete baseline distribution.
#[derive(Debug, Clone)]
pub enum DiscreteDistributionIr {
    /// `CountTable`.
    CountTable(CountTableIr),
    /// `NormalizedCountTable`.
    NormalizedCountTable(CountTableIr),
    /// List of `FieldRef/@field` for `chiSquareIndependence`.
    FieldRefs(Vec<FieldId>),
}

/// Lowered `TestDistributions` inside `BaselineModel`.
#[derive(Debug, Clone)]
pub struct TestDistributionsIr {
    /// `TestDistributions/@field` (target for baseline test).
    pub field: FieldId,
    /// Name of the test field (for materialization).
    pub field_name: String,
    /// `TestDistributions/@testStatistic`.
    pub test_statistic: BaselineTestStatistic,
    /// `TestDistributions/@resetValue` (for `CUSUM`).
    pub reset_value: f64,
    /// `TestDistributions/@windowSize`.
    pub window_size: i32,
    /// `TestDistributions/@weightField` if any.
    pub weight_field: Option<FieldId>,
    /// `TestDistributions/@normalizationScheme` if any.
    pub normalization_scheme: Option<String>,
    /// `Baseline` continuous or discrete.
    pub baseline_continuous: Option<ContinuousDistributionIr>,
    /// Baseline discrete (alternative storage for discrete case).
    pub baseline_discrete: Option<DiscreteDistributionIr>,
    /// `Alternate` continuous (only for `CUSUM`).
    pub alternate: Option<ContinuousDistributionIr>,
}

/// Lowered `BaselineModel` (change-detection).
#[derive(Debug, Clone)]
pub struct BaselineIr {
    /// `BaselineModel/@functionName`.
    pub function_name: String,
    /// Mining schema.
    pub mining_schema: MiningSchemaIr,
    /// Output fields.
    pub output: Vec<OutputFieldIr>,
    /// Targets.
    pub targets: Vec<TargetIr>,
    /// Single `TestDistributions`.
    pub test_distributions: TestDistributionsIr,
}

/// Best-fit algorithm for `TimeSeriesModel/@bestFit`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TimeSeriesAlgorithm {
    ARIMA,
    ExponentialSmoothing,
    SeasonalTrendDecomposition,
    SpectralAnalysis,
    StateSpaceModel,
    GARCH,
}

/// Single `TimeValue` inside `TimeSeries`.
#[derive(Debug, Clone)]
pub struct TimeValueIr {
    pub index: Option<i32>,
    pub time: Option<String>,
    pub value: f64,
    pub standard_error: Option<f64>,
}

/// `TimeCycle` inside `TimeAnchor`.
#[derive(Debug, Clone)]
pub struct TimeCycleIr {
    pub length: Option<i32>,
    pub type_: Option<String>,
    pub display_name: Option<String>,
    pub array: Vec<i32>,
}

/// `TimeException` inside `TimeAnchor`.
#[derive(Debug, Clone)]
pub struct TimeExceptionIr {
    pub type_: String,
    pub count: Option<i32>,
    pub array: Vec<i32>,
}

/// `TimeAnchor` inside `TimeSeries`.
#[derive(Debug, Clone)]
pub struct TimeAnchorIr {
    pub type_: Option<String>,
    pub offset: Option<i32>,
    pub stepsize: Option<i32>,
    pub display_name: Option<String>,
    pub time_cycles: Vec<TimeCycleIr>,
    pub time_exceptions: Vec<TimeExceptionIr>,
}

/// One `TimeSeries` history inside `TimeSeriesModel`.
#[derive(Debug, Clone)]
pub struct TimeSeriesDataIr {
    pub usage: String,
    pub start_time: Option<f64>,
    pub end_time: Option<f64>,
    pub interpolation_method: String,
    pub field: Option<FieldId>,
    pub field_name: Option<String>,
    pub time_anchor: Option<TimeAnchorIr>,
    pub time_values: Vec<TimeValueIr>,
}

/// `Level` for `ExponentialSmoothing`.
#[derive(Debug, Clone)]
pub struct LevelIr {
    pub alpha: Option<f64>,
    pub smoothed_value: f64,
}
/// `Trend_ExpoSmooth` for `ExponentialSmoothing`.
#[derive(Debug, Clone)]
pub struct TrendExpoSmoothIr {
    pub trend: String,
    pub gamma: Option<f64>,
    pub phi: Option<f64>,
    pub smoothed_value: Option<f64>,
    pub array: Vec<f64>,
}
/// `Seasonality_ExpoSmooth` for `ExponentialSmoothing`.
#[derive(Debug, Clone)]
pub struct SeasonalityExpoSmoothIr {
    pub type_: String,
    pub period: i32,
    pub unit: Option<String>,
    pub phase: Option<i32>,
    pub delta: Option<f64>,
    pub array: Vec<f64>,
}
/// Lowered `ExponentialSmoothing`.
#[derive(Debug, Clone)]
pub struct ExponentialSmoothingIr {
    pub rmse: Option<f64>,
    pub transformation: String,
    pub level: LevelIr,
    pub trend: Option<TrendExpoSmoothIr>,
    pub seasonality: Option<SeasonalityExpoSmoothIr>,
    pub time_values: Vec<TimeValueIr>,
}

/// `AR` coefficients.
#[derive(Debug, Clone)]
pub struct ArIr {
    pub array: Vec<f64>,
}
/// `MACoefficients`.
#[derive(Debug, Clone)]
pub struct MaCoefficientsIr {
    pub array: Vec<f64>,
}
/// `Residuals`.
#[derive(Debug, Clone)]
pub struct ResidualsIr {
    pub array: Vec<f64>,
}
/// `MA` with coefficients and residuals.
#[derive(Debug, Clone)]
pub struct MaIr {
    pub ma_coefficients: Option<MaCoefficientsIr>,
    pub residuals: Option<ResidualsIr>,
}
/// `NonseasonalComponent`.
#[derive(Debug, Clone)]
pub struct NonseasonalComponentIr {
    pub p: usize,
    pub d: usize,
    pub q: usize,
    pub ar: Option<ArIr>,
    pub ma: Option<MaIr>,
}
/// `SeasonalComponent`.
#[derive(Debug, Clone)]
pub struct SeasonalComponentIr {
    pub p: usize,
    pub d: usize,
    pub q: usize,
    pub period: usize,
    pub ar: Option<ArIr>,
    pub ma: Option<MaIr>,
}
/// `NonseasonalFactor` for transfer function.
#[derive(Debug, Clone)]
pub struct NonseasonalFactorIr {
    pub difference: Option<i32>,
    pub maximum_order: Option<i32>,
    pub array: Vec<f64>,
}
/// `SeasonalFactor` for transfer function.
#[derive(Debug, Clone)]
pub struct SeasonalFactorIr {
    pub difference: Option<i32>,
    pub maximum_order: Option<i32>,
    pub array: Vec<f64>,
}
/// `Numerator`.
#[derive(Debug, Clone)]
pub struct NumeratorIr {
    pub nonseasonal_factor: Option<NonseasonalFactorIr>,
    pub seasonal_factor: Option<SeasonalFactorIr>,
}
/// `Denominator`.
#[derive(Debug, Clone)]
pub struct DenominatorIr {
    pub nonseasonal_factor: Option<NonseasonalFactorIr>,
    pub seasonal_factor: Option<SeasonalFactorIr>,
}
/// `TrendCoefficients`.
#[derive(Debug, Clone)]
pub struct TrendCoefficientsIr {
    pub array: Vec<f64>,
}
/// `TransferFunctionValues`.
#[derive(Debug, Clone)]
pub struct TransferFunctionValuesIr {
    pub array: Vec<f64>,
}
/// `RegressorValues`.
#[derive(Debug, Clone)]
pub struct RegressorValuesIr {
    pub time_series: Option<Box<TimeSeriesDataIr>>,
    pub trend_coefficients: Option<TrendCoefficientsIr>,
    pub transfer_function_values: Option<TransferFunctionValuesIr>,
}
/// `DynamicRegressor`.
#[derive(Debug, Clone)]
pub struct DynamicRegressorIr {
    pub field: FieldId,
    pub field_name: String,
    pub transformation: String,
    pub delay: i32,
    pub future_values_method: String,
    pub target_field: Option<FieldId>,
    pub numerator: Option<NumeratorIr>,
    pub denominator: Option<DenominatorIr>,
    pub regressor_values: Option<RegressorValuesIr>,
}
/// `Theta` entry.
#[derive(Debug, Clone)]
pub struct ThetaIr {
    pub i: Option<i32>,
    pub j: Option<i32>,
    pub theta: f64,
}
#[derive(Debug, Clone)]
pub struct FinalThetaIr {
    pub thetas: Vec<ThetaIr>,
}
#[derive(Debug, Clone)]
pub struct FinalNoiseIr {
    pub array: Vec<f64>,
}
#[derive(Debug, Clone)]
pub struct FinalPredictedNoiseIr {
    pub array: Vec<f64>,
}
#[derive(Debug, Clone)]
pub struct FinalNuIr {
    pub array: Vec<f64>,
}
#[derive(Debug, Clone)]
pub struct FinalStateVectorIr {
    pub array: Vec<f64>,
}
#[derive(Debug, Clone)]
pub struct HVectorIr {
    pub array: Vec<f64>,
}
#[derive(Debug, Clone)]
pub struct FinalOmegaIr {
    pub matrix: Vec<Vec<f64>>,
}
#[derive(Debug, Clone)]
pub struct KalmanStateIr {
    pub final_omega: Option<FinalOmegaIr>,
    pub final_state_vector: Option<FinalStateVectorIr>,
    pub h_vector: Option<HVectorIr>,
}
#[derive(Debug, Clone)]
pub struct ThetaRecursionStateIr {
    pub final_noise: Option<FinalNoiseIr>,
    pub final_predicted_noise: Option<FinalPredictedNoiseIr>,
    pub final_theta: Option<FinalThetaIr>,
    pub final_nu: Option<FinalNuIr>,
}
#[derive(Debug, Clone)]
pub struct MaximumLikelihoodStatIr {
    pub method: String,
    pub period_deficit: i32,
    pub kalman_state: Option<KalmanStateIr>,
    pub theta_recursion_state: Option<ThetaRecursionStateIr>,
}
#[derive(Debug, Clone)]
pub struct OutlierEffectIr {
    pub type_: String,
    pub start_time: f64,
    pub magnitude: f64,
    pub damping_coefficient: Option<f64>,
}
/// Lowered `ARIMA`.
#[derive(Debug, Clone)]
pub struct ArimaIr {
    pub rmse: Option<f64>,
    pub transformation: String,
    pub constant_term: f64,
    pub prediction_method: String,
    pub nonseasonal_component: Option<NonseasonalComponentIr>,
    pub seasonal_component: Option<SeasonalComponentIr>,
    pub dynamic_regressors: Vec<DynamicRegressorIr>,
    pub maximum_likelihood_stat: Option<MaximumLikelihoodStatIr>,
    pub outlier_effects: Vec<OutlierEffectIr>,
}
/// `ARMAPart` for GARCH.
#[derive(Debug, Clone)]
pub struct ArmaPartIr {
    pub constant: f64,
    pub p: i32,
    pub q: i32,
    pub ar: Option<ArIr>,
    pub ma: Option<MaIr>,
}
#[derive(Debug, Clone)]
pub struct PastVariancesIr {
    pub array: Vec<f64>,
}
#[derive(Debug, Clone)]
pub struct ResidualSquareCoefficientsIr {
    pub residuals: Option<ResidualsIr>,
    pub ma_coefficients: Option<MaCoefficientsIr>,
}
#[derive(Debug, Clone)]
pub struct VarianceCoefficientsIr {
    pub past_variances: Option<PastVariancesIr>,
    pub ma_coefficients: Option<MaCoefficientsIr>,
}
#[derive(Debug, Clone)]
pub struct GarchPartIr {
    pub constant: f64,
    pub gp: i32,
    pub gq: i32,
    pub residual_square_coefficients: Option<ResidualSquareCoefficientsIr>,
    pub variance_coefficients: Option<VarianceCoefficientsIr>,
}
#[derive(Debug, Clone)]
pub struct GarchIr {
    pub arma_part: Option<ArmaPartIr>,
    pub garch_part: Option<GarchPartIr>,
}
/// `StateVector` etc for StateSpace.
#[derive(Debug, Clone)]
pub struct StateVectorIr {
    pub array: Vec<f64>,
}
#[derive(Debug, Clone)]
pub struct TransitionMatrixIr {
    pub matrix: Vec<Vec<f64>>,
}
#[derive(Debug, Clone)]
pub struct MeasurementMatrixIr {
    pub matrix: Vec<Vec<f64>>,
}
#[derive(Debug, Clone)]
pub struct InterceptVectorIr {
    pub type_: Option<String>,
    pub array: Vec<f64>,
}
#[derive(Debug, Clone)]
pub struct PredictedStateCovarianceMatrixIr {
    pub matrix: Vec<Vec<f64>>,
}
#[derive(Debug, Clone)]
pub struct SelectedStateCovarianceMatrixIr {
    pub matrix: Vec<Vec<f64>>,
}
#[derive(Debug, Clone)]
pub struct ObservationVarianceMatrixIr {
    pub matrix: Vec<Vec<f64>>,
}
#[derive(Debug, Clone)]
pub struct PsiVectorIr {
    pub target_field: Option<String>,
    pub variance: Option<String>,
    pub array: Vec<f64>,
}
#[derive(Debug, Clone)]
pub struct StateSpaceModelIr {
    pub variance: Option<f64>,
    pub period: Option<String>,
    pub intercept: f64,
    pub state_vector: Option<StateVectorIr>,
    pub transition_matrix: Option<TransitionMatrixIr>,
    pub measurement_matrix: Option<MeasurementMatrixIr>,
    pub intercept_vector: Option<InterceptVectorIr>,
    pub predicted_state_covariance_matrix: Option<PredictedStateCovarianceMatrixIr>,
    pub selected_state_covariance_matrix: Option<SelectedStateCovarianceMatrixIr>,
    pub observation_variance_matrix: Option<ObservationVarianceMatrixIr>,
    pub psi_vector: Option<PsiVectorIr>,
    pub dynamic_regressors: Vec<DynamicRegressorIr>,
}
#[derive(Debug, Clone)]
pub struct SpectralAnalysisIr {}
#[derive(Debug, Clone)]
pub struct SeasonalTrendDecompositionIr {}
/// Lowered `TimeSeriesModel`.
#[derive(Debug, Clone)]
pub struct TimeSeriesIr {
    pub function_name: String,
    pub model_name: Option<String>,
    pub algorithm_name: Option<String>,
    pub best_fit: TimeSeriesAlgorithm,
    pub is_scorable: bool,
    pub mining_schema: MiningSchemaIr,
    pub output: Vec<OutputFieldIr>,
    pub targets: Vec<TargetIr>,
    pub time_series: Vec<TimeSeriesDataIr>,
    pub spectral_analysis: Option<SpectralAnalysisIr>,
    pub arima: Option<ArimaIr>,
    pub exponential_smoothing: Option<ExponentialSmoothingIr>,
    pub seasonal_trend_decomposition: Option<SeasonalTrendDecompositionIr>,
    pub state_space_model: Option<StateSpaceModelIr>,
    pub garch: Option<GarchIr>,
}

/// Kernel for `GaussianProcessIr`.
#[derive(Debug, Clone)]
pub enum GaussianKernelIr {
    /// `RadialBasisKernel` — `exp(-gamma * lambda * ||x-y||^2)`.
    RadialBasis {
        gamma: f64,
        noise_variance: f64,
        lambda: f64,
        description: Option<String>,
    },
    /// `ARDSquaredExponentialKernel` — `exp(-gamma * Σ (diff^2)/(2*lambda_i^2))`.
    ARDSquaredExponential {
        gamma: f64,
        noise_variance: f64,
        lambdas: Vec<Vec<f64>>,
        description: Option<String>,
    },
    /// `AbsoluteExponentialKernel` — `exp(-gamma * Σ |diff|/lambda_i)`.
    AbsoluteExponential {
        gamma: f64,
        noise_variance: f64,
        lambdas: Vec<Vec<f64>>,
        description: Option<String>,
    },
    /// `GeneralizedExponentialKernel` — `exp(-gamma * ||x-y||^degree)`.
    GeneralizedExponential {
        gamma: f64,
        noise_variance: f64,
        lambdas: Vec<Vec<f64>>,
        degree: f64,
        description: Option<String>,
    },
}

/// Lowered `GaussianProcessModel`.
#[derive(Debug, Clone)]
pub struct GaussianProcessIr {
    /// `GaussianProcessModel/@functionName`.
    pub function_name: String,
    /// `GaussianProcessModel/@modelName`.
    pub model_name: Option<String>,
    /// Mining schema.
    pub mining_schema: MiningSchemaIr,
    /// Output fields.
    pub output: Vec<OutputFieldIr>,
    /// Targets.
    pub targets: Vec<TargetIr>,
    /// Kernel choice.
    pub kernel: GaussianKernelIr,
    /// `TrainingInstances` instance fields (for column mapping).
    pub instance_fields: Vec<FieldId>,
    /// Training rows as dense maps `FieldId -> Value`.
    pub training_instances:
        Vec<std::collections::HashMap<crate::base::FieldId, crate::base::Value>>,
    /// Training inputs pre-parsed as numeric vectors aligned with `instance_fields` / active fields for fast kernel.
    pub training_vectors: Vec<Vec<f64>>,
    /// Training target values aligned with `training_instances` for regression (`Continuous`) or classification (`Discrete`).
    pub training_targets: Vec<crate::base::Value>,
    /// `TrainingInstances/@isTransformed`.
    pub is_transformed: bool,
}

/// A single document in `TextModel` corpus.
#[derive(Debug, Clone)]
pub struct TextDocumentIr {
    /// `TextDocument/@id`.
    pub id: String,
    /// Interned `TextDocument/@id` as `SymbolId`.
    pub id_symbol: SymbolId,
    /// `TextDocument/@name`.
    pub name: Option<String>,
}

/// Normalization for `TextModel`.
#[derive(Debug, Clone)]
pub struct TextNormalizationIr {
    /// `localTermWeights` (`termFrequency`, `binary`, `logarithmic`, `augmentedNormalizedTermFrequency`).
    pub local_term_weights: String,
    /// `globalTermWeights` (`inverseDocumentFrequency`, `none`, `GFIDF`, etc.).
    pub global_term_weights: String,
    /// `documentNormalization` (`none`, `cosine`).
    pub document_normalization: String,
}

/// Similarity metric for `TextModel`.
#[derive(Debug, Clone)]
pub struct TextSimilarityIr {
    /// `similarityType` (`cosine`, `euclidean`).
    pub similarity_type: String,
}

/// Lowered `TextModel`.
#[derive(Debug, Clone)]
pub struct TextIr {
    /// `TextModel/@functionName`.
    pub function_name: String,
    /// `TextModel/@modelName`.
    pub model_name: Option<String>,
    /// Mining schema.
    pub mining_schema: MiningSchemaIr,
    /// Output fields.
    pub output: Vec<OutputFieldIr>,
    /// Targets.
    pub targets: Vec<TargetIr>,
    /// `TextDictionary` terms in order (`numberOfTerms == terms.len()`).
    pub dictionary: Vec<String>,
    /// `TextCorpus` documents in order.
    pub corpus: Vec<TextDocumentIr>,
    /// `DocumentTermMatrix` dense rows `docs x terms`.
    pub document_term_matrix: Vec<Vec<f64>>,
    /// Optional `TextModelNormalization`.
    pub normalization: Option<TextNormalizationIr>,
    /// Optional `TextModelSimiliarity`.
    pub similarity: Option<TextSimilarityIr>,
    /// `TextModel/@numberOfTerms`.
    pub number_of_terms: usize,
    /// `TextModel/@numberOfDocuments`.
    pub number_of_documents: usize,
}

/// Constraints for `SequenceIr`.
#[derive(Debug, Clone)]
pub struct SequenceConstraintsIr {
    pub minimum_number_of_items: Option<usize>,
    pub maximum_number_of_items: Option<usize>,
    pub minimum_support: Option<f64>,
    pub minimum_confidence: Option<f64>,
}

/// SetPredicate for `SequenceIr`.
#[derive(Debug, Clone)]
pub struct SetPredicateIr {
    pub id: String,
    pub field: FieldId,
    pub values: Vec<SymbolId>,
}

/// Delimiter for Sequence.
#[derive(Debug, Clone)]
pub struct DelimiterIr {
    pub delimiter: String,
    pub gap: String,
}

/// Time statistics.
#[derive(Debug, Clone)]
pub struct TimeIr {
    pub min: Option<f64>,
    pub max: Option<f64>,
    pub mean: Option<f64>,
    pub standard_deviation: Option<f64>,
}

/// Sequence — ordered sets.
#[derive(Debug, Clone)]
pub struct SequenceIr {
    pub id: String,
    pub number_of_sets: Option<usize>,
    pub occurrence: Option<i64>,
    pub support: Option<f64>,
    pub sets: Vec<String>,
    pub follow_sets: Vec<(DelimiterIr, Option<TimeIr>, String)>,
    pub time: Option<TimeIr>,
}

/// SequenceRule — antecedent -> consequent.
#[derive(Debug, Clone)]
pub struct SequenceRuleIr {
    pub id: String,
    pub number_of_sets: usize,
    pub occurrence: i64,
    pub support: f64,
    pub confidence: f64,
    pub lift: Option<f64>,
    pub antecedent: String,
    pub consequent: String,
    pub delimiter: DelimiterIr,
    pub time_between: Option<TimeIr>,
    pub time_total: Option<TimeIr>,
}

/// Lowered `SequenceModel`.
#[derive(Debug, Clone)]
pub struct SequenceModelIr {
    pub function_name: String,
    pub mining_schema: MiningSchemaIr,
    pub output: Vec<OutputFieldIr>,
    pub targets: Vec<TargetIr>,
    pub constraints: Option<SequenceConstraintsIr>,
    pub items: Vec<ItemIr>,
    pub itemsets: Vec<ItemsetIr>,
    pub set_predicates: Vec<SetPredicateIr>,
    pub sequences: Vec<SequenceIr>,
    pub sequence_rules: Vec<SequenceRuleIr>,
}

/// Parent value for Bayesian.
#[derive(Debug, Clone)]
pub struct BayesianParentValueIr {
    pub parent: FieldId,
    pub value: SymbolId,
}

/// Value probability for Bayesian discrete.
#[derive(Debug, Clone)]
pub struct BayesianValueProbabilityIr {
    pub value: SymbolId,
    pub probability: f64,
}

/// Discrete conditional probability table.
#[derive(Debug, Clone)]
pub struct DiscreteConditionalTableIr {
    pub parent_values: Vec<BayesianParentValueIr>,
    pub value_probabilities: Vec<BayesianValueProbabilityIr>,
    pub count: Option<f64>,
}

/// Continuous distribution bytecode for Bayesian.
#[derive(Debug, Clone)]
pub enum BayesianContinuousDistributionIr {
    Normal {
        mean: Vec<Op>,
        variance: Vec<Op>,
    },
    Lognormal {
        mean: Vec<Op>,
        variance: Vec<Op>,
    },
    Uniform {
        lower: Vec<Op>,
        upper: Vec<Op>,
    },
    Triangular {
        mean: Vec<Op>,
        lower: Vec<Op>,
        upper: Vec<Op>,
    },
}

/// Continuous conditional probability.
#[derive(Debug, Clone)]
pub struct ContinuousConditionalTableIr {
    pub parent_values: Vec<BayesianParentValueIr>,
    pub distributions: Vec<BayesianContinuousDistributionIr>,
    pub count: Option<f64>,
}

/// Discrete Bayesian node.
#[derive(Debug, Clone)]
pub struct DiscreteBayesianNodeIr {
    pub name: String,
    pub field: FieldId,
    pub count: Option<f64>,
    pub value_probabilities: Vec<BayesianValueProbabilityIr>,
    pub conditional_tables: Vec<DiscreteConditionalTableIr>,
    pub derived_fields: Vec<DerivedFieldIr>,
}

/// Continuous Bayesian node.
#[derive(Debug, Clone)]
pub struct ContinuousBayesianNodeIr {
    pub name: String,
    pub field: FieldId,
    pub count: Option<f64>,
    pub distributions: Vec<BayesianContinuousDistributionIr>,
    pub conditional_tables: Vec<ContinuousConditionalTableIr>,
    pub derived_fields: Vec<DerivedFieldIr>,
}

/// Bayesian node enum.
#[derive(Debug, Clone)]
pub enum BayesianNodeIr {
    Discrete(DiscreteBayesianNodeIr),
    Continuous(ContinuousBayesianNodeIr),
}

/// Lowered `BayesianNetworkModel`.
#[derive(Debug, Clone)]
pub struct BayesianNetworkIr {
    pub function_name: String,
    pub model_name: Option<String>,
    pub algorithm_name: Option<String>,
    pub model_type: Option<String>,
    pub inference_method: Option<String>,
    pub is_scorable: bool,
    pub mining_schema: MiningSchemaIr,
    pub output: Vec<OutputFieldIr>,
    pub targets: Vec<TargetIr>,
    pub nodes: Vec<BayesianNodeIr>,
}

/// Lowered `TreeModel`.
#[derive(Debug, Clone)]
pub struct TreeIr {
    /// `TreeModel/@functionName` (`classification` / `regression`).
    pub function_name: String,
    /// `TreeModel/@missingValueStrategy` (how to route missing during traversal).
    pub missing_value_strategy: MissingValueStrategy,
    /// `TreeModel/@noTrueChildStrategy` (what to return when no child predicate holds).
    pub no_true_child_strategy: NoTrueChildStrategy,
    /// Flat node list; root at index 0. See [`NodeIr`].
    pub nodes: Vec<NodeIr>,
    /// Mining schema for this tree (active inputs + optional target).
    pub mining_schema: MiningSchemaIr,
    /// `Targets` (rescaling / casting after tree score).
    pub targets: Vec<TargetIr>,
    /// `Output` fields (probability, predictedDisplayValue, etc.).
    pub output: Vec<OutputFieldIr>,
}

/// How to handle `Missing` during tree traversal (`TreeModel/@missingValueStrategy`).
///
/// Mirrors PMML behaviour. The unsupported variants `WeightedConfidence` and
/// `AggregateNodes` are never produced by lowering (they would have been rejected
/// earlier), but are preserved in the enum for `verify_ir` parity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MissingValueStrategy {
    /// Use the last non-missing prediction on the path (`lastPrediction`).
    LastPrediction,
    /// Return `Missing` / null prediction (`nullPrediction`).
    NullPrediction,
    /// Follow `Node/@defaultChild` (`defaultChild`).
    DefaultChild,
    /// No special handling (`none`).
    None,
    /// PMML-unsupported: weighted confidence fallback (`weightedConfidence`).
    WeightedConfidence,
    /// PMML-unsupported: aggregate over leaves (`aggregateNodes`).
    AggregateNodes,
}

/// How to handle the case that no child predicate is true (`TreeModel/@noTrueChildStrategy`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NoTrueChildStrategy {
    /// Return `Missing` / null (`returnNullPrediction`).
    ReturnNullPrediction,
    /// Return last prediction on the path (`returnLastPrediction`).
    ReturnLastPrediction,
}

/// Single node in a [`TreeIr`] (`Node/@id, @score` + predicate + children).
///
/// Nodes are stored flat: children are indices into `TreeIr.nodes`. `default_child`
/// is an index (not an id) resolved during lowering.
#[derive(Debug, Clone)]
pub struct NodeIr {
    /// `Node/@id` (stable identifier for `defaultChild` resolution).
    pub id: Option<String>,
    /// `Node/@score` (`Continuous(f64)` for regression, `Symbol` for classification).
    pub score: Option<SymbolIdOrContinuous>,
    /// Predicate tested at this node (`True` for the root).
    pub predicate: PredicateIr,
    /// Indices of child nodes in `TreeIr.nodes` (DFS order from `flatten_node`).
    pub children: Vec<usize>,
    /// Index of the `defaultChild` when `missingValueStrategy = defaultChild`.
    pub default_child: Option<usize>,
    /// `ScoreDistribution` (class probabilities per node, for `Output/probability`).
    pub score_distributions: Vec<ScoreDistributionIr>,
}

/// Predicate tested at a tree node or segment / rule.
#[derive(Debug, Clone)]
pub enum PredicateIr {
    /// Unconditional true (`True` / root predicate).
    True,
    /// `SimplePredicate`: `field operator value`.
    Simple {
        /// Field under test.
        field: FieldId,
        /// Operator (`equal`, `lessThan`, `isMissing`, etc.).
        operator: SimpleOperator,
        /// Value or `Missing` when operator is `isMissing` / `isNotMissing`.
        value: SymbolIdOrContinuous,
    },
    /// `SimpleSetPredicate`: `field isIn {values}` or `isNotIn`.
    SimpleSet {
        /// Field under test.
        field: FieldId,
        /// When `true` → `isIn`; `false` → `isNotIn`.
        is_in: bool,
        /// Set of values (already coerced per field `DataType`).
        array: Vec<SymbolIdOrContinuous>,
    },
    /// `CompoundPredicate`: `and` / `or` / `xor` / `surrogate` over sub-predicates.
    Compound {
        /// Logical operator.
        operator: CompoundOperator,
        /// Boxed sub-predicates, pooled in a `SmallVec` for typical arities 1–4.
        predicates: SmallVec<[Box<PredicateIr>; 4]>,
    },
}

/// Operator for a [`PredicateIr::Simple`] (`SimplePredicate/@operator`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SimpleOperator {
    /// `equal`.
    Equal,
    /// `notEqual`.
    NotEqual,
    /// `lessThan`.
    LessThan,
    /// `lessOrEqual`.
    LessOrEqual,
    /// `greaterThan`.
    GreaterThan,
    /// `greaterOrEqual`.
    GreaterOrEqual,
    /// `isMissing`.
    IsMissing,
    /// `isNotMissing`.
    IsNotMissing,
}

/// Operator for a [`PredicateIr::Compound`] (`CompoundPredicate/@booleanOperator`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompoundOperator {
    /// `and`.
    And,
    /// `or`.
    Or,
    /// `xor`.
    Xor,
    /// `surrogate`.
    Surrogate,
}

/// Class distribution at a node (`ScoreDistribution/@value, @recordCount`).
#[derive(Debug, Clone)]
pub struct ScoreDistributionIr {
    /// Class value (interned).
    pub value: SymbolId,
    /// `recordCount` (weight, may be 0).
    pub record_count: f64,
}

/// Integer cast method for a [`TargetIr`] (`Target/@castInteger` may carry `Round | Ceiling | Floor`).
///
/// Mirrors PMML `CastInteger`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CastIntegerMethod {
    /// Round to nearest (`round`).
    Round,
    /// Round toward `+∞` (`ceiling`).
    Ceiling,
    /// Round toward `-∞` (`floor`).
    Floor,
}

/// Single `TargetValue` entry inside a [`TargetIr`].
#[derive(Debug, Clone)]
pub struct TargetValueIr {
    /// `TargetValue/@value` (interned) when present.
    pub value: Option<SymbolId>,
    /// Raw string of `TargetValue/@value` (preserved for round-trip).
    pub value_str: Option<String>,
    /// `TargetValue/@displayValue`.
    pub display_value: Option<String>,
    /// `TargetValue/@priorProbability`.
    pub prior_probability: Option<f64>,
    /// `TargetValue/@defaultValue` (used for `MiningModel/modelChain`).
    pub default_value: Option<f64>,
}

/// Lowered `Target` (`Targets/Target`).
///
/// Controls post-processing of the raw model score: rescaling (`rescaleFactor`,
/// `rescaleConstant`), optional clamping (`min`, `max`), and optional integer
/// casting. Evaluator applies these in PMML order.
#[derive(Debug, Clone)]
pub struct TargetIr {
    /// `Target/@field` resolved to `FieldId` when declared (synthetic if needed).
    pub field: Option<FieldId>,
    /// Canonical target field name (raw `Target/@field` or `"target"` fallback).
    pub field_name: String,
    /// `Target/@opType` when explicitly declared.
    pub op_type: Option<OpType>,
    /// `Target/@rescaleConstant` (additive, default 0.0).
    pub rescale_constant: f64,
    /// `Target/@rescaleFactor` (multiplicative, default 1.0).
    pub rescale_factor: f64,
    /// `true` when any `castInteger` was declared (backward compat flag).
    pub cast_integer: bool,
    /// Integer cast method, if declared.
    pub cast_method: Option<CastIntegerMethod>,
    /// `Target/@min` (clamp low).
    pub min: Option<f64>,
    /// `Target/@max` (clamp high).
    pub max: Option<f64>,
    /// `TargetValue` entries in document order.
    pub target_values: Vec<TargetValueIr>,
}

/// Requested output feature for association rules (`OutputField/@ruleFeature`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RuleFeature {
    /// `antecedent`.
    Antecedent,
    /// `consequent`.
    Consequent,
    /// `rule` (antecedent + consequent).
    Rule,
    /// `ruleId`.
    RuleId,
    /// `confidence`.
    Confidence,
    /// `support`.
    Support,
    /// `lift`.
    Lift,
    /// `leverage`.
    Leverage,
    /// `affinity`.
    Affinity,
}

/// Algorithm for ranking / recommending association rules (`OutputField/@algorithm`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Algorithm {
    /// `recommendation`.
    Recommendation,
    /// `exclusiveRecommendation`.
    ExclusiveRecommendation,
    /// `ruleAssociation`.
    RuleAssociation,
}

/// Basis for ranking association rules (`OutputField/@rankBasis`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RankBasis {
    /// Rank by `confidence`.
    Confidence,
    /// Rank by `support`.
    Support,
    /// Rank by `lift`.
    Lift,
    /// Rank by `leverage`.
    Leverage,
    /// Rank by `affinity`.
    Affinity,
}

/// Order for ranking (`OutputField/@rankOrder`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RankOrder {
    /// Highest-rank first.
    Descending,
    /// Lowest-rank first.
    Ascending,
}

/// Lowered `OutputField` (`Output/OutputField`).
///
/// Describes a requested output: feature, rank / multi-valued handling, and
/// optional expression bytecode for `transformedValue` / `decision`.
///
/// # Examples
///
/// ```
/// use pmmlruntime::ir::{OutputFieldIr, RankBasis, RankOrder};
/// use pmmlruntime::base::ResultFeature;
/// let of = OutputFieldIr {
///     name: "probability".into(),
///     feature: ResultFeature::Probability,
///     value: None,
///     field: None,
///     target_field: None,
///     data_type: None,
///     op_type: None,
///     rule_feature: None,
///     algorithm: None,
///     rank: 1,
///     rank_basis: RankBasis::Confidence,
///     rank_order: RankOrder::Descending,
///     is_multi_valued: false,
///     segment_id: None,
///     is_final_result: true,
///     display_name: None,
///     expression_bytecode: None,
/// };
/// assert_eq!(of.feature, ResultFeature::Probability);
/// ```
#[derive(Debug, Clone)]
pub struct OutputFieldIr {
    /// `OutputField/@name`.
    pub name: String,
    /// `OutputField/@feature` (default `predictedValue`).
    pub feature: ResultFeature,
    /// `OutputField/@value` category (interned) when feature is probability etc. for a specific value.
    pub value: Option<SymbolId>,
    /// `OutputField/@field` or resolved alias for probability / affinity fields.
    pub field: Option<FieldId>,
    /// `OutputField/@targetField` (explicit target).
    pub target_field: Option<FieldId>,
    /// `OutputField/@dataType` when declared (otherwise inferred from feature).
    pub data_type: Option<DataType>,
    /// `OutputField/@opType` when declared.
    pub op_type: Option<OpType>,
    /// `OutputField/@ruleFeature` for association outputs.
    pub rule_feature: Option<RuleFeature>,
    /// `OutputField/@algorithm` for rule ranking.
    pub algorithm: Option<Algorithm>,
    /// `OutputField/@rank` (default 1).
    pub rank: i32,
    /// `OutputField/@rankBasis` (default `confidence`).
    pub rank_basis: RankBasis,
    /// `OutputField/@rankOrder` (default `descending`).
    pub rank_order: RankOrder,
    /// `OutputField/@isMultiValued` (`1` / `true` → `true`).
    pub is_multi_valued: bool,
    /// `OutputField/@segmentId` restricting output to a MiningModel segment.
    pub segment_id: Option<String>,
    /// `OutputField/@isFinalResult` (default `true`; `false` exposes intermediate Segmentation outputs).
    pub is_final_result: bool,
    /// `OutputField/@displayName`.
    pub display_name: Option<String>,
    /// Expression bytecode for `transformedValue` / `decision` (future use, `None` today).
    pub expression_bytecode: Option<Vec<Op>>,
}

/// Vendor extension (`Extension/@extender, @name, @value`).
///
/// Extensions are stored by lowering but never evaluated (D1 graceful handling).
/// See [`Ir::extensions`] and [`crate::ir::verify::verify_raw`].
#[derive(Debug, Clone)]
pub struct ExtensionIr {
    /// `Extension/@extender` (vendor, e.g., `"KNIME"`).
    pub extender: Option<String>,
    /// `Extension/@name` (vendor key).
    pub name: Option<String>,
    /// `Extension/@value` (payload string).
    pub value: Option<String>,
}

/// Top-level optimized representation consumed by the hot path.
///
/// Produced once by [`crate::ir::lower::lower()`] and held as `Arc<Ir>` in
/// `pmml-session`. All [`FieldId`]s and [`SymbolId`]s in `data_dictionary`,
/// `derived_fields`, and `model` are keys in `field_names` / `symbol_names`.
///
/// # Invariants
///
/// - Every [`FieldId`] referenced in `mining_schema` / `DerivedFieldIr` is
///   present in `field_names`.
/// - `num_fields()` equals `data_dictionary.len() + derived_fields.len()` (see
///   [`Ir::num_fields`]).
///
/// # Examples
///
/// ```
/// use pmmlruntime::xml::unmarshal;
/// use pmmlruntime::ir::lower;
/// let xml = br#"<PMML version="4.4"><Header/><DataDictionary><DataField name="x" dataType="double" optype="continuous"/></DataDictionary><TreeModel functionName="classification"><MiningSchema><MiningField name="x"/></MiningSchema><Node score="a"><True/></Node></TreeModel></PMML>"#;
/// let raw = unmarshal(xml).unwrap();
/// let ir = lower(raw).unwrap();
/// assert_eq!(ir.data_dictionary.len(), 1);
/// assert_eq!(ir.num_fields(), 1);
/// ```
#[derive(Debug, Clone)]
pub struct Ir {
    /// DataDictionary fields in document order (always includes every `DataField`).
    pub data_dictionary: Vec<FieldMeta>,
    /// Topologically-sorted derived fields from `TransformationDictionary` + model-local transforms.
    pub derived_fields: Vec<DerivedFieldIr>,
    /// The single scoring model for this PMML file.
    pub model: ModelIr,
    /// Snapshot of `field_name → FieldId` at lowering time for pretty-printing and session layout.
    pub field_names: std::collections::HashMap<FieldId, String>,
    /// Snapshot of `symbol_string → SymbolId` at lowering time (discrete values, category names, scores).
    pub symbol_names: std::collections::HashMap<SymbolId, String>,
    /// Vendor extensions stored but not evaluated (plan D1 graceful handling).
    pub extensions: Vec<ExtensionIr>,
    /// Audit: PMML 4.4 `pmml.xsd` element coverage (304 of 304 addressed, see `docs/PLAN.md` §1.5).
    pub element_coverage: usize,
}

impl Ir {
    /// Total field count: `data_dictionary.len() + derived_fields.len()`.
    ///
    /// Determines the length of the hot-path `&mut [crate::base::Value]` array
    /// allocated in `pmml-session` (actually `max_field_id` vs `num_fields()+4`,
    /// but never less than 16). See crate-level docs.
    ///
    /// # Examples
    ///
    /// ```
    /// use pmmlruntime::xml::unmarshal;
    /// use pmmlruntime::ir::lower;
    /// let xml = br#"<PMML version="4.4"><Header/><DataDictionary><DataField name="a" dataType="double" optype="continuous"/></DataDictionary><RegressionModel functionName="regression"><MiningSchema><MiningField name="a"/></MiningSchema><RegressionTable intercept="0"/></RegressionModel></PMML>"#;
    /// let ir = lower(unmarshal(xml).unwrap()).unwrap();
    /// assert_eq!(ir.num_fields(), 1);
    /// ```
    #[must_use]
    pub fn num_fields(&self) -> usize {
        self.data_dictionary.len() + self.derived_fields.len()
    }
}