pyrucast 0.9.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
//! Value-range selection — extract, zone by zone, the part of a field's
//! support whose values fall inside a `[lower, upper]` band (see
//! [`Band`], built from `ge` / `gt` / `le` / `lt`).
//!
//! The two entry points mirror the two field flavours and the two kinds
//! of support they carry:
//!
//! - [`select_nodes`] over a [`NodeField`]: each zone yields a **POI1
//!   `SubMesh`** holding the nodes that pass the test;
//! - [`select_cells`] over an [`ElementField`]: each zone yields a
//!   `SubMesh` of the zone's **own element type** holding the cells that
//!   pass — a cell passes only when **every** Gauss point does (the band
//!   must hold all along the cell).
//!
//! Both return a [`Mesh`] with **one submesh per processed zone**
//! ([[feedback-viz-per-element]] — zones stay separate, nothing merged).
//! The structure is therefore parallel to the input field, minus the
//! zones skipped by the component filter.
//!
//! # Component filter
//!
//! - `components = None` ⇒ test **every** component of each zone;
//! - `components = Some(list)` ⇒ test **only** those components, and only
//!   on the zones that carry **all** of them. A zone missing any listed
//!   component is skipped entirely (it produces no submesh).
//!
//! Within a retained point/cell the bounds are combined with **AND**: the
//! point is kept only if *each* tested component lies in the band.
//!
//! # Example
//!
//! Isolate the plastified region of a beam — the cells whose cumulated
//! plastic strain `p` exceeds a threshold — by building a one-sided
//! [`Band`] (`p > 0.02`, upper side left open) and handing it to
//! [`select_cells`]:
//!
//! ```ignore
//! use pyrucast::ops::field::band::Band;
//! use pyrucast::ops::field::select::select_cells;
//!
//! // `p > 0.02`, no upper bound: `gt = Some(0.02)`, everything else `None`.
//! let band = Band::new(None, Some(0.02), None, None)?;
//!
//! // Test only the `p` component; zones lacking it are skipped.
//! let plastified = select_cells(&state, &band, Some(vec!["p".into()]))?;
//! ```
//!
//! Use `ge`/`le` for inclusive bounds and give both sides for a closed
//! band, e.g. `Band::new(Some(0.0), None, Some(1.0), None)` for `0 <= v <= 1`.

use crate::aggregate::Aggregate;
use crate::atoms::NodeId;
use crate::containers::element_field::{ElementField, SubElementField};
use crate::containers::field::SubField;
use crate::containers::mesh::{Mesh, SubMesh};
use crate::containers::node_field::{NodeField, SubNodeField};
use crate::error::Result;
use crate::handle::Handle;

use crate::atoms::Band;

/// Indices, into a zone's component list, of the components to test.
///
/// `None` ⇒ the filter names a component the zone does not carry (callers
/// decide what that means: [`select`](self) skips the zone, [`mask`](super::mask)
/// leaves it identity). With no filter, every component is tested.
pub(crate) fn components_to_test(
    zone: &[String],
    requested: &Option<Vec<String>>,
) -> Option<Vec<usize>> {
    match requested {
        None => Some((0..zone.len()).collect()),
        Some(names) => {
            let mut idx = Vec::with_capacity(names.len());
            for name in names {
                idx.push(zone.iter().position(|c| c == name)?);
            }
            Some(idx)
        }
    }
}

// ─── Per-zone builders ──────────────────────────────────────────────────────

/// POI1 submesh of the nodes of `sub` passing the band on every tested
/// component. `None` when the component filter skips this zone.
fn sub_node_submesh(
    sub: &SubNodeField,
    band: &Band,
    components: &Option<Vec<String>>,
) -> Result<Option<SubMesh>> {
    let comps = SubField::components(sub);
    let test = match components_to_test(comps, components) {
        Some(t) => t,
        None => return Ok(None),
    };
    let ncomp = comps.len();
    let values = sub.values();
    let mut kept: Vec<NodeId> = Vec::new();
    // Node ids read in place, then the guard is released: building the POI1
    // below write-locks the `Coords`.
    {
        let support = sub.support();
        let support = support.read();
        for (ni, &nid) in sub.nodes_with(&support).iter().enumerate() {
            let row = &values[ni * ncomp..(ni + 1) * ncomp];
            if test.iter().all(|&ci| band.contains(row[ci])) {
                kept.push(nid);
            }
        }
    }
    Ok(Some(SubMesh::poi1_from_node_ids(sub.coords(), &kept)?))
}

