pyrucast 0.7.1

Finite-element library in Rust, inspired by cast3m, exposed to Python
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
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
//! Physical model — orchestrator of sub-models that assemble into a
//! [`crate::containers::matrix::Matrix`].
//!
//! The model layer is the **physics-aware** counterpart of the
//! geometry layer (`Mesh`, `SubMesh`) and the interpolation layer
//! (`FiniteElementSpace`, `SubFiniteElementSpace`). A [`Model`] is an aggregate of
//! [`SubModel`]s; each [`SubModel`] is one physics instance (a variant of
//! the enum) that owns its supports and dispatches its behaviour through
//! the [`SubModelKind`] trait. The Model is a pure orchestrator: it enumerates
//! the DOFs of its sub-models, dimensions a
//! [`crate::containers::matrix::Matrix`], and
//! loops over the sub-models to accumulate the contributions.
//!
//! # Architecture
//!
//! ```text
//! Model
//! ├── sub_models: Vec<Handle<SubModel>>
//! ├── primal_vars(): Vec<String>      # union over sub-models — columns
//! └── dual_vars():   Vec<String>      # union over sub-models — rows
//!
//! ops::model (operators, not Model methods) — declares the physics
//! ├── heat_conduction(fes) -> Model          # one sub-model per subspace
//! └── dirichlet(...)       -> Model          # composed with `union` / `|`
//!
//! ops::matrix (operators, not Model methods)
//! ├── stiffness(model, materials) -> Matrix   # rows: dual × cols: primal
//! └── mass(model)                 -> Matrix   # same DOF layout, may be empty
//!
//! SubModel  (enum : stockage + sérialisation ; dispatch via as_kind())
//! ├── HeatConduction(HeatConduction)
//! ├── Dirichlet(Dirichlet)             # constraint = Lagrange multiplier
//! └── ...
//!
//! SubModelKind  (trait : tout le comportement, co-localisé par physique)
//! └── primal_vars / dual_vars / material_* / build_*_blocks / render / ...
//! ```
//!
//! The model layer is purely matrix-producing. Loads (right-hand side
//! vectors) are entirely the user's responsibility: read
//! `model.dual_vars()`, build a [`crate::containers::node_field::SubNodeField`] with
//! the matching component names, and feed `Matrix + SubNodeField` to the
//! solver.
//!
//! # Lagrange multipliers and DOF identification
//!
//! `SubModel::Dirichlet` introduces new DOFs of two kinds, both living on the
//! **multiplier nodes** supplied by the user (`multiplier_mesh`; the sub-model
//! creates no node):
//!
//! - the **primal** of the constraint sub-model is `multiplier` (default
//!   `lambda_<imposed_variable>`) at the multiplier nodes — the Lagrange
//!   multiplier itself, an unknown of the augmented system whose solved value
//!   is the reaction;
//! - the **dual** of the constraint sub-model is `imposed_value` (default
//!   `imposed_<imposed_variable>`) at the multiplier nodes — the constraint
//!   equation row, and the slot at which the user writes the imposed value.
//!
//! Distinct `(NodeId, field_name)` pairs keep these multiplier DOFs apart from
//! the primary DOFs. The blocks `C` (constraint) and `Cᵀ` (its transpose — the
//! reaction in the target's `target_dual` row) are stored explicitly and each
//! marked **non-symmetric**: only their union `C ∪ Cᵀ` is symmetric, a global
//! property of the saddle-point system (the dense LU solver ignores the flag
//! anyway).
//!
//! # Example: 1-D heat conduction with a Dirichlet condition
//!
//! ```
//! use pyrucast::aggregate::Aggregate;
//! use pyrucast::atoms::NodeId;
//! use pyrucast::coords::Coords;
//! use pyrucast::containers::element_field::SubElementField;
//! use pyrucast::atoms::ElementType;
//! use pyrucast::containers::finite_element_space::FiniteElementSpace;
//! use pyrucast::containers::mesh::{Mesh, SubMesh};
//! use pyrucast::containers::field::SubField;
//! use pyrucast::containers::model::{Model, SubModel};
//! use pyrucast::atoms::Node;
//! use pyrucast::ops::matrix;
//! use pyrucast::ops::mesh;
//! use pyrucast::handle::Handle;
//!
//! // 1-D Coords with two nodes spanning [0, 1].
//! let coords = Handle::new(Coords::new(1).unwrap());
//! let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
//! let b = Node::create_in(coords.clone(), &[1.0]).unwrap();
//! let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
//! mesh.add_cell(&[a.id(), b.id()]).unwrap();
//! let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
//! let sub = fes.get(0).unwrap();
//!
//! // Conductivity k = 1, uniform — passed at assembly time, not stored in the model.
//! let mut mat = SubElementField::new(sub.clone(), vec!["k".into()]).unwrap();
//! mat.set_uniform("k", 1.0).unwrap();
//! use pyrucast::containers::element_field::ElementField;
//! let mut materials = ElementField::empty();
//! materials.add_sub(Handle::new(mat)).unwrap();
//!
//! let mut model = Model::empty();
//! model
//!     .add_sub(Handle::new(SubModel::heat_conduction(sub).unwrap()))
//!     .unwrap();
//! // Dirichlet on node `a`: the imposed POI1 mesh + a colocated multiplier
//! // support minted by the `barycenter` mesher.
//! let imposed = Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&a)).unwrap());
//! let multiplier = mesh::barycenter(&imposed).unwrap();
//! model
//!     .add_sub(Handle::new(
//!         SubModel::dirichlet(&model, "T", &imposed, &multiplier, Default::default())
//!             .unwrap(),
//!     ))
//!     .unwrap();
//!
//! let k = pyrucast::ops::matrix::stiffness(&model, &materials).unwrap();
//! // 2 real DOFs ("T") + 1 multiplier DOF + 2 real rows ("q") + 1 multiplier row.
//! assert_eq!(k.n_rows().unwrap(), 3);
//! assert_eq!(k.n_cols().unwrap(), 3);
//! ```

use crate::aggregate::Aggregate;
use crate::atoms::NodeId;
use crate::containers::element_field::SubElementField;
use crate::containers::finite_element_space::{FiniteElementSpace, SubFiniteElementSpace};
use crate::containers::matrix::AssemblyPattern;
use crate::containers::mesh::Mesh;
use crate::containers::node_field::{NodeField, SubNodeField};
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use crate::models::symmetry::MaterialSymmetry;
use crate::models::tensor::Kinematics;
use crate::models::{
    bernoulli, boundary_transfer, contact, damage, dirichlet, elasticity, embedded, fick, flux,
    heat_conduction, interface_transfer, mpc, plasticity, radiation, shell, timoshenko, truss,
    Constraint, MatrixKind, Physics, RelationSense, SubModelKind,
};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::sync::{Arc, OnceLock};

/// Record `g` at a relation's multiplier node in the `constraint_rhs*` helpers,
/// erroring when two entries hit the **same** relation with different values.
/// `caller` names the method for the message.
fn insert_relation_value(
    values: &mut std::collections::HashMap<(NodeId, String), f64>,
    multiplier_node: NodeId,
    slot: &str,
    g: f64,
    caller: &str,
) -> Result<()> {
    if let Some(prev) = values.insert((multiplier_node, slot.to_string()), g)
        && prev != g
    {
        return Err(PyrucastError::Message(format!(
            "{caller}: conflicting values ({prev} and {g}) for the same relation \
                 (multiplier node {multiplier_node}, slot {slot})"
        )));
    }
    Ok(())
}

// ─── SubModel ──────────────────────────────────────────────────────────────

/// One physics instance, bound to its supports (FE spaces, materials, node
/// sets). A [`Model`] is a `Vec<Handle<SubModel>>`.
///
/// This enum is a **pure storage + dispatch** shell: it derives
/// `Serialize`/`Deserialize` (so models persist through the `bincode`
/// backbone), and forwards every behavioural call to the variant's
/// [`SubModelKind`] implementation through [`SubModel::as_kind`]. All physics
/// logic lives in the per-variant structs under [`crate::models`].
///
/// Adding a physics means adding **one variant here** and **one arm to
/// [`SubModel::as_kind`]** — no other site in this file changes.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::{Model, SubModel};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::tensor::Kinematics;
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::models::{Physics, RelationSense};
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let maillage = Mesh::from_submesh(sm);
/// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let mult = mesh::barycenter(&impose).unwrap();
/// // Une variante par physique ; tout le reste du code passe par
/// // `as_kind()` plutôt que de refaire le `match`.
/// let m = SubModel::heat_conduction(zone.clone())?;
/// assert!(matches!(m, SubModel::HeatConduction(_)));
/// assert_eq!(m.physics(), &[Physics::Thermal]);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Serialize, Deserialize)]
pub enum SubModel {
    /// Linear heat conduction — see [`heat_conduction::HeatConduction`].
    HeatConduction(heat_conduction::HeatConduction),
    /// Surface exchange with an imposed ambient (Robin / film) — see
    /// [`boundary_transfer::BoundaryTransfer`].
    BoundaryTransfer(boundary_transfer::BoundaryTransfer),
    /// Dirichlet constraint via Lagrange multipliers — see
    /// [`dirichlet::Dirichlet`].
    Dirichlet(dirichlet::Dirichlet),
    /// Multi-point constraint (linear relations) via Lagrange multipliers —
    /// see [`mpc::Mpc`].
    Mpc(mpc::Mpc),
    /// Embedded (immersed) constraint tying immersed nodes to a host
    /// interpolation — see [`embedded::Embedded`].
    Embedded(embedded::Embedded),
    /// Node-to-surface contact (unilateral, frictionless) — see
    /// [`contact::Contact`].
    Contact(contact::Contact),
    /// Truss / bar (axial-force) element — see [`truss::Truss`].
    Truss(truss::Truss),
    /// Linear elasticity (2-D plane / 3-D solid) — see [`elasticity::Elasticity`].
    Elasticity(elasticity::Elasticity),
    /// Perfect von Mises elastoplasticity — see [`plasticity::Plasticity`].
    Plasticity(plasticity::Plasticity),
    /// Damage — Mazars, tension/compression, or orthotropic SiC/SiC; see
    /// [`damage::Damage`].
    Mazars(damage::Damage),
    /// Timoshenko beam — shear-deformable, in a 1-D, plane or space
    /// configuration read from the mesh. See [`timoshenko::Timoshenko`].
    ///
    /// > The `Frame` and `Frame3d` variants that once sat here were the same
    /// > physics in 2-D and 3-D; they are gone, and the two indices after this
    /// > one shifted with them. That is a `bincode` break, taken knowingly.
    Timoshenko(timoshenko::Timoshenko),
    // New variants go **at the end**: `bincode` serialises the variant index, so
    // inserting one in the middle would silently misread every saved model.
    /// Fickian diffusion (concentration / mass flux) — see [`fick::Fick`].
    Fick(fick::Fick),
    /// Exchange law across an interface between two meshes — see
    /// [`interface_transfer::InterfaceTransfer`].
    InterfaceTransfer(interface_transfer::InterfaceTransfer),
    /// Radiation to infinity (Stefan-Boltzmann boundary) — see
    /// [`radiation::Radiation`].
    Radiation(radiation::Radiation),
    /// Euler-Bernoulli beam (1-D, plane frame, space frame) — see
    /// [`bernoulli::Bernoulli`].
    Bernoulli(bernoulli::Bernoulli),
    /// Shell — see [`shell::Shell`].
    Shell(shell::Shell),
    /// Distributed load — see [`flux::Flux`]. The first variant whose whole term
    /// is on the right of `Σ f_int = Σ f_ext`.
    Flux(flux::Flux),
}

