pyrucast 0.11.0

Finite-element library in Rust, inspired by cast3m, exposed to Python
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
//! Material symmetry — **isotropic**, **orthotropic**, **anisotropic**.
//!
//! Symmetry is an axis of its own, orthogonal to the kinematic hypothesis
//! ([`Kinematics`]) and to the physics: elasticity, heat conduction and
//! Fickian diffusion all read their coefficients through this module. A physics
//! stores a [`MaterialSymmetry`] and asks here for its constitutive matrix; it
//! never parses a frame or inverts a compliance itself.
//!
//! ## The frame is given by vectors, not angles
//!
//! An orthotropic (or anisotropic) material carries **material axes**, supplied
//! as ordinary components of the material field:
//!
//! | space | components | meaning |
//! |---|---|---|
//! | 2-D | `V1X`, `V1Y` | the first material axis; the second is its in-plane normal |
//! | 3-D | `V1X…V1Z`, `V2X…V2Z` | the first two axes; the third is `V1 × V2` |
//!
//! They are orthonormalised here (Gram-Schmidt), so `V2` need only be
//! *approximately* perpendicular to `V1` — it is the plane they span that
//! matters. Vectors rather than Euler angles: no convention to remember, no
//! gimbal case, and the frame varies naturally from cell to cell (a wound
//! composite, a rolled plate) since it travels through the material field like
//! any other coefficient.
//!
//! ## How the constitutive matrix is built
//!
//! Always the same three steps, whatever the physics:
//!
//! 1. build the coefficient tensor **in the material axes** (where orthotropy is
//!    diagonal and the anisotropic constants are given);
//! 2. rotate it to the global axes;
//! 3. reduce it to the kinematics (plane stress / plane strain / axisymmetric / solid).
//!
//! The rotation of the elastic tensor goes through the **fourth-order tensor**
//! `C_ijkl`, not through a 6×6 Bond matrix. It costs `3⁸` multiply-adds each
//! time it is built — at every Gauss point for the elastic stiffness, whose
//! material may vary inside a cell — and it removes the
//! whole family of index and factor-of-two mistakes that Voigt rotation
//! formulas invite. With **engineering** shear the Voigt ↔ tensor map carries no
//! factor at all: `C_ijkl = D[voigt(i,j)][voigt(k,l)]`.
//!
//! **Isotropy is left untouched**: it short-circuits to
//! [`elastic::constitutive`] and to
//! the plain scalar conductivity, so every existing assembly keeps its exact
//! numbers.

use crate::containers::element_field::SubElementField;
use crate::containers::field::SubField;
use crate::error::{PyrucastError, Result};
use crate::models::continuum::elastic;
use crate::models::tensor::Kinematics;
use nalgebra::{Matrix3, Vector3};
use serde::{Deserialize, Serialize};

/// Which material symmetry the coefficients of a physics obey.
///
/// Mirrors Cast3M, where `ISOTROPE` / `ORTHOTROPE` / `ANISOTROPE` qualifies the
/// **material** of a formulation rather than naming a different kinematics — hence an
/// axis carried by the existing physics, not three duplicated ones.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::tensor::Kinematics;
/// # use pyrucast::models::symmetry::{self, MaterialSymmetry};
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let mut mat = SubElementField::from_uniform_per_component(
/// #     fes.get(0).unwrap(),
/// #     vec!["k_1".into(), "k_2".into(), "k_3".into(), "V1X".into(), "V1Y".into()],
/// #     &[9.0, 1.0, 1.0, 0.0, 1.0]).unwrap();
/// // One axis carried by the existing physics, not three duplicated physics:
/// // it is the **material** that is isotropic, orthotropic or anisotropic.
/// assert!(!MaterialSymmetry::Isotropic.has_frame());
/// assert!(MaterialSymmetry::Orthotropic.has_frame());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum MaterialSymmetry {
    /// Two constants, no privileged direction.
    #[default]
    Isotropic,
    /// Three orthogonal material axes, each with its own moduli.
    Orthotropic,
    /// The full tensor of constants, in a material frame.
    Anisotropic,
}

impl MaterialSymmetry {
    /// The lowercase name of this symmetry — the inverse of
    /// [`from_name`](crate::named::Named::from_name).
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::element_field::SubElementField;
    /// # use pyrucast::containers::field::SubField;
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::{self, MaterialSymmetry};
    /// # use pyrucast::named::Named;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
    /// # let mut mat = SubElementField::from_uniform_per_component(
    /// #     fes.get(0).unwrap(),
    /// #     vec!["k_1".into(), "k_2".into(), "k_3".into(), "V1X".into(), "V1Y".into()],
    /// #     &[9.0, 1.0, 1.0, 0.0, 1.0]).unwrap();
    /// assert_eq!(MaterialSymmetry::Anisotropic.name(), "anisotropic");
    /// // The exact inverse of `from_name`, and case does not matter.
    /// assert_eq!(MaterialSymmetry::from_name(MaterialSymmetry::Anisotropic.name()),
    ///            Some(MaterialSymmetry::Anisotropic));
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn name(self) -> &'static str {
        match self {
            Self::Isotropic => "isotropic",
            Self::Orthotropic => "orthotropic",
            Self::Anisotropic => "anisotropic",
        }
    }

    /// Whether this symmetry needs material axes (everything but isotropy).
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::element_field::SubElementField;
    /// # use pyrucast::containers::field::SubField;
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::{self, MaterialSymmetry};
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
    /// # let mut mat = SubElementField::from_uniform_per_component(
    /// #     fes.get(0).unwrap(),
    /// #     vec!["k_1".into(), "k_2".into(), "k_3".into(), "V1X".into(), "V1Y".into()],
    /// #     &[9.0, 1.0, 1.0, 0.0, 1.0]).unwrap();
    /// // A material frame only makes sense if there is a preferred direction.
    /// assert!(!MaterialSymmetry::Isotropic.has_frame());
    /// assert!(MaterialSymmetry::Anisotropic.has_frame());
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn has_frame(self) -> bool {
        self != Self::Isotropic
    }
}

