fitskit 0.2.0

Pure Rust FITS v4.0 reader/writer with tile-compression read and write
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
//! Tests reading NASA sample FITS files from the samp/ directory.
//! These tests are skipped if the samp/ directory is not present.

use fitskit::*;
use std::path::Path;

const SAMP_DIR: &str = "samp";

fn samp(name: &str) -> std::path::PathBuf {
    Path::new(SAMP_DIR).join(name)
}

macro_rules! require_samples {
    () => {
        if !Path::new(SAMP_DIR).is_dir() {
            eprintln!("skipping: samp/ directory not present");
            return;
        }
    };
}

#[test]
fn read_euv_image() {
    require_samples!();
    let fits = FitsFile::from_file(samp("EUVEngc4151imgx.fits")).unwrap();

    let primary = fits.primary();
    assert_eq!(primary.header.get_bool("SIMPLE"), Some(true));
    assert_eq!(primary.header.get_int("BITPIX"), Some(8));
    assert_eq!(primary.header.get_int("NAXIS"), Some(0));
    assert!(matches!(primary.data, HduData::Empty));

    assert!(
        fits.len() > 1,
        "expected extensions, got {} HDUs",
        fits.len()
    );

    let mut image_count = 0;
    let mut bintable_count = 0;
    for hdu in fits.extensions() {
        match &hdu.data {
            HduData::Image(_) => image_count += 1,
            HduData::BinTable(_) => bintable_count += 1,
            _ => {}
        }
    }
    assert!(image_count > 0, "expected IMAGE extensions");
    assert!(bintable_count > 0, "expected BINTABLE extensions");

    for hdu in fits.extensions() {
        if let HduData::Image(img) = &hdu.data {
            assert_eq!(img.bitpix(), Bitpix::I16);
            assert_eq!(img.axes.len(), 2);
            assert!(img.width().unwrap() > 0);
            assert!(img.height().unwrap() > 0);
            break;
        }
    }
}

#[test]
fn read_fgs_with_ascii_table() {
    require_samples!();
    let fits = FitsFile::from_file(samp("FGSf64y0106m_a1f.fits")).unwrap();

    let primary = fits.primary();
    assert_eq!(primary.header.get_bool("SIMPLE"), Some(true));
    assert_eq!(primary.header.get_int("BITPIX"), Some(32));
    assert_eq!(primary.header.get_int("NAXIS"), Some(2));
    assert_eq!(primary.header.get_int("NAXIS1"), Some(89688));
    assert_eq!(primary.header.get_int("NAXIS2"), Some(7));

    if let HduData::Image(img) = &primary.data {
        assert_eq!(img.bitpix(), Bitpix::I32);
        assert_eq!(img.axes, vec![89688, 7]);
        assert_eq!(img.num_pixels(), 89688 * 7);
    } else {
        panic!("expected image data in primary HDU");
    }

    assert_eq!(fits.len(), 2, "expected primary + 1 extension");
    if let HduData::AsciiTable(table) = &fits.extensions()[0].data {
        assert_eq!(table.nrows, 7);
        assert_eq!(table.columns.len(), 6);
    } else {
        panic!("expected ASCII TABLE extension");
    }
}

#[test]
fn read_foc_float_image() {
    require_samples!();
    let fits = FitsFile::from_file(samp("FOCx38i0101t_c0f.fits")).unwrap();

    let primary = fits.primary();
    assert_eq!(primary.header.get_int("BITPIX"), Some(-32));
    assert_eq!(primary.header.get_int("NAXIS"), Some(2));
    assert_eq!(primary.header.get_int("NAXIS1"), Some(1024));
    assert_eq!(primary.header.get_int("NAXIS2"), Some(1024));

    if let HduData::Image(img) = &primary.data {
        assert_eq!(img.bitpix(), Bitpix::F32);
        assert_eq!(img.num_pixels(), 1024 * 1024);

        if let PixelData::F32(data) = &img.pixels {
            assert!(!data.is_empty());
            let non_zero = data.iter().filter(|&&v| v != 0.0).count();
            assert!(non_zero > 0, "expected some non-zero pixels");
        }
    } else {
        panic!("expected float image data");
    }

    assert_eq!(fits.len(), 2);
    if let HduData::AsciiTable(table) = &fits.extensions()[0].data {
        assert_eq!(table.nrows, 1);
        assert_eq!(table.columns.len(), 18);
    } else {
        panic!("expected ASCII TABLE extension");
    }
}

