honeycomb-core 0.11.0

Core structure implementation for combinatorial maps
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
// TODO: replace this with a hashmap too
use std::collections::BTreeMap;

use itertools::multizip;
use num_traits::Zero;
use rustc_hash::FxHashMap as HashMap;
use vtkio::model::{CellType, DataSet, VertexNumbers};
use vtkio::{IOBuffer, Vtk};

use crate::attributes::AttrStorageManager;
use crate::cmap::{BuilderError, CMap2, CMap3, DartIdType, VertexIdType};
use crate::geometry::{CoordsFloat, Vertex2, Vertex3};

// --- Custom

pub(crate) struct CMapFile {
    pub meta: (String, usize, usize),
    pub betas: String,
    pub unused: Option<String>,
    pub vertices: Option<String>,
}

pub(crate) fn parse_meta(meta_line: &str) -> Result<(String, usize, usize), BuilderError> {
    let parts: Vec<&str> = meta_line.split_whitespace().collect();
    if parts.len() != 3 {
        return Err(BuilderError::BadMetaData("incorrect format"));
    }

    Ok((
        parts[0].to_string(),
        parts[1]
            .parse()
            .map_err(|_| BuilderError::BadMetaData("could not parse dimension"))?,
        parts[2]
            .parse()
            .map_err(|_| BuilderError::BadMetaData("could not parse dart number"))?,
    ))
}

impl TryFrom<String> for CMapFile {
    type Error = BuilderError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        let mut sections = HashMap::default();
        let mut current_section = String::new();

        for line in value.trim().lines() {
            let trimmed = line.trim();
            if trimmed.is_empty() || trimmed.starts_with('#') {
                // ignore empty & comment lines
                continue;
            }
            if trimmed.starts_with('[') && trimmed.contains(']') {
                // process section header
                let section_name = trimmed.trim_matches(['[', ']']).to_lowercase();

                if section_name != "meta"
                    && section_name != "betas"
                    && section_name != "unused"
                    && section_name != "vertices"
                {
                    return Err(BuilderError::UnknownHeader(section_name));
                }

                if sections
                    .insert(section_name.clone(), String::new())
                    .is_some()
                {
                    return Err(BuilderError::DuplicatedSection(section_name));
                }
                current_section = section_name;

                continue;
            }
            if !current_section.is_empty() {
                // regular line
                let line_without_comment = trimmed.split('#').next().unwrap().trim();
                if !line_without_comment.is_empty() {
                    let current_content = sections.get_mut(&current_section).unwrap();
                    if !current_content.is_empty() {
                        current_content.push('\n');
                    }
                    current_content.push_str(line_without_comment);
                }
            }
        }

        if !sections.contains_key("meta") {
            // missing required section
            return Err(BuilderError::MissingSection("meta"));
        }
        if !sections.contains_key("betas") {
            // missing required section
            return Err(BuilderError::MissingSection("betas"));
        }

        Ok(Self {
            meta: parse_meta(sections["meta"].as_str())?,
            betas: sections["betas"].clone(),
            unused: sections.get("unused").cloned(),
            vertices: sections.get("vertices").cloned(),
        })
    }
}

// ------ building routines

