pyrucast 0.15.0

Finite-element library in Rust, inspired by cast3m, exposed to Python
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
//! Python wrappers for [`crate::containers::node_field::SubNodeField`] and
//! [`crate::containers::node_field::NodeField`].

use crate::atoms::NodeId;
use crate::containers::field::SubField;
use crate::containers::mesh::SubMesh;
use crate::containers::node_field::{NodeField, SubNodeField};
use crate::coords::Coords;
use crate::error::PyrucastError;
use crate::handle::Handle;
use crate::py::mesh::{PyMesh, PySubMesh};
use crate::py::node::PyNode;
use pyo3::exceptions::PyTypeError;
use pyo3::prelude::*;

/// Resolve a node list from the several shapes a caller may pass to a
/// batch read: a list of `Node`, a POI1 `SubMesh`, or a `Mesh` (its
/// submeshes' nodes taken in connectivity order — one entry per point for
/// a POI1 mesh). Order is preserved; duplicates are kept.
///
/// The ids are meant for a field whose nodes live in `coords` (`None`: an
/// empty field), so nodes and meshes from another `Coords` are refused.
fn extract_node_ids(
    obj: &Bound<'_, PyAny>,
    coords: Option<&Handle<Coords>>,
) -> PyResult<Vec<NodeId>> {
    let check = |zone: &SubMesh| -> PyResult<()> {
        match coords {
            Some(c) if !c.same_object(&zone.coords()) => {
                Err(PyrucastError::Message("mismatched Coords".into()).into())
            }
            _ => Ok(()),
        }
    };
    if let Ok(sm) = obj.extract::<PyRef<PySubMesh>>() {
        let zone = sm.handle.read();
        check(&zone)?;
        return Ok(zone.connectivity().to_vec());
    }
    if let Ok(mesh) = obj.extract::<PyRef<PyMesh>>() {
        let mut ids: Vec<NodeId> = Vec::new();
        for h in &mesh.inner {
            let zone = h.read();
            check(&zone)?;
            ids.extend_from_slice(zone.connectivity());
        }
        return Ok(ids);
    }
    if let Ok(nodes) = obj.extract::<Vec<PyRef<'_, PyNode>>>() {
        return nodes.iter().map(|n| n.id_in(coords)).collect();
    }
    Err(PyTypeError::new_err(
        "expected a list of Node, a SubMesh, or a Mesh",
    ))
}

// ─── SubNodeField (view) ────────────────────────────────────────────────────

/// A **view** into one zone of a `NodeField`, obtained by indexing
/// (`node_field[i]`) — never constructed directly. Build at the parent
/// level instead: `NodeField(support, components)`, composed with `|`.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyclass)]
#[pyclass(name = "SubNodeField")]
pub struct PySubNodeField {
    pub(crate) handle: Handle<SubNodeField>,
}

#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pymethods)]
#[pymethods]
impl PySubNodeField {
    /// Number of nodes in the support.
    #[getter]
    fn node_count(&self) -> usize {
        self.handle.read().node_count()
    }

    /// Value at node index `node_idx`, component index `comp_idx`.
    fn get(&self, node_idx: usize, comp_idx: usize) -> PyResult<f64> {
        Ok(self.handle.read().get(node_idx, comp_idx)?)
    }

    /// Set the value at node index `node_idx`, component index `comp_idx`.
    fn set(&self, node_idx: usize, comp_idx: usize, value: f64) -> PyResult<()> {
        self.handle.write().set(node_idx, comp_idx, value)?;
        Ok(())
    }

    /// Value at `node`, component index `comp_idx`.
    fn get_by_node(&self, node: PyRef<'_, PyNode>, comp_idx: usize) -> PyResult<f64> {
        let nid = node.id_in(Some(&self.handle.read().coords()))?;
        Ok(self.handle.read().get_by_node(nid, comp_idx)?)
    }

    /// Set the value at `node`, component index `comp_idx`.
    fn set_by_node(&self, node: PyRef<'_, PyNode>, comp_idx: usize, value: f64) -> PyResult<()> {
        let nid = node.id_in(Some(&self.handle.read().coords()))?;
        self.handle.write().set_by_node(nid, comp_idx, value)?;
        Ok(())
    }

    /// All component values at node index `node_idx`, in order.
    fn node_values(&self, node_idx: usize) -> PyResult<Vec<f64>> {
        Ok(self.handle.read().node_values(node_idx)?.to_vec())
    }

