pyrucast 0.15.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
//! Dirichlet constraint via Lagrange multipliers.
//!
//! A Dirichlet sub-model imposes `u = u_d` on a set of constrained nodes. It
//! is a *constraint*, not a volumetric physics: it carries no material and no
//! constitutive law. It is built from **one mesh supplied by the user**,
//! `imposed_mesh`, of any element type: its distinct nodes, all zones
//! together, are the constrained nodes — one relation per node.
//!
//! Each relation gets a multiplier node of its own, minted at construction by
//! the [`barycenter`](crate::ops::mesh::barycenter()) mesher — colocated with
//! its constrained node, in the same submesh structure. The user reaches them
//! through [`Constraint::multiplier_mesh`], or never touches them at all:
//! [`SubModel::constraint_rhs`](crate::containers::model::SubModel::constraint_rhs)
//! writes `u_d` keyed by the constrained node.
//!
//! # Variables
//!
//! A Dirichlet sub-model imposes the **primal of another model** yet owns its
//! own pair of variables:
//!
//! - `imposed_variable` (e.g. `"T"`) — the constrained primal of the **target**
//!   physics (a *column* of the target's stiffness);
//! - `target_dual` (e.g. `"q"`) — the **target's** dual variable; the row into
//!   which the constraint reaction `Cᵀ` is added (it cannot be derived from
//!   `imposed_variable` — the `T → q` map is target-specific);
//! - [`MULTIPLIER`] — this sub-model's own **primal**: the Lagrange
//!   multiplier, an unknown of the augmented system, whose solved value is the
//!   **reaction**;
//! - [`IMPOSED`] — this sub-model's own **dual**: the constraint-equation row,
//!   and the **slot** at which the imposed value `u_d` is written in the load
//!   `SubNodeField` (on the multiplier node).
//!
//! The last two are the names of every constraint relation.

use crate::aggregate::Aggregate;
use crate::containers::element_field::SubElementField;
use crate::containers::mesh::Mesh;
use crate::dump::DumpOptions;
use crate::error::{PyrucastError, Result};
use crate::models::transfer::{constrained_physics, constraint_physics};
use crate::models::{
    constraint_block_pair, Constraint, ConstraintTerm, Contribution, MatrixKind, Physics, Relation,
    RelationSense, SubModelKind, IMPOSED, MULTIPLIER,
};
use crate::ops::mesh::barycenter;
use serde::{Deserialize, Serialize};

/// Dirichlet constraint imposed via Lagrange multipliers.
///
/// See the module documentation for the meaning of the variable names and the
/// two meshes. The imposed value `u_d` is **not** stored here: the user
/// supplies it through the load `SubNodeField` at the multiplier node's
/// [`IMPOSED`] component.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::{Constraint, RelationSense, SubModelKind};
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let maillage = Mesh::from_submesh(sm);
/// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # use pyrucast::models::dirichlet::Dirichlet;
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// // A support: `u = u_d` at the imposed nodes, through a Lagrange multiplier.
/// let d = Dirichlet::new(&impose, &cible, "T", RelationSense::Equality)?;
/// assert_eq!(d.relations()?.len(), 1);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Serialize, Deserialize)]
pub struct Dirichlet {
    /// Constrained primal of the target physics (e.g. `"T"`).
    pub(crate) imposed_variable: String,
    /// Target physics's dual; row where the reaction `Cᵀ` lands (e.g. `"q"`).
    pub(crate) target_dual: String,
    /// POI1 mesh of the constrained nodes, one node per cell, each node once:
    /// the user's mesh through `to_poi1` then `consolidate`. For a single zone
    /// that is the zone's own POI1 companion, shared, not copied.
    pub(crate) imposed_mesh: Mesh,
    /// POI1 mesh of the multiplier nodes, minted at construction and paired
    /// element-for-element with `imposed_mesh` (same submesh structure, same
    /// per-submesh cell count).
    pub(crate) multiplier_mesh: Mesh,
    /// Equality (default) or unilateral inequality (`u ≥ u_d` / `u ≤ u_d`),
    /// solved by the active-set operator.
    pub(crate) sense: RelationSense,
    /// Nature of the physics it constrains (`Mechanical` for a `u_x`), read
    /// from the target at construction.
    pub(crate) target_physics: Option<Physics>,
}