#[test]
fn read_iue_header_only() {
    require_samples!();
    let fits = FitsFile::from_file(samp("IUElwp25637mxlo.fits")).unwrap();

    let primary = fits.primary();
    assert_eq!(primary.header.get_bool("SIMPLE"), Some(true));
    assert_eq!(primary.header.get_int("BITPIX"), Some(8));
    assert_eq!(primary.header.get_int("NAXIS"), Some(0));
    assert!(matches!(primary.data, HduData::Empty));

    assert!(
        primary.header.find("TELESCOP").is_some() || primary.header.find("INSTRUME").is_some(),
        "expected instrument metadata"
    );
}

#[test]
fn read_wfpc2_3d_cube() {
    require_samples!();
    let fits = FitsFile::from_file(samp("WFPC2u5780205r_c0fx.fits")).unwrap();

    let primary = fits.primary();
    assert_eq!(primary.header.get_int("BITPIX"), Some(-32));
    assert_eq!(primary.header.get_int("NAXIS"), Some(3));
    assert_eq!(primary.header.get_int("NAXIS1"), Some(200));
    assert_eq!(primary.header.get_int("NAXIS2"), Some(200));
    assert_eq!(primary.header.get_int("NAXIS3"), Some(4));

    if let HduData::Image(img) = &primary.data {
        assert_eq!(img.bitpix(), Bitpix::F32);
        assert_eq!(img.axes, vec![200, 200, 4]);
        assert_eq!(img.num_pixels(), 200 * 200 * 4);
    } else {
        panic!("expected 3D image data");
    }

    assert_eq!(fits.len(), 2);
    if let HduData::AsciiTable(table) = &fits.extensions()[0].data {
        assert_eq!(table.nrows, 4);
        assert_eq!(table.columns.len(), 49);
    } else {
        panic!("expected ASCII TABLE extension");
    }
}

#[test]
fn all_sample_files_readable() {
    require_samples!();
    let fits_files = [
        "EUVEngc4151imgx.fits",
        "FGSf64y0106m_a1f.fits",
        "FOCx38i0101t_c0f.fits",
        "IUElwp25637mxlo.fits",
        "WFPC2u5780205r_c0fx.fits",
    ];

    for name in &fits_files {
        let path = samp(name);
        let result = FitsFile::from_file(&path);
        assert!(result.is_ok(), "failed to read {name}: {:?}", result.err());

        let fits = result.unwrap();
        assert!(!fits.is_empty(), "{name}: expected at least one HDU");
        assert_eq!(
            fits.primary().header.get_bool("SIMPLE"),
            Some(true),
            "{name}: missing SIMPLE=T"
        );
    }
}

// --- Tiled-image compression: RICE_1 / GZIP_1 round-trip vs originals --------
//
// Each compressed `.fz` fixture has the SAME HDU ordering as its uncompressed
// source: every `HduData::Image` HDU in the source appears, in order, as a
// compressed-image `HduData::BinTable` (ZIMAGE=T) in the `.fz`. We decompress
// each and assert byte-exact equality of the pixel buffers.
//
// These are guarded per-fixture with `Path::exists()` so they skip cleanly on a
// machine without the (gitignored, GCS-hosted) fixtures.