    /// The POI1 `SubMesh` this zone lives on — shared, not copied: a zone
    /// built on it combines node by node with this one.
    fn support(&self) -> PySubMesh {
        PySubMesh {
            handle: SubField::support(&*self.handle.read()),
        }
    }

    /// Value at `node` for the named `component`.
    fn value(&self, node: PyRef<'_, PyNode>, component: &str) -> PyResult<f64> {
        let nid = node.id_in(Some(&self.handle.read().coords()))?;
        Ok(self.handle.read().value(nid, component)?)
    }

    /// Set the value at `node` for the named `component`.
    fn set_value(&self, node: PyRef<'_, PyNode>, component: &str, value: f64) -> PyResult<()> {
        let nid = node.id_in(Some(&self.handle.read().coords()))?;
        self.handle.write().set_value(nid, component, value)?;
        Ok(())
    }

    /// Set `component` to `value` at every node of the zone.
    fn set_uniform(&self, component: &str, value: f64) -> PyResult<()> {
        use crate::containers::field::SubField;
        self.handle.write().set_uniform(component, value)?;
        Ok(())
    }

    // ── Arithmetic operators (return a new sub-field) ───────────────────
    //
    // `rhs` may be a float (scalar broadcast over every node × component) or
    // another `SubNodeField` (per-component union with passthrough on a shared
    // support). Division does not guard against zero (inf/nan).

