pyrucast 0.1.3

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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
//! Python wrappers for the field operations in [`crate::ops::field`].
//!
//! Free functions that build or transform a [`PyNodeField`]. Kept here —
//! mirroring `src/ops/field/` — rather than on the field classes, per
//! the `py/ops/` convention (operations live with operations).
//!
//! Transitional note: the Rust ops still work on a single
//! `SubNodeField`; this wrapper bridges through `Aggregate::unit()`
//! (unitary aggregates only) until the ops are generalised to the
//! `NodeField` aggregate.

use crate::py::element_field::{PyElementField, PySubElementField};
use crate::py::finite_element_space::PyFiniteElementSpace;
use crate::py::mesh::PyMesh;
use crate::py::node_field::{PyNodeField, PySubNodeField};
use crate::store::{insert, read};
use pyo3::exceptions::PyTypeError;
use pyo3::prelude::*;

/// Build a `NodeField` carrying the coordinates 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).
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (mesh, components=None))]
pub fn coordinates(mesh: PyRef<PyMesh>, components: Option<Vec<String>>) -> PyResult<PyNodeField> {
    Ok(PyNodeField {
        inner: crate::ops::field::coordinates(&mesh.inner, components)?,
    })
}

/// Set node coordinates from `field` (absolute): for every node, the
/// active-set coordinate on axis `a` becomes `field.value(node,
/// components[a])`. `components` lists one component name per spatial axis,
/// in axis order; `None` → `["X", "Y", "Z"][:dim]`. Mutates the field's
/// `Coords` in place.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (field, components=None))]
pub fn set_coordinates(field: PyRef<PyNodeField>, components: Option<Vec<String>>) -> PyResult<()> {
    crate::ops::field::set_coordinates(&field.inner, components)?;
    Ok(())
}

/// Displace nodes by `field` (incremental): `coord[a] += field.value(node,
/// components[a])` on the active coordinate set. `components` lists one
/// displacement-component name per spatial axis, in axis order; `None` →
/// `["ux", "uy", "uz"][:dim]`. Mutates the field's `Coords` in place.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (field, components=None))]
pub fn displace(field: PyRef<PyNodeField>, components: Option<Vec<String>>) -> PyResult<()> {
    crate::ops::field::displace(&field.inner, components)?;
    Ok(())
}

/// 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.
#[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::field::restrict(&field.inner, &mesh.inner)?,
    })
}

/// 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.
#[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::field::restrict_like(&field.inner, &target.inner)?,
    })
}

/// Merge two node fields « au plus juste »: structural union of their
/// zones, consolidated — zones sharing a component set are fused, the
/// others stay separate (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::field::merge(&a.inner, &b.inner)?,
    })
}

/// Gradient `∇f` of a node `field` at the Gauss points of `fespace`.
///
/// Geometric and physics-agnostic: each component of `field` is
/// differentiated w.r.t. every spatial axis, giving an `ElementField` with
/// one component `grad_<name>_<axis>` per (input component, axis) pair
/// (`grad_T_x`, …). Feed the result to `integrate_behavior`.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn gradient(
    field: PyRef<PyNodeField>,
    fespace: PyRef<PyFiniteElementSpace>,
) -> PyResult<PyElementField> {
    let ef = crate::ops::field::gradient(&field.inner, &fespace.inner)?;
    Ok(PyElementField { inner: ef })
}

/// Linearized (small-strain) deformation `ε = ½(∇u + ∇uᵀ)` of a displacement
/// field `u` at the Gauss points of `fespace`.
///
/// `u` must carry exactly `space_dim` components, taken in order as the
/// displacement along x, y, z. Returns the symmetric strain tensor
/// (`eps_xx`, `eps_xy`, … in tensor convention). The only deformation
/// measure for now; non-linear ones will share this shape.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn deformation(
    u: PyRef<PyNodeField>,
    fespace: PyRef<PyFiniteElementSpace>,
) -> PyResult<PyElementField> {
    let ef = crate::ops::field::deformation(&u.inner, &fespace.inner)?;
    Ok(PyElementField { inner: ef })
}

/// Interpolate a nodal `field` to the Gauss points of `fespace`
/// (`f(ξ_g) = Σ_i f_i N_i(ξ_g)`), turning a per-node `NodeField` into a
/// per-element `ElementField` with the same component names. Cast3M `CHAN`
/// (nodes → Gauss).
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn interp_to_gauss(
    field: PyRef<PyNodeField>,
    fespace: PyRef<PyFiniteElementSpace>,
) -> PyResult<PyElementField> {
    let ef = crate::ops::field::interp_to_gauss(&field.inner, &fespace.inner)?;
    Ok(PyElementField { inner: ef })
}

