pyrucast 0.11.0

Finite-element library in Rust, inspired by cast3m, exposed to Python
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! Operators on the **coordinates** themselves: the only three that write
//! into them, and the one that computes in another configuration.
//!
//! The writers are the write side of
//! [`node_field::positions`](fn@crate::ops::node_field::positions), which
//! reads the geometry as a nodal field: [`set`](fn@set) puts absolute
//! positions back, [`displace`](fn@displace) adds an increment, and
//! [`displace_from`](fn@displace_from) lays one configuration at another
//! plus a displacement. All act on the [`Coords`] the
//! field hangs from, in place. [`in_config`](fn@in_config) runs a computation
//! with another configuration active, and makes the one before it active
//! again.

use crate::atoms::NodeId;
use crate::containers::field::Field;
use crate::containers::node_field::NodeField;
use crate::coords::Coords;
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;

/// Resolve the per-axis component names: one name per spatial axis, in axis
/// order. `None` falls back to `default[..dim]`. Errors if the count does
/// not match `dim` or if a name is absent from `field` (union of zones).
fn resolve_axis_components(
    field: &NodeField,
    components: Option<Vec<String>>,
    dim: usize,
    default: &[&str],
) -> Result<Vec<String>> {
    let comps = match components {
        Some(c) => c,
        None => default[..dim.min(default.len())]
            .iter()
            .map(|s| s.to_string())
            .collect(),
    };
    if comps.len() != dim {
        return Err(PyrucastError::Message(format!(
            "expected {dim} component name(s) (one per axis), got {}",
            comps.len()
        )));
    }
    let have = Field::components(field);
    for name in &comps {
        if !have.iter().any(|c| c == name) {
            return Err(PyrucastError::Message(format!(
                "component '{name}' not in field (has: [{}])",
                have.join(", ")
            )));
        }
    }
    Ok(comps)
}

/// Per distinct node of `field`, the value of each of `comps` — read
/// through the aggregate (first zone wins), so interface nodes appear
/// exactly once. Errors if a node lacks one of the components.
fn per_node_values(field: &NodeField, comps: &[String]) -> Result<Vec<(NodeId, Vec<f64>)>> {
    let nodes = field.node_ids();
    let mut out = Vec::with_capacity(nodes.len());
    for nid in nodes {
        let mut values = Vec::with_capacity(comps.len());
        for name in comps {
            values.push(field.value(nid, name)?);
        }
        out.push((nid, values));
    }
    Ok(out)
}

/// **Set** node coordinates from `field` (absolute): for every distinct
/// node `n` of the field, `coord[a] = field.value(n, components[a])` on
/// the active coordinate set. `components` lists one field-component name
/// per spatial axis, in axis order; `None` → `["X", "Y", "Z"][..dim]`
/// (symmetric with [`crate::ops::node_field::positions`](fn@crate::ops::node_field::positions)). In-place on the field's
/// `Coords`.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{Band, ElementType, Node};
/// # use pyrucast::containers::element_field::ElementField;
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::node_field::NodeField;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::ops::{coords as ops_coords, element_field, field, measure, mesh, node_field};
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [2.0, 0.0], [0.0, 2.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 support = mesh::poi1_from_nodes(&n).unwrap();
/// # let champ = |noms: Vec<String>| {
/// #     NodeField::from_submesh(&support.get(0).unwrap(), noms).unwrap()
/// # };
/// # let temp = champ(vec!["T".into()]);
/// # {
/// #     let mut z = temp.get(0).unwrap().write();
/// #     z.set_value(n[0].id(), "T", 10.0).unwrap();
/// #     z.set_value(n[1].id(), "T", 50.0).unwrap();
/// #     z.set_value(n[2].id(), "T", 90.0).unwrap();
/// # }
/// // Writes the positions **into the frame**: the inverse of
/// // `node_field::positions`. It is an assumed side effect.
/// // The default components are `X`, `Y`, `Z` — those that
/// // `positions` produit.
/// let cible = node_field::positions(&maillage, None)?;
/// cible.get(0)?.write().add_to_component("X", 1.0)?;
/// ops_coords::set(&cible, None)?;
/// assert_eq!(n[0].position()?, vec![1.0, 0.0]);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn set(field: &NodeField, components: Option<Vec<String>>) -> Result<()> {
    let coords = field.coords()?;
    let dim = coords.read().dim() as usize;
    let comps = resolve_axis_components(field, components, dim, &["X", "Y", "Z"])?;
    let targets = per_node_values(field, &comps)?;
    let mut c = coords.write();
    for (nid, coord) in &targets {
        c.set_position(*nid, coord)?;
    }
    Ok(())
}