/// Submesh (zone's own element type) of the cells of `sub` whose **every**
/// Gauss point passes the band on every tested component. `None` when the
/// component filter skips this zone.
fn sub_element_submesh(
    sub: &SubElementField,
    band: &Band,
    components: &Option<Vec<String>>,
) -> Result<Option<SubMesh>> {
    let comps = SubField::components(sub);
    let test = match components_to_test(comps, components) {
        Some(t) => t,
        None => return Ok(None),
    };
    let ncomp = comps.len();
    let ngauss = sub.gauss_count();
    let ncells = sub.cell_count();
    let values = sub.values();

    // Underlying mesh of the FE subspace — read its connectivity once.
    let smh = SubField::support(sub).read().submesh();
    let smr = smh.read();
    let et = smr.element_type();
    let npc = et.nodes_per_cell();
    let conn = smr.connectivity();
    let coords = smr.coords();
    // The kept cells are gathered whole, then posted in one locked pass.
    let mut kept: Vec<NodeId> = Vec::new();
    for cell in 0..ncells {
        let pass = (0..ngauss).all(|g| {
            let base = (cell * ngauss + g) * ncomp;
            test.iter().all(|&ci| band.contains(values[base + ci]))
        });
        if pass {
            kept.extend_from_slice(&conn[cell * npc..(cell + 1) * npc]);
        }
    }
    drop(smr);
    Ok(Some(SubMesh::from_connectivity(coords, et, kept)?))
}

// ─── Public operators ───────────────────────────────────────────────────────

/// Select the nodes of `field` passing `band`, zone by zone. Returns a
/// [`Mesh`] of POI1 submeshes — one per processed zone.
///
/// See the [module documentation](self) for the component-filter and
/// AND-across-components semantics.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{Band, ElementType, Node};
/// # use pyrucast::containers::element_field::{ElementField, SubElementField};
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::node_field::NodeField;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::ops::mesh::{self, select};
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let maillage = Mesh::from_submesh(sm);
/// # let support = mesh::poi1_from_nodes(&n).unwrap();
/// # let temp = NodeField::from_submesh(&support.get(0).unwrap(), vec!["T".into()]).unwrap();
/// # {
/// #     let mut z = temp.get(0).unwrap().write();
/// #     z.set_value(n[0].id(), "T", 10.0).unwrap();
/// #     z.set_value(n[1].id(), "T", 50.0).unwrap();
/// #     z.set_value(n[2].id(), "T", 90.0).unwrap();
/// # }
/// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
/// # let mut flux = ElementField::new(&fes, vec!["q".into()]).unwrap();
/// # flux.get(0).unwrap().write().set_uniform("q", 5.0).unwrap();
/// # let bande = Band::new(Some(40.0), None, None, None).unwrap();
/// // The nodes with T ≥ 40: two out of three. The result is a POI1 mesh, one
/// // zone per processed zone.
/// let chauds = select::select_nodes(&temp, &bande, None)?;
/// assert_eq!(chauds.cell_count(), 2);
/// assert_eq!(chauds.element_types()?, vec![ElementType::POI1]);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn select_nodes(
    field: &NodeField,
    band: &Band,
    components: Option<Vec<String>>,
) -> Result<Mesh> {
    let mut out = Mesh::empty();
    for h in field.iter() {
        if let Some(sm) = sub_node_submesh(&h.read(), band, &components)? {
            out.add_sub(Handle::new(sm))?;
        }
    }
    Ok(out)
}

/// Select the cells of `field` passing `band`, zone by zone. A cell is kept
/// only when **all** its Gauss points pass. Returns a [`Mesh`] of submeshes
/// (each of its zone's element type) — one per processed zone.
///
/// See the [module documentation](self) for the component-filter and
/// AND semantics.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{Band, ElementType, Node};
/// # use pyrucast::containers::element_field::{ElementField, SubElementField};
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::node_field::NodeField;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::ops::mesh::{self, select};
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let maillage = Mesh::from_submesh(sm);
/// # let support = mesh::poi1_from_nodes(&n).unwrap();
/// # let temp = NodeField::from_submesh(&support.get(0).unwrap(), vec!["T".into()]).unwrap();
/// # {
/// #     let mut z = temp.get(0).unwrap().write();
/// #     z.set_value(n[0].id(), "T", 10.0).unwrap();
/// #     z.set_value(n[1].id(), "T", 50.0).unwrap();
/// #     z.set_value(n[2].id(), "T", 90.0).unwrap();
/// # }
/// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
/// # let mut flux = ElementField::new(&fes, vec!["q".into()]).unwrap();
/// # flux.get(0).unwrap().write().set_uniform("q", 5.0).unwrap();
/// # let bande = Band::new(Some(40.0), None, None, None).unwrap();
/// // A cell is retained only if **all** its Gauss points pass.
/// let forte = Band::new(Some(1.0), None, None, None)?;
/// assert_eq!(select::select_cells(&flux, &forte, None)?.cell_count(), 1);
/// let trop = Band::new(Some(10.0), None, None, None)?;
/// assert_eq!(select::select_cells(&flux, &trop, None)?.cell_count(), 0);
/// // And the zone keeps its element type, not POI1.
/// assert_eq!(select::select_cells(&flux, &forte, None)?.element_types()?,
///            vec![ElementType::TRI3]);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn select_cells(
    field: &ElementField,
    band: &Band,
    components: Option<Vec<String>>,
) -> Result<Mesh> {
    let mut out = Mesh::empty();
    for h in field.iter() {
        if let Some(sm) = sub_element_submesh(&h.read(), band, &components)? {
            out.add_sub(Handle::new(sm))?;
        }
    }
    Ok(out)
}

