section-properties 0.2.0

Structural cross-section properties: geometric/principal moments, section moduli, warping/torsion FEM, plastic, cold-formed, and fire analysis.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
//! 2D Euler-Bernoulli Beam FEM
//!
//! Implements a 2D frame/beam element with 3 DOF per node: [u, v, θ]
//! where u = axial displacement, v = transverse displacement, θ = rotation.
//!
//! The element has 6 DOF total: [u_i, v_j, θ_i, u_j, v_j, θ_j]
//!
//! Uses engineering-mnemonic local variable names (`L`, `E`, `A`, `I`, `P`,
//! `T`, `N1`..`N4`, etc.) throughout, so `non_snake_case` is allowed here.
#![allow(non_snake_case)]

use crate::fea::{
    SparseMatrix,
    solver::{LinearSolver, SolverError, SolverRegistry, SolverSelection},
};
use crate::geometry::Point;
use crate::material::Material;

/// Beam cross-section properties for 2D Euler-Bernoulli beam
#[derive(Debug, Clone, Copy)]
pub struct BeamSection {
    /// Cross-sectional area `m²`
    pub area: f64,
    /// Second moment of area about local z-axis (bending in local x-y plane) `m⁴`
    pub second_moment: f64,
}

impl BeamSection {
    /// Create a new beam section
    pub fn new(area: f64, second_moment: f64) -> Self {
        Self {
            area,
            second_moment,
        }
    }

    /// Create from a rectangle section
    pub fn rectangle(width: f64, height: f64) -> Self {
        let area = width * height;
        let second_moment = width * height.powi(3) / 12.0;
        Self {
            area,
            second_moment,
        }
    }

    /// Create from a circular section
    pub fn circle(radius: f64) -> Self {
        let area = std::f64::consts::PI * radius * radius;
        let second_moment = std::f64::consts::PI * radius.powi(4) / 4.0;
        Self {
            area,
            second_moment,
        }
    }

    /// Create from a circular hollow section
    pub fn circle_hollow(outer_radius: f64, inner_radius: f64) -> Self {
        let area =
            std::f64::consts::PI * (outer_radius * outer_radius - inner_radius * inner_radius);
        let second_moment =
            std::f64::consts::PI * (outer_radius.powi(4) - inner_radius.powi(4)) / 4.0;
        Self {
            area,
            second_moment,
        }
    }

    /// Create from [`crate::SectionProperties`] for a beam aligned with the
    /// **global x-axis**.
    ///
    /// The second moment of area is `props.ix = ∫y² dA`, which resists
    /// bending in the global x-y plane about the z-axis — the correct
    /// inertia for a horizontal member whose local x coincides with global x.
    ///
    /// For a vertical member (local x = global y), use
    /// [`Self::from_section_properties_y`] instead. A blind
    /// `From<SectionProperties>` implementation is intentionally **not**
    /// provided because choosing the wrong axis produces silently incorrect
    /// results.
    pub fn from_section_properties_x(props: &crate::section_properties::SectionProperties) -> Self {
        Self {
            area: props.area,
            second_moment: props.ix,
        }
    }

    /// Create from [`crate::SectionProperties`] for a beam aligned with the
    /// **global y-axis**.
    ///
    /// The second moment of area is `props.iy = ∫x² dA`, which resists
    /// bending in the global x-y plane about the z-axis — the correct
    /// inertia for a vertical member whose local x coincides with global y.
    ///
    /// For a horizontal member (local x = global x), use
    /// [`Self::from_section_properties_x`] instead.
    pub fn from_section_properties_y(props: &crate::section_properties::SectionProperties) -> Self {
        Self {
            area: props.area,
            second_moment: props.iy,
        }
    }
}

/// Internal section forces `N`, `V`, `M` at a point along a beam element.
///
/// All quantities below are expressed in the element's LOCAL coordinate
/// system (see [`BeamElement::local_stiffness`] for the local axes and DOF
/// ordering).
///
/// # Sign convention
///
/// - [`axial`](Self::axial): axial internal force, **tension positive** —
///   positive pulls the material apart along +x, the `node_i -> node_j`
///   direction.
/// - [`shear`](Self::shear): transverse shear internal force, defined so that
///   `d(moment)/dx = shear` and `d(shear)/dx = q`, where `q` is the local
///   transverse load intensity (positive upward, i.e. local +y). Equivalently,
///   with `q_down` = downward load per length, `d(shear)/dx = -q_down`.
/// - [`moment`](Self::moment): bending moment, **sagging positive**
///   (`moment = E·I·v''` for a horizontal element with local +y up).
///
/// These are internal *resultants at a section*, and are a different concept
/// from the element-on-node equilibrium forces returned by
/// [`BeamSolver::element_end_forces`]. At the element ends the two are related
/// by explicit sign factors documented on
/// [`BeamSolver::element_section_forces`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SectionForces {
    /// Axial internal force (tension positive) `N`
    pub axial: f64,
    /// Transverse shear internal force `N`; satisfies `d(moment)/dx = shear`
    pub shear: f64,
    /// Bending moment (sagging positive) `Nm`
    pub moment: f64,
}

impl SectionForces {
    /// Create a section-force triple
    pub fn new(axial: f64, shear: f64, moment: f64) -> Self {
        Self {
            axial,
            shear,
            moment,
        }
    }
}

/// One sampled point of a beam internal-force diagram.
///
/// Produced by [`BeamSolver::sample_element_forces`] and
/// [`BeamSolver::sample_beam_forces`]. The sample is a thin record over
/// [`SectionForces`]; the diagram API samples
/// [`BeamSolver::element_section_forces`] and never interpolates nodal forces.
///
/// # Coordinates
///
/// - [`element_index`](Self::element_index): element index in the model
///   (`BeamModel::elements` order).
/// - [`xi`](Self::xi): element-local normalized coordinate in `[0, 1]`
///   (`xi = 0` at the element's `node_i`, `xi = 1` at `node_j`).
/// - [`x`](Self::x): beam arclength measured from the start of element 0
///   (element 0's `node_i`), accumulated in model order:
///   `x = Σ_{e < element_index} length(e) + xi · length(element_index)`.
///   This is a physical beam distance, not an element-local coordinate, so
///   adjacent elements produce **duplicate** `x` values at a shared node
///   (element `i` at `xi = 1` and element `i+1` at `xi = 0`). Duplicates are
///   intentional and are never removed.
///
/// # Section forces
///
/// [`section_forces`](Self::section_forces) are the beam-LOCAL `N`, `V`, `M`
/// from [`SectionForces`] (same sign convention; not transformed to global
/// axes). At an interior point load they follow the existing left-limit
/// convention of [`BeamSolver::element_section_forces`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BeamForceSample {
    /// Element index in model order.
    pub element_index: usize,
    /// Element-local normalized coordinate, `0` at `node_i`, `1` at `node_j`.
    pub xi: f64,
    /// Beam arclength from the start of element 0 (see type docs).
    pub x: f64,
    /// Local section forces `N`, `V`, `M` at this sample.
    pub section_forces: SectionForces,
}

/// A sampled beam internal-force diagram (recoverable via
/// [`BeamSolver::beam_force_diagram`]).
///
/// This is a plain container of [`BeamForceSample`] points in model order. It
/// deliberately performs **no** interpolation, and exposes no plotting or GUI
/// functionality; a future visualization layer consumes [`samples`](Self::samples)
/// (each carrying its own `x` coordinate) directly.
#[derive(Debug, Clone)]
pub struct BeamForceDiagram {
    /// Samples in model order, element by element.
    pub samples: Vec<BeamForceSample>,
}

impl BeamForceDiagram {
    /// Create a diagram from pre-computed samples.
    pub fn new(samples: Vec<BeamForceSample>) -> Self {
        Self { samples }
    }

    /// Axial force `N` at every sample, in `samples` order.
    pub fn axial(&self) -> Vec<f64> {
        self.samples
            .iter()
            .map(|s| s.section_forces.axial)
            .collect()
    }

    /// Shear force `V` at every sample, in `samples` order.
    pub fn shear(&self) -> Vec<f64> {
        self.samples
            .iter()
            .map(|s| s.section_forces.shear)
            .collect()
    }

    /// Bending moment `M` at every sample, in `samples` order.
    pub fn moment(&self) -> Vec<f64> {
        self.samples
            .iter()
            .map(|s| s.section_forces.moment)
            .collect()
    }

    /// Beam arclength `x` at every sample, in `samples` order.
    pub fn x(&self) -> Vec<f64> {
        self.samples.iter().map(|s| s.x).collect()
    }
}

/// Nodal displacement of a beam node, in the GLOBAL coordinate system.
///
/// DOF ordering follows the rest of the beam module: `ux` (global x),
/// `uy` (global y), `rz` (rotation about global z, counter-clockwise
/// positive). Values are given in the user's consistent unit system. They are
/// **not** rotated into element-local axes.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BeamNodalDisplacement {
    /// Displacement along global +x.
    pub ux: f64,
    /// Displacement along global +y.
    pub uy: f64,
    /// Rotation about global +z (counter-clockwise positive).
    pub rz: f64,
}

/// External support reaction at a constrained beam node, in the GLOBAL
/// coordinate system.
///
/// A reaction is the force/moment the support supplies to hold a constrained
/// DOF. It is a different concept from an element-on-node end force
/// ([`BeamSolver::element_end_forces`]) and from a section internal force
/// ([`SectionForces`]).
///
/// Only constrained DOFs contribute a reaction; unconstrained DOFs are
/// reported as exactly `0.0` (see [`BeamAnalysisResult::reaction`]). Signs are
/// such that, at global equilibrium, `Σ reactions + Σ applied loads = 0`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BeamReaction {
    /// Reaction force along global +x.
    pub fx: f64,
    /// Reaction force along global +y.
    pub fy: f64,
    /// Reaction moment about global +z (counter-clockwise positive).
    pub mz: f64,
}

/// Unified, read-only result view of an already-solved [`BeamSolver`].
///
/// Create one with [`BeamSolver::results`]. It is a thin **aggregation /
/// delegation layer**: every quantity is produced by the existing solver
/// methods, and none of the FEM mathematics is reimplemented here.
///
/// # When the solve happens
///
/// Constructing a `BeamAnalysisResult` does **not** solve anything. Call
/// [`BeamSolver::solve`] first; the result reflects the solver's current
/// displacement state.
///
/// # The three force concepts (kept distinct on purpose)
///
/// 1. **Support reaction** — [`BeamReaction`] / [`Self::reaction`]: the
///    external force supplied by a *support* at a constrained DOF (global
///    coordinates).
/// 2. **Element-on-node end force** — [`Self::element_end_forces`]: the 6
///    element equilibrium forces `[N_i, V_i, M_i, N_j, V_j, M_j]` acting at an
///    element's two nodes (local coordinates).
/// 3. **Section internal force** — [`Self::section_forces`]: the internal
///    resultants `N`, `V`, `M` at an arbitrary point `xi` inside an element
///    (local coordinates).
///
/// These are intentionally exposed through different types/methods and must
/// not be conflated.
///
/// # Ownership / cost
///
/// The result borrows the solver (`&BeamSolver`) and snapshots the reaction
/// vector once at construction; it never copies stiffness matrices. Accessors
/// are cheap: displacements are O(1), reactions are O(1) lookups into the
/// snapshot, and element/section/sampling calls delegate to the solver (they
/// perform the same work as the corresponding solver methods).
#[derive(Clone)]
pub struct BeamAnalysisResult<'a> {
    solver: &'a BeamSolver,
    /// Global reaction snapshot, length `n_dof`, with unconstrained DOFs set
    /// to exactly zero.
    reactions: Vec<f64>,
}

impl std::fmt::Debug for BeamAnalysisResult<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BeamAnalysisResult")
            .field("nodes", &self.solver.model.nodes.len())
            .field("elements", &self.solver.model.elements.len())
            .finish_non_exhaustive()
    }
}

impl<'a> BeamAnalysisResult<'a> {
    /// Number of nodes in the analysed model.
    pub fn n_nodes(&self) -> usize {
        self.solver.model.nodes.len()
    }

    /// Number of elements in the analysed model.
    pub fn n_elements(&self) -> usize {
        self.solver.model.elements.len()
    }

    /// Name of the linear-solver backend used by the solve that produced this
    /// result (`"dense"`, `"skyline_ldlt"`, `"sparse_lu"`, `"cg"`, `"iccg"`,
    /// ...), or `None` if no linear system was solved (e.g. fully constrained).
    pub fn solver_name(&self) -> Option<&str> {
        self.solver.solver_name()
    }

    /// Raw global displacement vector, DOF-ordered
    /// `[ux0, uy0, rz0, ux1, uy1, rz1, ...]`.
    ///
    /// This is a borrowed view into the solver (no copy).
    pub fn displacements(&self) -> &[f64] {
        &self.solver.u_global
    }

    /// Nodal displacement (GLOBAL) at `node_index`.
    ///
    /// # Errors
    ///
    /// [`FemError::InvalidInput`] if `node_index` is out of bounds.
    pub fn displacement(&self, node_index: usize) -> Result<BeamNodalDisplacement, FemError> {
        if node_index >= self.solver.model.nodes.len() {
            return Err(FemError::InvalidInput(format!(
                "Invalid node index: {} (max: {})",
                node_index,
                self.solver.model.nodes.len().saturating_sub(1)
            )));
        }
        Ok(BeamNodalDisplacement {
            ux: self.solver.displacement(node_index, 0)?,
            uy: self.solver.displacement(node_index, 1)?,
            rz: self.solver.displacement(node_index, 2)?,
        })
    }

    /// Support reaction (GLOBAL) at `node_index`.
    ///
    /// Only constrained DOFs carry a value; unconstrained DOFs are reported as
    /// exactly `0.0` (the raw residual `K·u - f` at a free DOF is numerical
    /// round-off and is not a physical support reaction). At a node that is not
    /// a support, all three components are therefore `0.0`.
    ///
    /// # Errors
    ///
    /// [`FemError::InvalidInput`] if `node_index` is out of bounds.
    pub fn reaction(&self, node_index: usize) -> Result<BeamReaction, FemError> {
        if node_index >= self.solver.model.nodes.len() {
            return Err(FemError::InvalidInput(format!(
                "Invalid node index: {} (max: {})",
                node_index,
                self.solver.model.nodes.len().saturating_sub(1)
            )));
        }
        let base = self.solver.model.dof_index(node_index, 0);
        Ok(BeamReaction {
            fx: self.reactions[base],
            fy: self.reactions[base + 1],
            mz: self.reactions[base + 2],
        })
    }

    /// Element-on-node end forces in LOCAL coordinates for `element_index`:
    /// `[N_i, V_i, M_i, N_j, V_j, M_j]`.
    ///
    /// Delegates to the same recovery used by
    /// [`BeamSolver::element_end_forces`].
    ///
    /// # Errors
    ///
    /// [`FemError::InvalidInput`] if `element_index` is out of bounds.
    pub fn element_end_forces(&self, element_index: usize) -> Result<[f64; 6], FemError> {
        self.solver.element_on_node_end_forces_local(element_index)
    }

    /// Section internal forces `N`, `V`, `M` (LOCAL) at `(element_index, xi)`.
    ///
    /// Thin delegation to [`BeamSolver::element_section_forces`] (single
    /// source of truth for the N/V/M equations).
    ///
    /// # Errors
    ///
    /// Same as [`BeamSolver::element_section_forces`].
    pub fn section_forces(&self, element_index: usize, xi: f64) -> Result<SectionForces, FemError> {
        self.solver.element_section_forces(element_index, xi)
    }

    /// Whole-beam force samples (Phase 2.5).
    ///
    /// Delegates to [`BeamSolver::sample_beam_forces`].
    ///
    /// # Errors
    ///
    /// Same as [`BeamSolver::sample_beam_forces`].
    pub fn sample_forces(&self, n_per_element: usize) -> Result<Vec<BeamForceSample>, FemError> {
        self.solver.sample_beam_forces(n_per_element)
    }

