pyrucast 0.11.0

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
//! Per-physics implementations of [`crate::containers::model::SubModel`]
//! variants.
//!
//! Each file here owns the **specifics** of one physics: a struct holding
//! its supports (FE spaces, materials, node sets) plus an [`impl SubModelKind`]
//! carrying *all* of its behaviour — variable names, material contract,
//! local assembly, and rendering. The
//! [`crate::containers::model::SubModel`] enum exists **only** for storage
//! and serialization; it dispatches every call through
//! [`SubModel::as_kind`](crate::containers::model::SubModel::as_kind)
//! so no generic code (the assembler, `Dump`, …) ever needs a per-variant
//! `match`.
//!
//! # Adding a new physics
//!
//! 1. add `models/<name>.rs` with a struct + `impl SubModelKind` (and a
//!    `new(...)` constructor doing any build-time work);
//! 2. add one variant to [`crate::containers::model::SubModel`];
//! 3. add one arm to
//!    [`SubModel::as_kind`](crate::containers::model::SubModel::as_kind);
//! 4. declare the parent-level operator with
//!    [`physics_operator!`](crate::physics_operator) **in the same file**: it
//!    emits the Rust operator *and* its `#[pyfunction]`, so nothing is written
//!    by hand under `py/`;
//! 5. raccord: `pub use` in [`crate::ops::model`], and the registration in the
//!    (flat) `#[pymodule]` of `lib.rs`.
//!
//! Everything else is generic. See the book chapter *"Ajouter une physique"*
//! for the full walkthrough.

use crate::aggregate::Aggregate;
use crate::atoms::NodeId;
use crate::containers::element_field::SubElementField;
use crate::containers::field::SubField;
use crate::containers::finite_element_space::SubFiniteElementSpace;
use crate::containers::matrix::{hash_f64, hash_name, hash_nodes, mint_pair, Symmetry, FNV_SEED};
use crate::containers::matrix::{DofOrdering, SubMatrix};
use crate::containers::mesh::{Mesh, SubMesh};
use crate::containers::node_field::NodeField;
use crate::dump::DumpOptions;
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use crate::named::Named;
use serde::{Deserialize, Serialize};

pub mod beam;
pub mod bernoulli;
pub mod boundary_transfer;
pub mod contact;
pub mod continuum;
pub mod damage;
pub mod dirichlet;
pub mod elasticity;
pub mod embedded;
pub mod fick;
pub mod flux;
pub mod frame;
pub mod frame3d;
pub mod heat_conduction;
pub mod interface_transfer;
pub mod kernel;
pub mod mpc;
pub mod plasticity;
pub mod radiation;
pub mod shell;
pub mod symmetry;
pub mod tensor;
pub mod timoshenko;
pub mod transfer;
pub mod truss;

pub use kernel::CellGeom;

/// The kind of element matrix a physics contributes — the discriminant that
/// makes the whole assembly pipeline (recipe → scatter → per-kind pattern cache)
/// matrix-agnostic. One `assemble_*` entry point per variant
/// ([`crate::ops::matrix`]) drives the **same** machinery with a different
/// per-element kernel; a physics that has no term for a given kind contributes
/// nothing (its [`matrix_layout`](SubModelKind::matrix_layout) returns `None`).
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # 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::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
/// # 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 fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// // Four matrix kinds and **one single** machinery: the per-element kernel
/// // differs, everything else is shared. A physics with no term for a kind
/// // contributes nothing to it.
/// assert_eq!(MatrixKind::COUNT, 4);
/// assert_eq!(MatrixKind::Stiffness.index(), 0);
/// assert!(volume.as_kind().matrix_layout(MatrixKind::Stiffness).is_some());
/// // A constraint has no matrix layout: it goes through `contributions`, not
/// // through an element kernel.
/// assert!(appui.as_kind().matrix_layout(MatrixKind::Stiffness).is_none());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum MatrixKind {
    /// Stiffness / conductivity `K` — `∫ Bᵀ D B` (Cast3M `RIGI` / `COND`).
    #[default]
    Stiffness,
    /// Mass / capacity `M` — `∫ ρ Nᵀ N` (Cast3M `MASS` / `CAPA`).
    Mass,
    /// Geometric (initial-stress) stiffness `K_g` — `∫ Gᵀ σ̂ G` (Cast3M `KSIG`).
    Geometric,
    /// Consistent tangent `K_t` — `∫ Bᵀ D_alg B` (Cast3M `KTAN`).
    Tangent,
}

impl MatrixKind {
    /// Number of variants — the width of the per-kind pattern cache.
    ///
    /// ```
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # 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::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
    /// # 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 fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
    /// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
    /// // Four matrix kinds and **one single** machinery: the per-element kernel
    /// // differs, everything else is shared. A physics with no term for a kind
    /// // contributes nothing to it.
    /// assert_eq!(MatrixKind::COUNT, 4);
    /// assert_eq!(MatrixKind::Stiffness.index(), 0);
    /// assert!(volume.as_kind().matrix_layout(MatrixKind::Stiffness).is_some());
    /// // A constraint has no matrix layout: it goes through `contributions`, not
    /// // through an element kernel.
    /// assert!(appui.as_kind().matrix_layout(MatrixKind::Stiffness).is_none());
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub const COUNT: usize = 4;

    /// Dense index in `0..COUNT`, for indexing per-kind caches.
    ///
    /// ```
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # 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::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
    /// # 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 fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
    /// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
    /// // The index serves as the rank in the pattern cache, one per kind.
    /// assert!(MatrixKind::Stiffness.index() < MatrixKind::COUNT);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub const fn index(self) -> usize {
        self as usize
    }
}

/// How a physics obtains its consistent tangent — a property of the **law**,
/// declared once, not re-derived at every Gauss point.
///
/// Purely **informative**: nothing branches on it. The guard against paying for
/// a tangent is having to call [`crate::ops::matrix::tangent`] at all. What this
/// buys is that a caller can know the price *before* paying it — a Newton loop
/// facing a `Numerical` law may legitimately prefer the elastic stiffness as its
/// iteration operator.
///
/// ```
/// # use pyrucast::models::TangentSource;
/// # use pyrucast::models::plasticity::law::PlasticLaw;
/// // Only two laws have a closed form; the others derive the radial return by
/// // central differences — twelve return maps per Gauss point.
/// assert_eq!(PlasticLaw::Perfect.tangent_source(), TangentSource::Analytic);
/// assert_eq!(PlasticLaw::Gurson.tangent_source(), TangentSource::Numerical);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TangentSource {
    /// Closed form: a few dozen operations.
    Analytic,
    /// Central differences on the return map: **twelve return maps per Gauss
    /// point**.
    Numerical,
}

/// Structural declaration a volumetric physics gives so the **global**
/// assembler ([`crate::ops::matrix::stiffness`]) can build its stiffness
/// contribution as a *computed* [`SubMatrix`] — a recipe, no eagerly
/// materialised values — and scatter it straight into the global CSR.
///
/// Every field mirrors, one-for-one, what the physics'
/// [`build_stiffness_blocks`](SubModelKind::build_stiffness_blocks) would pass to
/// [`kernel::assemble_block`]. The
/// literal `build_stiffness_blocks` is **kept** alongside it as the bit-for-bit
/// equivalence reference. Volumetric blocks are square on a single support, so
/// one [`SubMesh`] gives both the row and column node sequence.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::containers::matrix::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::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
/// # 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 fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// // The **structural** declaration of a volumetric physics: enough to build
/// // a *computed* block and pour it straight into the global CSR. Each field
/// // mirrors one argument of `assemble_block`.
/// let l = volume.as_kind().matrix_layout(MatrixKind::Stiffness).unwrap();
/// assert_eq!(l.dual_vars, vec!["q".to_string()]);
/// assert_eq!(l.primal_vars, vec!["T".to_string()]);
/// // A standard Galerkin form is symmetric on its own.
/// assert_eq!(l.symmetry, Symmetry::Full);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub struct MatrixLayout {
    /// FE subspaces the element kernel integrates over. **Give a `Vec`**: a
    /// single subspace for a plain volumetric physics, or several — sharing one
    /// submesh, differing only by quadrature — for a multi-quadrature element
    /// (a shear-deformable beam, a shell). The primary (index 0) drives the cell
    /// loop and the DOF numbering; [`element_matrix`](Domain::element_matrix)
    /// receives one [`CellGeom`] per subspace, in this order.
    pub fespaces: Vec<Handle<SubFiniteElementSpace>>,
    /// POI1 sub-mesh giving the block's row **and** column node sequence.
    pub support: Handle<SubMesh>,
    /// Row variable names (dual).
    pub dual_vars: Vec<String>,
    /// Column variable names (primal).
    pub primal_vars: Vec<String>,
    /// `(node_local, var)` ↔ matrix-index ordering.
    pub ordering: DofOrdering,
    /// What share of the matrix's symmetry the block carries — **declared** by
    /// the physics, believed without verification. A standard Galerkin bilinear
    /// form is [`Symmetry::Full`]; see [`Symmetry`] for what the other shares
    /// mean and who may claim them.
    pub symmetry: Symmetry,
}

/// One stiffness contribution of a sub-model, as handed to the global
/// assembler ([`crate::ops::matrix::stiffness`]).
///
/// A sub-model declares *how* each of its blocks is produced without the
/// assembler needing to know its concrete type: it just iterates
/// [`SubModelKind::contributions`] and folds each variant in. This is the seam that
/// keeps `Dirichlet`, a volumetric physics, and (later) a coupling/contact
/// sub-model on one uniform path — the discriminant is the variant, not a
/// per-type `match` in the assembler.
///
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # 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::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
/// # 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 fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// # use pyrucast::models::Contribution;
/// // The discriminant that puts a constraint, a volumetric physics and a
/// // coupling on one single path: the variant decides, not a per-type
/// // `match` in the assembler.
/// let c = appui.as_kind().contributions(MatrixKind::Stiffness, None)?;
/// assert!(!c.is_empty());
/// // A support brings **literal** blocks; a volumetric physics, a computed
/// // recipe.
/// assert!(matches!(c[0], Contribution::Literal(_)));
/// assert!(matches!(
///     volume.as_kind().contributions(MatrixKind::Stiffness, None)?[0],
///     Contribution::Computed(_)));
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub enum Contribution {
    /// A block integrated on the fly and scattered straight into the global CSR
    /// (no values materialised): the fast path of every volumetric physics. The
    /// assembler resolves the material and wraps this
    /// [`MatrixLayout`] into a computed [`SubMatrix`].
    Computed(MatrixLayout),
    /// One-or-more blocks whose values the sub-model has already filled in
    /// (`Dirichlet`'s C / Cᵀ, MPC, …). Scattered by the literal path.
    Literal(Vec<SubMatrix>),
    /// An **off-diagonal** block coupling two distinct meshes — integrated on the
    /// fly like [`Computed`](Self::Computed), but with its rows on one mesh and
    /// its columns on another (an interface exchange law, `h(c₁ − c₂)`).
    ///
    /// Everything below this seam was already row/col-asymmetric —
    /// [`SubMatrix::computed`](crate::containers::matrix::SubMatrix::computed)
    /// takes both supports, and so do the scatter and the kernel drivers. Only
    /// [`MatrixLayout`] collapsed them into one field, which is why this is a
    /// separate layout rather than an extra field there: adding one would have
    /// touched every existing physics for a need none of them has.
    Coupling(CouplingLayout),
}