/// Assert that decompressing every compressed-image HDU in `fz_name` reproduces,
/// byte-for-byte, the corresponding `HduData::Image` HDUs of `src_name`.
fn assert_rice_roundtrip(src_name: &str, fz_name: &str) {
    let fz_path = samp(fz_name);
    if !fz_path.exists() {
        eprintln!("skipping: fixture {fz_name} not present");
        return;
    }
    let src = FitsFile::from_file(samp(src_name)).expect("read source");
    let fz = FitsFile::from_file(&fz_path).expect("read .fz");

    // Source image HDUs, in order.
    let src_images: Vec<&ImageData> = src
        .hdus
        .iter()
        .filter_map(|h| match &h.data {
            HduData::Image(im) if !im.pixels.to_bytes().is_empty() => Some(im),
            _ => None,
        })
        .collect();

    // Compressed-image HDUs in the .fz, in order.
    let mut matched = 0usize;
    let mut src_iter = src_images.iter();
    for hdu in &fz.hdus {
        if let Some(cimg) = hdu.as_compressed_image() {
            let orig = src_iter
                .next()
                .expect("more compressed images than source images");
            let dec = cimg.decompress().expect("decompress");
            assert_eq!(
                dec.axes, orig.axes,
                "{fz_name}: axes mismatch on compressed HDU #{matched}"
            );
            assert_eq!(
                dec.pixels.to_bytes(),
                orig.pixels.to_bytes(),
                "{fz_name}: pixel bytes differ on compressed HDU #{matched}"
            );
            matched += 1;
        }
    }
    assert!(matched > 0, "{fz_name}: found no compressed-image HDUs");
}

#[test]
fn rice_roundtrip_euv_row_tiled() {
    // 512x512 I16, RICE row tiling (512x1 = one tile per row).
    assert_rice_roundtrip("EUVEngc4151imgx.fits", "EUVEngc4151imgx.rice.fits.fz");
}

#[test]
fn rice_roundtrip_euv_square_tiled() {
    // Same source, forced 100x100 tiles: exercises 2-D edge-truncated tiling.
    assert_rice_roundtrip("EUVEngc4151imgx.fits", "EUVEngc4151imgx.rice_t100.fits.fz");
}

#[test]
fn rice_roundtrip_fgs_i32() {
    // 89688x7 I32 image.
    assert_rice_roundtrip("FGSf64y0106m_a1f.fits", "FGSf64y0106m_a1f.rice.fits.fz");
}

#[test]
fn plio_roundtrip_euv() {
    // PLIO_1 (IRAF pixel-list RLE) over the I16 EUV image extensions. Lossless,
    // so the decode must reproduce the source pixels byte-for-byte.
    assert_rice_roundtrip("EUVEngc4151imgx.fits", "EUVEngc4151imgx.plio.fits.fz");
}

#[test]
fn hcompress_int_roundtrip_euv() {
    // HCOMPRESS_1 with SCALE=0 is LOSSLESS for integer images, so the decode of
    // the I16 EUV extensions must be byte-exact vs the source. Exercises both the
    // 512x16 and 2048x16 tile geometries.
    assert_rice_roundtrip(
        "EUVEngc4151imgx.fits",
        "EUVEngc4151imgx.hcomp_int.fits.fz",
    );
}

// --- float tile-compression: bit-exact vs funpack -------------------------
//
// Quantized-float decompression is *lossy*, so the reconstructed floats will not
// equal the original uncompressed sample. The authoritative oracle is funpack's own
// reconstruction: fitskit and funpack must apply the identical dither table + per-tile
// scaling, so fitskit's output must be BIT-IDENTICAL to funpack's. We invoke the
// `funpack` CLI at test time and compare; the test skips cleanly when either the
// fixture or the `funpack` binary is absent (so CI without cfitsio stays green).