impl crate::named::Named for MaterialSymmetry {
    const LABEL: &'static str = "symmetry";
    const VALUES: &'static [Self] = &[Self::Isotropic, Self::Orthotropic, Self::Anisotropic];

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

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

// ─── The material frame ─────────────────────────────────────────────────────

/// Frame components required in 2-D: the first axis, in the plane.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::tensor::Kinematics;
/// # use pyrucast::models::symmetry::{self, MaterialSymmetry};
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let mut mat = SubElementField::from_uniform_per_component(
/// #     fes.get(0).unwrap(),
/// #     vec!["k_1".into(), "k_2".into(), "k_3".into(), "V1X".into(), "V1Y".into()],
/// #     &[9.0, 1.0, 1.0, 0.0, 1.0]).unwrap();
/// // In 2-D the first axis is enough: the second is its in-plane normal.
/// assert_eq!(symmetry::FRAME_2D, ["V1X", "V1Y"]);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub const FRAME_2D: [&str; 2] = ["V1X", "V1Y"];
/// Frame components required in 3-D: the first two axes (the third is `V1 × V2`).
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::tensor::Kinematics;
/// # use pyrucast::models::symmetry::{self, MaterialSymmetry};
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let mut mat = SubElementField::from_uniform_per_component(
/// #     fes.get(0).unwrap(),
/// #     vec!["k_1".into(), "k_2".into(), "k_3".into(), "V1X".into(), "V1Y".into()],
/// #     &[9.0, 1.0, 1.0, 0.0, 1.0]).unwrap();
/// // In 3-D, two axes; the third is V1 × V2.
/// assert_eq!(symmetry::FRAME_3D.len(), 6);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub const FRAME_3D: [&str; 6] = ["V1X", "V1Y", "V1Z", "V2X", "V2Y", "V2Z"];

/// The frame components a symmetry requires in a space of dimension `space_dim`
/// — empty for isotropy, which has no privileged direction.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::tensor::Kinematics;
/// # use pyrucast::models::symmetry::{self, MaterialSymmetry};
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let mut mat = SubElementField::from_uniform_per_component(
/// #     fes.get(0).unwrap(),
/// #     vec!["k_1".into(), "k_2".into(), "k_3".into(), "V1X".into(), "V1Y".into()],
/// #     &[9.0, 1.0, 1.0, 0.0, 1.0]).unwrap();
/// // What the material field must carry **on top of** the constants.
/// assert!(symmetry::frame_components(MaterialSymmetry::Isotropic, 3).is_empty());
/// assert_eq!(symmetry::frame_components(MaterialSymmetry::Orthotropic, 2).len(), 2);
/// assert_eq!(symmetry::frame_components(MaterialSymmetry::Orthotropic, 3).len(), 6);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn frame_components(symmetry: MaterialSymmetry, space_dim: usize) -> &'static [&'static str] {
    if !symmetry.has_frame() {
        &[]
    } else if space_dim == 2 {
        &FRAME_2D
    } else {
        &FRAME_3D
    }
}

/// The rotation `R` taking **material** axes to **global** axes (its columns are
/// the material axes expressed globally), read from the material field of `cell`.
///
/// In 3-D, `V1` and `V2` are orthonormalised by Gram-Schmidt and the third axis
/// closes a right-handed frame. In 2-D only `V1` is read: the second axis is its
/// in-plane normal and the third is the out-of-plane direction, which keeps the
/// hoop direction of an axisymmetric kinematics as a material axis — as it must be.
///
/// Errors on a degenerate frame (a null `V1`, or a `V2` parallel to it), which
/// would otherwise produce a silently meaningless material.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::tensor::Kinematics;
/// # use pyrucast::models::symmetry::{self, MaterialSymmetry};
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let mut mat = SubElementField::from_uniform_per_component(
/// #     fes.get(0).unwrap(),
/// #     vec!["k_1".into(), "k_2".into(), "k_3".into(), "V1X".into(), "V1Y".into()],
/// #     &[9.0, 1.0, 1.0, 0.0, 1.0]).unwrap();
/// // R takes the **material** axes to the global ones: its columns are the
/// // axes matériau vus globalement. Ici V1 = (0, 1) : un quart de tour. Le
/// // frame closes the contract, so it starts here at position 3.
/// let ligne = mat.point_values(0, 0)?.to_vec();
/// let r = symmetry::frame_rotation(|k| ligne[k], 3, 2)?;
/// assert!((r[(0, 0)] - 0.0).abs() < 1e-12 && (r[(1, 0)] - 1.0).abs() < 1e-12);
/// // A degenerate frame is refused rather than silently absurd.
/// mat.set_uniform("V1Y", 0.0)?;
/// let nul = mat.point_values(0, 0)?.to_vec();
/// assert!(symmetry::frame_rotation(|k| nul[k], 3, 2).is_err());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn frame_rotation(
    v: impl Fn(usize) -> f64,
    frame_at: usize,
    space_dim: usize,
) -> Result<Matrix3<f64>> {
    // The frame components close every anisotropic contract, in the order
    // V1X, V1Y(, V1Z, V2X, V2Y, V2Z) — `frame_at` is where they start.
    let read = |k: usize| -> Result<f64> { Ok(v(frame_at + k)) };
    let degenerate = |what: &str| {
        PyrucastError::Message(format!(
            "material frame: {what} — the orthotropy axes must be non-null and independent \
             (V1, V2 are orthonormalised, so V2 need only be roughly perpendicular to V1)"
        ))
    };

    if space_dim == 2 {
        let v1 = Vector3::new(read(0)?, read(1)?, 0.0);
        let e1 = v1
            .try_normalize(f64::EPSILON)
            .ok_or_else(|| degenerate("V1 is null"))?;
        // The in-plane normal, then the out-of-plane axis: a right-handed frame
        // whose third axis is `z` (the hoop direction in axisymmetry).
        let e2 = Vector3::new(-e1[1], e1[0], 0.0);
        let e3 = Vector3::new(0.0, 0.0, 1.0);
        return Ok(Matrix3::from_columns(&[e1, e2, e3]));
    }

    let v1 = Vector3::new(read(0)?, read(1)?, read(2)?);
    let v2 = Vector3::new(read(3)?, read(4)?, read(5)?);
    let e1 = v1
        .try_normalize(f64::EPSILON)
        .ok_or_else(|| degenerate("V1 is null"))?;
    // Gram-Schmidt: strip from V2 whatever it has along V1.
    let e2 = (v2 - e1 * v2.dot(&e1))
        .try_normalize(f64::EPSILON)
        .ok_or_else(|| degenerate("V2 is null or parallel to V1"))?;
    let e3 = e1.cross(&e2);
    Ok(Matrix3::from_columns(&[e1, e2, e3]))
}

// ─── Voigt ↔ fourth-order tensor ────────────────────────────────────────────

/// Voigt slot of a tensor index pair, in this crate's order
/// `[xx, yy, zz, yz, xz, xy]`. Symmetric, so `(i,j)` and `(j,i)` agree.
const VOIGT_OF: [[usize; 3]; 3] = [[0, 5, 4], [5, 1, 3], [4, 3, 2]];

/// A fourth-order stiffness tensor `C_ijkl`.
type Tensor4 = [[[[f64; 3]; 3]; 3]; 3];

/// `C_ijkl = D[voigt(i,j)][voigt(k,l)]` — exact, no factor, because `D` is
/// expressed against **engineering** shear (`γ = 2ε`), which is precisely what
/// absorbs the double-counting of the off-diagonal pairs in `C_ijkl ε_kl`.
fn to_tensor(d: &[[f64; 6]; 6]) -> Tensor4 {
    let mut c = [[[[0.0; 3]; 3]; 3]; 3];
    for (i, ci) in c.iter_mut().enumerate() {
        for (j, cij) in ci.iter_mut().enumerate() {
            for (k, cijk) in cij.iter_mut().enumerate() {
                for (l, v) in cijk.iter_mut().enumerate() {
                    *v = d[VOIGT_OF[i][j]][VOIGT_OF[k][l]];
                }
            }
        }
    }
    c
}

/// The inverse map: pick the representative index pair of each Voigt slot.
fn from_tensor(c: &Tensor4) -> [[f64; 6]; 6] {
    const PAIRS: [(usize, usize); 6] = [(0, 0), (1, 1), (2, 2), (1, 2), (0, 2), (0, 1)];
    let mut d = [[0.0; 6]; 6];
    for (a, &(i, j)) in PAIRS.iter().enumerate() {
        for (b, &(k, l)) in PAIRS.iter().enumerate() {
            d[a][b] = c[i][j][k][l];
        }
    }
    d
}

/// Rotate a fourth-order tensor from material to global axes:
/// `C'_pqrs = R_pi R_qj R_rk R_sl C_ijkl`.
fn rotate_tensor(c: &Tensor4, r: &Matrix3<f64>) -> Tensor4 {
    // Four successive single-index contractions instead of one 8-fold loop:
    // 4·3⁵ = 972 multiply-adds rather than 3⁸ = 6561, and each pass is a plain
    // matrix product along one axis.
    let mut a = *c;
    for _axis in 0..4 {
        let mut b = [[[[0.0; 3]; 3]; 3]; 3];
        for (p, bp) in b.iter_mut().enumerate() {
            for (j, bpj) in bp.iter_mut().enumerate() {
                for (k, bpjk) in bpj.iter_mut().enumerate() {
                    for (l, v) in bpjk.iter_mut().enumerate() {
                        let mut acc = 0.0;
                        for i in 0..3 {
                            acc += r[(p, i)] * a[i][j][k][l];
                        }
                        *v = acc;
                    }
                }
            }
        }
        // Cycle the axes so the next pass contracts the following index.
        let mut rotated = [[[[0.0; 3]; 3]; 3]; 3];
        for (i, ri) in rotated.iter_mut().enumerate() {
            for (j, rij) in ri.iter_mut().enumerate() {
                for (k, rijk) in rij.iter_mut().enumerate() {
                    for (l, v) in rijk.iter_mut().enumerate() {
                        *v = b[j][k][l][i];
                    }
                }
            }
        }
        a = rotated;
    }
    a
}

/// Rotate a 6×6 engineering-Voigt matrix from material to global axes.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::tensor::Kinematics;
/// # use pyrucast::models::symmetry::{self, MaterialSymmetry};
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let mut mat = SubElementField::from_uniform_per_component(
/// #     fes.get(0).unwrap(),
/// #     vec!["k_1".into(), "k_2".into(), "k_3".into(), "V1X".into(), "V1Y".into()],
/// #     &[9.0, 1.0, 1.0, 0.0, 1.0]).unwrap();
/// # use nalgebra::Matrix3;
/// // An identity rotation changes nothing…
/// let d = symmetry::orthotropic_from_constants(
///     [210e3, 10e3, 10e3], [0.3, 0.3, 0.3], [5e3, 5e3, 5e3])?;
/// assert_eq!(symmetry::rotate_voigt(&d, &Matrix3::identity()), d);
/// // …a quarter turn swaps the first two directions.
/// let ligne = mat.point_values(0, 0)?.to_vec();
/// let r = symmetry::frame_rotation(|k| ligne[k], 3, 2)?;
/// let dr = symmetry::rotate_voigt(&d, &r);
/// assert!((dr[0][0] - d[1][1]).abs() < 1e-6);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn rotate_voigt(d: &[[f64; 6]; 6], r: &Matrix3<f64>) -> [[f64; 6]; 6] {
    from_tensor(&rotate_tensor(&to_tensor(d), r))
}

// ─── Elasticity ─────────────────────────────────────────────────────────────

/// Orthotropic elastic constants, in the material axes.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::tensor::Kinematics;
/// # use pyrucast::models::symmetry::{self, MaterialSymmetry};
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let mut mat = SubElementField::from_uniform_per_component(
/// #     fes.get(0).unwrap(),
/// #     vec!["k_1".into(), "k_2".into(), "k_3".into(), "V1X".into(), "V1Y".into()],
/// #     &[9.0, 1.0, 1.0, 0.0, 1.0]).unwrap();
/// // Nine constants in the material axes: three moduli, three
/// // coefficients de Poisson, trois modules de cisaillement.
/// assert_eq!(symmetry::ORTHOTROPIC_ELASTIC[0], "E_1");
/// assert_eq!(symmetry::ORTHOTROPIC_ELASTIC.len(), 9);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub const ORTHOTROPIC_ELASTIC: [&str; 9] = [
    "E_1", "E_2", "E_3", "nu_12", "nu_13", "nu_23", "G_12", "G_13", "G_23",
];

/// The 21 independent constants of a general anisotropic stiffness, named
/// `C_<i><j>` over the upper triangle of the Voigt matrix (`1..=6`, this crate's
/// order `[xx, yy, zz, yz, xz, xy]`).
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::tensor::Kinematics;
/// # use pyrucast::models::symmetry::{self, MaterialSymmetry};
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let mut mat = SubElementField::from_uniform_per_component(
/// #     fes.get(0).unwrap(),
/// #     vec!["k_1".into(), "k_2".into(), "k_3".into(), "V1X".into(), "V1Y".into()],
/// #     &[9.0, 1.0, 1.0, 0.0, 1.0]).unwrap();
/// // The 21 independent constants, on Voigt's upper triangle.
/// assert_eq!(symmetry::ANISOTROPIC_ELASTIC[0], "C_11");
/// assert_eq!(symmetry::ANISOTROPIC_ELASTIC.len(), 21);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub const ANISOTROPIC_ELASTIC: [&str; 21] = [
    "C_11", "C_12", "C_13", "C_14", "C_15", "C_16", "C_22", "C_23", "C_24", "C_25", "C_26", "C_33",
    "C_34", "C_35", "C_36", "C_44", "C_45", "C_46", "C_55", "C_56", "C_66",
];

/// Full 3-D orthotropic stiffness in the material axes: invert the normal
/// compliance block, and put the three shear moduli on the diagonal.
///
/// The compliance uses the reciprocity relations `ν_ji/E_j = ν_ij/E_i`, so only
/// the three « major » Poisson ratios are asked for. Errors if the resulting
/// compliance is singular — which is what an inconsistent set of ratios
/// (`ν_12² > E_1/E_2`, …) produces, and which would otherwise assemble a
/// non-positive stiffness in silence.
fn orthotropic_stiffness(v: impl Fn(usize) -> f64) -> Result<[[f64; 6]; 6]> {
    // Positions in [`ORTHOTROPIC_ELASTIC`], which opens every orthotropic
    // material contract: the nine constants, then the frame.
    orthotropic_from_constants([v(0), v(1), v(2)], [v(3), v(4), v(5)], [v(6), v(7), v(8)])
}

/// The same, from bare constants — the arithmetic core, so it can be exercised
/// without a material field. `nu` is `[ν_12, ν_13, ν_23]`, `g` is `[G_12, G_13, G_23]`.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::tensor::Kinematics;
/// # use pyrucast::models::symmetry::{self, MaterialSymmetry};
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let mut mat = SubElementField::from_uniform_per_component(
/// #     fes.get(0).unwrap(),
/// #     vec!["k_1".into(), "k_2".into(), "k_3".into(), "V1X".into(), "V1Y".into()],
/// #     &[9.0, 1.0, 1.0, 0.0, 1.0]).unwrap();
/// // The arithmetic core, exercisable without a material field. A material
/// // orthotrope dégénéré en isotrope redonne la matrice isotrope.
/// let d = symmetry::orthotropic_from_constants(
///     [210e3, 210e3, 210e3], [0.3, 0.3, 0.3], [80769.0, 80769.0, 80769.0])?;
/// assert!((d[0][0] - d[1][1]).abs() < 1e-6);
/// assert!((d[0][1] - d[0][2]).abs() < 1e-6);
/// // A null or negative modulus is refused; the compliance must further
/// // rester inversible.
/// assert!(symmetry::orthotropic_from_constants(
///     [0.0, 210e3, 210e3], [0.3, 0.3, 0.3], [80769.0, 80769.0, 80769.0]).is_err());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn orthotropic_from_constants(e: [f64; 3], nu: [f64; 3], g: [f64; 3]) -> Result<[[f64; 6]; 6]> {
    let ([e1, e2, e3], [nu12, nu13, nu23], [g12, g13, g23]) = (e, nu, g);
    for (name, value) in [("E_1", e1), ("E_2", e2), ("E_3", e3)] {
        if value <= 0.0 {
            return Err(PyrucastError::Message(format!(
                "orthotropic elasticity: {name} = {value} — the Young moduli must be positive"
            )));
        }
    }
    let compliance = Matrix3::new(
        1.0 / e1,
        -nu12 / e1,
        -nu13 / e1,
        -nu12 / e1,
        1.0 / e2,
        -nu23 / e2,
        -nu13 / e1,
        -nu23 / e2,
        1.0 / e3,
    );
    let normal = compliance.try_inverse().ok_or_else(|| {
        PyrucastError::Message(
            "orthotropic elasticity: the compliance is singular — check the Poisson ratios \
             (a physical set satisfies nu_ij² < E_i/E_j)"
                .into(),
        )
    })?;
    let mut d = [[0.0; 6]; 6];
    for i in 0..3 {
        for j in 0..3 {
            d[i][j] = normal[(i, j)];
        }
    }
    // Voigt order [xx, yy, zz, yz, xz, xy] ⇒ slot 3 is `yz` (G_23), 4 is `xz`
    // (G_13), 5 is `xy` (G_12).
    d[3][3] = g23;
    d[4][4] = g13;
    d[5][5] = g12;
    Ok(d)
}

/// Full 3-D anisotropic stiffness in the material axes, read straight from the
/// 21 upper-triangle components and mirrored.
fn anisotropic_stiffness(v: impl Fn(usize) -> f64) -> [[f64; 6]; 6] {
    let mut d = [[0.0; 6]; 6];
    // [`ANISOTROPIC_ELASTIC`] covers the upper triangle, in that order.
    let mut k = 0;
    for i in 0..6 {
        for j in i..6 {
            let value = v(k);
            k += 1;
            d[i][j] = value;
            d[j][i] = value;
        }
    }
    d
}

/// The constitutive (Voigt) matrix of a cell, in **global** axes and reduced to
/// `kinematics` — the single entry point every mechanical kernel uses.
///
/// Isotropy short-circuits to [`elastic::constitutive`], keeping its exact
/// closed forms (and therefore the exact numbers of every assembly that predates
/// this module). The other two build the full 3-D stiffness in the material
/// axes, rotate it by the frame, then reduce.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::tensor::Kinematics;
/// # use pyrucast::models::symmetry::{self, MaterialSymmetry};
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let mut mat = SubElementField::from_uniform_per_component(
/// #     fes.get(0).unwrap(),
/// #     vec!["k_1".into(), "k_2".into(), "k_3".into(), "V1X".into(), "V1Y".into()],
/// #     &[9.0, 1.0, 1.0, 0.0, 1.0]).unwrap();
/// # let iso = SubElementField::from_uniform_per_component(
/// #     fes.get(0)?, vec!["E".into(), "nu".into()], &[210e3, 0.3])?;
/// // The single entry door of the mechanical kernels. Isotropy
/// // short-circuits to the closed forms, so nothing changes for it.
/// let d = symmetry::elastic_constitutive(
///     &iso, 0, MaterialSymmetry::Isotropic, Kinematics::PlaneStress, 2)?;
/// assert_eq!(d.len(), 3);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn elastic_constitutive(
    material: &SubElementField,
    cell: usize,
    symmetry: MaterialSymmetry,
    kinematics: Kinematics,
    space_dim: usize,
) -> Result<Vec<Vec<f64>>> {
    let contract = elastic::material_contract(symmetry, space_dim);
    let idx = material.resolve_components(contract, "material")?;
    let row = material.point_values(cell, 0)?;
    let mut d = [[0.0_f64; 6]; 6];
    let v = elastic_constitutive_into(row, &idx, symmetry, kinematics, space_dim, &mut d)?;
    Ok(d[..v].iter().map(|r| r[..v].to_vec()).collect())
}

/// [`elastic_constitutive`] from a **material row** and its resolved layout,
/// writing into a caller-owned buffer and returning the Voigt size `v`.
///
/// The form a constitutive kernel calls: `idx` gives the position of each
/// component of the symmetry's material contract in `material`, resolved once
/// per zone, so this reads by index and allocates nothing.
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::symmetry::{self, MaterialSymmetry};
/// # use pyrucast::models::tensor::Kinematics;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()])?;
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm))?;
/// // A material laid out the other way round: the table absorbs the order gap.
/// let mat = SubElementField::from_uniform_per_component(
///     fes.get(0)?, vec!["nu".into(), "E".into()], &[0.3, 210_000.0])?;
/// let idx = mat.resolve_components(&["E", "nu"], "material")?;
/// let mut d = [[0.0_f64; 6]; 6];
/// let v = symmetry::elastic_constitutive_into(
///     mat.point_values(0, 0)?, &idx, MaterialSymmetry::Isotropic,
///     Kinematics::PlaneStress, 2, &mut d)?;
/// assert_eq!(v, 3);
/// assert!((d[0][0] - 210_000.0 / (1.0 - 0.09)).abs() < 1e-6);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn elastic_constitutive_into(
    material: &[f64],
    idx: &[u32],
    symmetry: MaterialSymmetry,
    kinematics: Kinematics,
    space_dim: usize,
    out: &mut [[f64; 6]; 6],
) -> Result<usize> {
    let v = |k: usize| material[idx[k] as usize];
    if symmetry == MaterialSymmetry::Isotropic {
        return Ok(elastic::constitutive_into(
            v(0),
            v(1),
            kinematics,
            space_dim,
            out,
        ));
    }
    let (d_mat, frame_at) = match symmetry {
        MaterialSymmetry::Orthotropic => (orthotropic_stiffness(v)?, ORTHOTROPIC_ELASTIC.len()),
        MaterialSymmetry::Anisotropic => (anisotropic_stiffness(v), ANISOTROPIC_ELASTIC.len()),
        MaterialSymmetry::Isotropic => unreachable!("handled above"),
    };
    let r = frame_rotation(v, frame_at, space_dim)?;
    Ok(reduce_to_model_into(
        &rotate_voigt(&d_mat, &r),
        kinematics,
        out,
    ))
}