    /// Whole-beam force diagram (Phase 2.5).
    ///
    /// Delegates to [`BeamSolver::beam_force_diagram`].
    ///
    /// # Errors
    ///
    /// Same as [`BeamSolver::beam_force_diagram`].
    pub fn diagram(&self, n_per_element: usize) -> Result<BeamForceDiagram, FemError> {
        self.solver.beam_force_diagram(n_per_element)
    }
}

/// 2D Euler–Bernoulli beam element between two nodes.
///
/// Local axes: x from `node_i` to `node_j`, y transverse (positive up), with
/// counter-clockwise rotation. Element end forces are ordered
/// `[N_i, V_i, M_i, N_j, V_j, M_j]` in these local axes; see
/// [`BeamSolver::element_end_forces`] for the recovery formula.
#[derive(Debug, Clone)]
pub struct BeamElement {
    /// Node i index
    pub node_i: usize,
    /// Node j index
    pub node_j: usize,
    /// Material
    pub material: Material,
    /// Cross-section properties
    pub section: BeamSection,
}

impl BeamElement {
    /// Create a new beam element
    pub fn new(
        node_i: usize,
        node_j: usize,
        material: Material,
        section: BeamSection,
    ) -> Result<Self, FemError> {
        if node_i == node_j {
            return Err(FemError::InvalidModel(
                "Beam element cannot have same start and end node".to_string(),
            ));
        }
        Ok(Self {
            node_i,
            node_j,
            material,
            section,
        })
    }

    /// Get element length from node coordinates
    pub fn length(&self, node_i: Point, node_j: Point) -> f64 {
        let dx = node_j.x - node_i.x;
        let dy = node_j.y - node_i.y;
        (dx * dx + dy * dy).sqrt()
    }

    /// Compute local stiffness matrix (6x6) in local coordinates
    ///
    /// Local DOF ordering: [u_i, v_i, θ_i, u_j, v_j, θ_j]
    ///
    /// Returns a 6x6 matrix in row-major order (`Vec<Vec<f64>>`)
    pub fn local_stiffness(&self, node_i: Point, node_j: Point) -> [[f64; 6]; 6] {
        let L = self.length(node_i, node_j);
        if L <= 0.0 {
            return [[0.0; 6]; 6];
        }

        let E = self.material.youngs_modulus;
        let A = self.section.area;
        let I = self.section.second_moment;

        let EA_L = E * A / L;
        let EI_L3 = E * I / L.powi(3);
        let EI_L2 = E * I / L.powi(2);
        let EI_L = E * I / L;

        // Standard 2D Euler-Bernoulli beam stiffness matrix
        // DOF order: [u_i, v_i, θ_i, u_j, v_j, θ_j]
        let mut k = [[0.0; 6]; 6];

        // Axial terms
        k[0][0] = EA_L;
        k[0][3] = -EA_L;
        k[3][0] = -EA_L;
        k[3][3] = EA_L;

        // Bending terms
        // v_i terms
        k[1][1] = 12.0 * EI_L3;
        k[1][2] = 6.0 * EI_L2;
        k[1][4] = -12.0 * EI_L3;
        k[1][5] = 6.0 * EI_L2;

        // θ_i terms
        k[2][1] = 6.0 * EI_L2;
        k[2][2] = 4.0 * EI_L;
        k[2][4] = -6.0 * EI_L2;
        k[2][5] = 2.0 * EI_L;

        // v_j terms
        k[4][1] = -12.0 * EI_L3;
        k[4][2] = -6.0 * EI_L2;
        k[4][4] = 12.0 * EI_L3;
        k[4][5] = -6.0 * EI_L2;

        // θ_j terms
        k[5][1] = 6.0 * EI_L2;
        k[5][2] = 2.0 * EI_L;
        k[5][4] = -6.0 * EI_L2;
        k[5][5] = 4.0 * EI_L;

        k
    }

    /// Compute coordinate transformation matrix (6x6)
    ///
    /// Transforms from local to global coordinates
    /// Local DOF: [u_i, v_i, θ_i, u_j, v_j, θ_j]
    /// Global DOF: [U_i, V_i, Θ_i, U_j, V_j, Θ_j]
    pub fn transformation_matrix(&self, node_i: Point, node_j: Point) -> [[f64; 6]; 6] {
        let dx = node_j.x - node_i.x;
        let dy = node_j.y - node_i.y;
        let L = (dx * dx + dy * dy).sqrt();

        if L <= 0.0 {
            return [[0.0; 6]; 6];
        }

        let c = dx / L;
        let s = dy / L;

        // Transformation matrix T (6x6)
        // [ c  s  0  0  0  0 ]
        // [-s  c  0  0  0  0 ]
        // [ 0  0  1  0  0  0 ]
        // [ 0  0  0  c  s  0 ]
        // [ 0  0  0 -s  c  0 ]
        // [ 0  0  0  0  0  1 ]
        let mut T = [[0.0; 6]; 6];

        // Node i block
        T[0][0] = c;
        T[0][1] = s;
        T[1][0] = -s;
        T[1][1] = c;
        T[2][2] = 1.0;

        // Node j block
        T[3][3] = c;
        T[3][4] = s;
        T[4][3] = -s;
        T[4][4] = c;
        T[5][5] = 1.0;

        T
    }

    /// Rotate a **global** force (or load-intensity) vector into this element's
    /// **local** axes.
    ///
    /// Distributed loads and point loads are specified in LOCAL coordinates
    /// (local x along `node_i -> node_j`, local y transverse), while nodal
    /// forces are global — see `docs/beam_fem.md`. Use this helper when your
    /// input data is global, e.g.
    ///
    /// ```text
    /// let (qx, qy) = element.to_local_force(ni, nj, gx, gy)?;
    /// model.add_distributed_load(elem, qx, qy)?;
    /// ```
    ///
    /// A load intensity (N/m) transforms exactly like a force (N), so the same
    /// helper applies to both. This is a pure coordinate rotation: it changes
    /// no FEM convention and performs no calculation on the model.
    pub fn to_local_force(&self, node_i: Point, node_j: Point, gx: f64, gy: f64) -> (f64, f64) {
        let t = self.transformation_matrix(node_i, node_j);
        // u_local = T · u_global, restricted to the translational block:
        //   fx_local =  c·gx + s·gy
        //   fy_local = -s·gx + c·gy
        (t[0][0] * gx + t[0][1] * gy, t[1][0] * gx + t[1][1] * gy)
    }

    /// Element stiffness matrix (6x6) in **GLOBAL** coordinates.
    ///
    /// `k_global = Tᵀ · k_local · T`, with the DOF order
    /// `[ux_i, uy_i, rz_i, ux_j, uy_j, rz_j]` (global axes).
    pub fn global_stiffness(&self, node_i: Point, node_j: Point) -> [[f64; 6]; 6] {
        let k_local = self.local_stiffness(node_i, node_j);
        let T = self.transformation_matrix(node_i, node_j);

        // k_global = T^T * k_local * T
        let mut k_global = [[0.0; 6]; 6];

        for i in 0..6 {
            for j in 0..6 {
                let mut sum = 0.0;
                for k in 0..6 {
                    for l in 0..6 {
                        sum += T[k][i] * k_local[k][l] * T[l][j];
                    }
                }
                k_global[i][j] = sum;
            }
        }

        k_global
    }

    /// Compute consistent nodal load vector for uniform distributed load (6 DOF) in LOCAL coordinates
    ///
    /// Local DOF ordering: [u_i, v_i, θ_i, u_j, v_j, θ_j]
    /// Sign convention:
    /// - qx > 0: tensile axial load (pulling beam in +x direction)
    /// - qy > 0: upward transverse load (in +y direction)
    ///
    /// Returns a 6-element vector in local coordinates
    pub fn consistent_nodal_load(
        &self,
        node_i: Point,
        node_j: Point,
        qx: f64,
        qy: f64,
    ) -> Result<[f64; 6], FemError> {
        let L = self.length(node_i, node_j);
        if L <= 0.0 {
            return Err(FemError::InvalidInput(
                "Beam element has zero or negative length for distributed load".to_string(),
            ));
        }

        // Consistent nodal load vector for uniform distributed load
        // Axial (qx): linear shape functions
        // f_u_i = qx * L / 2, f_u_j = qx * L / 2
        //
        // Transverse (qy): Hermite cubic shape functions
        // f_v_i = qy * L / 2
        // f_θ_i = qy * L^2 / 12  (positive = counterclockwise in local coords)
        // f_v_j = qy * L / 2
        // f_θ_j = -qy * L^2 / 12 (negative = clockwise in local coords)
        //
        // Note: Local v is positive upward, local θ is positive counterclockwise
        let qx_L2 = qx * L / 2.0;
        let qy_L2 = qy * L / 2.0;
        let qy_L2_12 = qy * L * L / 12.0;

        Ok([
            qx_L2,     // u_i: axial
            qy_L2,     // v_i: transverse
            qy_L2_12,  // θ_i: moment (CCW positive)
            qx_L2,     // u_j: axial
            qy_L2,     // v_j: transverse
            -qy_L2_12, // θ_j: moment (CW negative)
        ])
    }

    /// Compute consistent nodal load vector for a point load at given position (6 DOF) in LOCAL coordinates
    ///
    /// Local DOF ordering: [u_i, v_i, θ_i, u_j, v_j, θ_j]
    /// Position is measured from node_i (0.0) to node_j (1.0)
    /// Sign convention:
    /// - fx > 0: tensile axial force (pulling in +x direction)
    /// - fy > 0: upward transverse force (in +y direction)
    /// - mz > 0: counterclockwise moment about z-axis (positive θ direction)
    ///
    /// Uses shape functions:
    /// - Axial: linear shape functions N1 = 1-ξ, N2 = ξ
    /// - Transverse: Hermite cubic shape functions
    /// - Moment: shape functions for moment
    pub fn consistent_nodal_load_point(
        &self,
        node_i: Point,
        node_j: Point,
        position: f64,
        fx: f64,
        fy: f64,
        mz: f64,
    ) -> Result<[f64; 6], FemError> {
        let L = self.length(node_i, node_j);
        if L <= 0.0 {
            return Err(FemError::InvalidInput(
                "Beam element has zero or negative length for point load".to_string(),
            ));
        }
        if !(0.0..=1.0).contains(&position) {
            return Err(FemError::InvalidInput(format!(
                "Point load position must be in [0, 1], got {}",
                position
            )));
        }

        let xi = position; // normalized position
        let one_minus_xi = 1.0 - xi;

        // Axial: linear shape functions
        // N1 = 1-ξ, N2 = ξ
        // f_u_i = fx * (1-ξ), f_u_j = fx * ξ
        let f_u_i = fx * one_minus_xi;
        let f_u_j = fx * xi;

        // Transverse: Hermite cubic shape functions
        // N1 = 1 - 3ξ² + 2ξ³
        // N2 = L(ξ - 2ξ² + ξ³)
        // N3 = 3ξ² - 2ξ³
        // N4 = L(-ξ² + ξ³)
        let xi2 = xi * xi;
        let xi3 = xi2 * xi;

        let N1 = 1.0 - 3.0 * xi2 + 2.0 * xi3;
        let N2 = L * (xi - 2.0 * xi2 + xi3);
        let N3 = 3.0 * xi2 - 2.0 * xi3;
        let N4 = L * (-xi2 + xi3);

        // f_v_i = fy * N1, f_θ_i = fy * N2
        // f_v_j = fy * N3, f_θ_j = fy * N4
        let f_v_i = fy * N1;
        let f_theta_i = fy * N2;
        let f_v_j = fy * N3;
        let f_theta_j = fy * N4;

        // Moment: shape functions for applied moment (from virtual work: δW = M * δθ(x_p))
        // Rotation shape functions: θ(x) = dN1/dx * v_i + dN2/dx * θ_i + dN3/dx * v_j + dN4/dx * θ_j
        // M1 = dN1/dx = (6/L)(ξ² - ξ) = -(6/L)ξ(1-ξ)
        // M2 = dN2/dx = 1 - 4ξ + 3ξ²
        // M3 = dN3/dx = (6/L)(ξ - ξ²) = (6/L)ξ(1-ξ)
        // M4 = dN4/dx = -2ξ + 3ξ²
        // For a point moment mz at ξ, the equivalent nodal loads are:
        // f_v_i = mz * M1 = -6mz/L * ξ(1-ξ)
        // f_θ_i = mz * M2 = mz * (1 - 4ξ + 3ξ²)
        // f_v_j = mz * M3 = 6mz/L * ξ(1-ξ)
        // f_θ_j = mz * M4 = mz * (-2ξ + 3ξ²)
        let one_minus_xi = 1.0 - xi;
        let f_v_i_moment = mz * (-6.0 * xi * one_minus_xi / L); // M1 = -(6/L)ξ(1-ξ)
        let f_theta_i_moment = mz * (1.0 - 4.0 * xi + 3.0 * xi2); // M2 = 1 - 4ξ + 3ξ²
        let f_v_j_moment = mz * (6.0 * xi * one_minus_xi / L); // M3 = (6/L)ξ(1-ξ)
        let f_theta_j_moment = mz * (-2.0 * xi + 3.0 * xi2); // M4 = -2ξ + 3ξ²

        Ok([
            f_u_i,                        // u_i: axial
            f_v_i + f_v_i_moment,         // v_i: transverse + moment
            f_theta_i + f_theta_i_moment, // θ_i: rotation + moment
            f_u_j,                        // u_j: axial
            f_v_j + f_v_j_moment,         // v_j: transverse + moment
            f_theta_j + f_theta_j_moment, // θ_j: rotation + moment
        ])
    }
}

/// Beam node with 3 DOF: [u, v, θ]
#[derive(Debug, Clone, Copy)]
pub struct BeamNode {
    /// Node index
    pub id: usize,
    /// X coordinate
    pub x: f64,
    /// Y coordinate
    pub y: f64,
}

impl BeamNode {
    pub fn new(id: usize, x: f64, y: f64) -> Self {
        Self { id, x, y }
    }

    pub fn point(&self) -> Point {
        Point::new(self.x, self.y)
    }
}

/// Distributed load on a beam element in LOCAL coordinates
///
/// Local coordinate system:
/// - x axis: along beam from node_i to node_j (axial direction)
/// - y axis: transverse direction (positive v)
/// - z axis: out of plane (rotation θ about z)
///
/// Sign convention:
/// - qx > 0: tensile axial load (pulling beam in +x direction)
/// - qy > 0: upward transverse load (in +y direction)
#[derive(Debug, Clone, Copy)]
pub struct DistributedLoad {
    /// Element index (index in elements Vec)
    pub element_idx: usize,
    /// Uniform axial load per unit length [N/m] in local x direction
    pub qx: f64,
    /// Uniform transverse load per unit length [N/m] in local y direction
    pub qy: f64,
}

impl DistributedLoad {
    /// Create a new distributed load on an element
    pub fn new(element_idx: usize, qx: f64, qy: f64) -> Self {
        Self {
            element_idx,
            qx,
            qy,
        }
    }

    /// Uniform transverse load only (`qy`), in **LOCAL** element coordinates
    /// (`qy > 0` upward in local +y).
    pub fn transverse(element_idx: usize, qy: f64) -> Self {
        Self {
            element_idx,
            qx: 0.0,
            qy,
        }
    }

    /// Uniform axial load only (`qx`), in **LOCAL** element coordinates
    /// (`qx > 0` tensile, towards `node_j`).
    pub fn axial(element_idx: usize, qx: f64) -> Self {
        Self {
            element_idx,
            qx,
            qy: 0.0,
        }
    }
}