    /// `subfield[node, "UX"] = v` — raises if the node or component is absent.
    fn __setitem__(&self, key: (PyRef<'_, PyNode>, String), value: f64) -> PyResult<()> {
        let (node, comp) = key;
        let nid = node.id_in(Some(&self.handle.read().coords()))?;
        self.handle.write().set_value(nid, &comp, value)?;
        Ok(())
    }

    /// Smallest value of the named `component` — or, called without one, the
    /// smallest value of the **whole** field, every component pooled. Pooling
    /// reads the field as the flat list of its values: on components carrying
    /// different units it answers "the smallest number in there", not a
    /// physical quantity.
    #[pyo3(signature = (component=None))]
    fn min(&self, component: Option<&str>) -> PyResult<f64> {
        Ok(SubField::min(&*self.handle.read(), component)?)
    }

    /// Largest value of the named `component` — or, called without one, the
    /// largest value of the **whole** field, every component pooled (see `min`).
    #[pyo3(signature = (component=None))]
    fn max(&self, component: Option<&str>) -> PyResult<f64> {
        Ok(SubField::max(&*self.handle.read(), component)?)
    }

    /// Sum of the named `component` over the support — Σ over the nodes, or over
    /// the Gauss points for a field by elements. The resultant of a nodal force
    /// field, one component at a time. An empty support sums to `0.0`.
    fn sum(&self, component: &str) -> PyResult<f64> {
        Ok(SubField::sum(&*self.handle.read(), component)?)
    }

    /// The `order`-norm of the field's values.
    ///
    /// # Parameters
    ///
    /// - `order`: `2`, the default, gives the Euclidean norm `√(Σ v²)`; any
    ///   `p ≥ 1` gives `(Σ |v|ᵖ)^(1/p)`; `0` gives the largest `|v|`, the
    ///   infinity norm.
    /// - `components`: the components to measure, the others ignored; `None`
    ///   takes every component. A name the field does not carry is ignored.
    ///
    /// # Returns
    ///
    /// The norm, a `float`; `0.0` for a field without values, or carrying none
    /// of `components`.
    #[pyo3(signature = (order = 2, components = None))]
    fn norm(&self, order: u32, components: Option<Vec<String>>) -> f64 {
        let names: Option<Vec<&str>> = components
            .as_ref()
            .map(|v| v.iter().map(String::as_str).collect());
        SubField::norm(&*self.handle.read(), order, names.as_deref())
    }

    /// Component names, in order.
    fn components(&self) -> Vec<String> {
        self.handle.read().components().to_vec()
    }

    /// Number of components stored per node, or per Gauss point for a field by
    /// elements.
    #[getter]
    fn component_count(&self) -> usize {
        self.handle.read().component_count()
    }

    /// Index of component `name`, or `None` if unknown — no default index would
    /// say "absent" without being mistaken for a real one.
    fn component_index(&self, name: &str) -> Option<usize> {
        self.handle.read().component_index(name)
    }

    /// Keep only the named components, in the order the field holds them.
    ///
    /// `components` is a single name or a list of names (e.g. the result of
    /// `model.primal_vars()`). Returns a **new** field of the caller's own kind,
    /// sharing its support; the original is untouched. A name the zone does not
    /// carry is ignored; errors if it carries none of them — a zone keeps at
    /// least one component, and filtering never invents one.
    fn filter_components(&self, components: &Bound<'_, PyAny>) -> PyResult<Self> {
        let wanted = crate::py::ops::field::extract_names(components)?;
        let out = self.handle.read().select_components(wanted.as_slice())?;
        Ok(Self {
            handle: Handle::new(out),
        })
    }

    /// Rename one component, `old` to `new`, leaving every other untouched.
    ///
    /// Returns a **new** field of the caller's own kind, on the same support. The
    /// component order is kept — renaming is not reordering. Errors if `old` is
    /// absent, or if `new` is already taken: a name is how a component is
    /// addressed, so two of them cannot share one.
    fn rename_component(&self, old: &str, new: &str) -> PyResult<Self> {
        let out = self.handle.read().rename_component(old, new)?;
        Ok(Self {
            handle: Handle::new(out),
        })
    }
}

impl PySubNodeField {
    /// Dispatch an arithmetic operator: float → scalar broadcast,
    /// `SubNodeField` → `merge_components` (union of components, passthrough).
    pub(crate) fn scalar_or_combine(
        &self,
        rhs: &Bound<'_, PyAny>,
        op: fn(f64, f64) -> f64,
    ) -> PyResult<PySubNodeField> {
        if let Ok(s) = rhs.extract::<f64>() {
            let out = self.handle.read().map_all(|v| op(v, s));
            Ok(PySubNodeField {
                handle: Handle::new(out),
            })
        } else if let Ok(other) = rhs.extract::<PyRef<PySubNodeField>>() {
            let a = (*self.handle.read()).clone();
            let b = (*other.handle.read()).clone();
            Ok(PySubNodeField {
                handle: Handle::new(a.merge_components(&b, op)?),
            })
        } else {
            Err(PyTypeError::new_err(
                "unsupported operand: expected a float or a SubNodeField",
            ))
        }
    }
}

crate::impl_dump_pymethod!(handle PySubNodeField, handle);

// ─── NodeField (aggregate) ──────────────────────────────────────────────────

/// A field of values carried by mesh nodes — one `SubNodeField` block per
/// zone, with possibly different components from one zone to the next.
///
/// Build with `NodeField(support, components)` where `support` is a `Mesh`
/// (one sub-field per submesh) or a single `SubMesh`; index it
/// (`field[i]`) to reach a `SubNodeField`, compose zones with `|`. Reads
/// (`field.value(node, "T")`) take the first zone defining the pair;
/// `field.check()` verifies that zones agree on shared interface nodes.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyclass)]
#[pyclass(name = "NodeField")]
pub struct PyNodeField {
    pub(crate) inner: NodeField,
}

#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pymethods)]
#[pymethods]
impl PyNodeField {
    /// `NodeField(support, components)` — a field with uniform values. With a
    /// `Mesh` support: one `SubNodeField` per submesh, each on the
    /// distinct nodes of its zone — its POI1 companion, `SubMesh.to_poi1()`.
    /// With a `SubMesh`: a single zone. A POI1 zone listing each node once is
    /// its own companion, so the field lands on that very zone.
    ///
    /// Each entry of `components` is a `(name, value)` pair, the component
    /// holding `value` at every node, or a bare name, holding zero:
    /// `[("T", 20.0), "u_x"]`.
    #[new]
    fn py_new(
        support: &Bound<'_, PyAny>,
        components: Vec<crate::py::ops::field::InitialComponent>,
    ) -> PyResult<Self> {
        use crate::py::ops::field::InitialComponent;
        let names = InitialComponent::names(&components);
        let inner = if let Ok(mesh) = support.extract::<PyRef<PyMesh>>() {
            NodeField::new(&mesh.inner, names)?
        } else if let Ok(sm) = support.extract::<PyRef<PySubMesh>>() {
            NodeField::from_submesh(&sm.handle, names)?
        } else {
            return Err(PyTypeError::new_err("expected a Mesh or a SubMesh"));
        };
        InitialComponent::fill(&inner, &components);
        Ok(Self { inner })
    }

    /// Explicit `components` list per submesh of `mesh`.
    #[classmethod]
    fn with_components_per_submesh(
        _cls: &pyo3::Bound<'_, pyo3::types::PyType>,
        mesh: PyRef<PyMesh>,
        components_per_submesh: Vec<Vec<String>>,
    ) -> PyResult<Self> {
        let inner = NodeField::with(&mesh.inner, &components_per_submesh)?;
        Ok(Self { inner })
    }