/// Reduce a full-3-D engineering-Voigt matrix to the kinematics's `v×v` matrix: the
/// `[xx, yy, xy]` block for plane strain, its **static condensation** on `ε_zz`
/// (so `σ_zz = 0`) for plane stress, the `[rr, zz, θθ, rz]` block for
/// axisymmetric, the full `6×6` for the solid.
///
/// Shared by the anisotropic constitutive path and by the consistent tangent of
/// the non-linear laws — the reduction is a property of the *kinematics*, not of
/// the constitutive law that produced the 6×6.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::tensor::Kinematics;
/// # use pyrucast::models::symmetry::{self, MaterialSymmetry};
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let mut mat = SubElementField::from_uniform_per_component(
/// #     fes.get(0).unwrap(),
/// #     vec!["k_1".into(), "k_2".into(), "k_3".into(), "V1X".into(), "V1Y".into()],
/// #     &[9.0, 1.0, 1.0, 0.0, 1.0]).unwrap();
/// // The reduction hinges on the **kinematics**, not on the law that produced
/// // the 6×6 — hence it being shared with the nonlinear tangents.
/// let d = symmetry::orthotropic_from_constants(
///     [210e3, 210e3, 210e3], [0.3, 0.3, 0.3], [80769.0, 80769.0, 80769.0])?;
/// assert_eq!(symmetry::reduce_to_model(&d, Kinematics::PlaneStrain).len(), 3);
/// assert_eq!(symmetry::reduce_to_model(&d, Kinematics::Full3D).len(), 6);
/// // Plane stress: static condensation on ε_zz, hence σ_zz = 0 — the (0,0)
/// // term is **smaller** there than in plane strain.
/// let cp = symmetry::reduce_to_model(&d, Kinematics::PlaneStress);
/// let dp = symmetry::reduce_to_model(&d, Kinematics::PlaneStrain);
/// assert!(cp[0][0] < dp[0][0]);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn reduce_to_model(d3: &[[f64; 6]; 6], kinematics: Kinematics) -> Vec<Vec<f64>> {
    let mut d = [[0.0_f64; 6]; 6];
    let v = reduce_to_model_into(d3, kinematics, &mut d);
    d[..v].iter().map(|r| r[..v].to_vec()).collect()
}

