caexfer 0.1.2

Transfer linear finite-element meshes 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
use std::collections::{BTreeMap, BTreeSet, btree_map::Entry};

use super::{Card, ParsedBdf, parse_real};
use crate::core::{
    Cell, CellKind, Diagnostic, Error, Mesh, Point, Result, Severity, ValidationReport,
};

/// Parsed GRID values in the native coordinate frame of the source card.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Grid {
    /// Positive GRID identifier.
    pub id: u64,

    /// Coordinate frame identifier; zero means the basic frame.
    pub cp: u64,

    /// Native CP-frame coordinates; `geometry()` requires CP=0.
    pub coordinates: [f64; 3],

    /// Output coordinate frame identifier.
    pub cd: i64,

    /// Superelement identifier.
    pub seid: u64,

    /// One-based physical line containing the GRID card.
    pub line: usize,
}

/// One category of information excluded from a geometry projection.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Omission {
    /// Kind of omitted information.
    pub category: String,

    /// Number of affected source records.
    pub count: usize,

    /// Human-readable explanation.
    pub detail: String,
}

/// Geometry extracted from a BDF plus a report of discarded semantics.
#[derive(Debug, Clone, PartialEq)]
pub struct GeometryProjection {
    /// Supported points and linear cells with their original IDs.
    pub mesh: Mesh,

    /// Information intentionally absent from this geometry-only projection.
    pub omissions: Vec<Omission>,

    /// True when a GRID output displacement frame is not the basic frame.
    pub has_nonbasic_output_frame: bool,
}

/// Parse a required positive BDF ID with the originating physical line.
fn positive(input: &str, field: &str, line: usize) -> Result<u64> {
    let value = input.parse::<u64>().map_err(|_| {
        Error::new(
            "E_INTEGER",
            format!("{field} must be a positive integer, got {input:?}"),
        )
        .at(line)
    })?;
    if value == 0 {
        return Err(Error::new("E_INTEGER", format!("{field} must be positive")).at(line));
    }
    Ok(value)
}

/// Parse an optional nonnegative BDF integer; a blank means the defined zero.
fn nonnegative(input: &str, field: &str, line: usize) -> Result<u64> {
    if input.is_empty() {
        return Ok(0);
    }
    input.parse::<u64>().map_err(|_| {
        Error::new(
            "E_INTEGER",
            format!("{field} must be nonnegative, got {input:?}"),
        )
        .at(line)
    })
}

/// These cards can be excluded from a geometry projection. Their meanings
/// are not interpreted or solver-validated.
fn opaque_nongeometry(name: &str) -> bool {
    matches!(
        name,
        "MAT1"
            | "MAT2"
            | "MAT3"
            | "MAT4"
            | "MAT5"
            | "MAT8"
            | "MAT9"
            | "PSHELL"
            | "PSOLID"
            | "PLSOLID"
            | "PROD"
            | "PBAR"
            | "PBARL"
            | "PBEAM"
            | "PBEAML"
            | "PCOMP"
            | "PCOMPG"
            | "PARAM"
            | "FORCE"
            | "FORCE1"
            | "FORCE2"
            | "MOMENT"
            | "MOMENT1"
            | "MOMENT2"
            | "PLOAD"
            | "PLOAD1"
            | "PLOAD2"
            | "PLOAD4"
            | "GRAV"
            | "LOAD"
            | "SPC"
            | "SPC1"
            | "SPCADD"
            | "SPCD"
            | "MPC"
            | "MPCADD"
            | "SET1"
            | "SET3"
            | "EIGR"
            | "EIGRL"
            | "TSTEP"
            | "TSTEPNL"
            | "FREQ"
            | "FREQ1"
            | "FREQ2"
            | "DLOAD"
            | "RLOAD1"
            | "RLOAD2"
            | "TLOAD1"
            | "TLOAD2"
            | "TABLED1"
            | "TABLED2"
            | "TABLED3"
            | "TABLED4"
            | "CORD1R"
            | "CORD1C"
            | "CORD1S"
            | "CORD2R"
            | "CORD2C"
            | "CORD2S"
    )
}

