oxiphysics-io 0.1.1

File I/O and serialization for the OxiPhysics engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
// Copyright 2026 COOLJAPAN OU (Team KitaSan)
// SPDX-License-Identifier: Apache-2.0

//! PLOT3D format for CFD grid and solution files.
//!
//! Supports multi-block structured grids in ASCII PLOT3D `.xyz` and `.q`
//! formats as commonly used in CFD solvers.
//!
//! # File layout
//!
//! ## Grid file (.xyz)
//! ```text
//! `nblocks`
//! `ni1` `nj1` `nk1`  [`ni2` `nj2` `nk2` …]
//! <x values block 1> <y values block 1> <z values block 1>
//!//! ```
//!
//! ## Solution file (.q)
//! ```text
//! `nblocks`
//! `ni1` `nj1` `nk1`  [`ni2` `nj2` `nk2` …]
//! `mach` `alpha` `rey` `time`   (per block)
//! `rho` <rho*u> <rho*v> <rho*w> `e`  (per point, per block)
//! ```

use std::fmt::Write as FmtWrite;
use std::str::SplitAsciiWhitespace;

use crate::Error as IoError;

// ── Helper ───────────────────────────────────────────────────────────────────

/// Parse the next f64 token from an iterator.
fn next_f64<'a>(iter: &mut SplitAsciiWhitespace<'a>) -> Result<f64, IoError> {
    iter.next()
        .ok_or_else(|| IoError::Parse("unexpected end of PLOT3D data".into()))?
        .parse::<f64>()
        .map_err(|e| IoError::Parse(e.to_string()))
}

/// Parse the next usize token from an iterator.
fn next_usize<'a>(iter: &mut SplitAsciiWhitespace<'a>) -> Result<usize, IoError> {
    iter.next()
        .ok_or_else(|| IoError::Parse("unexpected end of PLOT3D data".into()))?
        .parse::<usize>()
        .map_err(|e| IoError::Parse(e.to_string()))
}

// ── Grid ─────────────────────────────────────────────────────────────────────

/// A single structured block in a PLOT3D grid.
///
/// Coordinates are stored in row-major order with the fastest index being
/// `i` (x-direction), then `j` (y-direction), then `k` (z-direction).
#[allow(dead_code)]
#[derive(Debug, Clone, PartialEq)]
pub struct Plot3dBlock {
    /// Number of grid points in the i-direction.
    pub ni: usize,
    /// Number of grid points in the j-direction.
    pub nj: usize,
    /// Number of grid points in the k-direction.
    pub nk: usize,
    /// x-coordinates (`ni × nj × nk` values).
    pub x: Vec<f64>,
    /// y-coordinates (`ni × nj × nk` values).
    pub y: Vec<f64>,
    /// z-coordinates (`ni × nj × nk` values).
    pub z: Vec<f64>,
}

impl Plot3dBlock {
    /// Total number of grid points in this block.
    pub fn n_points(&self) -> usize {
        self.ni * self.nj * self.nk
    }
}

/// A multi-block PLOT3D structured grid.
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct Plot3dGrid {
    /// Ordered list of structured blocks.
    pub blocks: Vec<Plot3dBlock>,
}

impl Plot3dGrid {
    /// Create a new empty grid.
    pub fn new() -> Self {
        Self { blocks: Vec::new() }
    }

    /// Number of blocks.
    pub fn n_blocks(&self) -> usize {
        self.blocks.len()
    }

    /// Dimensions `(ni, nj, nk)` of block `b`.
    ///
    /// Returns `None` if `b` is out of range.
    pub fn block_dimensions(&self, b: usize) -> Option<(usize, usize, usize)> {
        self.blocks.get(b).map(|blk| (blk.ni, blk.nj, blk.nk))
    }
}

impl Default for Plot3dGrid {
    fn default() -> Self {
        Self::new()
    }
}

