pyrucast 0.12.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
//! Linear heat-conduction physics — assembly of the cell-wise stiffness
//! `K_ij = ∫ k · ∇N_i · ∇N_j dx`.
//!
//! Primal variable `"T"` (temperature, columns), dual `"q"` (heat flux,
//! rows). The conductivity is read from a [`SubElementField`] component
//! named [`MATERIAL_COMPONENT`].

use crate::containers::element_field::SubElementField;
use crate::containers::field::ABSENT_COMPONENT;
use crate::containers::finite_element_space::SubFiniteElementSpace;
use crate::containers::matrix::DofOrdering;
use crate::containers::matrix::Symmetry;
use crate::containers::mesh::SubMesh;
use crate::containers::model::SubModel;
use crate::dump::DumpOptions;
use crate::error::Result;
use crate::handle::Handle;
use crate::models::kernel::MAX_CELL_DOFS;
use crate::models::owned_components;
use crate::models::symmetry::{self, MaterialSymmetry};
use crate::models::ElementLayout;
use crate::models::ZoneLayout;
use crate::models::{
    Behavior, CellGeom, Domain, MatrixLayout, Physics, StrainOperator, SubModelKind,
};
use serde::{Deserialize, Serialize};

/// Column DOF name (temperature).
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::matrix::{DofOrdering};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::kernel::assemble_block;
/// # use pyrucast::models::symmetry::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 zone = fes.get(0).unwrap();
/// # let support = zone.read().submesh().read().to_poi1().unwrap();
/// # let mat = Handle::new(SubElementField::from_uniform_per_component(
/// #     zone.clone(), vec!["k".into()], &[2.0]).unwrap());
/// # use pyrucast::models::heat_conduction;
/// // The conduction's primal: that is the name a border law or a constraint
/// // must cite to couple to it.
/// assert_eq!(heat_conduction::PRIMAL_VAR, "T");
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub const PRIMAL_VAR: &str = "T";
/// Row DOF name (heat flux).
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::matrix::{DofOrdering};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::kernel::assemble_block;
/// # use pyrucast::models::symmetry::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 zone = fes.get(0).unwrap();
/// # let support = zone.read().submesh().read().to_poi1().unwrap();
/// # let mat = Handle::new(SubElementField::from_uniform_per_component(
/// #     zone.clone(), vec!["k".into()], &[2.0]).unwrap());
/// # use pyrucast::models::heat_conduction;
/// assert_eq!(heat_conduction::DUAL_VAR, "q");
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub const DUAL_VAR: &str = "q";
/// Required component on the material `SubElementField` (isotropic
/// conductivity).
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::matrix::{DofOrdering};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::kernel::assemble_block;
/// # use pyrucast::models::symmetry::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 zone = fes.get(0).unwrap();
/// # let support = zone.read().submesh().read().to_poi1().unwrap();
/// # let mat = Handle::new(SubElementField::from_uniform_per_component(
/// #     zone.clone(), vec!["k".into()], &[2.0]).unwrap());
/// # use pyrucast::models::heat_conduction;
/// // La conductivité isotrope. L'orthotropie en demande davantage.
/// assert_eq!(heat_conduction::MATERIAL_COMPONENT, "k");
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub const MATERIAL_COMPONENT: &str = "k";
/// Material contract returned by [`SubModelKind::material_components`] for the
/// isotropic default.
const MATERIAL_COMPONENTS: &[&str] = &[MATERIAL_COMPONENT];
/// Orthotropic conductivities plus the in-plane material axis (2-D).
const ORTHOTROPIC_2D: &[&str] = &["k_1", "k_2", "k_3", "V1X", "V1Y"];
/// Orthotropic conductivities plus the two material axes (3-D).
const ORTHOTROPIC_3D: &[&str] = &[
    "k_1", "k_2", "k_3", "V1X", "V1Y", "V1Z", "V2X", "V2Y", "V2Z",
];
/// The symmetric conductivity tensor plus the in-plane material axis (2-D).
const ANISOTROPIC_2D: &[&str] = &["k_11", "k_12", "k_13", "k_22", "k_23", "k_33", "V1X", "V1Y"];
/// The symmetric conductivity tensor plus the two material axes (3-D).
const ANISOTROPIC_3D: &[&str] = &[
    "k_11", "k_12", "k_13", "k_22", "k_23", "k_33", "V1X", "V1Y", "V1Z", "V2X", "V2Y", "V2Z",
];

