pyrucast 0.13.1

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
//! Python wrappers for [`crate::ops::node_field`] — the operators that
//! produce a `NodeField`.

use crate::aggregate::Aggregate;
use crate::handle::Handle;
use crate::py::element_field::{PyElementField, PySubElementField};
use crate::py::mesh::PyMesh;
use crate::py::model::PyModel;
use crate::py::node_field::PyNodeField;
use crate::py::node_field::PySubNodeField;
use pyo3::exceptions::PyTypeError;
use pyo3::prelude::*;
use pyrucast_macros::py_op;

/// Build a `NodeField` carrying the position of every node of `mesh`
/// — one `SubNodeField` per submesh, on the distinct nodes of its zone.
///
/// One component per requested axis (`"X"`, `"Y"`, `"Z"`). `components=None`
/// requests all the axes the mesh's `Coords` has (`["X"]` in 1-D,
/// `["X", "Y"]` in 2-D, `["X", "Y", "Z"]` in 3-D).
#[py_op(method_on = PyMesh)]
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (mesh, components=None))]
pub fn positions(mesh: PyRef<PyMesh>, components: Option<Vec<String>>) -> PyResult<PyNodeField> {
    Ok(PyNodeField {
        inner: crate::ops::node_field::positions(&mesh.inner, components)?,
    })
}

/// Restrict `field` to the nodes used by `mesh`.
///
/// Returns a new `NodeField` with one zone per submesh of `mesh`, each
/// supported on the submesh's canonical POI1 node cloud (its distinct nodes,
/// materialised once and cached). Two restrictions onto the **same** `mesh`
/// share that support, so they combine directly: `restrict(a, mesh) -
/// restrict(b, mesh)` is the node-by-node difference. That support is also the
/// one a stiffness block over `mesh` uses, so `K * restrict(f, mesh)` and
/// `solve(K, f) - restrict(g, mesh)` line up too.
///
/// Each zone carries the union of `field`'s components; nodes of `mesh` absent
/// from `field` are assigned `0.0`. Element operations on the region
/// (`gradient`, `integral`, `deformation`, `interp_to_gauss`) take `mesh` as a
/// separate argument and read the field by node id. Use `restrict_like` to
/// land on the exact support of an existing field instead of a mesh.
///
/// Errors if `mesh` and `field` are attached to different `Coords`s.
#[py_op(method_on = PyNodeField)]
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn restrict(field: PyRef<PyNodeField>, mesh: PyRef<PyMesh>) -> PyResult<PyNodeField> {
    Ok(PyNodeField {
        inner: crate::ops::node_field::restrict(&field.inner, &mesh.inner)?,
    })
}

/// `field` read at the nodes of `target`, through the cells of `mesh` — Cast3M
/// `PROI` onto a geometry. `field` is a nodal field or a field at the Gauss
/// points:
///
/// - **nodal** (`NodeField`, `SubNodeField`): a node of `target` inside a cell
///   of `mesh` takes `Σ Nᵢ(ξ) f(nodeᵢ)`, the shape functions of that cell at
///   the node (quadratic cells interpolate quadratically). `field` is read
///   first zone first, a node of `mesh` it does not define reading zero.
///   `mesh` and `field` must share their `Coords`.
/// - **at the Gauss points** (`ElementField`, `SubElementField`): the node
///   takes the value that cell's **own** Gauss points give there — their
///   least-squares fit on the cell, the one a plot colours the cell with.
///   Nothing is averaged between cells: a line of points crossing from one
///   cell to its neighbour shows the jump between them. A point on a face
///   shared by two cells is read in one of them; to follow a field along a
///   line, put the points between the nodes. `mesh` is the field's own cells:
///   each of its submeshes must carry a zone of the field.
///
/// Every component is carried. A node of `target` outside `mesh` — farther
/// than `tol` outside every cell's reference element — gets zero. `mesh` and
/// `target` may live in different `Coords`, each read in its active
/// configuration. One zone per submesh of `target`, like `positions`.
///
/// An empty `field` or `target` gives an empty field; an empty `mesh` gives
/// zero at every node of `target`. Errors: `mesh` and `target` in different
/// dimensions; for a nodal field, `field` and `mesh` on different `Coords`;
/// for a field at the Gauss points, a submesh of `mesh` it has no zone on.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (field, mesh, target, tol=1e-6))]
pub fn project(
    field: &Bound<'_, PyAny>,
    mesh: PyRef<PyMesh>,
    target: PyRef<PyMesh>,
    tol: f64,
) -> PyResult<PyNodeField> {
    if let Ok(f) = field.extract::<PyRef<PyNodeField>>() {
        project_node(f, mesh, target, tol)
    } else if let Ok(f) = field.extract::<PyRef<PyElementField>>() {
        project_element(f, mesh, target, tol)
    } else if let Ok(f) = field.extract::<PyRef<PySubNodeField>>() {
        project_sub_node(f, mesh, target, tol)
    } else if let Ok(f) = field.extract::<PyRef<PySubElementField>>() {
        project_sub_element(f, mesh, target, tol)
    } else {
        Err(PyTypeError::new_err(
            "project: expected a NodeField, SubNodeField, ElementField or SubElementField",
        ))
    }
}