/// Parse an ASCII PLOT3D `.xyz` file from a string.
///
/// # Errors
/// Returns `Error::Parse` if the input is malformed.
pub fn read_plot3d_grid(src: &str) -> Result<Plot3dGrid, IoError> {
    let mut iter = src.split_ascii_whitespace();
    let nblocks = next_usize(&mut iter)?;
    let mut dims: Vec<(usize, usize, usize)> = Vec::with_capacity(nblocks);
    for _ in 0..nblocks {
        let ni = next_usize(&mut iter)?;
        let nj = next_usize(&mut iter)?;
        let nk = next_usize(&mut iter)?;
        dims.push((ni, nj, nk));
    }
    let mut blocks = Vec::with_capacity(nblocks);
    for (ni, nj, nk) in dims {
        let n = ni * nj * nk;
        let mut x = Vec::with_capacity(n);
        let mut y = Vec::with_capacity(n);
        let mut z = Vec::with_capacity(n);
        for _ in 0..n {
            x.push(next_f64(&mut iter)?);
        }
        for _ in 0..n {
            y.push(next_f64(&mut iter)?);
        }
        for _ in 0..n {
            z.push(next_f64(&mut iter)?);
        }
        blocks.push(Plot3dBlock {
            ni,
            nj,
            nk,
            x,
            y,
            z,
        });
    }
    Ok(Plot3dGrid { blocks })
}

/// Write a PLOT3D grid to an ASCII string.
pub fn write_plot3d_grid(grid: &Plot3dGrid) -> String {
    let mut out = String::new();
    let _ = writeln!(out, "{}", grid.n_blocks());
    for blk in &grid.blocks {
        let _ = writeln!(out, "{} {} {}", blk.ni, blk.nj, blk.nk);
    }
    for blk in &grid.blocks {
        let n = blk.n_points();
        for k in 0..n {
            let _ = writeln!(out, "{:.15e}", blk.x[k]);
        }
        for k in 0..n {
            let _ = writeln!(out, "{:.15e}", blk.y[k]);
        }
        for k in 0..n {
            let _ = writeln!(out, "{:.15e}", blk.z[k]);
        }
    }
    out
}

// ── Solution ─────────────────────────────────────────────────────────────────

/// Free-stream reference parameters stored per block in a `.q` file.
#[allow(dead_code)]
#[derive(Debug, Clone, PartialEq)]
pub struct Plot3dFreestream {
    /// Mach number.
    pub mach: f64,
    /// Angle of attack (degrees).
    pub alpha: f64,
    /// Reynolds number.
    pub reynolds: f64,
    /// Non-dimensional time.
    pub time: f64,
}

/// Solution variables at a single grid point.
///
/// The five conservative variables used in the PLOT3D `.q` format are
/// stored: density, three momentum components, and total energy.
#[allow(dead_code)]
#[derive(Debug, Clone, PartialEq)]
pub struct Plot3dQPoint {
    /// Density ρ.
    pub rho: f64,
    /// x-momentum ρ·u.
    pub rho_u: f64,
    /// y-momentum ρ·v.
    pub rho_v: f64,
    /// z-momentum ρ·w.
    pub rho_w: f64,
    /// Total energy per unit volume e.
    pub e: f64,
}

/// A single solution block in a PLOT3D `.q` file.
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct Plot3dSolutionBlock {
    /// Grid dimensions matching the corresponding [`Plot3dBlock`].
    pub ni: usize,
    /// Grid dimensions matching the corresponding [`Plot3dBlock`].
    pub nj: usize,
    /// Grid dimensions matching the corresponding [`Plot3dBlock`].
    pub nk: usize,
    /// Free-stream reference parameters.
    pub freestream: Plot3dFreestream,
    /// Solution data (one entry per grid point).
    pub q: Vec<Plot3dQPoint>,
}

impl Plot3dSolutionBlock {
    /// Total number of solution points.
    pub fn n_points(&self) -> usize {
        self.ni * self.nj * self.nk
    }
}

/// A multi-block PLOT3D solution.
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct Plot3dSolution {
    /// Ordered list of solution blocks.
    pub blocks: Vec<Plot3dSolutionBlock>,
}