/// Thermal (free-dilation) strain `ε_th = α·(T − t_ref)` at the Gauss points of
/// `fespace` — Cast3M `EPTH`. `temperature` is a per-element field carrying
/// `"T"` (e.g. from `interp_to_gauss`); `materials` carries `"alpha"` (supplied
/// via `material_field`). Returns the strain tensor in the same layout as
/// `deformation`, so `deformation(u, fespace) - thermal_strain(...)` is the
/// mechanical strain. Backbone of uncoupled thermomechanics: assemble the
/// thermal load with `internal_forces(model, integrate_behavior(model, ε_th,
/// materials))` and recover `σ = D:(ε − ε_th)`.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn thermal_strain(
    temperature: PyRef<PyElementField>,
    materials: PyRef<PyElementField>,
    fespace: PyRef<PyFiniteElementSpace>,
    t_ref: f64,
) -> PyResult<PyElementField> {
    let ef = crate::ops::field::thermal_strain(
        &temperature.inner,
        &materials.inner,
        &fespace.inner,
        t_ref,
    )?;
    Ok(PyElementField { inner: ef })
}

/// Timoshenko-beam section strains `(kappa, gamma)` of a `(w, theta)` node
/// field at the Gauss points of `fespace`. Feed the result to
/// `integrate_behavior` of a Timoshenko model to obtain the section forces
/// `M = E·I·κ` and `V = G·A_s·γ`.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn beam_deformation(
    field: PyRef<PyNodeField>,
    fespace: PyRef<PyFiniteElementSpace>,
) -> PyResult<PyElementField> {
    let ef = crate::ops::field::beam_deformation(&field.inner, &fespace.inner)?;
    Ok(PyElementField { inner: ef })
}

/// Weak divergence `div F` of a per-element **vector** field — the adjoint of
/// `gradient`: `d_i = ∫ ∇N_i · F dΩ`, accumulated per node. The field must
/// carry exactly `space_dim` components (the vector components in order).
/// Returns a `NodeField` with a single `"div"` component (one zone per subspace).
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn divergence(field: PyRef<PyElementField>) -> PyResult<PyNodeField> {
    let nf = crate::ops::field::divergence(&field.inner)?;
    Ok(PyNodeField { inner: nf })
}

/// Integral `∫_Ω f dΩ` of a field over its support, using the finite-element
/// quadrature — the total of one `component` (e.g. the resultant of a
/// distributed force **density**).
///
/// - `NodeField`: interpolates with the shape functions, `∫ Σ_i f_i N_i dΩ` —
///   `fespace` is **required**.
/// - `ElementField`: integrates the Gauss-point values directly,
///   `Σ_cell Σ_g f·|J|·w` — `fespace` is ignored.
///
/// For a field of already-integrated **nodal** forces, the resultant is a plain
/// sum instead: `field.sum(component)`.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (field, component, fespace=None))]
pub fn integral(
    field: &Bound<'_, PyAny>,
    component: &str,
    fespace: Option<PyRef<PyFiniteElementSpace>>,
) -> PyResult<f64> {
    if let Ok(f) = field.extract::<PyRef<PyNodeField>>() {
        let fes = fespace.ok_or_else(|| {
            PyTypeError::new_err("integral: a NodeField needs a FiniteElementSpace (fespace=...)")
        })?;
        return Ok(crate::ops::field::integral(
            &f.inner, &fes.inner, component,
        )?);
    }
    if let Ok(f) = field.extract::<PyRef<PyElementField>>() {
        return Ok(crate::ops::field::integral_element(&f.inner, component)?);
    }
    Err(PyTypeError::new_err(
        "integral: expected a NodeField (with fespace=...) or an ElementField",
    ))
}

