caexfer 0.2.0

Transfer finite-element meshes, voxel occupancy, and results across CAE formats
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
//! Bounded single-zone SU2 ASCII mesh with named boundary markers.
//!
//! Interior cells and marker facets share one [`Mesh`] while [`CellSet`] names
//! identify the boundary elements. Node and cell IDs are assigned in source
//! order because native SU2 connectivity uses zero-based array positions.

use crate::core::{Cell, CellKind, CellSet, Dataset, Error, Mesh, Point, Result};
use std::collections::BTreeSet;
use std::io::Write;

/// Geometry projected from one SU2 zone.
#[derive(Debug, Clone, PartialEq)]
pub struct Projection {
    /// Mesh with marker cells in named cell sets.
    pub dataset: Dataset,

    /// Input dimension, which can be useful when no elements are present.
    pub dimension: u8,
}

/// One unvalidated native connectivity record.
struct RawCell {
    /// Native VTK-style kind.
    kind: CellKind,

    /// Zero-based point positions in the later `NPOIN` section.
    indices: Vec<usize>,
}

/// Format-specific structural error.
fn err(message: impl Into<String>) -> Error {
    Error::new("E_SU2", message)
}

/// Parse the value of one required `KEY= value` line.
fn value<'a>(line: &'a str, key: &str) -> Result<&'a str> {
    let (actual, value) = line
        .split_once('=')
        .ok_or_else(|| err(format!("expected {key}=")))?;
    if !actual.trim().eq_ignore_ascii_case(key) {
        return Err(err(format!("expected {key}=")));
    }
    Ok(value.trim())
}

/// Advance to the next nonempty record, allowing `%` comment lines.
fn next<'a>(lines: &mut impl Iterator<Item = &'a str>, what: &str) -> Result<&'a str> {
    lines
        .find(|line| !line.trim().is_empty() && !line.trim_start().starts_with('%'))
        .map(str::trim)
        .ok_or_else(|| err(format!("missing {what}")))
}

/// Check a declared record count against the input byte length.
fn count(line: &str, key: &str, max: usize) -> Result<usize> {
    let count = value(line, key)?
        .parse::<usize>()
        .map_err(|_| err(format!("invalid {key}")))?;
    if count > max {
        return Err(err(format!("{key} exceeds input size")));
    }
    Ok(count)
}

/// Map SU2's VTK-style cell numbers to the seven linear kinds.
fn kind(number: u32) -> Result<CellKind> {
    match number {
        3 => Ok(CellKind::Line2),
        5 => Ok(CellKind::Triangle3),
        9 => Ok(CellKind::Quad4),
        10 => Ok(CellKind::Tet4),
        12 => Ok(CellKind::Hex8),
        13 => Ok(CellKind::Wedge6),
        14 => Ok(CellKind::Pyramid5),
        _ => Err(err(format!("unsupported SU2 element type {number}"))),
    }
}

/// Reverse map for supported linear cells.
fn number(kind: CellKind) -> u8 {
    match kind {
        CellKind::Line2 => 3,
        CellKind::Triangle3 => 5,
        CellKind::Quad4 => 9,
        CellKind::Tet4 => 10,
        CellKind::Hex8 => 12,
        CellKind::Wedge6 => 13,
        CellKind::Pyramid5 => 14,
    }
}