impl Plot3dSolution {
    /// Number of blocks in this solution.
    pub fn n_blocks(&self) -> usize {
        self.blocks.len()
    }
}

/// Parse an ASCII PLOT3D `.q` solution file from a string.
///
/// # Errors
/// Returns `Error::Parse` if the input is malformed.
pub fn read_plot3d_solution(src: &str) -> Result<Plot3dSolution, IoError> {
    let mut iter = src.split_ascii_whitespace();
    let nblocks = next_usize(&mut iter)?;
    let mut dims: Vec<(usize, usize, usize)> = Vec::with_capacity(nblocks);
    for _ in 0..nblocks {
        let ni = next_usize(&mut iter)?;
        let nj = next_usize(&mut iter)?;
        let nk = next_usize(&mut iter)?;
        dims.push((ni, nj, nk));
    }
    let mut blocks = Vec::with_capacity(nblocks);
    for (ni, nj, nk) in dims {
        let mach = next_f64(&mut iter)?;
        let alpha = next_f64(&mut iter)?;
        let reynolds = next_f64(&mut iter)?;
        let time = next_f64(&mut iter)?;
        let n = ni * nj * nk;
        let mut q = Vec::with_capacity(n);
        for _ in 0..n {
            let rho = next_f64(&mut iter)?;
            let rho_u = next_f64(&mut iter)?;
            let rho_v = next_f64(&mut iter)?;
            let rho_w = next_f64(&mut iter)?;
            let e = next_f64(&mut iter)?;
            q.push(Plot3dQPoint {
                rho,
                rho_u,
                rho_v,
                rho_w,
                e,
            });
        }
        blocks.push(Plot3dSolutionBlock {
            ni,
            nj,
            nk,
            freestream: Plot3dFreestream {
                mach,
                alpha,
                reynolds,
                time,
            },
            q,
        });
    }
    Ok(Plot3dSolution { blocks })
}

/// Write a PLOT3D solution to an ASCII string.
pub fn write_plot3d_solution(sol: &Plot3dSolution) -> String {
    let mut out = String::new();
    let _ = writeln!(out, "{}", sol.n_blocks());
    for blk in &sol.blocks {
        let _ = writeln!(out, "{} {} {}", blk.ni, blk.nj, blk.nk);
    }
    for blk in &sol.blocks {
        let fs = &blk.freestream;
        let _ = writeln!(
            out,
            "{:.15e} {:.15e} {:.15e} {:.15e}",
            fs.mach, fs.alpha, fs.reynolds, fs.time
        );
        for pt in &blk.q {
            let _ = writeln!(
                out,
                "{:.15e} {:.15e} {:.15e} {:.15e} {:.15e}",
                pt.rho, pt.rho_u, pt.rho_v, pt.rho_w, pt.e
            );
        }
    }
    out
}