pub fn build_2d_from_cmap_file<T: CoordsFloat>(
    f: CMapFile,
    manager: AttrStorageManager, // FIXME: find a cleaner solution to populate the manager
) -> Result<CMap2<T>, BuilderError> {
    if f.meta.1 != 2 {
        // mismatched dim
        return Err(BuilderError::BadMetaData(
            "mismatch between requested dimension and header",
        ));
    }
    let map = CMap2::new_with_undefined_attributes(f.meta.2, manager);

    // putting it in a scope to drop the data
    let betas = f.betas.lines().collect::<Vec<_>>();
    if betas.len() != 3 {
        // mismatched dim
        return Err(BuilderError::InconsistentData(
            "wrong number of beta functions",
        ));
    }
    let b0 = betas[0]
        .split_whitespace()
        .map(str::parse)
        .collect::<Vec<_>>();
    let b1 = betas[1]
        .split_whitespace()
        .map(str::parse)
        .collect::<Vec<_>>();
    let b2 = betas[2]
        .split_whitespace()
        .map(str::parse)
        .collect::<Vec<_>>();

    // mismatched dart number
    if b0.len() != f.meta.2 + 1 {
        return Err(BuilderError::InconsistentData(
            "wrong number of values for the beta 0 function",
        ));
    }
    if b1.len() != f.meta.2 + 1 {
        return Err(BuilderError::InconsistentData(
            "wrong number of values for the beta 1 function",
        ));
    }
    if b2.len() != f.meta.2 + 1 {
        return Err(BuilderError::InconsistentData(
            "wrong number of values for the beta 2 function",
        ));
    }

    for (d, b0d, b1d, b2d) in multizip((
        (1..=f.meta.2),
        b0.into_iter().skip(1),
        b1.into_iter().skip(1),
        b2.into_iter().skip(1),
    )) {
        let b0d = b0d.map_err(|_| BuilderError::BadValue("could not parse a b0 value"))?;
        let b1d = b1d.map_err(|_| BuilderError::BadValue("could not parse a b1 value"))?;
        let b2d = b2d.map_err(|_| BuilderError::BadValue("could not parse a b2 value"))?;
        map.set_betas(d as DartIdType, [b0d, b1d, b2d]);
    }

    if let Some(unused) = f.unused {
        for u in unused.split_whitespace() {
            let d = u
                .parse()
                .map_err(|_| BuilderError::BadValue("could not parse an unused ID"))?;
            map.release_dart(d)
                .expect("E: unused dart has non-null beta images");
        }
    }

    if let Some(vertices) = f.vertices {
        for l in vertices.trim().lines() {
            let mut it = l.split_whitespace();
            let id: VertexIdType = it
                .next()
                .ok_or(BuilderError::BadValue("incorrect vertex line format"))?
                .parse()
                .map_err(|_| BuilderError::BadValue("could not parse vertex ID"))?;
            let x: f64 = it
                .next()
                .ok_or(BuilderError::BadValue("incorrect vertex line format"))?
                .parse()
                .map_err(|_| BuilderError::BadValue("could not parse vertex x coordinate"))?;
            let y: f64 = it
                .next()
                .ok_or(BuilderError::BadValue("incorrect vertex line format"))?
                .parse()
                .map_err(|_| BuilderError::BadValue("could not parse vertex y coordinate"))?;
            if it.next().is_some() {
                return Err(BuilderError::BadValue("incorrect vertex line format"));
            }
            map.set_vertex(id, Vertex2(T::from(x).unwrap(), T::from(y).unwrap()));
        }
    }

    Ok(map)
}