/// One sub-model's declaration of a term of the residual — the nodal twin of
/// [`Contribution`], and the same idea: a **recipe**, never an assembled
/// container. [`crate::ops::node_field::internal_forces()`] and
/// [`crate::ops::node_field::external_forces()`] consume it exactly as
/// [`crate::ops::matrix::assemble_kind`] consumes a `Contribution` — they
/// resolve what the term reads, run the machinery, and gather the result.
///
/// That split is what keeps the declaration total: a sub-model that resolves
/// nothing cannot fail, and the one `Result` of the whole path sits on the
/// operator, where a caller can act on it.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # 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::{ResidualContribution, SubModelKind};
/// # 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 fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let volume = SubModel::heat_conduction(zone, MaterialSymmetry::Isotropic).unwrap();
/// // A physics that integrates a law declares a computed recipe, on its own
/// // layout — never the field, which the operator will produce.
/// let declare = volume.as_kind().internal_force_contribution();
/// assert!(matches!(declare[..], [ResidualContribution::Computed(_)]));
/// ```
pub enum ResidualContribution {
    /// A term integrated on the fly and scattered to the nodes: the fast path
    /// of every physics whose term is an integral. The layout is the sub-model's
    /// own (its stiffness layout for `∫ Bᵀ σ`), and the per-cell kernel is
    /// [`SubModelKind::internal_force_element`].
    Computed(MatrixLayout),
    /// A field the sub-model has already filled in — a hand-made load. The twin
    /// of [`Contribution::Literal`].
    Literal(NodeField),
    /// The terms of a **constraint**: apply its [`Constraint::relations`] to the
    /// current solution. On the internal side that is the reaction `Cᵀ λ`,
    /// spread over the constrained nodes — term `k` carrying `aₖ·λ` into the
    /// dual row of its own variable — plus `C·u` on the constraint's own row.
    ///
    /// It is a variant rather than a `Literal` because the declaration is total:
    /// a sub-model that has not seen the solution cannot have filled a field
    /// with it.
    Relations,
}

/// Structural declaration of an **inter-mesh** block: rows integrated on one
/// mesh, columns on another, paired cell by cell.
///
/// The two sides must be **conforming** — same element type, same cell count,
/// cell `i` of one facing cell `i` of the other. That is checked when the block
/// is built, and reported rather than approximated: a non-matching interface is
/// a meshing problem, not something an assembler should paper over.
// ANCHOR: coupling_layout
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::containers::matrix::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::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
/// # 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 fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// # use pyrucast::containers::matrix::DofOrdering;
/// # use pyrucast::models::CouplingLayout;
/// // What an **interface** law describes: row *and* column subspaces, on
/// // two facing meshes, where a [`MatrixLayout`] holds on a single
/// // support. Conformity is checked when the block is built, and
/// // **reported** rather than approximated: an interface that does not
/// // match is a meshing problem.
/// let l = CouplingLayout {
///     fespaces: vec![zone.clone()],
///     col_fespaces: vec![zone.clone()],
///     row_support: zone.read().submesh().read().to_poi1()?,
///     col_support: zone.read().submesh().read().to_poi1()?,
///     dual_vars: vec!["q".into()],
///     primal_vars: vec!["T".into()],
///     ordering: DofOrdering::NodesThenVars,
///     // An inter-mesh block is never symmetric alone; a real exchange law
///     // declares its two off-diagonal blocks a `Half` pair instead.
///     symmetry: Symmetry::None,
/// };
/// assert_eq!(l.fespaces.len(), l.col_fespaces.len());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub struct CouplingLayout {
    /// FE subspaces carrying the **rows** (the primary drives the cell loop).
    pub fespaces: Vec<Handle<SubFiniteElementSpace>>,
    /// FE subspaces carrying the **columns**, on the facing mesh.
    pub col_fespaces: Vec<Handle<SubFiniteElementSpace>>,
    /// POI1 sub-mesh giving the block's row node sequence.
    pub row_support: Handle<SubMesh>,
    /// POI1 sub-mesh giving the block's column node sequence.
    pub col_support: Handle<SubMesh>,
    /// Row variable names (dual).
    pub dual_vars: Vec<String>,
    /// Column variable names (primal).
    pub primal_vars: Vec<String>,
    /// `(node_local, var)` ↔ matrix-index ordering.
    pub ordering: DofOrdering,
    /// What share of the matrix's symmetry the block carries. An inter-mesh
    /// block is never symmetric alone — its rows and columns live on facing
    /// meshes — so an exchange law declares its two off-diagonal blocks a
    /// [`Symmetry::Half`] pair, exactly as a constraint declares `C` and `Cᵀ`.
    pub symmetry: Symmetry,
}
// ANCHOR_END: coupling_layout

/// The **nature** of a physics — its coarse classification, orthogonal to the
/// `Domain` / `Constraint` capability axis. It answers "which field of physics"
/// where the capability seams answer "domain or constraint".
///
/// A physics declares a **set** of natures (usually one): a plain physics is
/// single-natured, a coupled physics (e.g. a future thermo-mechanical element)
/// spans several, and a block that belongs to none is left **untagged** (an empty
/// set — the "nothing" case for hand-built / other matrices). [`Other`](Self::Other)
/// is the explicit odd-one-out nature, for a block one *wants* classified as
/// "other" rather than merely untagged.
///
/// A single nature is fully determined by the
/// [`SubModel`](crate::containers::model::SubModel) variant, so
/// [`SubModelKind::physics`] returns a per-physics **constant** slice (like
/// [`label`](SubModelKind::label)) rather than a stored field. The set travels
/// with each assembled block onto the [`SubMatrix`], and feeds the
/// [`Model::filter`](crate::containers::model::Model::filter) /
/// [`Matrix::filter`](crate::containers::matrix::Matrix::filter) selectors
/// (which match by **containment**).
///
/// ```
/// # use pyrucast::models::Physics;
/// // A sub-model's nature travels with every assembled block: it is what
/// // `Model::filter` and `Matrix::filter` read.
/// assert_eq!(Physics::ALL.len(), 6);
/// // Diffusion and thermal are **distinct** despite their common Laplacian:
/// // a coupled problem must be able to select one without the other.
/// assert_ne!(Physics::Diffusion, Physics::Thermal);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Physics {
    /// Solid mechanics — elasticity, plasticity, damage, bars, beams, frames.
    Mechanical,
    /// Heat conduction (and future thermal physics).
    Thermal,
    /// A Lagrange constraint — Dirichlet, MPC, embedded, contact.
    Constraint,
    /// "Other / nothing" — a nature for a block that fits none of the above but is
    /// still explicitly classified (as opposed to simply untagged).
    Other,
    /// Mass transport — Fickian diffusion and its interface laws. Distinct from
    /// [`Thermal`](Self::Thermal) despite sharing the Laplacian: the variables
    /// are a concentration and a mass flux, not a temperature and a heat flux,
    /// and a coupled problem must be able to select one without the other.
    Diffusion,
    /// Radiative exchange. Carried **in addition to**
    /// [`Thermal`](Self::Thermal) by a radiation sub-model — so it stays part of
    /// a thermal assembly, while `filter("radiation")` isolates the non-linear
    /// boundary term on its own.
    Radiation,
}

impl Physics {
    /// The lowercase name of this nature (the inverse of
    /// [`from_name`](crate::named::Named::from_name)).
    ///
    /// ```
    /// # use pyrucast::models::Physics;
    /// # use pyrucast::named::Named;
    /// // Exact inverse of `from_name`, for the six natures.
    /// assert!(Physics::ALL.iter().all(|p| Physics::from_name(p.name()) == Some(*p)));
    /// ```
    pub fn name(self) -> &'static str {
        match self {
            Self::Mechanical => "mechanical",
            Self::Thermal => "thermal",
            Self::Constraint => "constraint",
            Self::Other => "other",
            Self::Diffusion => "diffusion",
            Self::Radiation => "radiation",
        }
    }

    /// Every nature, in declaration order — the single source for the tag list
    /// quoted in the `filter` error messages, so a new nature cannot be added
    /// without the messages following.
    ///
    /// ```
    /// # use pyrucast::models::Physics;
    /// // The single source of the list quoted by the `filter` messages: a
    /// // nature cannot be added without the messages following.
    /// assert!(Physics::ALL.contains(&Physics::Radiation));
    /// ```
    pub const ALL: [Physics; 6] = [
        Self::Mechanical,
        Self::Thermal,
        Self::Constraint,
        Self::Other,
        Self::Diffusion,
        Self::Radiation,
    ];
}

impl crate::named::Named for Physics {
    const LABEL: &'static str = "physics";
    const VALUES: &'static [Self] = &Self::ALL;

    fn name(self) -> &'static str {
        Physics::name(self)
    }
}

impl std::fmt::Display for Physics {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.name())
    }
}