// ── Tests ────────────────────────────────────────────────────────────────────

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

    fn make_single_block_grid() -> Plot3dGrid {
        let blk = Plot3dBlock {
            ni: 2,
            nj: 2,
            nk: 1,
            x: vec![0.0, 1.0, 0.0, 1.0],
            y: vec![0.0, 0.0, 1.0, 1.0],
            z: vec![0.0, 0.0, 0.0, 0.0],
        };
        Plot3dGrid { blocks: vec![blk] }
    }

    fn make_single_block_solution() -> Plot3dSolution {
        let fs = Plot3dFreestream {
            mach: 0.5,
            alpha: 0.0,
            reynolds: 1e6,
            time: 0.0,
        };
        let pts: Vec<Plot3dQPoint> = (0..4)
            .map(|i| Plot3dQPoint {
                rho: 1.0 + i as f64 * 0.1,
                rho_u: 0.5,
                rho_v: 0.0,
                rho_w: 0.0,
                e: 2.5,
            })
            .collect();
        Plot3dSolution {
            blocks: vec![Plot3dSolutionBlock {
                ni: 2,
                nj: 2,
                nk: 1,
                freestream: fs,
                q: pts,
            }],
        }
    }

    #[test]
    fn test_grid_n_blocks() {
        let g = make_single_block_grid();
        assert_eq!(g.n_blocks(), 1);
    }

    #[test]
    fn test_grid_n_points() {
        let g = make_single_block_grid();
        assert_eq!(g.blocks[0].n_points(), 4);
    }

    #[test]
    fn test_block_dimensions() {
        let g = make_single_block_grid();
        assert_eq!(g.block_dimensions(0), Some((2, 2, 1)));
    }

    #[test]
    fn test_block_dimensions_out_of_range() {
        let g = make_single_block_grid();
        assert_eq!(g.block_dimensions(5), None);
    }

    #[test]
    fn test_write_read_grid_roundtrip() {
        let original = make_single_block_grid();
        let s = write_plot3d_grid(&original);
        let parsed = read_plot3d_grid(&s).expect("parse should succeed");
        assert_eq!(parsed.n_blocks(), original.n_blocks());
        let orig_blk = &original.blocks[0];
        let pars_blk = &parsed.blocks[0];
        assert_eq!(pars_blk.ni, orig_blk.ni);
        assert_eq!(pars_blk.nj, orig_blk.nj);
        assert_eq!(pars_blk.nk, orig_blk.nk);
        for i in 0..orig_blk.n_points() {
            assert!((orig_blk.x[i] - pars_blk.x[i]).abs() < 1e-10);
            assert!((orig_blk.y[i] - pars_blk.y[i]).abs() < 1e-10);
            assert!((orig_blk.z[i] - pars_blk.z[i]).abs() < 1e-10);
        }
    }

    #[test]
    fn test_read_grid_error_on_empty() {
        assert!(read_plot3d_grid("").is_err());
    }

    #[test]
    fn test_read_grid_error_on_truncated() {
        // Only block count with no dimensions
        assert!(read_plot3d_grid("1").is_err());
    }

    #[test]
    fn test_write_grid_contains_nblocks() {
        let g = make_single_block_grid();
        let s = write_plot3d_grid(&g);
        assert!(s.starts_with("1\n"));
    }

    #[test]
    fn test_solution_n_blocks() {
        let sol = make_single_block_solution();
        assert_eq!(sol.n_blocks(), 1);
    }

    #[test]
    fn test_solution_n_points() {
        let sol = make_single_block_solution();
        assert_eq!(sol.blocks[0].n_points(), 4);
    }

    #[test]
    fn test_write_read_solution_roundtrip() {
        let original = make_single_block_solution();
        let s = write_plot3d_solution(&original);
        let parsed = read_plot3d_solution(&s).expect("parse should succeed");
        assert_eq!(parsed.n_blocks(), original.n_blocks());
        let ob = &original.blocks[0];
        let pb = &parsed.blocks[0];
        assert!((ob.freestream.mach - pb.freestream.mach).abs() < 1e-10);
        assert!((ob.freestream.reynolds - pb.freestream.reynolds).abs() < 1.0);
        for i in 0..ob.n_points() {
            assert!((ob.q[i].rho - pb.q[i].rho).abs() < 1e-10);
            assert!((ob.q[i].rho_u - pb.q[i].rho_u).abs() < 1e-10);
            assert!((ob.q[i].e - pb.q[i].e).abs() < 1e-10);
        }
    }

    #[test]
    fn test_read_solution_error_on_empty() {
        assert!(read_plot3d_solution("").is_err());
    }

    #[test]
    fn test_read_solution_error_on_truncated() {
        assert!(read_plot3d_solution("1").is_err());
    }

    #[test]
    fn test_write_solution_contains_mach() {
        let sol = make_single_block_solution();
        let s = write_plot3d_solution(&sol);
        assert!(s.contains("5.000000000000000e-1") || s.contains("5.0000000000000"));
    }

    #[test]
    fn test_multi_block_grid_roundtrip() {
        let blk1 = Plot3dBlock {
            ni: 2,
            nj: 1,
            nk: 1,
            x: vec![0.0, 1.0],
            y: vec![0.0, 0.0],
            z: vec![0.0, 0.0],
        };
        let blk2 = Plot3dBlock {
            ni: 3,
            nj: 1,
            nk: 1,
            x: vec![1.0, 2.0, 3.0],
            y: vec![0.0, 0.0, 0.0],
            z: vec![0.0, 0.0, 0.0],
        };
        let grid = Plot3dGrid {
            blocks: vec![blk1, blk2],
        };
        let s = write_plot3d_grid(&grid);
        let parsed = read_plot3d_grid(&s).unwrap();
        assert_eq!(parsed.n_blocks(), 2);
        assert_eq!(parsed.blocks[1].ni, 3);
    }

    #[test]
    fn test_plot3d_default_grid() {
        let g = Plot3dGrid::default();
        assert_eq!(g.n_blocks(), 0);
    }

    #[test]
    fn test_plot3d_block_clone() {
        let blk = Plot3dBlock {
            ni: 1,
            nj: 1,
            nk: 1,
            x: vec![0.0],
            y: vec![0.0],
            z: vec![0.0],
        };
        let blk2 = blk.clone();
        assert_eq!(blk2.ni, 1);
    }

    #[test]
    fn test_freestream_clone() {
        let fs = Plot3dFreestream {
            mach: 1.0,
            alpha: 2.0,
            reynolds: 3.0,
            time: 4.0,
        };
        let fs2 = fs.clone();
        assert!((fs2.mach - 1.0).abs() < 1e-12);
    }

    #[test]
    fn test_qpoint_clone() {
        let pt = Plot3dQPoint {
            rho: 1.0,
            rho_u: 2.0,
            rho_v: 3.0,
            rho_w: 4.0,
            e: 5.0,
        };
        let pt2 = pt.clone();
        assert!((pt2.e - 5.0).abs() < 1e-12);
    }

    #[test]
    fn test_grid_debug_format() {
        let g = make_single_block_grid();
        let s = format!("{g:?}");
        assert!(s.contains("Plot3dGrid"));
    }

    #[test]
    fn test_solution_debug_format() {
        let sol = make_single_block_solution();
        let s = format!("{sol:?}");
        assert!(s.contains("Plot3dSolution"));
    }

    #[test]
    fn test_write_grid_has_coordinates() {
        let g = make_single_block_grid();
        let s = write_plot3d_grid(&g);
        // The x=1.0 value must be present as a floating-point token
        assert!(s.contains("1.000000000000000e0") || s.contains("1.0000000000000"));
    }

    #[test]
    fn test_solution_q_length() {
        let sol = make_single_block_solution();
        assert_eq!(sol.blocks[0].q.len(), 4);
    }

    #[test]
    fn test_block_dimensions_3d() {
        let blk = Plot3dBlock {
            ni: 3,
            nj: 4,
            nk: 5,
            x: vec![0.0; 60],
            y: vec![0.0; 60],
            z: vec![0.0; 60],
        };
        let g = Plot3dGrid { blocks: vec![blk] };
        assert_eq!(g.block_dimensions(0), Some((3, 4, 5)));
        assert_eq!(g.blocks[0].n_points(), 60);
    }

    #[test]
    fn test_write_read_3d_block() {
        let n = 8; // 2×2×2
        let blk = Plot3dBlock {
            ni: 2,
            nj: 2,
            nk: 2,
            x: (0..n).map(|i| i as f64 * 0.1).collect(),
            y: (0..n).map(|i| i as f64 * 0.2).collect(),
            z: (0..n).map(|i| i as f64 * 0.3).collect(),
        };
        let grid = Plot3dGrid { blocks: vec![blk] };
        let s = write_plot3d_grid(&grid);
        let parsed = read_plot3d_grid(&s).unwrap();
        for i in 0..n {
            assert!((grid.blocks[0].z[i] - parsed.blocks[0].z[i]).abs() < 1e-10);
        }
    }
}