impl SubModel {
    /// Borrow the variant as its [`SubModelKind`] behaviour. This is the
    /// **only** per-variant `match` in the model layer; every generic
    /// method (variable names, material contract, assembly, rendering)
    /// dispatches through it.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// // Le seul `match` par variante de la couche modèle : tout le reste
    /// // — noms de variables, contrat matériau, assemblage — passe par là.
    /// let m = SubModel::heat_conduction(zone.clone())?;
    /// assert_eq!(m.as_kind().primal_vars(), vec!["T".to_string()]);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn as_kind(&self) -> &dyn SubModelKind {
        match self {
            SubModel::HeatConduction(p) => p,
            SubModel::BoundaryTransfer(p) => p,
            SubModel::Dirichlet(p) => p,
            SubModel::Mpc(p) => p,
            SubModel::Embedded(p) => p,
            SubModel::Contact(p) => p,
            SubModel::Truss(p) => p,
            SubModel::Elasticity(p) => p,
            SubModel::Plasticity(p) => p,
            SubModel::Mazars(p) => p,
            SubModel::Timoshenko(p) => p,
            SubModel::Fick(p) => p,
            SubModel::InterfaceTransfer(p) => p,
            SubModel::Radiation(p) => p,
            SubModel::Bernoulli(p) => p,
            SubModel::Shell(p) => p,
            SubModel::Flux(p) => p,
        }
    }

    /// Distributed-load sub-model on an FE subspace: `∫ φ N dΓ` into the `dual`
    /// row, the density supplied at assembly time as `phi_<dual>`.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::SubModel;
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::SubModelKind;
    /// # use pyrucast::ops::model;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
    /// # sm.add_cell(&[n[0].id(), n[1].id()]).unwrap();
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let cible = model::heat_conduction(&fes)?;
    /// let charge = SubModel::flux(zone, &cible, "q".into())?;
    /// assert_eq!(charge.as_kind().label(), "Flux");
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn flux(
        fespace: Handle<SubFiniteElementSpace>,
        target: &Model,
        dual: String,
    ) -> Result<Self> {
        Ok(SubModel::Flux(flux::Flux::new(fespace, target, dual)?))
    }

    /// Heat-conduction sub-model on an FE subspace.
    ///
    /// Material data (conductivity `"k"`, …) is supplied separately at
    /// assembly time via [`crate::ops::matrix::stiffness`], keeping
    /// the model immutable and material-independent. See
    /// [`heat_conduction::HeatConduction::new`] for the support it builds.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// let m = SubModel::heat_conduction(zone.clone())?;
    /// // Le matériau n'entre pas ici : le modèle reste immuable et sans matière.
    /// assert_eq!(m.material_components(), Some(vec!["k".to_string()]));
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn heat_conduction(fespace: Handle<SubFiniteElementSpace>) -> Result<Self> {
        Self::heat_conduction_with_symmetry(fespace, MaterialSymmetry::Isotropic)
    }

    /// Heat conduction with an explicit material symmetry — an orthotropic or
    /// anisotropic conductivity carries its constants **and its axes** through
    /// the material field. See [`crate::models::symmetry`].
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// // Une conductivité orthotrope porte ses constantes **et ses axes** dans
    /// // le champ matériau — d'où un contrat matériau plus large.
    /// let iso = SubModel::heat_conduction(zone.clone())?;
    /// let ortho = SubModel::heat_conduction_with_symmetry(
    ///     zone.clone(), MaterialSymmetry::Orthotropic)?;
    /// assert!(ortho.material_components().unwrap().len()
    ///         > iso.material_components().unwrap().len());
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn heat_conduction_with_symmetry(
        fespace: Handle<SubFiniteElementSpace>,
        symmetry: MaterialSymmetry,
    ) -> Result<Self> {
        Ok(SubModel::HeatConduction(
            heat_conduction::HeatConduction::with_symmetry(fespace, symmetry)?,
        ))
    }

    /// Surface exchange with an imposed ambient (Robin / film) on a boundary FE
    /// subspace, on the `(primal, dual)` pairs given.
    ///
    /// Naming the bulk physics' own DOFs is what makes the boundary term couple
    /// straight into it — `[("T", "q")]` beside a conduction, `[("c_H2",
    /// "j_H2")]` beside a diffusion, the three displacement pairs for an elastic
    /// foundation. `target` is the model assembling those pairs; it gives the
    /// exchange its nature. The coefficients `h_<primal>` **and** the ambients
    /// `a_ext_<primal>` are supplied at assembly time, in the material: the
    /// exchange goes into the matrix, the ambient term `h·a_ext ∫N_i dΓ` comes
    /// out of [`crate::ops::node_field::external_forces()`].
    /// See [`boundary_transfer::BoundaryTransfer::new`].
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// # let mut bord = SubMesh::new(coords.clone(), ElementType::SEG2);
    /// # bord.add_cell(&[n[0].id(), n[1].id()])?;
    /// # let fes_bord = FiniteElementSpace::lagrange1(&Mesh::from_submesh(bord))?;
    /// // Nommer les DDL de la physique de volume, c'est ce qui fait que le
    /// // terme de bord se couple droit dedans.
    /// let m = SubModel::boundary_transfer(
    ///     fes_bord.get(0)?, &cible, vec![("T".into(), "q".into())])?;
    /// assert_eq!(m.primal_vars(), vec!["T".to_string()]);
    /// assert!(m.material_components().unwrap().contains(&"h_T".to_string()));
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn boundary_transfer(
        fespace: Handle<SubFiniteElementSpace>,
        target: &Model,
        components: Vec<(String, String)>,
    ) -> Result<Self> {
        Ok(SubModel::BoundaryTransfer(
            boundary_transfer::BoundaryTransfer::new(fespace, target, components)?,
        ))
    }

    /// Truss / bar sub-model on a `SEG2` FE subspace. Material data (`E`, `A`)
    /// is supplied at assembly time. See [`truss::Truss::new`].
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// # let mut b = SubMesh::new(coords.clone(), ElementType::SEG2);
    /// # b.add_cell(&[n[0].id(), n[1].id()])?;
    /// # let barres = FiniteElementSpace::lagrange1(&Mesh::from_submesh(b))?;
    /// let m = SubModel::truss(barres.get(0)?)?;
    /// assert_eq!(m.material_components(), Some(vec!["E".to_string(), "A".to_string()]));
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn truss(fespace: Handle<SubFiniteElementSpace>) -> Result<Self> {
        Ok(SubModel::Truss(truss::Truss::new(fespace)?))
    }

    /// **Isotropic** linear-elasticity sub-model on an FE subspace, with the
    /// given 2-D/3-D model. Material data (`E`, `nu`) is supplied at assembly
    /// time. See [`elasticity::Elasticity::new`].
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// let m = SubModel::elasticity(zone.clone(), Kinematics::PlaneStress)?;
    /// assert_eq!(m.primal_vars(), vec!["u_x".to_string(), "u_y".to_string()]);
    /// assert_eq!(m.dual_vars(), vec!["f_x".to_string(), "f_y".to_string()]);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn elasticity(
        fespace: Handle<SubFiniteElementSpace>,
        kinematics: Kinematics,
    ) -> Result<Self> {
        Self::elasticity_with_symmetry(fespace, kinematics, MaterialSymmetry::Isotropic)
    }

    /// Linear elasticity with an explicit material symmetry — orthotropic and
    /// anisotropic materials carry their constants **and their axes** through the
    /// material field. See [`crate::models::symmetry`] for the contracts.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// // Isotrope : `E` et `nu`. Orthotrope : les modules par direction et les
    /// // axes du matériau, tous portés par le champ matériau.
    /// let m = SubModel::elasticity_with_symmetry(
    ///     zone.clone(), Kinematics::PlaneStress, MaterialSymmetry::Orthotropic)?;
    /// assert!(m.material_components().unwrap().len() > 2);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn elasticity_with_symmetry(
        fespace: Handle<SubFiniteElementSpace>,
        kinematics: Kinematics,
        symmetry: MaterialSymmetry,
    ) -> Result<Self> {
        Ok(SubModel::Elasticity(elasticity::Elasticity::with_symmetry(
            fespace, kinematics, symmetry,
        )?))
    }

    /// Fickian-diffusion sub-model on an FE subspace (primal `c`, dual `j`),
    /// **isotropic**. Material data (the diffusivity) is supplied at assembly
    /// time. See [`fick::Fick::with_symmetry`].
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// // L'espèce nomme les variables : une diffusion par espèce transportée.
    /// let m = SubModel::fick(zone.clone(), "H2")?;
    /// assert_eq!(m.primal_vars(), vec!["c_H2".to_string()]);
    /// assert_eq!(m.dual_vars(), vec!["j_H2".to_string()]);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn fick(fespace: Handle<SubFiniteElementSpace>, species: &str) -> Result<Self> {
        Self::fick_with_symmetry(fespace, MaterialSymmetry::Isotropic, species)
    }

    /// Fickian diffusion with an explicit material symmetry — an orthotropic or
    /// anisotropic diffusivity carries its constants **and its axes** through
    /// the material field, exactly as [`Self::heat_conduction_with_symmetry`]
    /// does. See [`crate::models::symmetry`].
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// let m = SubModel::fick_with_symmetry(
    ///     zone.clone(), MaterialSymmetry::Orthotropic, "H2")?;
    /// assert_eq!(m.physics(), &[Physics::Diffusion]);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn fick_with_symmetry(
        fespace: Handle<SubFiniteElementSpace>,
        symmetry: MaterialSymmetry,
        species: &str,
    ) -> Result<Self> {
        Ok(SubModel::Fick(fick::Fick::with_symmetry(
            fespace, symmetry, species,
        )?))
    }

    /// Radiation-to-infinity sub-model on a **boundary** FE subspace —
    /// `q·n = σε(T⁴ − T_∞⁴)`. Same DOFs (`"T"`/`"q"`) as
    /// [`Self::heat_conduction`], so it couples straight into the conduction
    /// stiffness — `target`, which must assemble them. Material (`emis`,
    /// `T_inf`, optionally `sigma`) is supplied at assembly time. See
    /// [`radiation::Radiation::new`].
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// // Mêmes DDL que la conduction : le rayonnement se couple droit dedans.
    /// let m = SubModel::radiation(zone.clone(), &cible)?;
    /// assert_eq!(m.primal_vars(), vec!["T".to_string()]);
    /// assert_eq!(m.dual_vars(), vec!["q".to_string()]);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn radiation(fespace: Handle<SubFiniteElementSpace>, target: &Model) -> Result<Self> {
        Ok(SubModel::Radiation(radiation::Radiation::new(
            fespace, target,
        )?))
    }

    /// Euler-Bernoulli beam sub-model on a `SEG2` FE subspace, in the given
    /// configuration. See [`bernoulli::Bernoulli::new`].
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// # let mut b = SubMesh::new(coords.clone(), ElementType::SEG2);
    /// # b.add_cell(&[n[0].id(), n[1].id()])?;
    /// # use pyrucast::atoms::Interpolation;
    /// // La flèche est interpolée en Hermite cubique : une base Lagrange
    /// // porterait une flèche affine, de courbure identiquement nulle.
    /// let poutres = FiniteElementSpace::new(&Mesh::from_submesh(b), Interpolation::Hermite3)?;
    /// let m = SubModel::bernoulli(poutres.get(0)?)?;
    /// assert!(m.has_behavior());
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn bernoulli(fespace: Handle<SubFiniteElementSpace>) -> Result<Self> {
        Ok(SubModel::Bernoulli(bernoulli::Bernoulli::new(fespace)?))
    }

    /// Shell sub-model on a **surface** FE subspace in 3-D. See
    /// [`shell::Shell::new`].
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::SubModel;
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::shell::ShellModel;
    /// # use pyrucast::models::Physics;
    /// // Une coque vit sur une surface **plongée dans l'espace 3-D**.
    /// # let coords = Handle::new(Coords::new(3).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()])?;
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm))?;
    /// let m = SubModel::shell(fes.get(0)?, ShellModel::Thick)?;
    /// assert_eq!(m.physics(), &[Physics::Mechanical]);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn shell(fespace: Handle<SubFiniteElementSpace>, model: shell::ShellModel) -> Result<Self> {
        Ok(SubModel::Shell(shell::Shell::new(fespace, model)?))
    }

    /// Interface-exchange sub-model between two **conforming** boundary FE
    /// subspaces — `j·n = h(a₁ − a₂)` on each `(primal, dual)` pair given. The
    /// coefficients `h_<primal>` are supplied at assembly time. See
    /// [`interface_transfer::InterfaceTransfer::new`].
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// # let mut bord = SubMesh::new(coords.clone(), ElementType::SEG2);
    /// # bord.add_cell(&[n[0].id(), n[1].id()])?;
    /// # let fes_bord = FiniteElementSpace::lagrange1(&Mesh::from_submesh(bord))?;
    /// // Deux bords **conformes** : ici le même, ce qui suffit à montrer le
    /// // contrat ; en pratique deux faces en vis-à-vis.
    /// let m = SubModel::interface_transfer(
    ///     fes_bord.get(0)?, fes_bord.get(0)?, &cible,
    ///     vec![("T".into(), "q".into())], 1e-6)?;
    /// assert_eq!(m.primal_vars(), vec!["T".to_string()]);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn interface_transfer(
        side_a: Handle<SubFiniteElementSpace>,
        side_b: Handle<SubFiniteElementSpace>,
        target: &Model,
        components: Vec<(String, String)>,
        tol: f64,
    ) -> Result<Self> {
        Ok(SubModel::InterfaceTransfer(
            interface_transfer::InterfaceTransfer::new(side_a, side_b, target, components, tol)?,
        ))
    }

    /// **Perfect** (non-hardening) von Mises plasticity on an FE subspace, with
    /// the given 2-D/3-D model. Material (`E`, `nu`, `sigma_y`) is supplied at
    /// assembly / integration time. See [`plasticity::Plasticity::new`].
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// // Von Mises sans écrouissage : `sigma_y` en plus de l'élasticité.
    /// let m = SubModel::plasticity_perfect(zone.clone(), Kinematics::PlaneStrain)?;
    /// assert!(m.material_components().unwrap().contains(&"sigma_y".to_string()));
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn plasticity_perfect(
        fespace: Handle<SubFiniteElementSpace>,
        kinematics: Kinematics,
    ) -> Result<Self> {
        Self::plasticity_with_law(fespace, kinematics, plasticity::law::PlasticLaw::Perfect)
    }

    /// Elastoplasticity with an explicit yield law — the general form.
    /// The material each law needs is declared by
    /// [`PlasticLaw::material_components`](plasticity::law::PlasticLaw::material_components).
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// # use pyrucast::models::plasticity::law::PlasticLaw;
    /// // La loi d'écrouissage **déclare elle-même** le matériau qu'elle exige.
    /// let m = SubModel::plasticity_with_law(
    ///     zone.clone(), Kinematics::PlaneStrain, PlasticLaw::Perfect)?;
    /// assert!(m.has_behavior());
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn plasticity_with_law(
        fespace: Handle<SubFiniteElementSpace>,
        kinematics: Kinematics,
        law: plasticity::law::PlasticLaw,
    ) -> Result<Self> {
        Ok(SubModel::Plasticity(plasticity::Plasticity::with_law(
            fespace, kinematics, law,
        )?))
    }

    /// Mazars-damage sub-model on an FE subspace, with the given 2-D/3-D model.
    /// Material (`E`, `nu`, `eps_d0`, `A_t`, `B_t`, `A_c`, `B_c`) is supplied at
    /// assembly / integration time. See [`damage::Damage::new`].
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// let m = SubModel::mazars(zone.clone(), Kinematics::PlaneStress)?;
    /// let mat = m.material_components().unwrap();
    /// assert!(mat.contains(&"eps_d0".to_string()));
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn mazars(fespace: Handle<SubFiniteElementSpace>, kinematics: Kinematics) -> Result<Self> {
        Self::damage_with_law(fespace, kinematics, damage::law::DamageLaw::Mazars)
    }

    /// Damage with an explicit law — Mazars, the tension/compression pair, or the
    /// orthotropic SiC/SiC. See [`damage::Damage::with_law`].
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// # use pyrucast::models::damage::law::DamageLaw;
    /// let m = SubModel::damage_with_law(
    ///     zone.clone(), Kinematics::PlaneStress, DamageLaw::Mazars)?;
    /// assert_eq!(m.physics(), &[Physics::Mechanical]);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn damage_with_law(
        fespace: Handle<SubFiniteElementSpace>,
        kinematics: Kinematics,
        law: damage::law::DamageLaw,
    ) -> Result<Self> {
        Ok(SubModel::Mazars(damage::Damage::with_law(
            fespace, kinematics, law,
        )?))
    }

    /// Timoshenko-beam sub-model on a 1-D `SEG2` FE subspace (full Gauss).
    /// Material data (`E`, `I`, `G`, `A_s`) is supplied at assembly time. See
    /// [`timoshenko::Timoshenko::new`].
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// # let mut b = SubMesh::new(coords.clone(), ElementType::SEG2);
    /// # b.add_cell(&[n[0].id(), n[1].id()])?;
    /// # use pyrucast::atoms::Interpolation;
    /// // L'interpolation exacte dépend du matériau par Φ = 12EI/(G·A_s·L²) :
    /// // elle appartient à la formulation, pas à l'espace.
    /// let poutres =
    ///     FiniteElementSpace::new(&Mesh::from_submesh(b), Interpolation::ModelEmbedded)?;
    /// let m = SubModel::timoshenko(poutres.get(0)?)?;
    /// assert_eq!(m.physics(), &[Physics::Mechanical]);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn timoshenko(fespace: Handle<SubFiniteElementSpace>) -> Result<Self> {
        Ok(SubModel::Timoshenko(timoshenko::Timoshenko::new(fespace)?))
    }

    /// Dirichlet sub-model: enforce `imposed_variable = u_d` on the nodes of
    /// `imposed_mesh`, with multipliers living on `multiplier_mesh` and `u_d`
    /// supplied later by the user through the load `SubNodeField`.
    ///
    /// `target_dual` is the dual variable name of the target physics whose
    /// primal is being constrained (e.g. `"q"` for heat conduction, `"f_x"`
    /// for elasticity in `x`). `multiplier` / `imposed_value` default to
    /// `lambda_<imposed_variable>` / `imposed_<imposed_variable>` when `None`.
    /// `sense` (default equality) turns the constraint unilateral (`u ≥ u_d` /
    /// `u ≤ u_d`), solved by the active-set operator
    /// [`unilateral`](crate::ops::solver::unilateral).
    /// See [`dirichlet::Dirichlet::new`].
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// // `u_d` n'est pas ici : il est écrit plus tard, au nœud multiplicateur,
    /// // dans la composante `imposed_T`.
    /// let m = SubModel::dirichlet(
    ///     &cible, "T", &impose, &mult, RelationSense::Equality)?;
    /// assert_eq!(m.multiplier_nodes().len(), 1);
    /// assert_eq!(m.physics(), &[Physics::Constraint]);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    #[allow(clippy::too_many_arguments)]
    pub fn dirichlet(
        target: &Model,
        variable: &str,
        imposed_mesh: &Mesh,
        multiplier_mesh: &Mesh,
        sense: RelationSense,
    ) -> Result<Self> {
        Ok(SubModel::Dirichlet(dirichlet::Dirichlet::new(
            target,
            variable,
            imposed_mesh,
            multiplier_mesh,
            sense,
        )?))
    }

    /// Multi-point constraint sub-model: impose a linear relation
    /// `Σₖ aₖ·u(nodeₖ, varₖ) = g` per relation, via Lagrange multipliers.
    ///
    /// `terms` are the `(mesh, variable, target_dual, coefficient)` terms
    /// (build them with [`mpc::MpcTerm::new`]); `multiplier_mesh` carries one
    /// `λ` node per relation. `multiplier` / `imposed_value` default to
    /// `lambda_mpc` / `mpc_rhs`. The right-hand side `g` is written by the user
    /// in the load field at the multiplier node's `imposed_value` component
    /// (default `0`). `sense` (default equality) turns the relations unilateral
    /// (`Σ aₖ·uₖ ≥ g` / `≤ g`), solved by the active-set operator
    /// [`unilateral`](crate::ops::solver::unilateral). See [`mpc::Mpc::new`].
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// # use pyrucast::models::mpc::MpcTerm;
    /// # let a = mesh::poi1_from_nodes(&n[..1])?;
    /// # let b = mesh::poi1_from_nodes(&n[1..2])?;
    /// // Une relation « les deux nœuds ont la même température » : la somme
    /// // pondérée des termes vaut `g`, écrit plus tard au multiplicateur.
    /// let m = SubModel::mpc(
    ///     vec![MpcTerm::new(&cible, &a, "T", 1.0)?,
    ///          MpcTerm::new(&cible, &b, "T", -1.0)?],
    ///     &mult, RelationSense::Equality)?;
    /// assert_eq!(m.multiplier_nodes().len(), 1); // un λ par relation
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn mpc(
        terms: Vec<mpc::MpcTerm>,
        multiplier_mesh: &Mesh,
        sense: RelationSense,
    ) -> Result<Self> {
        Ok(SubModel::Mpc(mpc::Mpc::new(terms, multiplier_mesh, sense)?))
    }

    /// Embedded (immersed) constraint sub-model: tie each node of `immersed` to
    /// the interpolation of `host` at that node, for every `(variable,
    /// target_dual)` in `components` (e.g. `[("u_x","f_x"), ("u_y","f_y"),
    /// ("u_z","f_z")]`) — a bar « baignée » in a volume.
    ///
    /// The coupling weights are the host shape functions at each immersed node,
    /// computed once at build by locating the node in the host. `multipliers` /
    /// `imposed_values` default to `lambda_<variable>` / `imposed_<variable>`;
    /// `tol` is the location tolerance (default `1e-6`). The right-hand side `g`
    /// defaults to `0` (a rigid tie). See [`embedded::Embedded::new`].
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::elasticity(&fes, pyrucast::models::tensor::Kinematics::PlaneStress)
    ///     .unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// # let mut barre = SubMesh::new(coords.clone(), ElementType::SEG2);
    /// # let p: Vec<_> = [[0.25, 0.25], [0.5, 0.25]].iter()
    /// #     .map(|q| Node::create_in(coords.clone(), q).unwrap()).collect();
    /// # barre.add_cell(&[p[0].id(), p[1].id()])?;
    /// # let immergee = Mesh::from_submesh(barre);
    /// // Une barre « baignée » dans le volume : chaque nœud immergé est lié à
    /// // l'interpolation de l'hôte en ce point — les poids sont les N_i, donc
    /// // des coefficients qui **varient d'un nœud à l'autre**.
    /// let m = SubModel::embedded(
    ///     &cible, &immergee, &maillage,
    ///     vec!["u_x".into(), "u_y".into()], pyrucast::models::embedded::DEFAULT_TOL)?;
    /// assert_eq!(m.physics(), &[Physics::Constraint]);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    #[allow(clippy::too_many_arguments)]
    pub fn embedded(
        target: &Model,
        immersed: &Mesh,
        host: &Mesh,
        variables: Vec<String>,
        tol: f64,
    ) -> Result<Self> {
        Ok(SubModel::Embedded(embedded::Embedded::new(
            target, immersed, host, variables, tol,
        )?))
    }

    /// Node-to-surface contact sub-model: prevent the nodes of `slave` from
    /// penetrating the oriented `master` surface mesh — one **unilateral**
    /// relation (`≥`) per slave node, paired at build with its closest master
    /// facet ([`crate::ops::geom::project_points`]).
    ///
    /// `components` couples the displacement components through the facet
    /// normal: one `(variable, target_dual)` pair per space dimension, in
    /// ambient order (e.g. `[("u_x","f_x"), ("u_y","f_y")]`). `multiplier` /
    /// `imposed_value` default to `lambda_contact` / `contact_gap`. Solve with
    /// [`unilateral`](crate::ops::solver::unilateral); build the `−g₀`
    /// right-hand side with [`Model::contact_gaps`]. See
    /// [`contact::Contact::new`].
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::elasticity(&fes, pyrucast::models::tensor::Kinematics::PlaneStress)
    ///     .unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// # let mut maitre = SubMesh::new(coords.clone(), ElementType::SEG2);
    /// # maitre.add_cell(&[n[0].id(), n[1].id()])?;
    /// # let master = Mesh::from_submesh(maitre);
    /// # let slave = mesh::poi1_from_nodes(&n[2..3])?;
    /// // Une relation **unilatérale** par nœud esclave, appariée à sa facette
    /// // maître la plus proche dès la construction.
    /// let m = SubModel::contact(
    ///     &cible, &slave, &master,
    ///     vec!["u_x".into(), "u_y".into()])?;
    /// assert_eq!(m.multiplier_nodes().len(), 1);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn contact(
        target: &Model,
        slave: &Mesh,
        master: &Mesh,
        variables: Vec<String>,
    ) -> Result<Self> {
        Ok(SubModel::Contact(contact::Contact::new(
            target, slave, master, variables,
        )?))
    }

    /// The dual (residual) variable conjugate to a primal `variable`, by the
    /// positional pairing `primal_vars[i] ↔ dual_vars[i]` this sub-model
    /// declares, or `None` if it declares no such primal. A helper for the MPC
    /// mise-en-donnée: `dual_of("u_x") == Some("f_x")`.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// let m = SubModel::elasticity(zone.clone(), Kinematics::PlaneStress)?;
    /// // L'appariement est **positionnel** : primal_vars[i] ↔ dual_vars[i].
    /// assert_eq!(m.dual_of("u_x"), Some("f_x".into()));
    /// assert_eq!(m.dual_of("T"), None);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn dual_of(&self, variable: &str) -> Option<String> {
        let kind = self.as_kind();
        let position = kind.primal_vars().iter().position(|p| p == variable)?;
        kind.dual_vars().get(position).cloned()
    }

    /// Multiplier node ids introduced by this sub-model. Non-empty only
    /// for Lagrange variants (`Dirichlet`, future `MultipointConstraint`,
    /// …); empty for the other physics.
    ///
    /// Useful for the user who needs to write the imposed value `u_d` at
    /// the multiplier node's `imposed_value` component of the load
    /// `SubNodeField`.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// let d = SubModel::dirichlet(
    ///     &cible, "T", &impose, &mult, RelationSense::Equality)?;
    /// assert_eq!(d.multiplier_nodes().len(), 1);
    /// // Vide pour une physique volumique : elle n'introduit pas de multiplicateur.
    /// assert!(SubModel::heat_conduction(zone.clone())?.multiplier_nodes().is_empty());
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn multiplier_nodes(&self) -> Vec<NodeId> {
        let mut out = Vec::new();
        if let Some(constraint) = self.as_kind().as_constraint() {
            for sm in constraint.multiplier_mesh() {
                out.extend(sm.read().connectivity().iter().copied());
            }
        }
        out
    }

    /// POI1 [`Mesh`] of the multiplier nodes (shares the multiplier submeshes
    /// — zero-copy). Empty for non-Lagrange physics.
    ///
    /// This is the user-facing handle to the multiplier nodes: build a load
    /// [`crate::containers::node_field::SubNodeField`] on it to impose the
    /// constrained values.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// let d = SubModel::dirichlet(
    ///     &cible, "T", &impose, &mult, RelationSense::Equality)?;
    /// // Le maillage POI1 **partagé** — pas une copie : c'est la poignée sur
    /// // laquelle bâtir le champ de chargement.
    /// assert!(d.multiplier_mesh()?.node(0, 0, 0).is_ok());
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn multiplier_mesh(&self) -> Result<Mesh> {
        let mut mesh = Mesh::empty();
        if let Some(constraint) = self.as_kind().as_constraint() {
            for sm in constraint.multiplier_mesh() {
                mesh.add_sub(sm.clone())?;
            }
        }
        Ok(mesh)
    }

    /// Build the constraint load (right-hand side) for this sub-model from a set
    /// of `(constrained_node, g)` pairs — the mise-en-donnée helper that spares
    /// the user from rebuilding the multiplier mesh and remembering the
    /// imposed-value component name by hand.
    ///
    /// Returns a fresh [`NodeField`] over **this constraint's multiplier nodes**,
    /// carrying the single component the constraint uses as its imposed-value
    /// slot — its dual variable, e.g. `imposed_T` for a `Dirichlet` on `T` or
    /// `mpc_rhs` for an `Mpc`. Every multiplier node is present; each cited
    /// relation gets its `g`, the others default to `0`. Union it into the global
    /// load with `|` (`load | constraint_rhs`).
    ///
    /// A node **keys the relation it belongs to**: for `Dirichlet` the single
    /// constrained node, for `Mpc` any of the relation's term nodes. The method
    /// looks up that relation's multiplier node (via
    /// [`Constraint::relations`]) and writes
    /// `g` there. When a node participates in several relations (so node keying
    /// is ambiguous), key by index instead with
    /// [`constraint_rhs_by_index`](Self::constraint_rhs_by_index).
    ///
    /// Errors when `self` is not a constraint, when a cited node is constrained
    /// by none of its relations, when a node keys **several** relations (node
    /// keying is ambiguous there), or when two cited nodes key the *same*
    /// relation with conflicting values.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// # use pyrucast::containers::field::SubField;
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// let d = SubModel::dirichlet(
    ///     &cible, "T", &impose, &mult, RelationSense::Equality)?;
    /// // On cite le nœud **contraint** ; la méthode retrouve son multiplicateur
    /// // et y écrit la valeur, sous le bon nom de composante.
    /// let rhs = d.constraint_rhs(&[(n[0].id(), 100.0)])?;
    /// assert_eq!(rhs.get(0)?.read().components(), &["imposed_T".to_string()]);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn constraint_rhs(&self, imposed: &[(NodeId, f64)]) -> Result<NodeField> {
        let (constraint, components) = self.constraint_components()?;
        let relations = constraint.relations()?;

        // Map each constrained term node → the index of its relation, marking
        // `None` as soon as a node keys two *distinct* relations (a
        // multi-component `Embedded` node keys one relation per component, so it
        // is ambiguous here — the message points to the by-index variant).
        let mut node_to_rel: std::collections::HashMap<NodeId, Option<usize>> =
            std::collections::HashMap::new();
        for (i, rel) in relations.iter().enumerate() {
            for term in &rel.terms {
                node_to_rel
                    .entry(term.node)
                    .and_modify(|slot| {
                        if *slot != Some(i) {
                            *slot = None;
                        }
                    })
                    .or_insert(Some(i));
            }
        }

        // Resolve the requested (node, g) → (multiplier node, slot, g).
        let mut values: std::collections::HashMap<(NodeId, String), f64> =
            std::collections::HashMap::new();
        for &(node, g) in imposed {
            let idx = match node_to_rel.get(&node) {
                None => {
                    return Err(PyrucastError::Message(format!(
                        "constraint_rhs: node {node} is not constrained by this {}",
                        self.as_kind().label()
                    )))
                }
                Some(None) => {
                    return Err(PyrucastError::Message(format!(
                        "constraint_rhs: node {node} keys several relations of this {} — \
                         node keying is ambiguous, use constraint_rhs_by_index",
                        self.as_kind().label()
                    )))
                }
                Some(Some(i)) => *i,
            };
            let rel = &relations[idx];
            insert_relation_value(
                &mut values,
                rel.multiplier_node,
                &rel.imposed_value,
                g,
                "constraint_rhs",
            )?;
        }

        self.multiplier_load(&components, &values)
    }

    /// Like [`constraint_rhs`](Self::constraint_rhs) but each relation is keyed
    /// by its **index** in [`Constraint::relations`]
    /// order (`0`-based) rather than by a node — the way to reach a relation
    /// whose nodes are shared with others, where node keying would be ambiguous.
    ///
    /// `imposed` is a set of `(relation_index, g)` pairs; the returned field and
    /// the union semantics are identical to `constraint_rhs`. Errors when `self`
    /// is not a constraint, when an index is out of range, or when two pairs
    /// target the same relation with conflicting values.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// let d = SubModel::dirichlet(
    ///     &cible, "T", &impose, &mult, RelationSense::Equality)?;
    /// // Par **indice de relation** : la voie quand un nœud en clé plusieurs.
    /// let rhs = d.constraint_rhs_by_index(&[(0, 100.0)])?;
    /// assert_eq!(rhs.node_count()?, 1);
    /// assert!(d.constraint_rhs_by_index(&[(7, 0.0)]).is_err());
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn constraint_rhs_by_index(&self, imposed: &[(usize, f64)]) -> Result<NodeField> {
        let (constraint, components) = self.constraint_components()?;
        let relations = constraint.relations()?;

        let mut values: std::collections::HashMap<(NodeId, String), f64> =
            std::collections::HashMap::new();
        for &(idx, g) in imposed {
            let rel = relations.get(idx).ok_or_else(|| {
                PyrucastError::Message(format!(
                    "constraint_rhs_by_index: relation index {idx} out of range (this \
                     constraint has {} relation(s))",
                    relations.len()
                ))
            })?;
            insert_relation_value(
                &mut values,
                rel.multiplier_node,
                &rel.imposed_value,
                g,
                "constraint_rhs_by_index",
            )?;
        }

        self.multiplier_load(&components, &values)
    }

    /// Borrow this sub-model as a [`Constraint`](crate::models::Constraint) and
    /// return its imposed-value components (its duals — one for a single-dual
    /// constraint, several for a multi-component `Embedded`). Shared entry check
    /// of the `constraint_rhs*` helpers.
    fn constraint_components(&self) -> Result<(&dyn Constraint, Vec<String>)> {
        let kind = self.as_kind();
        let constraint = kind.as_constraint().ok_or_else(|| {
            PyrucastError::Message(format!(
                "constraint_rhs: sub-model {} is not a constraint (it has no multipliers)",
                kind.label()
            ))
        })?;
        let components = kind.dual_vars();
        if components.is_empty() {
            return Err(PyrucastError::Message(
                "constraint_rhs: the constraint owns no dual (imposed-value) variable".into(),
            ));
        }
        Ok((constraint, components))
    }

    /// Build the constraint load over **every** multiplier node: one
    /// zero-initialised zone per multiplier submesh (carrying **all** the
    /// constraint's imposed-value `components`, sharing the supports and
    /// preserving the structure carried through `barycenter`), then drop each
    /// resolved `(multiplier node, slot) → g` in at its component. Shared tail of
    /// the `constraint_rhs*` helpers.
    fn multiplier_load(
        &self,
        components: &[String],
        values: &std::collections::HashMap<(NodeId, String), f64>,
    ) -> Result<NodeField> {
        let mut field = NodeField::default();
        for sm in &self.multiplier_mesh()? {
            let mut sub = SubNodeField::from_poi1(sm, components.to_vec())?;
            let nids: Vec<NodeId> = sm.read().connectivity().to_vec();
            for nid in nids {
                for comp in components {
                    if let Some(&g) = values.get(&(nid, comp.clone())) {
                        sub.set_value(nid, comp, g)?;
                    }
                }
            }
            field.add_sub(Handle::new(sub))?;
        }
        Ok(field)
    }

    /// FE subspace on which this sub-model expects its material data, or
    /// `None` if this physics doesn't need material data (e.g. `Dirichlet`).
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// assert!(SubModel::heat_conduction(zone.clone())?.material_fespace().is_some());
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// // Une contrainte n'a pas de matière.
    /// let d = SubModel::dirichlet(
    ///     &cible, "T", &impose, &mult, RelationSense::Equality)?;
    /// assert!(d.material_fespace().is_none());
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn material_fespace(&self) -> Option<Handle<SubFiniteElementSpace>> {
        self.as_kind().as_domain().map(|d| d.material_fespace())
    }

    /// Material component names this sub-model expects, or `None` if it
    /// doesn't need material data. Thin pass-through of
    /// [`Domain::material_components`](crate::models::Domain::material_components).
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// let m = SubModel::elasticity(zone.clone(), Kinematics::PlaneStress)?;
    /// assert_eq!(m.material_components(), Some(vec!["E".to_string(), "nu".to_string()]));
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn material_components(&self) -> Option<Vec<String>> {
        self.as_kind().as_domain().map(|d| d.material_components())
    }

    /// Optional material component names this sub-model accepts (never required).
    /// Thin pass-through of
    /// [`Domain::optional_material_components`](crate::models::Domain::optional_material_components).
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// // La dilatation thermique est **facultative** : sans `alpha`, le modèle
    /// // s'assemble sans elle.
    /// let m = SubModel::elasticity(zone.clone(), Kinematics::PlaneStress)?;
    /// assert!(m.optional_material_components().contains(&"alpha"));
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn optional_material_components(&self) -> &'static [&'static str] {
        self.as_kind()
            .as_domain()
            .map(|d| d.optional_material_components())
            .unwrap_or(&[])
    }

    /// Primal variable names introduced by this sub-model.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// assert_eq!(SubModel::heat_conduction(zone.clone())?.primal_vars(),
    ///            vec!["T".to_string()]);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn primal_vars(&self) -> Vec<String> {
        self.as_kind().primal_vars()
    }

    /// Dual variable names introduced by this sub-model.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// assert_eq!(SubModel::heat_conduction(zone.clone())?.dual_vars(),
    ///            vec!["q".to_string()]);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn dual_vars(&self) -> Vec<String> {
        self.as_kind().dual_vars()
    }

    /// This sub-model's set of [`Physics`] natures — a per-variant constant
    /// slice, determined entirely by the variant (a single nature today; several
    /// for a future coupled physics). Feeds [`Model::filter`] and travels with
    /// each assembled block onto the
    /// [`SubMatrix`](crate::containers::matrix::SubMatrix).
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// assert_eq!(SubModel::heat_conduction(zone.clone())?.physics(), &[Physics::Thermal]);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn physics(&self) -> &'static [Physics] {
        self.as_kind().physics()
    }

    /// Whether this sub-model carries a constitutive behaviour that can be
    /// integrated via `integrate_behavior` from a
    /// deformation field. `true` for volumetric physics, `false` for
    /// constraints (`Dirichlet`).
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// assert!(SubModel::heat_conduction(zone.clone())?.has_behavior());
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// let d = SubModel::dirichlet(
    ///     &cible, "T", &impose, &mult, RelationSense::Equality)?;
    /// assert!(!d.has_behavior()); // une contrainte n'a pas de loi de comportement
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn has_behavior(&self) -> bool {
        self.as_kind().as_domain().is_some()
    }

    /// FE subspace this sub-model integrates its behaviour on, or `None`
    /// for a constraint sub-model. The operators in
    /// [`crate::ops::element_field::behavior`] use it to pair the per-zone deformation
    /// field with its sub-model.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// # use pyrucast::handle::Handle as H;
    /// let m = SubModel::heat_conduction(zone.clone())?;
    /// assert!(H::same_object(&m.behavior_fespace().unwrap(), &zone));
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn behavior_fespace(&self) -> Option<Handle<SubFiniteElementSpace>> {
        self.as_kind().as_behavior().map(|b| b.behavior_fespace())
    }

    /// Integrate this sub-model's constitutive law (Cast3m `COMP`), stepping
    /// A → B. The caller ([`crate::ops::element_field::behavior::integrate`]) supplies the
    /// matching per-zone end-of-step `deformation` ε(B) (from
    /// [`crate::ops::element_field::gradient`] / [`crate::ops::element_field::deformation`]),
    /// the previous converged state `prev` (state at A, `None` on the first
    /// step), the `material`, and the time increment `dt` (`None` if
    /// rate-independent).
    pub(crate) fn integrate_behavior(
        &self,
        deformation: &Handle<SubElementField>,
        prev: &Handle<SubElementField>,
        material: &Handle<SubElementField>,
        dt: f64,
    ) -> Result<SubElementField> {
        self.as_kind()
            .as_behavior()
            .ok_or_else(|| {
                crate::error::PyrucastError::Message(format!(
                    "{}: no behaviour — integrate_behavior is undefined",
                    self.as_kind().label()
                ))
            })?
            .integrate_behavior(deformation, prev, material, dt)
    }

    /// Whether this sub-model's law needs the time increment — `false` for a
    /// sub-model with no behaviour at all.
    pub(crate) fn requires_dt(&self) -> bool {
        self.as_kind()
            .as_behavior()
            .is_some_and(|b| b.requires_dt())
    }

    /// This sub-model's material state **at rest** — the `prev` of a first step,
    /// which [`crate::ops::element_field::behavior::integrate`] materializes so
    /// that the state always exists.
    pub(crate) fn initial_state(
        &self,
        material: &Handle<SubElementField>,
    ) -> Result<SubElementField> {
        self.as_kind()
            .as_behavior()
            .ok_or_else(|| {
                crate::error::PyrucastError::Message(format!(
                    "{}: no behaviour — initial_state is undefined",
                    self.as_kind().label()
                ))
            })?
            .initial_state(&material.read())
    }
}