/// Point load applied at a specific position along an element in LOCAL coordinates
///
/// Local coordinate system:
/// - x axis: along beam from node_i to node_j (axial direction)
/// - y axis: transverse direction (positive v)
/// - z axis: out of plane (rotation θ about z)
///
/// Position is measured from node_i (x=0) to node_j (x=L)
///
/// Sign convention:
/// - fx > 0: tensile axial force (pulling in +x direction)
/// - fy > 0: upward transverse force (in +y direction)
/// - mz > 0: counterclockwise moment about z-axis (positive θ direction)
#[derive(Debug, Clone, Copy)]
pub struct PointLoad {
    /// Element index (index in elements Vec)
    pub element_idx: usize,
    /// Position along element from node_i (0.0 = node_i, 1.0 = node_j)
    pub position: f64,
    /// Axial force `N` in local x direction
    pub fx: f64,
    /// Transverse force `N` in local y direction
    pub fy: f64,
    /// Moment `Nm` about local z axis (positive = CCW)
    pub mz: f64,
}

impl PointLoad {
    /// Create a new point load on an element
    pub fn new(element_idx: usize, position: f64, fx: f64, fy: f64, mz: f64) -> Self {
        Self {
            element_idx,
            position,
            fx,
            fy,
            mz,
        }
    }

    /// Create a transverse point force only, in **LOCAL** element coordinates
    /// (`fy > 0` upward in local +y).
    pub fn transverse_force(element_idx: usize, position: f64, fy: f64) -> Self {
        Self {
            element_idx,
            position,
            fx: 0.0,
            fy,
            mz: 0.0,
        }
    }

    /// Create an axial point force only, in **LOCAL** element coordinates
    /// (`fx > 0` tensile, towards `node_j`).
    pub fn axial_force(element_idx: usize, position: f64, fx: f64) -> Self {
        Self {
            element_idx,
            position,
            fx,
            fy: 0.0,
            mz: 0.0,
        }
    }

    /// Create a point moment only, in **LOCAL** element coordinates
    /// (`mz > 0` counter-clockwise).
    pub fn moment(element_idx: usize, position: f64, mz: f64) -> Self {
        Self {
            element_idx,
            position,
            fx: 0.0,
            fy: 0.0,
            mz,
        }
    }
}

/// Applied moment at a specific node (in GLOBAL coordinates)
///
/// Sign convention:
/// - value > 0: counterclockwise moment (positive θ direction)
#[derive(Debug, Clone, Copy)]
pub struct AppliedMoment {
    /// Node index (index in nodes Vec)
    pub node_idx: usize,
    /// Moment value `Nm` in global coordinates (positive = CCW)
    pub value: f64,
}

impl AppliedMoment {
    pub fn new(node_idx: usize, value: f64) -> Self {
        Self { node_idx, value }
    }
}

/// A single degree of freedom of a beam node.
///
/// Ergonomic typed alternative to the raw `0/1/2` DOF indices used by
/// `BeamModel::dof_index` and [`BeamModel::try_fix_dof`]. The mapping is
/// fixed by the frozen Beam FEM contract (`docs/beam_fem.md`):
///
/// ```text
/// Dof::Ux -> 0   global translation along X
/// Dof::Uy -> 1   global translation along Y
/// Dof::Rz -> 2   global rotation about Z, counter-clockwise positive
/// ```
///
/// This is a naming layer only: the internal representation remains
/// `[ux, uy, rz]` in that order.
///
/// # Examples
///
/// ```rust
/// use section_properties::beam_fem::{BeamModel, BeamNode, Dof};
///
/// // Explicit, checked DOF references instead of raw 0/1/2 indices:
/// let mut model = BeamModel::new();
/// model.add_node(BeamNode::new(0, 0.0, 0.0));
/// model.try_fix(0, Dof::Uy, 0.0).unwrap();
///
/// assert_eq!(Dof::Ux.index(), 0);
/// assert_eq!(Dof::Uy.index(), 1);
/// assert_eq!(Dof::Rz.index(), 2);
/// assert_eq!(Dof::ALL, [Dof::Ux, Dof::Uy, Dof::Rz]);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Dof {
    /// Global translation along X (`ux`).
    Ux,
    /// Global translation along Y (`uy`).
    Uy,
    /// Global rotation about Z (`rz`), counter-clockwise positive.
    Rz,
}

impl Dof {
    /// All three DOFs in the canonical ordering `[ux, uy, rz]`.
    pub const ALL: [Dof; 3] = [Dof::Ux, Dof::Uy, Dof::Rz];

    /// Raw index of this DOF inside a node: `dof(node, d) = 3*node + d`.
    pub const fn index(self) -> usize {
        match self {
            Self::Ux => 0,
            Self::Uy => 1,
            Self::Rz => 2,
        }
    }

    /// Human-readable name (`"ux"`, `"uy"`, `"rz"`).
    pub const fn name(self) -> &'static str {
        match self {
            Self::Ux => "ux",
            Self::Uy => "uy",
            Self::Rz => "rz",
        }
    }
}

impl From<Dof> for usize {
    fn from(dof: Dof) -> Self {
        dof.index()
    }
}

impl TryFrom<usize> for Dof {
    type Error = FemError;

    /// Convert a raw DOF index into a [`Dof`].
    ///
    /// # Errors
    ///
    /// [`FemError::InvalidInput`] if `value` is not 0, 1 or 2.
    fn try_from(value: usize) -> Result<Self, FemError> {
        match value {
            0 => Ok(Self::Ux),
            1 => Ok(Self::Uy),
            2 => Ok(Self::Rz),
            other => Err(FemError::InvalidInput(format!(
                "Invalid DOF: {} (must be 0, 1, or 2)",
                other
            ))),
        }
    }
}

/// Beam model with nodes, elements, loads, and boundary conditions.
///
/// # Conventions
///
/// - Each node has three **global** DOFs `[ux, uy, rz]`, ordered
///   `dof(node, d) = 3*node + d`; `rz` is counter-clockwise positive.
/// - Element local x runs from `node_i` to `node_j`, local y is transverse
///   (positive up so that local rotation is counter-clockwise).
/// - Load coordinate systems differ by kind: [`add_nodal_force`] is global,
///   [`add_distributed_load`] and [`add_point_load`] are **local**,
///   [`add_applied_moment`] is a **global** `theta` load.
///
/// # Snapshot semantics
///
/// [`BeamSolver::from_model`] clones the model and assembles the global
/// stiffness matrix and force vector once. Mutating a `BeamModel` after a
/// solver has been built does not affect that solver; build a new solver to
/// pick up changes. See `docs/beam_fem.md` for the full contract.
///
/// [`add_nodal_force`]: Self::add_nodal_force
/// [`add_distributed_load`]: Self::add_distributed_load
/// [`add_point_load`]: Self::add_point_load
/// [`add_applied_moment`]: Self::add_applied_moment
#[derive(Debug, Clone)]
pub struct BeamModel {
    /// Nodes
    pub nodes: Vec<BeamNode>,
    /// Elements
    pub elements: Vec<BeamElement>,
    /// Nodal forces: (node_idx, dof, value)
    /// dof: 0=u, 1=v, 2=θ
    /// node_idx is the index in the nodes Vec (0, 1, 2, ...)
    pub nodal_forces: Vec<(usize, usize, f64)>,
    /// Distributed loads on elements (in LOCAL coordinates)
    pub distributed_loads: Vec<DistributedLoad>,
    /// Point loads on elements (in LOCAL coordinates)
    pub point_loads: Vec<PointLoad>,
    /// Applied moments at nodes (in GLOBAL coordinates)
    pub applied_moments: Vec<AppliedMoment>,
    /// Fixed DOFs: (node_idx, dof, value) - value is the prescribed displacement (usually 0.0)
    /// node_idx is the index in the nodes Vec (0, 1, 2, ...)
    pub fixed_dofs: Vec<(usize, usize, f64)>,
}

impl BeamModel {
    pub fn new() -> Self {
        Self {
            nodes: Vec::new(),
            elements: Vec::new(),
            nodal_forces: Vec::new(),
            distributed_loads: Vec::new(),
            point_loads: Vec::new(),
            applied_moments: Vec::new(),
            fixed_dofs: Vec::new(),
        }
    }

    pub fn add_node(&mut self, node: BeamNode) {
        self.nodes.push(node);
    }

    pub fn add_element(&mut self, element: BeamElement) {
        self.elements.push(element);
    }

    /// Add nodal force.
    ///
    /// Panics if `node_idx` is out of bounds, `dof` is not 0/1/2, or `value`
    /// is not finite (programmer error). Use [`Self::try_add_nodal_force`] for
    /// a fallible version.
    pub fn add_nodal_force(&mut self, node_idx: usize, dof: usize, value: f64) {
        self.try_add_nodal_force(node_idx, dof, value)
            .unwrap_or_else(|e| panic!("{}", e));
    }

    /// Fallible counterpart of [`Self::add_nodal_force`]: returns a structured
    /// error for an out-of-bounds node index, an invalid DOF (must be 0, 1 or 2),
    /// or a non-finite force value, instead of panicking.
    pub fn try_add_nodal_force(
        &mut self,
        node_idx: usize,
        dof: usize,
        value: f64,
    ) -> Result<(), FemError> {
        if node_idx >= self.nodes.len() {
            return Err(FemError::InvalidInput(format!(
                "Invalid node index: {} (max: {})",
                node_idx,
                self.nodes.len().saturating_sub(1)
            )));
        }
        if dof >= 3 {
            return Err(FemError::InvalidInput(format!(
                "Invalid DOF: {} (must be 0, 1, or 2)",
                dof
            )));
        }
        if !value.is_finite() {
            return Err(FemError::InvalidInput(format!(
                "Nodal force must be finite, got {}",
                value
            )));
        }
        self.nodal_forces.push((node_idx, dof, value));
        Ok(())
    }

    /// Fix a single DOF to a prescribed value.
    ///
    /// Panics if `node_idx` is out of bounds, `dof` is not 0/1/2, `value`
    /// is not finite, or the DOF already has a conflicting prescribed value
    /// (programmer error). Use [`Self::try_fix_dof`] for a fallible version.
    pub fn fix_dof(&mut self, node_idx: usize, dof: usize, value: f64) {
        self.try_fix_dof(node_idx, dof, value)
            .unwrap_or_else(|e| panic!("{}", e));
    }

    /// Fallible counterpart of [`Self::fix_dof`]: returns a structured error for
    /// an out-of-bounds node index, an invalid DOF (must be 0, 1 or 2), a
    /// non-finite prescribed value, or a conflicting existing prescribed
    /// displacement on the same DOF, instead of panicking.
    pub fn try_fix_dof(&mut self, node_idx: usize, dof: usize, value: f64) -> Result<(), FemError> {
        if node_idx >= self.nodes.len() {
            return Err(FemError::InvalidInput(format!(
                "Invalid node index: {} (max: {})",
                node_idx,
                self.nodes.len().saturating_sub(1)
            )));
        }
        if dof >= 3 {
            return Err(FemError::InvalidInput(format!(
                "Invalid DOF: {} (must be 0, 1, or 2)",
                dof
            )));
        }
        if !value.is_finite() {
            return Err(FemError::InvalidInput(format!(
                "Prescribed value must be finite, got {}",
                value
            )));
        }
        for &(n, d, v) in &self.fixed_dofs {
            if n == node_idx && d == dof {
                let scale = (v.abs() + value.abs()).max(1.0);
                if (v - value).abs() > 1e-12 * scale {
                    return Err(FemError::ConflictingPrescribedDisplacement {
                        node_idx,
                        dof,
                        first_value: v,
                        conflicting_value: value,
                    });
                }
                return Ok(());
            }
        }
        self.fixed_dofs.push((node_idx, dof, value));
        Ok(())
    }

    /// Override (upsert) a prescribed displacement: if `(node_idx, dof)` is
    /// already constrained, replace its value; otherwise add a new constraint.
    ///
    /// Unlike [`Self::try_fix_dof`], this does **not** detect conflicting
    /// values — it silently replaces the previous prescription.  Use this when
    /// the caller explicitly intends to override (e.g. applying a support
    /// settlement after a full fix).
    pub fn try_override_dof(
        &mut self,
        node_idx: usize,
        dof: usize,
        value: f64,
    ) -> Result<(), FemError> {
        if node_idx >= self.nodes.len() {
            return Err(FemError::InvalidInput(format!(
                "Invalid node index: {} (max: {})",
                node_idx,
                self.nodes.len().saturating_sub(1)
            )));
        }
        if dof >= 3 {
            return Err(FemError::InvalidInput(format!(
                "Invalid DOF: {} (must be 0, 1, or 2)",
                dof
            )));
        }
        if !value.is_finite() {
            return Err(FemError::InvalidInput(format!(
                "Prescribed value must be finite, got {}",
                value
            )));
        }
        for entry in &mut self.fixed_dofs {
            if entry.0 == node_idx && entry.1 == dof {
                entry.2 = value;
                return Ok(());
            }
        }
        self.fixed_dofs.push((node_idx, dof, value));
        Ok(())
    }

    /// Fix a node completely (all 3 DOFs to 0).
    ///
    /// Panics if `node_idx` is out of bounds or any DOF already has a
    /// conflicting prescribed value (programmer error). Use
    /// [`Self::try_fix_node`] for a fallible version.
    pub fn fix_node(&mut self, node_idx: usize) {
        self.try_fix_node(node_idx)
            .unwrap_or_else(|e| panic!("{}", e));
    }

    /// Fallible counterpart of [`Self::fix_node`]: returns a structured error
    /// for an out-of-bounds node index or a conflicting existing prescribed
    /// displacement on any of the node's DOFs, instead of panicking.
    ///
    /// # Errors
    ///
    /// [`FemError::InvalidInput`] if `node_idx` is out of bounds.
    /// [`FemError::ConflictingPrescribedDisplacement`] if any DOF already
    /// has a conflicting prescribed value.
    pub fn try_fix_node(&mut self, node_idx: usize) -> Result<(), FemError> {
        if node_idx >= self.nodes.len() {
            return Err(FemError::InvalidInput(format!(
                "Invalid node index: {} (max: {})",
                node_idx,
                self.nodes.len().saturating_sub(1)
            )));
        }
        self.try_fix_dof(node_idx, 0, 0.0)?;
        self.try_fix_dof(node_idx, 1, 0.0)?;
        self.try_fix_dof(node_idx, 2, 0.0)?;
        Ok(())
    }

    /// Typed counterpart of [`Self::try_fix_dof`]: constrain `(node_idx, dof)`
    /// to `value`.
    ///
    /// ```text
    /// model.try_fix(0, Dof::Uy, 0.0)?;   // == model.try_fix_dof(0, 1, 0.0)?
    /// ```
    ///
    /// `dof` is always a **global** DOF; there is no local DOF variant. This
    /// delegates to [`Self::try_fix_dof`] and therefore shares the same
    /// boundary-condition storage, validation and static-condensation path.
    ///
    /// # Errors
    ///
    /// [`FemError::InvalidInput`] for an out-of-bounds node index or a
    /// non-finite prescribed value.
    /// [`FemError::ConflictingPrescribedDisplacement`] if the DOF already
    /// has a conflicting prescribed value.
    pub fn try_fix(&mut self, node_idx: usize, dof: Dof, value: f64) -> Result<(), FemError> {
        self.try_fix_dof(node_idx, dof.index(), value)
    }

    /// Typed counterpart of [`Self::try_override_dof`]: override (upsert) the
    /// prescribed displacement for `(node_idx, dof)` to `value`.
    ///
    /// Unlike [`Self::try_fix`], this silently replaces any existing
    /// constraint on the same DOF instead of returning
    /// [`FemError::ConflictingPrescribedDisplacement`].
    pub fn try_override(&mut self, node_idx: usize, dof: Dof, value: f64) -> Result<(), FemError> {
        self.try_override_dof(node_idx, dof.index(), value)
    }