/// True if a `funpack` binary is on PATH.
fn funpack_available() -> bool {
    std::process::Command::new("funpack")
        .arg("-V")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Decompress `fz_name` with the `funpack` CLI into a temp `.fits` and read it back.
fn funpack_reference(fz_name: &str) -> Option<FitsFile> {
    let fz_path = samp(fz_name);
    let mut out = std::env::temp_dir();
    out.push(format!(
        "fitskit_funpack_ref_{}_{}.fits",
        std::process::id(),
        fz_name.replace(['/', '.'], "_")
    ));
    let _ = std::fs::remove_file(&out);
    let status = std::process::Command::new("funpack")
        .arg("-O")
        .arg(&out)
        .arg("-C") // don't update checksums
        .arg(&fz_path)
        .status()
        .ok()?;
    if !status.success() {
        return None;
    }
    let f = FitsFile::from_file(&out).ok();
    let _ = std::fs::remove_file(&out);
    f
}

/// Assert that fitskit's float decompression of every compressed-image HDU in `fz_name`
/// is byte-exact against funpack's reconstruction of the same file.
fn assert_float_matches_funpack(fz_name: &str) {
    let fz_path = samp(fz_name);
    if !fz_path.exists() {
        eprintln!("skipping: fixture {fz_name} not present");
        return;
    }
    if !funpack_available() {
        eprintln!("skipping: funpack binary not available");
        return;
    }
    let reference = match funpack_reference(fz_name) {
        Some(r) => r,
        None => {
            eprintln!("skipping: funpack failed on {fz_name}");
            return;
        }
    };

    // funpack reference image HDUs (the reconstructed floats), in order.
    let ref_images: Vec<&ImageData> = reference
        .hdus
        .iter()
        .filter_map(|h| match &h.data {
            HduData::Image(im) if !im.pixels.to_bytes().is_empty() => Some(im),
            _ => None,
        })
        .collect();

    let fz = FitsFile::from_file(&fz_path).expect("read .fz");
    let mut ref_iter = ref_images.iter();
    let mut matched = 0usize;
    for hdu in &fz.hdus {
        if let Some(cimg) = hdu.as_compressed_image() {
            let reference_img = ref_iter
                .next()
                .expect("more compressed images than funpack reference images");
            let dec = cimg.decompress().expect("fitskit float decompress");
            assert_eq!(
                dec.axes, reference_img.axes,
                "{fz_name}: axes mismatch on compressed HDU #{matched}"
            );
            compare_floats_vs_funpack(fz_name, matched, &dec.pixels, &reference_img.pixels);
            matched += 1;
        }
    }
    assert!(matched > 0, "{fz_name}: found no compressed-image HDUs");
}

/// Compare fitskit's reconstructed floats against funpack's, element-by-element.
///
/// fitskit reproduces cfitsio's unquantization *exactly*, including the fused
/// multiply-add (`x*scale + zero` contracted to a single FMA) that the cfitsio C code
/// relies on, so every reconstructed pixel must be bit-identical to funpack's. NaNs
/// (from `ZBLANK`) only have to match as NaN — IEEE leaves the payload unspecified.
fn compare_floats_vs_funpack(fz_name: &str, hdu: usize, got: &PixelData, want: &PixelData) {
    fn cmp(fz_name: &str, hdu: usize, a: f64, b: f64) {
        if a.is_nan() && b.is_nan() {
            return;
        }
        assert!(
            a.to_bits() == b.to_bits(),
            "{fz_name} HDU#{hdu}: fitskit={a} ({:#x}) != funpack={b} ({:#x})",
            a.to_bits(),
            b.to_bits()
        );
    }
    match (got, want) {
        (PixelData::F32(g), PixelData::F32(w)) => {
            assert_eq!(g.len(), w.len(), "{fz_name} HDU#{hdu}: length mismatch");
            for (x, y) in g.iter().zip(w.iter()) {
                cmp(fz_name, hdu, *x as f64, *y as f64);
            }
        }
        (PixelData::F64(g), PixelData::F64(w)) => {
            assert_eq!(g.len(), w.len(), "{fz_name} HDU#{hdu}: length mismatch");
            for (x, y) in g.iter().zip(w.iter()) {
                cmp(fz_name, hdu, *x, *y);
            }
        }
        _ => panic!("{fz_name} HDU#{hdu}: pixel type mismatch vs funpack reference"),
    }
}

#[test]
fn float_rice_nodither_matches_funpack() {
    // 1024x1024 F32, RICE_1, ZQUANTIZ=NO_DITHER.
    assert_float_matches_funpack("FOCx38i0101t_c0f.rice_nodith.fits.fz");
}

#[cfg(feature = "gzip")]
#[test]
fn float_gzip_lossless_matches_funpack() {
    // 1024x1024 F32, GZIP_1, ZQUANTIZ=NONE (raw floats, no quantization). Needs gzip.
    assert_float_matches_funpack("FOCx38i0101t_c0f.gzip_lossless.fits.fz");
}

#[test]
fn float_rice_dither1_matches_funpack() {
    // 1024x1024 F32, RICE_1, ZQUANTIZ=SUBTRACTIVE_DITHER_1.
    assert_float_matches_funpack("FOCx38i0101t_c0f.rice_dith.fits.fz");
}

#[test]
fn float_rice_dither2_matches_funpack() {
    // 1024x1024 F32, RICE_1, ZQUANTIZ=SUBTRACTIVE_DITHER_2 (preserves exact zeros),
    // generated by scripts/gen_compressed_fixtures.sh with `fpack -r -qz5 16`.
    assert_float_matches_funpack("FOCx38i0101t_c0f.rice_dith2.fits.fz");
}

#[test]
fn float_cube_rice_dither1_matches_funpack() {
    // 200x200x4 F32 cube, RICE_1, SUBTRACTIVE_DITHER_1.
    assert_float_matches_funpack("WFPC2u5780205r_c0fx.rice_dith.fits.fz");
}

#[test]
fn float_cube_rice_nodither_matches_funpack() {
    // 200x200x4 F32 cube, RICE_1, NO_DITHER.
    assert_float_matches_funpack("WFPC2u5780205r_c0fx.rice_nodith.fits.fz");
}

#[test]
fn float_hcompress_dither1_matches_funpack() {
    // 1024x1024 F32, HCOMPRESS_1 (SCALE=0 on the quantized ints),
    // ZQUANTIZ=SUBTRACTIVE_DITHER_1. Lossy (quantized), so validate bit-exact
    // against funpack's own reconstruction. Tiles are 1024x16.
    assert_float_matches_funpack("FOCx38i0101t_c0f.hcomp.fits.fz");
}

#[cfg(feature = "gzip")]
#[test]
fn gzip1_roundtrip_euv() {
    // GZIP_1 stores raw big-endian image integers per tile; needs the `gzip` feature.
    assert_rice_roundtrip("EUVEngc4151imgx.fits", "EUVEngc4151imgx.gzip1.fits.fz");
}

// === ENCODE (write) path: fitskit produces tile-compressed FITS ================
//
// Two oracles per algorithm:
//   (1) internal: image.compress(opts) -> as_compressed_image().decompress() == image
//       (byte-exact for lossless RICE/GZIP int + lossless-float GZIP).
//   (2) interop:  write the fitskit-compressed file, run the `funpack` CLI on it, and
//       confirm funpack's reconstruction matches the original image (byte-exact for
//       lossless cases). This proves fitskit emits standard, cfitsio-readable compressed
//       FITS. Skipped cleanly when samples or `funpack` are absent.

use fitskit::tile_compress::CompressOptions;
use fitskit::{CompressionType, Quantize};

/// Collect the non-empty image HDUs (primary + extensions) of an uncompressed sample.
fn sample_images(src_name: &str) -> Vec<ImageData> {
    let src = FitsFile::from_file(samp(src_name)).expect("read source");
    src.hdus
        .iter()
        .filter_map(|h| match &h.data {
            HduData::Image(im) if !im.pixels.to_bytes().is_empty() => Some(im.clone()),
            _ => None,
        })
        .collect()
}

/// Build a fitskit `.fz`-style FitsFile: empty primary + one compressed-image extension
/// per source image, all using `opts`.
fn compress_sample(images: &[ImageData], opts: &CompressOptions) -> FitsFile {
    let mut fits = FitsFile::with_empty_primary();
    // funpack expects EXTEND in the primary.
    fits.primary_mut()
        .header
        .set("EXTEND", HeaderValue::Logical(true), None);
    for img in images {
        fits.push_extension(img.compress(opts).expect("compress"));
    }
    fits
}

/// Internal round-trip: every compressed extension decompresses byte-exactly.
fn assert_internal_roundtrip(images: &[ImageData], opts: &CompressOptions) {
    let fits = compress_sample(images, opts);
    let comp: Vec<&Hdu> = fits
        .hdus
        .iter()
        .filter(|h| h.as_compressed_image().is_some())
        .collect();
    assert_eq!(comp.len(), images.len());
    for (orig, hdu) in images.iter().zip(comp) {
        let dec = hdu.as_compressed_image().unwrap().decompress().unwrap();
        assert_eq!(dec.axes, orig.axes, "internal: axes");
        assert_eq!(
            dec.pixels.to_bytes(),
            orig.pixels.to_bytes(),
            "internal: pixel bytes"
        );
    }
    // Also confirm the file re-reads from bytes as compressed images.
    let bytes = fits.to_bytes().expect("to_bytes");
    let reread = FitsFile::from_bytes(&bytes).expect("reread");
    let n = reread
        .hdus
        .iter()
        .filter(|h| h.as_compressed_image().is_some())
        .count();
    assert_eq!(n, images.len(), "reread: compressed HDU count");
}

/// Interop: funpack reads fitskit's compressed output back to `images` (byte-exact).
fn assert_funpack_reads_fitskit(src_name: &str, opts: &CompressOptions, tag: &str) {
    if !Path::new(SAMP_DIR).is_dir() {
        eprintln!("skipping: samp/ not present");
        return;
    }
    if !funpack_available() {
        eprintln!("skipping: funpack binary not available");
        return;
    }
    let images = sample_images(src_name);
    assert!(!images.is_empty(), "{src_name}: no source images");
    let fits = compress_sample(&images, opts);

    // funpack requires the file to be named *.fz.
    let mut fz = std::env::temp_dir();
    fz.push(format!("fitskit_enc_{}_{}.fits.fz", std::process::id(), tag));
    let mut out = std::env::temp_dir();
    out.push(format!("fitskit_enc_{}_{}.fits", std::process::id(), tag));
    let _ = std::fs::remove_file(&fz);
    let _ = std::fs::remove_file(&out);
    fits.to_file(&fz).expect("write fitskit .fz");

    let status = std::process::Command::new("funpack")
        .arg("-O")
        .arg(&out)
        .arg("-C")
        .arg(&fz)
        .status()
        .expect("run funpack");
    assert!(status.success(), "{tag}: funpack failed on fitskit output");

    let recon = FitsFile::from_file(&out).expect("read funpack output");
    let recon_images: Vec<&ImageData> = recon
        .hdus
        .iter()
        .filter_map(|h| match &h.data {
            HduData::Image(im) if !im.pixels.to_bytes().is_empty() => Some(im),
            _ => None,
        })
        .collect();
    assert_eq!(
        recon_images.len(),
        images.len(),
        "{tag}: funpack image count"
    );
    for (orig, got) in images.iter().zip(recon_images) {
        assert_eq!(got.axes, orig.axes, "{tag}: funpack axes");
        assert_eq!(
            got.pixels.to_bytes(),
            orig.pixels.to_bytes(),
            "{tag}: funpack pixel bytes differ from original (lossless expected)"
        );
    }
    let _ = std::fs::remove_file(&fz);
    let _ = std::fs::remove_file(&out);
}

fn rice_opts(tile: Option<Vec<usize>>) -> CompressOptions {
    CompressOptions {
        algorithm: CompressionType::Rice1,
        tile,
        ..Default::default()
    }
}

#[test]
fn encode_rice_i16_internal() {
    require_samples!();
    assert_internal_roundtrip(&sample_images("EUVEngc4151imgx.fits"), &rice_opts(None));
    // square 2-D tiling with edge truncation
    assert_internal_roundtrip(
        &sample_images("EUVEngc4151imgx.fits"),
        &rice_opts(Some(vec![100, 100])),
    );
}

#[test]
fn encode_rice_i16_interop_funpack() {
    assert_funpack_reads_fitskit("EUVEngc4151imgx.fits", &rice_opts(None), "rice_i16");
}

#[test]
fn encode_rice_i16_square_tiles_interop_funpack() {
    assert_funpack_reads_fitskit(
        "EUVEngc4151imgx.fits",
        &rice_opts(Some(vec![100, 100])),
        "rice_i16_t100",
    );
}

#[test]
fn encode_rice_i32_internal() {
    require_samples!();
    assert_internal_roundtrip(&sample_images("FGSf64y0106m_a1f.fits"), &rice_opts(None));
}

#[test]
fn encode_rice_i32_interop_funpack() {
    assert_funpack_reads_fitskit("FGSf64y0106m_a1f.fits", &rice_opts(None), "rice_i32");
}

#[cfg(feature = "gzip")]
#[test]
fn encode_gzip_i16_internal() {
    require_samples!();
    for alg in [CompressionType::Gzip1, CompressionType::Gzip2] {
        let opts = CompressOptions {
            algorithm: alg,
            ..Default::default()
        };
        assert_internal_roundtrip(&sample_images("EUVEngc4151imgx.fits"), &opts);
    }
}

#[cfg(feature = "gzip")]
#[test]
fn encode_gzip1_i16_interop_funpack() {
    let opts = CompressOptions {
        algorithm: CompressionType::Gzip1,
        ..Default::default()
    };
    assert_funpack_reads_fitskit("EUVEngc4151imgx.fits", &opts, "gzip1_i16");
}

#[cfg(feature = "gzip")]
#[test]
fn encode_gzip2_i16_interop_funpack() {
    let opts = CompressOptions {
        algorithm: CompressionType::Gzip2,
        ..Default::default()
    };
    assert_funpack_reads_fitskit("EUVEngc4151imgx.fits", &opts, "gzip2_i16");
}

#[cfg(feature = "gzip")]
#[test]
fn encode_gzip_lossless_float_internal() {
    require_samples!();
    let opts = CompressOptions {
        algorithm: CompressionType::Gzip1,
        quantize: None, // lossless raw-float storage
        ..Default::default()
    };
    assert_internal_roundtrip(&sample_images("FOCx38i0101t_c0f.fits"), &opts);
}

#[cfg(feature = "gzip")]
#[test]
fn encode_gzip_lossless_float_interop_funpack() {
    let opts = CompressOptions {
        algorithm: CompressionType::Gzip1,
        quantize: None,
        ..Default::default()
    };
    assert_funpack_reads_fitskit("FOCx38i0101t_c0f.fits", &opts, "gzip_lossless_f32");
}

/// Lossy quantized-float RICE encode: round-trips within quantization tolerance via the
/// internal decoder. (Interop byte-exactness is not expected for lossy data; the
/// lossless cases above carry the funpack-reads-fitskit proof.)
#[test]
fn encode_rice_float_quantize_within_tolerance() {
    require_samples!();
    let images = sample_images("FOCx38i0101t_c0f.fits");
    let opts = CompressOptions {
        algorithm: CompressionType::Rice1,
        tile: None,
        quantize: Some(4.0),
        dither: Quantize::SubtractiveDither1,
        dither_seed: Some(5),
        ..Default::default()
    };
    let fits = compress_sample(&images, &opts);
    let comp: Vec<&Hdu> = fits
        .hdus
        .iter()
        .filter(|h| h.as_compressed_image().is_some())
        .collect();
    assert_eq!(comp.len(), images.len());
    for (orig, hdu) in images.iter().zip(comp) {
        let dec = hdu.as_compressed_image().unwrap().decompress().unwrap();
        assert_eq!(dec.axes, orig.axes);
        // Compare within a tolerance derived from the data's own dynamic range.
        let (o, r) = match (&orig.pixels, &dec.pixels) {
            (PixelData::F32(a), PixelData::F32(b)) => (a.clone(), b.clone()),
            _ => panic!("expected F32 float image"),
        };
        assert_eq!(o.len(), r.len());
        let finite_max = o
            .iter()
            .filter(|v| v.is_finite())
            .fold(0.0f32, |m, &v| m.max(v.abs()));
        let tol = (finite_max / 1000.0).max(1.0);
        let mut max_err = 0.0f32;
        for (&a, &b) in o.iter().zip(r.iter()) {
            if a.is_finite() && b.is_finite() {
                max_err = max_err.max((a - b).abs());
            }
        }
        assert!(
            max_err <= tol,
            "quantize round-trip max error {max_err} exceeds tolerance {tol}"
        );
    }
}