pyrucast 0.14.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
//! A field carried onto the nodes of another mesh: a nodal field through the
//! shape functions of the cells that interpolate it ([`project_node`]) — Cast3M
//! `PROI` onto a geometry —, a field at the Gauss points through each cell's own
//! fit of its values ([`project_element`]).

use std::collections::HashMap;

use crate::aggregate::Aggregate;
use crate::atoms::NodeId;
use crate::containers::element_field::ElementField;
use crate::containers::field::{Field, SubField};
use crate::containers::mesh::Mesh;
use crate::containers::node_field::{NodeField, SubNodeField};
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use crate::ops::element_field::fit::CellFit;
use crate::ops::geom::{locate_points, Location};
use crate::parallel::*;

/// `field` interpolated by the cells of `mesh` at the nodes of `target`: a node
/// of `target` that sits in a cell of `mesh` takes `Σᵢ Nᵢ(ξ) f(nodeᵢ)`, the
/// shape functions of that cell at the node's reference coordinates `ξ` —
/// quadratic cells interpolate quadratically. Every component of `field` is
/// carried.
///
/// A node of `target` outside `mesh` — farther than `tol` outside every
/// cell's reference domain — gets zero, as a nodal field reads a node it does
/// not define: projecting a patch onto a larger mesh is a normal thing. `tol`
/// is that reference-domain slack, without unit; the Python face defaults it
/// to `1e-6`, as for `embedded`. A point on a face shared by two cells is read in the first one,
/// which gives the same value for a continuous field.
///
/// `field` is read through its zones, first zone wins, and a node of `mesh`
/// it does not define reads zero. `mesh` and `target` may live in different
/// `Coords` — moving a field onto a remeshed part —, each read in its active
/// configuration. The result has one zone per submesh of `target`, like
/// [`positions`](fn@crate::ops::node_field::positions).
///
/// An empty `field` or `target` gives an empty field: nothing to carry, or
/// nowhere to carry it. An empty `mesh` holds no node of `target`: every one
/// gets zero.
///
/// Errors: `field` and `mesh` on different `Coords` (the field's nodes are the
/// ones `mesh`'s cells interpolate); `mesh` and `target` in different
/// dimensions.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::node_field::NodeField;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::ops::{mesh, node_field};
/// // A temperature T = 10 + 20 x on a triangle…
/// let coords = Handle::new(Coords::new(2)?);
/// let n: Vec<Node> = [[0.0, 0.0], [2.0, 0.0], [0.0, 2.0]]
///     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()])?;
/// let triangle = Mesh::from_submesh(sm);
/// let t = NodeField::new(&triangle, vec!["T".into()])?;
/// for (node, x) in n.iter().zip([0.0, 2.0, 0.0]) {
///     t.get(0)?.write().set_value(node.id(), "T", 10.0 + 20.0 * x)?;
/// }
/// // …carried onto two points of another `Coords`, the second outside.
/// let other = Handle::new(Coords::new(2)?);
/// let p: Vec<Node> = [[0.5, 0.5], [5.0, 5.0]]
///     .iter().map(|q| Node::create_in(other.clone(), q).unwrap()).collect();
/// let points = mesh::poi1_from_nodes(&p)?;
/// let carried = node_field::project_node(&t, &triangle, &points, 1e-6)?;
/// let z = carried.get(0)?.read();
/// assert!((z.value(p[0].id(), "T")? - 20.0).abs() < 1e-12);
/// assert_eq!(z.value(p[1].id(), "T")?, 0.0); // outside: zero, a patch
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn project_node(field: &NodeField, mesh: &Mesh, target: &Mesh, tol: f64) -> Result<NodeField> {
    let components = Field::components(field);
    if components.is_empty() || target.is_empty() {
        return Ok(NodeField::default());
    }
    // A mesh without zones locates nothing: every node of `target` reads zero.
    if !mesh.is_empty() {
        if !mesh.coords()?.same_object(&field.coords()?) {
            return Err(PyrucastError::Message(
                "project: `field` and `mesh` hang from different Coords — the cells of \
                 `mesh` interpolate the field from its own nodes"
                    .into(),
            ));
        }
        same_dimension(mesh, target)?;
    }
    let (index, points) = distinct_points(target)?;
    let locations = locate_points(mesh, &points, tol)?;

    // The values at every distinct node, node-major: each slot written once.
    let n_comp = components.len();
    let view = field.view();
    let reads = view.resolve_reads(&components);
    let mut values = vec![0.0; points.len() * n_comp];
    values
        .par_chunks_mut(n_comp)
        .zip(locations.par_iter())
        .with_min_len(MIN_PARALLEL_LEN)
        .for_each_init(Vec::new, |cell, (out, location)| {
            if let Some(Location { weights, nodes, .. }) = location {
                cell.resize(nodes.len() * n_comp, 0.0);
                view.gather_cell(nodes, &reads, cell);
                for (k, w) in weights.iter().enumerate() {
                    for (o, v) in out.iter_mut().zip(&cell[k * n_comp..(k + 1) * n_comp]) {
                        *o += w * v;
                    }
                }
            }
        });
    on_target(target, &components, &index, &values)
}