#[allow(clippy::too_many_lines)]
pub fn build_3d_from_cmap_file<T: CoordsFloat>(
    f: CMapFile,
    manager: AttrStorageManager, // FIXME: find a cleaner solution to populate the manager
) -> Result<CMap3<T>, BuilderError> {
    if f.meta.1 != 3 {
        // mismatched dim
        return Err(BuilderError::BadMetaData(
            "mismatch between requested dimension and header",
        ));
    }
    let map = CMap3::new_with_undefined_attributes(f.meta.2, manager);

    // putting it in a scope to drop the data
    let betas = f.betas.lines().collect::<Vec<_>>();
    if betas.len() != 4 {
        // mismatched dim
        return Err(BuilderError::InconsistentData(
            "wrong number of beta functions",
        ));
    }
    let b0 = betas[0]
        .split_whitespace()
        .map(str::parse)
        .collect::<Vec<_>>();
    let b1 = betas[1]
        .split_whitespace()
        .map(str::parse)
        .collect::<Vec<_>>();
    let b2 = betas[2]
        .split_whitespace()
        .map(str::parse)
        .collect::<Vec<_>>();
    let b3 = betas[3]
        .split_whitespace()
        .map(str::parse)
        .collect::<Vec<_>>();

    // mismatched dart number
    if b0.len() != f.meta.2 + 1 {
        return Err(BuilderError::InconsistentData(
            "wrong number of values for the beta 0 function",
        ));
    }
    if b1.len() != f.meta.2 + 1 {
        return Err(BuilderError::InconsistentData(
            "wrong number of values for the beta 1 function",
        ));
    }
    if b2.len() != f.meta.2 + 1 {
        return Err(BuilderError::InconsistentData(
            "wrong number of values for the beta 2 function",
        ));
    }
    if b3.len() != f.meta.2 + 1 {
        return Err(BuilderError::InconsistentData(
            "wrong number of values for the beta 2 function",
        ));
    }

    for (d, b0d, b1d, b2d, b3d) in multizip((
        (1..=f.meta.2),
        b0.into_iter().skip(1),
        b1.into_iter().skip(1),
        b2.into_iter().skip(1),
        b3.into_iter().skip(1),
    )) {
        let b0d = b0d.map_err(|_| BuilderError::BadValue("could not parse a b0 value"))?;
        let b1d = b1d.map_err(|_| BuilderError::BadValue("could not parse a b1 value"))?;
        let b2d = b2d.map_err(|_| BuilderError::BadValue("could not parse a b2 value"))?;
        let b3d = b3d.map_err(|_| BuilderError::BadValue("could not parse a b3 value"))?;
        map.set_betas(d as DartIdType, [b0d, b1d, b2d, b3d]);
    }

    if let Some(unused) = f.unused {
        for u in unused.split_whitespace() {
            let d = u
                .parse()
                .map_err(|_| BuilderError::BadValue("could not parse an unused ID"))?;
            map.release_dart(d)
                .expect("E: unused dart has non-null beta images");
        }
    }

    if let Some(vertices) = f.vertices {
        for l in vertices.trim().lines() {
            let mut it = l.split_whitespace();
            let id: VertexIdType = it
                .next()
                .ok_or(BuilderError::BadValue("incorrect vertex line format"))?
                .parse()
                .map_err(|_| BuilderError::BadValue("could not parse vertex ID"))?;
            let x: f64 = it
                .next()
                .ok_or(BuilderError::BadValue("incorrect vertex line format"))?
                .parse()
                .map_err(|_| BuilderError::BadValue("could not parse vertex x coordinate"))?;
            let y: f64 = it
                .next()
                .ok_or(BuilderError::BadValue("incorrect vertex line format"))?
                .parse()
                .map_err(|_| BuilderError::BadValue("could not parse vertex y coordinate"))?;
            let z: f64 = it
                .next()
                .ok_or(BuilderError::BadValue("incorrect vertex line format"))?
                .parse()
                .map_err(|_| BuilderError::BadValue("could not parse vertex z coordinate"))?;
            if it.next().is_some() {
                return Err(BuilderError::BadValue("incorrect vertex line format"));
            }
            map.set_vertex(
                id,
                Vertex3(
                    T::from(x).unwrap(),
                    T::from(y).unwrap(),
                    T::from(z).unwrap(),
                ),
            );
        }
    }

    Ok(map)
}

// --- VTK

macro_rules! if_predicate_return_err {
    ($pr: expr, $er: expr) => {
        if $pr {
            return Err($er);
        }
    };
}

macro_rules! build_vertices {
    ($v: ident) => {{
        if_predicate_return_err!(
            !($v.len() % 3).is_zero(),
            BuilderError::BadVtkData("vertex list contains an incomplete tuple")
        );
        $v.chunks_exact(3)
            .map(|slice| {
                // WE IGNORE Z values
                let &[x, y, _] = slice else { unreachable!() };
                Vertex2(T::from(x).unwrap(), T::from(y).unwrap())
            })
            .collect()
    }};
}

// ------ building routine