/// Squared Euclidean norm `xᵀx = Σ v²` of a field (Cast3M `XTX`) — the sum of
/// squares over every value of every zone. Accepts a `NodeField`,
/// `SubNodeField`, `ElementField` or `SubElementField`.
///
/// With `components` given, the sum is restricted to those components only
/// (the rest ignored); by default every component is taken.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (x, components = None))]
pub fn xtx(x: &Bound<'_, PyAny>, components: Option<Vec<String>>) -> PyResult<f64> {
    use crate::containers::field::{Field, SubField};
    let refs: Option<Vec<&str>> = components
        .as_ref()
        .map(|v| v.iter().map(String::as_str).collect());
    macro_rules! aggregate {
        ($inner:expr) => {
            match &refs {
                Some(c) => $inner.xtx_components(c)?,
                None => $inner.xtx()?,
            }
        };
    }
    macro_rules! sub {
        ($guard:expr) => {
            match &refs {
                Some(c) => $guard.xtx_components(c)?,
                None => $guard.xtx(),
            }
        };
    }
    if let Ok(a) = x.extract::<PyRef<PyNodeField>>() {
        return Ok(aggregate!(a.inner));
    }
    if let Ok(a) = x.extract::<PyRef<PyElementField>>() {
        return Ok(aggregate!(a.inner));
    }
    if let Ok(a) = x.extract::<PyRef<PySubNodeField>>() {
        return Ok(sub!(read(&a.handle)?));
    }
    if let Ok(a) = x.extract::<PyRef<PySubElementField>>() {
        return Ok(sub!(read(&a.handle)?));
    }
    Err(PyTypeError::new_err(
        "expected a NodeField, SubNodeField, ElementField or SubElementField",
    ))
}

/// Select the part of a field's support passing a value band, zone by zone —
/// a value-range filter returning a `Mesh`.
///
/// `field` may be a `NodeField` / `SubNodeField` (→ POI1 submeshes of the
/// passing **nodes**) or an `ElementField` / `SubElementField` (→ submeshes
/// of the passing **cells**, each of its zone's element type; a cell passes
/// only when *all* its Gauss points do). The result has one submesh per
/// processed zone.
///
/// The band is set by the four comparison bounds — `ge` (`≥`), `gt` (`>`),
/// `le` (`≤`), `lt` (`<`); give at most one lower (`ge`/`gt`) and one upper
/// (`le`/`lt`), at least one overall. With several components in play they
/// are combined with **AND**: a point/cell is kept only when *every* tested
/// component is in band.
///
/// `components=None` tests every component of each zone. A `components`
/// list tests **only** those components, and only on the zones carrying
/// **all** of them — a zone missing any listed component is skipped (no
/// submesh). Errors if no bound is given, or the lower one exceeds the upper.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (field, ge=None, gt=None, le=None, lt=None, components=None))]
#[allow(clippy::too_many_arguments)]
pub fn select(
    field: &Bound<'_, PyAny>,
    ge: Option<f64>,
    gt: Option<f64>,
    le: Option<f64>,
    lt: Option<f64>,
    components: Option<Vec<String>>,
) -> PyResult<PyMesh> {
    use crate::ops::field as ops;
    let band = ops::Band::new(ge, gt, le, lt)?;
    let inner = if let Ok(f) = field.extract::<PyRef<PyNodeField>>() {
        ops::select_nodes(&f.inner, &band, components)?
    } else if let Ok(f) = field.extract::<PyRef<PyElementField>>() {
        ops::select_cells(&f.inner, &band, components)?
    } else if let Ok(f) = field.extract::<PyRef<PySubNodeField>>() {
        ops::select_sub_nodes(&*read(&f.handle)?, &band, components)?
    } else if let Ok(f) = field.extract::<PyRef<PySubElementField>>() {
        ops::select_sub_cells(&*read(&f.handle)?, &band, components)?
    } else {
        return Err(PyTypeError::new_err(
            "expected a NodeField, SubNodeField, ElementField or SubElementField",
        ));
    };
    Ok(PyMesh { inner })
}

