Skip to main content

lensbench_export/
table.rs

1//! 数値の表(列の並び)と、その CSV・JSON・npz(NumPy)への書き出し。
2//!
3//! - [`rays`] は光線の面ごとの交点・方向・光路長を 1 行 1 交点の表にする。
4//! - [`from_json`] は解析の結果(JSON)を表にする(配列の値は `名前_1`, `名前_2`, … の列に展開)。
5//! - npz は無圧縮の zip に `列名.npy` を並べたもの(`numpy.load` で読める)。
6
7use std::io::Write;
8use std::path::Path;
9
10use lensbench_core::{Error, FieldSel, Result, System};
11use serde_json::{json, Map, Value};
12
13/// 列の値
14#[derive(Debug, Clone, PartialEq)]
15pub enum Col {
16    F64(Vec<f64>),
17    I64(Vec<i64>),
18    Str(Vec<String>),
19}
20
21impl Col {
22    pub fn len(&self) -> usize {
23        match self {
24            Col::F64(v) => v.len(),
25            Col::I64(v) => v.len(),
26            Col::Str(v) => v.len(),
27        }
28    }
29    pub fn is_empty(&self) -> bool {
30        self.len() == 0
31    }
32    fn cell(&self, i: usize) -> String {
33        match self {
34            Col::F64(v) => fmt_f64(v[i]),
35            Col::I64(v) => v[i].to_string(),
36            Col::Str(v) => csv_quote(&v[i]),
37        }
38    }
39    fn json(&self) -> Value {
40        match self {
41            // JSON に NaN はないので null にする
42            Col::F64(v) => Value::Array(
43                v.iter()
44                    .map(|&x| if x.is_finite() { json!(x) } else { Value::Null })
45                    .collect(),
46            ),
47            Col::I64(v) => json!(v),
48            Col::Str(v) => json!(v),
49        }
50    }
51}
52
53/// 列の並び(どの列も同じ長さ)
54#[derive(Debug, Clone, Default)]
55pub struct Table {
56    pub cols: Vec<(String, Col)>,
57    /// 表の外の値(単位など)。JSON と npz(スカラーは 0 次元、数の配列は 1 次元の配列)にだけ書く
58    pub meta: Map<String, Value>,
59}
60
61impl Table {
62    pub fn rows(&self) -> usize {
63        self.cols.first().map(|c| c.1.len()).unwrap_or(0)
64    }
65
66    pub fn get(&self, name: &str) -> Option<&Col> {
67        self.cols.iter().find(|c| c.0 == name).map(|c| &c.1)
68    }
69
70    pub fn write_csv<W: Write>(&self, w: &mut W) -> std::io::Result<()> {
71        let h: Vec<String> = self.cols.iter().map(|c| csv_quote(&c.0)).collect();
72        writeln!(w, "{}", h.join(","))?;
73        for i in 0..self.rows() {
74            let r: Vec<String> = self.cols.iter().map(|c| c.1.cell(i)).collect();
75            writeln!(w, "{}", r.join(","))?;
76        }
77        Ok(())
78    }
79
80    /// JSON: {"meta"..., "columns": {名前: [値…]}}(列ごと)
81    pub fn to_json(&self) -> Value {
82        let mut o = self.meta.clone();
83        let mut c = Map::new();
84        for (n, v) in &self.cols {
85            c.insert(n.clone(), v.json());
86        }
87        o.insert("rows".into(), json!(self.rows()));
88        o.insert("columns".into(), Value::Object(c));
89        Value::Object(o)
90    }
91
92    pub fn write_npz<W: Write>(&self, w: &mut W) -> std::io::Result<()> {
93        let mut z = Zip::new(ZIP_LIMITS);
94        write_npz_meta(&mut z, w, &self.meta)?;
95        for (n, c) in &self.cols {
96            z.add(w, &format!("{n}.npy"), &[&npy(c, false)])?;
97        }
98        z.finish(w)
99    }
100
101    /// 同じ列の並びの表を後ろに足す([`rays_each`] の塊をつなぐ)
102    fn append(&mut self, other: Table) {
103        if self.cols.is_empty() {
104            self.cols = other.cols;
105            return;
106        }
107        for ((_, a), (_, b)) in self.cols.iter_mut().zip(other.cols) {
108            match (a, b) {
109                (Col::F64(a), Col::F64(b)) => a.extend(b),
110                (Col::I64(a), Col::I64(b)) => a.extend(b),
111                (Col::Str(a), Col::Str(b)) => a.extend(b),
112                _ => unreachable!("the chunks have the same columns"),
113            }
114        }
115    }
116
117    /// 拡張子(csv・json・npz)で決めて書き出す
118    pub fn save(&self, path: &Path) -> lensbench_core::Result<()> {
119        let e = path
120            .extension()
121            .and_then(|x| x.to_str())
122            .map(|x| x.to_ascii_lowercase())
123            .unwrap_or_default();
124        let mut w: Vec<u8> = Vec::new();
125        let r = match e.as_str() {
126            "csv" => self.write_csv(&mut w),
127            "json" => serde_json::to_writer_pretty(&mut w, &self.to_json())
128                .map_err(std::io::Error::other)
129                .and_then(|_| writeln!(w)),
130            "npz" => self.write_npz(&mut w),
131            _ => {
132                return Err(
133                    format!("{}: the extension must be csv, json or npz", path.display()).into(),
134                );
135            }
136        };
137        r.and_then(|_| lensbench_core::vfs::write(path, w))
138            .map_err(lensbench_core::Error::io_at(path.display()))
139    }
140}
141
142fn fmt_f64(v: f64) -> String {
143    if v.is_nan() {
144        "nan".into()
145    } else if v.is_infinite() {
146        if v > 0.0 { "inf" } else { "-inf" }.into()
147    } else {
148        // 往復で同じ値に戻る最短の表記
149        format!("{v:?}")
150    }
151}
152
153fn csv_quote(s: &str) -> String {
154    if s.contains([',', '"', '\n', '\r']) {
155        format!("\"{}\"", s.replace('"', "\"\""))
156    } else {
157        s.to_string()
158    }
159}
160
161/// 表の外の値を npz に書く(スカラーは 0 次元、数の配列は 1 次元。ほかの値は書かない)
162fn write_npz_meta<W: Write>(
163    z: &mut Zip,
164    w: &mut W,
165    meta: &Map<String, Value>,
166) -> std::io::Result<()> {
167    for (k, v) in meta {
168        let c = match v {
169            Value::Number(n) => Some(match n.as_i64() {
170                Some(i) => npy(&Col::I64(vec![i]), true),
171                None => npy(&Col::F64(vec![n.as_f64().unwrap_or(f64::NAN)]), true),
172            }),
173            Value::String(s) => Some(npy(&Col::Str(vec![s.clone()]), true)),
174            Value::Array(a) if !a.is_empty() && a.iter().all(Value::is_number) => Some(npy(
175                &Col::F64(a.iter().map(|x| x.as_f64().unwrap_or(f64::NAN)).collect()),
176                false,
177            )),
178            _ => None,
179        };
180        if let Some(b) = c {
181            z.add(w, &format!("{k}.npy"), &[&b])?;
182        }
183    }
184    Ok(())
185}
186
187/// .npy の頭(版 1.0)。`shape` は `()`(0 次元)か `(n,)`
188fn npy_header(descr: &str, shape: &str) -> Vec<u8> {
189    let mut h = format!("{{'descr': '{descr}', 'fortran_order': False, 'shape': {shape}, }}");
190    // 魔法の 6 + 版 2 + 長さ 2 + 見出し + 改行 が 64 の倍数
191    while (10 + h.len() + 1) % 64 != 0 {
192        h.push(' ');
193    }
194    h.push('\n');
195    let mut b = Vec::with_capacity(10 + h.len());
196    b.extend_from_slice(b"\x93NUMPY\x01\x00");
197    b.extend_from_slice(&(h.len() as u16).to_le_bytes());
198    b.extend_from_slice(h.as_bytes());
199    b
200}
201
202/// .npy(版 1.0、リトルエンディアン)。scalar なら 0 次元
203fn npy(c: &Col, scalar: bool) -> Vec<u8> {
204    let (descr, data): (String, Vec<u8>) = match c {
205        Col::F64(v) => (
206            "<f8".into(),
207            v.iter().flat_map(|x| x.to_le_bytes()).collect(),
208        ),
209        Col::I64(v) => (
210            "<i8".into(),
211            v.iter().flat_map(|x| x.to_le_bytes()).collect(),
212        ),
213        Col::Str(v) => {
214            let n = v
215                .iter()
216                .map(|s| s.chars().count())
217                .max()
218                .unwrap_or(0)
219                .max(1);
220            let mut d = Vec::with_capacity(v.len() * n * 4);
221            for s in v {
222                let mut k = 0;
223                for ch in s.chars() {
224                    d.extend_from_slice(&(ch as u32).to_le_bytes());
225                    k += 1;
226                }
227                d.extend(std::iter::repeat_n(0u8, (n - k) * 4));
228            }
229            (format!("<U{n}"), d)
230        }
231    };
232    let shape = if scalar {
233        "()".to_string()
234    } else {
235        format!("({},)", c.len())
236    };
237    let mut b = npy_header(&descr, &shape);
238    b.extend_from_slice(&data);
239    b
240}
241
242#[cfg(test)]
243fn crc32(b: &[u8]) -> u32 {
244    !crc32_update(!0, b)
245}
246
247/// CRC-32 を続けて計算する(始めは `!0`、終わりに `!` を取る)
248fn crc32_update(mut c: u32, b: &[u8]) -> u32 {
249    static TABLE: std::sync::OnceLock<[u32; 256]> = std::sync::OnceLock::new();
250    let t = TABLE.get_or_init(|| {
251        let mut t = [0u32; 256];
252        for (i, e) in t.iter_mut().enumerate() {
253            let mut c = i as u32;
254            for _ in 0..8 {
255                c = if c & 1 != 0 {
256                    0xEDB8_8320 ^ (c >> 1)
257                } else {
258                    c >> 1
259                };
260            }
261            *e = c;
262        }
263        t
264    });
265    for &x in b {
266        c = t[((c ^ x as u32) & 0xff) as usize] ^ (c >> 8);
267    }
268    c
269}
270
271/// zip の 32 ビット・16 ビットの欄の上限(これ以上は zip64 の欄に書き、こちらは 0xFFFFFFFF・0xFFFF)
272#[derive(Clone, Copy)]
273struct ZipLimits {
274    u32: u64,
275    u16: usize,
276}
277
278const ZIP_LIMITS: ZipLimits = ZipLimits {
279    u32: u32::MAX as u64,
280    u16: u16::MAX as usize,
281};
282
283/// 無圧縮の zip(npz 用)を足すそばから書く(中身を全部は持たない)。4 GB・65,535 個を超える分は zip64 で書く
284/// (numpy の np.load も読む)
285struct Zip {
286    lim: ZipLimits,
287    /// 次の局所の頭の位置
288    off: u64,
289    central: Vec<u8>,
290    n: usize,
291}
292
293impl Zip {
294    fn new(lim: ZipLimits) -> Zip {
295        Zip {
296            lim,
297            off: 0,
298            central: Vec::new(),
299            n: 0,
300        }
301    }
302
303    /// 1 つ書く。中身は `parts` をつないだもの
304    fn add<W: Write>(&mut self, w: &mut W, name: &str, parts: &[&[u8]]) -> std::io::Result<()> {
305        let lim = self.lim;
306        let off = self.off;
307        let crc = !parts.iter().fold(!0u32, |c, p| crc32_update(c, p));
308        let nb = name.as_bytes();
309        let size: u64 = parts.iter().map(|p| p.len() as u64).sum();
310        let big = size >= lim.u32;
311        let far = off >= lim.u32;
312        // 版: zip64 の欄を持つなら 4.5
313        let ver: u16 = if big || far { 45 } else { 20 };
314        let size32 = if big { u32::MAX } else { size as u32 };
315        // 局所の頭: 大きければ大きさは zip64 の追加の欄(元の大きさ・圧縮後の大きさ)
316        let mut lx = Vec::new();
317        if big {
318            lx.extend_from_slice(&1u16.to_le_bytes());
319            lx.extend_from_slice(&16u16.to_le_bytes());
320            lx.extend_from_slice(&size.to_le_bytes());
321            lx.extend_from_slice(&size.to_le_bytes());
322        }
323        let mut h = Vec::with_capacity(30 + nb.len() + lx.len());
324        h.extend_from_slice(&0x0403_4b50u32.to_le_bytes());
325        h.extend_from_slice(&ver.to_le_bytes());
326        h.extend_from_slice(&0u16.to_le_bytes()); // フラグ
327        h.extend_from_slice(&0u16.to_le_bytes()); // 無圧縮
328        h.extend_from_slice(&0u16.to_le_bytes()); // 時刻
329        h.extend_from_slice(&0x0021u16.to_le_bytes()); // 日付 1980-01-01
330        h.extend_from_slice(&crc.to_le_bytes());
331        h.extend_from_slice(&size32.to_le_bytes());
332        h.extend_from_slice(&size32.to_le_bytes());
333        h.extend_from_slice(&(nb.len() as u16).to_le_bytes());
334        h.extend_from_slice(&(lx.len() as u16).to_le_bytes());
335        h.extend_from_slice(nb);
336        h.extend_from_slice(&lx);
337        w.write_all(&h)?;
338        for p in parts {
339            w.write_all(p)?;
340        }
341        // 中央の頭: zip64 の追加の欄は、溢れた欄だけを元の大きさ・圧縮後の大きさ・頭の位置の順に
342        let mut cx = Vec::new();
343        if big {
344            cx.extend_from_slice(&size.to_le_bytes());
345            cx.extend_from_slice(&size.to_le_bytes());
346        }
347        if far {
348            cx.extend_from_slice(&off.to_le_bytes());
349        }
350        if !cx.is_empty() {
351            let body = std::mem::take(&mut cx);
352            cx.extend_from_slice(&1u16.to_le_bytes());
353            cx.extend_from_slice(&(body.len() as u16).to_le_bytes());
354            cx.extend_from_slice(&body);
355        }
356        let c = &mut self.central;
357        c.extend_from_slice(&0x0201_4b50u32.to_le_bytes());
358        c.extend_from_slice(&ver.to_le_bytes());
359        c.extend_from_slice(&ver.to_le_bytes());
360        c.extend_from_slice(&0u16.to_le_bytes());
361        c.extend_from_slice(&0u16.to_le_bytes());
362        c.extend_from_slice(&0u16.to_le_bytes());
363        c.extend_from_slice(&0x0021u16.to_le_bytes());
364        c.extend_from_slice(&crc.to_le_bytes());
365        c.extend_from_slice(&size32.to_le_bytes());
366        c.extend_from_slice(&size32.to_le_bytes());
367        c.extend_from_slice(&(nb.len() as u16).to_le_bytes());
368        c.extend_from_slice(&(cx.len() as u16).to_le_bytes());
369        c.extend_from_slice(&[0u8; 6]); // 注釈・ディスク番号・内部属性
370        c.extend_from_slice(&0u32.to_le_bytes()); // 外部属性
371        c.extend_from_slice(&(if far { u32::MAX } else { off as u32 }).to_le_bytes());
372        c.extend_from_slice(nb);
373        c.extend_from_slice(&cx);
374        self.off += h.len() as u64 + size;
375        self.n += 1;
376        Ok(())
377    }
378
379    /// 中央の目録と終わりの記録を書く
380    fn finish<W: Write>(self, w: &mut W) -> std::io::Result<()> {
381        let Zip {
382            lim,
383            off,
384            central,
385            n,
386        } = self;
387        w.write_all(&central)?;
388        let clen = central.len() as u64;
389        // 終わりの記録: 数・中央の大きさ・位置のどれかが溢れれば、zip64 の終わりの記録とその在り処を先に書く
390        let z64 = n >= lim.u16 || clen >= lim.u32 || off >= lim.u32;
391        if z64 {
392            let mut e = Vec::with_capacity(56 + 20);
393            e.extend_from_slice(&0x0606_4b50u32.to_le_bytes());
394            e.extend_from_slice(&44u64.to_le_bytes()); // この後の大きさ
395            e.extend_from_slice(&45u16.to_le_bytes());
396            e.extend_from_slice(&45u16.to_le_bytes());
397            e.extend_from_slice(&[0u8; 8]); // ディスク番号
398            e.extend_from_slice(&(n as u64).to_le_bytes());
399            e.extend_from_slice(&(n as u64).to_le_bytes());
400            e.extend_from_slice(&clen.to_le_bytes());
401            e.extend_from_slice(&off.to_le_bytes());
402            e.extend_from_slice(&0x0706_4b50u32.to_le_bytes());
403            e.extend_from_slice(&0u32.to_le_bytes());
404            e.extend_from_slice(&(off + clen).to_le_bytes());
405            e.extend_from_slice(&1u32.to_le_bytes()); // ディスクの数
406            w.write_all(&e)?;
407        }
408        let n16 = if n >= lim.u16 { u16::MAX } else { n as u16 };
409        let c32 = |x: u64| if x >= lim.u32 { u32::MAX } else { x as u32 };
410        let mut e = Vec::with_capacity(22);
411        e.extend_from_slice(&0x0605_4b50u32.to_le_bytes());
412        e.extend_from_slice(&[0u8; 4]);
413        e.extend_from_slice(&n16.to_le_bytes());
414        e.extend_from_slice(&n16.to_le_bytes());
415        e.extend_from_slice(&c32(clen).to_le_bytes());
416        e.extend_from_slice(&c32(off).to_le_bytes());
417        e.extend_from_slice(&0u16.to_le_bytes());
418        w.write_all(&e)
419    }
420}
421
422/// 光線の表の作り方
423#[derive(Debug, Clone)]
424pub struct RayOptions {
425    /// 視野・波長(0 始まり)。None で全視野・主波長
426    pub fields: Option<Vec<usize>>,
427    pub waves: Option<Vec<usize>>,
428    /// 瞳座標
429    pub px: Vec<f64>,
430    pub py: Vec<f64>,
431    /// 書く面(None で物体面を除く全部、像面まで)
432    pub surfaces: Option<Vec<usize>>,
433}
434
435/// 光線の表の列([`rays`])。i は整数、f は実数
436const RAY_COLS: [(&str, bool); 18] = [
437    ("field", false),
438    ("wave", false),
439    ("ray", false),
440    ("px", true),
441    ("py", true),
442    ("surface", false),
443    ("x", true),
444    ("y", true),
445    ("z", true),
446    ("l", true),
447    ("m", true),
448    ("n", true),
449    ("gx", true),
450    ("gy", true),
451    ("gz", true),
452    ("opl", true),
453    ("err", false),
454    ("vig", false),
455];
456
457/// 光線の面ごとの交点の表(1 行 = 1 光線 × 1 面)。
458///
459/// 列: field・wave(1 始まり)、ray(0 始まり)、px・py、surface、
460/// x・y・z と l・m・n(その面の局所座標)、gx・gy・gz(大域座標)、opl(光線の開始点からの光路長 mm。
461/// 無限遠の物体では面 1 の頂点を通る、光線に垂直な面から)、
462/// err・vig(光線が止まった面・けられた面、0 はなし)。止まった後の面の値は NaN
463pub fn rays(s: &System, o: &RayOptions) -> Result<Table> {
464    let mut all = Table::default();
465    let meta = rays_each(s, o, |t| {
466        all.append(t);
467        Ok(())
468    })?;
469    if all.cols.is_empty() {
470        all = ray_chunk(Default::default(), Default::default(), Default::default());
471    }
472    all.meta = meta;
473    Ok(all)
474}
475
476/// [`rays`] の表を、視野・波長の組ごとの塊(同じ列の [`Table`]、meta は空)で `f` に渡す。返すのは表の meta。
477/// 全体を持たずに書き出すため([`save_rays`])
478pub fn rays_each(
479    s: &System,
480    o: &RayOptions,
481    mut f: impl FnMut(Table) -> Result<()>,
482) -> Result<Map<String, Value>> {
483    let nf = s.fields.len();
484    let nw = s.wavelengths.len();
485    let fields = o.fields.clone().unwrap_or_else(|| (0..nf).collect());
486    let waves = o.waves.clone().unwrap_or_else(|| vec![s.primary]);
487    if let Some(&i) = fields.iter().find(|&&i| i >= nf) {
488        return Err(Error::Invalid(format!("no field {} (1 to {nf})", i + 1)));
489    }
490    for &i in &waves {
491        lensbench_core::waves::index(i + 1, nw)?;
492    }
493    let img = s.image();
494    let surfs: Vec<usize> = match &o.surfaces {
495        None => (1..=img).collect(),
496        Some(v) => v.clone(),
497    };
498    if let Some(&j) = surfs.iter().find(|&&j| j == 0 || j > img) {
499        return Err(Error::Invalid(format!(
500            "surface {j} can't be written (1 to {img})"
501        )));
502    }
503    let last = *surfs.iter().max().unwrap_or(&img);
504    for &fi in &fields {
505        for &w in &waves {
506            let t = s.try_trace(FieldSel::Index(fi), &o.px, &o.py, Some(w), Some(last), true)?;
507            let mut ints: [Vec<i64>; 6] = Default::default();
508            let mut pxy: [Vec<f64>; 2] = Default::default();
509            let mut v: [Vec<f64>; 10] = Default::default();
510            for i in 0..o.px.len() {
511                let r = &t.rays[i];
512                for &j in &surfs {
513                    // 無視する面は記録がない
514                    let Some(q) = t.rec_at(j) else {
515                        continue;
516                    };
517                    let e = q.entry(i);
518                    ints[0].push(fi as i64 + 1);
519                    ints[1].push(w as i64 + 1);
520                    ints[2].push(i as i64);
521                    pxy[0].push(o.px[i]);
522                    pxy[1].push(o.py[i]);
523                    ints[3].push(j as i64);
524                    let vals = [
525                        e.xyz[0], e.xyz[1], e.xyz[2], e.lmn[0], e.lmn[1], e.lmn[2], e.p[0], e.p[1],
526                        e.p[2], e.opl,
527                    ];
528                    for k in 0..10 {
529                        v[k].push(vals[k]);
530                    }
531                    ints[4].push(r.status.code() as i64);
532                    ints[5].push(r.vig as i64);
533                }
534            }
535            f(ray_chunk(ints, pxy, v))?;
536        }
537    }
538    let mut meta = Map::new();
539    meta.insert("name".into(), json!(s.name));
540    meta.insert("unit".into(), json!("mm"));
541    meta.insert("wavelengths_um".into(), json!(s.wavelengths));
542    Ok(meta)
543}
544
545/// 光線の表の塊(整数の列 field・wave・ray・surface・err・vig、px・py、実数の列 x〜opl)
546fn ray_chunk(ints: [Vec<i64>; 6], pxy: [Vec<f64>; 2], v: [Vec<f64>; 10]) -> Table {
547    let [f, w, r, s, err, vig] = ints;
548    let [px, py] = pxy;
549    let mut cols = vec![
550        ("field".to_string(), Col::I64(f)),
551        ("wave".to_string(), Col::I64(w)),
552        ("ray".to_string(), Col::I64(r)),
553        ("px".to_string(), Col::F64(px)),
554        ("py".to_string(), Col::F64(py)),
555        ("surface".to_string(), Col::I64(s)),
556    ];
557    for ((n, _), c) in RAY_COLS[6..16].iter().zip(v) {
558        cols.push((n.to_string(), Col::F64(c)));
559    }
560    cols.push(("err".into(), Col::I64(err)));
561    cols.push(("vig".into(), Col::I64(vig)));
562    Table {
563        cols,
564        meta: Map::new(),
565    }
566}
567
568/// 書き出しの塊を溜めてから vfs の末尾に足す(1 回ごとにファイルを開かないため)
569struct VfsAppend {
570    path: std::path::PathBuf,
571    buf: Vec<u8>,
572}
573
574impl VfsAppend {
575    const CHUNK: usize = 8 << 20;
576}
577
578impl Write for VfsAppend {
579    fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
580        self.buf.extend_from_slice(b);
581        if self.buf.len() >= Self::CHUNK {
582            self.flush()?;
583        }
584        Ok(b.len())
585    }
586    fn flush(&mut self) -> std::io::Result<()> {
587        if !self.buf.is_empty() {
588            lensbench_core::vfs::append(&self.path, &self.buf)?;
589            self.buf.clear();
590        }
591        Ok(())
592    }
593}
594
595/// 一時の列のファイルを消す(途中の誤りでも残さない)
596struct Parts(Vec<std::path::PathBuf>);
597
598impl Drop for Parts {
599    fn drop(&mut self) {
600        for p in &self.0 {
601            let _ = lensbench_core::vfs::remove_file(p);
602        }
603    }
604}
605
606/// [`rays`] の表を、全体をメモリに作らずにファイルへ書く。CSV は塊ごとに末尾へ、npz は列ごとの一時ファイル
607/// (書き出し先の隣の `<名前>.part<k>`)に溜めて最後に 1 列ずつ zip に写す。JSON は列ごとの形なので [`rays`] で作ってから書く。
608/// 中身は `rays(s, o)?.save(path)` と同じ。返すのは行の数
609pub fn save_rays(s: &System, o: &RayOptions, path: &Path) -> Result<usize> {
610    let e = path
611        .extension()
612        .and_then(|x| x.to_str())
613        .map(|x| x.to_ascii_lowercase())
614        .unwrap_or_default();
615    let io = |r: std::io::Result<()>| r.map_err(lensbench_core::Error::io_at(path.display()));
616    match e.as_str() {
617        "csv" => {
618            let h: Vec<String> = RAY_COLS.iter().map(|c| csv_quote(c.0)).collect();
619            io(lensbench_core::vfs::write(
620                path,
621                format!("{}\n", h.join(",")),
622            ))?;
623            let mut rows = 0;
624            let mut w = VfsAppend {
625                path: path.to_path_buf(),
626                buf: Vec::new(),
627            };
628            let r = rays_each(s, o, |t| {
629                rows += t.rows();
630                for i in 0..t.rows() {
631                    let r: Vec<String> = t.cols.iter().map(|c| c.1.cell(i)).collect();
632                    io(writeln!(w, "{}", r.join(",")))?;
633                }
634                Ok(())
635            });
636            let done = r.and_then(|_| io(w.flush()));
637            if done.is_err() {
638                let _ = lensbench_core::vfs::remove_file(path);
639            }
640            done.map(|_| rows)
641        }
642        "npz" => {
643            let parts = Parts(
644                (0..RAY_COLS.len())
645                    .map(|k| {
646                        let mut n = path.file_name().unwrap_or_default().to_os_string();
647                        n.push(format!(".part{k}"));
648                        path.with_file_name(n)
649                    })
650                    .collect(),
651            );
652            for p in &parts.0 {
653                io(lensbench_core::vfs::write(p, b""))?;
654            }
655            let mut rows = 0;
656            let meta = rays_each(s, o, |t| {
657                rows += t.rows();
658                for ((_, c), p) in t.cols.iter().zip(&parts.0) {
659                    let b: Vec<u8> = match c {
660                        Col::F64(v) => v.iter().flat_map(|x| x.to_le_bytes()).collect(),
661                        Col::I64(v) => v.iter().flat_map(|x| x.to_le_bytes()).collect(),
662                        Col::Str(_) => unreachable!("the ray table has no text columns"),
663                    };
664                    io(lensbench_core::vfs::append(p, b))?;
665                }
666                Ok(())
667            })?;
668            io(lensbench_core::vfs::write(path, b""))?;
669            let mut w = VfsAppend {
670                path: path.to_path_buf(),
671                buf: Vec::new(),
672            };
673            let done = (|| -> std::io::Result<()> {
674                let mut z = Zip::new(ZIP_LIMITS);
675                write_npz_meta(&mut z, &mut w, &meta)?;
676                for ((n, float), p) in RAY_COLS.iter().zip(&parts.0) {
677                    let data = lensbench_core::vfs::read(p)?;
678                    let descr = if *float { "<f8" } else { "<i8" };
679                    let h = npy_header(descr, &format!("({rows},)"));
680                    z.add(&mut w, &format!("{n}.npy"), &[&h, &data])?;
681                }
682                z.finish(&mut w)?;
683                w.flush()
684            })();
685            if done.is_err() {
686                let _ = lensbench_core::vfs::remove_file(path);
687            }
688            io(done).map(|_| rows)
689        }
690        _ => {
691            let t = rays(s, o)?;
692            t.save(path)?;
693            Ok(t.rows())
694        }
695    }
696}
697
698/// 解析の結果(JSON)を表にする。最初の「オブジェクトの配列」の値を行に、なければ全体を 1 行にする。
699/// 配列の値は `名前_1`, `名前_2`, …(入れ子は `名前_1_2`)の列に展開する。表の外のスカラーは meta へ
700pub fn from_json(v: &Value) -> Table {
701    let mut meta = Map::new();
702    let mut records: Option<&Vec<Value>> = None;
703    if let Value::Object(m) = v {
704        for (k, x) in m {
705            match x {
706                Value::Array(a)
707                    if records.is_none() && !a.is_empty() && a.iter().all(Value::is_object) =>
708                {
709                    records = Some(a)
710                }
711                Value::Number(_) | Value::String(_) | Value::Bool(_) => {
712                    meta.insert(k.clone(), x.clone());
713                }
714                _ => {}
715            }
716        }
717    }
718    let one = [v.clone()];
719    let recs: &[Value] = match records {
720        Some(a) => a,
721        None => {
722            meta.clear();
723            &one
724        }
725    };
726    // 行ごとに平らにした (列名, 値)
727    let flat: Vec<Vec<(String, Value)>> = recs
728        .iter()
729        .map(|r| {
730            let mut out = Vec::new();
731            if let Value::Object(m) = r {
732                for (k, x) in m {
733                    flatten(k, x, &mut out);
734                }
735            }
736            out
737        })
738        .collect();
739    let mut names: Vec<String> = Vec::new();
740    for r in &flat {
741        for (k, _) in r {
742            if !names.contains(k) {
743                names.push(k.clone());
744            }
745        }
746    }
747    let mut cols = Vec::new();
748    for n in names {
749        let vals: Vec<Option<&Value>> = flat
750            .iter()
751            .map(|r| r.iter().find(|(k, _)| *k == n).map(|x| &x.1))
752            .collect();
753        // 整数の列は取り出しと同じ式で判定する
754        let ints: Option<Vec<i64>> = vals.iter().map(|x| x.and_then(Value::as_i64)).collect();
755        let all_num = vals
756            .iter()
757            .all(|x| matches!(x, None | Some(Value::Number(_)) | Some(Value::Null)));
758        let col = if let Some(ints) = ints {
759            Col::I64(ints)
760        } else if all_num {
761            Col::F64(
762                vals.iter()
763                    .map(|x| x.and_then(Value::as_f64).unwrap_or(f64::NAN))
764                    .collect(),
765            )
766        } else {
767            Col::Str(
768                vals.iter()
769                    .map(|x| match x {
770                        Some(Value::String(s)) => s.clone(),
771                        Some(Value::Null) | None => String::new(),
772                        Some(o) => o.to_string(),
773                    })
774                    .collect(),
775            )
776        };
777        cols.push((n, col));
778    }
779    Table { cols, meta }
780}
781
782fn flatten(k: &str, x: &Value, out: &mut Vec<(String, Value)>) {
783    match x {
784        Value::Array(a) => {
785            for (i, y) in a.iter().enumerate() {
786                flatten(&format!("{k}_{}", i + 1), y, out);
787            }
788        }
789        Value::Object(m) => {
790            for (kk, y) in m {
791                flatten(&format!("{k}_{kk}"), y, out);
792            }
793        }
794        _ => out.push((k.to_string(), x.clone())),
795    }
796}
797
798#[cfg(test)]
799mod tests {
800    use super::*;
801
802    /// 上限を小さくして zip64 の欄(大きさ・位置・数)を書かせ、npz の読み手で読み直す
803    #[test]
804    fn npz_over_limits_is_zip64() {
805        let cols = [
806            ("a", Col::F64((0..40).map(f64::from).collect())),
807            ("b", Col::I64(vec![1, 2, 3])),
808            ("c", Col::F64(vec![0.5])),
809        ];
810        let write = |lim: ZipLimits| {
811            let mut z = Zip::new(lim);
812            let mut out = Vec::new();
813            for (n, c) in &cols {
814                z.add(&mut out, &format!("{n}.npy"), &[&npy(c, false)])
815                    .unwrap();
816            }
817            z.finish(&mut out).unwrap();
818            out
819        };
820        let small = write(ZIP_LIMITS);
821        let big = write(ZipLimits { u32: 200, u16: 2 });
822        assert!(big.windows(4).any(|w| w == 0x0606_4b50u32.to_le_bytes()));
823        assert!(!small.windows(4).any(|w| w == 0x0606_4b50u32.to_le_bytes()));
824        for b in [small, big] {
825            let mut r = ndarray_npy::NpzReader::new(std::io::Cursor::new(b)).unwrap();
826            let a: ndarray::Array1<f64> = r.by_name("a.npy").unwrap();
827            assert_eq!(a.len(), 40);
828            assert_eq!(a[39], 39.0);
829            let b: ndarray::Array1<i64> = r.by_name("b.npy").unwrap();
830            assert_eq!(b.to_vec(), [1, 2, 3]);
831            let c: ndarray::Array1<f64> = r.by_name("c.npy").unwrap();
832            assert_eq!(c.to_vec(), [0.5]);
833        }
834    }
835
836    #[test]
837    fn crc32_known_value() {
838        assert_eq!(crc32(b"123456789"), 0xCBF4_3926);
839    }
840
841    #[test]
842    fn npy_header_is_aligned() {
843        let b = npy(&Col::F64(vec![1.0, 2.0]), false);
844        let hl = u16::from_le_bytes([b[8], b[9]]) as usize;
845        assert_eq!((10 + hl) % 64, 0);
846        assert_eq!(b.len(), 10 + hl + 16);
847        assert!(std::str::from_utf8(&b[10..10 + hl])
848            .unwrap()
849            .contains("'shape': (2,)"));
850    }
851
852    #[test]
853    fn json_records_are_flattened() {
854        let v = json!({"unit": "waves", "zernike": [
855            {"field": 1, "coef": [0.1, 0.2], "pv": 0.5},
856            {"field": 2, "coef": [0.3, 0.4], "pv": 0.25}]});
857        let t = from_json(&v);
858        let names: Vec<&str> = t.cols.iter().map(|c| c.0.as_str()).collect();
859        assert_eq!(names, ["field", "coef_1", "coef_2", "pv"]);
860        assert_eq!(t.get("field"), Some(&Col::I64(vec![1, 2])));
861        assert_eq!(t.get("coef_2"), Some(&Col::F64(vec![0.2, 0.4])));
862        assert_eq!(t.meta["unit"], "waves");
863        let mut b = Vec::new();
864        t.write_csv(&mut b).unwrap();
865        assert_eq!(
866            String::from_utf8(b).unwrap(),
867            "field,coef_1,coef_2,pv\n1,0.1,0.2,0.5\n2,0.3,0.4,0.25\n"
868        );
869    }
870}