/// The behaviour contract of one physics, co-located with its data struct.
///
/// Generic code calls these through
/// [`SubModel::as_kind`](crate::containers::model::SubModel::as_kind);
/// the [`SubModel`](crate::containers::model::SubModel) enum itself carries
/// no logic. Most methods have sensible defaults so a physics overrides
/// only what is specific to it (a plain domain physics typically implements
/// `primal_vars`, `dual_vars`, `as_domain` + the [`Domain`] capability,
/// `element_matrix`, `stiffness_layout`, `label` and `render`).
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # 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::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
/// # 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 fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// // The base contract, with defaults wherever possible: a physics writes
/// // only what is its own. **All** of the model layer goes through it,
/// // `as_kind` being the single `match`.
/// let k = volume.as_kind();
/// assert_eq!(k.primal_vars(), vec!["T".to_string()]);
/// assert!(k.as_domain().is_some());   // a volumetric physics
/// assert!(k.as_constraint().is_none());
/// // And the other way round for a support: it is a **compile-time** fact,
/// // not a run-time error.
/// assert!(appui.as_kind().as_domain().is_none());
/// assert!(appui.as_kind().as_constraint().is_some());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub trait SubModelKind: Sync {
    /// Primal variable names introduced by this physics (column labels).
    fn primal_vars(&self) -> Vec<String>;

    /// Dual variable names introduced by this physics (row labels).
    fn dual_vars(&self) -> Vec<String>;

    /// This physics' set of [`Physics`] natures — a per-variant **constant**
    /// slice, the classification counterpart of [`label`](Self::label). A plain
    /// physics returns a single-element slice; a coupled physics returns several.
    /// Required so every physics declares its nature(s) explicitly at its
    /// definition site. Matched by containment in the `filter` selectors.
    fn physics(&self) -> &'static [Physics];

    /// Borrow this sub-model as a [`Domain`] capability, or `None` (default) if
    /// it is not a domain physics (a constraint such as `Dirichlet`). A domain
    /// overrides this to return `Some(self)`. This is the seam the assembler,
    /// the material builders and [`crate::ops::element_field::behavior`] use — they never
    /// assume every sub-model reads material or integrates a behaviour.
    fn as_domain(&self) -> Option<&dyn Domain> {
        None
    }

    /// Borrow this sub-model as a [`Constraint`] capability, or `None`
    /// (default) if it imposes no Lagrange constraint (every plain volumetric
    /// physics). A constraint (`Dirichlet`, later MPC / strong contact)
    /// overrides this to return `Some(self)`. This is the seam the multiplier
    /// forwarders on [`SubModel`](crate::containers::model::SubModel) use — they
    /// never assume every sub-model carries multipliers.
    fn as_constraint(&self) -> Option<&dyn Constraint> {
        None
    }

    /// Borrow this sub-model as a [`Behavior`] capability, or `None` (default)
    /// if it integrates no constitutive law. A physics with a law overrides this
    /// to return `Some(self)`.
    ///
    /// This is the second half of what [`as_domain`](Self::as_domain) used to
    /// lock in one gesture. A physics can now say *I integrate on a subspace,
    /// with material* without also claiming *and I have a law* — which is what
    /// a boundary transfer needed, and what it had to fake.
    fn as_behavior(&self) -> Option<&dyn Behavior> {
        None
    }

    /// Dispatch the per-cell element kernel for `kind` — the single seam the
    /// global assembler drives (via a [`ComputedRecipe`](crate::containers::matrix::ComputedRecipe)),
    /// routing to [`element_matrix`](Domain::element_matrix) /
    /// [`element_mass`](Domain::element_mass) /
    /// [`element_geometric`](Domain::element_geometric) /
    /// [`element_tangent`](Behavior::element_tangent). `state` is `Some(_)` only for
    /// the kinds that consume the current stress/tangent field (geometric,
    /// tangent); the others ignore it.
    #[allow(clippy::too_many_arguments)]
    fn matrix_element(
        &self,
        kind: MatrixKind,
        geoms: &[CellGeom],
        material: &SubElementField,
        lay: &ElementLayout,
        inputs: &KernelState,
        ke: &mut [f64],
    ) -> Result<()> {
        // The **one** bridge between the base contract and the element kernels,
        // which live on `Domain`: only a physics that produces a matrix has
        // them, and only such a physics declares a material FE subspace.
        let domain = self.as_domain().ok_or_else(|| {
            PyrucastError::Message(format!(
                "{}: no element kernel — this sub-model declares no Domain",
                self.label()
            ))
        })?;
        // The kind and its inputs are **paired by construction**: a mismatch can
        // only come from a hand-built recipe, and it is named here rather than
        // in every kernel.
        match (kind, inputs) {
            (MatrixKind::Stiffness, _) => domain.element_matrix(geoms, material, lay, ke),
            (MatrixKind::Mass, _) => domain.element_mass(geoms, material, lay, ke),
            (MatrixKind::Geometric, KernelState::State(state)) => {
                domain.element_geometric(geoms, material, lay, state, ke)
            }
            (
                MatrixKind::Tangent,
                KernelState::Behavior {
                    lay: zone,
                    deformation,
                    prev,
                    dt,
                },
            ) => {
                // The consistent tangent is the derivative of the law's step:
                // a physics without a law has none, and its tangent *is* its
                // stiffness.
                let behavior = self.as_behavior().ok_or_else(|| {
                    PyrucastError::Message(format!(
                        "{}: no consistent tangent — this sub-model integrates no law",
                        self.label()
                    ))
                })?;
                behavior.element_tangent(geoms, zone, deformation, prev, material, *dt, ke)
            }
            (kind, _) => Err(PyrucastError::Message(format!(
                "{}: the {kind:?} matrix was given the wrong inputs",
                self.label()
            ))),
        }
    }

    /// This sub-model's contributions of a given [`MatrixKind`], as the global
    /// assembler consumes them. **Default**: derived from
    /// [`matrix_layout`](Self::matrix_layout) — `Some(layout)` yields a single
    /// [`Contribution::Computed`] (a volumetric physics, integrated straight
    /// into the CSR); `None` falls back — **only for `Stiffness`** — to a
    /// [`Contribution::Literal`] built from
    /// [`build_stiffness_blocks`](Self::build_stiffness_blocks), errors for
    /// `Tangent` (a physics with no tangent kernel that has not declared
    /// [`tangent_is_stiffness`](Self::tangent_is_stiffness), which the
    /// assembler resolves before asking), and yields nothing for the other
    /// kinds (a physics with no term for that kind).
    ///
    /// A volumetric physics writes only its per-kind `element_*` + `*_layout`
    /// and takes the default. A sub-model whose blocks are *not* a single
    /// layout-driven integral (a constraint such as `Dirichlet`, which only
    /// contributes to `Stiffness`) overrides **this** method — that override is
    /// the extension seam, not a special case buried in the assembler.
    ///
    /// `material` is `Some(_)` iff [`Domain::material_fespace`] is declared
    /// (the assembler guarantees it); it is only consulted on the literal path —
    /// the computed path resolves material itself from the layout.
    fn contributions(
        &self,
        kind: MatrixKind,
        material: Option<&Handle<SubElementField>>,
    ) -> Result<Vec<Contribution>> {
        Ok(match self.matrix_layout(kind) {
            Some(layout) => vec![Contribution::Computed(layout)],
            // Here the `Option` earns its keep: a **constraint** sub-model has
            // no material at all, and that is what distinguishes it from a
            // domain. Below this line the question is settled.
            None if kind == MatrixKind::Stiffness => {
                let material = material.ok_or_else(|| {
                    PyrucastError::Message(format!(
                        "{}: a stiffness assembled cell by cell needs material data",
                        self.label()
                    ))
                })?;
                vec![Contribution::Literal(
                    self.build_stiffness_blocks(material)?,
                )]
            }
            None if kind == MatrixKind::Tangent => {
                return Err(PyrucastError::Message(format!(
                    "{}: no consistent tangent — this physics has no tangent kernel \
                     and does not declare its tangent to be its stiffness",
                    self.label()
                )))
            }
            None => Vec::new(),
        })
    }

    /// Build and fill the stiffness [`SubMatrix`] block(s) of this physics.
    /// `material` is `Some(_)` iff [`Domain::material_fespace`] is declared
    /// (the assembler guarantees it).
    ///
    /// **Default**: derived from [`stiffness_layout`](Self::stiffness_layout) —
    /// a single block on that layout, filled by
    /// [`element_matrix`](Domain::element_matrix) via [`kernel::assemble_block`].
    /// A plain volumetric physics therefore writes only `element_matrix` +
    /// `stiffness_layout` and gets this for free; this literal path serves as
    /// the bit-for-bit reference of the computed (scatter) path. A sub-model
    /// with **no** layout does not touch this method — it overrides
    /// [`contributions`](Self::contributions) instead (see `Dirichlet`).
    fn build_stiffness_blocks(&self, material: &Handle<SubElementField>) -> Result<Vec<SubMatrix>> {
        let Some(layout) = self.stiffness_layout() else {
            return Err(PyrucastError::Message(format!(
                "{}: build_stiffness_blocks has no default without a \
                 stiffness_layout — override it (e.g. a constraint such as \
                 Dirichlet, or a multi-block physics)",
                self.label()
            )));
        };
        let domain = self.as_domain().ok_or_else(|| {
            PyrucastError::Message(format!(
                "{}: no element kernel — this sub-model declares no Domain",
                self.label()
            ))
        })?;
        // Resolved once for the zone, before the parallel region: the closure
        // below captures the table, so no cell ever matches a component name.
        let lay = domain.element_layout(MatrixKind::Stiffness, &material.read(), None)?;
        let block = kernel::assemble_block(
            &layout.fespaces,
            &layout.support,
            &layout.support,
            layout.dual_vars,
            layout.primal_vars,
            layout.ordering,
            layout.symmetry,
            material,
            None,
            |geoms, m, _state, ke| domain.element_matrix(geoms, m, &lay, ke),
        )?;
        Ok(vec![block])
    }

    /// Structural layout of this physics' stiffness block, or `None` (default)
    /// for a physics assembled the literal way (constraints such as `Dirichlet`,
    /// or any multi-block physics). When `Some`, it drives **both** paths from a
    /// single description: the global assembler
    /// ([`crate::ops::matrix::stiffness`]) builds a *computed*
    /// [`SubMatrix`] and scatters [`element_matrix`](Domain::element_matrix)
    /// straight into the CSR (never materialising values), and the default
    /// [`build_stiffness_blocks`](Self::build_stiffness_blocks) produces the
    /// *literal* equivalent from the same layout + kernel.
    fn stiffness_layout(&self) -> Option<MatrixLayout> {
        None
    }

    /// Structural layout of this physics' **mass / capacity** block, or `None`
    /// (default: no mass term). A continuum physics returns the same layout as
    /// its stiffness (same fespaces / support / vars) — only the kernel differs.
    fn mass_layout(&self) -> Option<MatrixLayout> {
        None
    }

    /// Structural layout of this physics' **geometric-stiffness** block, or
    /// `None` (default: none).
    fn geometric_layout(&self) -> Option<MatrixLayout> {
        None
    }

    /// Structural layout of this physics' **consistent-tangent** block, or
    /// `None` (default: none).
    fn tangent_layout(&self) -> Option<MatrixLayout> {
        None
    }

    /// Whether this sub-model's consistent tangent **is** its stiffness: true of
    /// a linear physics that has no tangent kernel of its own (conduction,
    /// Fick, bars, beams, shells, boundary exchange) and of the constraints,
    /// whose relations are linear in the unknowns. A `Tangent` request then
    /// assembles this sub-model's [`Stiffness`](MatrixKind::Stiffness) — exact,
    /// not an approximation.
    ///
    /// Default `false`. A physics that declares neither this nor a
    /// [`tangent_layout`](Self::tangent_layout) makes the tangent an
    /// **error**: a silent zero block would make Newton fail far from the cause.
    fn tangent_is_stiffness(&self) -> bool {
        false
    }

    /// Dispatch to the per-kind layout ([`stiffness_layout`](Self::stiffness_layout)
    /// / [`mass_layout`](Self::mass_layout) /
    /// [`geometric_layout`](Self::geometric_layout) /
    /// [`tangent_layout`](Self::tangent_layout)). This is the seam
    /// [`contributions`](Self::contributions) and the global assembler drive; a
    /// physics implements the per-kind primitives, not this dispatcher.
    fn matrix_layout(&self, kind: MatrixKind) -> Option<MatrixLayout> {
        match kind {
            MatrixKind::Stiffness => self.stiffness_layout(),
            MatrixKind::Mass => self.mass_layout(),
            MatrixKind::Geometric => self.geometric_layout(),
            MatrixKind::Tangent => self.tangent_layout(),
        }
    }

    /// Local internal-force vector of one cell — the pure, sequential kernel
    /// that applies `Bᵀ` to the stress (Cast3m `BSIG`). It is the **transpose**
    /// of this physics' deformation operator `B` (the same `B` behind its
    /// [`crate::ops::element_field::deformation`](fn@crate::ops::element_field::deformation) /
    /// [`crate::ops::element_field::beam_deformation`](fn@crate::ops::element_field::beam_deformation)),
    /// so it mirrors [`Behavior::integrate_point`]'s producer.
    ///
    /// Fills `fe` — the cell's local force vector, node-major / variable-minor
    /// (`fe[li * n_dual + di]`, `di` indexing [`dual_vars`](Self::dual_vars)) —
    /// from the cell geometry and the `stress` (the [`Behavior::integrate_point`]
    /// output) borrowed in place. `geoms` holds one [`CellGeom`] per FE subspace
    /// of [`stiffness_layout`](Self::stiffness_layout), in that order.
    ///
    /// **Default**: the continuum-mechanics `f_{i,a} = Σ_g Σ_b (∂N_i/∂x_b) σ_ab`
    /// — one [`crate::ops::node_field::divergence`](fn@crate::ops::node_field::divergence)
    /// per row of the symmetric stress tensor `σ`, read in Voigt naming
    /// (`sigma_xx`, `sigma_xy`, …). A displacement physics (elasticity, Mazars,
    /// plasticity) gets it for free; a physics whose dual is not a displacement
    /// vector (heat, bar, beam) overrides it.
    /// Components this internal-force kernel reads from the state field, in the
    /// slot order its indices assume — the counterpart of
    /// [`Behavior::deformation_reads`] on the `Bᵀσ` side.
    ///
    /// Default: the continuum stress tensor, plus the hoop `σ_θθ` on a body of
    /// revolution, matching the default kernel below. A law reading a
    /// large-transformation measure is answered on the reference configuration
    /// instead, by the whole first Piola–Kirchhoff `P = F S` (`P_xx, P_xy, …`,
    /// hoop `P_zz`) — prepared by
    /// [`stress_measure`](fn@crate::ops::element_field::stress_measure), since
    /// neither `S` nor `T` is what `Bᵀ` applies to there.
    fn internal_force_reads(&self) -> Vec<String> {
        let Some(layout) = self.stiffness_layout() else {
            return Vec::new();
        };
        let space_dim = layout.fespaces[0].read().space_dim();
        let (mut names, prefix) = if reads_finite_strain(self) {
            (
                continuum::internal_force::full_matrix_reads("P", space_dim),
                "P",
            )
        } else {
            (
                continuum::internal_force::voigt_matrix_reads("sigma", space_dim),
                "sigma",
            )
        };
        if layout.fespaces[0].read().is_axisymmetric() {
            names.push(format!("{prefix}_zz"));
        }
        names
    }

    fn internal_force_element(
        &self,
        geoms: &[CellGeom],
        stress: &SubElementField,
        lay: &[u32],
        _material: &SubElementField,
        _mat: &[u32],
        fe: &mut [f64],
    ) -> Result<()> {
        if reads_finite_strain(self) {
            continuum::internal_force::continuum_internal_force_element_full(geoms, stress, lay, fe)
        } else {
            continuum::internal_force::continuum_internal_force_element(geoms, stress, lay, fe)
        }
    }

    /// What this term applies its `Bᵀ` to, at the points of `fespace` — read
    /// when the sub-model has no constitutive law to produce a state.
    ///
    /// **Default**: the primal itself, interpolated there. That is what a
    /// boundary transfer reads — its `∫ h·a·N` needs `a`, not a stress. An
    /// interface reads a **jump** across two conforming sides, which is neither
    /// a state nor a single interpolation, and overrides this.
    ///
    /// The seam exists because the operator cannot guess: it knows how to
    /// resolve a state from a behaviour, and how to interpolate a primal, but
    /// what a term reads is the term's own business.
    ///
    /// ```
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::field::SubField;
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::SubModel;
    /// # use pyrucast::containers::node_field::NodeField;
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::{Physics, SubModelKind};
    /// # use pyrucast::ops::mesh;
    /// # 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))?;
    /// # let zone = fes.get(0)?;
    /// # let support = mesh::poi1_from_nodes(&n)?;
    /// # let mut u = NodeField::from_submesh(&support.get(0)?, vec!["T".into()])?;
    /// # u.get(0)?.write().set_uniform("T", 3.0)?;
    /// # let conduction = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic)?;
    /// # let bord = SubModel::boundary_transfer(
    /// #     zone.clone(), &conduction, vec!["T".into()])?;
    /// // A boundary transfer reads the primal at the points, not a state: its
    /// // value there is the field's, interpolated.
    /// let lu = bord.as_kind().residual_input(&zone, &u)?;
    /// assert_eq!(lu.read().components(), &["T".to_string()]);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    fn residual_input(
        &self,
        fespace: &Handle<SubFiniteElementSpace>,
        solution: &NodeField,
    ) -> Result<Handle<SubElementField>> {
        let mut one = crate::containers::finite_element_space::FiniteElementSpace::empty();
        one.add_sub(fespace.clone())?;
        crate::ops::element_field::interp_to_gauss(solution, &one)?.get(0)
    }

    /// This sub-model's contributions to the **internal** side of the balance
    /// `Σ f_int = Σ f_ext` — empty when it has no term there.
    ///
    /// The nodal twin of [`contributions`](Self::contributions), and it works
    /// the same way: a sub-model declares a **recipe**, never an assembled
    /// container. [`crate::ops::node_field::internal_forces()`] resolves the
    /// state zone, drives the kernel and gathers the field, exactly as
    /// [`crate::ops::matrix::assemble_kind`] resolves the material, drives the
    /// block and gathers the matrix. Nothing here can fail, because nothing
    /// here is resolved.
    ///
    /// With [`external_force_contribution`](Self::external_force_contribution)
    /// the pair yields `r` itself, where `contributions` yields the blocks of
    /// `∂r/∂u`. The residual is the gap between the two sums, so **no physics
    /// ever writes a sign**: an author places their term on one side of the
    /// equals sign or the other, which is a question of physics, and the single
    /// subtraction lives in the caller.
    ///
    /// **Default**: one [`ResidualContribution::Computed`] on the stiffness
    /// layout for a sub-model that integrates a law — the `∫ Bᵀ σ` whose kernel
    /// is [`internal_force_element`](Self::internal_force_element). A
    /// constraint, having no such layout, declares nothing.
    ///
    /// ```
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # 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::{RelationSense, ResidualContribution, SubModelKind};
    /// # 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 fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
    /// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
    /// # let volume = SubModel::heat_conduction(zone, MaterialSymmetry::Isotropic).unwrap();
    /// // A volumetric physics declares its integral; a support declares its
    /// // relations, from which the operator draws the reaction.
    /// assert!(matches!(volume.as_kind().internal_force_contribution()[..],
    ///                  [ResidualContribution::Computed(_)]));
    /// assert!(matches!(appui.as_kind().internal_force_contribution()[..],
    ///                  [ResidualContribution::Relations]));
    /// ```
    fn internal_force_contribution(&self) -> Vec<ResidualContribution> {
        match (self.as_domain(), self.stiffness_layout()) {
            (Some(_), Some(layout)) => vec![ResidualContribution::Computed(layout)],
            _ => Vec::new(),
        }
    }

    /// Local **external** force vector of one cell — the per-cell kernel of an
    /// integrated given term, `∫ N φ dΩ`. The counterpart of
    /// [`internal_force_element`](Self::internal_force_element) on the other
    /// side of the equals sign, and it reads the **material**, where the given
    /// density lives, rather than a state.
    ///
    /// Fills `fe` node-major / variable-minor, like its twin. Default errors:
    /// only a physics that declares a
    /// [`ResidualContribution::Computed`] on the external side ever reaches it.
    fn external_force_element(
        &self,
        _geoms: &[CellGeom],
        _material: &SubElementField,
        _lay: &ElementLayout,
        _fe: &mut [f64],
    ) -> Result<()> {
        Err(PyrucastError::Message(format!(
            "{}: no external kernel — external_force_element is undefined for this physics",
            self.label()
        )))
    }

    /// This sub-model's contributions to the **external** side of
    /// `Σ f_int = Σ f_ext` — the given data of its terms, on the right of the
    /// equals sign — empty when it has none.
    ///
    /// **Default**: nothing. A physics whose term is entirely a response to `u`
    /// (elasticity, conduction, a bar) declares none; the ambient of a boundary
    /// transfer and a distributed flux load will declare one.
    ///
    /// ```
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # 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;
    /// # 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 fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let volume = SubModel::heat_conduction(zone, MaterialSymmetry::Isotropic).unwrap();
    /// // Conduction only responds to `u`: nothing on the right of the equals sign.
    /// assert!(volume.as_kind().external_force_contribution().is_empty());
    /// ```
    fn external_force_contribution(&self) -> Vec<ResidualContribution> {
        Vec::new()
    }

    /// Short type label, e.g. `"HeatConduction"` (used by `Debug` and the
    /// default `display`).
    fn label(&self) -> &'static str;

    /// One-line summary for `Display`. Default: `SubModel<{label}>`.
    fn display(&self) -> String {
        format!("SubModel<{}>", self.label())
    }

    /// Full multi-line rendering for [`crate::dump::Dump`].
    fn render(&self, opts: &DumpOptions) -> String;
}