/// [`reduce_to_model`] writing into a caller-owned buffer, returning the Voigt
/// size `v` it filled (`d[..v][..v]`).
///
/// The form a constitutive kernel calls: the same reduction, but on the stack.
/// The allocating shape above builds two levels of `Vec` for a matrix of at most
/// thirty-six numbers, which is nothing once per assembly and a great deal once
/// per Gauss point of every iteration.
/// ```
/// # use pyrucast::models::symmetry;
/// # use pyrucast::models::tensor::Kinematics;
/// // The same reduction as `reduce_to_model`, on the stack.
/// let d3 = symmetry::orthotropic_from_constants(
///     [210e3, 210e3, 210e3], [0.3, 0.3, 0.3], [80_769.0, 80_769.0, 80_769.0])?;
/// let mut d = [[0.0_f64; 6]; 6];
/// let v = symmetry::reduce_to_model_into(&d3, Kinematics::PlaneStrain, &mut d);
/// assert_eq!(v, 3);
/// let attendu = symmetry::reduce_to_model(&d3, Kinematics::PlaneStrain);
/// assert_eq!(d[0][..v], attendu[0][..]);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn reduce_to_model_into(
    d3: &[[f64; 6]; 6],
    kinematics: Kinematics,
    out: &mut [[f64; 6]; 6],
) -> usize {
    /// Where each axisymmetric Voigt slot `[rr, zz, θθ, rz]` sits in the 3-D order.
    const AXI_TO_3D: [usize; 4] = [0, 1, 2, 5];
    /// The in-plane slots `[xx, yy, xy]`.
    const PLANE: [usize; 3] = [0, 1, 5];
    match kinematics {
        // Axisymmetric: the plain [rr, zz, θθ, rz] sub-block. No condensation —
        // all four strains are prescribed (the hoop is measured, not assumed).
        Kinematics::Axisymmetric => {
            for (a, &i) in AXI_TO_3D.iter().enumerate() {
                for (b, &j) in AXI_TO_3D.iter().enumerate() {
                    out[a][b] = d3[i][j];
                }
            }
            AXI_TO_3D.len()
        }
        Kinematics::Full3D => {
            *out = *d3;
            6
        }
        Kinematics::PlaneStrain => {
            for (a, &i) in PLANE.iter().enumerate() {
                for (b, &j) in PLANE.iter().enumerate() {
                    out[a][b] = d3[i][j];
                }
            }
            PLANE.len()
        }
        Kinematics::PlaneStress => {
            // Condense the out-of-plane normal `zz` (index 2) so σ_zz = 0:
            // D2[i][j] = D3[i][j] − D3[i][2]·D3[2][j]/D3[2][2].
            let z = 2usize;
            let dzz = d3[z][z];
            for (a, &i) in PLANE.iter().enumerate() {
                for (b, &j) in PLANE.iter().enumerate() {
                    out[a][b] = d3[i][j] - d3[i][z] * d3[z][j] / dzz;
                }
            }
            PLANE.len()
        }
    }
}