/// A field at the Gauss points read at the nodes of `target`: a node of
/// `target` that sits in a cell of `mesh` takes the value that cell's **own**
/// Gauss points give there — their least-squares fit on the cell, the one a
/// plot colours the cell with, evaluated at the node's reference coordinates
/// `ξ`. Nothing is averaged between cells: where two neighbours disagree, a
/// line of points crossing from one to the other shows the jump. A point on a
/// face shared by two cells is read in the first one found; to follow a
/// field along a line, put the points between the nodes.
///
/// `mesh` is the field's own cells: each of its submeshes must carry a zone
/// of `field`. A zone lacking one of the field's components reads zero for it.
/// A node of `target` outside `mesh` gets zero, every node of `target` once, as
/// for [`project_node`]; the result has one zone per submesh of `target`.
///
/// Errors: a submesh of `mesh` with no zone of `field`; `mesh` and `target` in
/// different dimensions.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::ElementField;
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::ops::{mesh, node_field};
/// // Two squares side by side, a stress of 1 in the left one and 5 in the right.
/// let coords = Handle::new(Coords::new(2)?);
/// let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [2.0, 0.0], [0.0, 1.0], [1.0, 1.0], [2.0, 1.0]]
///     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// let mut sm = SubMesh::new(coords.clone(), ElementType::QUA4);
/// sm.add_cell(&[n[0].id(), n[1].id(), n[4].id(), n[3].id()])?;
/// sm.add_cell(&[n[1].id(), n[2].id(), n[5].id(), n[4].id()])?;
/// let squares = Mesh::from_submesh(sm);
/// let fes = FiniteElementSpace::lagrange1(&squares)?;
/// let s = ElementField::new(&fes, vec!["s".into()])?;
/// s.get(0)?.write().set_cell_uniform(0, "s", 1.0)?;
/// s.get(0)?.write().set_cell_uniform(1, "s", 5.0)?;
/// // Read on either side of the shared edge: each side keeps its own value.
/// let other = Handle::new(Coords::new(2)?);
/// let p: Vec<Node> = [[0.9, 0.5], [1.1, 0.5]]
///     .iter().map(|q| Node::create_in(other.clone(), q).unwrap()).collect();
/// let read = node_field::project_element(&s, &squares, &mesh::poi1_from_nodes(&p)?, 1e-6)?;
/// let z = read.get(0)?.read();
/// assert!((z.value(p[0].id(), "s")? - 1.0).abs() < 1e-12);
/// assert!((z.value(p[1].id(), "s")? - 5.0).abs() < 1e-12);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn project_element(
    field: &ElementField,
    mesh: &Mesh,
    target: &Mesh,
    tol: f64,
) -> Result<NodeField> {
    let components = Field::components(field);
    if components.is_empty() || target.is_empty() {
        return Ok(NodeField::default());
    }
    if !mesh.is_empty() {
        same_dimension(mesh, target)?;
    }

    // Per submesh of `mesh`: the zone living on it, the fit of its space, and
    // where each of the field's components sits in it — all resolved once.
    struct Host<'v> {
        values: &'v [f64],
        stride: usize,
        n_gauss: usize,
        fit: CellFit,
        reads: Vec<(usize, usize)>,
    }
    let view = field.view();
    let mut hosts = Vec::with_capacity(mesh.len());
    for (s, sm) in mesh.into_iter().enumerate() {
        let zone = view.zone_for_submesh(sm).ok_or_else(|| {
            PyrucastError::Message(format!(
                "project: submesh {s} of `mesh` carries no zone of the field — `mesh` must be \
                 the cells the field lives on"
            ))
        })?;
        let fit = CellFit::for_space(&zone.support().read())?;
        let reads = components
            .iter()
            .enumerate()
            .filter_map(|(k, c)| zone.component_index(c).map(|i| (k, i)))
            .collect();
        hosts.push(Host {
            values: zone.values(),
            stride: zone.components().len(),
            n_gauss: zone.gauss_count(),
            fit,
            reads,
        });
    }

    let (index, points) = distinct_points(target)?;
    let locations = locate_points(mesh, &points, tol)?;
    let n_comp = components.len();
    // Buffers sized once, to the largest zone: a point only takes its slice.
    let max_gauss = hosts.iter().map(|h| h.n_gauss).max().unwrap_or(0);
    let max_nodes = hosts
        .iter()
        .map(|h| h.fit.nodes_per_cell())
        .max()
        .unwrap_or(0);
    let mut values = vec![0.0; points.len() * n_comp];
    values
        .par_chunks_mut(n_comp)
        .zip(locations.par_iter())
        .with_min_len(MIN_PARALLEL_LEN)
        .for_each_init(
            || (vec![0.0; max_gauss], vec![0.0; max_nodes]),
            |(gauss_buffer, nodal_buffer), (out, location)| {
                // A point outside `mesh` keeps its 0s.
                if let Some(Location {
                    submesh,
                    cell,
                    weights,
                    ..
                }) = location
                {
                    let host = &hosts[*submesh];
                    let gauss = &mut gauss_buffer[..host.n_gauss];
                    let nodal = &mut nodal_buffer[..host.fit.nodes_per_cell()];
                    let first = cell * host.n_gauss * host.stride;
                    for &(k, i) in &host.reads {
                        for (g, slot) in gauss.iter_mut().enumerate() {
                            *slot = host.values[first + g * host.stride + i];
                        }
                        host.fit.nodal_values_into(gauss, nodal);
                        out[k] = weights.iter().zip(nodal.iter()).map(|(w, v)| w * v).sum();
                    }
                }
            },
        );
    on_target(target, &components, &index, &values)
}