/// A sub-model that imposes a **Lagrange constraint** — an optional capability,
/// not part of the base [`SubModelKind`] contract. A constraint implements it
/// *and* returns `Some(self)` from [`SubModelKind::as_constraint`]; a plain
/// volumetric physics implements neither, so it simply has no multipliers.
///
/// This is the seam of the constraint family — `Dirichlet` today, MPC and strong
/// contact later — and the natural home for the multiplier-driven logic they
/// share (e.g. the future condensation of the multiplier DOFs).
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # 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::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
/// # 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 fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// // The **constraint** capability: relations, each with its multiplier node
/// // and the component its right-hand side is written into.
/// let c = appui.as_kind().as_constraint().unwrap();
/// let r = c.relations()?;
/// assert_eq!(r.len(), 1);
/// assert_eq!(r[0].terms.len(), 1);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub trait Constraint {
    /// POI1 mesh carrying this constraint's multiplier nodes — one node per
    /// relation, minted by the constraint itself. Borrowed from the sub-model;
    /// generic code clones it when an owned [`Mesh`] is needed.
    fn multiplier_mesh(&self) -> &Mesh;

    /// The linear relations this constraint imposes, in a **method-neutral**
    /// form: one [`Relation`] per multiplier node, each carrying its terms
    /// `(node, variable, target_dual, coefficient)`. It is the single source of
    /// truth the imposition methods consume — the Lagrange path
    /// ([`SubModelKind::contributions`]) builds its `C` / `Cᵀ` blocks from the
    /// same relations a future master/slave *elimination* will read, so neither
    /// re-parses the user's mesh-per-term input.
    fn relations(&self) -> Result<Vec<Relation>>;
}

/// One term of a linear constraint relation, carried **method-neutrally**:
/// `coefficient · u(node, variable)`. Its reaction `coefficient · λ` lands in
/// `target_dual`, the dual (residual) row of `variable` in its physics.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # 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::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
/// # 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 fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// // One relation term: a node, its variable, and the dual of the targeted
/// // physics — the latter is what hooks the constraint onto the physics it
/// // constrains.
/// let r = appui.as_kind().as_constraint().unwrap().relations()?;
/// assert_eq!(r[0].terms[0].node, n[0].id());
/// assert_eq!(r[0].terms[0].variable, "T");
/// assert_eq!(r[0].terms[0].target_dual, "q");
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Clone, Debug)]
pub struct ConstraintTerm {
    /// Constrained node (a column of the target physics' stiffness).
    pub node: NodeId,
    /// Constrained primal variable (e.g. `"u_x"`).
    pub variable: String,
    /// Dual row of `variable` where the reaction is injected (e.g. `"f_x"`).
    pub target_dual: String,
    /// Scalar coefficient `aₖ`.
    pub coefficient: f64,
}

/// The sense of a constraint relation: an **equality** (the default, always
/// enforced) or a **unilateral inequality** solved by the active-set operator
/// [`solver::solve`](crate::ops::solver::solve).
///
/// The KKT conditions follow the sign convention of the existing Lagrange
/// blocks (`Cᵀ·λ` is *added* to the target's dual row):
///
/// - [`GreaterEqual`](Self::GreaterEqual): `C·u ≥ g`, `λ ≥ 0`, `λ·(C·u − g) = 0`;
/// - [`LessEqual`](Self::LessEqual): `C·u ≤ g`, `λ ≤ 0`, `λ·(C·u − g) = 0`.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # 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::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
/// # 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 fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// // Equality, or inequality — what moves the constraint from the direct
/// // solver to the active set. The Python face takes the sense by its name,
/// // `"="` (the default), `">="` or `"<="`, and reads `≥` and `≤` as well.
/// # use pyrucast::named::Named;
/// assert_eq!(RelationSense::default(), RelationSense::Equality);
/// assert_eq!(RelationSense::parse(">=")?, RelationSense::GreaterEqual);
/// assert_eq!(RelationSense::parse("≤")?, RelationSense::LessEqual);
/// assert!(RelationSense::parse("≠").is_err());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum RelationSense {
    /// `Σₖ aₖ·uₖ = g` — always enforced (both solve paths).
    #[default]
    Equality,
    /// `Σₖ aₖ·uₖ ≥ g` — enforced only while active (reaction `λ ≥ 0`).
    GreaterEqual,
    /// `Σₖ aₖ·uₖ ≤ g` — enforced only while active (reaction `λ ≤ 0`).
    LessEqual,
}