/// The material contract of a symmetry in a space of dimension `space_dim` —
/// disjoint component sets, so an isotropic and an orthotropic conduction zone
/// resolve separately on one mesh (see [`crate::ops::matrix::assemble_kind`]).
fn material_contract(symmetry: MaterialSymmetry, space_dim: usize) -> &'static [&'static str] {
    match (symmetry, space_dim) {
        (MaterialSymmetry::Isotropic, _) => MATERIAL_COMPONENTS,
        (MaterialSymmetry::Orthotropic, 2) => ORTHOTROPIC_2D,
        (MaterialSymmetry::Orthotropic, _) => ORTHOTROPIC_3D,
        (MaterialSymmetry::Anisotropic, 2) => ANISOTROPIC_2D,
        (MaterialSymmetry::Anisotropic, _) => ANISOTROPIC_3D,
    }
}
/// Extra material components consumed **only** by the heat-capacity (mass)
/// matrix: density `rho` and specific heat `cp` (so the volumetric heat capacity
/// is `ρ·cp`). Optional — the conductivity assembly does not need them.
const CAPACITY_COMPONENTS: &[&str] = &["rho", "cp"];

/// Axis suffixes for the vector components of the deformation / flux at a
/// Gauss point, indexed by spatial direction (`x`, `y`, `z`).
const AXES: [&str; 3] = ["x", "y", "z"];

/// Deformation component names (`grad_T_x`, …), one per spatial direction —
/// the leading components of the behaviour-input field consumed by
/// [`SubModelKind::integrate_behavior`]. They match what
/// [`crate::ops::element_field::gradient`] names the gradient of a temperature field
/// whose component is [`PRIMAL_VAR`].
fn deformation_components(space_dim: usize) -> Vec<String> {
    (0..space_dim)
        .map(|a| format!("grad_{PRIMAL_VAR}_{}", AXES[a]))
        .collect()
}

/// Flux component names (`flux_x`, …), one per spatial direction. The value
/// stored is the **weak-form** flux `k·∇T` (such that `∫ Bᵀ·flux = K·T`,
/// hence the « COMP == stiffness » match in the linear case); the physical
/// Fourier flux is its opposite, `−k·∇T`.
fn flux_components(space_dim: usize) -> Vec<String> {
    (0..space_dim)
        .map(|a| format!("flux_{}", AXES[a]))
        .collect()
}

/// Linear heat conduction.
///
/// - primal variable: `"T"` (temperature, columns).
/// - dual variable:   `"q"` (heat flux row labels).
/// - Material data (conductivity `"k"`, …) is **not** stored here; it is
///   supplied at assembly time via [`crate::ops::matrix::stiffness`].
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Interpolation, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::{Domain, SubModelKind};
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&n.iter().map(|x| x.id()).collect::<Vec<_>>()).unwrap();
/// # let maillage = Mesh::from_submesh(sm);
/// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # use pyrucast::models::heat_conduction::{self, HeatConduction};
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// let hc = HeatConduction::new(zone.clone(), MaterialSymmetry::Isotropic)?;
/// assert_eq!(hc.primal_vars(), vec![heat_conduction::PRIMAL_VAR.to_string()]);
/// assert_eq!(hc.dual_vars(), vec![heat_conduction::DUAL_VAR.to_string()]);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Clone, Serialize, Deserialize)]
pub struct HeatConduction {
    pub(crate) fespace: Handle<SubFiniteElementSpace>,
    /// POI1 SubMesh covering the unique nodes of `fespace`'s submesh,
    /// built once at construction. Reused as the row/col support of every
    /// assembled stiffness block — no per-assembly rebuild.
    pub(crate) support: Handle<SubMesh>,
    pub(crate) space_dim: usize,
    pub(crate) symmetry: MaterialSymmetry,
}