    /// Number of distinct nodes across the zones.
    #[getter]
    fn node_count(&self) -> usize {
        self.inner.node_count()
    }

    /// Value at `node` for the named `component` — the first zone
    /// defining both wins. Raises if none does.
    fn value(&self, node: PyRef<'_, PyNode>, component: &str) -> PyResult<f64> {
        let nid = node.id_in(self.inner.coords().ok().as_ref())?;
        Ok(self.inner.value(nid, component)?)
    }

    /// Values for the named `component` at several nodes, returned in the
    /// **same order** as given — the batch form of `value`. `nodes` is
    /// either a list of `Node`, or a `SubMesh` or a `Mesh` whose
    /// connectivity is read in order (for a POI1, its points). The first zone defining each
    /// `(node, component)` pair wins; raises on the first node the field
    /// does not define.
    fn values(&self, nodes: &Bound<'_, PyAny>, component: &str) -> PyResult<Vec<f64>> {
        let ids = extract_node_ids(nodes, self.inner.coords().ok().as_ref())?;
        Ok(self.inner.values_at(&ids, component)?)
    }

    /// Verify zone coherence: every `(node, component)` stored by several
    /// zones must hold the same value everywhere. Raises on the first
    /// conflict.
    fn check(&self) -> PyResult<()> {
        Ok(self.inner.check()?)
    }

    /// Visualize this field alone, as a **coloured point cloud** over
    /// its support nodes — the POI1 support has no connectivity, so no
    /// surface can be drawn here; use `mesh.plot(field=...)` with the
    /// original mesh for surfaces.
    ///
    /// Same `view` / `save` / `show_axes` / `component` / `vmin` /
    /// `vmax` / `cmap` / `title` semantics as `Mesh.plot`.
    /// `revolve` / `revolve_angle` sweep an axisymmetric plot into its body
    /// of revolution — see `SubMesh.plot`.
    #[cfg(feature = "viz")]
    #[pyo3(signature = (view=None, save=None, show_axes=true, component=None, vmin=None, vmax=None, cmap=None, revolve=false, revolve_angle=360.0, title=None))]
    #[allow(clippy::too_many_arguments)]
    fn plot(
        &self,
        view: Option<(f64, f64, f64)>,
        save: Option<std::path::PathBuf>,
        show_axes: bool,
        component: Option<String>,
        vmin: Option<f64>,
        vmax: Option<f64>,
        cmap: Option<crate::viz::Colormap>,
        revolve: bool,
        revolve_angle: f64,
        title: Option<String>,
    ) -> PyResult<()> {
        let view = crate::py::build_view(view, show_axes, revolve, revolve_angle)?;
        let scale = crate::viz::ColorScale {
            cmap: cmap.unwrap_or_default(),
            vmin,
            vmax,
        };
        self.inner.plot(
            view,
            save.as_deref(),
            component.as_deref(),
            scale,
            title.as_deref(),
        )?;
        Ok(())
    }

    /// The mesh this field lives on: each zone's POI1 support, one per zone,
    /// in order — `f.support()[i]` is `f[i].support()`, shared, not copied.
    /// Two zones on one support list it twice; `s | s` keeps each once. A
    /// field built on the supports, each once, combines node by node with
    /// this one.
    fn support(&self) -> PyMesh {
        PyMesh {
            inner: self.inner.support(),
        }
    }

    // ── Per-component scalar ops (in place, on every zone defining it) ──

    // ── Arithmetic operators (return a new field) ───────────────────────
    //
    // `rhs`: a float (scalar over every zone), a `NodeField` (per support and
    // component, union with passthrough), or a `SubNodeField` (targeted zone
    // update).

    /// Smallest value of `component` across the zones defining it — or, called
    /// without a component, the smallest value of the **whole** field, every
    /// component of every zone pooled (see the sub-field's `min` for what
    /// pooling means).
    #[pyo3(signature = (component=None))]
    fn min(&self, component: Option<&str>) -> PyResult<f64> {
        use crate::containers::field::Field;
        Ok(Field::min(&self.inner, component)?)
    }

    /// Largest value of `component` across the zones defining it — or, called
    /// without a component, the largest value of the **whole** field (see `min`).
    #[pyo3(signature = (component=None))]
    fn max(&self, component: Option<&str>) -> PyResult<f64> {
        use crate::containers::field::Field;
        Ok(Field::max(&self.inner, component)?)
    }