/// Parse a connectivity row, ignoring only a validated optional row index.
fn connectivity(line: &str, expected_dimension: u8, ordinal: usize) -> Result<RawCell> {
    let words = line.split_whitespace().collect::<Vec<_>>();
    let number = words
        .first()
        .ok_or_else(|| err("empty SU2 element"))?
        .parse::<u32>()
        .map_err(|_| err("invalid SU2 element type"))?;
    let kind = kind(number)?;
    if kind.dimension() != expected_dimension {
        return Err(err("SU2 element has wrong dimension for its section"));
    }
    let arity = kind.node_count();
    if words.len() != arity + 1 && words.len() != arity + 2 {
        return Err(err("SU2 element has wrong connectivity width"));
    }
    let indices = words[1..=arity]
        .iter()
        .map(|word| {
            word.parse::<usize>()
                .map_err(|_| err("invalid SU2 point index"))
        })
        .collect::<Result<Vec<_>>>()?;
    if words.len() == arity + 2 {
        let explicit = words[arity + 1]
            .parse::<usize>()
            .map_err(|_| err("invalid SU2 element index"))?;
        if explicit != ordinal {
            return Err(err("SU2 element index differs from row order"));
        }
    }
    Ok(RawCell { kind, indices })
}

/// Add one validated raw cell using deterministic one-based IDs.
fn add_cell(mesh: &mut Mesh, raw: RawCell) -> Result<u64> {
    if raw.indices.iter().any(|&index| index >= mesh.points.len()) {
        return Err(err("SU2 element references missing point"));
    }
    let id = mesh
        .cells
        .len()
        .checked_add(1)
        .and_then(|value| u64::try_from(value).ok())
        .ok_or_else(|| err("too many SU2 elements"))?;
    mesh.cells.push(Cell {
        id,
        kind: raw.kind,
        connectivity: raw.indices,
        property_id: None,
    });
    Ok(id)
}

/// Read a single-zone ASCII SU2 mesh, including named boundary markers.
///
/// The file's zero-based connectivity is projected into deterministic one-based
/// point/cell IDs. Neither units nor boundary-condition values are inferred.
///
/// # Errors
///
/// Returns `E_SU2` for unsupported zones, malformed sections, excessive
/// counts, invalid connectivity, or markers with invalid names or facets.
pub fn read_projection(source: &str) -> Result<Projection> {
    let mut lines = source.lines();
    let maximum = source.len();
    let dimension = value(next(&mut lines, "NDIME")?, "NDIME")?
        .parse::<u8>()
        .map_err(|_| err("invalid NDIME"))?;
    if !matches!(dimension, 2 | 3) {
        return Err(err("only 2D and 3D SU2 meshes are supported"));
    }
    let elements = count(next(&mut lines, "NELEM")?, "NELEM", maximum)?;
    let mut interior = Vec::with_capacity(elements);
    for ordinal in 0..elements {
        interior.push(connectivity(
            next(&mut lines, "interior element")?,
            dimension,
            ordinal,
        )?);
    }
    let points = count(next(&mut lines, "NPOIN")?, "NPOIN", maximum)?;
    let mut mesh = Mesh {
        points: Vec::with_capacity(points),
        cells: Vec::with_capacity(elements),
        ..Mesh::default()
    };
    for ordinal in 0..points {
        let words = next(&mut lines, "point")?
            .split_whitespace()
            .collect::<Vec<_>>();
        if words.len() != usize::from(dimension) && words.len() != usize::from(dimension) + 1 {
            return Err(err("SU2 point has wrong coordinate width"));
        }
        let mut position = [0.0_f64; 3];
        for (coordinate, word) in position.iter_mut().zip(&words) {
            *coordinate = word
                .parse::<f64>()
                .map_err(|_| err("invalid SU2 coordinate"))?;
            if !coordinate.is_finite() {
                return Err(err("nonfinite SU2 coordinate"));
            }
        }
        if words.len() == usize::from(dimension) + 1 {
            let explicit = words[usize::from(dimension)]
                .parse::<usize>()
                .map_err(|_| err("invalid SU2 point index"))?;
            if explicit != ordinal {
                return Err(err("SU2 point index differs from row order"));
            }
        }
        mesh.points.push(Point {
            id: u64::try_from(ordinal + 1).map_err(|_| err("too many SU2 points"))?,
            position,
        });
    }
    for raw in interior {
        add_cell(&mut mesh, raw)?;
    }
    let markers = count(next(&mut lines, "NMARK")?, "NMARK", maximum)?;
    for _ in 0..markers {
        let name = value(next(&mut lines, "MARKER_TAG")?, "MARKER_TAG")?.to_owned();
        if name.is_empty() || name.contains(['\n', '\r', '=']) {
            return Err(err("invalid SU2 marker name"));
        }
        let facets = count(next(&mut lines, "MARKER_ELEMS")?, "MARKER_ELEMS", maximum)?;
        let mut cell_ids = Vec::with_capacity(facets);
        for ordinal in 0..facets {
            let raw = connectivity(next(&mut lines, "marker element")?, dimension - 1, ordinal)?;
            cell_ids.push(add_cell(&mut mesh, raw)?);
        }
        mesh.cell_sets.push(CellSet {
            name,
            dimension: dimension - 1,
            cell_ids,
        });
    }
    if lines.any(|line| !line.trim().is_empty() && !line.trim_start().starts_with('%')) {
        return Err(err("trailing or unsupported SU2 sections"));
    }
    mesh.validate()?;
    Ok(Projection {
        dataset: Dataset {
            mesh,
            fields: vec![],
        },
        dimension,
    })
}