impl HeatConduction {
    /// Heat conduction on an FE subspace, with the given material symmetry. An
    /// orthotropic or anisotropic conductivity carries its material axes through
    /// the material field (see [`crate::models::symmetry`]). Builds the stable
    /// POI1 [`SubMesh`] covering the subspace's unique nodes (reused as the
    /// row/col support of every assembled block).
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::symmetry::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 zone = fes.get(0).unwrap();
    /// # use pyrucast::models::heat_conduction::HeatConduction;
    /// # use pyrucast::models::Domain;
    /// let hc = HeatConduction::new(zone.clone(), MaterialSymmetry::Isotropic)?;
    /// assert_eq!(hc.material_components(), vec!["k".to_string()]);
    /// // An orthotropic conductivity reads its principal values and its axes.
    /// let ortho = HeatConduction::new(zone.clone(), MaterialSymmetry::Orthotropic)?;
    /// assert!(ortho.material_components().len() > 1);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn new(fespace: Handle<SubFiniteElementSpace>, symmetry: MaterialSymmetry) -> Result<Self> {
        let (submesh, space_dim) = {
            let s = fespace.read();
            (s.submesh(), s.space_dim())
        };
        let support = submesh.read().to_poi1()?;
        Ok(Self {
            fespace,
            support,
            space_dim,
            symmetry,
        })
    }
}

impl SubModelKind for HeatConduction {
    fn primal_vars(&self) -> Vec<String> {
        vec![PRIMAL_VAR.to_string()]
    }

    fn dual_vars(&self) -> Vec<String> {
        vec![DUAL_VAR.to_string()]
    }

    fn as_domain(&self) -> Option<&dyn Domain> {
        Some(self)
    }

    fn as_behavior(&self) -> Option<&dyn Behavior> {
        Some(self)
    }

    fn stiffness_layout(&self) -> Option<MatrixLayout> {
        Some(MatrixLayout {
            fespaces: vec![self.fespace.clone()],
            support: self.support.clone(),
            dual_vars: self.dual_vars(),
            primal_vars: self.primal_vars(),
            ordering: DofOrdering::NodesThenVars,
            symmetry: Symmetry::Full,
        })
    }

    /// The heat-capacity (mass) matrix shares the conductivity layout (same
    /// fespace, support, single `T` DOF per node) — only the kernel differs.
    fn mass_layout(&self) -> Option<MatrixLayout> {
        self.stiffness_layout()
    }

    /// Internal nodal fluxes `q_i = ∫ ∇N_i · flux dx` of one cell — `Bᵀ` applied
    /// to the weak-form flux, the scalar-transport counterpart of the
    /// continuum-mechanics default (and identical to
    /// [`crate::ops::node_field::divergence`](fn@crate::ops::node_field::divergence) of the
    /// flux vector). Single dual variable `q`, so `fe[i]` per node.
    fn internal_force_reads(&self) -> Vec<String> {
        flux_components(self.space_dim)
    }

    fn internal_force_element(
        &self,
        geoms: &[CellGeom],
        stress: &SubElementField,
        lay: &[u32],
        _material: &SubElementField,
        _mat: &[u32],
        fe: &mut [f64],
    ) -> Result<()> {
        let geom = &geoms[0];
        let d = geom.space_dim;
        let mut dn_buf = [0.0_f64; MAX_CELL_DOFS];
        for g in 0..geom.n_gauss {
            let dn = &mut dn_buf[..geom.n_nodes * d];
            geom.dn_dx(g, dn)?; // [i * d + a]
            let w = geom.det_j_w(g);
            // The flux row, sliced once: its bounds were settled with the zone,
            // so a node no longer re-proves them component by component.
            let row = stress.row(geom.cell, g);
            for i in 0..geom.n_nodes {
                let mut s = 0.0;
                for a in 0..d {
                    s += dn[i * d + a] * row[lay[a] as usize];
                }
                fe[i] += s * w;
            }
        }
        Ok(())
    }