impl Dirichlet {
    /// Build a Dirichlet constraint imposing `variable = u_d` on the nodes of
    /// `imposed_mesh`, one relation per node, each with a multiplier node of
    /// its own minted beside it.
    ///
    /// `imposed_mesh` is any mesh: its distinct nodes, all zones together, are
    /// the constrained nodes — `imposed_mesh.to_poi1().consolidate()`. A node
    /// that several zones share gets one relation, not one per zone (two would
    /// leave the system singular). The constrained nodes form **one** POI1
    /// zone: a single zone, the usual case (an edge, a face), gives its own
    /// POI1 companion, so the solution on that support pairs node by node with
    /// the fields on that zone — a POI1 zone listing each node once is used as
    /// is; several zones are fused into a new POI1 zone.
    ///
    /// `variable` is a primal of `target`, whose dual row (e.g. `"q"`) is read
    /// from it.
    ///
    /// `sense` turns the constraint unilateral: `GreaterEqual` imposes
    /// `u ≥ u_d` (`LessEqual`: `u ≤ u_d`), enforced only while in contact — such
    /// a model is solved by the active-set operator
    /// [`solve`](crate::ops::solver::solve).
    ///
    /// Errors when `variable` is not a primal of `target`, or when
    /// `imposed_mesh` holds no node.
    ///
    /// ```
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::{Constraint, RelationSense, SubModelKind};
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # use pyrucast::models::dirichlet::Dirichlet;
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
    /// let d = Dirichlet::new(&impose, &cible, "T", RelationSense::Equality)?;
    /// // The multiplier node is the constraint's own, minted beside the
    /// // imposed node.
    /// let m = d.multiplier_mesh();
    /// assert_eq!(m.cell_count(), 1);
    /// assert_ne!(m.node(0, 0, 0)?.id(), n[0].id());
    /// assert_eq!(m.node(0, 0, 0)?.position()?, vec![0.0, 0.0]);
    /// // A variable the target does not assemble is refused.
    /// assert!(Dirichlet::new(&impose, &cible, "u_x", RelationSense::Equality).is_err());
    /// // Any mesh will do: the triangle holds its three nodes.
    /// let all = Dirichlet::new(&maillage, &cible, "T", RelationSense::Equality)?;
    /// assert_eq!(all.multiplier_mesh().cell_count(), 3);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn new(
        imposed_mesh: &Mesh,
        target: &crate::containers::model::Model,
        variable: &str,
        sense: RelationSense,
    ) -> Result<Self> {
        // The target's own names, read from the target rather than retyped: the
        // `T → q` map is its business, and a mistyped one would build a
        // constraint on a variable nobody assembles — a singular matrix, with
        // nothing to point at.
        let imposed_variable = variable.to_string();
        let target_dual = target.dual_of(variable).ok_or_else(|| {
            PyrucastError::Message(format!(
                "Dirichlet: `{variable}` is not a primal of the model it constrains — it \
                 declares {:?}",
                target.primal_vars()
            ))
        })?;
        if imposed_mesh.cell_count() == 0 {
            return Err(PyrucastError::Message(
                "Dirichlet: imposed_mesh must constrain at least one node".into(),
            ));
        }
        // Its distinct nodes, all zones together: one relation per node.
        let imposed = imposed_mesh.to_poi1().consolidate();
        // One fresh node per relation, beside its constrained node.
        let multiplier_mesh = barycenter(&imposed)?;
        let target_physics = constrained_physics(target, [imposed_variable.as_str()]);

        Ok(Self {
            imposed_variable,
            target_dual,
            imposed_mesh: imposed,
            multiplier_mesh,
            sense,
            target_physics,
        })
    }
}

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

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

    /// Its relations, applied to the solution: the force `Cᵀ λ` on the
    /// constrained nodes (the opposite of the reaction), and `C·u` on its own
    /// row.
    fn internal_force_contribution(&self) -> Vec<crate::models::ResidualContribution> {
        vec![crate::models::ResidualContribution::Relations]
    }

    fn as_constraint(&self) -> Option<&dyn Constraint> {
        Some(self)
    }

    /// Dirichlet contributes its **literal** C / Cᵀ blocks directly — it has no
    /// [`stiffness_layout`](SubModelKind::stiffness_layout) (nothing is
    /// integrated on a cell), so it bypasses the layout-driven default and
    /// returns a single [`Contribution::Literal`] carrying the filled blocks.
    /// This is *the* seam that keeps the assembler free of any Dirichlet-specific
    /// special case.
    fn contributions(
        &self,
        kind: MatrixKind,
        _material: Option<&crate::handle::Handle<SubElementField>>,
    ) -> Result<Vec<Contribution>> {
        // A constraint only enters the global (stiffness) matrix — no mass or
        // geometric term. A tangent request reaches it as a stiffness one
        // (`tangent_is_stiffness`), so it never arrives here.
        if kind != MatrixKind::Stiffness {
            return Ok(Vec::new());
        }
        // One C / Cᵀ pair per submesh pair — the submeshes are used directly as
        // row/col supports (no flattening), so the submesh structure carried
        // through `barycenter` is preserved. Dirichlet is the single-term
        // relation with coefficient 1, so it defers to the shared block builder.
        let mut blocks = Vec::with_capacity(self.imposed_mesh.len() * 2);
        for i in 0..self.imposed_mesh.len() {
            let imp_sm = self.imposed_mesh.get(i)?;
            let mult_sm = self.multiplier_mesh.get(i)?;
            let (c_block, ct_block) = constraint_block_pair(
                &mult_sm,
                &imp_sm,
                &self.imposed_variable,
                &self.target_dual,
                1.0,
                self.sense,
            )?;
            blocks.push(c_block);
            blocks.push(ct_block);
        }
        Ok(vec![Contribution::Literal(blocks)])
    }

    /// A linear relation: its tangent block **is** its stiffness block.
    fn tangent_is_stiffness(&self) -> bool {
        true
    }

    fn physics(&self) -> &'static [Physics] {
        constraint_physics(self.target_physics)
    }

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

    fn display(&self) -> String {
        let n = self.imposed_mesh.cell_count();
        format!(
            "SubModel<Dirichlet({})>: {} constrained node(s)",
            self.imposed_variable, n
        )
    }

    fn render(&self, _opts: &DumpOptions) -> String {
        let nc = self.imposed_mesh.cell_count();
        let nm = self.multiplier_mesh.cell_count();
        format!(
            "SubModel<Dirichlet({imposed_variable})>\n  primal var(s): {MULTIPLIER} \
             (multiplier)\n  dual var(s):   {IMPOSED} (imposed value)\n  \
             targets primary dual: {target_dual}\n  sense: {sense}\n  \
             constrained: {nc} node(s)\n  multipliers: {nm} node(s)",
            imposed_variable = self.imposed_variable,
            target_dual = self.target_dual,
            sense = self.sense,
        )
    }
}