/// Write one complete cell connectivity row using SU2 point positions.
fn write_cell(cell: &Cell, writer: &mut impl Write) -> Result<()> {
    write!(writer, "{}", number(cell.kind))?;
    for index in &cell.connectivity {
        write!(writer, " {index}")?;
    }
    writeln!(writer)?;
    Ok(())
}

/// Write a single-zone ASCII SU2 mesh with named lower-dimensional markers.
///
/// Every boundary cell must belong to at least one named cell set. Other cell
/// sets, node sets, source IDs, and fields have no native mapping; conversion
/// reports those losses. A 2D mesh must lie in z=0.
///
/// # Errors
///
/// Returns `E_SU2` when there is no 2D/3D interior, a boundary cell is
/// unmarked, a marker name is invalid, or the mesh is not representable.
pub fn write_data(dataset: &Dataset, mut writer: impl Write) -> Result<()> {
    dataset.validate()?;
    if !dataset.fields.is_empty() {
        return Err(err("SU2 cannot encode numeric fields"));
    }
    let mesh = &dataset.mesh;
    if mesh.cells.iter().any(|cell| cell.property_id.is_some()) {
        return Err(err("SU2 cannot encode property IDs"));
    }
    let dimension = mesh
        .cells
        .iter()
        .map(|cell| cell.kind.dimension())
        .max()
        .ok_or_else(|| err("SU2 requires interior cells"))?;
    if !matches!(dimension, 2 | 3) {
        return Err(err("SU2 requires 2D or 3D interior cells"));
    }
    if !mesh.node_sets.is_empty()
        || mesh
            .cell_sets
            .iter()
            .any(|set| set.dimension != dimension - 1)
    {
        return Err(err("SU2 writer accepts named boundary cell sets only"));
    }
    if dimension == 2 && mesh.points.iter().any(|point| point.position[2] != 0.0) {
        return Err(err("2D SU2 cannot encode nonzero z coordinates"));
    }
    let markers = mesh
        .cell_sets
        .iter()
        .filter(|set| set.dimension == dimension - 1)
        .collect::<Vec<_>>();
    let mut marker_ids = BTreeSet::<u64>::new();
    for marker in &markers {
        if marker.name.contains(['\n', '\r', '=']) {
            return Err(err("invalid SU2 marker name"));
        }
        marker_ids.extend(marker.cell_ids.iter().copied());
    }
    if mesh
        .cells
        .iter()
        .any(|cell| cell.kind.dimension() < dimension && !marker_ids.contains(&cell.id))
    {
        return Err(err("lower-dimensional SU2 cell has no named marker"));
    }
    let interior = mesh
        .cells
        .iter()
        .filter(|cell| cell.kind.dimension() == dimension)
        .collect::<Vec<_>>();
    writeln!(writer, "NDIME= {dimension}")?;
    writeln!(writer, "NELEM= {}", interior.len())?;
    for cell in interior {
        write_cell(cell, &mut writer)?;
    }
    writeln!(writer, "NPOIN= {}", mesh.points.len())?;
    for point in &mesh.points {
        write!(writer, "{} {}", point.position[0], point.position[1])?;
        if dimension == 3 {
            write!(writer, " {}", point.position[2])?;
        }
        writeln!(writer)?;
    }
    writeln!(writer, "NMARK= {}", markers.len())?;
    for marker in markers {
        writeln!(writer, "MARKER_TAG= {}", marker.name)?;
        writeln!(writer, "MARKER_ELEMS= {}", marker.cell_ids.len())?;
        for id in &marker.cell_ids {
            let cell = mesh
                .cells
                .iter()
                .find(|cell| cell.id == *id)
                .ok_or_else(|| err("marker references missing cell"))?;
            write_cell(cell, &mut writer)?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Retain SU2 marker names and boundary edge orientation on round trip.
    #[test]
    fn marker_names_and_oriented_edges_roundtrip() {
        let source = "NDIME= 2\nNELEM= 1\n5 0 1 2\nNPOIN= 3\n0 0\n1 0\n0 1\nNMARK= 2\nMARKER_TAG= inlet\nMARKER_ELEMS= 1\n3 0 1\nMARKER_TAG= wall\nMARKER_ELEMS= 2\n3 1 2\n3 2 0\n";
        let first = read_projection(source).unwrap();
        assert_eq!(first.dataset.mesh.cell_sets[0].name, "inlet");
        assert_eq!(first.dataset.mesh.cell_sets[1].cell_ids.len(), 2);
        let mut bytes = Vec::new();
        write_data(&first.dataset, &mut bytes).unwrap();
        let second = read_projection(std::str::from_utf8(&bytes).unwrap()).unwrap();
        assert_eq!(second.dataset, first.dataset);
    }

    /// Reject incorrect SU2 counts and boundary cells without a marker.
    #[test]
    fn bad_counts_and_unmarked_boundaries_fail() {
        assert_eq!(
            read_projection("NDIME= 2\nNELEM= 99999999\n")
                .unwrap_err()
                .code,
            "E_SU2"
        );
        let source = "NDIME= 2\nNELEM= 1\n5 0 1 2\nNPOIN= 3\n0 0\n1 0\n0 1\nNMARK= 1\nMARKER_TAG= inlet\nMARKER_ELEMS= 1\n3 0 1\n";
        let mut data = read_projection(source).unwrap().dataset;
        data.mesh.cell_sets.clear();
        assert_eq!(write_data(&data, Vec::new()).unwrap_err().code, "E_SU2");
    }

    /// Round-trip supported three-dimensional SU2 cells and markers.
    #[test]
    fn three_dimensional_linear_cells_round_trip() {
        let kinds = [
            CellKind::Tet4,
            CellKind::Hex8,
            CellKind::Wedge6,
            CellKind::Pyramid5,
        ];
        let points = (0..8)
            .map(|index| Point {
                id: u64::try_from(index + 1).unwrap(),
                position: [f64::from(u32::try_from(index).unwrap()), 0.0, 0.0],
            })
            .collect();
        let cells = kinds
            .into_iter()
            .enumerate()
            .map(|(index, kind)| Cell {
                id: u64::try_from(index + 1).unwrap(),
                kind,
                connectivity: (0..kind.node_count()).collect(),
                property_id: None,
            })
            .collect();
        let dataset = Dataset {
            mesh: Mesh {
                points,
                cells,
                ..Mesh::default()
            },
            fields: Vec::new(),
        };
        let mut output = Vec::new();
        write_data(&dataset, &mut output).unwrap();
        let parsed = read_projection(std::str::from_utf8(&output).unwrap()).unwrap();
        assert_eq!(parsed.dimension, 3);
        assert_eq!(parsed.dataset, dataset);
    }

    /// Reject invalid SU2 indices and unknown cell type codes.
    #[test]
    fn positional_indices_and_unrecognized_types_fail() {
        let base = "NDIME= 2\nNELEM= 1\n5 0 1 2 0\nNPOIN= 3\n0 0 0\n1 0 1\n0 1 2\nNMARK= 0\n";
        assert_eq!(read_projection(base).unwrap().dataset.mesh.cells.len(), 1);
        for bad in [
            base.replace("5 0 1 2 0", "5 0 1 2 9"),
            base.replace("0 1 2\n", "0 1 9\n"),
            base.replace("5 0 1 2 0", "99 0 1 2 0"),
        ] {
            assert_eq!(read_projection(&bad).unwrap_err().code, "E_SU2");
        }
        let quad = "NDIME= 2\nNELEM= 1\n9 0 1 2 3\nNPOIN= 4\n0 0\n1 0\n1 1\n0 1\nNMARK= 0\n";
        let data = read_projection(quad).unwrap().dataset;
        let mut output = Vec::new();
        write_data(&data, &mut output).unwrap();
        assert_eq!(
            read_projection(std::str::from_utf8(&output).unwrap())
                .unwrap()
                .dataset,
            data
        );
    }

    /// Validate the section boundaries before constructing a partial mesh.
    #[test]
    fn malformed_sections_and_connectivity_fail_with_specific_errors() {
        let base = "NDIME= 2\nNELEM= 1\n5 0 1 2\nNPOIN= 3\n0 0\n1 0\n0 1\nNMARK= 1\nMARKER_TAG= inlet\nMARKER_ELEMS= 1\n3 0 1\n";
        for (old, new, expected) in [
            ("NDIME= 2", "NDIME= 1", "only 2D and 3D"),
            ("NELEM= 1", "WRONG= 1", "expected NELEM="),
            ("5 0 1 2", "3 0 1", "wrong dimension"),
            ("5 0 1 2", "5 0 1", "wrong connectivity width"),
            ("5 0 1 2", "5 0 1 9", "references missing point"),
            ("1 0\n0 1", "1 0 0 1\n0 1", "wrong coordinate width"),
            ("1 0\n0 1", "NaN 0\n0 1", "nonfinite SU2 coordinate"),
            (
                "MARKER_TAG= inlet",
                "MARKER_TAG= ",
                "invalid SU2 marker name",
            ),
            ("3 0 1\n", "3 0 1\nNZONE= 2\n", "trailing or unsupported"),
        ] {
            let changed = base.replacen(old, new, 1);
            let error = read_projection(&changed).unwrap_err();
            assert!(error.message.contains(expected), "{new}: {error}");
        }
    }

    /// The writer must reject mesh metadata SU2 cannot preserve.
    #[test]
    fn writer_rejects_nonrepresentable_mesh_metadata() {
        let base = "NDIME= 2\nNELEM= 1\n5 0 1 2\nNPOIN= 3\n0 0\n1 0\n0 1\nNMARK= 0\n";
        let original = read_projection(base).unwrap().dataset;
        let mut invalid = original.clone();
        invalid.mesh.points[0].position[2] = 1.0;
        assert!(
            write_data(&invalid, Vec::new())
                .unwrap_err()
                .message
                .contains("nonzero z")
        );
        invalid = original.clone();
        invalid.mesh.node_sets.push(crate::core::NodeSet {
            name: "fixed".into(),
            point_ids: vec![1],
        });
        assert!(
            write_data(&invalid, Vec::new())
                .unwrap_err()
                .message
                .contains("boundary cell sets only")
        );
        invalid = original;
        invalid.mesh.cells[0].kind = CellKind::Line2;
        invalid.mesh.cells[0].connectivity.truncate(2);
        assert!(
            write_data(&invalid, Vec::new())
                .unwrap_err()
                .message
                .contains("2D or 3D interior")
        );
    }
}