pyrucast 0.12.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
use crate::aggregate::Aggregate;
use crate::atoms::ElementType;
use crate::atoms::NodeId;
use crate::containers::mesh::{Mesh, SubMesh};
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;

/// Sweep two line meshes into a mesh of `element_type`, building `n_layers`
/// layers between them.
///
/// Both meshes must be single-submesh lines of the same degree with the same
/// number of elements, attached to the same `Coords`. `n_layers` must be ≥ 1.
///
/// - **SEG2 lines**: `element_type` is one of `QUA4`, `TRI3`, `QUA8`,
///   `QUA9`, `TRI6`. A `QUA4` mesh is always built first; the others are
///   derived from it (diagonal split for triangles, [`super::to_quadratic`]
///   for the quadratic siblings, a fresh centre node per cell for `QUA9`).
/// - **SEG3 lines**: `element_type` is `QUA8` or `QUA9`, built directly
///   by the sweep kernel itself: the lines' own mid-nodes are
///   re-used, so a strip between two arcs follows them exactly.
///
/// Column `j` of `mesh_a` is linearly interpolated with column `j` of
/// `mesh_b` to produce the intermediate layers. Endpoint nodes from both
/// meshes are re-used (refcount incremented); intermediate nodes are
/// created at evenly spaced positions. **Two closed loops** (each ending on
/// its own first node) give a closed ring: the seam is shared, not doubled.
///
/// QUA4 node order per element (counterclockwise, `mesh_a` side first):
/// `[k][j]`, `[k][j+1]`, `[k+1][j+1]`, `[k+1][j]`.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(3).unwrap());
/// # let p = |x: &[f64]| Node::create_in(coords.clone(), x).unwrap();
/// // Two **conforming** lines stitched by QUA4: the mesh is
/// // not an extrusion, the two borders being allowed to differ.
/// let a = mesh::line(&p(&[0.0, 0.0, 0.0]), &p(&[1.0, 0.0, 0.0]), 2, ElementType::SEG2)?;
/// let b = mesh::line(&p(&[0.0, 1.0, 0.0]), &p(&[2.0, 1.0, 0.0]), 2, ElementType::SEG2)?;
/// let s = mesh::sweep(&a, &b, 1, ElementType::QUA4)?;
/// assert_eq!(s.cell_count(), 2);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn sweep(
    mesh_a: &Mesh,
    mesh_b: &Mesh,
    n_layers: usize,
    element_type: ElementType,
) -> Result<Mesh> {
    use crate::ops::mesh::sweep_kernel::grid_between;
    if line_degree(mesh_a) == ElementType::SEG3 {
        return match element_type {
            ElementType::QUA8 | ElementType::QUA9 => {
                grid_between(mesh_a, mesh_b, n_layers, element_type)
            }
            other => Err(PyrucastError::Message(format!(
                "sweep: SEG3 lines give QUA8 or QUA9, not {other} (a SEG3 line has mid-nodes \
                 that {other} cannot carry)"
            ))),
        };
    }
    let qua4 = grid_between(mesh_a, mesh_b, n_layers, ElementType::QUA4)?;
    finish_surface(qua4, element_type, "sweep")
}

/// The element type of a one-zone line, `SEG2` when the mesh has another
/// shape — the sweep kernel then reports what is wrong.
fn line_degree(mesh: &Mesh) -> ElementType {
    match mesh.get(0) {
        Ok(zone) if mesh.len() == 1 => zone.read().element_type(),
        _ => ElementType::SEG2,
    }
}