/// Per-component 0/1 **mask** of a field against a value band — same flavour
/// and same structure as the input (Cast3M's `MASQUE`).
///
/// Unlike [`select`](fn@select), which extracts the passing support into a
/// `Mesh`, `mask` keeps the field's exact shape (zones, support, components)
/// and only rewrites the values: `1.0` where the band holds, `0.0` where it
/// does not — so the result is multipliable term by term with the input
/// (`field * mask(field, ge=0)` zeroes the negatives, component by component).
/// A `NodeField` masks per node, an `ElementField` per Gauss point.
///
/// The band is set by the four comparison bounds `ge` (`≥`), `gt` (`>`),
/// `le` (`≤`), `lt` (`<`) — same rules as [`select`](fn@select). There is
/// **no** AND across components here: each value stands on its own.
///
/// `components=None` tests every component. A `components` list tests only
/// those; the others stay at `1.0` (identity for the product), and a zone
/// missing a listed component is left all-`1.0`. Errors if no bound is given,
/// or the lower one exceeds the upper.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[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>> {
    use crate::ops::field as ops;
    let band = ops::Band::new(ge, gt, le, lt)?;
    if let Ok(f) = field.extract::<PyRef<PyNodeField>>() {
        let out = ops::mask_nodes(&f.inner, &band, components)?;
        Ok(Py::new(py, PyNodeField { inner: out })?.into_any())
    } else if let Ok(f) = field.extract::<PyRef<PyElementField>>() {
        let out = ops::mask_cells(&f.inner, &band, components)?;
        Ok(Py::new(py, PyElementField { inner: out })?.into_any())
    } else if let Ok(f) = field.extract::<PyRef<PySubNodeField>>() {
        let out = ops::mask_sub_nodes(&*read(&f.handle)?, &band, components);
        Ok(Py::new(
            py,
            PySubNodeField {
                handle: insert(out),
            },
        )?
        .into_any())
    } else if let Ok(f) = field.extract::<PyRef<PySubElementField>>() {
        let out = ops::mask_sub_cells(&*read(&f.handle)?, &band, components);
        Ok(Py::new(
            py,
            PySubElementField {
                handle: insert(out),
            },
        )?
        .into_any())
    } else {
        Err(PyTypeError::new_err(
            "expected a NodeField, SubNodeField, ElementField or SubElementField",
        ))
    }
}

/// Keep only the named `components` of a field, zone by zone — Cast3M's `EXCO`
/// (component extraction).
///
/// `components` is a single name or a list of names; a list `model.primal_vars()`
/// is the intended input (strip a `solve` result of its dual/Lagrange unknowns).
/// In each zone the requested components are kept in the zone's **own** order;
/// a zone carrying **none** of them is dropped, and a zone carrying **only**
/// requested components has its sub-field **shared** (handle copied, not
/// duplicated). Names the field does not carry are ignored; errors if no zone
/// carries any of `components`.
///
/// Accepts a `NodeField`, `SubNodeField`, `ElementField` or `SubElementField`
/// and returns the same flavour.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn filter_components(
    py: Python<'_>,
    field: &Bound<'_, PyAny>,
    components: &Bound<'_, PyAny>,
) -> PyResult<Py<PyAny>> {
    use crate::containers::field::{Field, SubField};
    let wanted = extract_names(components)?;
    if let Ok(f) = field.extract::<PyRef<PyNodeField>>() {
        let inner = f.inner.filter_components(wanted.as_slice())?;
        return Ok(Py::new(py, PyNodeField { inner })?.into_any());
    }
    if let Ok(f) = field.extract::<PyRef<PyElementField>>() {
        let inner = f.inner.filter_components(wanted.as_slice())?;
        return Ok(Py::new(py, PyElementField { inner })?.into_any());
    }
    if let Ok(f) = field.extract::<PyRef<PySubNodeField>>() {
        let out = read(&f.handle)?.select_components(wanted.as_slice())?;
        return Ok(Py::new(
            py,
            PySubNodeField {
                handle: insert(out),
            },
        )?
        .into_any());
    }
    if let Ok(f) = field.extract::<PyRef<PySubElementField>>() {
        let out = read(&f.handle)?.select_components(wanted.as_slice())?;
        return Ok(Py::new(
            py,
            PySubElementField {
                handle: insert(out),
            },
        )?
        .into_any());
    }
    Err(PyTypeError::new_err(
        "expected a NodeField, SubNodeField, ElementField or SubElementField",
    ))
}

/// Rename component `old` to `new` in a field, zone by zone — the renaming half
/// of Cast3M's `EXCO`. Values are preserved (metadata-only change). A zone
/// without `old` is carried unchanged; errors if no zone carries `old`, or if a
/// zone already has a component named `new`.
///
/// Accepts a `NodeField`, `SubNodeField`, `ElementField` or `SubElementField`
/// and returns the same flavour.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn rename_component(
    py: Python<'_>,
    field: &Bound<'_, PyAny>,
    old: &str,
    new: &str,
) -> PyResult<Py<PyAny>> {
    use crate::containers::field::{Field, SubField};
    if let Ok(f) = field.extract::<PyRef<PyNodeField>>() {
        let inner = f.inner.rename_component(old, new)?;
        return Ok(Py::new(py, PyNodeField { inner })?.into_any());
    }
    if let Ok(f) = field.extract::<PyRef<PyElementField>>() {
        let inner = f.inner.rename_component(old, new)?;
        return Ok(Py::new(py, PyElementField { inner })?.into_any());
    }
    if let Ok(f) = field.extract::<PyRef<PySubNodeField>>() {
        let out = read(&f.handle)?.rename_component(old, new)?;
        return Ok(Py::new(
            py,
            PySubNodeField {
                handle: insert(out),
            },
        )?
        .into_any());
    }
    if let Ok(f) = field.extract::<PyRef<PySubElementField>>() {
        let out = read(&f.handle)?.rename_component(old, new)?;
        return Ok(Py::new(
            py,
            PySubElementField {
                handle: insert(out),
            },
        )?
        .into_any());
    }
    Err(PyTypeError::new_err(
        "expected a NodeField, SubNodeField, ElementField or SubElementField",
    ))
}