impl fmt::Debug for SubModel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SubModel")
            .field("kind", &self.as_kind().label())
            .field("physics", &self.as_kind().physics())
            .finish()
    }
}

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

impl crate::dump::Dump for SubModel {
    fn render(&self, opts: &crate::dump::DumpOptions) -> String {
        self.as_kind().render(opts)
    }
}

// ─── Model ─────────────────────────────────────────────────────────────────

/// Aggregate of sub-models. Produces matrices on explicit demand.
///
/// Internally a `Vec<Handle<SubModel>>` — see [`Aggregate`]. The Handle
/// refcount keeps each sub-model alive as long as any `Model` (or
/// `PySubModel`) references it; dropping the last reference triggers the
/// sub-model's `Drop` (which releases the Lagrange-multiplier nodes for
/// Dirichlet sub-models).
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::{Model, SubModel};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::tensor::Kinematics;
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::models::{Physics, RelationSense};
/// # use pyrucast::ops::mesh;
/// # use pyrucast::ops::model;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let maillage = Mesh::from_submesh(sm);
/// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let mult = mesh::barycenter(&impose).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
/// // Un modèle se **compose** : la physique, puis les appuis. Chaque
/// // sous-modèle garde sa nature, ce qui permet de les retrouver ensuite.
/// let m = model::heat_conduction(&fes)?.union(
///     &model::dirichlet(&cible, "T", &impose, &mult,
///                       RelationSense::Equality)?)?;
/// assert_eq!(m.len(), 2);
/// assert_eq!(m.filter(Physics::Thermal)?.len(), 1);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Serialize, Deserialize, Default)]
pub struct Model {
    subs: Vec<Handle<SubModel>>,
    /// Memoised global CSR sparsity, **one slot per [`MatrixKind`]** (see
    /// [`Model::matrix_pattern`]). Each kind has its own block topology (mass and
    /// stiffness may span different sub-models), hence its own sparsity. Derived
    /// state: never serialized, and cleared whenever the model changes
    /// (`add_sub` → `post_push`), since a new sub-model changes the DOF layout.
    #[serde(skip)]
    matrix_patterns: [OnceLock<Arc<AssemblyPattern>>; MatrixKind::COUNT],
}

