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
/// A model consists of a series of coupled components which are solved together.
/// The model orchastrates the passing of state between different components.
/// Each component is solved for a given time step in an order determined by their
/// dependencies.
/// Once all components and state is solved for, the model will move to the next time step.
/// The state from previous steps is preserved as it is useful as output or in the case where
/// a component needs previous values.
///
/// The model also holds all of the exogenous variables required by the model.
/// The required variables are identified when building the model.
/// If a required exogenous variable isn't provided, then the build step will fail.
use crate::component::{
Component, GridType, InputState, OutputState, RequirementDefinition, RequirementType,
};
use crate::errors::{RSCMError, RSCMResult};
use crate::interpolate::strategies::{InterpolationStrategy, LinearSplineStrategy};
use crate::schema::VariableSchema;
use crate::spatial::{FourBoxGrid, FourBoxRegion, HemisphericGrid, ScalarRegion};
use crate::state::{HemisphericSlice, StateValue};
use crate::timeseries::{FloatValue, Time, TimeAxis, Timeseries};
use crate::timeseries_collection::{TimeseriesCollection, TimeseriesData, VariableType};
use numpy::ndarray::Array;
use petgraph::dot::{Config, Dot};
use petgraph::graph::NodeIndex;
use petgraph::visit::{Bfs, IntoNeighbors, IntoNodeIdentifiers, Visitable};
use petgraph::Graph;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::ops::Index;
use std::sync::Arc;
type C = Arc<dyn Component>;
type CGraph = Graph<C, RequirementDefinition>;
#[derive(Debug)]
struct VariableDefinition {
name: String,
unit: String,
grid_type: GridType,
}
impl VariableDefinition {
fn from_requirement_definition(definition: &RequirementDefinition) -> Self {
Self {
name: definition.name.clone(),
unit: definition.unit.clone(),
grid_type: definition.grid_type,
}
}
}
/// Direction of a grid transformation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TransformDirection {
/// Read-side: aggregating schema data before component reads it
/// (e.g., schema has FourBox, component wants Scalar)
Read,
/// Write-side: aggregating component output before storing in schema
/// (e.g., component produces FourBox, schema wants Scalar)
Write,
}
/// A required grid transformation identified during validation.
///
/// These are collected during component validation against the schema
/// and used to configure runtime grid aggregation (transform-on-read/write).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RequiredTransformation {
/// The variable name being transformed
pub variable: String,
/// The unit of the variable
pub unit: String,
/// The source grid type (finer resolution)
pub source_grid: GridType,
/// The target grid type (coarser resolution)
pub target_grid: GridType,
/// Direction of the transformation
pub direction: TransformDirection,
}
/// A null component that does nothing
///
/// Used as an initial component to ensure that the model is connected
#[derive(Debug, Serialize, Deserialize)]
struct NullComponent {}
#[typetag::serde]
impl Component for NullComponent {
fn definitions(&self) -> Vec<RequirementDefinition> {
vec![]
}
fn solve(
&self,
_t_current: Time,
_t_next: Time,
_input_state: &InputState,
) -> RSCMResult<OutputState> {
Ok(OutputState::new())
}
}
/// Build a new model from a set of components
///
/// The builder generates a graph that defines the inter-component dependencies
/// and determines what variables are endogenous and exogenous to the model.
/// This graph is used by the model to define the order in which components are solved.
///
/// # Examples
/// TODO: figure out how to share example components throughout the docs
pub struct ModelBuilder {
components: Vec<C>,
exogenous_variables: TimeseriesCollection,
initial_values: HashMap<String, FloatValue>,
pub time_axis: Arc<TimeAxis>,
schema: Option<VariableSchema>,
/// Custom weights for grid aggregation, keyed by grid type
///
/// When provided, these override the default weights used when creating
/// timeseries and performing grid transformations. Weights must sum to 1.0.
grid_weights: HashMap<GridType, Vec<f64>>,
}
/// Checks if the new definition is valid
///
/// If any definitions share a name then the units and grid types must be equivalent.
/// When `has_schema` is true, grid type checking is skipped because the schema validation
/// will handle grid compatibility with relaxed rules (allowing aggregation).
///
/// Returns an error if the parameter definition is inconsistent with any existing definitions.
fn verify_definition(
definitions: &mut HashMap<String, VariableDefinition>,
definition: &RequirementDefinition,
component_name: &str,
existing_component_name: Option<&str>,
has_schema: bool,
) -> RSCMResult<()> {
let existing = definitions.get(&definition.name);
match existing {
Some(existing) => {
if existing.unit != definition.unit {
return Err(RSCMError::Error(format!(
"Unit mismatch for variable '{}': component '{}' uses '{}' but component '{}' uses '{}'. \
All producers and consumers of a variable must use the same unit.",
definition.name,
existing_component_name.unwrap_or("unknown"),
existing.unit,
component_name,
definition.unit
)));
}
// Skip grid type check when schema is present - schema validation handles it
// with relaxed rules that allow aggregation
if !has_schema && existing.grid_type != definition.grid_type {
return Err(RSCMError::GridTypeMismatch {
variable: definition.name.clone(),
producer_component: existing_component_name.unwrap_or("unknown").to_string(),
consumer_component: component_name.to_string(),
producer_grid: existing.grid_type.to_string(),
consumer_grid: definition.grid_type.to_string(),
});
}
}
None => {
definitions.insert(
definition.name.clone(),
VariableDefinition::from_requirement_definition(definition),
);
}
}
Ok(())
}
use crate::state::{ReadTransformInfo, TransformContext};
/// Extract the input state for the current time step
///
/// By default, for endogenous variables which are calculated as part of the model
/// the most recent value is used, whereas, for exogenous variables the values are linearly
/// interpolated.
/// This ensures that state calculated from previous components within the same timestep
/// is used.
///
/// The result should contain values for the current time step for all input variable
pub fn extract_state(
collection: &TimeseriesCollection,
input_names: Vec<String>,
t_current: Time,
) -> InputState<'_> {
let mut state = Vec::new();
input_names.into_iter().for_each(|name| {
let ts = collection
.get_by_name(name.as_str())
.unwrap_or_else(|| panic!("No timeseries with variable='{}'", name));
state.push(ts);
});
InputState::build(state, t_current)
}
/// Extract the input state with transform context for grid aggregation.
///
/// Like `extract_state`, but includes transformation context for automatic
/// grid aggregation when reading variables at coarser resolutions.
pub fn extract_state_with_transforms(
collection: &TimeseriesCollection,
input_names: Vec<String>,
t_current: Time,
transform_context: TransformContext,
) -> InputState<'_> {
let mut state = Vec::new();
input_names.into_iter().for_each(|name| {
let ts = collection
.get_by_name(name.as_str())
.unwrap_or_else(|| panic!("No timeseries with variable='{}'", name));
state.push(ts);
});
InputState::build_with_transforms(state, t_current, transform_context)
}
/// Aggregate a StateValue from a finer grid to a coarser grid.
///
/// This function performs write-side grid transformation, aggregating component output
/// at a finer resolution to the schema's declared coarser resolution before storage.
///
/// # Arguments
///
/// * `value` - The StateValue to aggregate
/// * `source_grid` - The grid type the component produced (finer resolution)
/// * `target_grid` - The grid type the schema expects (coarser resolution)
/// * `weights` - Optional custom weights for aggregation; uses default grid weights if None
///
/// # Supported transformations
///
/// * FourBox -> Scalar: weighted average of all 4 regions
/// * FourBox -> Hemispheric: weighted average within each hemisphere
/// * Hemispheric -> Scalar: weighted average of 2 hemispheres
///
/// # Errors
///
/// Returns an error if:
/// * The source grid is coarser than the target (disaggregation not supported)
/// * The StateValue variant doesn't match the declared source_grid
fn aggregate_state_value(
value: &StateValue,
source_grid: GridType,
target_grid: GridType,
weights: Option<&Vec<f64>>,
) -> RSCMResult<StateValue> {
match (source_grid, target_grid) {
// FourBox -> Scalar: aggregate all 4 regions to global
(GridType::FourBox, GridType::Scalar) => {
let slice = match value {
StateValue::FourBox(s) => s,
_ => panic!(
"StateValue type mismatch: expected FourBox but got {:?}",
value
),
};
let grid = match weights {
Some(w) => {
let arr: [f64; 4] = w.as_slice().try_into().unwrap_or_else(|_| {
panic!("FourBox weights must have 4 elements, got {}", w.len())
});
FourBoxGrid::with_weights(arr)
}
None => FourBoxGrid::magicc_standard(),
};
Ok(StateValue::Scalar(slice.aggregate_global(&grid)))
}
// FourBox -> Hemispheric: aggregate by hemisphere
(GridType::FourBox, GridType::Hemispheric) => {
let slice = match value {
StateValue::FourBox(s) => s,
_ => panic!(
"StateValue type mismatch: expected FourBox but got {:?}",
value
),
};
let grid_weights = match weights {
Some(w) => {
let arr: [f64; 4] = w.as_slice().try_into().unwrap_or_else(|_| {
panic!("FourBox weights must have 4 elements, got {}", w.len())
});
arr
}
None => [0.25, 0.25, 0.25, 0.25],
};
// Aggregate by hemisphere using weighted averages
let values = slice.as_array();
let no = FourBoxRegion::NorthernOcean as usize;
let nl = FourBoxRegion::NorthernLand as usize;
let so = FourBoxRegion::SouthernOcean as usize;
let sl = FourBoxRegion::SouthernLand as usize;
let northern = (values[no] * grid_weights[no] + values[nl] * grid_weights[nl])
/ (grid_weights[no] + grid_weights[nl]);
let southern = (values[so] * grid_weights[so] + values[sl] * grid_weights[sl])
/ (grid_weights[so] + grid_weights[sl]);
Ok(StateValue::Hemispheric(HemisphericSlice::from([
northern, southern,
])))
}
// Hemispheric -> Scalar: aggregate both hemispheres to global
(GridType::Hemispheric, GridType::Scalar) => {
let slice = match value {
StateValue::Hemispheric(s) => s,
_ => panic!(
"StateValue type mismatch: expected Hemispheric but got {:?}",
value
),
};
let grid = match weights {
Some(w) => {
let arr: [f64; 2] = w.as_slice().try_into().unwrap_or_else(|_| {
panic!("Hemispheric weights must have 2 elements, got {}", w.len())
});
HemisphericGrid::with_weights(arr)
}
None => HemisphericGrid::default(),
};
Ok(StateValue::Scalar(slice.aggregate_global(&grid)))
}
// Same grid type: no transformation needed (identity)
(s, t) if s == t => Ok(value.clone()),
// Any other combination is not supported (disaggregation)
_ => Err(RSCMError::GridTransformationNotSupported {
source_grid: format!("{:?}", source_grid),
target_grid: format!("{:?}", target_grid),
variable: "unknown".to_string(),
}),
}
}
/// Check that a component graph is valid
///
/// We require a directed acyclic graph which doesn't contain any cycles (other than a self-referential node).
/// This avoids the case where component `A` depends on a component `B`,
/// but component `B` also depends on component `A`.
fn is_valid_graph<G>(g: G) -> bool
where
G: IntoNodeIdentifiers + IntoNeighbors + Visitable,
{
use petgraph::visit::{depth_first_search, DfsEvent};
depth_first_search(g, g.node_identifiers(), |event| match event {
DfsEvent::BackEdge(a, b) => {
// If the cycle is self-referential then that is fine
match a == b {
true => Ok(()),
false => Err(()),
}
}
_ => Ok(()),
})
.is_err()
}
impl ModelBuilder {
pub fn new() -> Self {
Self {
components: vec![],
initial_values: HashMap::new(),
exogenous_variables: TimeseriesCollection::new(),
time_axis: Arc::new(TimeAxis::from_values(Array::range(2000.0, 2100.0, 1.0))),
schema: None,
grid_weights: HashMap::new(),
}
}
/// Set custom weights for a grid type
///
/// These weights override the default grid weights used when:
/// - Creating timeseries for grid-based variables
/// - Performing automatic grid transformations (when enabled)
///
/// # Arguments
///
/// * `grid_type` - The grid type to configure (FourBox or Hemispheric)
/// * `weights` - Area-based weights that must sum to 1.0
///
/// # Panics
///
/// Panics if:
/// - `grid_type` is `Scalar` (scalars have no weights)
/// - `weights` length does not match the grid size (4 for FourBox, 2 for Hemispheric)
/// - `weights` do not sum to approximately 1.0 (within 1e-6)
///
/// # Examples
///
/// ```rust
/// use rscm_core::model::ModelBuilder;
/// use rscm_core::component::GridType;
///
/// let mut builder = ModelBuilder::new();
/// // Area-based weights for FourBox grid
/// builder.with_grid_weights(GridType::FourBox, vec![0.36, 0.14, 0.36, 0.14]);
/// ```
pub fn with_grid_weights(&mut self, grid_type: GridType, weights: Vec<f64>) -> &mut Self {
// Validate grid type
let expected_size = match grid_type {
GridType::Scalar => {
panic!("Cannot set weights for Scalar grid type (scalars have no regional weights)")
}
GridType::FourBox => 4,
GridType::Hemispheric => 2,
};
// Validate weights length
assert_eq!(
weights.len(),
expected_size,
"Weights length {} does not match {} grid size {}",
weights.len(),
grid_type,
expected_size
);
// Validate weights sum to 1.0
let sum: f64 = weights.iter().sum();
assert!(
(sum - 1.0).abs() < 1e-6,
"Weights must sum to 1.0, got {}",
sum
);
self.grid_weights.insert(grid_type, weights);
self
}
/// Create a FourBoxGrid using custom weights if configured, otherwise use defaults
fn create_four_box_grid(&self) -> crate::spatial::FourBoxGrid {
use crate::spatial::FourBoxGrid;
match self.grid_weights.get(&GridType::FourBox) {
Some(weights) => {
let weights_arr: [f64; 4] = weights
.as_slice()
.try_into()
.expect("FourBox weights should have 4 elements");
FourBoxGrid::with_weights(weights_arr)
}
None => FourBoxGrid::magicc_standard(),
}
}
/// Create a HemisphericGrid using custom weights if configured, otherwise use defaults
fn create_hemispheric_grid(&self) -> crate::spatial::HemisphericGrid {
use crate::spatial::HemisphericGrid;
match self.grid_weights.get(&GridType::Hemispheric) {
Some(weights) => {
let weights_arr: [f64; 2] = weights
.as_slice()
.try_into()
.expect("Hemispheric weights should have 2 elements");
HemisphericGrid::with_weights(weights_arr)
}
None => HemisphericGrid::equal_weights(),
}
}
/// Set the variable schema for the model
///
/// The schema defines all variables (including aggregates) that the model uses.
/// When a schema is provided, the builder validates:
/// - Component outputs are defined in the schema
/// - Component inputs are defined in the schema or produced by other components
/// - Units and grid types match between components and schema
///
/// Variables defined in the schema but not produced by any component will
/// be initialised to NaN.
pub fn with_schema(&mut self, schema: VariableSchema) -> &mut Self {
self.schema = Some(schema);
self
}
/// Register a component with the builder
pub fn with_component(&mut self, component: Arc<dyn Component + Send + Sync>) -> &mut Self {
self.components.push(component);
self
}
/// Supply exogenous data to be used by the model
///
/// Any unneeded timeseries will be ignored.
pub fn with_exogenous_variable(
&mut self,
name: &str,
timeseries: Timeseries<FloatValue>,
) -> &mut Self {
self.exogenous_variables.add_timeseries(
name.to_string(),
timeseries,
VariableType::Exogenous,
);
self
}
/// Supply exogenous data to be used by the model
///
/// Any unneeded timeseries will be ignored.
pub fn with_exogenous_collection(&mut self, collection: TimeseriesCollection) -> &mut Self {
self.exogenous_variables.extend(collection);
self
}
/// Adds some state to the set of initial values
///
/// These initial values are used to provide some initial values at `t_0`.
/// Initial values are used for requirements which have a type of `RequirementType::State`.
/// State variables read their value from the previous timestep in order to generate a new value
/// for the next timestep.
/// Building a model where any variables which have `RequirementType::State`, but
/// do not have an initial value will result in an error.
pub fn with_initial_values(
&mut self,
initial_values: HashMap<String, FloatValue>,
) -> &mut Self {
for (name, value) in initial_values.into_iter() {
self.initial_values.insert(name, value);
}
self
}
/// Specify the time axis that will be used by the model
///
/// This time axis defines the time steps (including bounds) on which the model will be iterated.
pub fn with_time_axis(&mut self, time_axis: TimeAxis) -> &mut Self {
self.time_axis = Arc::new(time_axis);
self
}
/// Validate a component's requirements against the schema
///
/// Checks that:
/// - All outputs are defined in the schema (as variables or aggregates)
/// - All inputs are defined in the schema (as variables or aggregates)
/// - Units match between component and schema
/// - Grid types are compatible (allowing aggregation where valid)
///
/// Returns a list of required grid transformations for mismatched grids.
fn validate_component_against_schema(
&self,
schema: &VariableSchema,
component_name: &str,
inputs: &[RequirementDefinition],
outputs: &[RequirementDefinition],
endogenous: &HashMap<String, NodeIndex>,
) -> RSCMResult<Vec<RequiredTransformation>> {
let mut transformations = Vec::new();
// Validate outputs
// Write-side: component produces finer grid than schema → aggregate before storage
for output in outputs {
// Check if output is defined in schema
if !schema.contains(&output.name) {
return Err(RSCMError::SchemaUndefinedOutput {
component: component_name.to_string(),
variable: output.name.clone(),
unit: output.unit.clone(),
});
}
// Check unit matches
if let Some(schema_unit) = schema.get_unit(&output.name) {
if schema_unit != output.unit {
return Err(RSCMError::ComponentSchemaUnitMismatch {
variable: output.name.clone(),
component: component_name.to_string(),
component_unit: output.unit.clone(),
schema_unit: schema_unit.to_string(),
});
}
}
// Check grid type compatibility
if let Some(schema_grid) = schema.get_grid_type(&output.name) {
if schema_grid != output.grid_type {
// Write-side: component grid can aggregate to schema grid?
// Component produces finer data → aggregation to schema is OK
if output.grid_type.can_aggregate_to(schema_grid) {
// Valid write-side aggregation needed
transformations.push(RequiredTransformation {
variable: output.name.clone(),
unit: output.unit.clone(),
source_grid: output.grid_type,
target_grid: schema_grid,
direction: TransformDirection::Write,
});
} else {
// Invalid: would require disaggregation (broadcast)
// Component produces coarser data than schema expects
return Err(RSCMError::GridTransformationNotSupported {
variable: output.name.clone(),
source_grid: output.grid_type.to_string(),
target_grid: schema_grid.to_string(),
});
}
}
}
}
// Validate inputs
// Read-side: component wants coarser grid than schema → aggregate before read
for input in inputs {
// Skip empty links
if input.requirement_type == RequirementType::EmptyLink {
continue;
}
// Input is valid if:
// 1. It's defined in the schema (as variable or aggregate), OR
// 2. It's produced by another component (endogenous)
if !schema.contains(&input.name) && !endogenous.contains_key(&input.name) {
return Err(RSCMError::SchemaUndefinedInput {
component: component_name.to_string(),
variable: input.name.clone(),
unit: input.unit.clone(),
});
}
// If it's in the schema, check unit and grid type compatibility
if schema.contains(&input.name) {
if let Some(schema_unit) = schema.get_unit(&input.name) {
if schema_unit != input.unit {
return Err(RSCMError::ComponentSchemaUnitMismatch {
variable: input.name.clone(),
component: component_name.to_string(),
component_unit: input.unit.clone(),
schema_unit: schema_unit.to_string(),
});
}
}
if let Some(schema_grid) = schema.get_grid_type(&input.name) {
if schema_grid != input.grid_type {
// Read-side: schema grid can aggregate to component grid?
// Schema has finer data → aggregation for component is OK
if schema_grid.can_aggregate_to(input.grid_type) {
// Valid read-side aggregation needed
transformations.push(RequiredTransformation {
variable: input.name.clone(),
unit: input.unit.clone(),
source_grid: schema_grid,
target_grid: input.grid_type,
direction: TransformDirection::Read,
});
} else {
// Invalid: would require disaggregation (broadcast)
// Component wants finer data than schema provides
return Err(RSCMError::GridTransformationNotSupported {
variable: input.name.clone(),
source_grid: schema_grid.to_string(),
target_grid: input.grid_type.to_string(),
});
}
}
}
}
}
Ok(transformations)
}
/// Builds the component graph for the registered components and creates a concrete model
///
/// Returns an error if the component definitions are inconsistent.
pub fn build(&self) -> RSCMResult<Model> {
// todo: refactor once this is more stable
let mut graph: CGraph = Graph::new();
let mut endrogoneous: HashMap<String, NodeIndex> = HashMap::new();
let mut exogenous: Vec<String> = vec![];
let mut definitions: HashMap<String, VariableDefinition> = HashMap::new();
// Track which component owns each variable for better error messages
let mut variable_owners: HashMap<String, String> = HashMap::new();
let initial_node = graph.add_node(Arc::new(NullComponent {}));
for component in &self.components {
let node = graph.add_node(component.clone());
let mut has_dependencies = false;
// Get component name from Debug implementation
let component_name = format!("{:?}", component);
// Extract just the type name (before the first '{' or ' ')
let component_name = component_name
.split(['{', ' ', '('])
.next()
.unwrap_or("UnknownComponent")
.to_string();
let requires = component.inputs();
let provides = component.outputs();
for requirement in requires {
let existing_owner = variable_owners.get(&requirement.name).map(|s| s.as_str());
verify_definition(
&mut definitions,
&requirement,
&component_name,
existing_owner,
self.schema.is_some(),
)?;
if let Some(&producer_node) = endrogoneous.get(&requirement.name) {
// Link to the node that provides the requirement
graph.add_edge(producer_node, node, requirement.clone());
has_dependencies = true;
} else {
// Add a new variable that must be defined outside of the model
if !exogenous.contains(&requirement.name) {
exogenous.push(requirement.name.clone());
}
}
}
if !has_dependencies {
// If the node has no dependencies on other components,
// create a link to the initial node.
// This ensures that we have a single connected graph
// There might be smarter ways to iterate over the nodes, but this is fine for now
graph.add_edge(
initial_node,
node,
RequirementDefinition::new("", "", RequirementType::EmptyLink),
);
}
for requirement in provides {
let existing_owner = variable_owners.get(&requirement.name).map(|s| s.as_str());
verify_definition(
&mut definitions,
&requirement,
&component_name,
existing_owner,
self.schema.is_some(),
)?;
// Track this component as the owner of this variable
variable_owners.insert(requirement.name.clone(), component_name.clone());
let val = endrogoneous.get(&requirement.name);
match val {
None => {
endrogoneous.insert(requirement.name.clone(), node);
}
Some(node_index) => {
graph.add_edge(*node_index, node, requirement.clone());
endrogoneous.insert(requirement.name.clone(), node);
}
}
}
}
// Check that the component graph doesn't contain any loops
assert!(!is_valid_graph(&graph));
// Collect all required grid transformations
let mut all_transformations: Vec<RequiredTransformation> = Vec::new();
// Validate against schema if provided
if let Some(schema) = &self.schema {
// First validate the schema itself
schema.validate()?;
// Validate each component against the schema and collect transformations
for component in &self.components {
let component_name = format!("{:?}", component);
let component_name = component_name
.split(['{', ' ', '('])
.next()
.unwrap_or("UnknownComponent")
.to_string();
let component_transforms = self.validate_component_against_schema(
schema,
&component_name,
&component.inputs(),
&component.outputs(),
&endrogoneous,
)?;
all_transformations.extend(component_transforms);
}
// Handle schema variables (4.5)
// For variables only declared as inputs (not produced by any component),
// add them to definitions using the schema's grid type.
// For variables that are produced by components, update the grid type
// to match the schema (the schema is the source of truth for storage grid type).
for (name, var_def) in &schema.variables {
if !definitions.contains_key(name) {
// Variable not produced by any component - add it as exogenous
definitions.insert(
name.clone(),
VariableDefinition {
name: name.clone(),
unit: var_def.unit.clone(),
grid_type: var_def.grid_type,
},
);
// Mark as exogenous since it's not produced by any component
exogenous.push(name.clone());
} else {
// Variable exists (from component input declaration) - update grid type to match schema
// This ensures storage uses schema's grid type, and read transforms will handle conversion
if let Some(def) = definitions.get_mut(name) {
if def.grid_type != var_def.grid_type && !endrogoneous.contains_key(name) {
// Only update if this variable is exogenous (input-only)
// If a component outputs this variable, the write transform will handle conversion
def.grid_type = var_def.grid_type;
exogenous.push(name.clone());
}
}
}
}
// Add aggregator components for each aggregate definition (5.1, 5.2, 5.3)
// Process aggregates in topological order to handle chained aggregates
let ordered_aggregates = schema.topological_order_aggregates();
for agg_name in &ordered_aggregates {
let agg_def = schema.get_aggregate(agg_name).unwrap();
// Create the aggregator component (5.1)
let aggregator = crate::schema::AggregatorComponent::from_definition(agg_def);
// Add to graph (5.2)
let agg_node = graph.add_node(Arc::new(aggregator.clone()));
// Track the component name for variable ownership
let agg_component_name = format!("Aggregator:{}", agg_name);
variable_owners.insert(agg_name.clone(), agg_component_name.clone());
// Add dependency edges from contributor sources to aggregator (5.3)
let mut has_dependencies = false;
for contributor in &agg_def.contributors {
// Find the node that produces this contributor
if let Some(&producer_node) = endrogoneous.get(contributor) {
// Add edge from producer to aggregator
graph.add_edge(
producer_node,
agg_node,
RequirementDefinition::with_grid(
contributor,
&agg_def.unit,
RequirementType::Input,
agg_def.grid_type,
),
);
has_dependencies = true;
}
// If contributor is exogenous, the aggregator will read from the
// timeseries collection which will have been populated
}
// If aggregator has no component dependencies, link to initial node
if !has_dependencies {
graph.add_edge(
initial_node,
agg_node,
RequirementDefinition::new("", "", RequirementType::EmptyLink),
);
}
// Register the aggregate output as endogenous
endrogoneous.insert(agg_name.clone(), agg_node);
// Add aggregate variable to definitions
definitions.insert(
agg_name.clone(),
VariableDefinition {
name: agg_name.clone(),
unit: agg_def.unit.clone(),
grid_type: agg_def.grid_type,
},
);
}
}
// Store transformations for runtime grid auto-aggregation
// Split into read and write transforms for efficient lookup during execution
let mut read_transforms: HashMap<String, RequiredTransformation> = HashMap::new();
let mut write_transforms: HashMap<String, RequiredTransformation> = HashMap::new();
for transform in all_transformations {
match transform.direction {
TransformDirection::Read => {
read_transforms.insert(transform.variable.clone(), transform);
}
TransformDirection::Write => {
write_transforms.insert(transform.variable.clone(), transform);
}
}
}
// Create the timeseries collection using the information from the components
let mut collection = TimeseriesCollection::new();
for (name, definition) in definitions {
assert_eq!(definition.name, name);
if exogenous.contains(&name) {
// Exogenous variable is expected to be supplied
if self.initial_values.contains_key(&name) {
// An initial value was provided
let mut ts = Timeseries::new_empty_scalar(
self.time_axis.clone(),
definition.unit,
InterpolationStrategy::from(LinearSplineStrategy::new(true)),
);
ts.set(0, ScalarRegion::Global, self.initial_values[&name]);
// Note that timeseries that are initialised are defined as Endogenous
// all but the first time point come from the model.
// This could potentially be defined as a different VariableType if needed.
collection.add_timeseries(name, ts, VariableType::Endogenous)
} else {
// Check if the timeseries is available in the provided exogenous variables
// then interpolate to the right timebase
// Look for exogenous data matching the schema's grid type
let exogenous_data = self.exogenous_variables.get_data(&name);
match (exogenous_data, definition.grid_type) {
(Some(TimeseriesData::Scalar(ts)), GridType::Scalar) => {
collection.add_timeseries(
name,
ts.to_owned().interpolate_into(self.time_axis.clone()),
VariableType::Exogenous,
);
}
(Some(TimeseriesData::FourBox(ts)), GridType::FourBox) => {
collection.add_four_box_timeseries(
name,
ts.to_owned().interpolate_into(self.time_axis.clone()),
VariableType::Exogenous,
);
}
(Some(TimeseriesData::Hemispheric(ts)), GridType::Hemispheric) => {
collection.add_hemispheric_timeseries(
name,
ts.to_owned().interpolate_into(self.time_axis.clone()),
VariableType::Exogenous,
);
}
_ => {
// No exogenous data provided or grid type mismatch
// Create empty timeseries (all NaN) matching the schema's grid type
// This is expected for schema variables without writers
match definition.grid_type {
GridType::Scalar => collection.add_timeseries(
definition.name,
Timeseries::new_empty_scalar(
self.time_axis.clone(),
definition.unit,
InterpolationStrategy::from(LinearSplineStrategy::new(
true,
)),
),
VariableType::Exogenous,
),
GridType::FourBox => collection.add_four_box_timeseries(
definition.name,
crate::timeseries::GridTimeseries::new_empty(
self.time_axis.clone(),
self.create_four_box_grid(),
definition.unit,
InterpolationStrategy::from(LinearSplineStrategy::new(
true,
)),
),
VariableType::Exogenous,
),
GridType::Hemispheric => collection.add_hemispheric_timeseries(
definition.name,
crate::timeseries::GridTimeseries::new_empty(
self.time_axis.clone(),
self.create_hemispheric_grid(),
definition.unit,
InterpolationStrategy::from(LinearSplineStrategy::new(
true,
)),
),
VariableType::Exogenous,
),
}
}
}
}
} else {
// Create a placeholder for data that will be generated by the model
// If there's a write transform, use the target grid type (schema's type)
// instead of the component's declared output type
let storage_grid_type = write_transforms
.get(&name)
.map(|t| t.target_grid)
.unwrap_or(definition.grid_type);
match storage_grid_type {
GridType::Scalar => collection.add_timeseries(
definition.name,
Timeseries::new_empty_scalar(
self.time_axis.clone(),
definition.unit,
InterpolationStrategy::from(LinearSplineStrategy::new(true)),
),
VariableType::Endogenous,
),
GridType::FourBox => collection.add_four_box_timeseries(
definition.name,
crate::timeseries::GridTimeseries::new_empty(
self.time_axis.clone(),
self.create_four_box_grid(),
definition.unit,
InterpolationStrategy::from(LinearSplineStrategy::new(true)),
),
VariableType::Endogenous,
),
GridType::Hemispheric => collection.add_hemispheric_timeseries(
definition.name,
crate::timeseries::GridTimeseries::new_empty(
self.time_axis.clone(),
self.create_hemispheric_grid(),
definition.unit,
InterpolationStrategy::from(LinearSplineStrategy::new(true)),
),
VariableType::Endogenous,
),
}
}
}
// Add the components to the graph
Ok(Model::with_transforms(
graph,
initial_node,
collection,
self.time_axis.clone(),
self.grid_weights.clone(),
read_transforms,
write_transforms,
))
}
}
impl Default for ModelBuilder {
fn default() -> Self {
Self::new()
}
}
/// A coupled set of components that are solved on a common time axis.
///
/// These components are solved over time steps defined by the ['time_axis'].
/// Components may pass state between themselves.
/// Each component may require information from other components to be solved (endogenous) or
/// predefined data (exogenous).
///
/// For example, a component to calculate the Effective Radiative Forcing(ERF) of CO_2 may
/// require CO_2 concentrations as input state and provide CO_2 ERF.
/// The component is agnostic about where/how that state is defined.
/// If the model has no components which provide CO_2 concentrations,
/// then a CO_2 concentration timeseries must be defined externally.
/// If the model also contains a carbon cycle component which produced CO_2 concentrations,
/// then the ERF component will be solved after the carbon cycle model.
#[derive(Debug, Serialize, Deserialize)]
pub struct Model {
/// A directed graph with components as nodes and the edges defining the state dependencies
/// between nodes.
/// This graph is traversed on every time step to ensure that any state dependencies are
/// solved before another component needs the state.
components: CGraph,
/// The base node of the graph from where to begin traversing.
initial_node: NodeIndex,
/// The model state
///
/// Variable names within the model are unique and these variable names are used by
/// components to request state.
collection: TimeseriesCollection,
time_axis: Arc<TimeAxis>,
time_index: usize,
/// Custom weights for grid aggregation, keyed by grid type
///
/// Used for grid transformations during model execution.
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
grid_weights: HashMap<GridType, Vec<f64>>,
/// Read-side transformations: variable name -> transformation needed when component reads
///
/// When a component reads a variable at a coarser grid than the schema declares,
/// this maps the variable name to the transformation needed (e.g., FourBox -> Scalar).
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
read_transforms: HashMap<String, RequiredTransformation>,
/// Write-side transformations: variable name -> transformation needed when component writes
///
/// When a component writes a variable at a finer grid than the schema declares,
/// this maps the variable name to the transformation needed (e.g., FourBox -> Scalar).
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
write_transforms: HashMap<String, RequiredTransformation>,
}
impl Model {
pub fn new(
components: CGraph,
initial_node: NodeIndex,
collection: TimeseriesCollection,
time_axis: Arc<TimeAxis>,
) -> Self {
Self::with_grid_weights(
components,
initial_node,
collection,
time_axis,
HashMap::new(),
)
}
/// Create a new Model with custom grid weights
///
/// The grid_weights are used for grid transformations during model execution.
pub fn with_grid_weights(
components: CGraph,
initial_node: NodeIndex,
collection: TimeseriesCollection,
time_axis: Arc<TimeAxis>,
grid_weights: HashMap<GridType, Vec<f64>>,
) -> Self {
Self::with_transforms(
components,
initial_node,
collection,
time_axis,
grid_weights,
HashMap::new(),
HashMap::new(),
)
}
/// Create a new Model with grid weights and transformations
///
/// This is the full constructor that includes both grid weights and the
/// read/write transformations for automatic grid aggregation.
pub fn with_transforms(
components: CGraph,
initial_node: NodeIndex,
collection: TimeseriesCollection,
time_axis: Arc<TimeAxis>,
grid_weights: HashMap<GridType, Vec<f64>>,
read_transforms: HashMap<String, RequiredTransformation>,
write_transforms: HashMap<String, RequiredTransformation>,
) -> Self {
Self {
components,
initial_node,
collection,
time_axis,
time_index: 0,
grid_weights,
read_transforms,
write_transforms,
}
}
/// Get the configured grid weights
///
/// Returns the custom weights if configured, or None if using defaults.
pub fn get_grid_weights(&self, grid_type: GridType) -> Option<&Vec<f64>> {
self.grid_weights.get(&grid_type)
}
/// Get all required transformations for introspection
///
/// Returns a vector of all required transformations, both read-side and write-side.
/// This is useful for debugging and understanding what grid aggregations will occur.
pub fn required_transformations(&self) -> Vec<&RequiredTransformation> {
self.read_transforms
.values()
.chain(self.write_transforms.values())
.collect()
}
/// Get read-side transformations
///
/// These transformations aggregate data when components read variables at coarser
/// resolutions than the schema declares.
pub fn read_transforms(&self) -> &HashMap<String, RequiredTransformation> {
&self.read_transforms
}
/// Get write-side transformations
///
/// These transformations aggregate data when components write variables at finer
/// resolutions than the schema declares.
pub fn write_transforms(&self) -> &HashMap<String, RequiredTransformation> {
&self.write_transforms
}
/// Gets the time value at the current step
pub fn current_time(&self) -> Time {
self.time_axis.at(self.time_index).unwrap()
}
pub fn current_time_bounds(&self) -> (Time, Time) {
self.time_axis.at_bounds(self.time_index).unwrap()
}
/// Solve a single component for the current timestep
///
/// The updated state from the component is then pushed into the model's timeseries collection
/// to be later used by other components.
/// The output state defines the values at the next time index as it represents the state
/// at the start of the next timestep.
fn step_model_component(&mut self, component: C) {
// Build transform context for read-side aggregation
let input_names = component.input_names();
let input_state = if self.read_transforms.is_empty() {
extract_state(&self.collection, input_names, self.current_time())
} else {
// Build transform context with only the transforms relevant to this component's inputs
let mut read_transform_info = HashMap::new();
for name in &input_names {
if let Some(transform) = self.read_transforms.get(name) {
read_transform_info.insert(
name.clone(),
ReadTransformInfo {
source_grid: transform.source_grid,
weights: self.grid_weights.get(&transform.source_grid).cloned(),
},
);
}
}
if read_transform_info.is_empty() {
extract_state(&self.collection, input_names, self.current_time())
} else {
let context = TransformContext {
read_transforms: read_transform_info,
};
extract_state_with_transforms(
&self.collection,
input_names,
self.current_time(),
context,
)
}
};
let (start, end) = self.current_time_bounds();
let result = component.solve(start, end, &input_state);
match result {
Ok(output_state) => {
for (key, state_value) in output_state.iter() {
let data = self.collection.get_data_mut(key).unwrap();
// Apply write-side transformation if needed (component produces finer grid
// than schema expects)
let final_value = if let Some(transform) = self.write_transforms.get(key) {
let weights = self.grid_weights.get(&transform.source_grid);
match aggregate_state_value(
state_value,
transform.source_grid,
transform.target_grid,
weights,
) {
Ok(v) => v,
Err(e) => {
println!("Write-side aggregation failed for {}: {}", key, e);
continue;
}
}
} else {
state_value.clone()
};
// The next time index is used as this output state represents the value of a
// variable at the end of the current time step.
// This is the same as the start of the next timestep.
let result = match &final_value {
StateValue::Scalar(v) => data.set_scalar(key, self.time_index + 1, *v),
StateValue::FourBox(slice) => {
data.set_four_box(key, self.time_index + 1, slice)
}
StateValue::Hemispheric(slice) => {
data.set_hemispheric(key, self.time_index + 1, slice)
}
};
if let Err(e) = result {
println!("Failed to set output {}: {}", key, e);
}
}
}
Err(err) => {
println!("Solving failed: {}", err)
}
}
}
/// Step the model forward a step by solving each component for the current time step.
///
/// A breadth-first search across the component graph starting at the initial node
/// will solve the components in a way that ensures any models with dependencies are solved
/// after the dependent component is first solved.
fn step_model(&mut self) {
let mut bfs = Bfs::new(&self.components, self.initial_node);
while let Some(nx) = bfs.next(&self.components) {
let c = self.components.index(nx);
self.step_model_component(c.clone())
}
}
/// Steps the model forward one time step
///
/// This solves the current time step and then updates the index.
pub fn step(&mut self) {
assert!(self.time_index < self.time_axis.len() - 1);
self.step_model();
self.time_index += 1;
}
/// Steps the model until the end of the time axis
pub fn run(&mut self) {
while self.time_index < self.time_axis.len() - 1 {
self.step();
}
}
/// Create a diagram the represents the component graph
///
/// Useful for debugging
pub fn as_dot(&self) -> Dot<'_, &CGraph> {
Dot::with_attr_getters(
&self.components,
&[Config::NodeNoLabel, Config::EdgeNoLabel],
&|_, er| format!("label = {:?}", er.weight().name),
&|_, (_, component)| {
// Escape quotes and backslashes for DOT format
let debug_str = format!("{:?}", component);
let escaped = debug_str.replace('\\', "\\\\").replace('"', "\\\"");
format!("label = \"{}\"", escaped)
},
)
}
/// Returns true if the model has no more time steps to process
pub fn finished(&self) -> bool {
self.time_index == self.time_axis.len() - 1
}
pub fn timeseries(&self) -> &TimeseriesCollection {
&self.collection
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::example_components::{TestComponent, TestComponentParameters};
use crate::interpolate::strategies::PreviousStrategy;
use is_close::is_close;
use numpy::array;
use numpy::ndarray::{Array, Axis};
use std::iter::zip;
fn get_emissions() -> Timeseries<FloatValue> {
use crate::spatial::ScalarGrid;
let values = array![0.0, 10.0].insert_axis(Axis(1));
Timeseries::new(
values,
Arc::new(TimeAxis::from_bounds(array![1800.0, 1850.0, 2100.0])),
ScalarGrid,
"GtC / yr".to_string(),
InterpolationStrategy::from(PreviousStrategy::new(true)),
)
}
#[test]
fn step() {
let time_axis = TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0));
let mut model = ModelBuilder::new()
.with_time_axis(time_axis)
.with_component(Arc::new(TestComponent::from_parameters(
TestComponentParameters {
conversion_factor: 0.5,
},
)))
.with_exogenous_variable("Emissions|CO2", get_emissions())
.build()
.unwrap();
assert_eq!(model.time_index, 0);
model.step();
model.step();
assert_eq!(model.time_index, 2);
assert_eq!(model.current_time(), 2022.0);
model.run();
assert_eq!(model.time_index, 4);
assert!(model.finished());
let concentrations = model
.collection
.get_data("Concentrations|CO2")
.and_then(|data| data.as_scalar())
.unwrap();
println!("{:?}", concentrations.values());
// The first value for an endogenous timeseries without a y0 value is NaN.
// This is because the values in the timeseries represents the state at the start
// of a time step.
// Since the values from t-1 aren't known we can't solve for y0
assert!(concentrations.at(0, ScalarRegion::Global).unwrap().is_nan());
let mut iter = concentrations.values().into_iter();
iter.next(); // Skip the first value
assert!(iter.all(|x| !x.is_nan()));
}
#[test]
fn dot() {
let time_axis = TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0));
let model = ModelBuilder::new()
.with_time_axis(time_axis)
.with_component(Arc::new(TestComponent::from_parameters(
TestComponentParameters {
conversion_factor: 0.5,
},
)))
.with_exogenous_variable("Emissions|CO2", get_emissions())
.build()
.unwrap();
let exp = r#"digraph {
0 [ label = "NullComponent"]
1 [ label = "TestComponent { parameters: TestComponentParameters { conversion_factor: 0.5 } }"]
0 -> 1 [ label = ""]
}
"#;
let res = format!("{:?}", model.as_dot());
assert_eq!(res, exp);
}
#[test]
fn serialise_and_deserialise_model() {
let mut model = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_component(Arc::new(TestComponent::from_parameters(
TestComponentParameters {
conversion_factor: 0.5,
},
)))
.with_exogenous_variable("Emissions|CO2", get_emissions())
.build()
.unwrap();
model.step();
let serialised = serde_json::to_string_pretty(&model).unwrap();
println!("Pretty JSON");
println!("{}", serialised);
let serialised = toml::to_string(&model).unwrap();
println!("TOML");
println!("{}", serialised);
let expected = r#"initial_node = 0
time_index = 1
[components]
node_holes = []
edge_property = "directed"
edges = [[0, 1, { name = "", unit = "", requirement_type = "EmptyLink", grid_type = "Scalar" }]]
[[components.nodes]]
type = "NullComponent"
[[components.nodes]]
type = "TestComponent"
[components.nodes.parameters]
conversion_factor = 0.5
[[collection.timeseries]]
name = "Concentrations|CO2"
variable_type = "Endogenous"
[collection.timeseries.data.Scalar]
units = "ppm"
latest = 1
interpolation_strategy = "Linear"
[collection.timeseries.data.Scalar.values]
v = 1
dim = [5, 1]
data = [nan, 5.0, nan, nan, nan]
[collection.timeseries.data.Scalar.time_axis.bounds]
v = 1
dim = [6]
data = [2020.0, 2021.0, 2022.0, 2023.0, 2024.0, 2025.0]
[[collection.timeseries]]
name = "Emissions|CO2"
variable_type = "Exogenous"
[collection.timeseries.data.Scalar]
units = "GtC / yr"
latest = 4
interpolation_strategy = "Previous"
[collection.timeseries.data.Scalar.values]
v = 1
dim = [5, 1]
data = [10.0, 10.0, 10.0, 10.0, 10.0]
[collection.timeseries.data.Scalar.time_axis.bounds]
v = 1
dim = [6]
data = [2020.0, 2021.0, 2022.0, 2023.0, 2024.0, 2025.0]
[time_axis.bounds]
v = 1
dim = [6]
data = [2020.0, 2021.0, 2022.0, 2023.0, 2024.0, 2025.0]
"#;
assert_eq!(serialised, expected);
let deserialised = toml::from_str::<Model>(&serialised).unwrap();
assert!(zip(
model
.collection
.get_data("Emissions|CO2")
.and_then(|data| data.as_scalar())
.unwrap()
.values(),
deserialised
.collection
.get_data("Emissions|CO2")
.and_then(|data| data.as_scalar())
.unwrap()
.values()
)
.all(|(x0, x1)| { is_close!(*x0, *x1) || (x0.is_nan() && x0.is_nan()) }));
assert_eq!(model.current_time_bounds(), (2021.0, 2022.0));
assert_eq!(deserialised.current_time_bounds(), (2021.0, 2022.0));
}
mod grid_validation_tests {
use super::*;
/// A component that produces a FourBox output
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FourBoxProducer;
#[typetag::serde]
impl Component for FourBoxProducer {
fn definitions(&self) -> Vec<RequirementDefinition> {
vec![RequirementDefinition::four_box_output("Temperature", "K")]
}
fn solve(
&self,
_t_current: Time,
_t_next: Time,
_input_state: &InputState,
) -> RSCMResult<OutputState> {
use crate::state::{FourBoxSlice, StateValue};
let mut output = OutputState::new();
output.insert(
"Temperature".to_string(),
StateValue::FourBox(FourBoxSlice::from_array([288.0, 290.0, 287.0, 285.0])),
);
Ok(output)
}
}
/// A component that expects a Scalar input
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ScalarConsumer;
#[typetag::serde]
impl Component for ScalarConsumer {
fn definitions(&self) -> Vec<RequirementDefinition> {
vec![
RequirementDefinition::scalar_input("Temperature", "K"),
RequirementDefinition::scalar_output("Result", "W / m^2"),
]
}
fn solve(
&self,
_t_current: Time,
_t_next: Time,
input_state: &InputState,
) -> RSCMResult<OutputState> {
use crate::state::StateValue;
let temp = input_state.get_scalar_window("Temperature").at_start();
let mut output = OutputState::new();
output.insert("Result".to_string(), StateValue::Scalar(temp * 2.0));
Ok(output)
}
}
/// A component that expects a FourBox input (compatible with FourBoxProducer)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FourBoxConsumer;
#[typetag::serde]
impl Component for FourBoxConsumer {
fn definitions(&self) -> Vec<RequirementDefinition> {
vec![
RequirementDefinition::four_box_input("Temperature", "K"),
RequirementDefinition::scalar_output("GlobalTemperature", "K"),
]
}
fn solve(
&self,
_t_current: Time,
_t_next: Time,
input_state: &InputState,
) -> RSCMResult<OutputState> {
use crate::state::StateValue;
let temp = input_state
.get_four_box_window("Temperature")
.current_global();
let mut output = OutputState::new();
output.insert("GlobalTemperature".to_string(), StateValue::Scalar(temp));
Ok(output)
}
}
#[test]
fn test_grid_type_mismatch_returns_error() {
// This should return an error because FourBoxProducer outputs FourBox
// but ScalarConsumer expects Scalar
let result = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_component(Arc::new(FourBoxProducer))
.with_component(Arc::new(ScalarConsumer))
.build();
assert!(result.is_err());
let err = result.unwrap_err();
let err_msg = err.to_string();
assert!(err_msg.contains("Grid type mismatch for variable 'Temperature'"));
assert!(err_msg.contains("FourBoxProducer"));
assert!(err_msg.contains("ScalarConsumer"));
assert!(err_msg.contains("FourBox"));
assert!(err_msg.contains("Scalar"));
}
#[test]
fn test_matching_grid_types_ok() {
// This should work because both use FourBox for Temperature
let _model = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_component(Arc::new(FourBoxProducer))
.with_component(Arc::new(FourBoxConsumer))
.build()
.unwrap();
}
}
mod schema_validation_tests {
use super::grid_validation_tests::{FourBoxConsumer, FourBoxProducer};
use super::*;
use crate::schema::{AggregateOp, VariableSchema};
#[test]
fn test_model_with_valid_schema() {
// Schema that matches component requirements
let schema = VariableSchema::new()
.variable("Emissions|CO2", "GtCO2")
.variable("Concentrations|CO2", "ppm");
let _model = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(TestComponent::from_parameters(
TestComponentParameters {
conversion_factor: 0.5,
},
)))
.with_exogenous_variable("Emissions|CO2", get_emissions())
.build()
.unwrap();
}
#[test]
fn test_schema_rejects_undefined_output() {
// Schema missing the output variable
let schema = VariableSchema::new().variable("Emissions|CO2", "GtCO2");
// Missing "Concentrations|CO2"
let result = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(TestComponent::from_parameters(
TestComponentParameters {
conversion_factor: 0.5,
},
)))
.with_exogenous_variable("Emissions|CO2", get_emissions())
.build();
assert!(result.is_err());
let err = result.unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("Concentrations|CO2"),
"Error should mention missing variable: {}",
msg
);
assert!(
msg.contains("not defined in the schema"),
"Error should indicate schema issue: {}",
msg
);
}
#[test]
fn test_schema_rejects_undefined_input() {
// Schema missing the input variable (and no component produces it)
let schema = VariableSchema::new().variable("Concentrations|CO2", "ppm");
// Missing "Emissions|CO2"
let result = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(TestComponent::from_parameters(
TestComponentParameters {
conversion_factor: 0.5,
},
)))
.build();
assert!(result.is_err());
let err = result.unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("Emissions|CO2"),
"Error should mention missing variable: {}",
msg
);
}
#[test]
fn test_schema_rejects_unit_mismatch() {
// Schema with wrong unit for output variable
let schema = VariableSchema::new()
.variable("Emissions|CO2", "GtCO2")
.variable("Concentrations|CO2", "GtC"); // Wrong unit - should be "ppm"
let result = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(TestComponent::from_parameters(
TestComponentParameters {
conversion_factor: 0.5,
},
)))
.with_exogenous_variable("Emissions|CO2", get_emissions())
.build();
assert!(result.is_err());
let err = result.unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("Unit mismatch"),
"Error should indicate unit mismatch: {}",
msg
);
assert!(
msg.contains("Concentrations|CO2"),
"Error should mention the variable: {}",
msg
);
}
#[test]
fn test_schema_rejects_disaggregation_on_read() {
// Schema has Scalar temperature, but FourBoxConsumer wants FourBox input
// This is a disaggregation (broadcast) attempt and should fail
let schema = VariableSchema::new()
.variable_with_grid("Temperature", "K", GridType::Scalar)
.variable("GlobalTemperature", "K");
let result = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(FourBoxProducer)) // Writes FourBox, aggregated to Scalar (OK)
.with_component(Arc::new(FourBoxConsumer)) // Reads FourBox from Scalar schema (ERROR)
.build();
assert!(result.is_err());
let err = result.unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("Grid transformation not supported"),
"Error should indicate unsupported transformation: {}",
msg
);
assert!(
msg.contains("Scalar") && msg.contains("FourBox"),
"Error should mention the grid types: {}",
msg
);
}
#[test]
fn test_schema_with_aggregate_validates() {
// Schema with an aggregate definition
let schema = VariableSchema::new()
.variable("Emissions|CO2", "GtCO2")
.variable("Concentrations|CO2", "ppm")
.aggregate("Total Concentrations", "ppm", AggregateOp::Sum)
.from("Concentrations|CO2")
.build();
let _model = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(TestComponent::from_parameters(
TestComponentParameters {
conversion_factor: 0.5,
},
)))
.with_exogenous_variable("Emissions|CO2", get_emissions())
.build()
.unwrap();
}
#[test]
fn test_schema_creates_nan_for_unwritten_variables() {
// Schema has a variable that no component writes to
let schema = VariableSchema::new()
.variable("Emissions|CO2", "GtCO2")
.variable("Concentrations|CO2", "ppm")
.variable("Concentrations|CH4", "ppb"); // No component writes this
let model = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(TestComponent::from_parameters(
TestComponentParameters {
conversion_factor: 0.5,
},
)))
.with_exogenous_variable("Emissions|CO2", get_emissions())
.build()
.unwrap();
// The CH4 variable should exist but be all NaN
let ch4 = model
.timeseries()
.get_data("Concentrations|CH4")
.and_then(|d| d.as_scalar());
assert!(
ch4.is_some(),
"CH4 timeseries should exist even though no component writes it"
);
let ch4 = ch4.unwrap();
assert!(
ch4.values().iter().all(|v| v.is_nan()),
"All CH4 values should be NaN since no component writes to it"
);
}
#[test]
fn test_schema_invalid_aggregate_fails() {
// Schema with invalid aggregate (circular dependency)
let mut schema = VariableSchema::new();
schema.aggregates.insert(
"A".to_string(),
crate::schema::AggregateDefinition {
name: "A".to_string(),
unit: "units".to_string(),
grid_type: GridType::Scalar,
operation: AggregateOp::Sum,
contributors: vec!["B".to_string()],
},
);
schema.aggregates.insert(
"B".to_string(),
crate::schema::AggregateDefinition {
name: "B".to_string(),
unit: "units".to_string(),
grid_type: GridType::Scalar,
operation: AggregateOp::Sum,
contributors: vec!["A".to_string()],
},
);
let result = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.build();
assert!(result.is_err());
let err = result.unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("Circular dependency"),
"Error should indicate circular dependency: {}",
msg
);
}
#[test]
fn test_model_without_schema_still_works() {
// Ensure models without schema still work as before
let _model = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_component(Arc::new(TestComponent::from_parameters(
TestComponentParameters {
conversion_factor: 0.5,
},
)))
.with_exogenous_variable("Emissions|CO2", get_emissions())
.build()
.unwrap();
}
}
mod aggregate_execution_tests {
use super::*;
use crate::schema::{AggregateOp, VariableSchema};
use crate::spatial::ScalarRegion;
use crate::state::StateValue;
/// A simple component that produces ERF|CO2
#[derive(Debug, Clone, Serialize, Deserialize)]
struct CO2ERFComponent {
forcing_per_ppm: f64,
}
#[typetag::serde]
impl Component for CO2ERFComponent {
fn definitions(&self) -> Vec<RequirementDefinition> {
vec![
RequirementDefinition::scalar_input("Concentrations|CO2", "ppm"),
RequirementDefinition::scalar_output("ERF|CO2", "W/m^2"),
]
}
fn solve(
&self,
_t_current: Time,
_t_next: Time,
input_state: &InputState,
) -> RSCMResult<OutputState> {
let conc = input_state
.get_scalar_window("Concentrations|CO2")
.at_start();
let mut output = OutputState::new();
output.insert(
"ERF|CO2".to_string(),
StateValue::Scalar(conc * self.forcing_per_ppm),
);
Ok(output)
}
}
/// A simple component that produces ERF|CH4
#[derive(Debug, Clone, Serialize, Deserialize)]
struct CH4ERFComponent {
forcing_per_ppb: f64,
}
#[typetag::serde]
impl Component for CH4ERFComponent {
fn definitions(&self) -> Vec<RequirementDefinition> {
vec![
RequirementDefinition::scalar_input("Concentrations|CH4", "ppb"),
RequirementDefinition::scalar_output("ERF|CH4", "W/m^2"),
]
}
fn solve(
&self,
_t_current: Time,
_t_next: Time,
input_state: &InputState,
) -> RSCMResult<OutputState> {
let conc = input_state
.get_scalar_window("Concentrations|CH4")
.at_start();
let mut output = OutputState::new();
output.insert(
"ERF|CH4".to_string(),
StateValue::Scalar(conc * self.forcing_per_ppb),
);
Ok(output)
}
}
fn get_co2_concentrations() -> Timeseries<FloatValue> {
use crate::spatial::ScalarGrid;
let values = array![280.0, 400.0].insert_axis(Axis(1));
Timeseries::new(
values,
Arc::new(TimeAxis::from_bounds(array![1800.0, 1850.0, 2100.0])),
ScalarGrid,
"ppm".to_string(),
InterpolationStrategy::from(PreviousStrategy::new(true)),
)
}
fn get_ch4_concentrations() -> Timeseries<FloatValue> {
use crate::spatial::ScalarGrid;
let values = array![700.0, 1800.0].insert_axis(Axis(1));
Timeseries::new(
values,
Arc::new(TimeAxis::from_bounds(array![1800.0, 1850.0, 2100.0])),
ScalarGrid,
"ppb".to_string(),
InterpolationStrategy::from(PreviousStrategy::new(true)),
)
}
#[test]
fn test_aggregate_sum_execution() {
// Schema with aggregate summing two ERF components
let schema = VariableSchema::new()
.variable("Concentrations|CO2", "ppm")
.variable("Concentrations|CH4", "ppb")
.variable("ERF|CO2", "W/m^2")
.variable("ERF|CH4", "W/m^2")
.aggregate("ERF|Total", "W/m^2", AggregateOp::Sum)
.from("ERF|CO2")
.from("ERF|CH4")
.build();
let mut model = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(CO2ERFComponent {
forcing_per_ppm: 0.01, // 1 W/m^2 per 100 ppm
}))
.with_component(Arc::new(CH4ERFComponent {
forcing_per_ppb: 0.001, // 1 W/m^2 per 1000 ppb
}))
.with_exogenous_variable("Concentrations|CO2", get_co2_concentrations())
.with_exogenous_variable("Concentrations|CH4", get_ch4_concentrations())
.build()
.unwrap();
// Run the model
model.run();
// Check that the aggregate was computed
let total_erf = model
.timeseries()
.get_data("ERF|Total")
.and_then(|d| d.as_scalar())
.expect("ERF|Total should exist");
// At 2021+ (after first step):
// CO2: 400 ppm * 0.01 = 4.0 W/m^2
// CH4: 1800 ppb * 0.001 = 1.8 W/m^2
// Total: 5.8 W/m^2
let value = total_erf.at(1, ScalarRegion::Global).unwrap();
assert!(
(value - 5.8).abs() < 1e-10,
"ERF|Total should be 5.8, got {}",
value
);
}
#[test]
fn test_aggregate_mean_execution() {
// Schema with mean aggregate
let schema = VariableSchema::new()
.variable("Concentrations|CO2", "ppm")
.variable("Concentrations|CH4", "ppb")
.variable("ERF|CO2", "W/m^2")
.variable("ERF|CH4", "W/m^2")
.aggregate("ERF|Mean", "W/m^2", AggregateOp::Mean)
.from("ERF|CO2")
.from("ERF|CH4")
.build();
let mut model = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(CO2ERFComponent {
forcing_per_ppm: 0.01,
}))
.with_component(Arc::new(CH4ERFComponent {
forcing_per_ppb: 0.001,
}))
.with_exogenous_variable("Concentrations|CO2", get_co2_concentrations())
.with_exogenous_variable("Concentrations|CH4", get_ch4_concentrations())
.build()
.unwrap();
model.run();
let mean_erf = model
.timeseries()
.get_data("ERF|Mean")
.and_then(|d| d.as_scalar())
.expect("ERF|Mean should exist");
// Mean of 4.0 and 1.8 = 2.9 W/m^2
let value = mean_erf.at(1, ScalarRegion::Global).unwrap();
assert!(
(value - 2.9).abs() < 1e-10,
"ERF|Mean should be 2.9, got {}",
value
);
}
#[test]
fn test_aggregate_weighted_execution() {
// Schema with weighted aggregate (80% CO2, 20% CH4)
let schema = VariableSchema::new()
.variable("Concentrations|CO2", "ppm")
.variable("Concentrations|CH4", "ppb")
.variable("ERF|CO2", "W/m^2")
.variable("ERF|CH4", "W/m^2")
.aggregate(
"ERF|Weighted",
"W/m^2",
AggregateOp::Weighted(vec![0.8, 0.2]),
)
.from("ERF|CO2")
.from("ERF|CH4")
.build();
let mut model = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(CO2ERFComponent {
forcing_per_ppm: 0.01,
}))
.with_component(Arc::new(CH4ERFComponent {
forcing_per_ppb: 0.001,
}))
.with_exogenous_variable("Concentrations|CO2", get_co2_concentrations())
.with_exogenous_variable("Concentrations|CH4", get_ch4_concentrations())
.build()
.unwrap();
model.run();
let weighted_erf = model
.timeseries()
.get_data("ERF|Weighted")
.and_then(|d| d.as_scalar())
.expect("ERF|Weighted should exist");
// Weighted: 4.0 * 0.8 + 1.8 * 0.2 = 3.2 + 0.36 = 3.56 W/m^2
let value = weighted_erf.at(1, ScalarRegion::Global).unwrap();
assert!(
(value - 3.56).abs() < 1e-10,
"ERF|Weighted should be 3.56, got {}",
value
);
}
#[test]
fn test_aggregate_with_nan_contributor() {
// Schema where one contributor has no writer (all NaN)
let schema = VariableSchema::new()
.variable("Concentrations|CO2", "ppm")
.variable("ERF|CO2", "W/m^2")
.variable("ERF|N2O", "W/m^2") // No component writes this
.aggregate("ERF|Total", "W/m^2", AggregateOp::Sum)
.from("ERF|CO2")
.from("ERF|N2O")
.build();
let mut model = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(CO2ERFComponent {
forcing_per_ppm: 0.01,
}))
.with_exogenous_variable("Concentrations|CO2", get_co2_concentrations())
.build()
.unwrap();
model.run();
let total_erf = model
.timeseries()
.get_data("ERF|Total")
.and_then(|d| d.as_scalar())
.expect("ERF|Total should exist");
// ERF|N2O is NaN, so Sum should just be ERF|CO2 = 4.0 W/m^2
let value = total_erf.at(1, ScalarRegion::Global).unwrap();
assert!(
(value - 4.0).abs() < 1e-10,
"ERF|Total should be 4.0 (NaN excluded), got {}",
value
);
}
#[test]
fn test_chained_aggregates_execution() {
// Schema with chained aggregates: Total depends on GHG, GHG depends on CO2+CH4
let schema = VariableSchema::new()
.variable("Concentrations|CO2", "ppm")
.variable("Concentrations|CH4", "ppb")
.variable("ERF|CO2", "W/m^2")
.variable("ERF|CH4", "W/m^2")
.variable("ERF|Other", "W/m^2") // Will be NaN
.aggregate("ERF|GHG", "W/m^2", AggregateOp::Sum)
.from("ERF|CO2")
.from("ERF|CH4")
.build()
.aggregate("ERF|Total", "W/m^2", AggregateOp::Sum)
.from("ERF|GHG")
.from("ERF|Other")
.build();
let mut model = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(CO2ERFComponent {
forcing_per_ppm: 0.01,
}))
.with_component(Arc::new(CH4ERFComponent {
forcing_per_ppb: 0.001,
}))
.with_exogenous_variable("Concentrations|CO2", get_co2_concentrations())
.with_exogenous_variable("Concentrations|CH4", get_ch4_concentrations())
.build()
.unwrap();
model.run();
// Check ERF|GHG = CO2 + CH4 = 4.0 + 1.8 = 5.8
let ghg_erf = model
.timeseries()
.get_data("ERF|GHG")
.and_then(|d| d.as_scalar())
.expect("ERF|GHG should exist");
let ghg_value = ghg_erf.at(1, ScalarRegion::Global).unwrap();
assert!(
(ghg_value - 5.8).abs() < 1e-10,
"ERF|GHG should be 5.8, got {}",
ghg_value
);
// Check ERF|Total = GHG + Other(NaN) = 5.8
let total_erf = model
.timeseries()
.get_data("ERF|Total")
.and_then(|d| d.as_scalar())
.expect("ERF|Total should exist");
let total_value = total_erf.at(1, ScalarRegion::Global).unwrap();
assert!(
(total_value - 5.8).abs() < 1e-10,
"ERF|Total should be 5.8, got {}",
total_value
);
}
#[test]
fn test_aggregate_appears_in_dot_graph() {
let schema = VariableSchema::new()
.variable("Concentrations|CO2", "ppm")
.variable("ERF|CO2", "W/m^2")
.aggregate("ERF|Total", "W/m^2", AggregateOp::Sum)
.from("ERF|CO2")
.build();
let model = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(CO2ERFComponent {
forcing_per_ppm: 0.01,
}))
.with_exogenous_variable("Concentrations|CO2", get_co2_concentrations())
.build()
.unwrap();
let dot = format!("{:?}", model.as_dot());
// The aggregator component should appear in the graph
assert!(
dot.contains("AggregatorComponent"),
"Graph should contain AggregatorComponent: {}",
dot
);
}
}
mod grid_weight_tests {
use super::*;
#[test]
fn test_with_grid_weights_fourbox_valid() {
let mut builder = ModelBuilder::new();
builder.with_grid_weights(GridType::FourBox, vec![0.36, 0.14, 0.36, 0.14]);
assert_eq!(
builder.grid_weights.get(&GridType::FourBox),
Some(&vec![0.36, 0.14, 0.36, 0.14])
);
}
#[test]
fn test_with_grid_weights_hemispheric_valid() {
let mut builder = ModelBuilder::new();
builder.with_grid_weights(GridType::Hemispheric, vec![0.6, 0.4]);
assert_eq!(
builder.grid_weights.get(&GridType::Hemispheric),
Some(&vec![0.6, 0.4])
);
}
#[test]
#[should_panic(expected = "Cannot set weights for Scalar")]
fn test_with_grid_weights_scalar_panics() {
let mut builder = ModelBuilder::new();
builder.with_grid_weights(GridType::Scalar, vec![1.0]);
}
#[test]
#[should_panic(expected = "Weights length")]
fn test_with_grid_weights_wrong_length_panics() {
let mut builder = ModelBuilder::new();
builder.with_grid_weights(GridType::FourBox, vec![0.5, 0.5]); // Wrong: 2 instead of 4
}
#[test]
#[should_panic(expected = "Weights must sum to 1.0")]
fn test_with_grid_weights_wrong_sum_panics() {
let mut builder = ModelBuilder::new();
builder.with_grid_weights(GridType::FourBox, vec![0.3, 0.3, 0.3, 0.3]);
// Sum = 1.2
}
#[test]
fn test_custom_weights_applied_to_fourbox_timeseries() {
use crate::schema::VariableSchema;
// Custom weights: different from default [0.25, 0.25, 0.25, 0.25]
let custom_weights = vec![0.36, 0.14, 0.36, 0.14];
let schema =
VariableSchema::new().variable_with_grid("Temperature", "K", GridType::FourBox);
let model = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_grid_weights(GridType::FourBox, custom_weights.clone())
.build()
.unwrap();
// Verify custom weights are stored in the Model
let model_weights = model.get_grid_weights(GridType::FourBox);
assert_eq!(model_weights, Some(&custom_weights));
}
#[test]
fn test_model_get_grid_weights_returns_none_for_unset() {
let model = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.build()
.unwrap();
assert!(model.get_grid_weights(GridType::FourBox).is_none());
assert!(model.get_grid_weights(GridType::Hemispheric).is_none());
assert!(model.get_grid_weights(GridType::Scalar).is_none());
}
#[test]
fn test_grid_weights_serialisation_roundtrip() {
use crate::schema::VariableSchema;
let custom_weights = vec![0.36, 0.14, 0.36, 0.14];
let schema =
VariableSchema::new().variable_with_grid("Temperature", "K", GridType::FourBox);
let model = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_grid_weights(GridType::FourBox, custom_weights.clone())
.build()
.unwrap();
// Serialise and deserialise
let serialised = toml::to_string(&model).unwrap();
let deserialised: Model = toml::from_str(&serialised).unwrap();
// Verify weights are preserved
assert_eq!(
deserialised.get_grid_weights(GridType::FourBox),
Some(&custom_weights)
);
}
#[test]
fn test_empty_grid_weights_not_serialised() {
let model = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.build()
.unwrap();
let serialised = toml::to_string(&model).unwrap();
// The grid_weights section should not appear
assert!(
!serialised.contains("grid_weights"),
"Empty grid_weights should not be serialised: {}",
serialised
);
}
}
mod relaxed_grid_validation_tests {
use super::*;
use crate::schema::VariableSchema;
use crate::state::{FourBoxSlice, HemisphericSlice, StateValue};
/// A component that produces FourBox output
#[derive(Debug, Clone, Serialize, Deserialize)]
struct FourBoxProducer {
var_name: String,
}
#[typetag::serde]
impl Component for FourBoxProducer {
fn definitions(&self) -> Vec<RequirementDefinition> {
vec![RequirementDefinition::four_box_output(&self.var_name, "K")]
}
fn solve(
&self,
_t_current: Time,
_t_next: Time,
_input_state: &InputState,
) -> RSCMResult<OutputState> {
let mut output = OutputState::new();
output.insert(
self.var_name.clone(),
StateValue::FourBox(FourBoxSlice::from_array([1.0, 2.0, 3.0, 4.0])),
);
Ok(output)
}
}
/// A component that produces Hemispheric output
#[derive(Debug, Clone, Serialize, Deserialize)]
struct HemisphericProducer {
var_name: String,
}
#[typetag::serde]
impl Component for HemisphericProducer {
fn definitions(&self) -> Vec<RequirementDefinition> {
vec![RequirementDefinition::hemispheric_output(
&self.var_name,
"K",
)]
}
fn solve(
&self,
_t_current: Time,
_t_next: Time,
_input_state: &InputState,
) -> RSCMResult<OutputState> {
let mut output = OutputState::new();
output.insert(
self.var_name.clone(),
StateValue::Hemispheric(HemisphericSlice::from_array([1.0, 2.0])),
);
Ok(output)
}
}
/// A component that produces Scalar output
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ScalarProducer {
var_name: String,
}
#[typetag::serde]
impl Component for ScalarProducer {
fn definitions(&self) -> Vec<RequirementDefinition> {
vec![RequirementDefinition::scalar_output(&self.var_name, "K")]
}
fn solve(
&self,
_t_current: Time,
_t_next: Time,
_input_state: &InputState,
) -> RSCMResult<OutputState> {
let mut output = OutputState::new();
output.insert(self.var_name.clone(), StateValue::Scalar(1.5));
Ok(output)
}
}
/// A component that consumes Scalar input
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ScalarConsumer {
input_var: String,
output_var: String,
}
#[typetag::serde]
impl Component for ScalarConsumer {
fn definitions(&self) -> Vec<RequirementDefinition> {
vec![
RequirementDefinition::scalar_input(&self.input_var, "K"),
RequirementDefinition::scalar_output(&self.output_var, "K"),
]
}
fn solve(
&self,
_t_current: Time,
_t_next: Time,
input_state: &InputState,
) -> RSCMResult<OutputState> {
let value = input_state.get_scalar_window(&self.input_var).at_start();
let mut output = OutputState::new();
output.insert(self.output_var.clone(), StateValue::Scalar(value * 2.0));
Ok(output)
}
}
/// A component that consumes FourBox input
#[derive(Debug, Clone, Serialize, Deserialize)]
struct FourBoxConsumer {
input_var: String,
output_var: String,
}
#[typetag::serde]
impl Component for FourBoxConsumer {
fn definitions(&self) -> Vec<RequirementDefinition> {
vec![
RequirementDefinition::four_box_input(&self.input_var, "K"),
RequirementDefinition::scalar_output(&self.output_var, "K"),
]
}
fn solve(
&self,
_t_current: Time,
_t_next: Time,
input_state: &InputState,
) -> RSCMResult<OutputState> {
let value = input_state
.get_four_box_window(&self.input_var)
.current_global();
let mut output = OutputState::new();
output.insert(self.output_var.clone(), StateValue::Scalar(value));
Ok(output)
}
}
// Write-side aggregation tests
#[test]
fn test_write_side_fourbox_to_scalar_allowed() {
// Schema declares Scalar, component produces FourBox
// Should be allowed (write-side aggregation)
let schema =
VariableSchema::new().variable_with_grid("Temperature", "K", GridType::Scalar);
let result = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(FourBoxProducer {
var_name: "Temperature".to_string(),
}))
.build();
assert!(
result.is_ok(),
"Write-side FourBox->Scalar aggregation should be allowed: {:?}",
result.err()
);
}
#[test]
fn test_write_side_fourbox_to_hemispheric_allowed() {
// Schema declares Hemispheric, component produces FourBox
// Should be allowed (write-side aggregation)
let schema =
VariableSchema::new().variable_with_grid("Temperature", "K", GridType::Hemispheric);
let result = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(FourBoxProducer {
var_name: "Temperature".to_string(),
}))
.build();
assert!(
result.is_ok(),
"Write-side FourBox->Hemispheric aggregation should be allowed: {:?}",
result.err()
);
}
#[test]
fn test_write_side_hemispheric_to_scalar_allowed() {
// Schema declares Scalar, component produces Hemispheric
// Should be allowed (write-side aggregation)
let schema =
VariableSchema::new().variable_with_grid("Temperature", "K", GridType::Scalar);
let result = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(HemisphericProducer {
var_name: "Temperature".to_string(),
}))
.build();
assert!(
result.is_ok(),
"Write-side Hemispheric->Scalar aggregation should be allowed: {:?}",
result.err()
);
}
#[test]
fn test_write_side_scalar_to_fourbox_rejected() {
// Schema declares FourBox, component produces Scalar
// Should be rejected (cannot broadcast/disaggregate)
let schema =
VariableSchema::new().variable_with_grid("Temperature", "K", GridType::FourBox);
let result = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(ScalarProducer {
var_name: "Temperature".to_string(),
}))
.build();
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(
err.contains("Grid transformation not supported"),
"Should indicate transformation not supported: {}",
err
);
}
#[test]
fn test_write_side_scalar_to_hemispheric_rejected() {
// Schema declares Hemispheric, component produces Scalar
// Should be rejected (cannot broadcast/disaggregate)
let schema =
VariableSchema::new().variable_with_grid("Temperature", "K", GridType::Hemispheric);
let result = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(ScalarProducer {
var_name: "Temperature".to_string(),
}))
.build();
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(
err.contains("Grid transformation not supported"),
"Should indicate transformation not supported: {}",
err
);
}
#[test]
fn test_write_side_hemispheric_to_fourbox_rejected() {
// Schema declares FourBox, component produces Hemispheric
// Should be rejected (cannot disaggregate)
let schema =
VariableSchema::new().variable_with_grid("Temperature", "K", GridType::FourBox);
let result = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(HemisphericProducer {
var_name: "Temperature".to_string(),
}))
.build();
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(
err.contains("Grid transformation not supported"),
"Should indicate transformation not supported: {}",
err
);
}
// Read-side aggregation tests
#[test]
fn test_read_side_fourbox_schema_scalar_consumer_allowed() {
// Schema declares FourBox, component consumes Scalar
// Should be allowed (read-side aggregation)
let schema = VariableSchema::new()
.variable_with_grid("Temperature", "K", GridType::FourBox)
.variable("Output", "K");
let result = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(FourBoxProducer {
var_name: "Temperature".to_string(),
}))
.with_component(Arc::new(ScalarConsumer {
input_var: "Temperature".to_string(),
output_var: "Output".to_string(),
}))
.build();
assert!(
result.is_ok(),
"Read-side FourBox->Scalar aggregation should be allowed: {:?}",
result.err()
);
}
#[test]
fn test_read_side_hemispheric_schema_scalar_consumer_allowed() {
// Schema declares Hemispheric, component consumes Scalar
// Should be allowed (read-side aggregation)
let schema = VariableSchema::new()
.variable_with_grid("Temperature", "K", GridType::Hemispheric)
.variable("Output", "K");
let result = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(HemisphericProducer {
var_name: "Temperature".to_string(),
}))
.with_component(Arc::new(ScalarConsumer {
input_var: "Temperature".to_string(),
output_var: "Output".to_string(),
}))
.build();
assert!(
result.is_ok(),
"Read-side Hemispheric->Scalar aggregation should be allowed: {:?}",
result.err()
);
}
#[test]
fn test_read_side_scalar_schema_fourbox_consumer_rejected() {
// Schema declares Scalar, component consumes FourBox
// Should be rejected (cannot disaggregate/broadcast)
let schema = VariableSchema::new()
.variable_with_grid("Temperature", "K", GridType::Scalar)
.variable("Output", "K");
let result = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(ScalarProducer {
var_name: "Temperature".to_string(),
}))
.with_component(Arc::new(FourBoxConsumer {
input_var: "Temperature".to_string(),
output_var: "Output".to_string(),
}))
.build();
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(
err.contains("Grid transformation not supported"),
"Should indicate transformation not supported: {}",
err
);
}
#[test]
fn test_same_grid_always_allowed() {
// Same grid types should always be allowed
let schema = VariableSchema::new()
.variable_with_grid("Temperature", "K", GridType::FourBox)
.variable("Output", "K");
let result = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(FourBoxProducer {
var_name: "Temperature".to_string(),
}))
.with_component(Arc::new(FourBoxConsumer {
input_var: "Temperature".to_string(),
output_var: "Output".to_string(),
}))
.build();
assert!(
result.is_ok(),
"Same grid types should always be allowed: {:?}",
result.err()
);
}
}
/// Integration tests for write-side grid aggregation during model execution
mod write_side_integration_tests {
use super::*;
use crate::state::FourBoxSlice;
use is_close::is_close;
/// Component that produces FourBox output with known values
#[derive(Debug, Clone, Serialize, Deserialize)]
struct FourBoxWriter {
var_name: String,
/// Values to produce: [NO, NL, SO, SL]
values: [FloatValue; 4],
}
#[typetag::serde]
impl Component for FourBoxWriter {
fn definitions(&self) -> Vec<RequirementDefinition> {
vec![RequirementDefinition::four_box_output(&self.var_name, "K")]
}
fn solve(
&self,
_t_current: Time,
_t_next: Time,
_input_state: &InputState,
) -> RSCMResult<OutputState> {
let mut output = OutputState::new();
output.insert(
self.var_name.clone(),
StateValue::FourBox(FourBoxSlice::from_array(self.values)),
);
Ok(output)
}
}
/// Component that produces Hemispheric output with known values
#[derive(Debug, Clone, Serialize, Deserialize)]
struct HemisphericWriter {
var_name: String,
/// Values to produce: [Northern, Southern]
values: [FloatValue; 2],
}
#[typetag::serde]
impl Component for HemisphericWriter {
fn definitions(&self) -> Vec<RequirementDefinition> {
vec![RequirementDefinition::hemispheric_output(
&self.var_name,
"K",
)]
}
fn solve(
&self,
_t_current: Time,
_t_next: Time,
_input_state: &InputState,
) -> RSCMResult<OutputState> {
let mut output = OutputState::new();
output.insert(
self.var_name.clone(),
StateValue::Hemispheric(HemisphericSlice::from(self.values)),
);
Ok(output)
}
}
#[test]
fn test_write_aggregation_fourbox_to_scalar_execution() {
// Schema declares Scalar, component produces FourBox
// The model should aggregate FourBox values to Scalar on write
let schema =
VariableSchema::new().variable_with_grid("Temperature", "K", GridType::Scalar);
let mut model = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2023.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(FourBoxWriter {
var_name: "Temperature".to_string(),
values: [10.0, 20.0, 30.0, 40.0], // [NO, NL, SO, SL]
}))
.build()
.expect("Model should build");
// Verify write transform is registered
assert!(
model.write_transforms().contains_key("Temperature"),
"Write transform should be registered"
);
// Run one step
model.step();
// Check the collection has scalar data (not FourBox)
let data = model.timeseries().get_data("Temperature").unwrap();
let ts = data.as_scalar().expect("Should be stored as Scalar");
// Get the value at index 1 (after first step)
let value = ts.at_scalar(1).expect("Should have value at index 1");
// With default equal weights [0.25, 0.25, 0.25, 0.25]:
// 10*0.25 + 20*0.25 + 30*0.25 + 40*0.25 = 25.0
assert!(
is_close!(value, 25.0),
"Expected aggregated value 25.0, got {}",
value
);
}
#[test]
fn test_write_aggregation_fourbox_to_scalar_custom_weights() {
// Schema declares Scalar, component produces FourBox
// Use custom weights for aggregation
let schema =
VariableSchema::new().variable_with_grid("Temperature", "K", GridType::Scalar);
let mut model = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2023.0, 1.0)))
.with_schema(schema)
.with_grid_weights(GridType::FourBox, vec![0.36, 0.14, 0.36, 0.14])
.with_component(Arc::new(FourBoxWriter {
var_name: "Temperature".to_string(),
values: [10.0, 20.0, 30.0, 40.0],
}))
.build()
.expect("Model should build");
model.step();
let data = model.timeseries().get_data("Temperature").unwrap();
let ts = data.as_scalar().expect("Should be stored as Scalar");
let value = ts.at_scalar(1).expect("Should have value at index 1");
// With custom weights [0.36, 0.14, 0.36, 0.14]:
// 10*0.36 + 20*0.14 + 30*0.36 + 40*0.14 = 3.6 + 2.8 + 10.8 + 5.6 = 22.8
assert!(
is_close!(value, 22.8),
"Expected aggregated value 22.8, got {}",
value
);
}
#[test]
fn test_write_aggregation_fourbox_to_hemispheric_execution() {
// Schema declares Hemispheric, component produces FourBox
let schema =
VariableSchema::new().variable_with_grid("Temperature", "K", GridType::Hemispheric);
let mut model = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2023.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(FourBoxWriter {
var_name: "Temperature".to_string(),
values: [10.0, 20.0, 30.0, 40.0],
}))
.build()
.expect("Model should build");
model.step();
let data = model.timeseries().get_data("Temperature").unwrap();
let ts = data
.as_hemispheric()
.expect("Should be stored as Hemispheric");
let northern = ts.at_index(1, 0).expect("Should have northern value");
let southern = ts.at_index(1, 1).expect("Should have southern value");
// With equal weights [0.25, 0.25, 0.25, 0.25]:
// Northern = (10*0.25 + 20*0.25) / (0.25 + 0.25) = 7.5 / 0.5 = 15.0
// Southern = (30*0.25 + 40*0.25) / (0.25 + 0.25) = 17.5 / 0.5 = 35.0
assert!(
is_close!(northern, 15.0),
"Expected northern 15.0, got {}",
northern
);
assert!(
is_close!(southern, 35.0),
"Expected southern 35.0, got {}",
southern
);
}
#[test]
fn test_write_aggregation_hemispheric_to_scalar_execution() {
// Schema declares Scalar, component produces Hemispheric
let schema =
VariableSchema::new().variable_with_grid("Temperature", "K", GridType::Scalar);
let mut model = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2023.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(HemisphericWriter {
var_name: "Temperature".to_string(),
values: [15.0, 35.0], // [Northern, Southern]
}))
.build()
.expect("Model should build");
model.step();
let data = model.timeseries().get_data("Temperature").unwrap();
let ts = data.as_scalar().expect("Should be stored as Scalar");
let value = ts.at_scalar(1).expect("Should have value at index 1");
// With default equal weights [0.5, 0.5]:
// 15*0.5 + 35*0.5 = 25.0
assert!(
is_close!(value, 25.0),
"Expected aggregated value 25.0, got {}",
value
);
}
#[test]
fn test_write_aggregation_multiple_steps() {
// Run multiple steps to ensure aggregation works consistently
let schema =
VariableSchema::new().variable_with_grid("Temperature", "K", GridType::Scalar);
let mut model = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2025.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(FourBoxWriter {
var_name: "Temperature".to_string(),
values: [10.0, 20.0, 30.0, 40.0],
}))
.build()
.expect("Model should build");
// Run all steps
model.run();
let data = model.timeseries().get_data("Temperature").unwrap();
let ts = data.as_scalar().expect("Should be stored as Scalar");
// Check values at all indices after initial
for i in 1..5 {
let value = ts
.at_scalar(i)
.unwrap_or_else(|| panic!("Should have value at index {}", i));
assert!(
is_close!(value, 25.0),
"Expected aggregated value 25.0 at index {}, got {}",
i,
value
);
}
}
#[test]
fn test_no_schema_no_aggregation() {
// Without a schema, no aggregation should happen
// Component produces FourBox, it should stay as FourBox
let mut model = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2023.0, 1.0)))
.with_component(Arc::new(FourBoxWriter {
var_name: "Temperature".to_string(),
values: [10.0, 20.0, 30.0, 40.0],
}))
.build()
.expect("Model should build without schema");
// Verify no write transforms
assert!(
model.write_transforms().is_empty(),
"Should have no write transforms without schema"
);
model.step();
// Data should remain as FourBox
let data = model.timeseries().get_data("Temperature").unwrap();
assert!(
data.as_four_box().is_some(),
"Should be stored as FourBox without schema"
);
}
}
/// Tests for read-side grid auto-aggregation during model execution
///
/// These tests verify that when a component reads a variable at a coarser resolution
/// than the schema declares, the model automatically aggregates the data on read.
mod read_side_integration_tests {
use super::*;
use crate::interpolate::strategies::{InterpolationStrategy, LinearSplineStrategy};
use crate::spatial::{FourBoxGrid, HemisphericGrid};
use crate::state::FourBoxSlice;
use crate::timeseries::GridTimeseries;
use is_close::is_close;
use numpy::ndarray::Array2;
/// Component that reads a scalar input and outputs a scalar result
/// Used to test read-side aggregation when schema has FourBox/Hemispheric data
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ScalarReader {
input_var: String,
output_var: String,
}
#[typetag::serde]
impl Component for ScalarReader {
fn definitions(&self) -> Vec<RequirementDefinition> {
vec![
RequirementDefinition::scalar_input(&self.input_var, "K"),
RequirementDefinition::scalar_output(&self.output_var, "K"),
]
}
fn solve(
&self,
_t_current: Time,
_t_next: Time,
input_state: &InputState,
) -> RSCMResult<OutputState> {
// Read scalar value (model should auto-aggregate if source is grid)
let value = input_state.get_scalar_window(&self.input_var).at_start();
let mut output = OutputState::new();
output.insert(self.output_var.clone(), StateValue::Scalar(value));
Ok(output)
}
}
/// Component that reads hemispheric input and outputs a scalar result
#[derive(Debug, Clone, Serialize, Deserialize)]
struct HemisphericReader {
input_var: String,
output_var: String,
}
#[typetag::serde]
impl Component for HemisphericReader {
fn definitions(&self) -> Vec<RequirementDefinition> {
vec![
RequirementDefinition::hemispheric_input(&self.input_var, "K"),
RequirementDefinition::scalar_output(&self.output_var, "K"),
]
}
fn solve(
&self,
_t_current: Time,
_t_next: Time,
input_state: &InputState,
) -> RSCMResult<OutputState> {
let window = input_state.get_hemispheric_window(&self.input_var);
let northern = window.at_start(crate::spatial::HemisphericRegion::Northern);
let southern = window.at_start(crate::spatial::HemisphericRegion::Southern);
// Return mean as output
let mean = (northern + southern) / 2.0;
let mut output = OutputState::new();
output.insert(self.output_var.clone(), StateValue::Scalar(mean));
Ok(output)
}
}
/// Component that reads FourBox input (used for error case testing)
#[derive(Debug, Clone, Serialize, Deserialize)]
struct FourBoxReader {
input_var: String,
output_var: String,
}
#[typetag::serde]
impl Component for FourBoxReader {
fn definitions(&self) -> Vec<RequirementDefinition> {
vec![
RequirementDefinition::four_box_input(&self.input_var, "K"),
RequirementDefinition::scalar_output(&self.output_var, "K"),
]
}
fn solve(
&self,
_t_current: Time,
_t_next: Time,
input_state: &InputState,
) -> RSCMResult<OutputState> {
let window = input_state.get_four_box_window(&self.input_var);
let global = window.current_global();
let mut output = OutputState::new();
output.insert(self.output_var.clone(), StateValue::Scalar(global));
Ok(output)
}
}
/// Component that writes FourBox output (producer for chained tests)
#[derive(Debug, Clone, Serialize, Deserialize)]
struct FourBoxWriter {
var_name: String,
values: [FloatValue; 4],
}
#[typetag::serde]
impl Component for FourBoxWriter {
fn definitions(&self) -> Vec<RequirementDefinition> {
vec![RequirementDefinition::four_box_output(&self.var_name, "K")]
}
fn solve(
&self,
_t_current: Time,
_t_next: Time,
_input_state: &InputState,
) -> RSCMResult<OutputState> {
let mut output = OutputState::new();
output.insert(
self.var_name.clone(),
StateValue::FourBox(FourBoxSlice::from_array(self.values)),
);
Ok(output)
}
}
/// Helper to create FourBox exogenous data
fn create_four_box_exogenous(
name: &str,
values: [[f64; 4]; 3], // 3 timesteps, 4 regions each
) -> (String, GridTimeseries<FloatValue, FourBoxGrid>) {
let grid = FourBoxGrid::magicc_standard();
let time_axis = Arc::new(TimeAxis::from_values(Array::range(2020.0, 2023.0, 1.0)));
let flat_values: Vec<f64> = values.iter().flat_map(|row| row.iter().copied()).collect();
let data = Array2::from_shape_vec((3, 4), flat_values).unwrap();
let ts = GridTimeseries::new(
data,
time_axis,
grid,
"K".to_string(),
InterpolationStrategy::from(LinearSplineStrategy::new(true)),
);
(name.to_string(), ts)
}
/// Helper to create Hemispheric exogenous data
fn create_hemispheric_exogenous(
name: &str,
values: [[f64; 2]; 3], // 3 timesteps, 2 hemispheres each
) -> (String, GridTimeseries<FloatValue, HemisphericGrid>) {
let grid = HemisphericGrid::equal_weights();
let time_axis = Arc::new(TimeAxis::from_values(Array::range(2020.0, 2023.0, 1.0)));
let flat_values: Vec<f64> = values.iter().flat_map(|row| row.iter().copied()).collect();
let data = Array2::from_shape_vec((3, 2), flat_values).unwrap();
let ts = GridTimeseries::new(
data,
time_axis,
grid,
"K".to_string(),
InterpolationStrategy::from(LinearSplineStrategy::new(true)),
);
(name.to_string(), ts)
}
#[test]
fn test_read_aggregation_fourbox_to_scalar() {
// Schema declares FourBox variable, component reads as Scalar
// Model should auto-aggregate FourBox to Scalar on read
let schema = VariableSchema::new()
.variable_with_grid("Temperature", "K", GridType::FourBox)
.variable("GlobalTemp", "K");
// FourBox data: [NO, NL, SO, SL] for each timestep
let (name, ts) = create_four_box_exogenous(
"Temperature",
[
[10.0, 20.0, 30.0, 40.0], // t=2020
[11.0, 21.0, 31.0, 41.0], // t=2021
[12.0, 22.0, 32.0, 42.0], // t=2022
],
);
let mut builder = ModelBuilder::new();
builder
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2023.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(ScalarReader {
input_var: "Temperature".to_string(),
output_var: "GlobalTemp".to_string(),
}));
builder
.exogenous_variables
.add_four_box_timeseries(name, ts, VariableType::Exogenous);
let mut model = builder.build().expect("Model should build");
// Verify read transform is registered
assert!(
model.read_transforms().contains_key("Temperature"),
"Read transform should be registered for Temperature"
);
// Run one step
model.step();
// Check the output - should be the aggregated (mean) of the FourBox values
let data = model.timeseries().get_data("GlobalTemp").unwrap();
let ts = data.as_scalar().expect("Should be Scalar");
let value = ts.at_scalar(1).expect("Should have value at index 1");
// With equal weights [0.25, 0.25, 0.25, 0.25] at t=2020:
// (10 + 20 + 30 + 40) / 4 = 25.0
assert!(
is_close!(value, 25.0),
"Expected aggregated value 25.0, got {}",
value
);
}
#[test]
fn test_read_aggregation_fourbox_to_hemispheric() {
// Schema declares FourBox variable, component reads as Hemispheric
let schema = VariableSchema::new()
.variable_with_grid("Temperature", "K", GridType::FourBox)
.variable("MeanTemp", "K");
let (name, ts) = create_four_box_exogenous(
"Temperature",
[
[10.0, 20.0, 30.0, 40.0], // [NO, NL, SO, SL]
[10.0, 20.0, 30.0, 40.0],
[10.0, 20.0, 30.0, 40.0],
],
);
let mut builder = ModelBuilder::new();
builder
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2023.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(HemisphericReader {
input_var: "Temperature".to_string(),
output_var: "MeanTemp".to_string(),
}));
builder
.exogenous_variables
.add_four_box_timeseries(name, ts, VariableType::Exogenous);
let mut model = builder.build().expect("Model should build");
// Verify read transform is registered
assert!(
model.read_transforms().contains_key("Temperature"),
"Read transform should be registered"
);
model.step();
let data = model.timeseries().get_data("MeanTemp").unwrap();
let ts = data.as_scalar().expect("Should be Scalar");
let value = ts.at_scalar(1).expect("Should have value at index 1");
// FourBox [10, 20, 30, 40] -> Hemispheric [15, 35] (mean of each hemisphere)
// Then component computes mean: (15 + 35) / 2 = 25.0
assert!(
is_close!(value, 25.0),
"Expected mean of hemispheres 25.0, got {}",
value
);
}
#[test]
fn test_read_aggregation_hemispheric_to_scalar() {
// Schema declares Hemispheric variable, component reads as Scalar
let schema = VariableSchema::new()
.variable_with_grid("Temperature", "K", GridType::Hemispheric)
.variable("GlobalTemp", "K");
let (name, ts) = create_hemispheric_exogenous(
"Temperature",
[
[15.0, 35.0], // [Northern, Southern]
[16.0, 36.0],
[17.0, 37.0],
],
);
let mut builder = ModelBuilder::new();
builder
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2023.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(ScalarReader {
input_var: "Temperature".to_string(),
output_var: "GlobalTemp".to_string(),
}));
builder.exogenous_variables.add_hemispheric_timeseries(
name,
ts,
VariableType::Exogenous,
);
let mut model = builder.build().expect("Model should build");
assert!(
model.read_transforms().contains_key("Temperature"),
"Read transform should be registered"
);
model.step();
let data = model.timeseries().get_data("GlobalTemp").unwrap();
let ts = data.as_scalar().expect("Should be Scalar");
let value = ts.at_scalar(1).expect("Should have value at index 1");
// With equal weights [0.5, 0.5]: (15 + 35) / 2 = 25.0
assert!(
is_close!(value, 25.0),
"Expected aggregated value 25.0, got {}",
value
);
}
#[test]
fn test_read_aggregation_multiple_consumers() {
// Two components reading same FourBox variable at different resolutions
// One reads as Scalar, other reads as Hemispheric
let schema = VariableSchema::new()
.variable_with_grid("Temperature", "K", GridType::FourBox)
.variable("GlobalTemp", "K")
.variable("HemisphericMean", "K");
let (name, ts) = create_four_box_exogenous(
"Temperature",
[
[10.0, 20.0, 30.0, 40.0],
[10.0, 20.0, 30.0, 40.0],
[10.0, 20.0, 30.0, 40.0],
],
);
let mut builder = ModelBuilder::new();
builder
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2023.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(ScalarReader {
input_var: "Temperature".to_string(),
output_var: "GlobalTemp".to_string(),
}))
.with_component(Arc::new(HemisphericReader {
input_var: "Temperature".to_string(),
output_var: "HemisphericMean".to_string(),
}));
builder
.exogenous_variables
.add_four_box_timeseries(name, ts, VariableType::Exogenous);
let mut model = builder.build().expect("Model should build");
model.step();
// ScalarReader should get mean of all 4: 25.0
let global = model
.timeseries()
.get_data("GlobalTemp")
.unwrap()
.as_scalar()
.unwrap()
.at_scalar(1)
.unwrap();
assert!(
is_close!(global, 25.0),
"Expected global 25.0, got {}",
global
);
// HemisphericReader gets hemispheric aggregation [15, 35], then computes mean: 25.0
let hemi_mean = model
.timeseries()
.get_data("HemisphericMean")
.unwrap()
.as_scalar()
.unwrap()
.at_scalar(1)
.unwrap();
assert!(
is_close!(hemi_mean, 25.0),
"Expected hemispheric mean 25.0, got {}",
hemi_mean
);
}
#[test]
fn test_read_disaggregation_scalar_to_fourbox_rejected() {
// Schema declares Scalar, but component wants FourBox input
// This is disaggregation (broadcast) and should be rejected at build time
let schema = VariableSchema::new()
.variable_with_grid("Temperature", "K", GridType::Scalar)
.variable("Result", "K");
let result = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2023.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(FourBoxReader {
input_var: "Temperature".to_string(),
output_var: "Result".to_string(),
}))
.build();
assert!(result.is_err(), "Disaggregation should be rejected");
let err = result.unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("Grid transformation not supported"),
"Error should mention unsupported transformation: {}",
msg
);
}
#[test]
fn test_read_aggregation_chain_write_then_read() {
// Test: FourBoxWriter writes FourBox -> schema is FourBox
// -> ScalarReader reads at_start (from previous timestep) as Scalar (read aggregation)
//
// ScalarReader uses at_start() which reads from the previous timestep.
// We need to run at least 2 steps: first step populates, second step reads.
let schema = VariableSchema::new()
.variable_with_grid("Temperature", "K", GridType::FourBox)
.variable("GlobalTemp", "K");
let mut model = ModelBuilder::new()
.with_time_axis(TimeAxis::from_values(Array::range(2020.0, 2024.0, 1.0)))
.with_schema(schema)
.with_component(Arc::new(FourBoxWriter {
var_name: "Temperature".to_string(),
values: [10.0, 20.0, 30.0, 40.0],
}))
.with_component(Arc::new(ScalarReader {
input_var: "Temperature".to_string(),
output_var: "GlobalTemp".to_string(),
}))
.build()
.expect("Model should build");
// FourBoxWriter writes FourBox, ScalarReader reads as Scalar via read aggregation
assert!(
model.read_transforms().contains_key("Temperature"),
"Read transform should be registered"
);
// First step: FourBoxWriter writes to index 1, ScalarReader reads from index 0 (NaN)
model.step();
// Second step: FourBoxWriter writes to index 2, ScalarReader reads from index 1 (the FourBox value)
model.step();
// Check the value at index 2 - ScalarReader read the aggregated value from step 1
let value = model
.timeseries()
.get_data("GlobalTemp")
.unwrap()
.as_scalar()
.unwrap()
.at_scalar(2)
.unwrap();
// FourBox [10, 20, 30, 40] aggregated to Scalar: 25.0
assert!(
is_close!(value, 25.0),
"Expected aggregated value 25.0, got {}",
value
);
}
}
/// Tests for the aggregate_state_value helper function
mod aggregate_state_value_tests {
use super::*;
use crate::state::FourBoxSlice;
use is_close::is_close;
#[test]
fn test_fourbox_to_scalar_default_weights() {
// With equal weights (default MAGICC standard), result is mean
let fourbox = StateValue::FourBox(FourBoxSlice::from([10.0, 20.0, 30.0, 40.0]));
let result =
aggregate_state_value(&fourbox, GridType::FourBox, GridType::Scalar, None).unwrap();
match result {
StateValue::Scalar(v) => {
// Default weights are equal [0.25, 0.25, 0.25, 0.25]
// 10*0.25 + 20*0.25 + 30*0.25 + 40*0.25 = 25.0
assert!(is_close!(v, 25.0), "Expected 25.0, got {}", v);
}
_ => panic!("Expected Scalar, got {:?}", result),
}
}
#[test]
fn test_fourbox_to_scalar_custom_weights() {
let fourbox = StateValue::FourBox(FourBoxSlice::from([10.0, 20.0, 30.0, 40.0]));
let weights = vec![0.36, 0.14, 0.36, 0.14]; // Ocean-biased weights
let result = aggregate_state_value(
&fourbox,
GridType::FourBox,
GridType::Scalar,
Some(&weights),
)
.unwrap();
match result {
StateValue::Scalar(v) => {
// 10*0.36 + 20*0.14 + 30*0.36 + 40*0.14 = 3.6 + 2.8 + 10.8 + 5.6 = 22.8
assert!(is_close!(v, 22.8), "Expected 22.8, got {}", v);
}
_ => panic!("Expected Scalar, got {:?}", result),
}
}
#[test]
fn test_fourbox_to_hemispheric_default_weights() {
let fourbox = StateValue::FourBox(FourBoxSlice::from([10.0, 20.0, 30.0, 40.0]));
let result =
aggregate_state_value(&fourbox, GridType::FourBox, GridType::Hemispheric, None)
.unwrap();
match result {
StateValue::Hemispheric(slice) => {
// With equal weights [0.25, 0.25, 0.25, 0.25]:
// Northern = (10*0.25 + 20*0.25) / (0.25 + 0.25) = 7.5 / 0.5 = 15.0
// Southern = (30*0.25 + 40*0.25) / (0.25 + 0.25) = 17.5 / 0.5 = 35.0
assert!(
is_close!(slice.as_array()[0], 15.0),
"Expected Northern=15.0, got {}",
slice.as_array()[0]
);
assert!(
is_close!(slice.as_array()[1], 35.0),
"Expected Southern=35.0, got {}",
slice.as_array()[1]
);
}
_ => panic!("Expected Hemispheric, got {:?}", result),
}
}
#[test]
fn test_fourbox_to_hemispheric_custom_weights() {
let fourbox = StateValue::FourBox(FourBoxSlice::from([10.0, 20.0, 30.0, 40.0]));
let weights = vec![0.36, 0.14, 0.36, 0.14]; // Ocean-biased
let result = aggregate_state_value(
&fourbox,
GridType::FourBox,
GridType::Hemispheric,
Some(&weights),
)
.unwrap();
match result {
StateValue::Hemispheric(slice) => {
// Northern = (10*0.36 + 20*0.14) / (0.36 + 0.14) = (3.6 + 2.8) / 0.5 = 12.8
// Southern = (30*0.36 + 40*0.14) / (0.36 + 0.14) = (10.8 + 5.6) / 0.5 = 32.8
assert!(
is_close!(slice.as_array()[0], 12.8),
"Expected Northern=12.8, got {}",
slice.as_array()[0]
);
assert!(
is_close!(slice.as_array()[1], 32.8),
"Expected Southern=32.8, got {}",
slice.as_array()[1]
);
}
_ => panic!("Expected Hemispheric, got {:?}", result),
}
}
#[test]
fn test_hemispheric_to_scalar_default_weights() {
let hemispheric = StateValue::Hemispheric(HemisphericSlice::from([15.0, 35.0]));
let result =
aggregate_state_value(&hemispheric, GridType::Hemispheric, GridType::Scalar, None)
.unwrap();
match result {
StateValue::Scalar(v) => {
// Default weights [0.5, 0.5] -> mean
// 15*0.5 + 35*0.5 = 25.0
assert!(is_close!(v, 25.0), "Expected 25.0, got {}", v);
}
_ => panic!("Expected Scalar, got {:?}", result),
}
}
#[test]
fn test_hemispheric_to_scalar_custom_weights() {
let hemispheric = StateValue::Hemispheric(HemisphericSlice::from([10.0, 30.0]));
let weights = vec![0.4, 0.6]; // Southern-biased
let result = aggregate_state_value(
&hemispheric,
GridType::Hemispheric,
GridType::Scalar,
Some(&weights),
)
.unwrap();
match result {
StateValue::Scalar(v) => {
// 10*0.4 + 30*0.6 = 4 + 18 = 22.0
assert!(is_close!(v, 22.0), "Expected 22.0, got {}", v);
}
_ => panic!("Expected Scalar, got {:?}", result),
}
}
#[test]
fn test_identity_transformation_scalar() {
let scalar = StateValue::Scalar(42.0);
let result =
aggregate_state_value(&scalar, GridType::Scalar, GridType::Scalar, None).unwrap();
match result {
StateValue::Scalar(v) => assert_eq!(v, 42.0),
_ => panic!("Expected Scalar, got {:?}", result),
}
}
#[test]
fn test_identity_transformation_fourbox() {
let fourbox = StateValue::FourBox(FourBoxSlice::from([1.0, 2.0, 3.0, 4.0]));
let result =
aggregate_state_value(&fourbox, GridType::FourBox, GridType::FourBox, None)
.unwrap();
match result {
StateValue::FourBox(slice) => {
assert_eq!(*slice.as_array(), [1.0, 2.0, 3.0, 4.0]);
}
_ => panic!("Expected FourBox, got {:?}", result),
}
}
#[test]
fn test_disaggregation_scalar_to_fourbox_rejected() {
let scalar = StateValue::Scalar(25.0);
let result = aggregate_state_value(&scalar, GridType::Scalar, GridType::FourBox, None);
assert!(
result.is_err(),
"Disaggregation Scalar->FourBox should be rejected"
);
}
#[test]
fn test_disaggregation_scalar_to_hemispheric_rejected() {
let scalar = StateValue::Scalar(25.0);
let result =
aggregate_state_value(&scalar, GridType::Scalar, GridType::Hemispheric, None);
assert!(
result.is_err(),
"Disaggregation Scalar->Hemispheric should be rejected"
);
}
#[test]
fn test_disaggregation_hemispheric_to_fourbox_rejected() {
let hemispheric = StateValue::Hemispheric(HemisphericSlice::from([15.0, 35.0]));
let result =
aggregate_state_value(&hemispheric, GridType::Hemispheric, GridType::FourBox, None);
assert!(
result.is_err(),
"Disaggregation Hemispheric->FourBox should be rejected"
);
}
}
}