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
//! The exchange law `h(a − b)` — what a boundary and an interface share.
//!
//! One law, two situations, and the only difference is **which side of the
//! equals sign the far medium lives on**:
//!
//! | | the far side is… | where it goes |
//! |---|---|---|
//! | [boundary](crate::models::boundary_transfer) | a **datum** (an ambient value) | the right-hand side, `h·a_ext ∫N dΓ` |
//! | [interface](crate::models::interface_transfer) | an **unknown** (the other mesh's field) | the matrix, as a coupling block |
//!
//! The off-diagonal block *is* the right-hand side made implicit. That is why
//! the two physics share this module rather than each carrying a copy of
//! `∫NᵢNⱼ`: the boundary kernel is the interface kernel with both sides on the
//! same cell.
//!
//! ## What is transferred is the caller's to say
//!
//! Neither physics knows what it transports. It is given a list of variables —
//! the same shape [`embedded`](crate::models::embedded) and
//! [`contact`](crate::models::contact) take, the two other laws that tie meshes
//! together — each paired with the dual row the model it couples into declares
//! for it, and everything else follows from it:
//!
//! ```text
//! transferred  (dual)  material   behaviour input     behaviour output
//! "T"          q       h_T        T      / jump_T     flux_T
//! "c_H2"       j_H2    h_c_H2     c_H2   / jump_c_H2  flux_c_H2
//! "u_x"        f_x     h_u_x      u_x    / jump_u_x   flux_u_x
//! ```
//!
//! One coefficient per transferred quantity, named after it. A surface exchange
//! on displacements is then a **Winkler elastic foundation**, and an interface
//! one a joint of finite stiffness — neither needed a line of new physics.
//!
//! ## When *not* to use it on displacements
//!
//! Tying two surfaces by making `h` large is a penalty method, and a
//! [`Mpc`](crate::models::mpc) does it exactly, without degrading the
//! conditioning. The test is where the number comes from: **if `h` comes from a
//! measurement this is physics; if `h` was chosen "large enough", it wanted a
//! constraint.**

use crate::containers::element_field::SubElementField;
use crate::containers::field::SubField;
use crate::containers::model::{Model, SubModel};
use crate::error::{PyrucastError, Result};
use crate::models::{CellGeom, Physics};

/// The material component carrying the exchange coefficient of one transferred
/// quantity — `h_T`, `h_c_H2`, `h_u_x`.
///
/// Derived rather than tabulated, which is what made
/// [`Domain::material_components`](crate::models::Domain::material_components)
/// owned: the name is not known until the caller says what is transferred.
///
/// ```
/// # use pyrucast::models::transfer;
/// // The name is not tabulated: it follows from what the caller carries.
/// assert_eq!(transfer::coefficient_name("T"), "h_T");
/// assert_eq!(transfer::coefficient_name("c_H2"), "h_c_H2");
/// ```
pub fn coefficient_name(primal: &str) -> String {
    format!("h_{primal}")
}

/// The behaviour **output** component of one transferred quantity: the exchanged
/// flux density `h·(a − b)`.
///
/// ```
/// # use pyrucast::models::transfer;
/// // La **sortie** de la loi : la densité de flux échangée.
/// assert_eq!(transfer::flux_name("T"), "flux_T");
/// ```
pub fn flux_name(primal: &str) -> String {
    format!("flux_{primal}")
}

/// The **ambient** of one transferred quantity across a boundary: the far-field
/// value `a_ext` the exchange drives towards, named after the quantity —
/// `a_ext_T`, `a_ext_c_H2`.
///
/// It is a material component like the coefficient beside it, and **required**
/// for the same reason `T_inf` is required of radiation: the term
/// `∫ h·a_ext·N` exists whether or not anyone remembers it, and a forgotten
/// ambient silently reads as zero.
///
/// ```
/// # use pyrucast::models::transfer;
/// assert_eq!(transfer::ambient_name("T"), "a_ext_T");
/// ```
pub fn ambient_name(primal: &str) -> String {
    format!("a_ext_{primal}")
}

/// The behaviour **input** component of an interface law: the jump of one
/// transferred quantity across it, `a₁ − a₂`.
///
/// A boundary law needs no such name — its input is the field itself, the far
/// side being a datum rather than a second unknown.
///
/// ```
/// # use pyrucast::models::transfer;
/// // An interface law's **input**: the jump a₁ − a₂. A border law does not
/// // need it — its input is the field itself.
/// assert_eq!(transfer::jump_name("T"), "jump_T");
/// ```
pub fn jump_name(primal: &str) -> String {
    format!("jump_{primal}")
}