/// Deliver a `QUA4` grid as the surface type the caller asked for.
///
/// The structured surface meshers — [`sweep`],
/// [`transfinite`](super::transfinite) — build a pure quadrangle grid; the
/// pavers ([`pave_surface`](super::pave_surface) and the grid meshers) build
/// one that may also hold a few `TRI3`, and only ask for the quadrangle
/// types. All owe the same conversions. `op` only names the operator in the
/// error message.
pub(super) fn finish_surface(qua4: Mesh, element_type: ElementType, op: &str) -> Result<Mesh> {
    match element_type {
        ElementType::QUA4 => Ok(qua4),
        ElementType::QUA8 => super::to_quadratic(&qua4),
        ElementType::QUA9 => qua8_to_qua9(&super::to_quadratic(&qua4)?),
        ElementType::TRI3 => qua4_to_tri3(&qua4),
        ElementType::TRI6 => super::to_quadratic(&qua4_to_tri3(&qua4)?),
        other => Err(PyrucastError::Message(format!(
            "{op}: unsupported element type {other} (expected QUA4, TRI3, QUA8, QUA9, TRI6)"
        ))),
    }
}

/// Split each QUA4 cell into two TRI3 cells along the `(0, 2)` diagonal:
/// `(0, 1, 2)` and `(0, 2, 3)`. Nodes are re-used, no new node is created.
///
/// Shared with [`super::transfinite`], which derives `TRI3`/`TRI6` from a
/// QUA4 grid the same way [`sweep`] does.
pub(super) fn qua4_to_tri3(mesh: &Mesh) -> Result<Mesh> {
    let coords = mesh.coords()?;
    let mut result = Mesh::empty();
    for sm_h in mesh {
        // Guard held for this zone's pass: what follows only reads.
        let s = sm_h.read();
        let (color, conn) = (s.face_color(), s.connectivity());
        // Two triangles per quad, laid out whole then posted in one locked
        // pass over the `Coords`.
        let split: Vec<NodeId> = conn
            .chunks(4)
            .flat_map(|cell| [cell[0], cell[1], cell[2], cell[0], cell[2], cell[3]])
            .collect();
        let mut new_sm = SubMesh::from_connectivity(coords.clone(), ElementType::TRI3, split)?;
        new_sm.set_face_color(color);
        result.add_sub(Handle::new(new_sm))?;
    }
    Ok(result)
}