/// Extract a component-name argument that is either a single `str` or a list of
/// `str` (e.g. the result of `model.primal_vars()`) into a `Vec<String>`.
pub(crate) fn extract_names(arg: &Bound<'_, PyAny>) -> PyResult<Vec<String>> {
    if let Ok(name) = arg.extract::<String>() {
        return Ok(vec![name]);
    }
    if let Ok(names) = arg.extract::<Vec<String>>() {
        return Ok(names);
    }
    Err(PyTypeError::new_err(
        "components: expected a str or a list of str",
    ))
}

/// Global scalar product `∑ xᵢ · yᵢ` of two **whole** fields — Cast3M's `XTY`.
///
/// `x` and `y` must be the same flavour (`NodeField` / `SubNodeField` /
/// `ElementField` / `SubElementField`), sit on the same support/decomposition,
/// and carry the same components (aligned by name). Returns a single float —
/// the field inner product used for energies (`F·u`), residual norms, etc.
///
/// For the **node-by-node** scalar product (a field, one value per node),
/// see [`psca`](fn@psca).
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn xty(x: &Bound<'_, PyAny>, y: &Bound<'_, PyAny>) -> PyResult<f64> {
    use crate::containers::field::{Field, SubField};
    if let Ok(a) = x.extract::<PyRef<PyNodeField>>() {
        let b = y
            .extract::<PyRef<PyNodeField>>()
            .map_err(|_| PyTypeError::new_err("xty: both operands must be NodeFields"))?;
        return Ok(a.inner.dot_field(&b.inner)?);
    }
    if let Ok(a) = x.extract::<PyRef<PyElementField>>() {
        let b = y
            .extract::<PyRef<PyElementField>>()
            .map_err(|_| PyTypeError::new_err("xty: both operands must be ElementFields"))?;
        return Ok(a.inner.dot_field(&b.inner)?);
    }
    if let Ok(a) = x.extract::<PyRef<PySubNodeField>>() {
        let b = y
            .extract::<PyRef<PySubNodeField>>()
            .map_err(|_| PyTypeError::new_err("xty: both operands must be SubNodeFields"))?;
        return Ok(read(&a.handle)?.dot(&*read(&b.handle)?)?);
    }
    if let Ok(a) = x.extract::<PyRef<PySubElementField>>() {
        let b = y
            .extract::<PyRef<PySubElementField>>()
            .map_err(|_| PyTypeError::new_err("xty: both operands must be SubElementFields"))?;
        return Ok(read(&a.handle)?.dot(&*read(&b.handle)?)?);
    }
    Err(PyTypeError::new_err(
        "expected a NodeField, SubNodeField, ElementField or SubElementField",
    ))
}