/// Check a caller's transferred variables, and return the material contract
/// they imply. An empty list is a caller error: a law that transfers nothing has
/// no matrix to assemble and no coefficient to read.
///
/// ```
/// # use pyrucast::models::transfer;
/// assert_eq!(transfer::material_contract("BoundaryTransfer", &["T".to_string()])?,
///            vec!["h_T".to_string()]);
/// // A law that transports nothing has neither matrix nor coefficient: that
/// // is a call error, not a degenerate case to let through.
/// assert!(transfer::material_contract("BoundaryTransfer", &[]).is_err());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn material_contract(label: &str, variables: &[String]) -> Result<Vec<String>> {
    if variables.is_empty() {
        return Err(PyrucastError::Message(format!(
            "{label}: nothing to transfer — give at least one variable, e.g. [\"T\"] for a \
             thermal exchange or [\"u_x\", \"u_y\"] for an elastic one"
        )));
    }
    Ok(variables.iter().map(|v| coefficient_name(v)).collect())
}

/// The `'static` singleton slice of one nature, so a physics whose nature is
/// **stored** can still answer [`SubModelKind::physics`](crate::models::SubModelKind::physics)
/// without the trait
/// having to hand out owned data.
///
/// A transfer law's nature cannot be deduced from its variable names, which the
/// caller chooses freely; it is read once from the model it couples into (see
/// `target_physics`) and kept. There are finitely many natures, and each has
/// exactly one slice.
///
/// ```
/// # use pyrucast::models::transfer;
/// # use pyrucast::models::Physics;
/// // A transfer law's kind does not follow from the variable names, which the
/// // caller picks: it comes from the target, is kept, then given back here as
/// // a `'static` slice.
/// assert_eq!(transfer::physics_slice(Physics::Thermal), &[Physics::Thermal]);
/// ```
pub fn physics_slice(physics: Physics) -> &'static [Physics] {
    match physics {
        Physics::Mechanical => &[Physics::Mechanical],
        Physics::Thermal => &[Physics::Thermal],
        Physics::Constraint => &[Physics::Constraint],
        Physics::Other => &[Physics::Other],
        Physics::Diffusion => &[Physics::Diffusion],
        Physics::Radiation => &[Physics::Radiation],
    }
}

/// The natures of a constraint: [`Constraint`](Physics::Constraint) first,
/// then the nature of the physics it constrains when it constrains a single
/// one.
///
/// A Dirichlet on `u_x` is a mechanical constraint: `model.filter(Mechanical)`
/// must hand it over with the elasticity it pins, or the mechanical part of a
/// coupled model would come out singular. A relation tying the unknowns of two
/// physics (`None`) belongs to neither — no single-physics sub-problem could
/// solve it — and stays a bare constraint. `Constraint` heads the slice so that
/// whoever reads a constraint's primary nature still reads that.
///
/// ```
/// # use pyrucast::models::transfer;
/// # use pyrucast::models::Physics;
/// assert_eq!(
///     transfer::constraint_physics(Some(Physics::Mechanical)),
///     &[Physics::Constraint, Physics::Mechanical]
/// );
/// // A relation across two physics belongs to neither.
/// assert_eq!(transfer::constraint_physics(None), &[Physics::Constraint]);
/// ```
pub fn constraint_physics(target: Option<Physics>) -> &'static [Physics] {
    match target {
        None | Some(Physics::Constraint) => &[Physics::Constraint],
        Some(Physics::Mechanical) => &[Physics::Constraint, Physics::Mechanical],
        Some(Physics::Thermal) => &[Physics::Constraint, Physics::Thermal],
        Some(Physics::Other) => &[Physics::Constraint, Physics::Other],
        Some(Physics::Diffusion) => &[Physics::Constraint, Physics::Diffusion],
        Some(Physics::Radiation) => &[Physics::Constraint, Physics::Radiation],
    }
}

/// The single nature of the physics a constraint acts on, read from the model
/// it constrains: the owner of each constrained primal, which must all agree.
///
/// `None` when the primals belong to several physics, or to none of `target`'s
/// sub-models — the constraint then carries no nature beyond
/// [`Constraint`](Physics::Constraint) (see [`constraint_physics`]). Read once,
/// at construction.
pub(crate) fn constrained_physics<'a>(
    target: &Model,
    primals: impl IntoIterator<Item = &'a str>,
) -> Option<Physics> {
    let mut nature: Option<Physics> = None;
    for primal in primals {
        let found = owner_physics(target, |sub| {
            sub.as_kind().primal_vars().iter().any(|p| p == primal)
        })?;
        match nature {
            Some(first) if first != found => return None,
            _ => nature = Some(found),
        }
    }
    nature
}