    /// Sum of `component` over the nodes of the field (Σ over the whole field)
    /// — the resultant of a nodal force field, one component at a time. A node
    /// that several zones carry counts once. Errors if no zone defines the
    /// component.
    fn sum(&self, component: &str) -> PyResult<f64> {
        use crate::containers::field::Field;
        Ok(Field::sum(&self.inner, component)?)
    }

    /// The `order`-norm of the field's values.
    ///
    /// # Parameters
    ///
    /// - `order`: `2`, the default, gives the Euclidean norm `√(Σ v²)`; any
    ///   `p ≥ 1` gives `(Σ |v|ᵖ)^(1/p)`; `0` gives the largest `|v|`, the
    ///   infinity norm.
    /// - `components`: the components to measure, wherever a zone carries them,
    ///   the others ignored; `None` takes every component. A name the field does
    ///   not carry is ignored.
    ///
    /// # Returns
    ///
    /// The norm, a `float`; `0.0` for a field without values, or carrying none
    /// of `components`. A node that
    /// several zones carry counts once.
    #[pyo3(signature = (order = 2, components = None))]
    fn norm(&self, order: u32, components: Option<Vec<String>>) -> f64 {
        let names: Option<Vec<&str>> = components
            .as_ref()
            .map(|v| v.iter().map(String::as_str).collect());
        crate::containers::field::Field::norm(&self.inner, order, names.as_deref())
    }

    /// Union of the zones' component names, first-seen order.
    fn components(&self) -> Vec<String> {
        use crate::containers::field::Field;
        Field::components(&self.inner)
    }

    /// Keep only the named components, in the order the field holds them.
    ///
    /// `components` is a single name or a list of names (e.g. the result of
    /// `model.primal_vars()`). Returns a **new** field of the caller's own kind,
    /// sharing its support; the original is untouched. A name the field does not
    /// carry is ignored: a zone carrying none of the names is dropped, and a field
    /// carrying none of them gives an empty field — filtering never invents a
    /// component.
    fn filter_components(&self, components: &Bound<'_, PyAny>) -> PyResult<Self> {
        use crate::containers::field::Field;
        let wanted = crate::py::ops::field::extract_names(components)?;
        Ok(Self {
            inner: self.inner.filter_components(wanted.as_slice()),
        })
    }

