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
//! Exchange law across an interface — the first inter-mesh coupling.
//!
//! Two unit squares laid side by side, `[0,1]×[0,1]` and `[1,2]×[0,1]`, that do
//! **not** share their junction: at `x = 1` each carries its own pair of nodes,
//! and the two bodies are tied only by the exchange law `j·n = h(c₁ − c₂)`.
//!
//! A uniform flux density `q` enters at `x = 0` and the concentration is imposed
//! at `x = 2`. In steady state the same `q` crosses everything, so the profile
//! is piecewise linear with a **jump** at the interface:
//!
//! ```text
//! drop across each square : q/D          jump across the interface : q/h
//! ```
//!
//! The jump is the whole point. It is what an interface law adds over a shared
//! node, and it is carried entirely by the two **off-diagonal** blocks — those
//! whose rows live on one mesh and whose columns live on the other, which is
//! what `Contribution::Coupling` exists for. A stiff interface (`h → ∞`)
//! recovers the continuous solution, which the second test checks.
//!
//! Single source for the « transfert d'interface » example of the diffusion book
//! chapter; runs under `cargo test`.

// ANCHOR: example
use pyrucast::aggregate::Aggregate;
use pyrucast::atoms::{ElementType, Node};
use pyrucast::containers::element_field::ElementField;
use pyrucast::containers::finite_element_space::FiniteElementSpace;
use pyrucast::containers::mesh::{Mesh, SubMesh};
use pyrucast::containers::model::Model;
use pyrucast::containers::node_field::{NodeField, SubNodeField};
use pyrucast::coords::Coords;
use pyrucast::handle::Handle;
use pyrucast::models::interface_transfer::DEFAULT_TOL;
use pyrucast::models::symmetry::MaterialSymmetry;
use pyrucast::models::{Physics, IMPOSED};
use pyrucast::ops::model;
use pyrucast::ops::solver::solve;
use pyrucast::Result;

/// The diffusing species — every name of the Fick physics carries it.
const SPECIES: &str = "H2";

const D: f64 = 2.0; // diffusivity, both squares
const Q: f64 = 10.0; // flux density injected at x = 0
const C_RIGHT: f64 = 1.0; // concentration imposed at x = 2

#[test]
fn an_interface_law_makes_the_field_jump() -> Result<()> {
    const H: f64 = 5.0; // transfer coefficient
    let (geom, solution) = solve_two_squares(H)?;

    let c = |n: &Node| solution.value(n.id(), &format!("c_{SPECIES}"));
    let far_left = c(&geom.left[0])?; // (0, 0)
    let left_face = c(&geom.left[1])?; // (1, 0), left side
    let right_face = c(&geom.right[0])?; // (1, 0), right side
    let far_right = c(&geom.right[1])?; // (2, 0)

    let tol = 1e-10;
    assert!((far_right - C_RIGHT).abs() < tol, "c(2) = {far_right}");
    // Slope q/D over the unit width of each square.
    assert!(
        (far_left - left_face - Q / D).abs() < tol,
        "left square: {far_left} → {left_face}"
    );
    assert!(
        (right_face - far_right - Q / D).abs() < tol,
        "right square: {right_face} → {far_right}"
    );
    // …and the jump across the interface is q/h — the exchange law itself.
    let jump = left_face - right_face;
    assert!(
        (jump - Q / H).abs() < tol,
        "jump = {jump}, expected {}",
        Q / H
    );
    Ok(())
}
// ANCHOR_END: example