    /// Constrain all three DOFs of a node to the given prescribed values.
    ///
    /// Use this for a prescribed displacement/rotation (e.g. a support
    /// settlement such as `try_fix_node_with_values(0, 0.0, -0.01, 0.0)`); a
    /// fully fixed node is `try_fix_node_with_values(i, 0.0, 0.0, 0.0)`, which
    /// is what [`Self::try_fix_node`] does.
    ///
    /// This is a convenience wrapper: it delegates to [`Self::try_override_dof`]
    /// for `ux`, `uy` and `rz`, so it uses the same boundary-condition storage
    /// and the same static-condensation path. It does not add a second BC
    /// representation and does not change reaction recovery.  Any existing
    /// constraint on the same DOF is **replaced**.
    ///
    /// # Override vs conflict semantics
    ///
    /// Unlike [`Self::try_fix_node`], which delegates to [`Self::try_fix_dof`]
    /// and returns [`FemError::ConflictingPrescribedDisplacement`] when a DOF
    /// already has a different prescribed value, this method **silently
    /// replaces** the existing constraint.  This is intentional: the typical
    /// use case is applying a support settlement after an initial full fix
    /// (`try_fix_node(i)` → `try_fix_node_with_values(i, 0.0, -0.01, 0.0)`),
    /// where the override is the desired behaviour.
    ///
    /// # Errors
    ///
    /// [`FemError::InvalidInput`] for an out-of-bounds node index or any
    /// non-finite prescribed value. All inputs are validated **before** any
    /// boundary condition is recorded, so a rejected call leaves the model
    /// unchanged (no partially fixed node).
    pub fn try_fix_node_with_values(
        &mut self,
        node_idx: usize,
        ux: f64,
        uy: f64,
        rz: f64,
    ) -> Result<(), FemError> {
        if node_idx >= self.nodes.len() {
            return Err(FemError::InvalidInput(format!(
                "Invalid node index: {} (max: {})",
                node_idx,
                self.nodes.len().saturating_sub(1)
            )));
        }
        for (dof, value) in [(Dof::Ux, ux), (Dof::Uy, uy), (Dof::Rz, rz)] {
            if !value.is_finite() {
                return Err(FemError::InvalidInput(format!(
                    "Prescribed value for {} must be finite, got {}",
                    dof.name(),
                    value
                )));
            }
        }
        self.try_override_dof(node_idx, Dof::Ux.index(), ux)?;
        self.try_override_dof(node_idx, Dof::Uy.index(), uy)?;
        self.try_override_dof(node_idx, Dof::Rz.index(), rz)?;
        Ok(())
    }

    /// Add a distributed load on an element (in LOCAL coordinates)
    /// element_idx is the index in the elements Vec (0, 1, 2, ...)
    pub fn add_distributed_load(
        &mut self,
        element_idx: usize,
        qx: f64,
        qy: f64,
    ) -> Result<(), FemError> {
        if element_idx >= self.elements.len() {
            return Err(FemError::InvalidInput(format!(
                "Invalid element index: {} (max: {})",
                element_idx,
                self.elements.len().saturating_sub(1)
            )));
        }
        if !qx.is_finite() || !qy.is_finite() {
            return Err(FemError::InvalidInput(format!(
                "Distributed load must be finite, got qx = {}, qy = {}",
                qx, qy
            )));
        }
        self.distributed_loads
            .push(DistributedLoad::new(element_idx, qx, qy));
        Ok(())
    }

    /// Add a point load on an element (in LOCAL coordinates)
    /// element_idx is the index in the elements Vec (0, 1, 2, ...)
    /// position is measured from node_i (0.0) to node_j (1.0)
    pub fn add_point_load(
        &mut self,
        element_idx: usize,
        position: f64,
        fx: f64,
        fy: f64,
        mz: f64,
    ) -> Result<(), FemError> {
        if element_idx >= self.elements.len() {
            return Err(FemError::InvalidInput(format!(
                "Invalid element index: {} (max: {})",
                element_idx,
                self.elements.len().saturating_sub(1)
            )));
        }
        if !(0.0..=1.0).contains(&position) {
            return Err(FemError::InvalidInput(format!(
                "Point load position must be in [0, 1], got {}",
                position
            )));
        }
        if !fx.is_finite() || !fy.is_finite() || !mz.is_finite() {
            return Err(FemError::InvalidInput(format!(
                "Point load must be finite, got fx = {}, fy = {}, mz = {}",
                fx, fy, mz
            )));
        }
        self.point_loads
            .push(PointLoad::new(element_idx, position, fx, fy, mz));
        Ok(())
    }

    /// Add a point force only (transverse or axial) on an element.
    ///
    /// Components are **LOCAL** to the element (local x from `node_i` to
    /// `node_j`, local y transverse, positive up). Use
    /// [`BeamElement::to_local_force`] to convert global input data. `position`
    /// must be in `[0, 1]`.
    ///
    /// # Errors
    ///
    /// [`FemError::InvalidInput`] for an out-of-bounds element, a `position`
    /// outside `[0, 1]`, or a non-finite component.
    pub fn add_point_force(
        &mut self,
        element_idx: usize,
        position: f64,
        fx: f64,
        fy: f64,
    ) -> Result<(), FemError> {
        self.add_point_load(element_idx, position, fx, fy, 0.0)
    }

    /// Add a point moment only on an element.
    ///
    /// `mz` is **LOCAL** to the element (`mz > 0` counter-clockwise) and
    /// `position` must be in `[0, 1]`. This is an element load, distinct from
    /// [`Self::add_applied_moment`], which is a nodal (global) moment that is
    /// never part of an element's equivalent load vector.
    ///
    /// # Errors
    ///
    /// [`FemError::InvalidInput`] for an out-of-bounds element, a `position`
    /// outside `[0, 1]`, or a non-finite value.
    pub fn add_point_moment(
        &mut self,
        element_idx: usize,
        position: f64,
        mz: f64,
    ) -> Result<(), FemError> {
        self.add_point_load(element_idx, position, 0.0, 0.0, mz)
    }

    /// Add an applied moment at a node (in GLOBAL coordinates).
    ///
    /// This is a nodal external load applied to the global `theta` DOF
    /// (`value > 0` counter-clockwise). It is **not** an element load: it never
    /// enters an element's equivalent nodal-load vector, so element end forces
    /// are unaffected by it except through the displacement field.
    ///
    /// # Errors
    ///
    /// [`FemError::InvalidInput`] for an out-of-bounds node index or a
    /// non-finite value.
    pub fn add_applied_moment(&mut self, node_idx: usize, value: f64) -> Result<(), FemError> {
        if node_idx >= self.nodes.len() {
            return Err(FemError::InvalidInput(format!(
                "Invalid node index: {} (max: {})",
                node_idx,
                self.nodes.len().saturating_sub(1)
            )));
        }
        if !value.is_finite() {
            return Err(FemError::InvalidInput(format!(
                "Applied moment must be finite, got {}",
                value
            )));
        }
        self.applied_moments
            .push(AppliedMoment::new(node_idx, value));
        Ok(())
    }

    /// Get total number of DOFs
    pub fn n_dof(&self) -> usize {
        self.nodes.len() * 3
    }

    /// Map (node_idx, dof) to global DOF index.
    ///
    /// Note: node_idx must be the index in the nodes Vec (0, 1, 2, ...).
    /// This is NOT an arbitrary user-defined ID. Node IDs are implicitly their
    /// position in the nodes vector.
    pub(crate) fn dof_index(&self, node_idx: usize, dof: usize) -> usize {
        node_idx * 3 + dof
    }
}

/// The condensed (boundary-conditioned) free-free stiffness system of a
/// [`BeamSolver`]: `K_ff` plus the reduced-index -> global-DOF map.
///
/// This is the **single** representation of the system that static
/// condensation produces and that the linear solver factorises. It is retained
/// so that structural diagnostics read the exact same matrix the solve path
/// built, rather than reassembling an identical-looking second copy: two
/// independent assemblies are mathematically equal but not necessarily
/// bit-identical, and a rank probe sitting at a relative tolerance floor is
/// exactly the kind of consumer that a ULP difference can flip.
///
/// Crate-internal on purpose - this is not part of the public surface. Its
/// fields are private: consumers read `K_ff` and the DOF map through the
/// read-only accessors so the retained system cannot be mutated from outside.
#[derive(Debug, Clone)]
pub(crate) struct ReducedSystem {
    /// The free-free stiffness block `K_ff` (already compressed).
    k_ff: SparseMatrix,
    /// Reduced DOF index -> global DOF index (`3 * node + dof`).
    free_to_global: Vec<usize>,
}

impl ReducedSystem {
    /// Retain a condensed system from an already-built `K_ff` and DOF map.
    pub(crate) fn new(k_ff: SparseMatrix, free_to_global: Vec<usize>) -> Self {
        Self {
            k_ff,
            free_to_global,
        }
    }

    /// The retained free-free stiffness block `K_ff`.
    pub(crate) fn k_ff(&self) -> &SparseMatrix {
        &self.k_ff
    }

    /// The retained reduced-index -> global-DOF map (`3 * node + dof`).
    pub(crate) fn free_to_global(&self) -> &[usize] {
        &self.free_to_global
    }
}

/// Beam FEM solver using the unified LinearSolver abstraction.
///
/// # Complete workflow
///
/// ```rust
/// use section_properties::beam_fem::{BeamElement, BeamModel, BeamNode, BeamSection, BeamSolver, Dof};
/// use section_properties::material::Material;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // 1. model: unit cantilever (E = A = I = 1, L = 1)
/// let mut model = BeamModel::new();
/// model.add_node(BeamNode::new(0, 0.0, 0.0));
/// model.add_node(BeamNode::new(1, 1.0, 0.0));
/// model.add_element(BeamElement::new(
///     0,
///     1,
///     Material::new(1.0, 0.3, 1.0, "unit"),
///     BeamSection::new(1.0, 1.0),
/// )?);
///
/// // 2. boundary condition: clamp node 0 (typed DOF API)
/// model.try_fix_node_with_values(0, 0.0, 0.0, 0.0)?;
///
/// // 3. load: global transverse force at the tip
/// model.add_nodal_force(1, 1, -100.0);
///
/// // 4. solve
/// let mut solver = BeamSolver::from_model(&model)?;
/// solver.solve_configured()?;
///
/// // 5. post-process: typed displacement and reaction access
/// let uy = solver.displacement_dof(1, Dof::Uy)?; // -P L^3 / 3EI
/// let rz = solver.displacement_dof(1, Dof::Rz)?; // -P L^2 / 2EI
/// let ry = solver.reaction_dof(0, Dof::Uy)?; // +P
///
/// assert!((uy + 100.0 / 3.0).abs() < 1e-9);
/// assert!((rz + 50.0).abs() < 1e-9);
/// assert!((ry - 100.0).abs() < 1e-9);
/// # Ok(())
/// # }
/// ```
pub struct BeamSolver {
    /// Global stiffness matrix
    k_global: SparseMatrix,
    /// Global force vector
    f_global: Vec<f64>,
    /// Displacement solution
    u_global: Vec<f64>,
    /// Fixed DOFs (true if constrained)
    fixed_dofs: Vec<bool>,
    /// Prescribed values for constrained DOFs (None = 0.0, Some(value) = prescribed)
    prescribed_values: Vec<Option<f64>>,
    /// Original stiffness matrix (for reaction computation)
    k_original: SparseMatrix,
    /// Number of DOFs
    n_dof: usize,
    /// Model reference
    model: BeamModel,
    /// Configured solver selection (defaults to [`SolverSelection::Auto`]).
    solver_selection: SolverSelection,
    /// Name of the backend used by the most recent successful solve, if any.
    solver_name: Option<String>,
    /// The condensed free-free system retained by
    /// [`Self::apply_boundary_conditions`], if it has run. Populated before any
    /// backend is created or factorisation attempted, so it is available even
    /// after a failed solve.
    reduced: Option<ReducedSystem>,
}