/// Single-zone [`select_nodes`] — a [`Mesh`] with one POI1 submesh, or an
/// empty mesh when the component filter skips the zone.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{Band, ElementType, Node};
/// # use pyrucast::containers::element_field::{ElementField, SubElementField};
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::node_field::NodeField;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::ops::mesh::{self, select};
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let maillage = Mesh::from_submesh(sm);
/// # let support = mesh::poi1_from_nodes(&n).unwrap();
/// # let temp = NodeField::from_submesh(&support.get(0).unwrap(), vec!["T".into()]).unwrap();
/// # {
/// #     let mut z = temp.get(0).unwrap().write();
/// #     z.set_value(n[0].id(), "T", 10.0).unwrap();
/// #     z.set_value(n[1].id(), "T", 50.0).unwrap();
/// #     z.set_value(n[2].id(), "T", 90.0).unwrap();
/// # }
/// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
/// # let mut flux = ElementField::new(&fes, vec!["q".into()]).unwrap();
/// # flux.get(0).unwrap().write().set_uniform("q", 5.0).unwrap();
/// # let bande = Band::new(Some(40.0), None, None, None).unwrap();
/// // The single-zone form: a mesh with one POI1 submesh only.
/// let chauds = select::select_sub_nodes(&temp.get(0)?.read(), &bande, None)?;
/// assert_eq!(chauds.len(), 1);
/// assert_eq!(chauds.cell_count(), 2);
/// // A component filter that does not apply to the zone skips it, and returns
/// // an **empty** mesh rather than an error.
/// let absente = select::select_sub_nodes(
///     &temp.get(0)?.read(), &bande, Some(vec!["u_x".into()]))?;
/// assert!(absente.is_empty());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn select_sub_nodes(
    sub: &SubNodeField,
    band: &Band,
    components: Option<Vec<String>>,
) -> Result<Mesh> {
    let mut out = Mesh::empty();
    if let Some(sm) = sub_node_submesh(sub, band, &components)? {
        out.add_sub(Handle::new(sm))?;
    }
    Ok(out)
}