    /// Linear conduction: the consistent tangent **is** the conductivity.
    fn tangent_is_stiffness(&self) -> bool {
        true
    }

    fn physics(&self) -> &'static [Physics] {
        &[Physics::Thermal]
    }

    fn label(&self) -> &'static str {
        "HeatConduction"
    }

    fn render(&self, _opts: &DumpOptions) -> String {
        let primal = self.primal_vars().join(", ");
        let dual = self.dual_vars().join(", ");
        let n = self.support.read().cell_count();
        format!(
            "SubModel<HeatConduction({})>\n  primal var(s): {primal}\n  \
             dual var(s):   {dual}\n  support: {n} node(s)",
            self.symmetry
        )
    }
}

impl Domain for HeatConduction {
    fn material_fespace(&self) -> Handle<SubFiniteElementSpace> {
        self.fespace.clone()
    }

    fn material_components(&self) -> Vec<String> {
        owned_components(material_contract(self.symmetry, self.space_dim))
    }

    /// `rho` + `cp` — required only by the heat-capacity (mass) matrix, never by
    /// the conductivity assembly.
    fn optional_material_components(&self) -> &'static [&'static str] {
        CAPACITY_COMPONENTS
    }

    fn element_matrix(
        &self,
        geoms: &[CellGeom],
        material: &SubElementField,
        lay: &ElementLayout,
        ke: &mut [f64],
    ) -> Result<()> {
        element_stiffness(&geoms[0], material, lay, self.symmetry, ke)
    }

    fn element_mass(
        &self,
        geoms: &[CellGeom],
        material: &SubElementField,
        lay: &ElementLayout,
        ke: &mut [f64],
    ) -> Result<()> {
        element_capacity(&geoms[0], material, lay, ke)
    }
}

impl Behavior for HeatConduction {
    fn behavior_fespace(&self) -> Handle<SubFiniteElementSpace> {
        self.fespace.clone()
    }

    fn behavior_output_components(&self) -> Vec<String> {
        flux_components(self.fespace.read().space_dim())
    }

    /// Linear constitutive law: weak-form flux = k·∇T at one Gauss point.
    /// (No internal-state variables — `VAR0`/`VAR1` are empty; a non-linear law
    /// would read trailing state components of `input` and write updated ones.)
    fn deformation_reads(&self) -> Vec<String> {
        deformation_components(self.space_dim)
    }

    fn strain_operator(&self) -> StrainOperator {
        StrainOperator::Gradient
    }

    fn integrate_point(
        &self,
        geom: &CellGeom,
        _g: usize,
        lay: &ZoneLayout,
        deformation: &[f64],
        _prev: &[f64],
        material: &[f64],
        _dt: f64,
        out: &mut [f64],
    ) -> Result<()> {
        let space_dim = geom.space_dim;
        let k3 = symmetry::transport_tensor_from(
            |k| material[lay.material[k] as usize],
            self.symmetry,
            space_dim,
        )?;
        for a in 0..space_dim {
            let mut acc = 0.0;
            for b in 0..space_dim {
                acc += k3[(a, b)] * deformation[lay.deformation[b] as usize];
            }
            out[a] = acc;
        }
        Ok(())
    }
}