/// A stiff interface (`h → ∞`) must recover the single continuous body: the jump
/// vanishes as `q/h`, so the two facing values converge to each other.
/// The interface returns its residual term **on both sides**, equal and opposite.
///
/// `∫h(a₁−a₂)N` on A and its opposite on B: the integral of a difference is the
/// difference of the integrals, and each scatters onto its own space. What is
/// coupled is the matrix — rows on A, columns on B — not the vector, which
/// produces only one number per node. The interface therefore no longer has a
/// law: its `h·(a₁−a₂)` is its own operator's coefficient applied to the jump,
/// not a behaviour.
/// The interface's residual **is** its matrix applied to the solution.
///
/// The operator is linear: `r = K·u` is not an approximation but an identity,
/// and it is the only test that pins the *values* down. The antisymmetry, for
/// its part, survives an error shared by both sides — both contributions are
/// born of the same jump, up to the sign. That is what it took to see that the
/// jump was read by position in an interpolated field that carries **every**
/// composantes de la solution, multiplicateur de Dirichlet compris.
#[test]
fn the_interface_residual_is_its_matrix_applied_to_the_solution() -> Result<()> {
    const H: f64 = 5.0;
    let (geom, model, materials) = two_square_model(H)?;
    let (_, solution) = solve_two_squares(H)?;

    let interface = {
        let mut m = Model::empty();
        for h in &model {
            if h.read().as_kind().label() == "InterfaceTransfer" {
                m.add_sub(h.clone())?;
            }
        }
        m
    };
    let state = ElementField::empty();
    let r = pyrucast::ops::node_field::internal_forces(&interface, &state, &solution, &materials)?;
    let k = pyrucast::ops::matrix::stiffness(&interface, &materials)?;
    let ku = (&k * &solution)?;

    let dual = format!("j_{SPECIES}");
    let mut vus = 0;
    for n in [&geom.left[1], &geom.left[2], &geom.right[0], &geom.right[3]] {
        let got = r.value(n.id(), &dual)?;
        let want = ku.value(n.id(), &dual)?;
        assert!(
            (got - want).abs() < 1e-9 * want.abs().max(1.0),
            "r ≠ K·u en {:?} : {got} vs {want}",
            n.id()
        );
        vus += 1;
    }
    assert_eq!(vus, 4);
    Ok(())
}

#[test]
fn the_interface_renders_equal_and_opposite_fluxes() -> Result<()> {
    const H: f64 = 5.0;
    let (geom, model, materials) = two_square_model(H)?;
    let (_, solution) = solve_two_squares(H)?;

    // Le résidu de l'interface seule : on pointe le sous-modèle qu'on veut.
    let interface = {
        let mut m = Model::empty();
        for h in &model {
            if h.read().as_kind().label() == "InterfaceTransfer" {
                m.add_sub(h.clone())?;
            }
        }
        m
    };
    let state = pyrucast::containers::element_field::ElementField::empty();
    let f = pyrucast::ops::node_field::internal_forces(&interface, &state, &solution, &materials)?;

    let dual = format!("j_{SPECIES}");
    // Sum on each side of the interface: the two faces looking at each other.
    let cote_a: f64 = [&geom.left[1], &geom.left[2]]
        .iter()
        .map(|n| f.value(n.id(), &dual).unwrap_or(0.0))
        .sum();
    let cote_b: f64 = [&geom.right[0], &geom.right[3]]
        .iter()
        .map(|n| f.value(n.id(), &dual).unwrap_or(0.0))
        .sum();

    assert!(cote_a.abs() > 1e-9, "l'interface doit transporter un flux");
    assert!(
        (cote_a + cote_b).abs() < 1e-9 * cote_a.abs().max(1.0),
        "les deux côtés doivent s'annuler : {cote_a} et {cote_b}"
    );
    Ok(())
}

#[test]
fn a_stiff_interface_recovers_a_continuous_body() -> Result<()> {
    let mut previous = f64::INFINITY;
    for h in [1e2, 1e4, 1e6] {
        let (geom, solution) = solve_two_squares(h)?;
        let jump = solution.value(geom.left[1].id(), &format!("c_{SPECIES}"))?
            - solution.value(geom.right[0].id(), &format!("c_{SPECIES}"))?;
        assert!(
            (jump - Q / h).abs() < 1e-8 * jump.abs().max(1.0),
            "h = {h}: jump {jump} ≠ {}",
            Q / h
        );
        assert!(
            jump < previous,
            "the jump must shrink with h: {jump} ≥ {previous}"
        );
        previous = jump;
    }
    assert!(previous < 1e-4, "residual jump {previous}");
    Ok(())
}

/// The exchange term is symmetric overall (`+K −K / −K +K`), so the assembled
/// stiffness stays symmetric even though **each** coupling block alone is not.
/// That is the structural check that the four blocks land where they should.
#[test]
fn the_four_blocks_sum_to_a_symmetric_operator() -> Result<()> {
    let (_, model, materials) = two_square_model(3.0)?;
    let k = pyrucast::ops::matrix::stiffness(&model, &materials)?;
    let dense = k.to_dmatrix()?;
    let n = k.row_dofs()?.len();
    assert_eq!(dense.shape(), (n, n));
    for i in 0..n {
        for j in 0..n {
            let (a, b) = (dense[(i, j)], dense[(j, i)]);
            assert!((a - b).abs() < 1e-12, "K[{i},{j}] = {a} ≠ {b} = K[{j},{i}]");
        }
    }
    // The coupling really is there: some entry links a left-side DOF to a
    // right-side one, which a pair of independent bodies could never produce.
    let coupling = (0..n)
        .flat_map(|i| (0..n).map(move |j| (i, j)))
        .any(|(i, j)| i != j && dense[(i, j)].abs() > 1e-12);
    assert!(coupling, "the interface must couple the two meshes");
    Ok(())
}