impl Constraint for Dirichlet {
    fn multiplier_mesh(&self) -> &Mesh {
        &self.multiplier_mesh
    }

    /// Dirichlet is a single-term relation `1·u ⋈ u_d` per constrained node
    /// (`⋈` is the sub-model's sense, `=` by default).
    fn relations(&self) -> Result<Vec<Relation>> {
        let mut relations = Vec::with_capacity(self.imposed_mesh.cell_count());
        for i in 0..self.imposed_mesh.len() {
            // Read in place: the loop below only copies ids out by value and
            // clones strings, it never re-locks either submesh.
            let imposed = self.imposed_mesh.get(i)?.read();
            let multiplier = self.multiplier_mesh.get(i)?.read();
            for (imp, mult) in imposed
                .connectivity()
                .iter()
                .zip(multiplier.connectivity().iter())
            {
                relations.push(Relation {
                    multiplier_node: *mult,
                    terms: vec![ConstraintTerm {
                        node: *imp,
                        variable: self.imposed_variable.clone(),
                        target_dual: self.target_dual.clone(),
                        coefficient: 1.0,
                    }],
                    sense: self.sense,
                });
            }
        }
        Ok(relations)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::atoms::{ElementType, Node, NodeId};
    use crate::containers::finite_element_space::FiniteElementSpace;
    use crate::containers::mesh::SubMesh;
    use crate::containers::model::Model;
    use crate::containers::node_field::NodeField;
    use crate::coords::Coords;
    use crate::handle::Handle;
    use crate::models::symmetry::MaterialSymmetry;
    use crate::ops::{element_field, matrix, mesh, model, node_field, solver};
    use std::collections::HashSet;

    /// The README plate: 10 cm of steel, 20 × 20 QUA4, heated throughout.
    /// Returns the plate, its finite-element space and its conduction model.
    fn plate() -> (Mesh, FiniteElementSpace, Model) {
        let coords = Handle::new(Coords::new(2).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let b = Node::create_in(coords, &[0.10, 0.0]).unwrap();
        let edge = mesh::line(&a, &b, 20, ElementType::SEG2).unwrap();
        let plate = mesh::extrude(&edge, &[0.0, 0.10], 20).unwrap();
        let fes = FiniteElementSpace::lagrange1(&plate).unwrap();
        let conduction = model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
        (plate, fes, conduction)
    }

    /// Solve the heated plate with `T = 0` held on `imposed`.
    fn solve_holding(fes: &FiniteElementSpace, conduction: &Model, imposed: &Mesh) -> NodeField {
        let held = model::dirichlet(imposed, conduction, "T", RelationSense::Equality).unwrap();
        let source = model::flux(fes, conduction, "q").unwrap();
        let whole = conduction.union(&held).unwrap().union(&source).unwrap();
        let materials =
            element_field::material_field(&whole, &[("k", 50.0), ("phi_q", 1.0e6)]).unwrap();
        let k = matrix::stiffness(&whole, &materials).unwrap();
        let rhs = node_field::external_forces(&whole, &materials).unwrap();
        solver::solve(&k, &rhs).unwrap()
    }

    /// The distinct node ids of `mesh`, counted here, apart from `to_poi1`.
    fn distinct_nodes(mesh: &Mesh) -> HashSet<NodeId> {
        mesh.iter()
            .flat_map(|zone| zone.read().connectivity().to_vec())
            .collect()
    }

    #[test]
    fn holds_an_edge_through_its_poi1_companion() {
        let (plate, fes, conduction) = plate();
        let border = mesh::border(&plate, None).unwrap();
        let on_edge = Dirichlet::new(&border, &conduction, "T", RelationSense::Equality).unwrap();
        let on_points = Dirichlet::new(
            &mesh::to_poi1(&border),
            &conduction,
            "T",
            RelationSense::Equality,
        )
        .unwrap();

        // One relation per border node: 80 of them, counted apart.
        assert_eq!(distinct_nodes(&border).len(), 80);
        assert_eq!(on_edge.imposed_mesh.cell_count(), 80);
        // Both land on the border's own POI1 companion, not on a copy.
        let companion = SubMesh::to_poi1(&border.get(0).unwrap());
        assert!(on_edge.imposed_mesh.get(0).unwrap().same_object(&companion));
        assert!(on_points
            .imposed_mesh
            .get(0)
            .unwrap()
            .same_object(&companion));

        // And they solve to the same temperature, node by node (to rounding:
        // the solver is the one step allowed not to be bitwise reproducible).
        let nodes: Vec<NodeId> = SubMesh::to_poi1(&plate.get(0).unwrap())
            .read()
            .connectivity()
            .to_vec();
        let t_edge = solve_holding(&fes, &conduction, &border);
        let t_points = solve_holding(&fes, &conduction, &mesh::to_poi1(&border));
        let edge_values = t_edge.values_at(&nodes, "T").unwrap();
        let points_values = t_points.values_at(&nodes, "T").unwrap();
        let t_max = edge_values.iter().cloned().fold(f64::MIN, f64::max);
        for (e, p) in edge_values.iter().zip(&points_values) {
            assert!((e - p).abs() <= 1e-12 * t_max, "{e} vs {p}");
        }
        assert!((t_max - 14.76).abs() < 5e-3, "T max = {t_max}");
    }

    #[test]
    fn keeps_a_poi1_zone_given_as_it_is() {
        let (plate, _fes, conduction) = plate();
        let corner = mesh::poi1_from_nodes(&[plate.node(0, 0, 0).unwrap()]).unwrap();
        let held = Dirichlet::new(&corner, &conduction, "T", RelationSense::Equality).unwrap();
        assert!(held
            .imposed_mesh
            .get(0)
            .unwrap()
            .same_object(&corner.get(0).unwrap()));
    }

    #[test]
    fn gives_a_node_two_zones_share_one_relation() {
        // A bar a–b–d, held on its two segments as two zones sharing `b`.
        let coords = Handle::new(Coords::new(1).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[1.0]).unwrap();
        let d = Node::create_in(coords, &[2.0]).unwrap();
        let bar = mesh::line(&a, &d, 2, ElementType::SEG2).unwrap();
        let halves = mesh::line(&a, &b, 1, ElementType::SEG2)
            .unwrap()
            .union(&mesh::line(&b, &d, 1, ElementType::SEG2).unwrap())
            .unwrap();
        assert_eq!(halves.len(), 2);
        let fes = FiniteElementSpace::lagrange1(&bar).unwrap();
        let conduction = model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();

        let held = Dirichlet::new(&halves, &conduction, "T", RelationSense::Equality).unwrap();
        // One zone, one relation per distinct node: a, b, d.
        assert_eq!(distinct_nodes(&halves).len(), 3);
        assert_eq!(held.imposed_mesh.len(), 1);
        assert_eq!(held.imposed_mesh.cell_count(), 3);

        // `b` is held once, so the system solves.
        let whole = conduction
            .union(&model::dirichlet(&halves, &conduction, "T", RelationSense::Equality).unwrap())
            .unwrap();
        let materials = element_field::material_field(&whole, &[("k", 1.0)]).unwrap();
        let k = matrix::stiffness(&whole, &materials).unwrap();
        let rhs = node_field::external_forces(&whole, &materials).unwrap();
        let t = solver::solve(&k, &rhs).unwrap();
        assert_eq!(t.value(b.id(), "T").unwrap(), 0.0);
    }
}