impl Named for RelationSense {
    const LABEL: &'static str = "relation sense";
    const VALUES: &'static [Self] = &[
        RelationSense::Equality,
        RelationSense::GreaterEqual,
        RelationSense::LessEqual,
    ];

    fn name(self) -> &'static str {
        match self {
            RelationSense::Equality => "=",
            RelationSense::GreaterEqual => ">=",
            RelationSense::LessEqual => "<=",
        }
    }

    // The doubled equality of programming languages, and the mathematical
    // symbols.
    fn aliases() -> &'static [(&'static str, Self)] {
        &[
            ("==", RelationSense::Equality),
            ("≥", RelationSense::GreaterEqual),
            ("≤", RelationSense::LessEqual),
        ]
    }
}

impl std::fmt::Display for RelationSense {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.name())
    }
}

/// The primal every constraint relation owns: its Lagrange multiplier, on a
/// node of its own, whose solved value is the reaction.
///
/// One name for every constraint: once in the matrix, a relation is a
/// relation, whatever built it. Two relations never meet on one degree of
/// freedom since each has its own multiplier node.
///
/// ```
/// assert_eq!(pyrucast::models::MULTIPLIER, "lambda");
/// ```
pub const MULTIPLIER: &str = "lambda";

/// The dual every constraint relation owns: its equation row, and the slot,
/// on the relation's multiplier node, where the user writes its right-hand
/// side `g` in the load field — see
/// [`SubModel::constraint_rhs`](crate::containers::model::SubModel::constraint_rhs).
///
/// ```
/// assert_eq!(pyrucast::models::IMPOSED, "imposed");
/// ```
pub const IMPOSED: &str = "imposed";

/// One linear constraint relation `Σₖ coeffₖ · u(nodeₖ, varₖ) ⋈ g` (`⋈` is the
/// [`sense`](Self::sense) — `=` by default), enforced by a fresh
/// `multiplier_node` whose solved value is the reaction. The right-hand
/// side `g` is supplied by the user in the load field at the multiplier node's
/// [`IMPOSED`] component, so it is **not** carried here.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # 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::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
/// # 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 fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// // One relation: its multiplier node, minted by the constraint, and its
/// // terms. It is the seam shared by every constraint.
/// let r = appui.as_kind().as_constraint().unwrap().relations()?;
/// assert_eq!(r[0].multiplier_node, appui.multiplier_mesh()?.node(0, 0, 0)?.id());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Clone, Debug)]
pub struct Relation {
    /// The Lagrange-multiplier node that enforces this relation, its own.
    pub multiplier_node: NodeId,
    /// The terms summed on the left-hand side.
    pub terms: Vec<ConstraintTerm>,
    /// Equality (default) or unilateral inequality — read by the solvers only,
    /// the Lagrange blocks are assembled identically either way.
    pub sense: RelationSense,
}

/// Build the Lagrange `C` / `Cᵀ` block pair for **one** constraint term over one
/// paired submesh (multiplier ↔ constrained, one cell per relation, paired
/// element-for-element), every entry equal to `coefficient`:
///
/// - **`C`**  — rows `(multiplier, IMPOSED)`, cols `(constrained, variable)`:
///   the constraint-equation row, which carries the relations' `sense`
///   ([`SubMatrix::row_sense`]) for the solver to read;
/// - **`Cᵀ`** — rows `(constrained, target_dual)`, cols `(multiplier, MULTIPLIER)`:
///   the reaction in the target's dual row.
///
/// Shared by [`dirichlet::Dirichlet`] (one term, `coefficient = 1`) and
/// [`mpc::Mpc`] (one call per term): the single place the saddle-point bordering
/// blocks are filled.
pub(crate) fn constraint_block_pair(
    multiplier_sm: &Handle<SubMesh>,
    constrained_sm: &Handle<SubMesh>,
    variable: &str,
    target_dual: &str,
    coefficient: f64,
    sense: RelationSense,
) -> Result<(SubMatrix, SubMatrix)> {
    // Neither block is symmetric — both are rectangular — but together they are,
    // and this is the one place that knows it: the same coefficient is written
    // into both, a few lines below. The identity folds in everything that tells
    // this pair from another; two constraints that hashed alike would be
    // *rejected* by `Matrix::symmetric`, never wrongly accepted.
    let (id_c, id_ct) = {
        let (mult_g, cons_g) = (multiplier_sm.read(), constrained_sm.read());
        let mut h = FNV_SEED;
        h = hash_nodes(h, mult_g.connectivity());
        h = hash_nodes(h, cons_g.connectivity());
        for name in [variable, target_dual] {
            h = hash_name(h, name);
        }
        mint_pair(hash_f64(h, coefficient))
    };
    // C block: rows = multiplier × IMPOSED, cols = constrained × variable.
    let mut c = SubMatrix::new(
        multiplier_sm.clone(),
        constrained_sm.clone(),
        vec![IMPOSED.to_string()],
        vec![variable.to_string()],
        DofOrdering::NodesThenVars,
        Symmetry::Half(id_c),
    );
    c.set_row_sense(sense);
    // Cᵀ block: rows = constrained × target_dual, cols = multiplier × MULTIPLIER.
    let mut ct = SubMatrix::new(
        constrained_sm.clone(),
        multiplier_sm.clone(),
        vec![target_dual.to_string()],
        vec![MULTIPLIER.to_string()],
        DofOrdering::NodesThenVars,
        Symmetry::Half(id_ct),
    );
    // Both blocks are built — hence both `seal`s, the only writers here — so the
    // node lists can now be read in place instead of copied: `add_entry` only
    // ever takes a read guard on the supports.
    let (mult_g, cons_g) = (multiplier_sm.read(), constrained_sm.read());
    for (cons, mult) in cons_g
        .connectivity()
        .iter()
        .zip(mult_g.connectivity().iter())
    {
        c.add_entry_with(
            &mult_g,
            &cons_g,
            *mult,
            IMPOSED,
            *cons,
            variable,
            coefficient,
        )?;
        ct.add_entry_with(
            &cons_g,
            &mult_g,
            *cons,
            target_dual,
            *mult,
            MULTIPLIER,
            coefficient,
        )?;
    }
    Ok((c, ct))
}

/// A static component list in the owned form [`Domain::material_components`]
/// returns — the one line every physics whose contract is fixed needs.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # 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::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
/// # 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 fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// # use pyrucast::models::owned_components;
/// // The shortcut every physics uses to hand back its material contract
/// // without retyping it.
/// assert_eq!(owned_components(&["E", "nu"]),
///            vec!["E".to_string(), "nu".to_string()]);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn owned_components(names: &[&str]) -> Vec<String> {
    names.iter().map(|s| s.to_string()).collect()
}

/// Where a physics' components sit in the rows its kernel is handed.
///
/// A constitutive kernel runs once per Gauss point — some tens of millions of
/// times in a non-linear solve — so it reads by **index**, never by name: a name
/// lookup is a string comparison that re-proves at every point what is a
/// property of the zone. This table is that proof, done once, before the
/// parallel region: it translates the canonical order a physics declares
/// ([`Behavior::deformation_reads`], [`Behavior::state_reads`],
/// [`Domain::material_components`]) into positions in the actual fields.
///
/// Resolving rather than assuming also makes the convention **checked**: a field
/// built by hand, in another order or missing a component, is refused by
/// [`Behavior::zone_layout`] with a message naming the field and the gap — instead
/// of silently feeding a permuted tensor to the law.
/// ```
/// # use pyrucast::models::ZoneLayout;
/// // A table says where to read, not what to read: the physics declares its
/// // canonical order, the zone translates it into positions.
/// let lay = ZoneLayout {
///     deformation: vec![2, 0, 1],
///     state: Vec::new(),
///     material: vec![0, 1],
///     optional_material: Vec::new(),
/// };
/// let ligne = [10.0, 20.0, 30.0];
/// // The convention's first component sits in third position.
/// assert_eq!(ligne[lay.deformation[0] as usize], 30.0);
/// ```
pub struct ZoneLayout {
    /// Position of each [`Behavior::deformation_reads`] component.
    pub deformation: Vec<u32>,
    /// Position of each [`Behavior::state_reads`] component in the `prev` row.
    pub state: Vec<u32>,
    /// Position of each **required** material component, in
    /// [`Domain::material_components`] order.
    pub material: Vec<u32>,
    /// Position of each **optional** material component, in
    /// [`Domain::optional_material_components`] order;
    /// [`ABSENT_COMPONENT`](crate::containers::field::ABSENT_COMPONENT) where
    /// the caller supplied none.
    pub optional_material: Vec<u32>,
}

/// What a **matrix** kernel reads, resolved once per zone — the counterpart of
/// [`ZoneLayout`] on the element side.
///
/// The two paths of a physics now hold the same shape: the point kernel gets a
/// [`ZoneLayout`] from [`Behavior::zone_layout`], the element kernel gets an
/// `ElementLayout` from [`Domain::element_layout`], and neither looks a
/// component up by name. A name search is a string comparison; done inside a
/// per-cell loop it re-proves at every cell what is a property of the *zone*.
///
/// ```
/// # use pyrucast::models::ElementLayout;
/// // A table says where to read. The physics declares its canonical order
/// // (`material_components`, `element_state_reads`), the zone translates it.
/// let lay = ElementLayout {
///     material: vec![1, 0],
///     optional_material: Vec::new(),
///     state: Vec::new(),
/// };
/// let ligne = [0.3, 210_000.0];
/// // `E` is declared first, but stored second in that particular field.
/// assert_eq!(ligne[lay.material[0] as usize], 210_000.0);
/// ```
pub struct ElementLayout {
    /// Position of each **required** material component, in
    /// [`Domain::material_components`] order.
    pub material: Vec<u32>,
    /// Position of each **optional** material component, in
    /// [`Domain::optional_material_components`] order;
    /// [`ABSENT_COMPONENT`](crate::containers::field::ABSENT_COMPONENT) where
    /// the caller supplied none.
    pub optional_material: Vec<u32>,
    /// Position of each [`Domain::element_state_reads`] component in the state
    /// row — empty for the kinds that read no state (stiffness, mass).
    pub state: Vec<u32>,
}

/// The borrowed twin of [`KernelInputs`](crate::containers::matrix::KernelInputs):
/// what a matrix kernel reads besides its material, already borrowed and, for the
/// tangent, already resolved.
///
/// The `ZoneLayout` travels **inside** the tangent variant because it belongs to
/// it: no other kind resolves one, and hanging an `Option<&ZoneLayout>` on the
/// signature would be a slot for three kinds to leave empty.
///
/// ```
/// # use pyrucast::models::KernelState;
/// // What a stiffness receives: nothing more than its material.
/// let inputs = KernelState::MaterialOnly;
/// assert!(matches!(inputs, KernelState::MaterialOnly));
/// ```
pub enum KernelState<'a> {
    /// Stiffness, mass.
    MaterialOnly,
    /// Geometric stiffness: the current stress.
    State(&'a SubElementField),
    /// Consistent tangent, evaluated at the point.
    Behavior {
        lay: &'a ZoneLayout,
        deformation: &'a SubElementField,
        prev: &'a SubElementField,
        dt: f64,
    },
}