/// **Displace** nodes by `field` (incremental): for every distinct node
/// `n`, `coord[a] += field.value(n, components[a])` on the active
/// coordinate set — an interface node shared by several zones is displaced
/// exactly once. `components` lists one displacement-component name per
/// spatial axis, in axis order; `None` → `["ux", "uy", "uz"][..dim]`.
/// In-place on the field's `Coords`.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{Band, ElementType, Node};
/// # use pyrucast::containers::element_field::ElementField;
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::node_field::NodeField;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::ops::{coords as ops_coords, element_field, field, measure, mesh, node_field};
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [2.0, 0.0], [0.0, 2.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 support = mesh::poi1_from_nodes(&n).unwrap();
/// # let champ = |noms: Vec<String>| {
/// #     NodeField::from_submesh(&support.get(0).unwrap(), noms).unwrap()
/// # };
/// # let temp = champ(vec!["T".into()]);
/// # {
/// #     let mut z = temp.get(0).unwrap().write();
/// #     z.set_value(n[0].id(), "T", 10.0).unwrap();
/// #     z.set_value(n[1].id(), "T", 50.0).unwrap();
/// #     z.set_value(n[2].id(), "T", 90.0).unwrap();
/// # }
/// // Adds a displacement to the positions instead of replacing them — the
/// // façon de passer en configuration déformée.
/// // The default components here are `ux`, `uy`, `uz`.
/// let u = champ(vec!["ux".into(), "uy".into()]);
/// u.get(0)?.write().add_to_component("ux", 0.5)?;
/// ops_coords::displace(&u, None)?;
/// assert_eq!(n[0].position()?, vec![0.5, 0.0]);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn displace(field: &NodeField, components: Option<Vec<String>>) -> Result<()> {
    let coords = field.coords()?;
    let dim = coords.read().dim() as usize;
    let comps = resolve_axis_components(field, components, dim, &["ux", "uy", "uz"])?;
    let increments = per_node_values(field, &comps)?;
    let mut c = coords.write();
    for (nid, inc) in &increments {
        let mut coord = c.position(*nid)?.to_vec();
        for (a, dv) in inc.iter().enumerate() {
            coord[a] += dv;
        }
        c.set_position(*nid, &coord)?;
    }
    Ok(())
}

/// Lay configuration `target` at configuration `reference` displaced by
/// `field` — `x = X + u`, in **absolute**: each node takes its `reference`
/// position plus its value in `field`, a node the field does not define stays
/// where the reference puts it. Called again with another `u`, it lands at
/// `X + u` again: nothing accumulates, which a restarted substep or an
/// accelerated iterate needs. The active configuration is left as it is.
/// `components` names one displacement component per axis; `None` →
/// `["ux", "uy", "uz"][..dim]`, as for [`displace`](fn@displace).
///
/// Errors: as [`Coords::displace_from`](crate::coords::Coords::displace_from),
/// and a component the field lacks.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::node_field::NodeField;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::ops::coords as ops_coords;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [2.0, 0.0], [0.0, 2.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 mesh = Mesh::from_submesh(sm);
/// let current = coords.write().add_config("current");
/// let u = NodeField::new(&mesh, vec!["u_x".into(), "u_y".into()])?;
/// u.get(0)?.write().set_value(n[1].id(), "u_x", 0.5)?;
/// let names = Some(vec!["u_x".to_string(), "u_y".to_string()]);
/// ops_coords::displace_from(&u, 0, current, names)?;
/// // The reference has not moved; the current configuration has.
/// assert_eq!(n[1].position()?, vec![2.0, 0.0]);
/// coords.write().select(current)?;
/// assert_eq!(n[1].position()?, vec![2.5, 0.0]);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn displace_from(
    field: &NodeField,
    reference: usize,
    target: usize,
    components: Option<Vec<String>>,
) -> Result<()> {
    let coords = field.coords()?;
    let dim = coords.read().dim() as usize;
    let comps = resolve_axis_components(field, components, dim, &["ux", "uy", "uz"])?;
    let increments = per_node_values(field, &comps)?;
    coords.write().displace_from(
        reference,
        target,
        increments.iter().map(|(nid, inc)| (*nid, inc.as_slice())),
    )
}