    /// Rename one component, `old` to `new`, leaving every other untouched.
    ///
    /// Returns a **new** field of the caller's own kind, on the same support. The
    /// component order is kept — renaming is not reordering. Errors if `old` is
    /// absent, or if `new` is already taken: a name is how a component is
    /// addressed, so two of them cannot share one.
    fn rename_component(&self, old: &str, new: &str) -> PyResult<Self> {
        use crate::containers::field::Field;
        Ok(Self {
            inner: Field::rename_component(&self.inner, old, new)?,
        })
    }
}

impl PyNodeField {
    /// Dispatch an arithmetic operator: float → scalar, `NodeField` →
    /// `merge_field` (per `(support, component)`, union/passthrough),
    /// `SubNodeField` → `merge_subfield` (targeted zone update).
    pub(crate) fn binary(
        &self,
        rhs: &Bound<'_, PyAny>,
        op: fn(f64, f64) -> f64,
    ) -> PyResult<PyNodeField> {
        use crate::containers::field::Field;
        if let Ok(s) = rhs.extract::<f64>() {
            Ok(PyNodeField {
                inner: self.inner.combine_scalar(op, s)?,
            })
        } else if let Ok(other) = rhs.extract::<PyRef<PyNodeField>>() {
            Ok(PyNodeField {
                inner: self.inner.merge_field(&other.inner, op)?,
            })
        } else if let Ok(sub) = rhs.extract::<PyRef<PySubNodeField>>() {
            let s = (*sub.handle.read()).clone();
            Ok(PyNodeField {
                inner: self.inner.merge_subfield(&s, op)?,
            })
        } else {
            Err(PyTypeError::new_err(
                "unsupported operand: expected a float, a NodeField, or a SubNodeField",
            ))
        }
    }
}

// Polymorphic subscript — **closed block**, undecorated on purpose (see
// `impl_aggregate_pymethods!`): its `.pyi` entries are the hand-written
// overloads submitted just below.
#[pymethods]
impl PySubNodeField {
    /// Indexing dispatches on the key:
    /// - `subfield[node, "UX"]` → the **value** (raises if node/component absent);
    /// - `subfield["UX"]` or `subfield[["UX", "UY"]]` → a **new sub-field** with
    ///   only those components (`filter_components`), so `u1[u2.components()]`
    ///   reprojects `u1` onto `u2`'s component set.
    fn __getitem__(&self, py: Python<'_>, key: &Bound<'_, PyAny>) -> PyResult<Py<PyAny>> {
        // (node, component) → scalar value.
        if let Ok((node, comp)) = key.extract::<(PyRef<'_, PyNode>, String)>() {
            let nid = node.id_in(Some(&self.handle.read().coords()))?;
            let v = self.handle.read().value(nid, &comp)?;
            return Ok(v.into_pyobject(py)?.into_any().unbind());
        }
        // "comp" or ["comp", …] → component selection (a new sub-field).
        let names = crate::py::ops::field::extract_names(key)?;
        let out =
            crate::containers::field::SubField::select_components(&*self.handle.read(), names)?;
        Ok(Py::new(
            py,
            PySubNodeField {
                handle: Handle::new(out),
            },
        )?
        .into_any())
    }
}

#[cfg(feature = "stub-gen")]
pyo3_stub_gen::inventory::submit! {
    pyo3_stub_gen::derive::gen_methods_from_python! { r#"
class PyNodeField:
    def __ge__(self, other: float) -> pyo3_stub_gen.RustType["PyNodeField"]:
        """`field >= x` → a fresh `NodeField` of per-component 0/1 flags (see
        `mask`), not a boolean. Combine masks with `*` and use them to weight or
        select values."""
    def __gt__(self, other: float) -> pyo3_stub_gen.RustType["PyNodeField"]:
        """`field > x` → a 0/1 mask field (see `__ge__`)."""
    def __le__(self, other: float) -> pyo3_stub_gen.RustType["PyNodeField"]:
        """`field <= x` → a 0/1 mask field (see `__ge__`)."""
    def __lt__(self, other: float) -> pyo3_stub_gen.RustType["PyNodeField"]:
        """`field < x` → a 0/1 mask field (see `__ge__`)."""
    "# }
}

#[cfg(feature = "stub-gen")]
pyo3_stub_gen::inventory::submit! {
    pyo3_stub_gen::derive::gen_methods_from_python! { r#"
class PySubNodeField:
    @overload
    def __getitem__(self, key: tuple[pyo3_stub_gen.RustType["PyNode"], str]) -> float:
        """`subfield[node, "UX"]` → the value carried by that node for that
        component. Raises if either is absent from this zone."""
    @overload
    def __getitem__(self, key: str) -> pyo3_stub_gen.RustType["PySubNodeField"]:
        """`subfield["UX"]` → a fresh `SubNodeField` on the same support,
        keeping only that component."""
    @overload
    def __getitem__(self, key: list[str]) -> pyo3_stub_gen.RustType["PySubNodeField"]:
        """`subfield[["UX", "UY"]]` → a fresh `SubNodeField` keeping only those
        components, so `u1[u2.components()]` reprojects `u1` onto `u2`'s
        component set."""
    def __ge__(self, other: float) -> pyo3_stub_gen.RustType["PySubNodeField"]:
        """`subfield >= x` → a fresh `SubNodeField` of per-component 0/1 flags
        (see `mask`), not a boolean."""
    def __gt__(self, other: float) -> pyo3_stub_gen.RustType["PySubNodeField"]:
        """`subfield > x` → a 0/1 mask field (see `__ge__`)."""
    def __le__(self, other: float) -> pyo3_stub_gen.RustType["PySubNodeField"]:
        """`subfield <= x` → a 0/1 mask field (see `__ge__`)."""
    def __lt__(self, other: float) -> pyo3_stub_gen.RustType["PySubNodeField"]:
        """`subfield < x` → a 0/1 mask field (see `__ge__`)."""
    "# }
}

crate::impl_aggregate_pymethods!(
    PyNodeField,
    PySubNodeField,
    "NodeField",
    subfield,
    NodeField,
    r#"
class PyNodeField:
    @overload
    def __getitem__(self, key: int) -> pyo3_stub_gen.RustType["PySubNodeField"]:
        """`field[i]` → the `SubNodeField` of zone i: the values carried by the
        nodes of one support."""
    @overload
    def __getitem__(self, key: slice) -> pyo3_stub_gen.RustType["PyNodeField"]:
        """`field[i:j:k]` → a fresh `NodeField` over the sliced zones, shared
        with this one (no deep copy)."""
    @overload
    def __getitem__(self, key: str) -> pyo3_stub_gen.RustType["PyNodeField"]:
        """`field["u_x"]` → a fresh `NodeField` keeping only that component, on
        every zone that carries it."""
    @overload
    def __getitem__(self, key: list[str]) -> pyo3_stub_gen.RustType["PyNodeField"]:
        """`field[["u_x", "u_y"]]` → a fresh `NodeField` keeping only those
        components, on every zone that carries them."""
    def __or__(self, other: pyo3_stub_gen.RustType["PyNodeField"] | pyo3_stub_gen.RustType["PySubNodeField"]) -> pyo3_stub_gen.RustType["PyNodeField"]:
        """`field | other` → a fresh `NodeField` holding the zones of both.
        Zones sharing the same support are **fused** (union of their
        components) — unlike `ElementField`, which juxtaposes them."""
    def __ror__(self, other: pyo3_stub_gen.RustType["PySubNodeField"]) -> pyo3_stub_gen.RustType["PyNodeField"]:
        """`subfield | field` — the mirror of `field | subfield`, differing only
        in that the lone zone comes first."""
    "#,
    r#"
class PySubNodeField:
    def __or__(self, other: pyo3_stub_gen.RustType["PySubNodeField"]) -> pyo3_stub_gen.RustType["PyNodeField"]:
        """`subfield | subfield` → a fresh `NodeField` holding both zones, fused
        if they share the same support."""
    "#,
    field_components
);

// ─── Opérateurs arithmétiques ───────────────────────────────────────────────
//
// Put here, and not in `field_macros.rs` where their macros live: a slot must be
// expanded in the module declaring its `#[pyclass]`, otherwise pyo3 generates an
// `unsafe` trampoline call that edition 2024 no longer covers.

crate::impl_field_binary_pyslot! {
    /// `field + other` — element-wise sum.
    [PyNodeField], __add__, |a, b| a + b,
    /// `scalar + field` — the mirror of `field + scalar`. Any other left operand is
    /// refused (`TypeError`).
    __radd__, |v, s| s + v
}
crate::impl_subfield_binary_pyslot! {
    /// `field + other` — element-wise sum.
    [PySubNodeField], __add__, |a, b| a + b,
    /// `scalar + field` — the mirror of `field + scalar`. Any other left operand is
    /// refused (`TypeError`).
    __radd__, |v, s| s + v
}
crate::impl_field_binary_pyslot! {
    /// `field - other` — element-wise difference.
    [PyNodeField], __sub__, |a, b| a - b,
    /// `scalar - field` — the scalar minus every value. Any other left operand is
    /// refused (`TypeError`).
    __rsub__, |v, s| s - v
}
crate::impl_subfield_binary_pyslot! {
    /// `field - other` — element-wise difference.
    [PySubNodeField], __sub__, |a, b| a - b,
    /// `scalar - field` — the scalar minus every value. Any other left operand is
    /// refused (`TypeError`).
    __rsub__, |v, s| s - v
}
crate::impl_field_binary_pyslot! {
    /// `field * other` — element-wise product.
    [PyNodeField], __mul__, |a, b| a * b,
    /// `scalar * field` — the mirror of `field * scalar`. Any other left
    /// operand is refused (`TypeError`).
    __rmul__, |v, s| s * v
}
crate::impl_subfield_binary_pyslot! {
    /// `field * other` — element-wise product.
    [PySubNodeField], __mul__, |a, b| a * b,
    /// `scalar * field` — the mirror of `field * scalar`. Any other left
    /// operand is refused (`TypeError`).
    __rmul__, |v, s| s * v
}
crate::impl_field_binary_pyslot! {
    /// `field / other` — element-wise quotient.
    [PyNodeField], __truediv__, |a, b| a / b,
    /// `scalar / field` — the scalar divided by every value (`inf` on a zero). Any other left operand is
    /// refused (`TypeError`).
    __rtruediv__, |v, s| s / v
}
crate::impl_subfield_binary_pyslot! {
    /// `field / other` — element-wise quotient.
    [PySubNodeField], __truediv__, |a, b| a / b,
    /// `scalar / field` — the scalar divided by every value (`inf` on a zero). Any other left operand is
    /// refused (`TypeError`).
    __rtruediv__, |v, s| s / v
}
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pymethods)]
#[pymethods]
impl PyNodeField {
    /// `field ** exponent` — element-wise power, same dispatch as the other
    /// operators (float → scalar, `NodeField` → per support and component,
    /// union with passthrough, `SubNodeField` → targeted zone). The ternary
    /// `pow(x, y, z)` modulo form is rejected.
    fn __pow__(&self, exponent: &Bound<'_, PyAny>, modulo: &Bound<'_, PyAny>) -> PyResult<Self> {
        crate::py::field_slots::reject_modulo(modulo)?;
        self.binary(exponent, |a, b| a.powf(b))
    }