/// A **domain** sub-model — an optional capability, not part of the base
/// [`SubModelKind`] contract. A domain is a physics defined *over a region*: it
/// reads material data **and** integrates a constitutive law over its cells. A
/// domain implements this trait *and* returns `Some(self)` from
/// [`SubModelKind::as_domain`]; a constraint such as `Dirichlet` implements
/// neither, so its absence of material and behaviour is a compile-time fact, not
/// a runtime error.
///
/// Material and behaviour used to be **one** capability here, and that was the
/// mistake: this trait asked for six methods, of which four served only those
/// that really have a law. A boundary transfer needs the integration and the
/// material — its `h` lives on a subspace, its `∫ h NᵀN` is integrated cell by
/// cell — and has no law at all; the price of admission was a kernel that
/// recomputed, point by point, what the matrix already knew.
///
/// So the law now lives next door, in [`Behavior`], which has `Domain` for
/// supertrait: every behaviour integrates, not every integration has a law.
/// What remains here is one fact — *I integrate on an FE subspace, with
/// material*.
///
/// An implementer writes the material declaration
/// ([`material_fespace`](Self::material_fespace)) and whichever matrix kernels
/// it has ([`element_matrix`](Self::element_matrix) & consorts); every one of
/// those is provided and errors by default, because a physics may integrate
/// without producing a matrix of a given kind — or any matrix at all, as a
/// distributed load does.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # 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::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
/// # 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 fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// // Matter and behaviour are **one single** capability: the material
/// // parameterises the constitutive law, it has no meaning without it.
/// let d = volume.as_kind().as_domain().unwrap();
/// assert_eq!(d.material_components(), vec!["k".to_string()]);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub trait Domain: Sync {
    /// FE subspace on which this domain expects its material data.
    fn material_fespace(&self) -> Handle<SubFiniteElementSpace>;

    /// Material component names this domain requires, or `None` if it declares a
    /// material FE subspace but constrains no particular component. Default:
    /// `None`.
    ///
    /// **Owned**, not `&'static`: a physics whose variables are given by the
    /// caller derives its coefficient names from them — a transfer law wants one
    /// `h_<variable>` per transferred quantity, which no static table can hold.
    /// The DOF names ([`SubModelKind::primal_vars`]) had always been owned for
    /// the same reason; this closes the asymmetry. It is read once per sub-model
    /// when the material field is built, so the allocation is not on any hot
    /// path. Most implementers hand a static list to
    /// [`owned_components`](fn@owned_components) and are done.
    fn material_components(&self) -> Vec<String> {
        Vec::new()
    }

    /// Material component names this domain **accepts but does not require**:
    /// passed through the material channel if supplied (kept by
    /// [`material_field`](fn@crate::ops::element_field::material_field)), never demanded
    /// at assembly (only the *required* components discriminate the material
    /// zone). Read by an ancillary operator — e.g. `alpha` (thermal expansion)
    /// consumed by
    /// [`crate::ops::element_field::thermal_strain`](fn@crate::ops::element_field::thermal_strain).
    /// Default: `&[]`.
    fn optional_material_components(&self) -> &'static [&'static str] {
        &[]
    }

    /// Components the **matrix** kernel of `kind` reads from the state field, in
    /// the slot order its indices assume — the counterpart of
    /// [`state_reads`](Behavior::state_reads) on the element side.
    ///
    /// Default: none. A stiffness or a mass reads only the material, so only the
    /// two state-consuming kinds — `Geometric` (the current stress) and
    /// `Tangent` (the algorithmic moduli) — declare anything here. The material
    /// side needs no declaration at all: [`material_components`](Self::material_components)
    /// already is it.
    fn element_state_reads(&self, _kind: MatrixKind) -> Vec<String> {
        Vec::new()
    }

    /// Resolve this physics' matrix conventions against the fields it will be
    /// handed — **the upstream half of index-based reading**, and the only place
    /// a matrix kernel's component names are matched at all.
    ///
    /// **Provided**, and rarely worth redefining; the mirror of
    /// [`zone_layout`](Behavior::zone_layout). The driver calls it once per zone,
    /// before the parallel region, and hands the result to every cell.
    fn element_layout(
        &self,
        kind: MatrixKind,
        material: &SubElementField,
        state: Option<&SubElementField>,
    ) -> Result<ElementLayout> {
        let mat_names = self.material_components();
        let mat_refs: Vec<&str> = mat_names.iter().map(String::as_str).collect();
        let state_names = self.element_state_reads(kind);
        let state_refs: Vec<&str> = state_names.iter().map(String::as_str).collect();
        let state_lay = match (state, state_refs.is_empty()) {
            (_, true) => Vec::new(),
            (Some(s), false) => s.resolve_components(&state_refs, "state")?,
            // The assembler supplies a state for exactly the kinds that read
            // one; a kernel declaring reads without one is a wiring mistake,
            // caught here rather than at a Gauss point.
            (None, false) => {
                return Err(PyrucastError::Message(format!(
                    "{kind:?}: this kernel reads {state_refs:?} from the state field, \
                     and none was supplied"
                )))
            }
        };
        Ok(ElementLayout {
            material: material.resolve_components(&mat_refs, "material")?,
            optional_material: material
                .resolve_optional_components(self.optional_material_components()),
            state: state_lay,
        })
    }

    /// Local element stiffness matrix of one cell — the pure, sequential kernel
    /// a physics author writes (the stiffness counterpart of
    /// [`integrate_point`](Behavior::integrate_point)). Fills `ke` (row-major,
    /// node-major / variable-minor: `ke[(li*n_dual+di) * n_cols_loc + (lj*n_primal+pj)]`)
    /// from the cell geometry and material.
    ///
    /// `geoms` holds one [`CellGeom`] per FE subspace declared in
    /// [`SubModelKind::stiffness_layout`], in that order: a plain volumetric
    /// physics reads `geoms[0]`, a multi-quadrature element (a shear-deformable
    /// beam, a shell) reads each — e.g. `geoms[0]` full Gauss for bending,
    /// `geoms[1]` reduced for shear.
    ///
    /// `lay` is [`element_layout`](Self::element_layout)'s answer, resolved once
    /// for the zone: read the material by `lay.material[k]`, **never by name** —
    /// a name search inside a per-cell loop re-proves at every cell what is a
    /// property of the zone.
    ///
    /// It **never sees rayon, the store, or a lock**: the assembler drives it in
    /// parallel over all cells. Default errors, like its four siblings: a
    /// physics may integrate on a subspace without producing a stiffness — a
    /// distributed load has a support and a density, and a null derivative.
    /// What decides is [`stiffness_layout`](SubModelKind::stiffness_layout),
    /// which such a physics leaves at `None`; the kernel is then never reached.
    fn element_matrix(
        &self,
        _geoms: &[CellGeom],
        _material: &SubElementField,
        _lay: &ElementLayout,
        _ke: &mut [f64],
    ) -> Result<()> {
        Err(PyrucastError::Message(
            "no stiffness kernel — element_matrix is undefined for this physics".into(),
        ))
    }

    /// Local element **mass** matrix of one cell (`∫ ρ Nᵀ N` for mechanics,
    /// `∫ ρ c Nᵀ N` for the thermal capacity) — the mass counterpart of
    /// [`element_matrix`](Self::element_matrix). Default errors: a physics may
    /// legitimately have no mass term.
    fn element_mass(
        &self,
        _geoms: &[CellGeom],
        _material: &SubElementField,
        _lay: &ElementLayout,
        _ke: &mut [f64],
    ) -> Result<()> {
        Err(PyrucastError::Message(
            "no mass kernel — element_mass is undefined for this physics".into(),
        ))
    }

    /// Local element **geometric (initial-stress) stiffness** of one cell
    /// (`∫ Gᵀ σ̂ G`). `state` carries this physics' current stress field (the
    /// [`integrate_behavior`](Behavior::integrate_behavior) output), read by
    /// `lay.state[k]`. Default errors: not every physics buckles.
    fn element_geometric(
        &self,
        _geoms: &[CellGeom],
        _material: &SubElementField,
        _lay: &ElementLayout,
        _state: &SubElementField,
        _ke: &mut [f64],
    ) -> Result<()> {
        Err(PyrucastError::Message(
            "no geometric-stiffness kernel — element_geometric is undefined for this physics"
                .into(),
        ))
    }

    /// Local element **coupling** matrix of one facing cell pair — the kernel
    /// behind [`Contribution::Coupling`]. `row_geoms` describes the cell on the
    /// row mesh, `col_geoms` the facing cell on the column mesh; `ke` is
    /// `(row nodes × dual) × (col nodes × primal)`, same node-major layout as
    /// [`element_matrix`](Self::element_matrix).
    ///
    /// It is the physics' job to carry the **sign**: an exchange law contributes
    /// `+h∫NᵢNⱼ` on its two diagonal blocks and `−h∫NᵢNⱼ` off-diagonal, and since
    /// the two go through different kernels there is no factor to thread through
    /// the assembler. Default errors: only an interface couples two meshes.
    fn coupling_element(
        &self,
        _kind: MatrixKind,
        _row_geoms: &[CellGeom],
        _col_geoms: &[CellGeom],
        _material: &SubElementField,
        _lay: &ElementLayout,
        _ke: &mut [f64],
    ) -> Result<()> {
        Err(PyrucastError::Message(
            "no coupling kernel — coupling_element is undefined for this physics".into(),
        ))
    }
}

/// How a law's input is produced from the nodal solution — the `B` of
/// `ε = B·u`, **named** by the law ([`Behavior::strain_operator`]) and **run**
/// by [`crate::ops::element_field::strain`](fn@crate::ops::element_field::strain).
///
/// The law declares, the operator runs: it holds the solution once for every
/// sub-model, and no law handles a nodal field. Each variant is one of the
/// geometric producers of [`crate::ops::element_field`], applied to the law's own
/// primal unknowns on its [`behavior_fespace`](Behavior::behavior_fespace):
///
/// | variant | producer | what the law reads |
/// |---|---|---|
/// | `Deformation(m)` | `deformation` | a strain measure of the displacement (`eps_xx`, …) |
/// | `Gradient` | `gradient` | the gradient of each unknown (`grad_T_x`, …) |
/// | `Value` | `interp_to_gauss` | the unknown itself at the point (`T`) |
/// | `Beam` | `beam_deformation` | section strains (`eps`, `kappa`, `gamma`, …) |
/// | `Shell(f)` | `shell_deformation` | membrane, curvatures, drilling, shear |
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # 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::tensor::Kinematics;
/// # use pyrucast::models::{StrainOperator, SubModelKind};
/// # use pyrucast::ops::element_field::StrainMeasure;
/// # 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 fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// let solide = SubModel::elasticity(zone.clone(), Kinematics::PlaneStrain, MaterialSymmetry::Isotropic, StrainMeasure::Linear)?;
/// let thermique = SubModel::heat_conduction(zone, MaterialSymmetry::Isotropic)?;
/// let entree = |m: &SubModel| m.as_kind().as_behavior().unwrap().strain_operator();
/// // A solid reads the small-strain tensor of its displacement, conduction the
/// // gradient of its temperature: the same `B·u`, two operators.
/// assert_eq!(entree(&solide), StrainOperator::Deformation(StrainMeasure::Linear));
/// assert_eq!(entree(&thermique), StrainOperator::Gradient);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StrainOperator {
    /// A strain measure of the displacement, one component per axis.
    Deformation(crate::ops::element_field::StrainMeasure),
    /// The gradient of each primal unknown.
    Gradient,
    /// The primal unknowns themselves, interpolated at the points.
    Value,
    /// A beam's section strains; they read `Φ` from the material.
    Beam,
    /// A shell's generalized strains, in the given formulation.
    Shell(shell::ShellFormulation),
}