/// A non-conforming interface is a meshing problem, and is reported as one
/// rather than resolved by a silent projection.
#[test]
fn a_non_conforming_interface_is_rejected() -> Result<()> {
    let coords = Handle::new(Coords::new(2)?);
    let node = |x: f64, y: f64| Node::create_in(coords.clone(), &[x, y]);
    let edge = |a: &Node, b: &Node| -> Result<FiniteElementSpace> {
        let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
        m.add_cell(&[a.id(), b.id()])?;
        FiniteElementSpace::lagrange1(&m)
    };
    let (a0, a1) = (node(1.0, 0.0)?, node(1.0, 1.0)?);
    // The facing edge sits at x = 1.5: the two sides do not describe one surface.
    let (b0, b1) = (node(1.5, 0.0)?, node(1.5, 1.0)?);
    let (side_a, side_b) = (edge(&a0, &a1)?, edge(&b0, &b1)?);
    // A valid target, so that it really is the geometry that gets refused.
    let target = model::fick(&side_a, SPECIES, MaterialSymmetry::Isotropic)?;
    let err = model::interface_transfer(
        &side_a,
        &side_b,
        &target,
        vec![format!("c_{SPECIES}")],
        DEFAULT_TOL,
    )
    .unwrap_err();
    let msg = err.to_string();
    assert!(msg.contains("not node-conforming"), "unexpected: {msg}");
    Ok(())
}

/// The interface is built **against** the model it ties, and takes its nature
/// from it: nothing in `"c_H2"` says « diffusion », the Fick models declaring
/// that unknown do.
#[test]
fn the_interface_takes_its_nature_from_its_target() -> Result<()> {
    let (_, model, _) = two_square_model(5.0)?;
    // The two Fick squares, and the interface tying them; the support and the
    // input are constraints and a load, counted apart.
    let diffusion = model.filter(Physics::Diffusion);
    assert!(diffusion
        .iter()
        .any(|sub| sub.read().as_kind().label() == "InterfaceTransfer"));
    assert!(model.filter(Physics::Thermal).is_empty());
    Ok(())
}

/// A variable the target does not declare would couple into nothing: refused
/// at construction, with the unknowns the target does declare in the message.
/// One it declares couples into the dual row the target pairs it with.
#[test]
fn a_variable_its_target_does_not_declare_is_rejected() -> Result<()> {
    let coords = Handle::new(Coords::new(2)?);
    let (a, b) = (
        Node::create_in(coords.clone(), &[1.0, 0.0])?,
        Node::create_in(coords.clone(), &[1.0, 1.0])?,
    );
    let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
    m.add_cell(&[a.id(), b.id()])?;
    let face = FiniteElementSpace::lagrange1(&m)?;
    let diffusion = model::fick(&face, SPECIES, MaterialSymmetry::Isotropic)?;

    // A thermal contact resistance on a model that does not know `T`.
    let err = model::interface_transfer(&face, &face, &diffusion, vec!["T".into()], DEFAULT_TOL)
        .unwrap_err()
        .to_string();
    assert!(err.contains("`T` is not an unknown"), "unexpected: {err}");

    // Beside a conduction, the concentration still couples into its own flux
    // row, read from the Fick model: never `q`.
    let both = diffusion.union(&model::heat_conduction(&face, MaterialSymmetry::Isotropic)?)?;
    let joint = model::interface_transfer(
        &face,
        &face,
        &both,
        vec![format!("c_{SPECIES}")],
        DEFAULT_TOL,
    )?;
    assert_eq!(joint.dual_vars(), vec![format!("j_{SPECIES}")]);

    // Two kinds in a single interface: one is built per physics.
    let err = model::interface_transfer(
        &face,
        &face,
        &both,
        vec![format!("c_{SPECIES}"), "T".into()],
        DEFAULT_TOL,
    )
    .unwrap_err()
    .to_string();
    assert!(err.contains("single nature"), "unexpected: {err}");
    Ok(())
}

// ─── Fixtures ───────────────────────────────────────────────────────────────

/// The two squares' nodes, `[bottom-left, bottom-right, top-right, top-left]`.
struct Geometry {
    left: Vec<Node>,
    right: Vec<Node>,
}