/// The nature of the first sub-model of `target` that `owns` a row — what a
/// term writing into another physics' rows inherits instead of declaring.
///
/// Only the head of [`physics()`](crate::models::SubModelKind::physics) is
/// taken: a radiation declares `[Thermal, Radiation]`, and what couples into it
/// is thermal. Read once, at construction — never at assembly.
pub(crate) fn owner_physics(target: &Model, owns: impl Fn(&SubModel) -> bool) -> Option<Physics> {
    target.into_iter().find_map(|h| {
        let sub = h.read();
        owns(&sub).then(|| sub.as_kind().physics()[0])
    })
}

/// The nature of a term acting on `(primal, dual)` pairs, read from the model
/// it couples into, which must assemble every one of them.
///
/// A pair is assembled when a sub-model of `target` counts `primal` among its
/// unknowns **and** pairs it with `dual`, the positional pairing of
/// [`SubModel::dual_of`]. Every pair must belong to one nature: a term carries
/// a single one, and `model.filter(…)` selects it by it.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::ops::element_field::StrainMeasure;
/// # 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::boundary_transfer::BoundaryTransfer;
/// # use pyrucast::models::tensor::Kinematics;
/// # use pyrucast::models::{Physics, SubModelKind};
/// # 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();
/// # let zone = fes.get(0).unwrap();
/// // Le constructeur d'un échange s'en sert : la nature sort de la cible.
/// let deux = model::heat_conduction(&fes, MaterialSymmetry::Isotropic)?
///     .union(&model::elasticity(&fes, Kinematics::PlaneStress, MaterialSymmetry::Isotropic, StrainMeasure::Linear)?)?;
/// let film = BoundaryTransfer::new(zone.clone(), &deux, vec!["T".into()])?;
/// assert_eq!(film.physics(), &[Physics::Thermal]);
/// let appui = BoundaryTransfer::new(zone.clone(), &deux, vec!["u_x".into()])?;
/// assert_eq!(appui.physics(), &[Physics::Mechanical]);
/// // Two kinds in a single term: refused.
/// assert!(BoundaryTransfer::new(zone, &deux, vec!["T".into(), "u_x".into()]).is_err());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub(crate) fn target_physics(
    label: &str,
    target: &Model,
    components: &[(String, String)],
) -> Result<Physics> {
    let mut nature: Option<Physics> = None;
    for (primal, dual) in components {
        let found = owner_physics(target, |sub| {
            sub.dual_of(primal).as_deref() == Some(dual.as_str())
        })
        .ok_or_else(|| {
            PyrucastError::Message(format!(
                "{label}: the model it couples into assembles no `{primal}` paired with \
                 `{dual}` — its unknowns are {:?}, paired with the rows {:?}",
                target.primal_vars(),
                target.dual_vars()
            ))
        })?;
        match nature {
            Some(first) if first != found => {
                return Err(PyrucastError::Message(format!(
                    "{label}: `({primal}, {dual})` belongs to a {} physics and the pairs \
                     before it to a {} one — a term carries a single nature, build one per \
                     physics",
                    found.name(),
                    first.name()
                )))
            }
            _ => nature = Some(found),
        }
    }
    nature.ok_or_else(|| {
        PyrucastError::Message(format!(
            "{label}: nothing to transfer — give at least one (primal, dual) pair"
        ))
    })
}

/// The `(primal, dual)` pairs of the `variables` a term acts on, each dual read
/// from the model it couples into ([`Model::dual_of`]), with that model's nature
/// for them ([`target_physics`]).
///
/// The caller names what is transferred and nothing more: the dual row is a
/// fact of the physics already declared, not something to type again. A
/// variable `target` does not declare is refused here, rather than building a
/// term coupled to nothing.
pub(crate) fn target_pairs(
    label: &str,
    target: &Model,
    variables: &[String],
) -> Result<(Vec<(String, String)>, Physics)> {
    let mut pairs = Vec::with_capacity(variables.len());
    for v in variables {
        let dual = target.dual_of(v).ok_or_else(|| {
            PyrucastError::Message(format!(
                "{label}: `{v}` is not an unknown of the model it couples into — it declares \
                 {:?}",
                target.primal_vars()
            ))
        })?;
        pairs.push((v.clone(), dual));
    }
    let physics = target_physics(label, target, &pairs)?;
    Ok((pairs, physics))
}