/// Promote each QUA8 cell to QUA9 by adding a fresh center node (node 8, the
/// mean of the 4 corners) — [`super::to_quadratic`] only produces the
/// serendipity QUA8, which has no center node to re-use.
///
/// Any other zone passes through unchanged: the `TRI6` a paver leaves among
/// its quadrangles is already the quadratic triangle, and shares its
/// three-node edges with the `QUA9` around it.
///
/// Shared with [`super::transfinite`] (see [`qua4_to_tri3`]).
pub(super) fn qua8_to_qua9(mesh: &Mesh) -> Result<Mesh> {
    let coords = mesh.coords()?;
    let mut result = Mesh::empty();
    for sm_h in mesh {
        if sm_h.read().element_type() != ElementType::QUA8 {
            result.add_sub(sm_h.clone())?;
            continue;
        }
        // Guard held for this zone's pass: what follows only reads.
        let s = sm_h.read();
        let (color, conn) = (s.face_color(), s.connectivity());
        // Every centre first — one flat buffer, one `Coords` write — then the
        // connectivity that references them, in order.
        let centers: Vec<f64> = {
            let c = coords.read();
            let dim = c.dim() as usize;
            let mut buf = Vec::with_capacity(conn.len() / 8 * dim);
            for cell in conn.chunks(8) {
                let corners: Vec<&[f64]> = cell[..4]
                    .iter()
                    .map(|&id| c.position(id))
                    .collect::<Result<_>>()?;
                buf.extend((0..dim).map(|d| corners.iter().map(|p| p[d]).sum::<f64>() / 4.0));
            }
            buf
        };
        let first = coords.write().add_nodes(&centers)?.start;
        let n_cells = conn.len() / 8;
        let with_center: Vec<NodeId> = conn
            .chunks(8)
            .enumerate()
            .flat_map(|(ci, cell)| {
                cell.iter()
                    .copied()
                    .chain(std::iter::once(NodeId(first + ci as u32)))
            })
            .collect();
        let mut new_sm =
            SubMesh::from_connectivity(coords.clone(), ElementType::QUA9, with_center)?;
        new_sm.set_face_color(color);
        // The zone owns the centres now; hand back the unit `add_nodes` gave.
        let owned: Vec<NodeId> = (first..first + n_cells as u32).map(NodeId).collect();
        coords.write().decref_all(&owned)?;
        result.add_sub(Handle::new(new_sm))?;
    }
    Ok(result)
}

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

    #[test]
    fn sweep_basic() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let a0 = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let a2 = Node::create_in(coords.clone(), &[2.0, 0.0]).unwrap();
        let mesh_a = line(&a0, &a2, 2, ElementType::SEG2).unwrap();

        let b0 = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();
        let b2 = Node::create_in(coords.clone(), &[2.0, 1.0]).unwrap();
        let mesh_b = line(&b0, &b2, 2, ElementType::SEG2).unwrap();

        let qua = sweep(&mesh_a, &mesh_b, 2, ElementType::QUA4).unwrap();
        assert_eq!(qua.element_types().unwrap(), vec![ElementType::QUA4]);
        assert_eq!(qua.cell_count(), 4);

        let n00 = qua.node(0, 0, 0).unwrap();
        assert_eq!(n00.position().unwrap(), vec![0.0, 0.0]);
        let n01 = qua.node(0, 0, 1).unwrap();
        assert!((n01.position().unwrap()[0] - 1.0).abs() < 1e-12);
        assert!((n01.position().unwrap()[1]).abs() < 1e-12);
        let n02 = qua.node(0, 0, 2).unwrap();
        assert!((n02.position().unwrap()[0] - 1.0).abs() < 1e-12);
        assert!((n02.position().unwrap()[1] - 0.5).abs() < 1e-12);
    }

    #[test]
    fn sweep_one_layer_reuses_endpoints() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let a0 = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let a1 = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
        let mesh_a = line(&a0, &a1, 1, ElementType::SEG2).unwrap();

        let b0 = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();
        let b1 = Node::create_in(coords.clone(), &[1.0, 1.0]).unwrap();
        let mesh_b = line(&b0, &b1, 1, ElementType::SEG2).unwrap();

        let qua = sweep(&mesh_a, &mesh_b, 1, ElementType::QUA4).unwrap();
        assert_eq!(qua.cell_count(), 1);

        assert_eq!(qua.node(0, 0, 0).unwrap().id(), a0.id());
        assert_eq!(qua.node(0, 0, 1).unwrap().id(), a1.id());
        assert_eq!(qua.node(0, 0, 2).unwrap().id(), b1.id());
        assert_eq!(qua.node(0, 0, 3).unwrap().id(), b0.id());
    }

    #[test]
    fn sweep_rejects_zero_layers() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
        let m = line(&a, &b, 1, ElementType::SEG2).unwrap();
        assert!(sweep(&m, &m, 0, ElementType::QUA4).is_err());
    }

    #[test]
    fn sweep_rejects_mismatched_elem_counts() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
        let c = Node::create_in(coords.clone(), &[2.0, 0.0]).unwrap();
        let m1 = line(&a, &b, 1, ElementType::SEG2).unwrap();
        let m2 = line(&a, &c, 2, ElementType::SEG2).unwrap();
        assert!(sweep(&m1, &m2, 1, ElementType::QUA4).is_err());
    }

    #[test]
    fn sweep_rejects_non_seg2() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
        let seg = line(&a, &b, 1, ElementType::SEG2).unwrap();

        let c = Node::create_in(coords.clone(), &[0.5, 1.0]).unwrap();
        let mut tri_mesh = Mesh::from_submesh(SubMesh::new(coords, ElementType::TRI3));
        tri_mesh.add_cell(&[a.id(), b.id(), c.id()]).unwrap();

        assert!(sweep(&tri_mesh, &seg, 1, ElementType::QUA4).is_err());
        assert!(sweep(&seg, &tri_mesh, 1, ElementType::QUA4).is_err());
    }

    #[test]
    fn sweep_rejects_unsupported_element_type() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
        let seg = line(&a, &b, 1, ElementType::SEG2).unwrap();
        assert!(sweep(&seg, &seg, 1, ElementType::HEX8).is_err());
    }

    #[test]
    fn sweep_tri3_splits_each_quad_in_two() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let a0 = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let a2 = Node::create_in(coords.clone(), &[2.0, 0.0]).unwrap();
        let mesh_a = line(&a0, &a2, 2, ElementType::SEG2).unwrap();

        let b0 = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();
        let b2 = Node::create_in(coords.clone(), &[2.0, 1.0]).unwrap();
        let mesh_b = line(&b0, &b2, 2, ElementType::SEG2).unwrap();

        let tri = sweep(&mesh_a, &mesh_b, 2, ElementType::TRI3).unwrap();
        assert_eq!(tri.element_types().unwrap(), vec![ElementType::TRI3]);
        // 4 QUA4 cells → 8 TRI3 cells.
        assert_eq!(tri.cell_count(), 8);
    }

    #[test]
    fn sweep_qua8_promotes_to_quadratic() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let a0 = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let a1 = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
        let mesh_a = line(&a0, &a1, 1, ElementType::SEG2).unwrap();

        let b0 = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();
        let b1 = Node::create_in(coords.clone(), &[1.0, 1.0]).unwrap();
        let mesh_b = line(&b0, &b1, 1, ElementType::SEG2).unwrap();

        let qua8 = sweep(&mesh_a, &mesh_b, 1, ElementType::QUA8).unwrap();
        assert_eq!(qua8.element_types().unwrap(), vec![ElementType::QUA8]);
        assert_eq!(qua8.cell_count(), 1);
    }

    #[test]
    fn sweep_qua9_has_center_node() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let a0 = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let a1 = Node::create_in(coords.clone(), &[2.0, 0.0]).unwrap();
        let mesh_a = line(&a0, &a1, 1, ElementType::SEG2).unwrap();

        let b0 = Node::create_in(coords.clone(), &[0.0, 2.0]).unwrap();
        let b1 = Node::create_in(coords.clone(), &[2.0, 2.0]).unwrap();
        let mesh_b = line(&b0, &b1, 1, ElementType::SEG2).unwrap();

        let qua9 = sweep(&mesh_a, &mesh_b, 1, ElementType::QUA9).unwrap();
        assert_eq!(qua9.element_types().unwrap(), vec![ElementType::QUA9]);
        assert_eq!(qua9.cell_count(), 1);

        let center = qua9.node(0, 0, 8).unwrap();
        assert_eq!(center.position().unwrap(), vec![1.0, 1.0]);
    }

    #[test]
    fn qua9_keeps_the_triangles_of_a_quad_dominant_mesh() {
        // A quadrangle beside a triangle, as a paver leaves them: the QUA8
        // zone gains its centres, the TRI6 one passes through as it is.
        let coords = Handle::new(Coords::new(2).unwrap());
        let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0], [2.0, 0.0]]
            .iter()
            .map(|p| Node::create_in(coords.clone(), p).unwrap())
            .collect();
        let mut quads = SubMesh::new(coords.clone(), ElementType::QUA4);
        quads
            .add_cell(&[n[0].id(), n[1].id(), n[2].id(), n[3].id()])
            .unwrap();
        let mut tris = SubMesh::new(coords.clone(), ElementType::TRI3);
        tris.add_cell(&[n[1].id(), n[4].id(), n[2].id()]).unwrap();
        let mut mixed = Mesh::empty();
        mixed.add_sub(Handle::new(quads)).unwrap();
        mixed.add_sub(Handle::new(tris)).unwrap();

        let qua9 = finish_surface(mixed, ElementType::QUA9, "test").unwrap();
        assert_eq!(
            qua9.element_types().unwrap(),
            vec![ElementType::QUA9, ElementType::TRI6]
        );
        assert_eq!(qua9.cell_count(), 2);
        assert_eq!(
            qua9.node(0, 0, 8).unwrap().position().unwrap(),
            vec![0.5, 0.5]
        );
    }

    /// A closed square loop of four SEG2, corners at `±h`.
    fn square_loop(coords: &Handle<Coords>, h: f64) -> Mesh {
        let n: Vec<Node> = [[-h, -h], [h, -h], [h, h], [-h, h]]
            .iter()
            .map(|p| Node::create_in(coords.clone(), p).unwrap())
            .collect();
        let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
        for i in 0..4 {
            sm.add_cell(&[n[i].id(), n[(i + 1) % 4].id()]).unwrap();
        }
        Mesh::from_submesh(sm)
    }

    /// The distinct node ids a one-zone mesh references.
    fn distinct_nodes(mesh: &Mesh) -> std::collections::HashSet<NodeId> {
        mesh.get(0)
            .unwrap()
            .read()
            .connectivity()
            .iter()
            .copied()
            .collect()
    }

    #[test]
    fn sweep_two_closed_loops_close_the_ring() {
        // 4 outer + 4 inner + 2 intermediate rings of 4: 16 nodes. A doubled
        // seam would add one node per intermediate ring, 18 in all.
        let coords = Handle::new(Coords::new(2).unwrap());
        let outer = square_loop(&coords, 2.0);
        let inner = square_loop(&coords, 1.0);
        let ring = sweep(&outer, &inner, 3, ElementType::QUA4).unwrap();
        assert_eq!(ring.cell_count(), 12);
        assert_eq!(distinct_nodes(&ring).len(), 16);
        // Last column of every layer = first column: cell 3 of a layer ends
        // where cell 0 starts.
        for k in 0..3 {
            assert_eq!(
                ring.node(0, 4 * k + 3, 1).unwrap().id(),
                ring.node(0, 4 * k, 0).unwrap().id()
            );
        }
    }

    #[test]
    fn sweep_refuses_a_closed_loop_onto_an_open_line() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let closed = square_loop(&coords, 2.0);
        let a = Node::create_in(coords.clone(), &[0.0, 5.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[4.0, 5.0]).unwrap();
        let open = line(&a, &b, 4, ElementType::SEG2).unwrap();
        let err = sweep(&closed, &open, 2, ElementType::QUA4).unwrap_err();
        assert!(err
            .to_string()
            .contains("mesh_a is a closed loop but mesh_b is open"));
    }

    /// Two parallel straight lines, `n` cells each, of the given degree.
    fn two_lines(coords: &Handle<Coords>, n: usize, et: ElementType) -> (Mesh, Mesh) {
        let p = |x: f64, y: f64| Node::create_in(coords.clone(), &[x, y]).unwrap();
        (
            line(&p(0.0, 0.0), &p(2.0, 0.5), n, et).unwrap(),
            line(&p(0.0, 1.0), &p(2.0, 1.5), n, et).unwrap(),
        )
    }

    /// Node positions of every cell, in local order.
    fn cell_positions(mesh: &Mesh) -> Vec<Vec<Vec<f64>>> {
        let npc = mesh.get(0).unwrap().read().element_type().nodes_per_cell();
        (0..mesh.cell_count())
            .map(|c| {
                (0..npc)
                    .map(|k| mesh.node(0, c, k).unwrap().position().unwrap())
                    .collect()
            })
            .collect()
    }

    fn assert_same_cells(a: &Mesh, b: &Mesh) {
        let (pa, pb) = (cell_positions(a), cell_positions(b));
        assert_eq!(pa.len(), pb.len());
        for (c, (ca, cb)) in pa.iter().zip(pb.iter()).enumerate() {
            assert_eq!(ca.len(), cb.len());
            for (k, (x, y)) in ca.iter().zip(cb.iter()).enumerate() {
                for d in 0..x.len() {
                    assert!(
                        (x[d] - y[d]).abs() < 1e-12,
                        "cell {c}, node {k}: {x:?} vs {y:?}"
                    );
                }
            }
        }
    }

    #[test]
    fn sweep_seg3_lines_match_the_promoted_strip_on_straight_lines() {
        // Between straight lines, the native quadratic strip and the QUA4
        // strip promoted by `to_quadratic` are the same mesh, node by node.
        let coords = Handle::new(Coords::new(2).unwrap());
        let (a2, b2) = two_lines(&coords, 3, ElementType::SEG2);
        let (a3, b3) = two_lines(&coords, 3, ElementType::SEG3);
        for et in [ElementType::QUA8, ElementType::QUA9] {
            let promoted = sweep(&a2, &b2, 2, et).unwrap();
            let native = sweep(&a3, &b3, 2, et).unwrap();
            assert_eq!(native.element_types().unwrap(), vec![et]);
            assert_same_cells(&native, &promoted);
        }
    }

    #[test]
    fn sweep_seg3_between_arcs_follows_them() {
        // A quarter ring between radii 1 and 2: the mid-nodes of the first
        // and last rows are those of the arcs, on the circles.
        use crate::ops::mesh::arc::arc;
        let coords = Handle::new(Coords::new(2).unwrap());
        let p = |x: f64, y: f64| Node::create_in(coords.clone(), &[x, y]).unwrap();
        let o = p(0.0, 0.0);
        let inner = arc(&p(1.0, 0.0), &o, &p(0.0, 1.0), 4, ElementType::SEG3).unwrap();
        let outer = arc(&p(2.0, 0.0), &o, &p(0.0, 2.0), 4, ElementType::SEG3).unwrap();
        let ring = sweep(&inner, &outer, 2, ElementType::QUA8).unwrap();
        assert_eq!(ring.cell_count(), 8);
        let radius = |c: usize, k: usize| {
            let x = ring.node(0, c, k).unwrap().position().unwrap();
            (x[0] * x[0] + x[1] * x[1]).sqrt()
        };
        for j in 0..4 {
            assert!((radius(j, 4) - 1.0).abs() < 1e-12); // first row, on the inner arc
            assert!((radius(4 + j, 6) - 2.0).abs() < 1e-12); // last row, on the outer arc
        }
    }

    #[test]
    fn sweep_seg3_refuses_linear_targets_and_mixed_degrees() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let (a2, _) = two_lines(&coords, 2, ElementType::SEG2);
        let (a3, b3) = two_lines(&coords, 2, ElementType::SEG3);
        assert!(sweep(&a3, &b3, 1, ElementType::QUA4).is_err());
        assert!(sweep(&a3, &b3, 1, ElementType::TRI6).is_err());
        assert!(sweep(&a3, &a2, 1, ElementType::QUA8).is_err());
        assert!(sweep(&a2, &a3, 1, ElementType::QUA8).is_err());
    }

    #[test]
    fn sweep_two_closed_seg3_loops_close_the_ring() {
        // Two concentric SEG3 circles of 6 cells, 2 layers: the seam is
        // shared on every level, mid-levels included.
        use crate::ops::mesh::circle::circle;
        let coords = Handle::new(Coords::new(2).unwrap());
        let o = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let inner = circle(&o, &[0.0, 0.0, 1.0], 1.0, 6, ElementType::SEG3).unwrap();
        let outer = circle(&o, &[0.0, 0.0, 1.0], 2.0, 6, ElementType::SEG3).unwrap();
        let ring = sweep(&inner, &outer, 2, ElementType::QUA8).unwrap();
        // Three corner levels of 6 corners + 6 mid-nodes, two mid-levels of 6
        // nodes: 36 + 12 = 48. A doubled seam would add one per level.
        assert_eq!(distinct_nodes(&ring).len(), 48);
    }

    #[test]
    fn sweep_tri6_splits_then_promotes() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let a0 = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let a1 = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
        let mesh_a = line(&a0, &a1, 1, ElementType::SEG2).unwrap();

        let b0 = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();
        let b1 = Node::create_in(coords.clone(), &[1.0, 1.0]).unwrap();
        let mesh_b = line(&b0, &b1, 1, ElementType::SEG2).unwrap();

        let tri6 = sweep(&mesh_a, &mesh_b, 1, ElementType::TRI6).unwrap();
        assert_eq!(tri6.element_types().unwrap(), vec![ElementType::TRI6]);
        assert_eq!(tri6.cell_count(), 2);
    }
}