impl BeamSolver {
    /// Create a new BeamSolver from a BeamModel
    pub fn from_model(model: &BeamModel) -> Result<Self, FemError> {
        let n_dof = model.n_dof();
        if n_dof == 0 {
            return Err(FemError::InvalidModel("Model has no nodes".to_string()));
        }

        // Validate element node indices
        for (elem_idx, element) in model.elements.iter().enumerate() {
            if element.node_i >= model.nodes.len() {
                return Err(FemError::InvalidModel(format!(
                    "Element {}: node_i index {} out of bounds (max: {})",
                    elem_idx,
                    element.node_i,
                    model.nodes.len().saturating_sub(1)
                )));
            }
            if element.node_j >= model.nodes.len() {
                return Err(FemError::InvalidModel(format!(
                    "Element {}: node_j index {} out of bounds (max: {})",
                    elem_idx,
                    element.node_j,
                    model.nodes.len().saturating_sub(1)
                )));
            }
            if element.node_i == element.node_j {
                return Err(FemError::InvalidModel(format!(
                    "Element {}: node_i and node_j cannot be the same",
                    elem_idx
                )));
            }
        }

        // Validate node coordinates are finite.
        for (idx, node) in model.nodes.iter().enumerate() {
            if !node.x.is_finite() || !node.y.is_finite() {
                return Err(FemError::InvalidModel(format!(
                    "Node {} has non-finite coordinates: ({}, {})",
                    idx, node.x, node.y
                )));
            }
        }

        // Validate material and section parameters (finite and positive). These
        // have no fallible constructor, so this is the authoritative boundary;
        // it also covers elements built via struct literal.
        for (elem_idx, element) in model.elements.iter().enumerate() {
            let e = element.material.youngs_modulus;
            let a = element.section.area;
            let i = element.section.second_moment;
            if !e.is_finite() || e <= 0.0 {
                return Err(FemError::InvalidModel(format!(
                    "Element {}: Young's modulus must be finite and positive, got {}",
                    elem_idx, e
                )));
            }
            if !a.is_finite() || a <= 0.0 {
                return Err(FemError::InvalidModel(format!(
                    "Element {}: cross-section area must be finite and positive, got {}",
                    elem_idx, a
                )));
            }
            if !i.is_finite() || i <= 0.0 {
                return Err(FemError::InvalidModel(format!(
                    "Element {}: second moment of area must be finite and positive, got {}",
                    elem_idx, i
                )));
            }
        }

        // Validate that every load and prescribed value is finite. Model fields
        // are public, so this cannot be delegated solely to the add_* helpers.
        for (node_id, dof, value) in &model.nodal_forces {
            if !value.is_finite() {
                return Err(FemError::InvalidModel(format!(
                    "Nodal force at node {} DOF {} is non-finite: {}",
                    node_id, dof, value
                )));
            }
        }
        for dl in &model.distributed_loads {
            if !dl.qx.is_finite() || !dl.qy.is_finite() {
                return Err(FemError::InvalidModel(format!(
                    "Distributed load on element {} is non-finite: qx = {}, qy = {}",
                    dl.element_idx, dl.qx, dl.qy
                )));
            }
        }
        for pl in &model.point_loads {
            if !pl.fx.is_finite() || !pl.fy.is_finite() || !pl.mz.is_finite() {
                return Err(FemError::InvalidModel(format!(
                    "Point load on element {} is non-finite: fx = {}, fy = {}, mz = {}",
                    pl.element_idx, pl.fx, pl.fy, pl.mz
                )));
            }
        }
        for am in &model.applied_moments {
            if !am.value.is_finite() {
                return Err(FemError::InvalidModel(format!(
                    "Applied moment at node {} is non-finite: {}",
                    am.node_idx, am.value
                )));
            }
        }
        for (node_id, dof, value) in &model.fixed_dofs {
            if !value.is_finite() {
                return Err(FemError::InvalidModel(format!(
                    "Prescribed value at node {} DOF {} is non-finite: {}",
                    node_id, dof, value
                )));
            }
        }

        // Build global stiffness matrix
        let mut k_global = SparseMatrix::new(n_dof);

        // Assemble element stiffness matrices
        for element in &model.elements {
            let node_i = model.nodes[element.node_i].point();
            let node_j = model.nodes[element.node_j].point();

            // Check for zero-length beam
            let dx = node_j.x - node_i.x;
            let dy = node_j.y - node_i.y;
            let L = (dx * dx + dy * dy).sqrt();
            if L <= 0.0 {
                return Err(FemError::InvalidModel(format!(
                    "Beam element has zero or negative length (nodes {} and {} at same position)",
                    element.node_i, element.node_j
                )));
            }

            let k_global_elem = element.global_stiffness(node_i, node_j);

            // Map element DOFs to global DOFs
            let dof_map = [
                model.dof_index(element.node_i, 0), // u_i
                model.dof_index(element.node_i, 1), // v_i
                model.dof_index(element.node_i, 2), // θ_i
                model.dof_index(element.node_j, 0), // u_j
                model.dof_index(element.node_j, 1), // v_j
                model.dof_index(element.node_j, 2), // θ_j
            ];

            // Assemble into global matrix
            for a in 0..6 {
                for b in 0..6 {
                    let val = k_global_elem[a][b];
                    k_global.add(dof_map[a], dof_map[b], val);
                }
            }
        }

        // Build force vector
        let mut f_global = vec![0.0; n_dof];
        for (node_id, dof, value) in &model.nodal_forces {
            if *node_id >= model.nodes.len() {
                return Err(FemError::InvalidModel(format!(
                    "Nodal force: node index {} out of bounds (max: {})",
                    node_id,
                    model.nodes.len().saturating_sub(1)
                )));
            }
            if *dof >= 3 {
                return Err(FemError::InvalidModel(format!(
                    "Nodal force: DOF {} invalid (must be 0, 1, or 2)",
                    dof
                )));
            }
            let idx = model.dof_index(*node_id, *dof);
            f_global[idx] += value;
        }

        // Assemble distributed loads
        for dl in &model.distributed_loads {
            if dl.element_idx >= model.elements.len() {
                return Err(FemError::InvalidModel(format!(
                    "Distributed load: element index {} out of bounds (max: {})",
                    dl.element_idx,
                    model.elements.len().saturating_sub(1)
                )));
            }
            let element = &model.elements[dl.element_idx];
            let node_i = model.nodes[element.node_i].point();
            let node_j = model.nodes[element.node_j].point();

            // Check for zero-length beam
            let dx = node_j.x - node_i.x;
            let dy = node_j.y - node_i.y;
            let L = (dx * dx + dy * dy).sqrt();
            if L <= 0.0 {
                return Err(FemError::InvalidModel(format!(
                    "Distributed load: beam element has zero or negative length (nodes {} and {} at same position)",
                    element.node_i, element.node_j
                )));
            }

            // Compute consistent nodal load in local coordinates
            let f_local = element.consistent_nodal_load(node_i, node_j, dl.qx, dl.qy)?;

            // Get transformation matrix
            let T = element.transformation_matrix(node_i, node_j);

            // Transform to global coordinates: f_global_elem = T^T * f_local
            let mut f_global_elem = [0.0; 6];
            for i in 0..6 {
                for j in 0..6 {
                    f_global_elem[i] += T[j][i] * f_local[j];
                }
            }

            // Map element DOFs to global DOFs
            let dof_map = [
                model.dof_index(element.node_i, 0), // u_i
                model.dof_index(element.node_i, 1), // v_i
                model.dof_index(element.node_i, 2), // θ_i
                model.dof_index(element.node_j, 0), // u_j
                model.dof_index(element.node_j, 1), // v_j
                model.dof_index(element.node_j, 2), // θ_j
            ];

            // Assemble into global force vector
            for a in 0..6 {
                f_global[dof_map[a]] += f_global_elem[a];
            }
        }

        // Assemble point loads
        for pl in &model.point_loads {
            if pl.element_idx >= model.elements.len() {
                return Err(FemError::InvalidModel(format!(
                    "Point load: element index {} out of bounds (max: {})",
                    pl.element_idx,
                    model.elements.len().saturating_sub(1)
                )));
            }
            let element = &model.elements[pl.element_idx];
            let node_i = model.nodes[element.node_i].point();
            let node_j = model.nodes[element.node_j].point();

            // Check for zero-length beam
            let dx = node_j.x - node_i.x;
            let dy = node_j.y - node_i.y;
            let L = (dx * dx + dy * dy).sqrt();
            if L <= 0.0 {
                return Err(FemError::InvalidModel(format!(
                    "Point load: beam element has zero or negative length (nodes {} and {} at same position)",
                    element.node_i, element.node_j
                )));
            }

            // Compute consistent nodal load in local coordinates
            let f_local = element.consistent_nodal_load_point(
                node_i,
                node_j,
                pl.position,
                pl.fx,
                pl.fy,
                pl.mz,
            )?;

            // Get transformation matrix
            let T = element.transformation_matrix(node_i, node_j);

            // Transform to global coordinates: f_global_elem = T^T * f_local
            let mut f_global_elem = [0.0; 6];
            for i in 0..6 {
                for j in 0..6 {
                    f_global_elem[i] += T[j][i] * f_local[j];
                }
            }

            // Map element DOFs to global DOFs
            let dof_map = [
                model.dof_index(element.node_i, 0), // u_i
                model.dof_index(element.node_i, 1), // v_i
                model.dof_index(element.node_i, 2), // θ_i
                model.dof_index(element.node_j, 0), // u_j
                model.dof_index(element.node_j, 1), // v_j
                model.dof_index(element.node_j, 2), // θ_j
            ];

            // Assemble into global force vector
            for a in 0..6 {
                f_global[dof_map[a]] += f_global_elem[a];
            }
        }

        // Assemble applied moments (already in global coordinates)
        for am in &model.applied_moments {
            if am.node_idx >= model.nodes.len() {
                return Err(FemError::InvalidModel(format!(
                    "Applied moment: node index {} out of bounds (max: {})",
                    am.node_idx,
                    model.nodes.len().saturating_sub(1)
                )));
            }
            // Applied moment is in global coordinates, DOF 2 = θ
            let idx = model.dof_index(am.node_idx, 2);
            f_global[idx] += am.value;
        }

        // Fixed DOFs and prescribed values
        let mut fixed_dofs = vec![false; n_dof];
        let mut prescribed_values = vec![None; n_dof];
        for (node_id, dof, value) in &model.fixed_dofs {
            if *node_id >= model.nodes.len() {
                return Err(FemError::InvalidModel(format!(
                    "Fixed DOF: node index {} out of bounds (max: {})",
                    node_id,
                    model.nodes.len().saturating_sub(1)
                )));
            }
            if *dof >= 3 {
                return Err(FemError::InvalidModel(format!(
                    "Fixed DOF: DOF {} invalid (must be 0, 1, or 2)",
                    dof
                )));
            }
            let idx = model.dof_index(*node_id, *dof);
            fixed_dofs[idx] = true;
            prescribed_values[idx] = Some(*value);
        }

        // Store original matrix for reaction computation
        let k_original = k_global.clone();

        Ok(Self {
            k_global,
            f_global,
            u_global: vec![0.0; n_dof],
            fixed_dofs,
            prescribed_values,
            k_original,
            n_dof,
            model: model.clone(),
            solver_selection: SolverSelection::Auto,
            solver_name: None,
            reduced: None,
        })
    }

    /// Apply boundary conditions using static condensation (exact enforcement)
    /// and retain the condensed system in `self.reduced`.
    ///
    /// Returns `(f_reduced, constrained_indices, constrained_values)`. The
    /// condensed stiffness `K_ff` and the free-DOF map are **moved** into
    /// `self.reduced` (no clone): diagnostics read that retained system, and
    /// the solve path factorises a bit-identical copy of it (the single deep
    /// copy on the solve path) rather than a second, independently assembled
    /// matrix.
    fn apply_boundary_conditions(&mut self) -> (Vec<f64>, Vec<usize>, Vec<f64>) {
        let n = self.n_dof;
        let fixed = &self.fixed_dofs;
        let prescribed = &self.prescribed_values;

        // Identify free and constrained DOFs
        let mut free_dofs = Vec::new();
        let mut constrained_dofs = Vec::new();
        let mut constrained_values = Vec::new();
        let mut free_to_global = Vec::new();
        let mut global_to_free = vec![None; n];

        for i in 0..n {
            if !fixed[i] {
                global_to_free[i] = Some(free_dofs.len());
                free_dofs.push(i);
                free_to_global.push(i);
            } else {
                let _constrained_idx = constrained_dofs.len();
                constrained_dofs.push(i);
                constrained_values.push(prescribed[i].unwrap_or(0.0));
            }
        }

        let n_free = free_dofs.len();
        if n_free == 0 {
            // All DOFs fixed - retain and return an empty system.
            self.reduced = Some(ReducedSystem::new(SparseMatrix::new(0), Vec::new()));
            return (Vec::new(), constrained_dofs, constrained_values);
        }

        // Extract free-free submatrix K_ff and force vector f_f
        let mut k_ff = SparseMatrix::new(n_free);
        let mut f_f = vec![0.0; n_free];

        // Compress original matrix to access CSR data
        let mut k_orig = self.k_global.clone();
        k_orig.compress();

        // Extract K_ff and compute K_fc * U_c directly
        let mut kfc_uc = vec![0.0; n_free];

        for (free_idx, &global_i) in free_dofs.iter().enumerate() {
            // Force vector
            f_f[free_idx] = self.f_global[global_i];

            // Stiffness matrix row
            let row_ptr = k_orig.row_ptr();
            let csr_cols = k_orig.csr_cols();
            let csr_vals = k_orig.csr_vals();

            for idx in row_ptr[global_i]..row_ptr[global_i + 1] {
                let global_j = csr_cols[idx];
                let val = csr_vals[idx];

                if let Some(free_j) = global_to_free[global_j] {
                    // free-free
                    k_ff.add(free_idx, free_j, val);
                } else if fixed[global_j] {
                    // free-constrained: accumulate K_fc * U_c directly
                    let constr_idx = constrained_dofs
                        .iter()
                        .position(|&x| x == global_j)
                        .unwrap();
                    kfc_uc[free_idx] += val * constrained_values[constr_idx];
                }
            }
        }

        k_ff.compress();

        // Compute reduced RHS: F_reduced = F_f - K_fc * U_c
        let mut f_reduced = f_f;
        for free_idx in 0..n_free {
            f_reduced[free_idx] -= kfc_uc[free_idx];
        }

        // Retain the condensed system for the solve path and read-only
        // diagnostics by *moving* the freshly built matrix and map (no clone).
        self.reduced = Some(ReducedSystem::new(k_ff, free_to_global));

        (f_reduced, constrained_dofs, constrained_values)
    }

    /// The condensed free-free system most recently built by
    /// [`Self::apply_boundary_conditions`]/[`Self::condense`], if it has run.
    ///
    /// The matrix is the exact one the solve path assembled and factorised -
    /// diagnostics must read this, never reassemble their own copy. `None` only
    /// before any condensation has happened on this solver.
    pub(crate) fn reduced_system(&self) -> Option<&ReducedSystem> {
        self.reduced.as_ref()
    }

    /// Copy the retained reduced system out for its one consuming use (the
    /// factorisation). This is the only deep copy of `K_ff` on the solve path;
    /// the retained original stays in `self.reduced` for diagnostics.
    ///
    /// Panics only if called before the system has been condensed, which the
    /// solve paths never do (`apply_boundary_conditions` runs first).
    fn retained_system_copy(&self) -> (SparseMatrix, Vec<usize>) {
        let retained = self
            .reduced
            .as_ref()
            .expect("apply_boundary_conditions retains the condensed system");
        (retained.k_ff().clone(), retained.free_to_global().to_vec())
    }

    /// Condense the boundary conditions and return the retained reduced system
    /// for read-only inspection.
    ///
    /// Semantics: the returned system is condensed from the solver's current
    /// model state. The **first** call runs the identical static-condensation
    /// code the solve path runs, so the returned matrix is bit-identical to the
    /// one a solve would factorise. A `BeamSolver` exposes no mutator that can
    /// change the assembled system (loads, supports and geometry are fixed in
    /// the `BeamModel` at construction; only the backend selection is settable,
    /// which does not affect `K_ff`), so repeated calls are **idempotent**:
    /// they return the already-retained system without re-condensing. It never
    /// panics.
    pub(crate) fn condense(&mut self) -> &ReducedSystem {
        if self.reduced.is_none() {
            self.apply_boundary_conditions();
        }
        self.reduced
            .as_ref()
            .expect("apply_boundary_conditions always retains the condensed system")
    }

    #[allow(dead_code)]
    fn find_diagonal_index(&self, matrix: &SparseMatrix, row: usize) -> Option<usize> {
        let row_ptr = matrix.row_ptr();
        let csr_cols = matrix.csr_cols();
        for idx in row_ptr[row]..row_ptr[row + 1] {
            if csr_cols[idx] == row {
                return Some(idx);
            }
        }
        None
    }

    /// Configure the solver selection used by [`Self::solve_configured`].
    ///
    /// Defaults to [`SolverSelection::Auto`]. Explicit selections are
    /// authoritative: if the requested backend cannot handle the condensed
    /// stiffness matrix, [`Self::solve_configured`] returns an error and does
    /// **not** substitute another backend.
    pub fn set_solver(&mut self, selection: SolverSelection) {
        self.solver_selection = selection;
    }

    /// The configured solver selection.
    pub fn solver_selection(&self) -> &SolverSelection {
        &self.solver_selection
    }

    /// Name of the backend used by the most recent **successful** solve.
    ///
    /// Semantics: the value describes the solution currently held by this
    /// solver. It is cleared before each solve attempt and set only when the
    /// solve completes successfully, so it is `None`:
    ///
    /// * before any solve;
    /// * after a failed solve attempt (no stale claim from an earlier run);
    /// * when the model was fully constrained and no linear system was solved.
    pub fn solver_name(&self) -> Option<&str> {
        self.solver_name.as_deref()
    }

    /// Factorize and expand a condensed system into the global solution.
    ///
    /// `k_ff`/`free_to_global` are the solver's retained system copied out for
    /// this one use - the only deep copy of `K_ff` on the solve path (the
    /// retained copy lives in `self.reduced` for diagnostics and is never
    /// duplicated again).
    fn factor_and_expand(
        &mut self,
        solver: &mut dyn LinearSolver,
        mut k_ff: SparseMatrix,
        f_reduced: Vec<f64>,
        free_to_global: Vec<usize>,
        constrained_dofs: Vec<usize>,
        constrained_values: Vec<f64>,
    ) -> Result<(), FemError> {
        if k_ff.n == 0 {
            // All DOFs fixed - just set prescribed values
            self.u_global = vec![0.0; self.n_dof];
            for (i, &global_idx) in constrained_dofs.iter().enumerate() {
                self.u_global[global_idx] = constrained_values[i];
            }
            return Ok(());
        }

        k_ff.compress();
        solver.factor(&k_ff).map_err(FemError::from)?;

        let u_free = solver.solve(&f_reduced).map_err(FemError::from)?;

        // Expand solution back to full DOF space
        self.u_global = vec![0.0; self.n_dof];
        for (free_idx, &global_idx) in free_to_global.iter().enumerate() {
            self.u_global[global_idx] = u_free[free_idx];
        }
        for (i, &global_idx) in constrained_dofs.iter().enumerate() {
            self.u_global[global_idx] = constrained_values[i];
        }
        Ok(())
    }