crate::impl_aggregate!(Model, SubModel, sub_model, "sub-model(s)", {
    fn post_push(&mut self) {
        // The block set changed ⇒ every cached sparsity is stale.
        self.matrix_patterns = Default::default();
    }
});
crate::impl_aggregate_dump!(Model);

impl Model {
    /// The model's [`AssemblyPattern`] for `kind`, built once and reused. On the
    /// first call `build` runs and its result is cached; later calls (same
    /// model + kind, e.g. a Newton loop re-assembling with new materials) return
    /// the cached pattern without touching the store — this is what makes
    /// repeated assembly scale, the sparsity being material-independent. The
    /// cache is cleared by `add_sub` (via `post_push`).
    pub(crate) fn matrix_pattern(
        &self,
        kind: MatrixKind,
        build: impl FnOnce() -> Result<AssemblyPattern>,
    ) -> Result<Arc<AssemblyPattern>> {
        let cell = &self.matrix_patterns[kind.index()];
        if let Some(p) = cell.get() {
            return Ok(p.clone());
        }
        let p = Arc::new(build()?);
        // A concurrent first caller may have won the race; either Arc is a valid
        // pattern for this (unchanged) model, so keep whichever landed.
        let _ = cell.set(p.clone());
        Ok(p)
    }
}