#[allow(clippy::too_many_lines)]
/// Internal building routine for [`CMap2::from_vtk_file`].
///
/// # Result / Errors
///
/// This implementation support only a very specific subset of VTK files. This result in many
/// possibilities for failure. This function may return:
///
/// - `Ok(CMap2)` -- The file was successfully parsed and its content made into a 2-map.
/// - `Err(BuilderError)` -- The function failed for one of the following reasons (sorted
///   by [`BuilderError`] variants):
///     - `UnsupportedVtkData`: The file contains unsupported data, i.e.:
///         - file format isn't Legacy,
///         - data set is something other than `UnstructuredGrid`,
///         - coordinate representation type isn't `float` or `double`
///         - mesh contains unsupported cell types (`PolyVertex`, `PolyLine`, `TriangleStrip`,
///           `Pixel` or anything 3D)
///     - `InvalidVtkFile`: The file contains inconsistencies, i.e.:
///         - the number of coordinates cannot be divided by `3`, meaning a tuple is incomplete
///         - the number of `Cells` and `CellTypes` isn't equal
///         - a given cell has an inconsistent number of vertices with its specified cell type
pub fn build_2d_from_vtk<T: CoordsFloat>(
    value: Vtk,
    mut _manager: AttrStorageManager, // FIXME: find a cleaner solution to populate the manager
) -> Result<CMap2<T>, BuilderError> {
    let mut cmap: CMap2<T> = CMap2::new(0);
    let mut sew_buffer: BTreeMap<(usize, usize), DartIdType> = BTreeMap::new();
    match value.data {
        DataSet::ImageData { .. }
        | DataSet::StructuredGrid { .. }
        | DataSet::RectilinearGrid { .. }
        | DataSet::PolyData { .. }
        | DataSet::Field { .. } => {
            return Err(BuilderError::UnsupportedVtkData("dataset not supported"));
        }
        DataSet::UnstructuredGrid { pieces, .. } => {
            let mut tmp = pieces.iter().map(|piece| {
                // assume inline data
                let Ok(tmp) = piece.load_piece_data(None) else {
                    return Err(BuilderError::UnsupportedVtkData("not inlined data piece"));
                };

                // build vertex list
                // since we're expecting coordinates, we'll assume floating type
                // we're also converting directly to our vertex type since we're building a 2-map
                let vertices: Vec<Vertex2<T>> = match tmp.points {
                    IOBuffer::F64(v) => build_vertices!(v),
                    IOBuffer::F32(v) => build_vertices!(v),
                    _ => {
                        return Err(BuilderError::UnsupportedVtkData(
                            "unsupported coordinate type",
                        ));
                    }
                };

                let vtkio::model::Cells { cell_verts, types } = tmp.cells;
                match cell_verts {
                    VertexNumbers::Legacy {
                        num_cells,
                        vertices: verts,
                    } => {
                        // check basic stuff
                        if_predicate_return_err!(
                            num_cells as usize != types.len(),
                            BuilderError::BadVtkData("different # of cell in CELLS and CELL_TYPES")
                        );

                        // build a collection of vertex lists corresponding of each cell
                        let mut cell_components: Vec<Vec<usize>> = Vec::new();
                        let mut take_next = 0;
                        for vertex_id in &verts {
                            if take_next.is_zero() {
                                // making it usize since it's a counter
                                take_next = *vertex_id as usize;
                                cell_components.push(Vec::with_capacity(take_next));
                            } else {
                                cell_components
                                    .last_mut()
                                    .expect("E: unreachable")
                                    .push(*vertex_id as usize);
                                take_next -= 1;
                            }
                        }
                        assert_eq!(num_cells as usize, cell_components.len());

                        let mut errs =
                            types
                                .iter()
                                .zip(cell_components.iter())
                                .map(|(cell_type, vids)| match cell_type {
                                    CellType::Vertex => {
                                        if_predicate_return_err!(
                                            vids.len() != 1,
                                            BuilderError::BadVtkData(
                                                "`Vertex` with incorrect # of vertices (!=1)"
                                            )
                                        );
                                        // silent ignore
                                        Ok(())
                                    }
                                    CellType::PolyVertex => Err(BuilderError::UnsupportedVtkData(
                                        "`PolyVertex` cell type",
                                    )),
                                    CellType::Line => {
                                        if_predicate_return_err!(
                                            vids.len() != 2,
                                            BuilderError::BadVtkData(
                                                "`Line` with incorrect # of vertices (!=2)"
                                            )
                                        );
                                        // silent ignore
                                        Ok(())
                                    }
                                    CellType::PolyLine => Err(BuilderError::UnsupportedVtkData(
                                        "`PolyLine` cell type",
                                    )),
                                    CellType::Triangle => {
                                        // check validity
                                        if_predicate_return_err!(
                                            vids.len() != 3,
                                            BuilderError::BadVtkData(
                                                "`Triangle` with incorrect # of vertices (!=3)"
                                            )
                                        );
                                        // build the triangle
                                        let d0 = cmap.allocate_used_darts(3);
                                        let (d1, d2) = (d0 + 1, d0 + 2);
                                        cmap.set_vertex(d0 as VertexIdType, vertices[vids[0]]);
                                        cmap.set_vertex(d1 as VertexIdType, vertices[vids[1]]);
                                        cmap.set_vertex(d2 as VertexIdType, vertices[vids[2]]);
                                        cmap.link::<1>(d0, d1).unwrap(); // edge d0 links vertices vids[0] & vids[1]
                                        cmap.link::<1>(d1, d2).unwrap(); // edge d1 links vertices vids[1] & vids[2]
                                        cmap.link::<1>(d2, d0).unwrap(); // edge d2 links vertices vids[2] & vids[0]
                                        // record a trace of the built cell for future 2-sew
                                        sew_buffer.insert((vids[0], vids[1]), d0);
                                        sew_buffer.insert((vids[1], vids[2]), d1);
                                        sew_buffer.insert((vids[2], vids[0]), d2);
                                        Ok(())
                                    }
                                    CellType::TriangleStrip => {
                                        Err(BuilderError::UnsupportedVtkData(
                                            "`TriangleStrip` cell type",
                                        ))
                                    }
                                    CellType::Polygon => {
                                        let n_vertices = vids.len();
                                        let d0 = cmap.allocate_used_darts(n_vertices);
                                        (0..n_vertices).for_each(|i| {
                                            let di = d0 + i as DartIdType;
                                            let dip1 =
                                                if i == n_vertices - 1 { d0 } else { di + 1 };
                                            cmap.set_vertex(di as VertexIdType, vertices[vids[i]]);
                                            cmap.link::<1>(di, dip1).unwrap();
                                            sew_buffer
                                                .insert((vids[i], vids[(i + 1) % n_vertices]), di);
                                        });
                                        Ok(())
                                    }
                                    CellType::Pixel => {
                                        Err(BuilderError::UnsupportedVtkData("`Pixel` cell type"))
                                    }
                                    CellType::Quad => {
                                        if_predicate_return_err!(
                                            vids.len() != 4,
                                            BuilderError::BadVtkData(
                                                "`Quad` with incorrect # of vertices (!=4)"
                                            )
                                        );
                                        // build the quad
                                        let d0 = cmap.allocate_used_darts(4);
                                        let (d1, d2, d3) = (d0 + 1, d0 + 2, d0 + 3);
                                        cmap.set_vertex(d0 as VertexIdType, vertices[vids[0]]);
                                        cmap.set_vertex(d1 as VertexIdType, vertices[vids[1]]);
                                        cmap.set_vertex(d2 as VertexIdType, vertices[vids[2]]);
                                        cmap.set_vertex(d3 as VertexIdType, vertices[vids[3]]);
                                        cmap.link::<1>(d0, d1).unwrap(); // edge d0 links vertices vids[0] & vids[1]
                                        cmap.link::<1>(d1, d2).unwrap(); // edge d1 links vertices vids[1] & vids[2]
                                        cmap.link::<1>(d2, d3).unwrap(); // edge d2 links vertices vids[2] & vids[3]
                                        cmap.link::<1>(d3, d0).unwrap(); // edge d3 links vertices vids[3] & vids[0]
                                        // record a trace of the built cell for future 2-sew
                                        sew_buffer.insert((vids[0], vids[1]), d0);
                                        sew_buffer.insert((vids[1], vids[2]), d1);
                                        sew_buffer.insert((vids[2], vids[3]), d2);
                                        sew_buffer.insert((vids[3], vids[0]), d3);
                                        Ok(())
                                    }
                                    _ => Err(BuilderError::UnsupportedVtkData(
                                        "CellType not supported in 2-maps",
                                    )),
                                });
                        if let Some(is_err) = errs.find(Result::is_err) {
                            return Err(is_err.unwrap_err()); // unwrap & wrap because type inference is clunky
                        }
                    }
                    VertexNumbers::XML { .. } => {
                        return Err(BuilderError::UnsupportedVtkData("XML format"));
                    }
                }
                Ok(())
            });
            // return the first error if there is one
            if let Some(is_err) = tmp.find(Result::is_err) {
                return Err(is_err.unwrap_err()); // unwrap & wrap because type inference is clunky
            }
        }
    }
    while let Some(((id0, id1), dart_id0)) = sew_buffer.pop_first() {
        if let Some(dart_id1) = sew_buffer.remove(&(id1, id0)) {
            cmap.sew::<2>(dart_id0, dart_id1).unwrap();
        }
    }
    Ok(cmap)
}