// The four flavours of `project`, each documented for its sole receiver. Not
// registered in the module — the free function above remains the polymorphic
// entry point — they give `#[py_op]` the method of each flavour.
// `#[pyfunction]` serves only to make valid the pyo3 signature that `#[py_op]`
// copies.

/// This nodal field interpolated by the cells of `mesh` at the nodes of
/// `target`: a node of `target` inside a cell of `mesh` takes `Σ Nᵢ(ξ)
/// f(nodeᵢ)`, the shape functions of that cell at the node (quadratic cells
/// interpolate quadratically); every component is carried. A node of `target`
/// outside `mesh` — farther than `tol` outside every cell's reference element
/// — gets zero. Read first zone first, a node of `mesh` the field does not
/// define reading zero. `mesh` and `target` may live in different `Coords`.
/// One zone per submesh of `target`. Errors: the field and `mesh` on
/// different `Coords`; `mesh` and `target` in different dimensions.
#[py_op(method_on = PyNodeField, name = "project")]
#[pyfunction]
#[pyo3(signature = (field, mesh, target, tol=1e-6))]
pub fn project_node(
    field: PyRef<PyNodeField>,
    mesh: PyRef<PyMesh>,
    target: PyRef<PyMesh>,
    tol: f64,
) -> PyResult<PyNodeField> {
    Ok(PyNodeField {
        inner: crate::ops::node_field::project_node(&field.inner, &mesh.inner, &target.inner, tol)?,
    })
}

/// This zone interpolated by the cells of `mesh` at the nodes of `target` —
/// as `NodeField.project`, for a field of this one zone.
#[py_op(method_on = PySubNodeField, name = "project")]
#[pyfunction]
#[pyo3(signature = (field, mesh, target, tol=1e-6))]
pub fn project_sub_node(
    field: PyRef<PySubNodeField>,
    mesh: PyRef<PyMesh>,
    target: PyRef<PyMesh>,
    tol: f64,
) -> PyResult<PyNodeField> {
    let mut whole = crate::containers::node_field::NodeField::default();
    whole.add_sub(field.handle.clone())?;
    Ok(PyNodeField {
        inner: crate::ops::node_field::project_node(&whole, &mesh.inner, &target.inner, tol)?,
    })
}

/// This field at the Gauss points read at the nodes of `target`: a node of
/// `target` inside a cell of `mesh` takes the value that cell's own Gauss
/// points give there — their least-squares fit on the cell, the one a plot
/// colours the cell with. Nothing is averaged between cells, so a line of
/// points crossing from one cell to its neighbour shows the jump between
/// them; a point on a shared face is read in one of the two. `mesh` is the
/// field's own cells (each submesh must carry a zone of it). A node outside
/// `mesh` gets zero. One zone per submesh of `target`. Errors: a submesh of
/// `mesh` without a zone of the field; `mesh` and `target` in different
/// dimensions.
#[py_op(method_on = PyElementField, name = "project")]
#[pyfunction]
#[pyo3(signature = (field, mesh, target, tol=1e-6))]
pub fn project_element(
    field: PyRef<PyElementField>,
    mesh: PyRef<PyMesh>,
    target: PyRef<PyMesh>,
    tol: f64,
) -> PyResult<PyNodeField> {
    Ok(PyNodeField {
        inner: crate::ops::node_field::project_element(
            &field.inner,
            &mesh.inner,
            &target.inner,
            tol,
        )?,
    })
}