    /// `scalar ** field` — the scalar raised to every value. Any other left
    /// operand is refused (`TypeError`), and so is a modulo.
    fn __rpow__(&self, base: f64, modulo: &Bound<'_, PyAny>) -> PyResult<Self> {
        crate::py::field_slots::reject_modulo(modulo)?;
        Ok(Self {
            inner: crate::containers::field::Field::combine_scalar(
                &self.inner,
                |v, s| s.powf(v),
                base,
            )?,
        })
    }

    /// `-field` — every value negated, in a new field.
    fn __neg__(&self) -> PyResult<Self> {
        Ok(Self {
            inner: crate::containers::field::Field::map_all(&self.inner, |v| -v)?,
        })
    }
}

#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pymethods)]
#[pymethods]
impl PySubNodeField {
    /// `field ** exponent` — element-wise power, same dispatch as the other
    /// operators (float exponent → broadcast; `SubNodeField` on the same
    /// support → per-component union with passthrough). The ternary
    /// `pow(x, y, z)` modulo form is rejected (meaningless on floats).
    fn __pow__(&self, exponent: &Bound<'_, PyAny>, modulo: &Bound<'_, PyAny>) -> PyResult<Self> {
        crate::py::field_slots::reject_modulo(modulo)?;
        self.scalar_or_combine(exponent, |a, b| a.powf(b))
    }