/// Single-zone [`select_cells`] — a [`Mesh`] with one submesh, or an empty
/// mesh when the component filter skips the zone.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{Band, ElementType, Node};
/// # use pyrucast::containers::element_field::{ElementField, SubElementField};
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::node_field::NodeField;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::ops::mesh::{self, select};
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let maillage = Mesh::from_submesh(sm);
/// # let support = mesh::poi1_from_nodes(&n).unwrap();
/// # let temp = NodeField::from_submesh(&support.get(0).unwrap(), vec!["T".into()]).unwrap();
/// # {
/// #     let mut z = temp.get(0).unwrap().write();
/// #     z.set_value(n[0].id(), "T", 10.0).unwrap();
/// #     z.set_value(n[1].id(), "T", 50.0).unwrap();
/// #     z.set_value(n[2].id(), "T", 90.0).unwrap();
/// # }
/// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
/// # let mut flux = ElementField::new(&fes, vec!["q".into()]).unwrap();
/// # flux.get(0).unwrap().write().set_uniform("q", 5.0).unwrap();
/// # let bande = Band::new(Some(40.0), None, None, None).unwrap();
/// let forte = Band::new(Some(1.0), None, None, None)?;
/// let zone = flux.get(0)?;
/// let retenues = select::select_sub_cells(&zone.read(), &forte, None)?;
/// assert_eq!(retenues.cell_count(), 1);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn select_sub_cells(
    sub: &SubElementField,
    band: &Band,
    components: Option<Vec<String>>,
) -> Result<Mesh> {
    let mut out = Mesh::empty();
    if let Some(sm) = sub_element_submesh(sub, band, &components)? {
        out.add_sub(Handle::new(sm))?;
    }
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::atoms::{ElementType, Node};
    use crate::containers::element_field::ElementField;
    use crate::containers::finite_element_space::FiniteElementSpace;
    use crate::containers::mesh::{Mesh, SubMesh};
    use crate::containers::node_field::{NodeField, SubNodeField};
    use crate::coords::Coords;
    use crate::handle::Handle;

    /// Single-zone POI1 NodeField over `n` 1-D nodes; returns (nodes, field).
    fn poi1_field(n: usize, components: Vec<String>) -> (Vec<Node>, NodeField) {
        let coords = Handle::new(Coords::new(1).unwrap());
        let nodes: Vec<Node> = (0..n)
            .map(|i| Node::create_in(coords.clone(), &[i as f64]).unwrap())
            .collect();
        let mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
        for nd in &nodes {
            sm.add_cell(&[nd.id()]).unwrap();
        }
        let field =
            NodeField::from_sub(SubNodeField::from_poi1(&Handle::new(sm), components).unwrap());
        (nodes, field)
    }

    /// Node ids of the (single) zone of a selection mesh, in order.
    fn picked(mesh: &Mesh, zone: usize) -> Vec<NodeId> {
        mesh.get(zone).unwrap().read().connectivity().to_vec()
    }

    #[test]
    fn select_nodes_min_max_band() {
        let (nodes, f) = poi1_field(5, vec!["T".into()]);
        {
            let mut s = f.get(0).unwrap().write();
            for i in 0..5 {
                s.set(i, 0, i as f64 * 10.0).unwrap(); // 0,10,20,30,40
            }
        }
        // 10 <= T <= 30 → nodes 1,2,3.
        let sel = select_nodes(
            &f,
            &Band::new(Some(10.0), None, Some(30.0), None).unwrap(),
            None,
        )
        .unwrap();
        assert_eq!(sel.len(), 1);
        let ids = picked(&sel, 0);
        assert_eq!(ids, vec![nodes[1].id(), nodes[2].id(), nodes[3].id()]);
    }

    #[test]
    fn select_nodes_open_bounds() {
        let (nodes, f) = poi1_field(3, vec!["T".into()]);
        {
            let mut s = f.get(0).unwrap().write();
            s.set(0, 0, -1.0).unwrap();
            s.set(1, 0, 5.0).unwrap();
            s.set(2, 0, 9.0).unwrap();
        }
        // Only an upper bound: T <= 5 → nodes 0,1.
        let sel = select_nodes(&f, &Band::new(None, None, Some(5.0), None).unwrap(), None).unwrap();
        assert_eq!(picked(&sel, 0), vec![nodes[0].id(), nodes[1].id()]);
        // Only a lower bound: T >= 5 → nodes 1,2.
        let sel = select_nodes(&f, &Band::new(Some(5.0), None, None, None).unwrap(), None).unwrap();
        assert_eq!(picked(&sel, 0), vec![nodes[1].id(), nodes[2].id()]);
    }

    #[test]
    fn select_nodes_all_components_and_semantics() {
        let (nodes, f) = poi1_field(3, vec!["U".into(), "V".into()]);
        {
            let mut s = f.get(0).unwrap().write();
            // node0: U=1 V=1 ; node1: U=1 V=9 ; node2: U=1 V=2
            s.set(0, 0, 1.0).unwrap();
            s.set(0, 1, 1.0).unwrap();
            s.set(1, 0, 1.0).unwrap();
            s.set(1, 1, 9.0).unwrap();
            s.set(2, 0, 1.0).unwrap();
            s.set(2, 1, 2.0).unwrap();
        }
        // 0 <= * <= 5 on BOTH components → node1 dropped (V=9).
        let sel = select_nodes(
            &f,
            &Band::new(Some(0.0), None, Some(5.0), None).unwrap(),
            None,
        )
        .unwrap();
        assert_eq!(picked(&sel, 0), vec![nodes[0].id(), nodes[2].id()]);
    }

    #[test]
    fn select_nodes_component_filter_restricts_test() {
        let (nodes, f) = poi1_field(3, vec!["U".into(), "V".into()]);
        {
            let mut s = f.get(0).unwrap().write();
            s.set(0, 0, 1.0).unwrap();
            s.set(0, 1, 1.0).unwrap();
            s.set(1, 0, 1.0).unwrap();
            s.set(1, 1, 9.0).unwrap();
            s.set(2, 0, 1.0).unwrap();
            s.set(2, 1, 2.0).unwrap();
        }
        // Test U only: U=1 everywhere ⇒ all kept despite V out of band.
        let sel = select_nodes(
            &f,
            &Band::new(Some(0.0), None, Some(5.0), None).unwrap(),
            Some(vec!["U".into()]),
        )
        .unwrap();
        assert_eq!(
            picked(&sel, 0),
            vec![nodes[0].id(), nodes[1].id(), nodes[2].id()]
        );
    }

    #[test]
    fn select_nodes_skips_zone_missing_requested_component() {
        // Two zones: zone0 has "T", zone1 has "P".
        let coords = Handle::new(Coords::new(1).unwrap());
        let n: Vec<Node> = (0..2)
            .map(|i| Node::create_in(coords.clone(), &[i as f64]).unwrap())
            .collect();
        let mk = |nid: NodeId, comp: &str| {
            let mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
            sm.add_cell(&[nid]).unwrap();
            SubNodeField::from_poi1(&Handle::new(sm), vec![comp.into()]).unwrap()
        };
        let f = NodeField::from_sub(mk(n[0].id(), "T"))
            .union(&NodeField::from_sub(mk(n[1].id(), "P")))
            .unwrap();
        assert_eq!(f.len(), 2);
        // Filter on "T": only zone0 is processed → one submesh out.
        let sel = select_nodes(
            &f,
            &Band::new(Some(-1e9), None, Some(1e9), None).unwrap(),
            Some(vec!["T".into()]),
        )
        .unwrap();
        assert_eq!(sel.len(), 1);
        assert_eq!(picked(&sel, 0), vec![n[0].id()]);
    }

    #[test]
    fn select_nodes_empty_selection_keeps_empty_zone() {
        let (_nodes, f) = poi1_field(3, vec!["T".into()]); // all zero
        let sel = select_nodes(
            &f,
            &Band::new(Some(100.0), None, Some(200.0), None).unwrap(),
            None,
        )
        .unwrap();
        assert_eq!(sel.len(), 1, "processed zone still yields a submesh");
        assert_eq!(sel.get(0).unwrap().read().cell_count(), 0);
    }

    /// One TRI3 + one QUA4 zone, lagrange-1; returns the ElementField.
    fn two_zone_element_field() -> (Vec<Node>, ElementField) {
        let coords = Handle::new(Coords::new(2).unwrap());
        #[rustfmt::skip]
        let n: Vec<Node> = [
            [0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [2.0, 0.0], [2.0, 1.0],
        ]
        .iter()
        .map(|p| Node::create_in(coords.clone(), p).unwrap())
        .collect();
        let mut mesh = Mesh::empty();
        let tri = {
            let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
            sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
            Handle::new(sm)
        };
        let qua = {
            let mut sm = SubMesh::new(coords.clone(), ElementType::QUA4);
            sm.add_cell(&[n[1].id(), n[3].id(), n[4].id(), n[2].id()])
                .unwrap();
            Handle::new(sm)
        };
        mesh.add_sub(tri).unwrap();
        mesh.add_sub(qua).unwrap();
        let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
        let ef = ElementField::new(&fes, vec!["s".into()]).unwrap();
        (n, ef)
    }

    #[test]
    fn select_cells_all_gauss_must_pass() {
        let (_n, ef) = two_zone_element_field();
        // Zone0 (TRI3): s = 2 everywhere → in band [0,5].
        ef.get(0).unwrap().write().set_uniform("s", 2.0).unwrap();
        // Zone1 (QUA4): one Gauss point at 100 → cell fails.
        {
            let mut s = ef.get(1).unwrap().write();
            s.set_uniform("s", 2.0).unwrap();
            s.set_value(0, 0, "s", 100.0).unwrap();
        }
        let sel = select_cells(
            &ef,
            &Band::new(Some(0.0), None, Some(5.0), None).unwrap(),
            None,
        )
        .unwrap();
        assert_eq!(sel.len(), 2, "one submesh per zone");
        // TRI3 cell kept, QUA4 cell dropped.
        assert_eq!(sel.get(0).unwrap().read().cell_count(), 1);
        assert_eq!(sel.get(0).unwrap().read().element_type(), ElementType::TRI3);
        assert_eq!(sel.get(1).unwrap().read().cell_count(), 0);
        assert_eq!(sel.get(1).unwrap().read().element_type(), ElementType::QUA4);
    }
}