impl Model {
    /// The contact right-hand side `−g₀`: a [`NodeField`] carrying, at each
    /// contact multiplier node's `imposed_value` slot, minus the initial signed
    /// gap of its relation — the load a contact model needs so that
    /// non-penetration reads `g₀ + C·u ≥ 0`. Merge it into the global load with
    /// `|`. The model must hold **exactly one** [`SubModel::Contact`]; pairs
    /// initially touching contribute `0` (omitting this helper entirely treats
    /// *every* pair as touching).
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # use pyrucast::ops::model;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::elasticity(&fes, pyrucast::models::tensor::Kinematics::PlaneStress)
    ///     .unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// # let mut maitre = SubMesh::new(coords.clone(), ElementType::SEG2);
    /// # maitre.add_cell(&[n[0].id(), n[1].id()])?;
    /// # let master = Mesh::from_submesh(maitre);
    /// # let slave = mesh::poi1_from_nodes(&n[2..3])?;
    /// let contact = model::contact(&cible, &slave, &master,
    ///     vec!["u_x".into(), "u_y".into()])?;
    /// // Le second membre −g₀ du contact, prêt à unioner au chargement.
    /// assert_eq!(contact.contact_gaps()?.node_count()?, 1);
    /// // Sur un modèle sans contact, la question n'a pas de réponse.
    /// assert!(model::heat_conduction(&fes)?.contact_gaps().is_err());
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn contact_gaps(&self) -> Result<NodeField> {
        let mut found: Option<Handle<SubModel>> = None;
        for h in self {
            if matches!(&*h.read(), SubModel::Contact(_)) {
                if found.is_some() {
                    return Err(PyrucastError::Message(
                        "contact_gaps: model holds several contact sub-models; call it on \
                         a single-contact model (the `contact` object)"
                            .into(),
                    ));
                }
                found = Some(h.clone());
            }
        }
        let handle = found.ok_or_else(|| {
            PyrucastError::Message("contact_gaps: model holds no contact sub-model".into())
        })?;
        let sub = handle.read();
        let SubModel::Contact(c) = &*sub else {
            unreachable!("filtered on Contact above");
        };
        let pairs: Vec<(usize, f64)> = c
            .gaps()
            .iter()
            .enumerate()
            .map(|(i, &g0)| (i, -g0))
            .collect();
        sub.constraint_rhs_by_index(&pairs)
    }

    /// POI1 [`Mesh`] of every constraint multiplier node across the model
    /// (shares the multiplier submeshes — zero-copy). Empty for a model with no
    /// constraint. The handle to the multipliers of a constraint that minted
    /// them itself (e.g. [`embedded`](crate::ops::model::embedded()), whose multiplier mesh is
    /// internal): read the nodes or build the load field on it.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # use pyrucast::ops::model;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// let m = model::heat_conduction(&fes)?.union(
    ///     &model::dirichlet(&cible, "T", &impose, &mult,
    ///                       RelationSense::Equality)?)?;
    /// // Les multiplicateurs de **toutes** les contraintes du modèle, partagés.
    /// assert!(m.multiplier_mesh()?.node(0, 0, 0).is_ok());
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn multiplier_mesh(&self) -> Result<Mesh> {
        let mut mesh = Mesh::empty();
        for h in self {
            if let Some(constraint) = h.read().as_kind().as_constraint() {
                for sm in constraint.multiplier_mesh() {
                    mesh.add_sub(sm.clone())?;
                }
            }
        }
        Ok(mesh)
    }