/// Two QUA4 squares with **duplicated** nodes at `x = 1`, their diffusion models,
/// and the interface law tying them.
fn two_square_model(h: f64) -> Result<(Geometry, Model, ElementField)> {
    let coords = Handle::new(Coords::new(2)?);
    let node = |x: f64, y: f64| Node::create_in(coords.clone(), &[x, y]);

    // Left square [0,1]², right square [1,2]×[0,1]. The two pairs at x = 1 are
    // distinct node objects at the same position: that is what lets `c` jump.
    let left = vec![
        node(0.0, 0.0)?,
        node(1.0, 0.0)?,
        node(1.0, 1.0)?,
        node(0.0, 1.0)?,
    ];
    let right = vec![
        node(1.0, 0.0)?,
        node(2.0, 0.0)?,
        node(2.0, 1.0)?,
        node(1.0, 1.0)?,
    ];

    let square = |ns: &[Node]| -> Result<FiniteElementSpace> {
        let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::QUA4));
        m.add_cell(&ns.iter().map(|n| n.id()).collect::<Vec<_>>())?;
        FiniteElementSpace::lagrange1(&m)
    };
    let edge = |a: &Node, b: &Node| -> Result<FiniteElementSpace> {
        let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
        m.add_cell(&[a.id(), b.id()])?;
        FiniteElementSpace::lagrange1(&m)
    };

    // The interface: the x = 1 edge of each square, node for node
    // (bottom → top on both sides, so local node k faces local node k).
    let face_left = edge(&left[1], &left[2])?;
    let face_right = edge(&right[0], &right[3])?;

    // Concentration imposed on the far-right edge (x = 2).
    let imposed = Mesh::from_submesh(SubMesh::poi1_from_nodes(&[
        right[1].clone(),
        right[2].clone(),
    ])?);

    // The two squares' diffusion: that is what the support constrains.
    let fick_pair = model::fick(&square(&left)?, SPECIES, MaterialSymmetry::Isotropic)?.union(
        &model::fick(&square(&right)?, SPECIES, MaterialSymmetry::Isotropic)?,
    )?;
    let model = fick_pair
        .union(&model::interface_transfer(
            &face_left,
            &face_right,
            &fick_pair,
            vec![format!("c_{SPECIES}")],
            DEFAULT_TOL,
        )?)?
        .union(&model::dirichlet(
            &imposed,
            &fick_pair,
            &format!("c_{SPECIES}"),
            Default::default(),
        )?)?;

    // The inlet: uniform flux density Q on the far-left edge (x = 0). A load
    // is a term of the model, so it joins it here and its density joins the
    // material below.
    let inlet = edge(&left[0], &left[3])?;
    let model = model.union(&model::flux(&inlet, &model, &format!("j_{SPECIES}"))?)?;

    // One material field for the whole model: the squares ask for `D`, the
    // interface for `h`, the inlet for its density, and each resolves its own
    // zone by its components.
    let materials = pyrucast::ops::element_field::material_field(
        &model,
        &[
            (&format!("D_{SPECIES}"), D),
            (&format!("h_c_{SPECIES}"), h),
            (&format!("phi_j_{SPECIES}"), Q),
        ],
    )?;
    Ok((Geometry { left, right }, model, materials))
}

/// Build, load and solve the two-square problem for a given transfer coefficient.
fn solve_two_squares(h: f64) -> Result<(Geometry, NodeField)> {
    let (geom, model, materials) = two_square_model(h)?;
    let coords = geom.left[0].coords();

    // The inlet's consistent nodal loads: the model carries the term, we ask
    // it for its value.
    let influx = pyrucast::ops::node_field::external_forces(&model, &materials)?;

    // The imposed concentration, on the Dirichlet multiplier nodes.
    let mult_mesh = model.multiplier_mesh()?;
    let mut imposed_sm = SubMesh::new(coords, ElementType::POI1);
    let mut mults = Vec::new();
    for i in 0..mult_mesh.len() {
        let cells = mult_mesh.get(i)?.read().cell_count();
        for cell in 0..cells {
            let id = mult_mesh.node(i, cell, 0)?.id();
            imposed_sm.add_cell(&[id])?;
            mults.push(id);
        }
    }
    let imposed_sm = Handle::new(imposed_sm);
    let mut imposed = SubNodeField::from_poi1(&imposed_sm, vec![IMPOSED.to_string()])?;
    for id in &mults {
        imposed.set_value(*id, IMPOSED, C_RIGHT)?;
    }

    let rhs = influx.union(&NodeField::from_sub(imposed))?;
    let stiffness = pyrucast::ops::matrix::stiffness(&model, &materials)?;
    let solution = solve(&stiffness, &rhs)?;
    Ok((geom, solution))
}