/// This zone at the Gauss points read at the nodes of `target` — as
/// `ElementField.project`, for a field of this one zone.
#[py_op(method_on = PySubElementField, name = "project")]
#[pyfunction]
#[pyo3(signature = (field, mesh, target, tol=1e-6))]
pub fn project_sub_element(
    field: PyRef<PySubElementField>,
    mesh: PyRef<PyMesh>,
    target: PyRef<PyMesh>,
    tol: f64,
) -> PyResult<PyNodeField> {
    let mut whole = crate::containers::element_field::ElementField::empty();
    whole.add_sub(field.handle.clone())?;
    Ok(PyNodeField {
        inner: crate::ops::node_field::project_element(&whole, &mesh.inner, &target.inner, tol)?,
    })
}

/// Reproject `field` onto the exact support and components of `target`,
/// zone by zone.
///
/// Unlike `restrict` (which lands on a fresh support materialised from a
/// mesh, carrying the union of `field`'s components), this reuses each zone
/// of `target` as-is — same support, same component list — so the result is
/// on the very same support as `target` and combines with it directly by the
/// arithmetic operators (`target + restrict_like(field, target)`). A
/// `(node, component)` pair is filled from `field` when it covers it, `0.0`
/// otherwise; nodes and components of `field` absent from `target` are dropped.
/// Errors if `target` and `field` are attached to different `Coords`s.
#[py_op(method_on = PyNodeField)]
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn restrict_like(
    field: PyRef<PyNodeField>,
    target: PyRef<PyNodeField>,
) -> PyResult<PyNodeField> {
    Ok(PyNodeField {
        inner: crate::ops::node_field::restrict_like(&field.inner, &target.inner)?,
    })
}

/// The union `a | b`: the zones of both fields, those on the same support
/// fused into one carrying the union of their components, those on distinct
/// supports side by side (nothing is densified).
///
/// Errors if the two fields hold different values at the same
/// `(node, component)` pair, or are attached to different `Coords`s.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn merge(a: PyRef<PyNodeField>, b: PyRef<PyNodeField>) -> PyResult<PyNodeField> {
    Ok(PyNodeField {
        inner: crate::ops::node_field::merge(&a.inner, &b.inner)?,
    })
}

/// Fuse the zones of a node `field` sharing the same support into one,
/// carrying the union of their components; zones on distinct supports stay
/// side by side.
///
/// Errors if two zones disagree on a value at a shared `(node, component)`
/// pair. `field` itself is left untouched.
#[py_op(method_on = PyNodeField)]
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(name = "consolidate_node")]
pub fn consolidate(field: PyRef<PyNodeField>) -> PyResult<PyNodeField> {
    Ok(PyNodeField {
        inner: crate::ops::node_field::consolidate(&field.inner)?,
    })
}

/// Weak divergence of a per-element quantity named `prefix` — the adjoint of
/// `gradient`: `d_i = ∫ ∇N_i · A dΩ`, accumulated per node.
///
/// The **rank is read off the names**, so one operator serves both: `A_x, A_y`
/// is a vector and yields a single `div_A` component; `A_xx, A_xy, A_yy` is a
/// symmetric tensor and yields one component per axis, `div_A_x, div_A_y`. The
/// tensor case is the internal forces of a continuum when the quantity is a
/// Cauchy stress — `divergence(stress, "sigma")` is Cast3m `BSIG` — but the
/// operator knows nothing of mechanics: it needs only the geometry and the
/// names. A node shared by several subspaces receives the sum of their
/// contributions.
#[py_op(method_on = PyElementField)]
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn divergence(field: PyRef<PyElementField>, prefix: &str) -> PyResult<PyNodeField> {
    let nf = crate::ops::node_field::divergence(&field.inner, prefix)?;
    Ok(PyNodeField { inner: nf })
}