// ─── Scalar transport (conduction, diffusion) ───────────────────────────────

/// Orthotropic conductivities / diffusivities, in the material axes. The prefix
/// is the physics' own (`k` for heat, `D` for Fick).
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::tensor::Kinematics;
/// # use pyrucast::models::symmetry::{self, MaterialSymmetry};
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let mut mat = SubElementField::from_uniform_per_component(
/// #     fes.get(0).unwrap(),
/// #     vec!["k_1".into(), "k_2".into(), "k_3".into(), "V1X".into(), "V1Y".into()],
/// #     &[9.0, 1.0, 1.0, 0.0, 1.0]).unwrap();
/// // The prefix is the physics': `k` for heat, `D` for Fick.
/// assert_eq!(symmetry::orthotropic_scalar("k"),
///            ["k_1".to_string(), "k_2".to_string(), "k_3".to_string()]);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn orthotropic_scalar(prefix: &str) -> [String; 3] {
    [
        format!("{prefix}_1"),
        format!("{prefix}_2"),
        format!("{prefix}_3"),
    ]
}

/// The six independent components of a symmetric anisotropic conductivity /
/// diffusivity tensor, upper triangle.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::tensor::Kinematics;
/// # use pyrucast::models::symmetry::{self, MaterialSymmetry};
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let mut mat = SubElementField::from_uniform_per_component(
/// #     fes.get(0).unwrap(),
/// #     vec!["k_1".into(), "k_2".into(), "k_3".into(), "V1X".into(), "V1Y".into()],
/// #     &[9.0, 1.0, 1.0, 0.0, 1.0]).unwrap();
/// // The six components of a symmetric tensor's upper triangle.
/// assert_eq!(symmetry::anisotropic_scalar("D")[0], "D_11");
/// assert_eq!(symmetry::anisotropic_scalar("D").len(), 6);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn anisotropic_scalar(prefix: &str) -> [String; 6] {
    [
        format!("{prefix}_11"),
        format!("{prefix}_12"),
        format!("{prefix}_13"),
        format!("{prefix}_22"),
        format!("{prefix}_23"),
        format!("{prefix}_33"),
    ]
}