/// `target` must live in the dimension of `mesh`.
fn same_dimension(mesh: &Mesh, target: &Mesh) -> Result<()> {
    let (dim, target_dim) = (mesh.coords()?.read().dim(), target.coords()?.read().dim());
    if dim != target_dim {
        return Err(PyrucastError::Message(format!(
            "project: `mesh` is {dim}-D and `target` {target_dim}-D"
        )));
    }
    Ok(())
}

/// The distinct nodes of `target`, each with its slot, and where they are.
#[allow(clippy::type_complexity)]
fn distinct_points(target: &Mesh) -> Result<(HashMap<NodeId, usize>, Vec<Vec<f64>>)> {
    let target_coords = target.coords()?;
    let mut index: HashMap<NodeId, usize> = HashMap::new();
    let mut points: Vec<Vec<f64>> = Vec::new();
    let c = target_coords.read();
    for sm in target {
        for &nid in sm.read().connectivity() {
            if let std::collections::hash_map::Entry::Vacant(e) = index.entry(nid) {
                e.insert(points.len());
                points.push(c.position(nid)?.to_vec());
            }
        }
    }
    Ok((index, points))
}

/// The node-major `values` laid on one zone per submesh of `target`.
fn on_target(
    target: &Mesh,
    components: &[String],
    index: &HashMap<NodeId, usize>,
    values: &[f64],
) -> Result<NodeField> {
    let n_comp = components.len();
    let mut out = NodeField::default();
    for sm in target {
        let mut sub = SubNodeField::from_support(sm, components.to_vec())?;
        let nodes = sub.node_ids();
        for (row, nid) in sub.values_mut().chunks_mut(n_comp).zip(&nodes) {
            let at = index[nid] * n_comp;
            row.copy_from_slice(&values[at..at + n_comp]);
        }
        out.add_sub(Handle::new(sub))?;
    }
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::atoms::{ElementType, Node};
    use crate::containers::mesh::SubMesh;
    use crate::coords::Coords;
    use crate::ops::mesh::poi1_from_nodes;

    /// An `n × n` grid of QUA4 on the unit square, and its nodes row by row.
    fn square(n: usize) -> (Mesh, Vec<Node>) {
        let coords = Handle::new(Coords::new(2).unwrap());
        let nodes: Vec<Node> = (0..=n)
            .flat_map(|j| (0..=n).map(move |i| (i, j)))
            .map(|(i, j)| {
                Node::create_in(coords.clone(), &[i as f64 / n as f64, j as f64 / n as f64])
                    .unwrap()
            })
            .collect();
        let at = |i: usize, j: usize| nodes[j * (n + 1) + i].id();
        let mut sm = SubMesh::new(coords, ElementType::QUA4);
        for j in 0..n {
            for i in 0..n {
                sm.add_cell(&[at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)])
                    .unwrap();
            }
        }
        (Mesh::from_submesh(sm), nodes)
    }

    /// The nodal field `f(x, y)` on `nodes`, one zone on `mesh`.
    fn sampled(mesh: &Mesh, nodes: &[Node], f: impl Fn(f64, f64) -> f64) -> NodeField {
        let field = NodeField::new(mesh, vec!["a".into(), "b".into()]).unwrap();
        {
            let mut z = field.get(0).unwrap().write();
            for n in nodes {
                let p = n.position().unwrap();
                z.set_value(n.id(), "a", f(p[0], p[1])).unwrap();
                z.set_value(n.id(), "b", -f(p[0], p[1])).unwrap();
            }
        }
        field
    }

    /// Points of a fresh `Coords`, as one POI1 zone.
    fn points(at: &[[f64; 2]]) -> (Mesh, Vec<Node>) {
        let coords = Handle::new(Coords::new(2).unwrap());
        let nodes: Vec<Node> = at
            .iter()
            .map(|p| Node::create_in(coords.clone(), p).unwrap())
            .collect();
        (poi1_from_nodes(&nodes).unwrap(), nodes)
    }

    /// A linear field is exact through bilinear cells, every component, on
    /// another `Coords`; a point off the square gets zero.
    #[test]
    fn a_linear_field_comes_back_exactly() {
        let (mesh, nodes) = square(3);
        let f = |x: f64, y: f64| 2.0 + 3.0 * x - 5.0 * y;
        let field = sampled(&mesh, &nodes, f);
        let at = [[0.1, 0.2], [0.5, 0.5], [0.97, 0.33], [1.0, 1.0], [1.5, 0.5]];
        let (target, targets) = points(&at);

        let carried = project_node(&field, &mesh, &target, 1e-6).unwrap();
        let z = carried.get(0).unwrap().read();
        for (node, p) in targets.iter().zip(&at[..4]) {
            assert!((z.value(node.id(), "a").unwrap() - f(p[0], p[1])).abs() < 1e-12);
            assert!((z.value(node.id(), "b").unwrap() + f(p[0], p[1])).abs() < 1e-12);
        }
        assert_eq!(z.value(targets[4].id(), "a").unwrap(), 0.0);
    }

    /// Through straight TRI6, a quadratic field is exact too.
    #[test]
    fn quadratic_cells_interpolate_quadratically() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let corners = [[0.0, 0.0], [2.0, 0.0], [0.0, 2.0]];
        let mids = [[1.0, 0.0], [1.0, 1.0], [0.0, 1.0]];
        let nodes: Vec<Node> = corners
            .iter()
            .chain(&mids)
            .map(|p| Node::create_in(coords.clone(), p).unwrap())
            .collect();
        let mut sm = SubMesh::new(coords, ElementType::TRI6);
        let ids: Vec<NodeId> = nodes.iter().map(Node::id).collect();
        sm.add_cell(&ids).unwrap();
        let mesh = Mesh::from_submesh(sm);
        let f = |x: f64, y: f64| x * x + x * y - 3.0 * y * y + 1.0;
        let field = sampled(&mesh, &nodes, f);
        let at = [[0.3, 0.4], [1.2, 0.5], [0.1, 1.7]];
        let (target, targets) = points(&at);

        let carried = project_node(&field, &mesh, &target, 1e-6).unwrap();
        let z = carried.get(0).unwrap().read();
        for (node, p) in targets.iter().zip(&at) {
            assert!((z.value(node.id(), "a").unwrap() - f(p[0], p[1])).abs() < 1e-12);
        }
    }

    /// `tol` is the slack beyond the reference element: a point just off the
    /// edge is caught with the usual 1e-6, left at zero with less.
    #[test]
    fn the_tolerance_catches_a_point_just_outside() {
        let (mesh, nodes) = square(1);
        let field = sampled(&mesh, &nodes, |x, _| 1.0 + x);
        // ξ = 2x − 1 = 1 + 4e-7 past the right edge.
        let (target, targets) = points(&[[1.0 + 2e-7, 0.5]]);
        let caught = project_node(&field, &mesh, &target, 1e-6).unwrap();
        let value = caught.get(0).unwrap().read().value(targets[0].id(), "a");
        assert!((value.unwrap() - 2.0).abs() < 1e-6);
        let missed = project_node(&field, &mesh, &target, 1e-8).unwrap();
        let value = missed.get(0).unwrap().read().value(targets[0].id(), "a");
        assert_eq!(value.unwrap(), 0.0);
    }

    /// One zone per submesh of `target`, a node they share carrying the same
    /// value in both; a field split in zones is read first zone first, and a
    /// node of `mesh` it does not define reads zero.
    #[test]
    fn zones_on_both_sides() {
        let (mesh, nodes) = square(1);
        // Zone 1 defines every node at 1; zone 0, read first, the left two at 3.
        let ones = NodeField::new(&mesh, vec!["a".into()]).unwrap();
        for n in &nodes {
            ones.get(0)
                .unwrap()
                .write()
                .set_value(n.id(), "a", 1.0)
                .unwrap();
        }
        let left = poi1_from_nodes(&[nodes[0].clone(), nodes[2].clone()]).unwrap();
        let threes = NodeField::new(&left, vec!["a".into()]).unwrap();
        for n in [&nodes[0], &nodes[2]] {
            threes
                .get(0)
                .unwrap()
                .write()
                .set_value(n.id(), "a", 3.0)
                .unwrap();
        }
        let mut field = NodeField::default();
        field.add_sub(threes.get(0).unwrap()).unwrap();
        field.add_sub(ones.get(0).unwrap()).unwrap();

        let coords = Handle::new(Coords::new(2).unwrap());
        let p: Vec<Node> = [[0.5, 0.0], [0.5, 0.5], [0.5, 1.0]]
            .iter()
            .map(|q| Node::create_in(coords.clone(), q).unwrap())
            .collect();
        let mut target = Mesh::empty();
        for pair in [[0, 1], [1, 2]] {
            let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
            sm.add_cell(&[p[pair[0]].id(), p[pair[1]].id()]).unwrap();
            target.add_sub(Handle::new(sm)).unwrap();
        }

        let carried = project_node(&field, &mesh, &target, 1e-6).unwrap();
        assert_eq!(carried.len(), 2);
        for zone in &carried {
            let z = zone.read();
            assert!((z.value(p[1].id(), "a").unwrap() - 2.0).abs() < 1e-12);
        }

        // A node of `mesh` the field leaves out reads zero: the right side.
        let carried = project_node(&threes, &mesh, &target, 1e-6).unwrap();
        let z = carried.get(0).unwrap().read();
        assert!((z.value(p[1].id(), "a").unwrap() - 1.5).abs() < 1e-12);
    }

    /// Nothing to carry or nowhere to carry it: an empty field. No cell to
    /// carry it through: zero everywhere.
    #[test]
    fn empty_sides_are_no_error() {
        let (mesh, nodes) = square(1);
        let field = sampled(&mesh, &nodes, |x, _| 1.0 + x);
        let (target, targets) = points(&[[0.5, 0.5]]);
        assert!(project_node(&NodeField::default(), &mesh, &target, 1e-6)
            .unwrap()
            .is_empty());
        assert!(project_node(&field, &mesh, &Mesh::empty(), 1e-6)
            .unwrap()
            .is_empty());
        let carried = project_node(&field, &Mesh::empty(), &target, 1e-6).unwrap();
        let z = carried.get(0).unwrap().read();
        assert_eq!(z.value(targets[0].id(), "a").unwrap(), 0.0);
        assert_eq!(z.value(targets[0].id(), "b").unwrap(), 0.0);
    }

    /// The TRI6 of `quadratic_cells_interpolate_quadratically`, and its nodes.
    fn tri6() -> (Mesh, Vec<Node>) {
        let coords = Handle::new(Coords::new(2).unwrap());
        let corners = [[0.0, 0.0], [2.0, 0.0], [0.0, 2.0]];
        let mids = [[1.0, 0.0], [1.0, 1.0], [0.0, 1.0]];
        let nodes: Vec<Node> = corners
            .iter()
            .chain(&mids)
            .map(|p| Node::create_in(coords.clone(), p).unwrap())
            .collect();
        let mut sm = SubMesh::new(coords, ElementType::TRI6);
        let ids: Vec<NodeId> = nodes.iter().map(Node::id).collect();
        sm.add_cell(&ids).unwrap();
        (Mesh::from_submesh(sm), nodes)
    }

    /// A quadratic field brought to the Gauss points comes back exactly: each
    /// cell's fit reproduces what its own space can hold.
    #[test]
    fn a_field_of_the_space_comes_back_exactly_from_the_gauss_points() {
        let (mesh, nodes) = tri6();
        let f = |x: f64, y: f64| x * x + x * y - 3.0 * y * y + 1.0;
        let nodal = sampled(&mesh, &nodes, f);
        let fes =
            crate::containers::finite_element_space::FiniteElementSpace::lagrange(&mesh).unwrap();
        let at_gauss = crate::ops::element_field::interp_to_gauss(&nodal, &fes).unwrap();
        let at = [[0.3, 0.4], [1.2, 0.5], [0.1, 1.7]];
        let (target, targets) = points(&at);

        let carried = project_element(&at_gauss, &mesh, &target, 1e-6).unwrap();
        let z = carried.get(0).unwrap().read();
        for (node, p) in targets.iter().zip(&at) {
            assert!((z.value(node.id(), "a").unwrap() - f(p[0], p[1])).abs() < 1e-10);
            assert!((z.value(node.id(), "b").unwrap() + f(p[0], p[1])).abs() < 1e-10);
        }
    }

    /// A point outside the cells reads zero; a component a zone lacks reads
    /// zero; a submesh of `mesh` without a zone of the field is refused.
    #[test]
    fn element_fields_read_zero_where_nothing_holds_them() {
        let (mesh, _) = square(1);
        let fes =
            crate::containers::finite_element_space::FiniteElementSpace::lagrange(&mesh).unwrap();
        let with_a = ElementField::new(&fes, vec!["a".into()]).unwrap();
        with_a
            .get(0)
            .unwrap()
            .write()
            .set_uniform("a", 2.0)
            .unwrap();
        let (target, targets) = points(&[[0.5, 0.5], [3.0, 3.0]]);
        let carried = project_element(&with_a, &mesh, &target, 1e-6).unwrap();
        let z = carried.get(0).unwrap().read();
        assert!((z.value(targets[0].id(), "a").unwrap() - 2.0).abs() < 1e-12);
        assert_eq!(z.value(targets[1].id(), "a").unwrap(), 0.0);

        // A field of two zones on the same cells, one component each.
        let with_b = ElementField::new(&fes, vec!["b".into()]).unwrap();
        with_b
            .get(0)
            .unwrap()
            .write()
            .set_uniform("b", 7.0)
            .unwrap();
        let mut both = ElementField::empty();
        both.add_sub(with_a.get(0).unwrap()).unwrap();
        both.add_sub(with_b.get(0).unwrap()).unwrap();
        let carried = project_element(&both, &mesh, &target, 1e-6).unwrap();
        let z = carried.get(0).unwrap().read();
        // First zone on the cells wins, and it carries no "b".
        assert!((z.value(targets[0].id(), "a").unwrap() - 2.0).abs() < 1e-12);
        assert_eq!(z.value(targets[0].id(), "b").unwrap(), 0.0);

        let (other, _) = square(1);
        let err = project_element(&with_a, &other, &target, 1e-6).unwrap_err();
        assert!(format!("{err}").contains("no zone"), "unexpected: {err}");
    }

    /// The field must hang from the `Coords` of `mesh`, and `target` live in
    /// the same dimension.
    #[test]
    fn mismatches_are_refused() {
        let (mesh, nodes) = square(1);
        let field = sampled(&mesh, &nodes, |x, _| x);
        let (other, _) = square(1);
        let (target, _) = points(&[[0.5, 0.5]]);
        assert!(project_node(&field, &other, &target, 1e-6).is_err());

        let coords = Handle::new(Coords::new(3).unwrap());
        let n = Node::create_in(coords, &[0.5, 0.5, 0.0]).unwrap();
        let in_3d = poi1_from_nodes(&[n]).unwrap();
        assert!(project_node(&field, &mesh, &in_3d, 1e-6).is_err());
    }
}