/// Node-by-node (or point-by-point) scalar product of two fields — Cast3M's
/// `PSCA`. Returns a **new field** of the same flavour as the inputs, carrying
/// a single `"psca"` component whose value at each node/point is `∑_c xᵣ,c·yᵣ,c`
/// (reduction over components only, the support is kept).
///
/// `x` and `y` must be the same flavour (`NodeField` / `SubNodeField` /
/// `ElementField` / `SubElementField`), sit on the same support/decomposition,
/// and carry the same components (aligned by name).
///
/// For the **global** scalar product (a single float over the whole field),
/// see [`xty`](fn@xty).
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn psca(py: Python<'_>, x: &Bound<'_, PyAny>, y: &Bound<'_, PyAny>) -> PyResult<Py<PyAny>> {
    use crate::containers::field::{Field, SubField};
    if let Ok(a) = x.extract::<PyRef<PyNodeField>>() {
        let b = y
            .extract::<PyRef<PyNodeField>>()
            .map_err(|_| PyTypeError::new_err("psca: both operands must be NodeFields"))?;
        let inner = a.inner.pscal_field(&b.inner)?;
        return Ok(Py::new(py, PyNodeField { inner })?.into_any());
    }
    if let Ok(a) = x.extract::<PyRef<PyElementField>>() {
        let b = y
            .extract::<PyRef<PyElementField>>()
            .map_err(|_| PyTypeError::new_err("psca: both operands must be ElementFields"))?;
        let inner = a.inner.pscal_field(&b.inner)?;
        return Ok(Py::new(py, PyElementField { inner })?.into_any());
    }
    if let Ok(a) = x.extract::<PyRef<PySubNodeField>>() {
        let b = y
            .extract::<PyRef<PySubNodeField>>()
            .map_err(|_| PyTypeError::new_err("psca: both operands must be SubNodeFields"))?;
        let out = read(&a.handle)?.pscal(&*read(&b.handle)?)?;
        return Ok(Py::new(
            py,
            PySubNodeField {
                handle: insert(out),
            },
        )?
        .into_any());
    }
    if let Ok(a) = x.extract::<PyRef<PySubElementField>>() {
        let b = y
            .extract::<PyRef<PySubElementField>>()
            .map_err(|_| PyTypeError::new_err("psca: both operands must be SubElementFields"))?;
        let out = read(&a.handle)?.pscal(&*read(&b.handle)?)?;
        return Ok(Py::new(
            py,
            PySubElementField {
                handle: insert(out),
            },
        )?
        .into_any());
    }
    Err(PyTypeError::new_err(
        "expected a NodeField, SubNodeField, ElementField or SubElementField",
    ))
}

// ── Element-wise unary maths (numpy-style) ──────────────────────────────────
//
// `pyrucast.cos(field)`, `pyrucast.exp(field)`, … apply a scalar function to
// every value of a field, returning a **new** field of the same type. They
// accept any of the four field flavours (`NodeField` / `SubNodeField` /
// `ElementField` / `SubElementField`) and mirror `crate::ops::field::*`.
// Results are unguarded (numpy-like): `log` of ≤ 0 → `-inf`/`nan`, etc.

/// Generate a `#[pyfunction] $name(field)` that dispatches over the four field
/// wrapper types and applies the matching `ops::field::$name`.
macro_rules! py_field_unary {
    ($name:ident, $doc:literal) => {
        #[doc = $doc]
        #[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
        #[pyfunction]
        pub fn $name(py: Python<'_>, field: &Bound<'_, PyAny>) -> PyResult<Py<PyAny>> {
            use crate::ops::field::$name as op;
            if let Ok(f) = field.extract::<PyRef<PyNodeField>>() {
                return Ok(Py::new(
                    py,
                    PyNodeField {
                        inner: op(&f.inner)?,
                    },
                )?
                .into_any());
            }
            if let Ok(f) = field.extract::<PyRef<PyElementField>>() {
                return Ok(Py::new(
                    py,
                    PyElementField {
                        inner: op(&f.inner)?,
                    },
                )?
                .into_any());
            }
            if let Ok(f) = field.extract::<PyRef<PySubNodeField>>() {
                let out = op(&*read(&f.handle)?)?;
                return Ok(Py::new(
                    py,
                    PySubNodeField {
                        handle: insert(out),
                    },
                )?
                .into_any());
            }
            if let Ok(f) = field.extract::<PyRef<PySubElementField>>() {
                let out = op(&*read(&f.handle)?)?;
                return Ok(Py::new(
                    py,
                    PySubElementField {
                        handle: insert(out),
                    },
                )?
                .into_any());
            }
            Err(PyTypeError::new_err(
                "expected a NodeField, SubNodeField, ElementField or SubElementField",
            ))
        }
    };
}

py_field_unary!(abs, "Element-wise absolute value of a field.");
py_field_unary!(
    sqrt,
    "Element-wise square root of a field (`nan` for negatives)."
);
py_field_unary!(exp, "Element-wise exponential `eˣ` of a field.");
py_field_unary!(
    log,
    "Element-wise natural logarithm of a field (`-inf`/`nan` for ≤ 0)."
);
py_field_unary!(log10, "Element-wise base-10 logarithm of a field.");
py_field_unary!(cos, "Element-wise cosine of a field (radians).");
py_field_unary!(sin, "Element-wise sine of a field (radians).");
py_field_unary!(tan, "Element-wise tangent of a field (radians).");
py_field_unary!(sinh, "Element-wise hyperbolic sine of a field.");
py_field_unary!(cosh, "Element-wise hyperbolic cosine of a field.");
py_field_unary!(tanh, "Element-wise hyperbolic tangent of a field.");