/// A field carrying **one point per cell** gathered at the nodes by
/// **summation** (Cast3M `CHAN 'CHPO' 'SOMM'`): each node receives, per
/// component, the sum of the values of the cells it belongs to — across zones
/// too. Not a smoothing: no average, no weight. Applied to the cell measures of
/// `cell_integral`, it gives the volume each node stands for. Raises on a zone
/// with more than one point per cell (build it on a `REDUCED` space).
#[py_op(method_on = PyElementField)]
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn sum_to_nodes(field: PyRef<PyElementField>) -> PyResult<PyNodeField> {
    let nf = crate::ops::node_field::sum_to_nodes(&field.inner)?;
    Ok(PyNodeField { inner: nf })
}

/// Internal nodal forces of `model` — the left side of `Σ f_int = Σ f_ext`
/// (Cast3m `BSIG` for a continuum).
///
/// The nodal mirror of `matrix.stiffness(model, materials)`: every sub-model is
/// asked for its term of the residual on the internal side. `state` is the
/// material-state field produced by `integrate_behavior` (`COMP`); a
/// behaviour-bearing sub-model applies its own `Bᵀ` (continuum solid, bar or
/// beam), a sub-model with no term here declares none. Returns a `NodeField`
/// whose components are each sub-model's dual variables (`f_x`, … for a
/// solid/bar; `f_w`, `m_theta` for a beam).
///
/// For a linear law the result equals the assembled stiffness applied to the
/// solution (`K·u`); a non-linear law gives the exact internal forces. Its
/// counterpart is `external_forces(model, materials)`, and the gap between the
/// two sums is the residual.
///
/// `solution` is the current one, multipliers included: a term that is linear in
/// `u` reads it directly — a boundary transfer's `∫ h·a·N` has no law to go
/// through — and a constraint draws its force `Cᵀ λ` from it, spread over the
/// constrained nodes by the relation's coefficients. That force is the
/// opposite of the **reaction**: the reaction of a model's constraints is
/// `−internal_forces(model.filter("constraint"), …)`, whichever way `solve`
/// treated the relations.
#[py_op(method_on = PyModel)]
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn internal_forces(
    model: PyRef<PyModel>,
    state: PyRef<PyElementField>,
    solution: PyRef<PyNodeField>,
    materials: PyRef<PyElementField>,
) -> PyResult<PyNodeField> {
    let nf = crate::ops::node_field::internal_forces(
        &model.inner,
        &state.inner,
        &solution.inner,
        &materials.inner,
    )?;
    Ok(PyNodeField { inner: nf })
}

/// External nodal forces of `model` — the right side of `Σ f_int = Σ f_ext`.
///
/// The counterpart of `internal_forces(model, state, solution, materials)`.
/// Every sub-model is asked for its terms of the residual on the external side:
/// the given data of its weak form, on the right of the equals sign. A physics
/// whose term is entirely a response to `u` (elasticity, conduction, a bar) has
/// none, so a model made only of those yields an empty field — which is the
/// honest answer, not a failure.
///
/// Splitting the two sides is what keeps signs out of the physics: an author
/// writes both halves positively, as the weak form reads, and the single
/// subtraction lives in the caller.
#[py_op(method_on = PyModel)]
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn external_forces(
    model: PyRef<PyModel>,
    materials: PyRef<PyElementField>,
) -> PyResult<PyNodeField> {
    let nf = crate::ops::node_field::external_forces(&model.inner, &materials.inner)?;
    Ok(PyNodeField { inner: nf })
}