/// Whether `kind` carries a law reading a large-transformation measure
/// (Green–Lagrange or Hencky): its residual is then written on the reference
/// configuration with the first Piola–Kirchhoff stress.
fn reads_finite_strain<K: SubModelKind + ?Sized>(kind: &K) -> bool {
    matches!(
        kind.as_behavior().map(|law| law.strain_operator()),
        Some(StrainOperator::Deformation(measure))
            if measure != crate::ops::element_field::StrainMeasure::Linear
    )
}

/// The **law** capability: a pointwise constitutive evaluation producing a
/// state, on top of a [`Domain`]'s integration.
///
/// This is the second of the two facts `Domain` used to lock together. A domain
/// says *I integrate on an FE subspace, with material*; a behaviour says *and I
/// have a law evaluated at each point*. The two are not orthogonal — a law is
/// evaluated on a subspace and reads material — hence the supertrait: every
/// behaviour is a domain, not every domain is a behaviour.
///
/// The distinction is not academic. A boundary transfer integrates `∫ h NᵀN`
/// and needs the first; its `h·a` is not a law but the coefficient of that same
/// operator applied at a point, and the residual `A·u` follows from the
/// operator itself. Requiring it to declare a law was the price of admission,
/// and it paid it with a kernel that recomputed what the matrix already knew.
///
/// A physics with a law implements both traits and returns `Some(self)` from
/// [`SubModelKind::as_behavior`]; one without implements `Domain` alone.
///
/// ## The convention every law follows
///
/// A law steps from A to B — the state at A, the strain at B — and computes the
/// stress at B as **the material at B applied to the elastic strain at B**:
/// `σ(B) = C(B) : ε_e(B)`. Elasticity and damage do it directly (their elastic
/// strain is the strain), plasticity through `ε_e = ε − ε_p`. A stress written
/// that way stays secant when the material depends on the state — a modulus
/// that drops with temperature lowers the stress at the same elastic strain —
/// so a step-by-step solver needs no correction when the materials move. An
/// incremental `σ(A) + C(B):Δε` would carry the stress of the old modulus
/// along instead. MFront writes its behaviours the same way.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # 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::{RelationSense, SubModelKind};
/// # 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 fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// # let volume = SubModel::heat_conduction(zone, MaterialSymmetry::Isotropic).unwrap();
/// // Conduction integrates **and** has a law; a support does neither. It is
/// // a compile-time fact, not a run-time error.
/// assert!(volume.as_kind().as_domain().is_some());
/// assert!(volume.as_kind().as_behavior().is_some());
/// assert!(appui.as_kind().as_domain().is_none());
/// assert!(appui.as_kind().as_behavior().is_none());
/// ```
pub trait Behavior: Domain {
    /// FE subspace this domain integrates its constitutive behaviour on. Its
    /// deformation input is produced geometrically by
    /// [`crate::ops::element_field::gradient`](fn@crate::ops::element_field::gradient) /
    /// [`crate::ops::element_field::deformation`](fn@crate::ops::element_field::deformation),
    /// and [`crate::ops::element_field::behavior`] uses this handle to pair the per-zone
    /// deformation field with its sub-model. Usually the same FE subspace as
    /// [`material_fespace`](Domain::material_fespace).
    fn behavior_fespace(&self) -> Handle<SubFiniteElementSpace>;

    /// Output component names of the material-state field produced by
    /// [`integrate_point`](Self::integrate_point) — the dual flux/stress
    /// followed by the updated internal state (`VAR1`), in order.
    fn behavior_output_components(&self) -> Vec<String>;

    /// Components this kernel reads from the **deformation** row, in the slot
    /// order its indices assume — the physics' own convention (`eps_xx`,
    /// `eps_yy`, `eps_xy` for a plane continuum; `grad_T_x`, … for conduction).
    ///
    /// Read once per zone by [`zone_layout`](Self::zone_layout), never at a
    /// Gauss point. Declaring it is physics — naming what the law consumes —
    /// and it is what lets the kernel index instead of search.
    fn deformation_reads(&self) -> Vec<String>;

    /// How the input [`deformation_reads`](Self::deformation_reads) names is
    /// produced from the nodal solution — this law's `B`, run by
    /// [`crate::ops::element_field::strain`](fn@crate::ops::element_field::strain).
    ///
    /// **Required**, deliberately: a law that forgot it would have no input, and
    /// a default would hand it someone else's.
    fn strain_operator(&self) -> StrainOperator;

    /// Components this kernel reads from the **previous state** row, in slot
    /// order. Default: none — most laws have no history.
    ///
    /// Every declared component must exist in the state: what a law reads back
    /// is what it wrote, so a mismatch is a real inconsistency, caught once per
    /// zone rather than turned into a silent zero at each point.
    fn state_reads(&self) -> Vec<String> {
        Vec::new()
    }

    /// Resolve this physics' conventions against the fields it will actually be
    /// handed — **the upstream half of index-based reading**, and the only place
    /// component names are matched at all.
    ///
    /// **Provided**, and rarely worth redefining. Required components must be
    /// present (a missing one names itself in the error); optional material
    /// components may be absent, marked
    /// [`ABSENT_COMPONENT`](crate::containers::field::ABSENT_COMPONENT).
    fn zone_layout(
        &self,
        deformation: &SubElementField,
        prev: &SubElementField,
        material: &SubElementField,
    ) -> Result<ZoneLayout> {
        let def_names = self.deformation_reads();
        let state_names = self.state_reads();
        let mat_names = self.material_components();
        let def_refs: Vec<&str> = def_names.iter().map(String::as_str).collect();
        let state_refs: Vec<&str> = state_names.iter().map(String::as_str).collect();
        let mat_refs: Vec<&str> = mat_names.iter().map(String::as_str).collect();
        Ok(ZoneLayout {
            deformation: deformation.resolve_components(&def_refs, "deformation")?,
            state: prev.resolve_components(&state_refs, "previous state")?,
            material: material.resolve_components(&mat_refs, "material")?,
            optional_material: material
                .resolve_optional_components(self.optional_material_components()),
        })
    }

    /// Local element **consistent tangent** of one cell (`∫ Bᵀ D_alg B`).
    /// `state` carries the algorithmic tangent moduli produced by
    /// [`integrate_point`](Self::integrate_point), read by `lay.state[k]`.
    /// Default errors: a linear law has no tangent of its own.
    #[allow(clippy::too_many_arguments)]
    fn element_tangent(
        &self,
        _geoms: &[CellGeom],
        _lay: &ZoneLayout,
        _deformation: &SubElementField,
        _prev: &SubElementField,
        _material: &SubElementField,
        _dt: f64,
        _ke: &mut [f64],
    ) -> Result<()> {
        Err(PyrucastError::Message(
            "no tangent kernel — element_tangent is undefined for this physics".into(),
        ))
    }

    /// The material state **at rest**, before any step — the `prev` of the first
    /// step. **Provided**: zero on every output component, which is the rest
    /// state of nearly every law (σ = 0, ε = 0, ε_p = 0, p = 0).
    ///
    /// It exists so that `prev` is **always** a real field. The alternative —
    /// an `Option` threaded down to the Gauss point — made every physics ask
    /// "is there a state yet?" some tens of millions of times per solve, to
    /// answer the same thing every time; and it is a question about the *step*,
    /// not about the point. The field has to be allocated for the step's output
    /// anyway, so materializing it costs one buffer that was already coming.
    ///
    /// Redefine it where the rest state is **not** the zero state: a law whose
    /// internal variable starts from a material constant (Gurson's initial
    /// porosity `f_0`) seeds it here, once, instead of testing for emptiness at
    /// every Gauss point.
    fn initial_state(&self, _material: &SubElementField) -> Result<SubElementField> {
        SubElementField::new(self.behavior_fespace(), self.behavior_output_components())
    }

    /// Whether this domain's law needs the **time increment** — a creep or
    /// viscoplastic law, whose answer depends on how long the step lasted.
    /// Default: `false`.
    ///
    /// Read once, by [`crate::ops::element_field::behavior::integrate`], which
    /// refuses the whole integration when such a law is handed no `dt`. The
    /// kernel then receives a plain `f64` and never asks: the question belongs
    /// to the step, and answering it per Gauss point answered it some tens of
    /// millions of times to say the same thing.
    fn requires_dt(&self) -> bool {
        false
    }

    /// The **elastic operator** of this law, when it has one: the continuum it
    /// stands on and the symmetry of its elastic constants, which head its
    /// material contract (`E`, `nu` for an isotropic law).
    ///
    /// It is what a plasticity law predicts with and a damage law degrades —
    /// the `D` of `σ = D:ε`, not the law's own response. Read by
    /// [`elastic_stress`](fn@crate::ops::element_field::elastic_stress) and
    /// [`elastic_strain`](fn@crate::ops::element_field::elastic_strain).
    /// Default: none — a conduction, a bar or a beam has no continuum `D`.
    fn elastic_operator(&self) -> Option<(&continuum::Continuum, symmetry::MaterialSymmetry)> {
        None
    }

    /// Where this physics' consistent tangent comes from — see
    /// [`TangentSource`]. Default: `Analytic`, which is the truth for every
    /// physics whose tangent is a closed form. A physics that differentiates its
    /// own law numerically says so, and a caller can then decide whether it
    /// wants to pay.
    fn tangent_source(&self) -> TangentSource {
        TangentSource::Analytic
    }

    /// The consistent tangent `D_alg` at **one Gauss point** — the mirror of
    /// [`integrate_point`](Self::integrate_point), and its exact inputs.
    ///
    /// It takes the same row slices for the same reason: the algorithmic tangent
    /// is the derivative of the *step* `ε(B) ↦ σ(B)` at frozen state A, not a
    /// tangent to a surface at a point. Both ends of the step are part of its
    /// definition — and a law differentiated by finite differences literally
    /// re-runs its return map from `prev`.
    ///
    /// Writes the full-3-D `6×6` modulus into `d`, a **caller-owned** buffer
    /// living outside the Gauss loop: this kernel allocates nothing, exactly
    /// like [`integrate_point`](Self::integrate_point). The reduction to the
    /// kinematics' Voigt size is the caller's business.
    ///
    /// Default: errors — not every physics has a tangent of its own.
    #[allow(clippy::too_many_arguments)]
    fn tangent_point(
        &self,
        _geom: &CellGeom,
        _g: usize,
        _lay: &ZoneLayout,
        _deformation: &[f64],
        _prev: &[f64],
        _material: &[f64],
        _dt: f64,
        _d: &mut [[f64; 6]; 6],
    ) -> Result<()> {
        Err(PyrucastError::Message(
            "no tangent kernel — tangent_point is undefined for this physics".into(),
        ))
    }