/// Element kernel: local conductivity matrix of one cell,
///   `K_local[i, j] = Σ_g k(g) · (∇N_i · ∇N_j)|_g · |J|_g · w_g`,
/// written into `ke` (flat row-major, side `n_nodes`, `ke[i * n_nodes + j]`).
/// Pure and sequential — driven in parallel by
/// [`crate::models::kernel::assemble_block`].
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::matrix::{DofOrdering, Symmetry};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::kernel::assemble_block;
/// # use pyrucast::models::symmetry::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 zone = fes.get(0).unwrap();
/// # let support = zone.read().submesh().read().to_poi1().unwrap();
/// # let mat = Handle::new(SubElementField::from_uniform_per_component(
/// #     zone.clone(), vec!["k".into()], &[2.0]).unwrap());
/// # use pyrucast::models::heat_conduction;
/// # use pyrucast::models::ElementLayout;
/// // The field is laid out in the contract's order: the table is the identity.
/// let lay = ElementLayout { material: vec![0], optional_material: vec![], state: vec![] };
/// // ∫ ∇Nᵀ k ∇N. A constant conductivity gives a singular matrix: a uniform
/// // temperature field conducts nothing.
/// let bloc = assemble_block(
///     std::slice::from_ref(&zone), &support, &support,
///     vec!["q".into()], vec!["T".into()], DofOrdering::NodesThenVars, Symmetry::Full,
///     &mat, None,
///     |geoms, m, _s, ke| heat_conduction::element_stiffness(
///         &geoms[0], m, &lay, MaterialSymmetry::Isotropic, ke),
/// )?;
/// let total: f64 = bloc.iter_entries()?.into_iter().map(|(_, _, _, _, v)| v).sum();
/// assert!(total.abs() < 1e-9);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn element_stiffness(
    geom: &CellGeom,
    material: &SubElementField,
    lay: &ElementLayout,
    symmetry: MaterialSymmetry,
    ke: &mut [f64],
) -> Result<()> {
    let n_nodes = geom.n_nodes;
    let space_dim = geom.space_dim;
    // Everything is read at the Gauss point — the constants and the material
    // axes of an oriented conductivity as much as an isotropic scalar: a
    // material field may vary inside a cell, and the law reads it there.
    let oriented = symmetry.has_frame();
    let mut dn_buf = [0.0_f64; MAX_CELL_DOFS];
    for g in 0..geom.n_gauss {
        let dn = &mut dn_buf[..n_nodes * geom.space_dim];
        geom.dn_dx(g, dn)?;
        let det_j_w = geom.det_j_w(g);
        let row = material.row(geom.cell, g);
        let tensor = if oriented {
            Some(symmetry::transport_tensor_from(
                |k| row[lay.material[k] as usize],
                symmetry,
                space_dim,
            )?)
        } else {
            None
        };
        match &tensor {
            None => {
                // The scalar conductivity, by the index the zone resolved.
                let k = row[lay.material[0] as usize];
                for i in 0..n_nodes {
                    for j in 0..n_nodes {
                        let mut grad_dot = 0.0;
                        for a in 0..space_dim {
                            grad_dot += dn[i * space_dim + a] * dn[j * space_dim + a];
                        }
                        ke[i * n_nodes + j] += k * grad_dot * det_j_w;
                    }
                }
            }
            // `∇N_iᵀ · K · ∇N_j` — the isotropic dot product is its `K = k·I` case.
            Some(k3) => {
                for i in 0..n_nodes {
                    for j in 0..n_nodes {
                        let mut acc = 0.0;
                        for a in 0..space_dim {
                            for b in 0..space_dim {
                                acc += dn[i * space_dim + a] * k3[(a, b)] * dn[j * space_dim + b];
                            }
                        }
                        ke[i * n_nodes + j] += acc * det_j_w;
                    }
                }
            }
        }
    }
    Ok(())
}