/// Recognize element cards that have a supported linear mesh projection.
/// Other cards remain in the original document and are reported as omissions.
fn element_kind(name: &str) -> Option<CellKind> {
    match name {
        "CROD" | "CONROD" | "CBAR" | "CBEAM" => Some(CellKind::Line2),
        "CTRIA3" => Some(CellKind::Triangle3),
        "CQUAD4" => Some(CellKind::Quad4),
        "CTETRA" => Some(CellKind::Tet4),
        "CHEXA" => Some(CellKind::Hex8),
        "CPENTA" => Some(CellKind::Wedge6),
        "CPYRAM" => Some(CellKind::Pyramid5),
        _ => None,
    }
}

/// Supported element connectivity before GRID IDs are resolved to mesh indices.
struct NativeElement {
    id: u64,
    property_id: Option<u64>,
    nodes: Vec<u64>,
    kind: CellKind,
    line: usize,
}

impl ParsedBdf {
    /// Decode one GRID's native values without resolving external defaults.
    /// GRDSET and INCLUDE make those defaults ambiguous and block projection.
    pub(crate) fn parse_grid(&self, card: &Card) -> Result<Grid> {
        // A native GRID cannot be interpreted while external defaults may
        // change its coordinate or output frame.
        if self.has_grdset {
            return Err(Error::new(
                "E_GRDSET",
                "GRDSET defaults are unresolved; native GRID values cannot be interpreted safely",
            )
            .at(card.line));
        }
        if !self.include_lines.is_empty() {
            return Err(Error::new("E_INCLUDE_UNRESOLVED", "INCLUDE may supply GRID defaults; typed GRID interpretation is disabled until the deck is flattened").at(card.line));
        }
        let f = |i| self.card_text(card, i);
        let id = positive(f(0), "GRID ID", card.line)?;
        let cp = nonnegative(f(1), "GRID CP", card.line)?;

        // Blank coordinate fields default to zero on GRID cards.
        let mut coordinates = [0.0; 3];
        for (axis, value) in coordinates.iter_mut().enumerate() {
            if !f(axis + 2).is_empty() {
                *value = parse_real(f(axis + 2)).map_err(|e| e.at(card.line))?;
            }
        }
        let cd = if f(5).is_empty() {
            0
        } else {
            f(5).parse::<i64>()
                .map_err(|_| Error::new("E_INTEGER", "invalid GRID CD").at(card.line))?
        };
        if cd < -1 {
            return Err(Error::new("E_INTEGER", "GRID CD must be >= -1").at(card.line));
        }

        // PS is a set of constraint digits, so repeated digits are invalid.
        let ps = f(6).to_string();
        let mut seen = BTreeSet::new();
        if !ps
            .bytes()
            .all(|byte| (b'1'..=b'6').contains(&byte) && seen.insert(byte))
        {
            return Err(Error::new(
                "E_GRID_PS",
                "GRID PS must contain unique digits 1 through 6",
            )
            .at(card.line));
        }
        let seid = nonnegative(f(7), "GRID SEID", card.line)?;
        if (8..card.fields.len()).any(|i| !f(i).is_empty()) {
            return Err(
                Error::new("E_GRID_FIELDS", "unexpected data after GRID SEID").at(card.line),
            );
        }
        Ok(Grid {
            id,
            cp,
            coordinates,
            cd,
            seid,
            line: card.line,
        })
    }