    /// Solve the system using the provided LinearSolver.
    ///
    /// The caller owns solver construction; [`Self::solve_configured`] instead
    /// uses the configured [`SolverSelection`].
    ///
    /// [`Self::solver_name`] is cleared at the start of this call and set only
    /// after the solve succeeds, so a failed solve never leaves stale
    /// observability implying a backend produced the current solution.
    pub fn solve(&mut self, solver: &mut dyn LinearSolver) -> Result<(), FemError> {
        self.solver_name = None;
        let (f_reduced, constrained_dofs, constrained_values) = self.apply_boundary_conditions();
        let (k_ff, free_to_global) = self.retained_system_copy();
        self.factor_and_expand(
            solver,
            k_ff,
            f_reduced,
            free_to_global,
            constrained_dofs,
            constrained_values,
        )?;
        self.solver_name = Some(solver.name().to_string());
        Ok(())
    }

    /// Solve using the configured [`SolverSelection`] (default [`Auto`]).
    ///
    /// The backend is chosen via [`SolverRegistry`] against the **condensed**
    /// (boundary-conditioned) stiffness matrix — the matrix that is actually
    /// factorized. Capability validation therefore sees the real system.
    ///
    /// # Errors
    ///
    /// All solver errors propagate as [`FemError::SolverError`]; an explicit
    /// invalid selection (e.g. a non-symmetric system with `skyline_ldlt`, or a
    /// matrix larger than the backend's `max_size`) returns an error and never
    /// silently switches backend.
    ///
    /// [`Self::solver_name`] is cleared before the solve is attempted and set
    /// only once it fully succeeds, so a failed attempt never leaves stale
    /// observability claiming the failed backend produced a solution.
    ///
    /// [`Auto`]: SolverSelection::Auto
    pub fn solve_configured(&mut self) -> Result<(), FemError> {
        self.solver_name = None;
        let (f_reduced, constrained_dofs, constrained_values) = self.apply_boundary_conditions();

        let n_free = self.reduced.as_ref().map_or(0, |r| r.k_ff().n);
        if n_free == 0 {
            self.u_global = vec![0.0; self.n_dof];
            for (i, &global_idx) in constrained_dofs.iter().enumerate() {
                self.u_global[global_idx] = constrained_values[i];
            }
            return Ok(());
        }

        // The single copy of the retained matrix: the backend is selected
        // against it and it is the matrix the factorisation consumes (no
        // separate probe copy).
        let (k_ff, free_to_global) = self.retained_system_copy();

        let registry = SolverRegistry::default();
        let mut solver = registry
            .create_selected(&k_ff, &self.solver_selection)
            .map_err(FemError::from)?;
        let name = solver.name().to_string();

        self.factor_and_expand(
            &mut *solver,
            k_ff,
            f_reduced,
            free_to_global,
            constrained_dofs,
            constrained_values,
        )?;
        self.solver_name = Some(name);
        Ok(())
    }

    /// Displacement of a global DOF at a node (raw-index accessor).
    ///
    /// `dof` is a raw index in the **global** system: `0 = ux`, `1 = uy`,
    /// `2 = rz`; the assembled slot is `3*node_idx + dof`
    /// (`3*node_idx + dof`).
    ///
    /// # Errors
    ///
    /// [`FemError::InvalidInput`] if `dof` is not 0, 1, or 2.  Previously
    /// `dof >= 3` silently aliased into the following node's DOF slot; this
    /// is now rejected.  Prefer the typed [`Self::displacement_dof`] with
    /// [`Dof`] for compile-time safety.
    ///
    /// [`FemError::InvalidInput`] if `node_idx` is out of bounds.  Previously
    /// out-of-range node indices silently returned `Ok(0.0)`; this is now
    /// rejected for consistency with [`Self::displacement_dof`].
    ///
    /// Before a successful solve the whole displacement vector is zero, so
    /// a valid query returns `Ok(0.0)`.
    pub fn displacement(&self, node_idx: usize, dof: usize) -> Result<f64, FemError> {
        if dof >= 3 {
            return Err(FemError::InvalidInput(format!(
                "Invalid DOF index: {} (must be 0=Ux, 1=Uy, 2=Rz)",
                dof
            )));
        }
        if node_idx >= self.model.nodes.len() {
            return Err(FemError::InvalidInput(format!(
                "Invalid node index: {} (max: {})",
                node_idx,
                self.model.nodes.len().saturating_sub(1)
            )));
        }
        let idx = self.model.dof_index(node_idx, dof);
        if idx < self.u_global.len() {
            Ok(self.u_global[idx])
        } else {
            Ok(0.0)
        }
    }

    /// Typed counterpart of [`Self::displacement`]: displacement of `dof` at
    /// `node_idx`, in the **global** system.
    ///
    /// This is a direct extraction from the global displacement vector — no
    /// recalculation, so the value is exactly what [`Self::displacement`]
    /// returns for the corresponding raw index. Reading before a successful
    /// solve yields `0.0` (the displacement vector is initialised to zero).
    ///
    /// # Errors
    ///
    /// [`FemError::InvalidInput`] if `node_idx` is out of bounds. (With a typed
    /// [`Dof`] an out-of-range DOF is impossible.)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use section_properties::beam_fem::{BeamElement, BeamModel, BeamNode, BeamSection, BeamSolver, Dof};
    /// use section_properties::material::Material;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut model = BeamModel::new();
    /// model.add_node(BeamNode::new(0, 0.0, 0.0));
    /// model.add_node(BeamNode::new(1, 1.0, 0.0));
    /// model.add_element(BeamElement::new(
    ///     0,
    ///     1,
    ///     Material::new(1.0, 0.3, 1.0, "unit"),
    ///     BeamSection::new(1.0, 1.0),
    /// )?);
    /// model.fix_node(0);
    /// model.add_nodal_force(1, 1, -100.0);
    ///
    /// let mut solver = BeamSolver::from_model(&model)?;
    /// solver.solve_configured()?;
    ///
    /// // tip deflection = -P L^3 / 3EI = -33.333...
    /// let uy = solver.displacement_dof(1, Dof::Uy)?;
    /// assert!((uy + 100.0 / 3.0).abs() < 1e-9);
    /// // identical to the raw-index accessor
    /// assert_eq!(uy, solver.displacement(1, 1)?);
    /// assert!(matches!(solver.displacement_dof(9, Dof::Uy), Err(_)));
    /// # Ok(())
    /// # }
    /// ```
    pub fn displacement_dof(&self, node_idx: usize, dof: Dof) -> Result<f64, FemError> {
        if node_idx >= self.model.nodes.len() {
            return Err(FemError::InvalidInput(format!(
                "Invalid node index: {} (max: {})",
                node_idx,
                self.model.nodes.len().saturating_sub(1)
            )));
        }
        let idx = self.model.dof_index(node_idx, dof.index());
        if idx < self.u_global.len() {
            Ok(self.u_global[idx])
        } else {
            Ok(0.0)
        }
    }

    /// The full **global** displacement vector (borrowed, not copied).
    ///
    /// Laid out as `[ux0, uy0, rz0, ux1, uy1, rz1, ...]`, i.e. slot
    /// `3*node + dof` with `dof` = `0/1/2` = `ux/uy/rz`
    /// (`3*node_idx + dof`). Before a successful solve every entry is
    /// `0.0`.
    pub fn displacements(&self) -> &[f64] {
        &self.u_global
    }

    /// Compute the global external support reactions.
    ///
    /// `R = K_original · u - f_global`, evaluated on the **unconstrained**
    /// (assembled) system after the full displacement vector has been
    /// reconstructed from static condensation:
    ///
    /// - at a constrained DOF, `R` is the support reaction;
    /// - at a free DOF, `R` is numerically zero.
    ///
    /// Together with the applied loads the reactions satisfy global
    /// equilibrium (`ΣF = 0`, `ΣM = 0`). They are **not** element end forces;
    /// see [`Self::element_end_forces`] for those.
    ///
    /// # Pre-solve behaviour
    ///
    /// Before a successful solve the displacement vector is zero, so this
    /// returns the raw algebraic quantity `K·0 - f = -f` — **not** physical
    /// support reactions. Check [`Self::solver_name`] (`Some(..)` only after a
    /// successful solve), or use [`Self::results`], whose reaction snapshot
    /// sets free DOFs to exactly `0.0`.
    pub fn reactions(&self) -> Vec<f64> {
        // R = K_original * u - f_global
        let mut reactions = vec![0.0; self.n_dof];

        // Compute K_original * u using public API
        let mut k_orig = self.k_original.clone();
        k_orig.compress();
        for i in 0..self.n_dof {
            let mut sum = 0.0;
            let row_ptr = k_orig.row_ptr();
            let csr_cols = k_orig.csr_cols();
            let csr_vals = k_orig.csr_vals();
            for idx in row_ptr[i]..row_ptr[i + 1] {
                let j = csr_cols[idx];
                sum += csr_vals[idx] * self.u_global[j];
            }
            reactions[i] = sum - self.f_global[i];
        }

        reactions
    }

    /// Get reaction at a specific DOF
    ///
    /// Raw-index accessor for the **global** reaction at `3*node_idx + dof`
    /// (`0 = ux` → `Fx`, `1 = uy` → `Fy`, `2 = rz` → `Mz`).
    ///
    /// # Errors
    ///
    /// [`FemError::InvalidInput`] if `dof` is not 0, 1, or 2.  Previously
    /// `dof >= 3` silently aliased into the following node's DOF slot; this
    /// is now rejected.  Prefer the typed [`Self::reaction_dof`] with [`Dof`]
    /// for compile-time safety.
    ///
    /// [`FemError::InvalidInput`] if `node_idx` is out of bounds.  Previously
    /// out-of-range node indices silently returned `Ok(0.0)`; this is now
    /// rejected for consistency with [`Self::reaction_dof`].
    ///
    /// Before a successful solve this returns the raw `K·0 - f` value, which
    /// is not a physical support reaction (see [`Self::reactions`]).
    pub fn reaction(&self, node_idx: usize, dof: usize) -> Result<f64, FemError> {
        if dof >= 3 {
            return Err(FemError::InvalidInput(format!(
                "Invalid DOF index: {} (must be 0=Ux, 1=Uy, 2=Rz)",
                dof
            )));
        }
        if node_idx >= self.model.nodes.len() {
            return Err(FemError::InvalidInput(format!(
                "Invalid node index: {} (max: {})",
                node_idx,
                self.model.nodes.len().saturating_sub(1)
            )));
        }
        let idx = self.model.dof_index(node_idx, dof);
        if idx < self.reactions().len() {
            Ok(self.reactions()[idx])
        } else {
            Ok(0.0)
        }
    }