/// Run `f` with configuration `config` of `coords` active, then make the
/// configuration that was active before it active again — after an error, and
/// after a panic, too. Everything `f` computes on the geometry (matrices,
/// normals, measures) sees `config`; what it returns is handed back.
///
/// The lock on `coords` is taken on entry and on exit only: `f` reads and
/// writes the coordinates freely, and may call `in_config` again. The active
/// configuration belongs to the `Coords`, not to the caller: another thread
/// computing on the same `Coords` meanwhile sees `config` too.
///
/// Errors: `config` out of range, before `f` runs; whatever `f` returns.
///
/// ```
/// # use pyrucast::atoms::Node;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::ops::coords as ops_coords;
/// let coords = Handle::new(Coords::new(2)?);
/// let n = Node::create_in(coords.clone(), &[1.0, 0.0])?;
/// let current = coords.write().add_config("current");
///
/// // Written in `current`, read in `current`; the reference is back after each.
/// ops_coords::in_config(&coords, current, || n.set_position(&[2.0, 0.0]))?;
/// let x = ops_coords::in_config(&coords, current, || n.position())?;
/// assert_eq!(x, vec![2.0, 0.0]);
/// assert_eq!(coords.read().active(), 0);
/// assert_eq!(n.position()?, vec![1.0, 0.0]);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn in_config<R>(
    coords: &Handle<Coords>,
    config: usize,
    f: impl FnOnce() -> Result<R>,
) -> Result<R> {
    let previous = {
        let mut c = coords.write();
        let previous = c.active();
        c.select(config)?;
        previous
    };
    // Caught only to restore, then resumed: nothing observes `f`'s state after
    // a panic, so asserting it unwind-safe is sound.
    let out = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
    // `previous` was valid on entry, and configurations are never removed.
    coords.write().select(previous)?;
    match out {
        Ok(result) => result,
        Err(panic) => std::panic::resume_unwind(panic),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::aggregate::Aggregate;
    use crate::atoms::{ElementType, Node};
    use crate::containers::mesh::{Mesh, SubMesh};
    use crate::containers::node_field::SubNodeField;
    use crate::coords::Coords;
    use crate::handle::Handle;
    use crate::ops::node_field::positions;

    #[test]
    fn set_writes_active_config() {
        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.clone(), &[1.0, 1.0]).unwrap();
        let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::POI1));
        mesh.add_cell(&[a.id()]).unwrap();
        mesh.add_cell(&[b.id()]).unwrap();

        // Field of target positions (X/Y), round-tripped from the reader.
        let f = positions(&mesh, None).unwrap();
        {
            let mut s = f.get(0).unwrap().write();
            s.set_value(a.id(), "X", 10.0).unwrap();
            s.set_value(a.id(), "Y", 20.0).unwrap();
        }

        set(&f, None).unwrap();
        {
            let c = coords.read();
            assert_eq!(c.position(a.id()).unwrap(), &[10.0, 20.0]);
            assert_eq!(c.position(b.id()).unwrap(), &[1.0, 1.0]);
        }
    }

    #[test]
    fn displace_adds_to_active_config() {
        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.clone(), &[1.0, 1.0]).unwrap();
        let support = Handle::new(SubMesh::poi1_from_nodes(&[a.clone(), b.clone()]).unwrap());
        let mut d = SubNodeField::from_poi1(&support, vec!["ux".into(), "uy".into()]).unwrap();
        d.set_value(a.id(), "ux", 5.0).unwrap();
        d.set_value(a.id(), "uy", -1.0).unwrap();
        d.set_value(b.id(), "ux", 2.0).unwrap();

        displace(&NodeField::from_sub(d), None).unwrap();
        {
            let c = coords.read();
            assert_eq!(c.position(a.id()).unwrap(), &[5.0, -1.0]);
            assert_eq!(c.position(b.id()).unwrap(), &[3.0, 1.0]);
        }
    }

    #[test]
    fn displace_moves_interface_nodes_once() {
        // Two zones sharing node `s`: the increment must apply once, not twice.
        let coords = Handle::new(Coords::new(1).unwrap());
        let s = Node::create_in(coords.clone(), &[1.0]).unwrap();
        let mut mesh = Mesh::empty();
        for _ in 0..2 {
            let mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
            sm.add_cell(&[s.id()]).unwrap();
            mesh.add_sub(Handle::new(sm)).unwrap();
        }
        let f = NodeField::new(&mesh, vec!["ux".into()]).unwrap();
        for i in 0..2 {
            f.get(i)
                .unwrap()
                .write()
                .set_value(s.id(), "ux", 0.5)
                .unwrap();
        }

        displace(&f, None).unwrap();
        assert_eq!(coords.read().position(s.id()).unwrap(), &[1.5]);
    }

    #[test]
    fn in_config_restores_the_previous_configuration() {
        let coords = Handle::new(Coords::new(1).unwrap());
        let a = coords.write().add_config("a");
        let b = coords.write().add_config("b");
        coords.write().select(a).unwrap();

        // After a value, nested: each level gives back the one it found.
        let seen = in_config(&coords, b, || {
            let inner = in_config(&coords, 0, || Ok(coords.read().active()))?;
            Ok((coords.read().active(), inner))
        })
        .unwrap();
        assert_eq!(seen, (b, 0));
        assert_eq!(coords.read().active(), a);

        // After an error, which is handed back.
        let err = in_config(&coords, b, || -> Result<()> {
            Err(PyrucastError::Message("inside".into()))
        });
        assert!(err.is_err());
        assert_eq!(coords.read().active(), a);

        // After a panic, which goes on unwinding.
        let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _ = in_config(&coords, b, || -> Result<()> { panic!("inside") });
        }));
        assert!(panicked.is_err());
        assert_eq!(coords.read().active(), a);

        // An index out of range: nothing runs, nothing changes.
        let mut ran = false;
        assert!(in_config(&coords, 3, || {
            ran = true;
            Ok(())
        })
        .is_err());
        assert!(!ran);
        assert_eq!(coords.read().active(), a);
    }

    #[test]
    fn writers_reject_wrong_component_count() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::POI1));
        mesh.add_cell(&[a.id()]).unwrap();
        let f = positions(&mesh, None).unwrap();
        // 2-D Coords needs 2 axis components, not 1.
        assert!(set(&f, Some(vec!["X".into()])).is_err());
        // Unknown component name.
        assert!(set(&f, Some(vec!["X".into(), "BOGUS".into()])).is_err());
    }
}