    /// The dual (residual) variable conjugate to a primal `variable`, searched
    /// across all sub-models (first match), or `None` if no sub-model declares
    /// it. A helper for the MPC mise-en-donnée: `model.dual_of("ux")` returns the
    /// dual to pass in an [`mpc::MpcTerm`].
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # use pyrucast::ops::model;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// let m = model::elasticity(&fes, Kinematics::PlaneStress)?;
    /// // Le dual conjugué, cherché sur l'ensemble des sous-modèles.
    /// assert_eq!(m.dual_of("u_y"), Some("f_y".into()));
    /// assert_eq!(m.dual_of("T"), None);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn dual_of(&self, variable: &str) -> Option<String> {
        for h in self {
            if let Some(dual) = h.read().dual_of(variable) {
                return Some(dual);
            }
        }
        None
    }

    /// Build the constraint load (right-hand side) from `(constrained_node, g)`
    /// pairs — the model-level entry point of the mise-en-donnée helper. The
    /// model must hold **exactly one** constraint sub-model (as returned by
    /// `model::dirichlet` / `model::mpc`); it delegates to
    /// [`SubModel::constraint_rhs`], whose doc describes the node keying and the
    /// returned field.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// # use pyrucast::containers::field::SubField;
    /// # use pyrucast::ops::model;
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// let m = model::heat_conduction(&fes)?.union(
    ///     &model::dirichlet(&cible, "T", &impose, &mult,
    ///                       RelationSense::Equality)?)?;
    /// // Le chargement de contrainte du modèle entier, à unioner au chargement.
    /// let rhs = m.constraint_rhs(&[(n[0].id(), 100.0)])?;
    /// assert_eq!(rhs.get(0)?.read().components(), &["imposed_T".to_string()]);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn constraint_rhs(&self, imposed: &[(NodeId, f64)]) -> Result<NodeField> {
        self.sole_constraint()?.read().constraint_rhs(imposed)
    }

    /// Build the constraint load from `(relation_index, g)` pairs — the
    /// model-level entry point that delegates to
    /// [`SubModel::constraint_rhs_by_index`] (relation keyed by its index rather
    /// than a node). The model must hold **exactly one** constraint sub-model.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # use pyrucast::ops::model;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// let m = model::dirichlet(&cible, "T", &impose, &mult,
    ///                          RelationSense::Equality)?;
    /// // Les indices courent sur les relations, contrainte par contrainte.
    /// assert!(m.constraint_rhs_by_index(&[(0, 100.0)]).is_ok());
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn constraint_rhs_by_index(&self, imposed: &[(usize, f64)]) -> Result<NodeField> {
        self.sole_constraint()?
            .read()
            .constraint_rhs_by_index(imposed)
    }

    /// The model's single constraint sub-model, or an error when it holds none
    /// or several. Shared lookup of the `constraint_rhs*` model-level helpers.
    fn sole_constraint(&self) -> Result<Handle<SubModel>> {
        let mut found: Option<Handle<SubModel>> = None;
        for h in self {
            if h.read().as_kind().as_constraint().is_some() {
                if found.is_some() {
                    return Err(PyrucastError::Message(
                        "constraint_rhs: model holds several constraint sub-models; call it \
                         on a single-constraint model (e.g. the `dirichlet` / `mpc` object)"
                            .into(),
                    ));
                }
                found = Some(h.clone());
            }
        }
        found.ok_or_else(|| {
            PyrucastError::Message("constraint_rhs: model holds no constraint sub-model".into())
        })
    }

    /// Primal variable names — union over all sub-models, first-seen order.
    /// These are the **column labels** of the assembled matrices and the
    /// component names of the solution `SubNodeField`.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # use pyrucast::ops::model;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// // L'union des primales de tous les sous-modèles, dédupliquée.
    /// let m = model::heat_conduction(&fes)?
    ///     .union(&model::elasticity(&fes, Kinematics::PlaneStress)?)?;
    /// assert_eq!(m.primal_vars(),
    ///            vec!["T".to_string(), "u_x".to_string(), "u_y".to_string()]);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn primal_vars(&self) -> Vec<String> {
        let mut all: Vec<String> = Vec::new();
        for h in self {
            all.extend(h.read().primal_vars());
        }
        union_names(all)
    }

    /// Dual variable names — union over all sub-models, first-seen order.
    /// These are the **row labels** of the assembled matrices and the
    /// component names of the load `SubNodeField`.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # use pyrucast::ops::model;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// let m = model::heat_conduction(&fes)?
    ///     .union(&model::elasticity(&fes, Kinematics::PlaneStress)?)?;
    /// assert_eq!(m.dual_vars(),
    ///            vec!["q".to_string(), "f_x".to_string(), "f_y".to_string()]);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn dual_vars(&self) -> Vec<String> {
        let mut all: Vec<String> = Vec::new();
        for h in self {
            all.extend(h.read().dual_vars());
        }
        union_names(all)
    }

    /// Rebuild the [`FiniteElementSpace`] this model integrates on: the
    /// behaviour subspace of each domain sub-model (constraints, which have
    /// none, are skipped), in order — **one subspace per domain sub-model**, a
    /// 1-to-1 correspondence (no deduplication). Subspace handles are **shared**,
    /// not copied. This is the exact inverse of the per-subspace operators of
    /// [`crate::ops::model`] (`model::elasticity(fes)` and friends build one
    /// sub-model per subspace).
    /// Errors if the model has no domain sub-model (nothing to integrate on).
    /// Combined with [`FiniteElementSpace::mesh`], lets a caller recover the FE
    /// space (and mesh) from the model alone; a single sub-model's own subspace
    /// is [`SubModel::behavior_fespace`].
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # use pyrucast::ops::model;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// // L'espace EF est **déduit** du modèle : c'est ce qui permet aux
    /// // opérateurs d'assemblage de ne recevoir que le modèle.
    /// let m = model::heat_conduction(&fes)?;
    /// assert_eq!(m.fespace()?.len(), fes.len());
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn fespace(&self) -> Result<FiniteElementSpace> {
        let mut fes = FiniteElementSpace::empty();
        for h in self {
            if let Some(sub) = h.read().behavior_fespace() {
                fes.add_sub(sub)?;
            }
        }
        if fes.is_empty() {
            return Err(PyrucastError::Message(
                "Model::fespace: model has no domain sub-model to integrate on".into(),
            ));
        }
        Ok(fes)
    }

    /// A fresh [`Model`] holding only the sub-models **whose nature set contains**
    /// the given [`Physics`] (`model.filter(Physics::Mechanical)` → every
    /// sub-model that is at least mechanical, including a coupled one).
    ///
    /// Sub-model order is preserved and the handles are **shared** (refcount
    /// bump, no deep copy) via [`Aggregate::subset`];
    /// the result may be empty. The matrix-side counterpart is
    /// [`Matrix::filter`](crate::containers::matrix::Matrix::filter).
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # use pyrucast::ops::model;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// let m = model::heat_conduction(&fes)?
    ///     .union(&model::elasticity(&fes, Kinematics::PlaneStress)?)?;
    /// // Extraire une physique du modèle multi-physique — les sous-modèles
    /// // sont **partagés**, pas copiés.
    /// assert_eq!(m.filter(Physics::Thermal)?.primal_vars(), vec!["T".to_string()]);
    /// assert!(m.filter(Physics::Diffusion)?.is_empty());
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn filter(&self, physics: Physics) -> Result<Model> {
        let mut indices: Vec<usize> = Vec::new();
        for (i, h) in self.iter().enumerate() {
            if h.read().physics().contains(&physics) {
                indices.push(i);
            }
        }
        self.subset(indices)
    }
}

// ─── Helpers ───────────────────────────────────────────────────────────────

fn union_names<I: IntoIterator<Item = String>>(iter: I) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    for name in iter {
        if !out.contains(&name) {
            out.push(name);
        }
    }
    out
}

// ─── Unit tests ────────────────────────────────────────────────────────────

// ─── Archive ────────────────────────────────────────────────────────────────

impl crate::archive::Archivable for SubModel {
    const TAG: &'static str = "SubModel";
}

impl crate::archive::Archivable for Model {
    const TAG: &'static str = "Model";
}

#[cfg(test)]
mod tests {

    /// A one-cell conduction model on `coords`, to be the target a constraint
    /// names. A Dirichlet reads its dual and checks its variable there.
    #[cfg(test)]
    fn target_conduction(coords: &Handle<Coords>, a: &Node) -> Model {
        let b = Node::create_in(coords.clone(), &[1.0]).unwrap();
        let mut sm = SubMesh::new(coords.clone(), crate::atoms::ElementType::SEG2);
        sm.add_cell(&[a.id(), b.id()]).unwrap();
        let fes = crate::containers::finite_element_space::FiniteElementSpace::lagrange1(
            &Mesh::from_submesh(sm),
        )
        .unwrap();
        crate::ops::model::heat_conduction(&fes).unwrap()
    }
    use super::*;
    use crate::aggregate::Aggregate;
    use crate::atoms::ElementType;
    use crate::atoms::Node;
    use crate::containers::element_field::ElementField;
    use crate::containers::field::SubField;
    use crate::containers::finite_element_space::FiniteElementSpace;
    use crate::containers::mesh::Mesh;
    use crate::containers::mesh::SubMesh;
    use crate::coords::Coords;
    use crate::handle::Handle;
    use crate::models::owned_components;
    use crate::ops::model;