    /// `scalar ** field` — the scalar raised to every value. Any other left
    /// operand is refused (`TypeError`), and so is a modulo.
    fn __rpow__(&self, base: f64, modulo: &Bound<'_, PyAny>) -> PyResult<Self> {
        crate::py::field_slots::reject_modulo(modulo)?;
        let out = crate::containers::field::SubField::map_all(&*self.handle.read(), move |v| {
            base.powf(v)
        });
        Ok(Self {
            handle: crate::handle::Handle::new(out),
        })
    }

    /// `-field` — every value negated, in a new sub-field.
    fn __neg__(&self) -> Self {
        let out = crate::containers::field::SubField::map_all(&*self.handle.read(), |v| -v);
        Self {
            handle: crate::handle::Handle::new(out),
        }
    }
}

// ─── Comparaisons ───────────────────────────────────────────────────────────
//
// A slot too, hence put here, and written by hand: it has one shape and cannot
// have another. What it shares with its three twins is its semantics, not its
// shape — `field_slots::band_of` says which value band a comparison stands for.
//
// Its block is **not** decorated with `gen_stub_pymethods`: CPython exposes these
// comparisons under the names `__ge__`/`__gt__`/`__le__`/`__lt__`, already
// declared by hand in the stub — generating them here would count them twice.

#[pymethods]
impl PyNodeField {
    /// Comparison sugar → a per-component 0/1 mask (see `mask`). `field >= x`
    /// / `> x` / `<= x` / `< x` test every component against the scalar `x`;
    /// `==` / `!=` and non-scalar right-hands fall back to `NotImplemented`.
    fn __richcmp__(
        &self,
        py: Python<'_>,
        other: &Bound<'_, PyAny>,
        op: pyo3::pyclass::CompareOp,
    ) -> PyResult<Py<PyAny>> {
        let Some(band) = crate::py::field_slots::band_of(op, other)? else {
            return Ok(py.NotImplemented());
        };
        let out = crate::ops::node_field::mask(&self.inner, &band, None)?;
        Ok(Py::new(py, Self { inner: out })?.into_any())
    }
}

#[pymethods]
impl PySubNodeField {
    /// Comparison sugar → a per-component 0/1 mask (see `mask`). `subfield >= x`
    /// / `> x` / `<= x` / `< x` test every component against the scalar `x`;
    /// `==` / `!=` and non-scalar right-hands fall back to `NotImplemented`.
    fn __richcmp__(
        &self,
        py: Python<'_>,
        other: &Bound<'_, PyAny>,
        op: pyo3::pyclass::CompareOp,
    ) -> PyResult<Py<PyAny>> {
        let Some(band) = crate::py::field_slots::band_of(op, other)? else {
            return Ok(py.NotImplemented());
        };
        // `mask_sub` returns no `Result` — the zone stands alone, there is no
        // aggregate to rebuild, hence nothing to refuse.
        let out = crate::ops::node_field::mask_sub(&self.handle.read(), &band, None);
        Ok(Py::new(
            py,
            Self {
                handle: Handle::new(out),
            },
        )?
        .into_any())
    }
}