/// The conductivity / diffusivity **tensor** of a cell in global axes, as a
/// `space_dim × space_dim` matrix (the leading block of the 3-D tensor).
///
/// `prefix` names the physics' coefficient (`"k"`, `"D"`). Everything is read
/// **at the Gauss point** `g` — the constants and, for orthotropy and
/// anisotropy, the material axes: a material field may vary inside a cell, and
/// the matrices integrate what the law reads.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::tensor::Kinematics;
/// # use pyrucast::models::symmetry::{self, MaterialSymmetry};
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let mut mat = SubElementField::from_uniform_per_component(
/// #     fes.get(0).unwrap(),
/// #     vec!["k_1".into(), "k_2".into(), "k_3".into(), "V1X".into(), "V1Y".into()],
/// #     &[9.0, 1.0, 1.0, 0.0, 1.0]).unwrap();
/// // Orthotrope, axes tournés d'un quart de tour : la conductivité forte
/// // (k_1 = 9) ends up **on y**, not on x.
/// let k = symmetry::transport_tensor(
///     &mat, 0, 0, MaterialSymmetry::Orthotropic, 2, "k")?;
/// assert!((k[(1, 1)] - 9.0).abs() < 1e-12);
/// assert!((k[(0, 0)] - 1.0).abs() < 1e-12);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn transport_tensor(
    material: &SubElementField,
    cell: usize,
    g: usize,
    symmetry: MaterialSymmetry,
    space_dim: usize,
    prefix: &str,
) -> Result<Matrix3<f64>> {
    let names: Vec<String> = match symmetry {
        MaterialSymmetry::Isotropic => vec![prefix.to_string()],
        MaterialSymmetry::Orthotropic => orthotropic_scalar(prefix).to_vec(),
        MaterialSymmetry::Anisotropic => anisotropic_scalar(prefix).to_vec(),
    };
    let frame: &[&str] = match (symmetry, space_dim) {
        (MaterialSymmetry::Isotropic, _) => &[],
        (_, 2) => &["V1X", "V1Y"],
        _ => &["V1X", "V1Y", "V1Z", "V2X", "V2Y", "V2Z"],
    };
    let mut read: Vec<f64> = Vec::with_capacity(names.len() + frame.len());
    for n in &names {
        read.push(material.value(cell, g, n)?);
    }
    for n in frame {
        read.push(material.value(cell, g, n)?);
    }
    transport_tensor_from(|k| read[k], symmetry, space_dim)
}