/// `sign · h ∫_Γ N_i^row N_j^col dΓ`, one uncoupled sub-block per transferred
/// quantity.
///
/// The four blocks of an interface come from this one function: the two diagonal
/// ones with `row_geom == col_geom` and `sign = +1`, the two off-diagonal ones
/// with the facing cell and `sign = −1`. A boundary term is the diagonal case
/// alone.
///
/// `ke` is laid out [`NodesThenVars`](crate::containers::matrix::DofOrdering),
/// so a node's variables are contiguous. Quantities do **not** couple to each
/// other — heat crossing a joint does not drive hydrogen across it — which is
/// why only the diagonal in the variable index is written.
///
/// The measure comes from the **row** side: on a conforming interface the two
/// carry the same surface, so either would do, and taking the row side keeps the
/// four blocks integrated identically — which is what makes them sum to a
/// consistent operator.
///
/// ```
/// # 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::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::transfer;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # sm.add_cell(&[n[0].id(), n[1].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!["h_T".into()], &[2.0]).unwrap());
/// # use pyrucast::models::ElementLayout;
/// // One `h_<primal>` coefficient per transferred pair, in the order
/// // `material_components` declares — here only one, hence the identity.
/// let lay = ElementLayout {
///     material: vec![0], optional_material: vec![], state: vec![],
/// };
/// // h ∫ N_i N_j dΓ: the measure comes from the **row** side, which is what
/// // makes an interface's four blocks integrate identically.
/// 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| {
///         transfer::exchange_matrix(&geoms[0], &geoms[0], m, &lay.material, 1.0, ke)
///     },
/// )?;
/// // The entries sum to h × the segment's length.
/// let total: f64 = bloc.iter_entries()?.into_iter().map(|(_, _, _, _, v)| v).sum();
/// assert!((total - 2.0).abs() < 1e-12);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn exchange_matrix(
    row_geom: &CellGeom,
    col_geom: &CellGeom,
    material: &SubElementField,
    coefficients: &[u32],
    sign: f64,
    ke: &mut [f64],
) -> Result<()> {
    // One coefficient `h_<primal>` per transferred pair, resolved once for the
    // zone. Taken as a slice rather than read off the whole material layout: a
    // boundary transfer also declares its ambient there, and the exchange is
    // not the only term that reads material.
    let n_vars = coefficients.len();
    let row_stride = col_geom.n_nodes * n_vars;
    for g in 0..row_geom.n_gauss {
        let row_shape = row_geom.n_at_g(g);
        let col_shape = col_geom.n_at_g(g);
        let w = row_geom.det_j_w(g);
        let row = material.row(row_geom.cell, g);
        for (v, &comp) in coefficients.iter().enumerate() {
            let hw = sign * row[comp as usize] * w;
            if hw == 0.0 {
                continue;
            }
            for i in 0..row_geom.n_nodes {
                let row = (i * n_vars + v) * row_stride;
                let hw_ni = hw * row_shape[i];
                for j in 0..col_geom.n_nodes {
                    ke[row + j * n_vars + v] += hw_ni * col_shape[j];
                }
            }
        }
    }
    Ok(())
}

/// `f_i = ∫ N_i · flux dΓ` — the internal nodal fluxes of an exchange law,
/// weighted by `N` and not by `Bᵀ`.
///
/// A film integrand is a flux **density**, not a gradient-conjugate quantity, so
/// the continuum default would be wrong here. For a linear law this equals
/// `(K·u)_i`, which is the invariant the internal forces must satisfy.
///
/// It **cannot fail**: the zone settled the shape of every read before the
/// parallel region, so this slices rows and adds. The `Result` is the trait's,
/// not its own — [`crate::models::SubModelKind::internal_force_element`] returns
/// one because other implementers need it.
///
/// ```
/// # 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::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::transfer;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # sm.add_cell(&[n[0].id(), n[1].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!["h_T".into()], &[2.0]).unwrap());
/// # let flux = SubElementField::from_uniform_per_component(
/// #     zone.clone(), vec!["flux_T".into()], &[1.0])?;
/// # let fe = std::sync::Mutex::new(vec![0.0; 2]);
/// // ∫ Nᵀ · flux dΓ — a transfer law's residual, on the nodal side. The
/// // components read are resolved **once**, before the loop.
/// let lay = flux.resolve_components(&["flux_T"], "flux")?;
/// // A unit density on a segment of length 1 splits in two.
/// pyrucast::models::kernel::reduce_cells(&zone, |geom| {
///     transfer::internal_force(geom, &flux, &lay, &mut fe.lock().unwrap())?;
///     Ok(0.0)
/// })?;
/// assert!((fe.lock().unwrap().iter().sum::<f64>() - 1.0).abs() < 1e-12);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn internal_force(
    geom: &CellGeom,
    stress: &SubElementField,
    lay: &[u32],
    fe: &mut [f64],
) -> Result<()> {
    let n_vars = lay.len();
    let stride = stress.component_count();
    let values = stress.values();
    for g in 0..geom.n_gauss {
        let shape = geom.n_at_g(g);
        let w = geom.det_j_w(g);
        let start = (geom.cell * geom.n_gauss + g) * stride;
        for (v, &comp) in lay.iter().enumerate() {
            let flux_w = values[start + comp as usize] * w;
            for i in 0..geom.n_nodes {
                fe[i * n_vars + v] += shape[i] * flux_w;
            }
        }
    }
    Ok(())
}