/// Element kernel: local **heat-capacity** (mass) matrix of one cell,
///   `C_local[i, j] = Σ_g ρ·cp · N_i N_j · |J|_g · w_g`,
/// written into `ke` (flat row-major, side `n_nodes`, `ke[i * n_nodes + j]`).
/// Density `rho` and specific heat `cp` are read at every Gauss point. Pure and
/// sequential.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::matrix::{DofOrdering, Symmetry};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::kernel::assemble_block;
/// # use pyrucast::models::symmetry::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 zone = fes.get(0).unwrap();
/// # let support = zone.read().submesh().read().to_poi1().unwrap();
/// # let mat = Handle::new(SubElementField::from_uniform_per_component(
/// #     zone.clone(), vec!["rho".into(), "cp".into()], &[3.0, 4.0]).unwrap());
/// # use pyrucast::models::heat_conduction;
/// # use pyrucast::models::ElementLayout;
/// // `rho` and `cp` are the conduction contract's two **optional**
/// // components: the conductivity never asks for them, the capacity does.
/// let lay = ElementLayout {
///     material: vec![], optional_material: vec![0, 1], state: vec![],
/// };
/// // ∫ ρ c_p Nᵀ N: the thermal capacity. Its sum is ρ·c_p × area —
/// // la capacité de la maille entière.
/// let bloc = assemble_block(
///     std::slice::from_ref(&zone), &support, &support,
///     vec!["q".into()], vec!["T".into()], DofOrdering::NodesThenVars, Symmetry::Full,
///     &mat, None,
///     |geoms, m, _s, ke| heat_conduction::element_capacity(&geoms[0], m, &lay, ke),
/// )?;
/// let total: f64 = bloc.iter_entries()?.into_iter().map(|(_, _, _, _, v)| v).sum();
/// assert!((total - 3.0 * 4.0 * 0.5).abs() < 1e-9);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn element_capacity(
    geom: &CellGeom,
    material: &SubElementField,
    lay: &ElementLayout,
    ke: &mut [f64],
) -> Result<()> {
    let n_nodes = geom.n_nodes;
    // `rho` and `cp` are the two optional components of the conduction contract
    // (`CAPACITY_COMPONENTS`): the conductivity assembly never asks for them,
    // the capacity cannot do without.
    let slot = |slot: usize, what: &str| -> Result<usize> {
        match lay.optional_material[slot] {
            ABSENT_COMPONENT => Err(crate::error::PyrucastError::Message(format!(
                "HeatConduction capacity matrix: material component `{}` ({what}) is required",
                CAPACITY_COMPONENTS[slot]
            ))),
            i => Ok(i as usize),
        }
    };
    let (rho, cp) = (slot(0, "density")?, slot(1, "specific heat")?);
    for g in 0..geom.n_gauss {
        let n = geom.n_at_g(g);
        let row = material.row(geom.cell, g);
        let w = geom.det_j_w(g) * row[rho] * row[cp];
        for i in 0..n_nodes {
            for j in 0..n_nodes {
                ke[i * n_nodes + j] += n[i] * n[j] * w;
            }
        }
    }
    Ok(())
}

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

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

    /// The rest state of `d` on its material — the `prev` of a first step,
    /// which the behaviour operator materializes for a caller who has none.
    fn rest<B: Behavior>(b: &B, mat: &Handle<SubElementField>) -> Handle<SubElementField> {
        Handle::new(b.initial_state(&mat.read()).unwrap())
    }
    use crate::aggregate::Aggregate;
    use crate::atoms::{ElementType, Node};
    use crate::containers::field::SubField;
    use crate::containers::finite_element_space::FiniteElementSpace;
    use crate::containers::mesh::Mesh;
    use crate::coords::Coords;
    use crate::handle::Handle;

    /// HeatConduction on a single SEG2 of length `L`.
    fn seg2_hc(length: f64) -> HeatConduction {
        let coords = Handle::new(Coords::new(1).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[length]).unwrap();
        let mut mesh = Mesh::from_submesh(SubMesh::new(coords, ElementType::SEG2));
        mesh.add_cell(&[a.id(), b.id()]).unwrap();
        let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
        HeatConduction::new(fes.get(0).unwrap(), MaterialSymmetry::Isotropic).unwrap()
    }

    #[test]
    fn behavior_fespace_is_the_physics_fespace() {
        let hc = seg2_hc(1.0);
        let fe = hc.behavior_fespace();
        assert!(fe.same_object(&hc.fespace));
    }

    /// COMP on a linear law returns the weak-form flux `k·∇T` — the exact
    /// quantity the assembled stiffness integrates (`∫ Bᵀ·flux = K·T`). The
    /// deformation input (`grad_T_x`) is what [`crate::ops::element_field::gradient`]
    /// produces from a nodal temperature; here it is set directly.
    #[test]
    fn integrate_behavior_returns_weak_form_flux() {
        let hc = seg2_hc(2.0);
        let grad = 1.5; // e.g. ΔT / L = 3 / 2
        let k = 1.5;

        let mut def = SubElementField::new(hc.fespace.clone(), deformation_components(1)).unwrap();
        def.set_uniform("grad_T_x", grad).unwrap();
        let def = Handle::new(def);

        let mut mat =
            SubElementField::new(hc.fespace.clone(), vec![MATERIAL_COMPONENT.to_string()]).unwrap();
        mat.set_uniform(MATERIAL_COMPONENT, k).unwrap();
        let mat = Handle::new(mat);

        let flux = hc
            .integrate_behavior(&def, &rest(&hc, &mat), &mat, 0.0)
            .unwrap();
        assert_eq!(flux.components(), &["flux_x".to_string()]);
        let expected = k * grad;
        for g in 0..flux.gauss_count() {
            assert!((flux.value(0, g, "flux_x").unwrap() - expected).abs() < 1e-12);
        }
    }
}