    /// Typed counterpart of [`Self::reaction`]: **global** support reaction of
    /// `dof` at `node_idx`.
    ///
    /// - `Dof::Ux` → translational X reaction;
    /// - `Dof::Uy` → translational Y reaction;
    /// - `Dof::Rz` → rotational reaction about Z (counter-clockwise positive).
    ///
    /// Delegates to the same [`Self::reactions`] vector, so the value is
    /// exactly what [`Self::reaction`] returns for the corresponding raw index;
    /// only a single reaction evaluation is performed. At a free DOF the value
    /// is numerically zero.
    ///
    /// # Errors
    ///
    /// [`FemError::InvalidInput`] if `node_idx` is out of bounds.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use section_properties::beam_fem::{BeamElement, BeamModel, BeamNode, BeamSection, BeamSolver, Dof};
    /// use section_properties::material::Material;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut model = BeamModel::new();
    /// model.add_node(BeamNode::new(0, 0.0, 0.0));
    /// model.add_node(BeamNode::new(1, 1.0, 0.0));
    /// model.add_element(BeamElement::new(
    ///     0,
    ///     1,
    ///     Material::new(1.0, 0.3, 1.0, "unit"),
    ///     BeamSection::new(1.0, 1.0),
    /// )?);
    /// model.fix_node(0);
    /// model.add_nodal_force(1, 1, -100.0);
    ///
    /// let mut solver = BeamSolver::from_model(&model)?;
    /// solver.solve_configured()?;
    ///
    /// // Support reactions: Ry = +P, Rz = +P·L
    /// let ry = solver.reaction_dof(0, Dof::Uy)?;
    /// let rz = solver.reaction_dof(0, Dof::Rz)?;
    /// assert!((ry - 100.0).abs() < 1e-9);
    /// assert!((rz - 100.0).abs() < 1e-9);
    /// assert_eq!(ry, solver.reaction(0, 1)?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn reaction_dof(&self, node_idx: usize, dof: Dof) -> Result<f64, FemError> {
        if node_idx >= self.model.nodes.len() {
            return Err(FemError::InvalidInput(format!(
                "Invalid node index: {} (max: {})",
                node_idx,
                self.model.nodes.len().saturating_sub(1)
            )));
        }
        let reactions = self.reactions();
        let idx = self.model.dof_index(node_idx, dof.index());
        if idx < reactions.len() {
            Ok(reactions[idx])
        } else {
            Ok(0.0)
        }
    }

    /// Access the original (unconstrained) global stiffness matrix.
    ///
    /// This is exposed crate-internally for debugging and diagnostics; it is
    /// not part of the public API surface.
    #[allow(dead_code)]
    pub(crate) fn stiffness_matrix(&self) -> &SparseMatrix {
        &self.k_original
    }

    /// Compute element end forces in LOCAL coordinates.
    ///
    /// Returns a vector of 6 forces per element in local coordinates:
    /// `[N_i, V_i, M_i, N_j, V_j, M_j]`, where `N` is axial force, `V` is
    /// transverse shear force, and `M` is bending moment.
    ///
    /// # Sign convention
    ///
    /// These are the forces the ELEMENT applies to its end NODES (reaction
    /// sense), i.e. `f_end = f_equiv - K_local·u_local`. Positive `N` is
    /// tension on the node, positive `V` is upward on the node, and positive
    /// `M` is counter-clockwise on the node.
    ///
    /// Applied moments at nodes are external concentrated loads whose effect is
    /// carried by the displacement field `u` (through the global force vector),
    /// so no separate correction is needed here. Recovered end moments therefore
    /// automatically satisfy nodal moment equilibrium:
    ///
    /// - free-end node with applied moment `M`: `M_element_j + M ≈ 0`;
    /// - internal node with applied moment `M` shared by two elements:
    ///   `M_left_j + M_right_i + M ≈ 0`.
    ///
    /// # Scope: nodal end forces, NOT section internal forces
    ///
    /// This method returns the *element-on-node* nodal equilibrium forces at
    /// `ξ = 0` and `ξ = 1` only. It is **not** a beam-section internal-force
    /// diagram, and the two are not interchangeable when the element carries a
    /// distributed load, an interior point force, or an interior point moment:
    /// the end values here include the consistent-load contributions and say
    /// nothing about `N(x)`, `V(x)`, `M(x)` *inside* the element.
    ///
    /// For the internal resultants at an arbitrary `ξ`, use
    /// [`Self::element_section_forces`], which recovers `N(x)`, `V(x)`, `M(x)`
    /// from equilibrium (including the correct jumps across point loads and
    /// moments). Do not overload this method to mean both.
    ///
    /// # Errors
    ///
    /// Propagates any error from the equivalent point-load recovery
    /// (see `Self::element_equivalent_nodal_forces`); a failed recovery is
    /// never silently replaced by a zero load.
    pub fn element_end_forces(&self) -> Result<Vec<[f64; 6]>, FemError> {
        let mut results = Vec::with_capacity(self.model.elements.len());
        for elem_idx in 0..self.model.elements.len() {
            results.push(self.element_on_node_end_forces_local(elem_idx)?);
        }
        Ok(results)
    }

    /// Local element displacement vector `[u_i, v_i, θ_i, u_j, v_j, θ_j]`.
    ///
    /// Returns the element's nodal displacements transformed from global to
    /// local coordinates (`u_local = T · u_global`).
    ///
    /// # Errors
    ///
    /// Returns [`FemError::InvalidInput`] if `element_idx` is out of bounds.
    fn element_local_displacement(&self, element_idx: usize) -> Result<[f64; 6], FemError> {
        let element = self.model.elements.get(element_idx).ok_or_else(|| {
            FemError::InvalidInput(format!(
                "Invalid element index: {} (max: {})",
                element_idx,
                self.model.elements.len().saturating_sub(1)
            ))
        })?;
        let node_i = self.model.nodes[element.node_i].point();
        let node_j = self.model.nodes[element.node_j].point();

        let dof_map = [
            self.model.dof_index(element.node_i, 0), // u_i
            self.model.dof_index(element.node_i, 1), // v_i
            self.model.dof_index(element.node_i, 2), // θ_i
            self.model.dof_index(element.node_j, 0), // u_j
            self.model.dof_index(element.node_j, 1), // v_j
            self.model.dof_index(element.node_j, 2), // θ_j
        ];
        let u_global_elem = [
            self.u_global[dof_map[0]],
            self.u_global[dof_map[1]],
            self.u_global[dof_map[2]],
            self.u_global[dof_map[3]],
            self.u_global[dof_map[4]],
            self.u_global[dof_map[5]],
        ];

        // Transform to local coordinates: u_local = T * u_global.
        let t = element.transformation_matrix(node_i, node_j);
        let mut u_local = [0.0; 6];
        for i in 0..6 {
            for j in 0..6 {
                u_local[i] += t[i][j] * u_global_elem[j];
            }
        }
        Ok(u_local)
    }

    /// Element-on-node end forces in LOCAL coordinates for a single element:
    /// `f_end = f_equiv - K_local · u_local`, ordered
    /// `[N_i, V_i, M_i, N_j, V_j, M_j]`.
    ///
    /// # Errors
    ///
    /// Propagates errors from [`Self::element_local_displacement`] and
    /// [`Self::element_equivalent_nodal_forces`].
    fn element_on_node_end_forces_local(&self, element_idx: usize) -> Result<[f64; 6], FemError> {
        let element = self.model.elements.get(element_idx).ok_or_else(|| {
            FemError::InvalidInput(format!(
                "Invalid element index: {} (max: {})",
                element_idx,
                self.model.elements.len().saturating_sub(1)
            ))
        })?;
        let node_i = self.model.nodes[element.node_i].point();
        let node_j = self.model.nodes[element.node_j].point();

        let u_local = self.element_local_displacement(element_idx)?;

        // Internal nodal force: f_stiffness = K_local * u_local.
        let k_local = element.local_stiffness(node_i, node_j);
        let mut f_stiffness = [0.0; 6];
        for i in 0..6 {
            for j in 0..6 {
                f_stiffness[i] += k_local[i][j] * u_local[j];
            }
        }

        // Equivalent nodal forces from distributed and point loads on this
        // element. Applied moments at nodes are external concentrated loads,
        // excluded from the equivalent element loads.
        let f_equiv = Self::element_equivalent_nodal_forces(
            &self.model,
            element_idx,
            element,
            node_i,
            node_j,
        )?;

        // Element-on-node end forces: f_end = f_equiv - f_stiffness.
        let mut end_forces = [0.0; 6];
        for i in 0..6 {
            end_forces[i] = f_equiv[i] - f_stiffness[i];
        }
        Ok(end_forces)
    }

    /// Compute equivalent nodal forces (in LOCAL coordinates) for an element
    /// from DISTRIBUTED and POINT loads (NOT including applied moments at
    /// nodes, which are external concentrated loads handled in the global
    /// force vector).
    ///
    /// Returns `[N_i, V_i, M_i, N_j, V_j, M_j]` in local coordinates.
    ///
    /// # Errors
    ///
    /// Propagates any error from [`BeamElement::consistent_nodal_load_point`]
    /// (for example a zero-length element). Point-load positions are validated
    /// when the load is added via [`BeamModel::add_point_load`], so in normal
    /// use this succeeds; the error path exists so that a failed equivalent-load
    /// computation can never be silently turned into a zero load.
    fn element_equivalent_nodal_forces(
        model: &BeamModel,
        elem_idx: usize,
        element: &BeamElement,
        node_i: Point,
        node_j: Point,
    ) -> Result<[f64; 6], FemError> {
        let mut f_equiv = [0.0; 6];

        // Distributed loads on this element.
        for dl in &model.distributed_loads {
            if dl.element_idx == elem_idx {
                let f_local = element.consistent_nodal_load(node_i, node_j, dl.qx, dl.qy)?;
                for i in 0..6 {
                    f_equiv[i] += f_local[i];
                }
            }
        }

        // Point loads on this element.
        for pl in &model.point_loads {
            if pl.element_idx == elem_idx {
                let f_local = element.consistent_nodal_load_point(
                    node_i,
                    node_j,
                    pl.position,
                    pl.fx,
                    pl.fy,
                    pl.mz,
                )?;
                for i in 0..6 {
                    f_equiv[i] += f_local[i];
                }
            }
        }

        Ok(f_equiv)
    }

    /// Compute element end forces in GLOBAL coordinates
    ///
    /// Returns a vector of 6 forces per element in global coordinates:
    /// [Fx_i, Fy_i, Mz_i, Fx_j, Fy_j, Mz_j]
    ///
    /// # Errors
    ///
    /// Propagates any error from [`Self::element_end_forces`].
    pub fn element_end_forces_global(&self) -> Result<Vec<[f64; 6]>, FemError> {
        let local_forces = self.element_end_forces()?;
        let mut results = Vec::new();

        for (idx, forces) in local_forces.iter().enumerate() {
            let element = &self.model.elements[idx];
            let node_i = self.model.nodes[element.node_i].point();
            let node_j = self.model.nodes[element.node_j].point();

            let T = element.transformation_matrix(node_i, node_j);

            // Transform local forces to global: f_global = T^T * f_local
            let mut f_global_elem = [0.0; 6];
            for i in 0..6 {
                for j in 0..6 {
                    f_global_elem[i] += T[j][i] * forces[j];
                }
            }

            results.push(f_global_elem);
        }

        Ok(results)
    }

    /// Compute the internal section forces `N`, `V`, `M` at normalized position
    /// `xi` along element `element_idx`, in LOCAL coordinates.
    ///
    /// `xi = 0` at `node_i` and `xi = 1` at `node_j`; the physical position is
    /// `x = xi · L`.
    ///
    /// # What this returns
    ///
    /// True beam-section internal resultants at the cut (see [`SectionForces`]
    /// for the sign convention):
    /// - `axial` (`N`): tension positive,
    /// - `shear` (`V`): satisfies `d(moment)/dx = shear`,
    /// - `moment` (`M`): sagging positive.
    ///
    /// These are beam-LOCAL quantities (not transformed to global axes). They
    /// are deliberately distinct from [`Self::element_end_forces`], which
    /// returns the element-on-node *nodal equilibrium* forces at the two ends
    /// only.
    ///
    /// # Method (equilibrium recovery)
    ///
    /// The result is obtained by enforcing equilibrium of the element segment
    /// `[0, x]` using the recovered i-end element-on-node force and the actual
    /// distributed / point loads — **not** by linearly interpolating the end
    /// forces. With the local axes of this module (+x from `node_i` to
    /// `node_j`, +y transverse with upward load `qy > 0`, `θ` CCW) and the
    /// i-end force `f_i = [N_i, V_i, M_i]` from [`Self::element_end_forces`]:
    ///
    /// ```text
    /// N(x) = N_i - qx·x - Σ_{x_p < x} fx_p
    /// V(x) = -V_i + qy·x + Σ_{x_p < x} fy_p
    /// M(x) = M_i - x·V_i + qy·x²/2 - Σ_{x_p < x} [(x_p - x)·fy_p + mz_p]
    /// ```
    ///
    /// This is the equilibrium-consistent extension of the Euler–Bernoulli
    /// relations: for an element with no span load (no distributed load and no
    /// interior point load) it reduces to the classical `N = E·A·du/dx` and
    /// `M = E·I·v''` implied by the element's cubic Hermite field, while
    /// additionally satisfying
    ///
    /// ```text
    /// dN/dx = -qx
    /// dV/dx =  qy          (qy = upward load intensity; = -q_down)
    /// dM/dx =  V
    /// ```
    ///
    /// and reproducing the correct jumps at interior point forces / moments.
    /// For statically determinate loadings the section forces are exact.
    ///
    /// # Discontinuities (point loads inside the element)
    ///
    /// A load at `x_p = xi_p · L` introduces a jump with this convention:
    ///
    /// ```text
    /// N(xi_p⁺) - N(xi_p⁻) = -fx_p
    /// V(xi_p⁺) - V(xi_p⁻) = +fy_p
    /// M(xi_p⁺) - M(xi_p⁻) = -mz_p
    /// ```
    ///
    /// Evaluating exactly at `xi = xi_p` returns the **left limit**
    /// (`x -> xi_p⁻`): loads located strictly before `xi` are included and a
    /// load exactly at `xi` is excluded. Evaluate at `xi_p ± ε` (or on the
    /// adjacent elements) to obtain the right-hand value.
    ///
    /// # Relation to element end forces
    ///
    /// At the element ends the section forces agree with
    /// [`Self::element_end_forces`] up to the sign factors of the
    /// internal-force convention:
    ///
    /// ```text
    /// xi = 0:  N = +N_i,  V = -V_i,  M = +M_i
    /// xi = 1:  N = -N_j,  V = +V_j,  M = -M_j
    /// ```
    ///
    /// # Nodal applied moments vs. interior point moments
    ///
    /// Two different moment-load mechanisms exist and must not be conflated:
    ///
    /// - [`BeamModel::add_point_load`] / [`BeamModel::add_point_moment`] stores
    ///   a moment *inside* an element (`0 < xi_p < 1`). It is a span load and
    ///   produces the interior jump `M(xi_p⁺) - M(xi_p⁻) = -mz_p` above.
    /// - [`BeamModel::add_applied_moment`] stores a concentrated moment at a
    ///   *mesh node*. It is **not** a span load: it enters the global force
    ///   vector (the θ DOF) and is therefore already carried by the
    ///   element-on-node end forces from which this recovery is built, so no
    ///   separate term is added here. (Adding one would double-count it.)
    ///
    /// For an internal node shared by elements `e` and `e+1` carrying an
    /// applied nodal moment `M_ext`, the recovered section moments on the two
    /// sides satisfy the nodal moment equilibrium
    ///
    /// ```text
    /// M(e+1, xi=0) - M(e, xi=1) + M_ext = 0
    /// ```
    ///
    /// which is the section-force form of the element-on-node end-force
    /// equilibrium `M_j(e) + M_i(e+1) + M_ext = 0` under the boundary relations
    /// above. Equivalently, the internal moment jumps by `-M_ext` across the
    /// node — the same sign as an interior point moment of equal value. A nodal
    /// moment applied at a free end yields a constant `+M_ext` along the
    /// element.
    ///
    /// ## Internal-node limits
    ///
    /// The "exact evaluation returns the left limit" rule applies to interior
    /// point loads with `0 < xi_p < 1`. A nodal applied moment is not evaluated
    /// from within one element; the meaningful statement is the two-sided
    /// equilibrium relation above between `element_section_forces(e, 1.0)` and
    /// `element_section_forces(e+1, 0.0)`.
    ///
    /// # Errors
    ///
    /// Returns [`FemError::InvalidInput`] if `element_idx` is out of bounds,
    /// if `xi` is outside `[0, 1]`, or if the element has zero length.
    pub fn element_section_forces(
        &self,
        element_idx: usize,
        xi: f64,
    ) -> Result<SectionForces, FemError> {
        let element = self.model.elements.get(element_idx).ok_or_else(|| {
            FemError::InvalidInput(format!(
                "Invalid element index: {} (max: {})",
                element_idx,
                self.model.elements.len().saturating_sub(1)
            ))
        })?;
        if !(0.0..=1.0).contains(&xi) {
            return Err(FemError::InvalidInput(format!(
                "Section position xi must be in [0, 1], got {}",
                xi
            )));
        }
        let node_i = self.model.nodes[element.node_i].point();
        let node_j = self.model.nodes[element.node_j].point();
        let length = element.length(node_i, node_j);
        if length <= 0.0 {
            return Err(FemError::InvalidInput(
                "Beam element has zero or negative length for section-force recovery".to_string(),
            ));
        }

        let x = xi * length;

        // Anchor at the i-end element-on-node force (LOCAL): [N_i, V_i, M_i, ...].
        let f_end = self.element_on_node_end_forces_local(element_idx)?;
        let n_i = f_end[0];
        let v_i = f_end[1];
        let m_i = f_end[2];

        // Uniform distributed load on this element (LOCAL), summed if repeated.
        let mut qx = 0.0;
        let mut qy = 0.0;
        for dl in &self.model.distributed_loads {
            if dl.element_idx == element_idx {
                qx += dl.qx;
                qy += dl.qy;
            }
        }

        // Point loads strictly to the left of x (left-limit convention).
        let mut sum_fx = 0.0;
        let mut sum_fy = 0.0;
        let mut sum_moment = 0.0;
        for pl in &self.model.point_loads {
            if pl.element_idx != element_idx {
                continue;
            }
            let x_p = pl.position * length;
            if x_p < x {
                sum_fx += pl.fx;
                sum_fy += pl.fy;
                sum_moment += (x_p - x) * pl.fy + pl.mz;
            }
        }

        let axial = n_i - qx * x - sum_fx;
        let shear = -v_i + qy * x + sum_fy;
        let moment = m_i - x * v_i + 0.5 * qy * x * x - sum_moment;

        Ok(SectionForces::new(axial, shear, moment))
    }

    /// Beam arclength from the start of element 0 to the start (`xi = 0`) of
    /// `element_index`, accumulated in model order.
    ///
    /// Private helper shared by the sampling APIs. `element_index` is assumed
    /// already validated; indices `>= elements.len()` simply sum all elements.
    fn element_start_distance(&self, element_index: usize) -> f64 {
        self.model
            .elements
            .iter()
            .take(element_index)
            .map(|e| {
                let ni = self.model.nodes[e.node_i].point();
                let nj = self.model.nodes[e.node_j].point();
                e.length(ni, nj)
            })
            .sum()
    }

    /// Sample the internal-force diagram of a single element at `n` uniformly
    /// spaced points, including both endpoints.
    ///
    /// Samples `xi = k / (n - 1)` for `k = 0..=n-1` (i.e. `k = 0, 1, …, n-1`),
    /// so `xi = 0` and `xi = 1` are always included. Each sample delegates to
    /// [`Self::element_section_forces`] — the N/V/M values are **not**
    /// interpolated or recomputed here.
    ///
    /// # Arguments
    ///
    /// - `element_index`: element index in `BeamModel::elements` order.
    /// - `n`: number of samples, must be `>= 2`.
    ///
    /// The returned samples carry the global beam arclength `x` (see
    /// [`BeamForceSample`]), measured from the start of element 0, so a sample
    /// on element `e` starts at `Σ_{k < e} length(k)`.
    ///
    /// # Discontinuities
    ///
    /// If a uniform `xi` lands exactly on an interior point load, the value is
    /// the existing **left-limit** result of
    /// [`Self::element_section_forces`]. No epsilon sampling is applied.
    ///
    /// # Errors
    ///
    /// Returns [`FemError::InvalidInput`] if `n < 2`, if `element_index` is out
    /// of bounds, or if the element has zero length.
    pub fn sample_element_forces(
        &self,
        element_index: usize,
        n: usize,
    ) -> Result<Vec<BeamForceSample>, FemError> {
        if n < 2 {
            return Err(FemError::InvalidInput(format!(
                "Number of samples n must be >= 2, got {}",
                n
            )));
        }
        if element_index >= self.model.elements.len() {
            return Err(FemError::InvalidInput(format!(
                "Invalid element index: {} (max: {})",
                element_index,
                self.model.elements.len().saturating_sub(1)
            )));
        }

        let element = &self.model.elements[element_index];
        let node_i = self.model.nodes[element.node_i].point();
        let node_j = self.model.nodes[element.node_j].point();
        let length = element.length(node_i, node_j);
        let start = self.element_start_distance(element_index);

        let mut samples = Vec::with_capacity(n);
        for k in 0..n {
            let xi = k as f64 / (n - 1) as f64;
            // Delegates to the authoritative recovery (also validates a
            // zero-length element via its existing error path).
            let section_forces = self.element_section_forces(element_index, xi)?;
            samples.push(BeamForceSample {
                element_index,
                xi,
                x: start + xi * length,
                section_forces,
            });
        }
        Ok(samples)
    }

    /// Sample the internal-force diagram of the whole beam at `n_per_element`
    /// uniformly spaced points per element.
    ///
    /// Elements are traversed in `BeamModel::elements` order. Global `x` is the
    /// physical beam arclength accumulated over the true element lengths (equal
    /// lengths are NOT assumed):
    /// `x = Σ_{k < e} length(k) + xi · length(e)`.
    ///
    /// # Shared boundaries are duplicated on purpose
    ///
    /// The last sample of element `e` (`xi = 1`) and the first sample of
    /// element `e+1` (`xi = 0`) share the same `x`. Both are returned:
    ///
    /// - when the internal force is continuous, the two values agree;
    /// - at a point force / moment discontinuity they differ and represent the
    ///   two one-sided limits.
    ///
    /// Duplicate `x` coordinates are **never** deduplicated — doing so would
    /// destroy discontinuities for a future plotting layer.
    ///
    /// # Errors
    ///
    /// Returns [`FemError::InvalidInput`] if `n_per_element < 2`, or for any
    /// per-element error from [`Self::sample_element_forces`].
    pub fn sample_beam_forces(
        &self,
        n_per_element: usize,
    ) -> Result<Vec<BeamForceSample>, FemError> {
        if n_per_element < 2 {
            return Err(FemError::InvalidInput(format!(
                "Number of samples per element must be >= 2, got {}",
                n_per_element
            )));
        }
        let mut samples = Vec::with_capacity(n_per_element * self.model.elements.len());
        for element_index in 0..self.model.elements.len() {
            samples.extend(self.sample_element_forces(element_index, n_per_element)?);
        }
        Ok(samples)
    }

    /// Sample the whole beam and wrap the result in a [`BeamForceDiagram`].
    ///
    /// Equivalent to [`Self::sample_beam_forces`] plus a container. No
    /// interpolation is performed.
    ///
    /// # Errors
    ///
    /// Same as [`Self::sample_beam_forces`].
    pub fn beam_force_diagram(&self, n_per_element: usize) -> Result<BeamForceDiagram, FemError> {
        Ok(BeamForceDiagram::new(
            self.sample_beam_forces(n_per_element)?,
        ))
    }

    /// Build a unified, read-only [`BeamAnalysisResult`] view of this solver.
    ///
    /// This does **not** run the solver: it is a cheap, infallible view over the
    /// current displacement state, so call [`Self::solve`] first. The reaction
    /// vector is snapshotted once here (masking unconstrained DOFs to exactly
    /// zero); everything else is delegated lazily to the solver.
    pub fn results(&self) -> BeamAnalysisResult<'_> {
        let mut reactions = self.reactions();
        for (i, reaction) in reactions.iter_mut().enumerate() {
            if !self.fixed_dofs[i] {
                *reaction = 0.0;
            }
        }
        BeamAnalysisResult {
            solver: self,
            reactions,
        }
    }
}