/// [`transport_tensor`] from a **material row** already read positionally: `v(k)`
/// is the `k`-th component of the physics' transport contract — the conductivity
/// constants, then the frame.
///
/// The form a constitutive kernel calls: no name, no allocation.
/// ```
/// # use pyrucast::models::symmetry::{self, MaterialSymmetry};
/// // Isotropic: one constant only, and the tensor is diagonal.
/// let k3 = symmetry::transport_tensor_from(|_| 1.5, MaterialSymmetry::Isotropic, 2)?;
/// assert_eq!(k3[(0, 0)], 1.5);
/// assert_eq!(k3[(0, 1)], 0.0);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn transport_tensor_from(
    v: impl Fn(usize) -> f64,
    symmetry: MaterialSymmetry,
    space_dim: usize,
) -> Result<Matrix3<f64>> {
    let k3 = match symmetry {
        MaterialSymmetry::Isotropic => Matrix3::from_diagonal_element(v(0)),
        MaterialSymmetry::Orthotropic => {
            let d = Matrix3::from_diagonal(&Vector3::new(v(0), v(1), v(2)));
            let r = frame_rotation(&v, 3, space_dim)?;
            r * d * r.transpose()
        }
        MaterialSymmetry::Anisotropic => {
            let (k11, k12, k13) = (v(0), v(1), v(2));
            let (k22, k23, k33) = (v(3), v(4), v(5));
            let d = Matrix3::new(k11, k12, k13, k12, k22, k23, k13, k23, k33);
            let r = frame_rotation(&v, 6, space_dim)?;
            r * d * r.transpose()
        }
    };
    Ok(k3)
}

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

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

    /// A rotation about `z` by `theta`, as the frame vectors would give it.
    fn rot_z(theta: f64) -> Matrix3<f64> {
        let (c, s) = (theta.cos(), theta.sin());
        Matrix3::new(c, -s, 0.0, s, c, 0.0, 0.0, 0.0, 1.0)
    }

    fn isotropic_6x6(e: f64, nu: f64) -> [[f64; 6]; 6] {
        let d = elastic::constitutive(e, nu, Kinematics::Full3D, 3);
        let mut out = [[0.0; 6]; 6];
        for (i, row) in d.iter().enumerate() {
            out[i].copy_from_slice(row);
        }
        out
    }

    #[test]
    fn tags_round_trip() {
        for s in [
            MaterialSymmetry::Isotropic,
            MaterialSymmetry::Orthotropic,
            MaterialSymmetry::Anisotropic,
        ] {
            assert_eq!(MaterialSymmetry::from_name(s.name()), Some(s));
        }
        assert_eq!(MaterialSymmetry::from_name("cubic"), None);
    }

    #[test]
    fn voigt_tensor_round_trip_is_the_identity() {
        // An arbitrary symmetric 6×6 must survive D → C_ijkl → D untouched.
        let mut d = [[0.0; 6]; 6];
        for i in 0..6 {
            for j in i..6 {
                let v = (i * 6 + j) as f64 + 1.0;
                d[i][j] = v;
                d[j][i] = v;
            }
        }
        let back = from_tensor(&to_tensor(&d));
        for i in 0..6 {
            for j in 0..6 {
                assert!((back[i][j] - d[i][j]).abs() < 1e-12, "slot ({i},{j})");
            }
        }
    }

    #[test]
    fn rotating_an_isotropic_stiffness_changes_nothing() {
        // Isotropy is invariant under every rotation — the sharpest available
        // check that the fourth-order rotation carries no stray index or factor.
        let d = isotropic_6x6(210e9, 0.3);
        for theta in [0.1, 0.7, 1.3, 2.9] {
            let r = rot_z(theta);
            let rotated = rotate_voigt(&d, &r);
            for i in 0..6 {
                for j in 0..6 {
                    assert!(
                        (rotated[i][j] - d[i][j]).abs() < 1e-3,
                        "theta = {theta}, slot ({i},{j}): {} vs {}",
                        rotated[i][j],
                        d[i][j]
                    );
                }
            }
        }
    }

    #[test]
    fn rotating_by_a_quarter_turn_swaps_the_material_axes() {
        // A 90° turn about `z` sends axis 1 onto axis 2: the rotated stiffness
        // must be the one of a material whose first two axes are exchanged.
        let mut d = [[0.0; 6]; 6];
        d[0][0] = 3.0;
        d[1][1] = 5.0;
        d[2][2] = 7.0;
        d[3][3] = 11.0;
        d[4][4] = 13.0;
        d[5][5] = 17.0;
        let rotated = rotate_voigt(&d, &rot_z(std::f64::consts::FRAC_PI_2));
        assert!((rotated[0][0] - 5.0).abs() < 1e-9);
        assert!((rotated[1][1] - 3.0).abs() < 1e-9);
        assert!((rotated[2][2] - 7.0).abs() < 1e-9);
        // `xy` shear is unchanged by a turn about `z`; `yz` and `xz` swap.
        assert!((rotated[5][5] - 17.0).abs() < 1e-9);
        assert!((rotated[3][3] - 13.0).abs() < 1e-9);
        assert!((rotated[4][4] - 11.0).abs() < 1e-9);
    }

    #[test]
    fn orthotropy_with_equal_constants_is_isotropy() {
        // Feeding the orthotropic law the isotropic constants must reproduce the
        // isotropic stiffness exactly — the two code paths meet.
        let (e, nu) = (210e9, 0.3);
        let g = e / (2.0 * (1.0 + nu));
        let d = orthotropic_from_constants([e, e, e], [nu, nu, nu], [g, g, g])
            .expect("isotropic constants are admissible");
        let iso = isotropic_6x6(e, nu);
        for i in 0..6 {
            for j in 0..6 {
                assert!((d[i][j] - iso[i][j]).abs() < 1e-3, "slot ({i},{j})");
            }
        }
    }

    #[test]
    fn plane_stress_reduction_kills_the_out_of_plane_stress() {
        // Condensing the solid stiffness on ε_zz must give back the closed-form
        // plane-stress matrix.
        let (e, nu) = (210e9, 0.3);
        let reduced = reduce_to_model(&isotropic_6x6(e, nu), Kinematics::PlaneStress);
        let expect = elastic::constitutive(e, nu, Kinematics::PlaneStress, 2);
        for i in 0..3 {
            for j in 0..3 {
                assert!(
                    (reduced[i][j] - expect[i][j]).abs() < 1e-3,
                    "slot ({i},{j}): {} vs {}",
                    reduced[i][j],
                    expect[i][j]
                );
            }
        }
    }

    #[test]
    fn frame_components_follow_the_symmetry_and_the_dimension() {
        assert!(frame_components(MaterialSymmetry::Isotropic, 3).is_empty());
        assert_eq!(
            frame_components(MaterialSymmetry::Orthotropic, 2),
            &FRAME_2D
        );
        assert_eq!(
            frame_components(MaterialSymmetry::Anisotropic, 3),
            &FRAME_3D
        );
    }
}