crate::physics_operator! {
    /// Heat-conduction `Model` spanning **every** subspace of `fespace` — one
    /// [`SubModel::HeatConduction`] per [`SubFiniteElementSpace`].
    ///
    /// This is the parent-level operator (see `CONVENTIONS.md`): it consumes the
    /// FE-space *parent* and returns a `Model`, so the caller never builds a
    /// `SubModel` by hand. A single-subspace `fespace` yields the unit case; several
    /// subspaces yield one zone each. Compose heterogeneous physics with `union`
    /// (Python `|`).
    ///
    /// `symmetry` selects the conductivity the material field must carry: the
    /// scalar `k`, the principal `k_1…` (orthotropic) or the symmetric tensor
    /// `k_11…` (anisotropic), the two oriented ones with the material axes. It
    /// is supplied at assembly time.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::ops::model;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
    /// // One sub-model per subspace: the model covers the **whole** FE space.
    /// let m = model::heat_conduction(&fes, MaterialSymmetry::Isotropic)?;
    /// assert_eq!(m.len(), fes.len());
    /// assert_eq!(m.primal_vars(), vec!["T".to_string()]);
    /// // An oriented conductivity reads its constants and its axes.
    /// let ortho = model::heat_conduction(&fes, MaterialSymmetry::Orthotropic)?;
    /// let reads = ortho.get(0).unwrap().read().material_components().unwrap();
    /// assert!(reads.contains(&"V1X".to_string()));
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn heat_conduction(fespace, symmetry: MaterialSymmetry = MaterialSymmetry::Isotropic) via SubModel::heat_conduction;
    python: "`model.heat_conduction(fespace, symmetry=\"isotropic\")` — heat-conduction\nmodel spanning **every** subspace of `fespace` (one zone per subspace). A\nsingle-subspace space gives the unit case; several give one zone each. Compose\nheterogeneous physics with `|`: `model.heat_conduction(fes) | model.dirichlet(...)`.\n\n`symmetry` is `\"isotropic\"` (the default), `\"orthotropic\"` or\n`\"anisotropic\"`, and selects which conductivity the material field must\ncarry: the scalar `k`, the principal `k_1, k_2, k_3`, or the symmetric\ntensor `k_11 … k_33`. The two oriented ones also require the material\naxes — `V1X, V1Y` in 2-D, `V1X…V1Z, V2X…V2Z` in 3-D."
}