/// FemError for beam FEM
#[derive(Debug, Clone, thiserror::Error)]
pub enum FemError {
    #[error("Invalid model: {0}")]
    InvalidModel(String),
    #[error("Solver error: {message}")]
    SolverError {
        /// The structured solver error that caused the failure.
        source: SolverError,
        /// Human-readable message, potentially including structural diagnosis.
        message: String,
    },
    #[error("Invalid input: {0}")]
    InvalidInput(String),
    // ---- frame-level structural diagnostics (see `crate::frame`) ----------
    #[error("Invalid node: {0}")]
    InvalidNode(String),
    #[error("Invalid member: {0}")]
    InvalidMember(String),
    #[error("Zero-length member: {0}")]
    ZeroLengthMember(String),
    #[error("Duplicate member: {0}")]
    DuplicateMember(String),
    #[error("Orphan node: {0}")]
    OrphanNode(String),
    #[error("Disconnected structure: {0}")]
    DisconnectedStructure(String),
    #[error(
        "Conflicting prescribed displacement at node {node_idx}, DOF {dof}: \
             first value {first_value}, conflicting value {conflicting_value}"
    )]
    ConflictingPrescribedDisplacement {
        node_idx: usize,
        dof: usize,
        first_value: f64,
        conflicting_value: f64,
    },
}

impl FemError {
    /// Return the structured [`SolverError`] if this is a `SolverError` variant.
    pub fn solver_error(&self) -> Option<&SolverError> {
        match self {
            FemError::SolverError { source, .. } => Some(source),
            _ => None,
        }
    }
}

impl From<SolverError> for FemError {
    fn from(e: SolverError) -> Self {
        FemError::SolverError {
            message: e.to_string(),
            source: e,
        }
    }
}

/// High-level API for beam analysis
pub struct BeamAnalysis;

impl BeamAnalysis {
    /// Analyze a cantilever beam with tip load
    pub fn cantilever_tip_load(L: f64, E: f64, _A: f64, I: f64, P: f64) -> (f64, f64, f64) {
        // Analytical solutions for cantilever with tip load P at free end
        // Fixed at x=0, load P downward (transverse) at x=L
        let u_tip = 0.0; // No axial displacement for transverse load
        let v_tip = P * L.powi(3) / (3.0 * E * I); // Transverse deflection
        let theta_tip = P * L.powi(2) / (2.0 * E * I); // Rotation

        (u_tip, v_tip, theta_tip)
    }

    /// Analyze a simply supported beam with central point load
    pub fn simply_supported_central_load(L: f64, E: f64, I: f64, P: f64) -> (f64, f64) {
        // Central deflection and rotation at support
        let v_mid = P * L.powi(3) / (48.0 * E * I);
        let theta_support = P * L.powi(2) / (16.0 * E * I);
        (v_mid, theta_support)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::material::Material;

    #[test]
    fn test_beam_section_creation() {
        let sec = BeamSection::new(1.0, 1.0);
        assert_eq!(sec.area, 1.0);
        assert_eq!(sec.second_moment, 1.0);

        let rect = BeamSection::rectangle(0.1, 0.2);
        assert!((rect.area - 0.02).abs() < 1e-10);
        assert!((rect.second_moment - 0.1 * 0.2_f64.powi(3) / 12.0).abs() < 1e-10);

        let circ = BeamSection::circle(0.05);
        assert!((circ.area - std::f64::consts::PI * 0.0025).abs() < 1e-10);
    }

    #[test]
    fn test_local_stiffness() {
        let material = Material::new(200e9, 0.3, 7850.0, "Steel");
        let section = BeamSection::new(0.01, 8.333e-6);
        let element = BeamElement::new(0, 1, material, section).unwrap();

        let node_i = Point::new(0.0, 0.0);
        let node_j = Point::new(1.0, 0.0);

        let k = element.local_stiffness(node_i, node_j);

        // Check symmetry
        for i in 0..6 {
            for j in 0..6 {
                assert!(
                    (k[i][j] - k[j][i]).abs() < 1e-10,
                    "Matrix not symmetric at ({},{})",
                    i,
                    j
                );
            }
        }

        // Check axial terms
        let E: f64 = 200e9;
        let A: f64 = 0.01;
        let L: f64 = 1.0;
        let EA_L = E * A / L;
        assert!((k[0][0] - EA_L).abs() < 1e-6);
        assert!((k[0][3] + EA_L).abs() < 1e-6);
        assert!((k[3][3] - EA_L).abs() < 1e-6);

        // Check bending terms
        let I: f64 = 8.333e-6;
        let EI_L3 = E * I / L.powi(3);
        let EI_L2 = E * I / L.powi(2);
        let EI_L = E * I / L;

        assert!((k[1][1] - 12.0 * EI_L3).abs() < 1e-6);
        assert!((k[1][2] - 6.0 * EI_L2).abs() < 1e-6);
        assert!((k[2][2] - 4.0 * EI_L).abs() < 1e-6);
        assert!((k[4][4] - 12.0 * EI_L3).abs() < 1e-6);
        assert!((k[5][5] - 4.0 * EI_L).abs() < 1e-6);
    }

    #[test]
    fn test_transformation_matrix() {
        let material = Material::new(200e9, 0.3, 7850.0, "Steel");
        let section = BeamSection::new(0.01, 8.333e-6);
        let element = BeamElement::new(0, 1, material, section).unwrap();

        // Horizontal beam
        let node_i = Point::new(0.0, 0.0);
        let node_j = Point::new(1.0, 0.0);
        let T = element.transformation_matrix(node_i, node_j);

        // For horizontal beam: c=1, s=0
        assert!((T[0][0] - 1.0).abs() < 1e-10);
        assert!((T[1][1] - 1.0).abs() < 1e-10);
        assert!((T[2][2] - 1.0).abs() < 1e-10);
        assert!((T[3][3] - 1.0).abs() < 1e-10);
        assert!((T[4][4] - 1.0).abs() < 1e-10);
        assert!((T[5][5] - 1.0).abs() < 1e-10);

        // Vertical beam
        let node_i = Point::new(0.0, 0.0);
        let node_j = Point::new(0.0, 1.0);
        let T = element.transformation_matrix(node_i, node_j);

        // For vertical beam: c=0, s=1
        assert!((T[0][0] - 0.0).abs() < 1e-10); // c
        assert!((T[0][1] - 1.0).abs() < 1e-10); // s
        assert!((T[1][0] - -1.0).abs() < 1e-10); // -s
        assert!((T[1][1] - 0.0).abs() < 1e-10); // c
    }

    #[test]
    fn test_global_stiffness_horizontal() {
        let material = Material::new(200e9, 0.3, 7850.0, "Steel");
        let section = BeamSection::new(0.01, 8.333e-6);
        let element = BeamElement::new(0, 1, material, section).unwrap();

        let node_i = Point::new(0.0, 0.0);
        let node_j = Point::new(1.0, 0.0);

        let k_global = element.global_stiffness(node_i, node_j);
        let k_local = element.local_stiffness(node_i, node_j);

        // For horizontal beam, global should equal local
        for i in 0..6 {
            for j in 0..6 {
                assert!((k_global[i][j] - k_local[i][j]).abs() < 1e-10);
            }
        }
    }

    #[test]
    fn test_global_stiffness_vertical() {
        let material = Material::new(200e9, 0.3, 7850.0, "Steel");
        let section = BeamSection::new(0.01, 8.333e-6);
        let element = BeamElement::new(0, 1, material, section).unwrap();

        let node_i = Point::new(0.0, 0.0);
        let node_j = Point::new(0.0, 1.0);

        let k_global = element.global_stiffness(node_i, node_j);

        // Check symmetry
        for i in 0..6 {
            for j in 0..6 {
                assert!((k_global[i][j] - k_global[j][i]).abs() < 1e-10);
            }
        }
    }

    #[test]
    fn test_cantilever_analytical() {
        let L = 1.0;
        let E = 200e9;
        let A = 0.01;
        let I = 8.333e-6;
        let P = 1000.0;

        let (u_tip, v_tip, theta_tip) = BeamAnalysis::cantilever_tip_load(L, E, A, I, P);

        // For tip load P downward: axial = 0, v = PL³/3EI, θ = PL²/2EI
        let expected_v = P * L.powi(3) / (3.0 * E * I);
        let expected_theta = P * L.powi(2) / (2.0 * E * I);

        assert!((v_tip - expected_v).abs() < 1e-10);
        assert!((theta_tip - expected_theta).abs() < 1e-10);
        assert!(u_tip.abs() < 1e-10); // No axial load in this case
    }

    #[test]
    fn test_beam_model() {
        let mut model = BeamModel::new();

        model.add_node(BeamNode::new(0, 0.0, 0.0));
        model.add_node(BeamNode::new(1, 1.0, 0.0));

        let material = Material::new(200e9, 0.3, 7850.0, "Steel");
        let section = BeamSection::new(0.01, 8.333e-6);
        model.add_element(BeamElement::new(0, 1, material, section).unwrap());

        model.fix_node(0);
        model.add_nodal_force(1, 1, -1000.0); // Downward force at tip

        assert_eq!(model.n_dof(), 6);
        assert_eq!(model.dof_index(0, 0), 0);
        assert_eq!(model.dof_index(0, 1), 1);
        assert_eq!(model.dof_index(0, 2), 2);
        assert_eq!(model.dof_index(1, 0), 3);
        assert_eq!(model.dof_index(1, 1), 4);
        assert_eq!(model.dof_index(1, 2), 5);
    }

    #[test]
    fn p1_02_reproduce_conflicting_prescribed_displacement() {
        let mut model = BeamModel::new();
        model.add_node(BeamNode::new(0, 0.0, 0.0));
        model.add_node(BeamNode::new(1, 1.0, 0.0));
        model.try_fix_dof(0, 1, 0.0).unwrap();
        let result = model.try_fix_dof(0, 1, 0.01);
        match result {
            Ok(()) => {
                panic!("P1-02 NOT fixed: conflicting prescribed displacement silently accepted")
            }
            Err(e) => println!("P1-02 confirmed: got Err = {:?}", e),
        }
    }

    #[test]
    fn p1_02_same_prescribed_value_is_idempotent() {
        let mut model = BeamModel::new();
        model.add_node(BeamNode::new(0, 0.0, 0.0));
        model.add_node(BeamNode::new(1, 1.0, 0.0));
        model.try_fix_dof(0, 1, 0.005).unwrap();
        model.try_fix_dof(0, 1, 0.005).unwrap();
        assert_eq!(model.fixed_dofs.len(), 1);
    }

    #[test]
    fn p1_02_different_dofs_are_independent() {
        let mut model = BeamModel::new();
        model.add_node(BeamNode::new(0, 0.0, 0.0));
        model.add_node(BeamNode::new(1, 1.0, 0.0));
        model.try_fix_dof(0, 0, 0.0).unwrap();
        model.try_fix_dof(0, 1, 0.01).unwrap();
        model.try_fix_dof(0, 2, 0.02).unwrap();
    }

    #[test]
    fn p1_02_different_nodes_are_independent() {
        let mut model = BeamModel::new();
        model.add_node(BeamNode::new(0, 0.0, 0.0));
        model.add_node(BeamNode::new(1, 1.0, 0.0));
        model.try_fix_dof(0, 0, 0.0).unwrap();
        model.try_fix_dof(1, 0, 0.01).unwrap();
    }

    #[test]
    fn p1_02_override_after_fix_allows_settlement() {
        let mut model = BeamModel::new();
        model.add_node(BeamNode::new(0, 0.0, 0.0));
        model.add_node(BeamNode::new(1, 1.0, 0.0));
        model.try_fix_node(0).unwrap();
        model.try_override_dof(0, 1, -0.005).unwrap();
        assert_eq!(model.fixed_dofs.len(), 3);
        let uy = model
            .fixed_dofs
            .iter()
            .find(|&&(n, d, _)| n == 0 && d == 1)
            .map(|&(_, _, v)| v)
            .unwrap();
        assert_eq!(uy, -0.005);
    }

    #[test]
    fn p1_02_override_replaces_existing_value() {
        let mut model = BeamModel::new();
        model.add_node(BeamNode::new(0, 0.0, 0.0));
        model.add_node(BeamNode::new(1, 1.0, 0.0));
        model.try_override_dof(0, 1, 0.01).unwrap();
        model.try_override_dof(0, 1, 0.02).unwrap();
        assert_eq!(model.fixed_dofs.len(), 1);
        assert_eq!(model.fixed_dofs[0].2, 0.02);
    }
}