    /// Returns `(coords, a_id, b_id, model, materials)`.
    fn build_seg2_heat_model(
        length: f64,
        k: f64,
        dirichlet_at_left: bool,
    ) -> (Handle<Coords>, NodeId, NodeId, Model, ElementField) {
        let coords = Handle::new(Coords::new(1).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[length]).unwrap();
        let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
        mesh.add_cell(&[a.id(), b.id()]).unwrap();
        let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
        let sub = fes.get(0).unwrap();

        let mut mat = SubElementField::new(sub.clone(), vec!["k".into()]).unwrap();
        mat.set_uniform("k", k).unwrap();
        let mut materials = ElementField::empty();
        materials.add_sub(Handle::new(mat)).unwrap();

        let mut model = Model::empty();
        model
            .add_sub(Handle::new(SubModel::heat_conduction(sub).unwrap()))
            .unwrap();
        if dirichlet_at_left {
            let imposed =
                Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&a)).unwrap());
            let multiplier = crate::ops::mesh::barycenter(&imposed).unwrap();
            model
                .add_sub(Handle::new(
                    SubModel::dirichlet(&model, "T", &imposed, &multiplier, Default::default())
                        .unwrap(),
                ))
                .unwrap();
        }
        (coords, a.id(), b.id(), model, materials)
    }

    #[test]
    fn primal_dual_vars_for_heat_conduction_alone() {
        let (_cfg, _, _, model, _mat) = build_seg2_heat_model(1.0, 1.0, false);
        assert_eq!(model.primal_vars(), vec!["T".to_string()]);
        assert_eq!(model.dual_vars(), vec!["q".to_string()]);
    }

    #[test]
    fn primal_dual_vars_include_lagrange_after_dirichlet() {
        let (_cfg, _, _, model, _mat) = build_seg2_heat_model(1.0, 1.0, true);
        assert_eq!(
            model.primal_vars(),
            vec!["T".to_string(), "lambda_T".to_string()]
        );
        // Dual side: "q" from heat conduction + "imposed_T" (the Dirichlet
        // dual — a distinct name, no longer colliding with the primal "T").
        assert_eq!(
            model.dual_vars(),
            vec!["q".to_string(), "imposed_T".to_string()]
        );
    }

    #[test]
    fn physics_nature_per_submodel() {
        // Heat conduction (Thermal) + a Dirichlet constraint (Constraint).
        let (_cfg, _, _, model, _mat) = build_seg2_heat_model(1.0, 1.0, true);
        let natures: Vec<Vec<Physics>> =
            model.iter().map(|h| h.read().physics().to_vec()).collect();
        assert_eq!(
            natures,
            vec![vec![Physics::Thermal], vec![Physics::Constraint]]
        );
    }

    #[test]
    fn filter_selects_submodels_by_physics() {
        let (_cfg, _, _, model, _mat) = build_seg2_heat_model(1.0, 1.0, true);
        assert_eq!(model.len(), 2);

        let thermal = model.filter(Physics::Thermal).unwrap();
        assert_eq!(thermal.len(), 1);
        assert_eq!(
            thermal.get(0).unwrap().read().physics(),
            &[Physics::Thermal]
        );

        let constraint = model.filter(Physics::Constraint).unwrap();
        assert_eq!(constraint.len(), 1);
        assert_eq!(
            constraint.get(0).unwrap().read().physics(),
            &[Physics::Constraint]
        );

        // A nature no sub-model has yields an empty model.
        let mechanical = model.filter(Physics::Mechanical).unwrap();
        assert_eq!(mechanical.len(), 0);
    }

    #[test]
    fn assembled_blocks_carry_physics_and_matrix_filters() {
        // Heat conduction (one computed block) + Dirichlet (a literal C/Cᵀ pair).
        let (_cfg, _, _, model, materials) = build_seg2_heat_model(1.0, 1.0, true);
        let k = crate::ops::matrix::stiffness(&model, &materials).unwrap();

        // Every assembled block is tagged (non-empty), computed and literal alike.
        for h in &k {
            assert!(!h.read().physics().is_empty(), "assembled block is tagged");
        }
        // The matrix as a whole reports both natures present.
        let present = k.physics();
        assert!(present.contains(&Physics::Thermal));
        assert!(present.contains(&Physics::Constraint));

        // The constraint filter keeps only the Dirichlet C/Cᵀ pair.
        let constraint = k.filter(Physics::Constraint).unwrap();
        assert_eq!(constraint.len(), 2);
        for h in &constraint {
            assert_eq!(h.read().physics(), &[Physics::Constraint]);
        }

        // The thermal filter keeps only the heat-conduction block.
        let thermal = k.filter(Physics::Thermal).unwrap();
        assert_eq!(thermal.len(), 1);
    }

    /// Heat conduction on `[0, L]` with one SEG2 of length L and k = 1:
    /// `K_local = (k/L) [[1, -1], [-1, 1]]` (analytical, see Hughes 1.4).
    #[test]
    fn heat_conduction_assembles_analytical_seg2_stiffness() {
        let length = 2.0;
        let k_val = 1.5;
        let (_cfg, a_id, b_id, model, materials) = build_seg2_heat_model(length, k_val, false);
        let k = crate::ops::matrix::stiffness(&model, &materials).unwrap();

        assert_eq!(k.n_rows().unwrap(), 2);
        assert_eq!(k.n_cols().unwrap(), 2);
        let expected = k_val / length;
        let tol = 1e-12;
        assert!((k.get(a_id, "q", a_id, "T") - expected).abs() < tol);
        assert!((k.get(a_id, "q", b_id, "T") + expected).abs() < tol);
        assert!((k.get(b_id, "q", a_id, "T") + expected).abs() < tol);
        assert!((k.get(b_id, "q", b_id, "T") - expected).abs() < tol);
    }

    /// Two SEG2 elements sharing the middle node form the classic
    /// tridiagonal `(1, -2, 1)` pattern after assembly.
    #[test]
    fn two_seg2_assembly_is_tridiagonal() {
        let coords = Handle::new(Coords::new(1).unwrap());
        let n0 = Node::create_in(coords.clone(), &[0.0]).unwrap();
        let n1 = Node::create_in(coords.clone(), &[1.0]).unwrap();
        let n2 = Node::create_in(coords.clone(), &[2.0]).unwrap();
        let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
        mesh.add_cell(&[n0.id(), n1.id()]).unwrap();
        mesh.add_cell(&[n1.id(), n2.id()]).unwrap();
        let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
        let sub = fes.get(0).unwrap();
        let mut mat = SubElementField::new(sub.clone(), vec!["k".into()]).unwrap();
        mat.set_uniform("k", 1.0).unwrap();
        let mut materials = ElementField::empty();
        materials.add_sub(Handle::new(mat)).unwrap();

        let mut model = Model::empty();
        model
            .add_sub(Handle::new(SubModel::heat_conduction(sub).unwrap()))
            .unwrap();
        let k = crate::ops::matrix::stiffness(&model, &materials).unwrap();
        assert_eq!(k.n_rows().unwrap(), 3);
        assert_eq!(k.n_cols().unwrap(), 3);

        let v = |i: NodeId, j: NodeId| k.get(i, "q", j, "T");
        let tol = 1e-12;
        // h = 1 ⇒ K_global = [[1, -1, 0], [-1, 2, -1], [0, -1, 1]].
        assert!((v(n0.id(), n0.id()) - 1.0).abs() < tol);
        assert!((v(n0.id(), n1.id()) + 1.0).abs() < tol);
        assert!((v(n0.id(), n2.id())).abs() < tol);
        assert!((v(n1.id(), n0.id()) + 1.0).abs() < tol);
        assert!((v(n1.id(), n1.id()) - 2.0).abs() < tol);
        assert!((v(n1.id(), n2.id()) + 1.0).abs() < tol);
        assert!((v(n2.id(), n0.id())).abs() < tol);
        assert!((v(n2.id(), n1.id()) + 1.0).abs() < tol);
        assert!((v(n2.id(), n2.id()) - 1.0).abs() < tol);
    }

    /// Dirichlet on the left node creates a multiplier node and writes
    /// both `C` and `Cᵀ` entries (each value 1.0).
    #[test]
    fn dirichlet_adds_one_multiplier_node_and_two_block_entries() {
        let (coords, a_id, _b_id, model, materials) = build_seg2_heat_model(1.0, 1.0, true);

        // The Coords grew by one node (the multiplier).
        let n_nodes = coords.read().node_count();
        assert_eq!(n_nodes, 3);

        let k = crate::ops::matrix::stiffness(&model, &materials).unwrap();
        // 2 real "q" rows + 1 multiplier "T" row = 3 rows.
        // 2 real "T" cols + 1 multiplier "lambda_T" col = 3 cols.
        assert_eq!(k.n_rows().unwrap(), 3);
        assert_eq!(k.n_cols().unwrap(), 3);

        // Find the multiplier node id: the only NodeId that appears in
        // a row labelled "imposed_T" of K.
        let row_dofs = k.row_dofs().unwrap();
        let mult = row_dofs
            .iter()
            .find(|(_, name)| name == "imposed_T")
            .expect("multiplier row missing")
            .0;

        // C entry: (mult, "imposed_T") × (a_id, "T") = 1
        assert_eq!(k.get(mult, "imposed_T", a_id, "T"), 1.0);
        // Cᵀ entry: (a_id, "q") × (mult, "lambda_T") = 1
        assert_eq!(k.get(a_id, "q", mult, "lambda_T"), 1.0);
        // Ensure lambda_T appears as a column.
        let col_dofs = k.col_dofs().unwrap();
        let lambda_col_present = col_dofs
            .iter()
            .any(|(n, name)| name == "lambda_T" && *n == mult);
        assert!(lambda_col_present);
    }

    /// The multiplier nodes (supplied by the user via `multiplier_mesh`) stay
    /// alive as long as **either** the user's mesh **or** the sub-model holds
    /// their submesh; once both are gone the node is released and collectable.
    /// The sub-model creates no node and never mutates the Coords.
    #[test]
    fn multiplier_nodes_live_with_their_mesh() {
        let coords = Handle::new(Coords::new(1).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0]).unwrap();

        let imposed =
            Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&a)).unwrap());
        let multiplier = crate::ops::mesh::barycenter(&imposed).unwrap();
        let cible = target_conduction(&coords, &a);
        // The multiplier node is owned by the multiplier submesh (refcount 1;
        // the transient Node below is dropped at the end of the statement).
        let mult_id = multiplier.node(0, 0, 0).unwrap().id();
        assert_eq!(coords.read().refcount(mult_id), 1);
        let sub =
            SubModel::dirichlet(&cible, "T", &imposed, &multiplier, Default::default()).unwrap();
        // Sharing the submesh handles does not touch node refcounts.
        assert_eq!(coords.read().refcount(mult_id), 1);
        assert_eq!(sub.multiplier_nodes(), vec![mult_id]);

        // Drop the user's multiplier mesh: the sub-model still holds the
        // submesh, so the node lives on.
        drop(multiplier);
        assert_eq!(coords.read().refcount(mult_id), 1);

        // Drop the sub-model too: the last holder of the multiplier submesh is
        // gone ⇒ the node is released and collectable.
        drop(sub);
        assert_eq!(coords.read().refcount(mult_id), 0);
        assert_eq!(coords.write().gc(), 1);
    }

    #[test]
    fn dirichlet_empty_imposed_mesh_rejected() {
        let coords = Handle::new(Coords::new(1).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
        let cible = target_conduction(&coords, &a);
        let empty = Mesh::empty();
        assert!(SubModel::dirichlet(&cible, "T", &empty, &empty, Default::default()).is_err());
    }

    #[test]
    fn heat_conduction_errors_on_missing_k_component() {
        // Material has only "rho_cp", not "k": stiffness assembly must fail.
        let coords = Handle::new(Coords::new(1).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[1.0]).unwrap();
        let mut mesh = Mesh::from_submesh(SubMesh::new(coords, ElementType::SEG2));
        mesh.add_cell(&[a.id(), b.id()]).unwrap();
        let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
        let sub = fes.get(0).unwrap();
        let mat = SubElementField::new(sub.clone(), vec!["rho_cp".into()]).unwrap();
        let mut materials = ElementField::empty();
        materials.add_sub(Handle::new(mat)).unwrap();
        let mut model = Model::empty();
        model
            .add_sub(Handle::new(SubModel::heat_conduction(sub).unwrap()))
            .unwrap();
        assert!(crate::ops::matrix::stiffness(&model, &materials).is_err());
    }

    #[test]
    fn empty_model_has_no_vars_and_empty_mass() {
        let model = Model::empty();
        assert_eq!(model.primal_vars(), Vec::<String>::new());
        assert_eq!(model.dual_vars(), Vec::<String>::new());
        let m = crate::ops::matrix::mass(&model, &ElementField::empty()).unwrap();
        assert_eq!(m.n_rows().unwrap(), 0);
        assert_eq!(m.n_cols().unwrap(), 0);
    }

    /// Parent-level `model::heat_conduction(&fes)` builds one sub-model per
    /// subspace and matches the hand-rolled `SubModel` + `add_sub` path, and
    /// `union` composes it with a Dirichlet `Model`.
    #[test]
    fn parent_operators_span_subspaces_and_compose() {
        let coords = Handle::new(Coords::new(1).unwrap());
        let n0 = Node::create_in(coords.clone(), &[0.0]).unwrap();
        let n1 = Node::create_in(coords.clone(), &[1.0]).unwrap();
        let n2 = Node::create_in(coords.clone(), &[2.0]).unwrap();

        // Two SEG2 zones, one SubMesh each → fes with two subspaces.
        let mut mesh = Mesh::empty();
        let sm_a = {
            let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
            sm.add_cell(&[n0.id(), n1.id()]).unwrap();
            Handle::new(sm)
        };
        let sm_b = {
            let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
            sm.add_cell(&[n1.id(), n2.id()]).unwrap();
            Handle::new(sm)
        };
        mesh.add_sub(sm_a).unwrap();
        mesh.add_sub(sm_b).unwrap();
        let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();

        // One HeatConduction sub-model per subspace.
        let hc = model::heat_conduction(&fes).unwrap();
        assert_eq!(hc.len(), 2);
        assert_eq!(hc.primal_vars(), vec!["T".to_string()]);
        assert_eq!(hc.dual_vars(), vec!["q".to_string()]);

        // Compose with a Dirichlet model via `union` (Python `|`).
        let imp = Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&n0)).unwrap());
        let mlt = crate::ops::mesh::barycenter(&imp).unwrap();
        let dir = model::dirichlet(&hc, "T", &imp, &mlt, Default::default()).unwrap();
        assert_eq!(dir.len(), 1);
        let full = hc.union(&dir).unwrap();
        assert_eq!(full.len(), 3);
        assert_eq!(
            full.primal_vars(),
            vec!["T".to_string(), "lambda_T".to_string()]
        );
    }

    /// Single-subspace `fes` → unit `Model` (the common case).
    #[test]
    fn parent_heat_conduction_unit_case() {
        let coords = Handle::new(Coords::new(1).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[1.0]).unwrap();
        let mut mesh = Mesh::from_submesh(SubMesh::new(coords, ElementType::SEG2));
        mesh.add_cell(&[a.id(), b.id()]).unwrap();
        let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
        let model = model::heat_conduction(&fes).unwrap();
        assert_eq!(model.len(), 1);
    }

    #[test]
    fn debug_and_display() {
        let (_cfg, _, _, model, _mat) = build_seg2_heat_model(1.0, 1.0, true);
        let d = format!("{:?}", model);
        assert!(d.contains("Model"));
        let s = format!("{}", model);
        assert!(s.contains("Model"));
        assert!(s.contains("2 sub-model"));
    }

    /// Two SEG2 zones with **different** conductivities, each carried by
    /// its own sub-model and its own SubElementField in a shared
    /// ElementField. The assembler must pick the right material per
    /// SubFiniteElementSpace.
    #[test]
    fn assemble_picks_per_zone_material() {
        let coords = Handle::new(Coords::new(1).unwrap());
        let n0 = Node::create_in(coords.clone(), &[0.0]).unwrap();
        let n1 = Node::create_in(coords.clone(), &[1.0]).unwrap();
        let n2 = Node::create_in(coords.clone(), &[2.0]).unwrap();

        // Zone A: SEG2 on [0, 1]. Zone B: SEG2 on [1, 2]. Each as its own
        // SubMesh inside one Mesh.
        let mut mesh = Mesh::empty();
        let sm_a = {
            let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
            sm.add_cell(&[n0.id(), n1.id()]).unwrap();
            Handle::new(sm)
        };
        let sm_b = {
            let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
            sm.add_cell(&[n1.id(), n2.id()]).unwrap();
            Handle::new(sm)
        };
        mesh.add_sub(sm_a).unwrap();
        mesh.add_sub(sm_b).unwrap();

        let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
        let sub_a = fes.get(0).unwrap();
        let sub_b = fes.get(1).unwrap();

        // Different conductivities on each zone.
        let k_a = 1.0;
        let k_b = 4.0;
        let mut mat_a = SubElementField::new(sub_a.clone(), vec!["k".into()]).unwrap();
        mat_a.set_uniform("k", k_a).unwrap();
        let mut mat_b = SubElementField::new(sub_b.clone(), vec!["k".into()]).unwrap();
        mat_b.set_uniform("k", k_b).unwrap();
        let mut materials = ElementField::empty();
        materials.add_sub(Handle::new(mat_a)).unwrap();
        materials.add_sub(Handle::new(mat_b)).unwrap();

        let mut model = Model::empty();
        model
            .add_sub(Handle::new(SubModel::heat_conduction(sub_a).unwrap()))
            .unwrap();
        model
            .add_sub(Handle::new(SubModel::heat_conduction(sub_b).unwrap()))
            .unwrap();

        let k = crate::ops::matrix::stiffness(&model, &materials).unwrap();

        // For a SEG2 of length h = 1 and conductivity k:
        // K_local = (k / h) [[1, -1], [-1, 1]] = k [[1, -1], [-1, 1]].
        let tol = 1e-12;
        let v = |i: NodeId, j: NodeId| k.get(i, "q", j, "T");
        // Diagonal at n0 = k_a only.
        assert!((v(n0.id(), n0.id()) - k_a).abs() < tol);
        // Diagonal at n1 = k_a + k_b (shared node).
        assert!((v(n1.id(), n1.id()) - (k_a + k_b)).abs() < tol);
        // Diagonal at n2 = k_b only.
        assert!((v(n2.id(), n2.id()) - k_b).abs() < tol);
        // Off-diagonals.
        assert!((v(n0.id(), n1.id()) + k_a).abs() < tol);
        assert!((v(n1.id(), n2.id()) + k_b).abs() < tol);
    }

    #[test]
    fn physics_declares_material_components() {
        let coords = Handle::new(Coords::new(1).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[1.0]).unwrap();
        let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
        mesh.add_cell(&[a.id(), b.id()]).unwrap();
        let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
        let sub = fes.get(0).unwrap();
        let hc = SubModel::heat_conduction(sub).unwrap();
        assert_eq!(hc.material_components(), Some(owned_components(&["k"])));

        let imposed =
            Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&a)).unwrap());
        let multiplier = crate::ops::mesh::barycenter(&imposed).unwrap();
        let cible = target_conduction(&coords, &a);
        let dir =
            SubModel::dirichlet(&cible, "T", &imposed, &multiplier, Default::default()).unwrap();
        assert!(dir.material_components().is_none());
    }

    /// `crate::ops::matrix::stiffness` must fail with a clear error when no
    /// SubElementField matches a HeatConduction's FE subspace.
    #[test]
    fn assemble_errors_when_no_material_matches_fespace() {
        let coords = Handle::new(Coords::new(1).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[1.0]).unwrap();
        let mut mesh = Mesh::from_submesh(SubMesh::new(coords, ElementType::SEG2));
        mesh.add_cell(&[a.id(), b.id()]).unwrap();
        let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
        let sub = fes.get(0).unwrap();

        // Empty ElementField — no SubElementField matches anything.
        let materials = ElementField::empty();
        let mut model = Model::empty();
        model
            .add_sub(Handle::new(SubModel::heat_conduction(sub).unwrap()))
            .unwrap();
        let err = crate::ops::matrix::stiffness(&model, &materials).unwrap_err();
        assert!(format!("{}", err).contains("no SubElementField"));
    }

    // ── constraint_rhs (mise-en-donnée helper) ──────────────────────────────

    /// Dirichlet: keying by the constrained node writes `g` at the multiplier
    /// node, on the constraint's dual component (`imposed_T`), and the field
    /// lives on the multiplier — not the constrained — node.
    #[test]
    fn constraint_rhs_dirichlet_writes_g_at_multiplier() {
        let coords = Handle::new(Coords::new(1).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
        let imposed =
            Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&a)).unwrap());
        let multiplier = crate::ops::mesh::barycenter(&imposed).unwrap();
        let cible = target_conduction(&coords, &a);
        let dirichlet =
            model::dirichlet(&cible, "T", &imposed, &multiplier, Default::default()).unwrap();

        let rhs = dirichlet.constraint_rhs(&[(a.id(), 3.0)]).unwrap();
        let mult_id = multiplier.node(0, 0, 0).unwrap().id();
        assert_eq!(rhs.value(mult_id, "imposed_T").unwrap(), 3.0);
        // Written on the multiplier node, not the constrained one.
        assert!(rhs.value(a.id(), "imposed_T").is_err());
    }

    /// MPC: a relation is keyed by *any* of its term nodes, both resolving to
    /// the same multiplier node and value. Non-cited relations default to 0.
    #[test]
    fn constraint_rhs_mpc_keyed_by_any_term_node() {
        let coords = Handle::new(Coords::new(1).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
        let b = Node::create_in(coords, &[1.0]).unwrap();
        let mesh_a =
            Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&a)).unwrap());
        let mesh_b =
            Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&b)).unwrap());
        let mult = crate::ops::mesh::barycenter(&mesh_b).unwrap();
        let cible = target_conduction(&a.coords(), &a);
        let terms = vec![
            crate::models::mpc::MpcTerm::new(&cible, &mesh_b, "T", 1.0).unwrap(),
            crate::models::mpc::MpcTerm::new(&cible, &mesh_a, "T", -1.0).unwrap(),
        ];
        let model = model::mpc(terms, &mult, Default::default()).unwrap();
        let mult_id = mult.node(0, 0, 0).unwrap().id();

        let rhs = model.constraint_rhs(&[(b.id(), 2.5)]).unwrap();
        assert_eq!(rhs.value(mult_id, "mpc_rhs").unwrap(), 2.5);
        // The other term node keys the same relation → same field.
        let rhs2 = model.constraint_rhs(&[(a.id(), 2.5)]).unwrap();
        assert_eq!(rhs2.value(mult_id, "mpc_rhs").unwrap(), 2.5);
    }

    /// A model without any constraint sub-model rejects the call.
    #[test]
    fn constraint_rhs_errors_without_constraint() {
        let (_c, _a, _b, model, _m) = build_seg2_heat_model(1.0, 1.0, false);
        assert!(model.constraint_rhs(&[]).is_err());
    }

    /// A node keying two *distinct* relations (here node `a`, a term of both) is
    /// ambiguous and rejected; a node keying a single relation still resolves.
    #[test]
    fn constraint_rhs_rejects_node_keying_several_relations() {
        let coords = Handle::new(Coords::new(1).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[1.0]).unwrap();
        let c = Node::create_in(coords.clone(), &[2.0]).unwrap();
        let m0 = Node::create_in(coords.clone(), &[0.5]).unwrap();
        let m1 = Node::create_in(coords.clone(), &[1.5]).unwrap();

        // Term 1 uses `a` in *both* relations; term 2 uses `b` then `c`.
        let mut t1 = SubMesh::new(coords.clone(), ElementType::POI1);
        t1.add_cell(&[a.id()]).unwrap();
        t1.add_cell(&[a.id()]).unwrap();
        let t1_mesh = Mesh::from_submesh(t1);
        let mut t2 = SubMesh::new(coords.clone(), ElementType::POI1);
        t2.add_cell(&[b.id()]).unwrap();
        t2.add_cell(&[c.id()]).unwrap();
        let t2_mesh = Mesh::from_submesh(t2);
        let mut mm = SubMesh::new(coords, ElementType::POI1);
        mm.add_cell(&[m0.id()]).unwrap();
        mm.add_cell(&[m1.id()]).unwrap();
        let mult = Mesh::from_submesh(mm);

        let cible = target_conduction(&a.coords(), &a);
        let terms = vec![
            crate::models::mpc::MpcTerm::new(&cible, &t1_mesh, "T", 1.0).unwrap(),
            crate::models::mpc::MpcTerm::new(&cible, &t2_mesh, "T", -1.0).unwrap(),
        ];
        let model = model::mpc(terms, &mult, Default::default()).unwrap();

        // `a` keys both relations → ambiguous.
        assert!(model.constraint_rhs(&[(a.id(), 1.0)]).is_err());
        // `b` keys only the first relation → resolves to m0.
        let rhs = model.constraint_rhs(&[(b.id(), 1.0)]).unwrap();
        assert_eq!(rhs.value(m0.id(), "mpc_rhs").unwrap(), 1.0);
        assert_eq!(rhs.value(m1.id(), "mpc_rhs").unwrap(), 0.0);

        // Keying by *index* sidesteps the ambiguity: relation 1 → m1.
        let by_idx = model.constraint_rhs_by_index(&[(1, 4.0)]).unwrap();
        assert_eq!(by_idx.value(m1.id(), "mpc_rhs").unwrap(), 4.0);
        assert_eq!(by_idx.value(m0.id(), "mpc_rhs").unwrap(), 0.0);
    }

    /// `constraint_rhs_by_index` writes `g` at the relation's multiplier node and
    /// rejects an out-of-range index.
    #[test]
    fn constraint_rhs_by_index_writes_and_bounds_checks() {
        let coords = Handle::new(Coords::new(1).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
        let imposed =
            Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&a)).unwrap());
        let multiplier = crate::ops::mesh::barycenter(&imposed).unwrap();
        let cible = target_conduction(&coords, &a);
        let dirichlet =
            model::dirichlet(&cible, "T", &imposed, &multiplier, Default::default()).unwrap();

        let mult_id = multiplier.node(0, 0, 0).unwrap().id();
        let rhs = dirichlet.constraint_rhs_by_index(&[(0, 2.0)]).unwrap();
        assert_eq!(rhs.value(mult_id, "imposed_T").unwrap(), 2.0);
        // Only one relation (index 0) → index 1 is out of range.
        assert!(dirichlet.constraint_rhs_by_index(&[(1, 2.0)]).is_err());
    }
}