    /// Iterate over GRID cards in source order after default checks.
    fn grids(&self) -> impl Iterator<Item = Result<Grid>> + '_ {
        self.cards
            .iter()
            .filter(|card| card.name() == "GRID")
            .map(|card| self.parse_grid(card))
    }

    /// Read one supported element's ID, explicit property, and GRID references.
    /// Extra solid-element fields are rejected to avoid silently linearizing
    /// higher-order cells.
    fn parse_element(&self, card: &Card, kind: CellKind) -> Result<NativeElement> {
        // CONROD has no property field; other supported cards require an
        // explicit PID so dialect-specific defaults are never guessed.
        let f = |i| self.card_text(card, i);
        let id = positive(f(0), "element ID", card.line)?;
        let conrod = card.name() == "CONROD";
        let property_id = if conrod {
            None
        } else {
            // Some dialects default PID to EID. Do not guess that rule here.
            Some(positive(
                f(1),
                "element PID (explicit value required in v0.1)",
                card.line,
            )?)
        };
        let first_node = if conrod { 1 } else { 2 };
        let mut nodes = Vec::new();
        for index in 0..kind.node_count() {
            nodes.push(positive(
                f(first_node + index),
                "element GRID reference",
                card.line,
            )?);
        }

        // Extra solid-card fields may indicate higher-order geometry, which
        // cannot be reduced to a linear cell without losing nodes.
        if matches!(card.name(), "CTETRA" | "CHEXA" | "CPENTA" | "CPYRAM") {
            let first_extra = first_node + kind.node_count();
            if (first_extra..card.fields.len()).any(|i| !f(i).is_empty()) {
                return Err(Error::new("E_HIGH_ORDER", format!("{} contains extra nodes/data; higher-order cells are not reduced to linear cells", card.name())).at(card.line));
            }
        }
        Ok(NativeElement {
            id,
            property_id,
            nodes,
            kind,
            line: card.line,
        })
    }

    /// Project all supported GRID and element cards into a mesh and findings.
    /// Keeps collecting scoped diagnostics so callers can inspect multiple
    /// omissions or errors from one document in a single pass.
    #[allow(clippy::too_many_lines)] // Geometry diagnostics share one pass over source cards.
    fn analyze_geometry(&self) -> (ValidationReport, Mesh) {
        // Collect source diagnostics and native IDs before forming indexed
        // connectivity; this lets one validation pass report multiple issues.
        let mut report = ValidationReport::default();
        let mut points = BTreeMap::new();
        let mut native_cells = BTreeMap::new();
        for card in &self.cards {
            match card.name() {
                "GRID" => match self.parse_grid(card) {
                    Ok(grid) => {
                        if grid.cp != 0 {
                            report.diagnostics.push(
                                Error::new(
                                    "E_COORDINATE_SYSTEM",
                                    format!(
                                        "GRID {} uses CP={}; coordinates are local and caexfer cannot transform them to the basic frame. Resolve the frame with a trusted BDF preprocessor before conversion; approval flags cannot bypass this error",
                                        grid.id, grid.cp
                                    ),
                                )
                                .at(grid.line)
                                .into(),
                            );
                        }
                        if grid.seid != 0 {
                            report.diagnostics.push(Error::new("E_SUPERELEMENT", format!("GRID {} uses SEID={}; superelements are unsupported", grid.id, grid.seid)).at(grid.line).into());
                        }
                        match points.entry(grid.id) {
                            Entry::Vacant(entry) => { entry.insert(grid); }
                            Entry::Occupied(_) => report.diagnostics.push(Error::new("E_DUPLICATE_GRID", format!("duplicate GRID {}", grid.id)).at(grid.line).into()),
                        }
                    }
                    Err(error) => report.diagnostics.push(error.into()),
                },
                "INCLUDE" => report.diagnostics.push(Error::new("E_INCLUDE_UNRESOLVED", "INCLUDE is not followed; flatten the deck with a trusted tool before geometry projection").at(card.line).into()),
                "GRDSET" => report.diagnostics.push(Error::new("E_GRDSET", "GRID defaults from GRDSET are not implemented; no coordinate defaults will be guessed").at(card.line).into()),
                "ENDDATA" => {},
                name if element_kind(name).is_some() => {

                    // Guard above establishes the match; no user input can make this None.
                    if let Some(kind) = element_kind(name) {
                        match self.parse_element(card, kind) {
                            Ok(element) => {
                                match native_cells.entry(element.id) {
                                    Entry::Vacant(entry) => { entry.insert(element); }
                                    Entry::Occupied(_) => report.diagnostics.push(Error::new("E_DUPLICATE_ELEMENT", format!("duplicate element {}", element.id)).at(element.line).into()),
                                }
                            }
                            Err(error) => report.diagnostics.push(error.into()),
                        }
                    }
                }
                name if opaque_nongeometry(name) => {

                    // Counted once per card type below, not once per large deck record.
                }
                name => report.diagnostics.push(Error::new("E_UNSUPPORTED_CARD", format!("{name} has an unknown effect on geometry; projection is refused")).at(card.line).into()),
            }
        }

        // Opaque nongeometry cards are counted by type for the scoped report.
        for (name, count) in self.card_counts() {
            if opaque_nongeometry(&name) {
                report.diagnostics.push(Diagnostic {
                    severity: Severity::Warning, code: "W_OPAQUE_CARD",
                    message: format!("{count} {name} card(s) not semantically validated; absent from geometry export"),
                    line: None,
                });
            }
        }

        // BTreeMap iteration gives deterministic ID order in the projected
        // points array, independent of source-card order.
        let mut mesh = Mesh::default();
        let mut node_indices = BTreeMap::new();
        for (id, grid) in points {
            node_indices.insert(id, mesh.points.len());
            mesh.points.push(Point {
                id,
                position: grid.coordinates,
            });
        }

        // Translate native GRID IDs to point indices, recording missing and
        // repeated references while retaining other usable cells.
        for (_, element) in native_cells {
            let mut connectivity = Vec::new();
            let mut seen = BTreeSet::new();
            let mut valid = true;
            for id in element.nodes {
                if !seen.insert(id) {
                    report.diagnostics.push(
                        Error::new(
                            "E_DEGENERATE_CONNECTIVITY",
                            format!("element {} repeats GRID {id}", element.id),
                        )
                        .at(element.line)
                        .into(),
                    );
                    valid = false;
                }
                if let Some(&index) = node_indices.get(&id) {
                    connectivity.push(index);
                } else {
                    report.diagnostics.push(
                        Error::new(
                            "E_MISSING_GRID",
                            format!("element {} references missing GRID {id}", element.id),
                        )
                        .at(element.line)
                        .into(),
                    );
                    valid = false;
                }
            }
            if valid {
                mesh.cells.push(Cell {
                    id: element.id,
                    kind: element.kind,
                    connectivity,
                    property_id: element.property_id,
                });
            }
        }
        if mesh.points.is_empty() {
            report
                .diagnostics
                .push(Error::new("E_EMPTY_GEOMETRY", "no usable GRID points found").into());
        }
        (report, mesh)
    }

    /// Explicitly lossy projection. Original IDs survive; materials, loads,
    /// constraints, section details, element offsets/orientations, GRID CD/PS,
    /// comments, and source formatting do not. Always inspect `omissions`.
    /// Geometry requiring unresolved coordinate frames or unknown elements
    /// returns an error instead of a partial mesh.
    ///
    /// # Errors
    ///
    /// Returns the first blocking geometry diagnostic, or an error if the
    /// projected mesh fails its structural checks.
    ///
    pub(crate) fn geometry(&self) -> Result<GeometryProjection> {
        // Refuse a partial mesh if scoped validation found any blocking error.
        let (report, mesh) = self.analyze_geometry();
        if let Some(diagnostic) = report
            .diagnostics
            .iter()
            .find(|d| d.severity == Severity::Error)
        {
            return Err(Error {
                code: diagnostic.code,
                message: diagnostic.message.clone(),
                line: diagnostic.line,
            });
        }
        mesh.validate()?;

        // The projection always loses the original document representation,
        // with additional omissions for full-deck and opaque card content.
        let mut omissions = Vec::new();
        omissions.push(Omission {
            category: "document".into(), count: 1,
            detail: "geometry-only: source text, comments, GRID CD/PS, element orientations/offsets/section data, and solver semantics are not represented; units remain unspecified".into(),
        });
        if self.full_deck {
            omissions.push(Omission {
                category: "control-sections".into(),
                count: 1,
                detail: "executive and case-control sections are not exported".into(),
            });
        }
        for (name, count) in self.card_counts() {
            if opaque_nongeometry(&name) {
                omissions.push(Omission {
                    category: name,
                    count,
                    detail: "opaque nongeometry card(s) not exported".into(),
                });
            }
        }
        let has_nonbasic_output_frame =
            self.grids().any(|grid| grid.is_ok_and(|grid| grid.cd != 0));
        Ok(GeometryProjection {
            mesh,
            omissions,
            has_nonbasic_output_frame,
        })
    }
}