    /// Constitutive law at **one Gauss point** — the pure, sequential kernel a
    /// physics author writes. Integrates the step **A → B** for cell `geom.cell`
    /// at Gauss point `g`:
    ///
    /// Every input is the **row of this Gauss point** — a borrowed slice of the
    /// field's own buffer, never a copy — read through `lay`:
    ///
    /// - `deformation` is the **end-of-step** kinematics ε(B) (the strain, the
    ///   temperature gradient `∇T`, …) produced by a *geometric* operator, in
    ///   [`deformation_reads`](Self::deformation_reads) order;
    /// - `prev` is the **converged state at the start of the step A** — the
    ///   dual flux/stress σ(A), the internal variables `VAR(A)`, and (for laws
    ///   that form an increment) the start-of-step kinematics ε(A). It is
    ///   **always** a real row: on the first step it is
    ///   [`initial_state`](Self::initial_state), the rest state;
    /// - `material` is this cell's material data, empty for a physics that
    ///   declares none;
    /// - `dt` is the time increment, `0.0` for a rate-independent law — a law
    ///   that needs one is guaranteed to get it, because
    ///   [`crate::ops::element_field::behavior::integrate`] refuses the whole
    ///   integration otherwise.
    ///
    /// Write the [`behavior_output_components`](Self::behavior_output_components)
    /// values — the material state at B (σ(B), `VAR(B)`, and any echoed ε(B)) —
    /// into `out`. It **never sees rayon, the store, or a lock**:
    /// [`integrate_behavior`](Self::integrate_behavior) drives it in parallel
    /// over all cells.
    ///
    /// Two invariants hold here, and they are what makes this kernel fast: **no
    /// test that upstream already settled** (a component's presence, a field's
    /// shape, an absent increment) and **no dynamic allocation** — no `Vec`, no
    /// `String`, no `format!`, no intermediate struct. What is left is the
    /// physics, including its own branches.
    // A constitutive kernel legitimately needs its geometry, the Gauss index,
    // its layout, the A→B kinematics, material, time step and output slot.
    #[allow(clippy::too_many_arguments)]
    fn integrate_point(
        &self,
        geom: &CellGeom,
        g: usize,
        lay: &ZoneLayout,
        deformation: &[f64],
        prev: &[f64],
        material: &[f64],
        dt: f64,
        out: &mut [f64],
    ) -> Result<()>;

    /// Integrate the constitutive law (Cast3m `COMP`). **Provided**: drives the
    /// point kernel [`integrate_point`](Self::integrate_point) in parallel over
    /// the behaviour FE subspace via [`kernel::element_pointwise`].
    ///
    /// This is the **incremental montage** A → B: `deformation` carries the
    /// end-of-step kinematics ε(B) alone, and `prev` — the *converged output of
    /// the previous step*, or [`initial_state`](Self::initial_state) on the
    /// first one — carries the whole state at A (σ(A), `VAR(A)`, ε(A)).
    /// Returns the **material-state** field
    /// at B: the dual flux/stress followed by the updated internal-state
    /// variables (`VAR1`), which becomes the next step's `prev`. Where
    /// [`SubModelKind::build_stiffness_blocks`] is the *linearization* of the
    /// law, this is its *exact* response: for a linear law the two agree
    /// (`∫ Bᵀ·flux = K·u`); a non-linear law departs from that tangent.
    ///
    /// The **layout is resolved here**, once, and `dt` captured by the point
    /// closure: below this line the kernel indexes and computes, and does
    /// nothing else.
    fn integrate_behavior(
        &self,
        deformation: &Handle<SubElementField>,
        prev: &Handle<SubElementField>,
        material: &Handle<SubElementField>,
        dt: f64,
    ) -> Result<SubElementField> {
        let fespace = self.behavior_fespace();
        let out_components = self.behavior_output_components();
        // One resolution per zone, against the fields actually handed over —
        // which is also where a hand-built field is refused.
        let lay = self.zone_layout(&deformation.read(), &prev.read(), &material.read())?;
        kernel::element_pointwise(
            &fespace,
            deformation,
            prev,
            material,
            out_components,
            |geom, g, def, prev, mat, out| {
                self.integrate_point(geom, g, &lay, def, prev, mat, dt, out)
            },
        )
    }
}

/// Declare a physics' **parent-level operator** and its Python twin, from a
/// single place in the physics' own file.
///
/// The author of a physics writes physics and documentation; the plumbing —
/// the sweep, the `#[pyfunction]`, the stub attribute, the unwrapping of the
/// Python wrappers — is emitted here. They never open `src/py/`.
///
/// Two doc blocks, because the two audiences differ: the Rust one carries the
/// `///` comment and its doctest, the Python one a string literal, which is
/// what lands in the `.pyi`. Sharing a single block would put a Rust doctest
/// into a Python docstring. Same shape as `define_polymorphic_pyfunction!` in
/// `src/py/ops/field.rs`, the house precedent.
///
/// What it emits for `truss` — declared `truss(fespace, strain_measure:
/// StrainMeasure = StrainMeasure::Linear) via SubModel::truss` — is an ordinary
/// function: it sweeps the FE space, one sub-model per subspace, and Rust passes
/// the argument the Python face defaults. That default is written into the Rust
/// documentation, so that a Rust reader knows what the Python one gets by
/// saying nothing.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::ops::element_field::StrainMeasure;
/// # use pyrucast::ops::model;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [2.0, 0.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut left = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # left.add_cell(&[n[0].id(), n[1].id()])?;
/// # let mut right = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # right.add_cell(&[n[1].id(), n[2].id()])?;
/// # let bars = Mesh::from_submesh(left).union(&Mesh::from_submesh(right))?;
/// let fes = FiniteElementSpace::lagrange1(&bars)?;
/// assert_eq!(fes.len(), 2);
/// let cables = model::truss(&fes, StrainMeasure::GreenLagrange)?;
/// assert_eq!(cables.len(), fes.len());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[macro_export]
macro_rules! physics_operator {

    // ── Alias: a named facade over a generic operator ───────────────────────
    //
    // Flow and damage laws are **attributes** of one single physics (cf.
    // `models::plasticity::law`), not extra physics. They nonetheless read better
    // named at the call site — `drucker_prager(fespace, k, strain_measure)` rather
    // than `plasticity(fespace, k, PlasticLaw::DruckerPrager, strain_measure)`. The facade
    // duplicates nothing: it forwards to the generic operator.
    //
    // Every such facade is a continuum law, and every continuum law reads a
    // strain measure, so the arm adds it after the declared arguments: Rust
    // passes it explicitly, the Python face takes it as `strain_measure`,
    // `"linear"` unless said otherwise — one name, each language its idiom.
    (
        $(#[$rust_doc:meta])*
        pub fn $name:ident(fespace $(, $arg:ident : $ty:ty)* $(,)?) = $target:path, $fixed:expr;
        python: $py_doc:literal
    ) => {
        $(#[$rust_doc])*
        ///
        /// The Python face defaults `strain_measure` to `StrainMeasure::Linear`.
        pub fn $name(
            fespace: &$crate::containers::finite_element_space::FiniteElementSpace,
            $($arg: $ty,)*
            strain_measure: $crate::ops::element_field::StrainMeasure,
        ) -> $crate::error::Result<$crate::containers::model::Model> {
            $target(fespace, $($arg,)* $fixed, strain_measure)
        }

        #[cfg(feature = "python-api")]
        ::paste::paste! {
        /// The Python face of this physics — generated, never hand-written.
        pub mod [<$name _py>] {
            #[allow(unused_imports)]
            use super::*;

            #[doc = $py_doc]
            #[doc = "\n\n`strain_measure` is the strain the law reads: `\"linear\"` (small \
                     strains, the default), `\"green_lagrange\"` (large rotations) or \
                     `\"hencky\"` (large plastic strains); the stress it writes is the \
                     dual, named after it (`sigma_*`, `S_*`, `T_*`)."]
            #[cfg_attr(feature = "stub-gen", ::pyo3_stub_gen::derive::gen_stub_pyfunction)]
            #[::pyo3::pyfunction]
            #[pyo3(signature = (
                fespace, $($arg,)*
                strain_measure = $crate::ops::element_field::StrainMeasure::Linear
            ))]
            pub fn $name(
                fespace: ::pyo3::PyRef<$crate::py::finite_element_space::PyFiniteElementSpace>,
                $($arg: $ty,)*
                strain_measure: $crate::ops::element_field::StrainMeasure,
            ) -> ::pyo3::PyResult<$crate::py::model::PyModel> {
                Ok($crate::py::model::PyModel {
                    inner: $target(&fespace.inner, $($arg,)* $fixed, strain_measure)?,
                })
            }
        } }
    };
    // ── Physics bearing on a target model ───────────────────────────────────
    //
    // A load introduces no unknown: it writes into the dual row of **another**
    // physics. It therefore needs the model it loads — to check there that the
    // row exists and to inherit its nature, which the row name alone is not
    // enough to settle. The fespace stays first: it is what one sweeps, and
    // the target is only one more argument.
    (
        $(#[$rust_doc:meta])*
        pub fn $name:ident(fespace, target $(, $arg:ident : $ty:ty)* $(,)?) via $sub:path;
        python: $py_doc:literal
    ) => {
        $(#[$rust_doc])*
        pub fn $name(
            fespace: &$crate::containers::finite_element_space::FiniteElementSpace,
            target: &$crate::containers::model::Model,
            $($arg: $ty,)*
        ) -> $crate::error::Result<$crate::containers::model::Model> {
            #[allow(clippy::clone_on_copy)]
            $crate::ops::model::spanning(fespace, |zone| $sub(zone, target $(, $arg.clone())*))
        }

        #[cfg(feature = "python-api")]
        ::paste::paste! {
        /// The Python face of this physics — generated, never hand-written.
        pub mod [<$name _py>] {
            #[allow(unused_imports)]
            use super::*;

            #[doc = $py_doc]
            #[cfg_attr(feature = "stub-gen", ::pyo3_stub_gen::derive::gen_stub_pyfunction)]
            #[::pyo3::pyfunction]
            pub fn $name(
                fespace: ::pyo3::PyRef<$crate::py::finite_element_space::PyFiniteElementSpace>,
                target: ::pyo3::PyRef<$crate::py::model::PyModel>,
                $($arg: $ty,)*
            ) -> ::pyo3::PyResult<$crate::py::model::PyModel> {
                Ok($crate::py::model::PyModel {
                    inner: super::$name(&fespace.inner, &target.inner $(, $arg)*)?,
                })
            }
        } }
    };
    // ── Physics on its FE space alone ───────────────────────────────────────
    //
    // An argument may carry a **Python** default (`arg: T = default`): Rust has
    // no default arguments, so its caller passes it explicitly, while the
    // Python face takes it as a keyword — one name, each language its idiom.
    (
        $(#[$rust_doc:meta])*
        pub fn $name:ident(fespace $(, $arg:ident : $ty:ty $(= $default:expr)?)* $(,)?) via $sub:path;
        python: $py_doc:literal
    ) => {
        $(#[$rust_doc])*
        $($(
            #[doc = ""]
            #[doc = concat!(
                "The Python face defaults `", stringify!($arg), "` to `", stringify!($default), "`."
            )]
        )?)*
        pub fn $name(
            fespace: &$crate::containers::finite_element_space::FiniteElementSpace,
            $($arg: $ty,)*
        ) -> $crate::error::Result<$crate::containers::model::Model> {
            // A non-`Copy` argument (`Vec<(String, String)>`) would be moved at
            // the first zone: the closure is `FnMut`, it sees several. So we
            // clone, which costs nothing on the enums.
            #[allow(clippy::clone_on_copy)]
            $crate::ops::model::spanning(fespace, |zone| $sub(zone $(, $arg.clone())*))
        }

        #[cfg(feature = "python-api")]
        ::paste::paste! {
        /// The Python face of this physics — generated, never hand-written.
        pub mod [<$name _py>] {
            // The argument types are written in the scope of the physics' own
            // file; a physics without arguments imports none.
            #[allow(unused_imports)]
            use super::*;

            #[doc = $py_doc]
            #[cfg_attr(feature = "stub-gen", ::pyo3_stub_gen::derive::gen_stub_pyfunction)]
            #[::pyo3::pyfunction]
            #[pyo3(signature = (fespace $(, $arg $(= $default)?)*))]
            pub fn $name(
                fespace: ::pyo3::PyRef<$crate::py::finite_element_space::PyFiniteElementSpace>,
                $($arg: $ty,)*
            ) -> ::pyo3::PyResult<$crate::py::model::PyModel> {
                Ok($crate::py::model::PyModel {
                    inner: super::$name(&fespace.inner $(, $arg)*)?,
                })
            }
        } }
    };
}