/// Per-component 0/1 **mask** of a field against a value band — same structure
/// as the input (Cast3M `MASQUE`): same zones, same support, same components,
/// only the values are rewritten (`1.0` inside the band, `0.0` outside). The
/// result is therefore multipliable term by term with the input.
///
/// `field` is a `NodeField` or a `SubNodeField`, and the result is of the same
/// kind. Its sibling `pyrucast.mesh.select` extracts the passing *support*
/// instead, and produces a `Mesh`.
///
/// The band is set by the four comparison bounds `ge` (`≥`), `gt` (`>`),
/// `le` (`≤`), `lt` (`<`). There is **no** AND across components: each value
/// stands on its own. `components=None` tests every component; a `components`
/// list tests only those, leaving the others at `1.0` (identity for the
/// product), and a zone missing a listed component is left all-`1.0`.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(name = "mask_node")]
#[pyo3(signature = (field, ge=None, gt=None, le=None, lt=None, components=None))]
#[allow(clippy::too_many_arguments)]
pub fn mask(
    py: Python<'_>,
    field: &Bound<'_, PyAny>,
    ge: Option<f64>,
    gt: Option<f64>,
    le: Option<f64>,
    lt: Option<f64>,
    components: Option<Vec<String>>,
) -> PyResult<Py<PyAny>> {
    if let Ok(f) = field.extract::<PyRef<PyNodeField>>() {
        Ok(Py::new(py, mask_node_field(f, ge, gt, le, lt, components)?)?.into_any())
    } else if let Ok(f) = field.extract::<PyRef<PySubNodeField>>() {
        Ok(Py::new(py, mask_sub_node_field(f, ge, gt, le, lt, components)?)?.into_any())
    } else {
        Err(PyTypeError::new_err(
            "expected a PyNodeField or PySubNodeField",
        ))
    }
}

// The two flavours of `mask`, each at its precise type. They are not registered
// in the module — the free function remains the only polymorphic entry point —
// but `#[py_op]` derives the receiver's method from them, carrying **their**
// documentation: that of one flavour, which need not mention the other.
// `#[pyfunction]` is there only to make `#[pyo3(signature = …)]` valid, which
// `#[py_op]` copies onto the method.

/// Per-component 0/1 **mask** of this field against a value band — same
/// structure as the field (Cast3M `MASQUE`): same zones, same support, same
/// components, only the values are rewritten (`1.0` inside the band, `0.0`
/// outside). The result is therefore multipliable term by term with the field.
///
/// Its sibling `select` extracts the passing *nodes* instead, and produces a
/// `Mesh`.
///
/// The band is set by the four comparison bounds `ge` (`≥`), `gt` (`>`),
/// `le` (`≤`), `lt` (`<`). There is **no** AND across components: each value
/// stands on its own. `components=None` tests every component; a `components`
/// list tests only those, leaving the others at `1.0` (identity for the
/// product), and a zone missing a listed component is left all-`1.0`.
#[py_op(method_on = PyNodeField, name = "mask")]
#[pyfunction]
#[pyo3(signature = (field, ge=None, gt=None, le=None, lt=None, components=None))]
pub fn mask_node_field(
    field: PyRef<PyNodeField>,
    ge: Option<f64>,
    gt: Option<f64>,
    le: Option<f64>,
    lt: Option<f64>,
    components: Option<Vec<String>>,
) -> PyResult<PyNodeField> {
    let band = crate::atoms::Band::new(ge, gt, le, lt)?;
    Ok(PyNodeField {
        inner: crate::ops::node_field::mask(&field.inner, &band, components)?,
    })
}

/// Per-component 0/1 **mask** of this sub-field against a value band — same
/// structure as the sub-field (Cast3M `MASQUE`): same support, same
/// components, only the values are rewritten (`1.0` inside the band, `0.0`
/// outside). The result is therefore multipliable term by term with the
/// sub-field.
///
/// Its sibling `select` extracts the passing *nodes* instead, and produces a
/// `Mesh`.
///
/// The band is set by the four comparison bounds `ge` (`≥`), `gt` (`>`),
/// `le` (`≤`), `lt` (`<`). There is **no** AND across components: each value
/// stands on its own. `components=None` tests every component; a `components`
/// list tests only those, leaving the others at `1.0` (identity for the
/// product). A listed component the sub-field does not carry leaves it
/// all-`1.0`.
#[py_op(method_on = PySubNodeField, name = "mask")]
#[pyfunction]
#[pyo3(signature = (field, ge=None, gt=None, le=None, lt=None, components=None))]
pub fn mask_sub_node_field(
    field: PyRef<PySubNodeField>,
    ge: Option<f64>,
    gt: Option<f64>,
    le: Option<f64>,
    lt: Option<f64>,
    components: Option<Vec<String>>,
) -> PyResult<PySubNodeField> {
    let band = crate::atoms::Band::new(ge, gt, le, lt)?;
    let out = crate::ops::node_field::mask_sub(&field.handle.read(), &band, components);
    Ok(PySubNodeField {
        handle: Handle::new(out),
    })
}