bioformats 0.1.1

Pure Rust reimplementation of Bio-Formats — read/write scientific image formats
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
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
//! ICS (Image Cytometry Standard) reader and writer.
//!
//! Supports ICS version 1.0 (`.ics` + `.ids` pair) and 2.0 (single `.ics` file).
//! Handles gzip-compressed data and all standard pixel types.

use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};

use crate::common::error::{BioFormatsError, Result};
use crate::common::metadata::{DimensionOrder, ImageMetadata, MetadataValue};
use crate::common::pixel_type::PixelType;
use crate::common::reader::FormatReader;
use crate::common::writer::FormatWriter;

// ---- header parsing ---------------------------------------------------------

#[derive(Debug, Default)]
struct IcsHeader {
    version: f32,
    filename: Option<PathBuf>,
    /// Axis names (e.g. ["bits","x","y","z","t"])
    order: Vec<String>,
    /// Axis sizes in the same order as `order`
    sizes: Vec<u32>,
    significant_bits: u8,
    format: String,      // "real" or "integer"
    sign: String,        // "signed" or "unsigned"
    byte_order: Vec<u8>, // e.g. [1,2,3,4]
    gzip_compressed: bool,
    /// Byte offset of pixel data in the data file
    data_offset: u64,
    extra: HashMap<String, String>,
}

impl IcsHeader {
    fn parse(path: &Path) -> Result<IcsHeader> {
        let f = File::open(path).map_err(BioFormatsError::Io)?;
        let mut reader = BufReader::new(f);
        let mut hdr = IcsHeader::default();

        let mut data_offset = 0u64;

        loop {
            let mut line = String::new();
            let n = reader.read_line(&mut line).map_err(BioFormatsError::Io)?;
            if n == 0 {
                break;
            }

            let line = line.trim_end_matches(|c| c == '\r' || c == '\n');
            if line.eq_ignore_ascii_case("end") {
                // For ICS2, data immediately follows
                data_offset = reader.stream_position().map_err(BioFormatsError::Io)?;
                break;
            }

            let tokens: Vec<&str> = line.split_ascii_whitespace().collect();
            if tokens.is_empty() {
                continue;
            }

            match tokens[0].to_ascii_lowercase().as_str() {
                "ics_version" if tokens.len() >= 2 => {
                    hdr.version = tokens[1].parse().unwrap_or(1.0);
                }
                "filename" if tokens.len() >= 2 => {
                    hdr.filename = Some(PathBuf::from(tokens[1..].join(" ")));
                }
                "layout" if tokens.len() >= 3 => match tokens[1].to_ascii_lowercase().as_str() {
                    "order" => {
                        hdr.order = tokens[2..].iter().map(|s| s.to_ascii_lowercase()).collect();
                    }
                    "sizes" => {
                        hdr.sizes = tokens[2..].iter().filter_map(|s| s.parse().ok()).collect();
                    }
                    "significant_bits" | "significant bits" if tokens.len() >= 3 => {
                        hdr.significant_bits = tokens[2].parse().unwrap_or(8);
                    }
                    _ => {}
                },
                "representation" if tokens.len() >= 3 => {
                    match tokens[1].to_ascii_lowercase().as_str() {
                        "format" => hdr.format = tokens[2].to_ascii_lowercase(),
                        "sign" => hdr.sign = tokens[2].to_ascii_lowercase(),
                        "byte_order" | "byteorder" => {
                            hdr.byte_order =
                                tokens[2..].iter().filter_map(|s| s.parse().ok()).collect();
                        }
                        "compression" if tokens.len() >= 3 => {
                            hdr.gzip_compressed =
                                tokens[2].contains("gzip") || tokens[2].contains("gz");
                        }
                        _ => {}
                    }
                }
                _ => {
                    // Store all other metadata as key-value
                    if tokens.len() >= 3 {
                        let key = format!("{}\t{}", tokens[0], tokens[1]);
                        let val = tokens[2..].join(" ");
                        hdr.extra.insert(key, val);
                    }
                }
            }
        }

        hdr.data_offset = data_offset;
        Ok(hdr)
    }
}

/// Port of MetadataTools.makeSaneDimensionOrder: ensure all of X,Y,Z,C,T are
/// present (appending any missing in canonical order), then map to the enum.
fn make_sane_dimension_order(order: &str) -> DimensionOrder {
    let mut s: String = order.to_uppercase();
    for c in ['X', 'Y', 'Z', 'C', 'T'] {
        if !s.contains(c) {
            s.push(c);
        }
    }
    // Drop the leading XY (always present) and inspect the trailing ZCT order.
    let tail: String = s.chars().filter(|c| matches!(c, 'Z' | 'C' | 'T')).collect();
    match tail.as_str() {
        "CTZ" => DimensionOrder::XYCTZ,
        "CZT" => DimensionOrder::XYCZT,
        "TCZ" => DimensionOrder::XYTCZ,
        "TZC" => DimensionOrder::XYTZC,
        "ZCT" => DimensionOrder::XYZCT,
        "ZTC" => DimensionOrder::XYZTC,
        _ => DimensionOrder::XYCZT,
    }
}

fn pixel_type_from_ics(significant_bits: u8, format: &str, sign: &str) -> PixelType {
    match (significant_bits, format, sign) {
        (1, _, _) => PixelType::Bit,
        (8, _, "signed") => PixelType::Int8,
        (8, _, _) => PixelType::Uint8,
        (16, _, "signed") => PixelType::Int16,
        (16, _, _) => PixelType::Uint16,
        (32, "real", _) => PixelType::Float32,
        (32, _, "signed") => PixelType::Int32,
        (32, _, _) => PixelType::Uint32,
        (64, "real", _) => PixelType::Float64,
        _ => PixelType::Uint8,
    }
}

fn build_metadata(hdr: &IcsHeader) -> Result<ImageMetadata> {
    // ICS axis order: the first axis is usually "bits" (samples per pixel).
    // The remaining axes are spatial/temporal dimensions.
    let axes = &hdr.order;
    let sizes = &hdr.sizes;
    if axes.len() != sizes.len() {
        return Err(BioFormatsError::Format(
            "ICS: order and sizes length mismatch".into(),
        ));
    }

    // Port of ICSReader.java core-metadata construction.
    // sizes default to 0 (matching Java's m.sizeX==0 sentinel used by storedRGB).
    let mut size_x = 0u32;
    let mut size_y = 0u32;
    let mut size_z = 0u32;
    let mut size_c = 0u32;
    let mut size_t = 0u32;

    // dimensionOrder begins as "XY" and gains Z/T/C in axis order (first occurrence).
    let mut dim_order = String::from("XY");
    let mut bits_per_pixel = 0u32;
    // storedRGB: channel axis appears before the X axis.
    let mut stored_rgb = false;
    let mut is_rgb = false;

    for (axis, &sz) in axes.iter().zip(sizes.iter()) {
        match axis.as_str() {
            "bits" => {
                bits_per_pixel = sz;
                while bits_per_pixel % 8 != 0 {
                    bits_per_pixel += 1;
                }
                if bits_per_pixel == 24 || bits_per_pixel == 48 {
                    bits_per_pixel /= 3;
                }
            }
            "x" | "width" => size_x = sz,
            "y" | "height" => size_y = sz,
            "z" | "depth" => {
                size_z = sz;
                if !dim_order.contains('Z') {
                    dim_order.push('Z');
                }
            }
            "t" | "time" => {
                if size_t == 0 {
                    size_t = sz;
                } else {
                    size_t *= sz;
                }
                if !dim_order.contains('T') {
                    dim_order.push('T');
                }
            }
            // Any other axis (c, ch, channel, p, f, ...) is treated as a channel axis.
            _ => {
                if size_c == 0 {
                    size_c = sz;
                } else {
                    size_c *= sz;
                }
                // storedRGB / rgb depend on whether channel axis preceded X.
                stored_rgb = size_x == 0;
                is_rgb = size_x == 0 && size_c <= 4 && size_c > 1;
                if !dim_order.contains('C') {
                    dim_order.push('C');
                }
            }
        }
    }

    let dimension_order = make_sane_dimension_order(&dim_order);

    if size_z == 0 {
        size_z = 1;
    }
    if size_c == 0 {
        size_c = 1;
    }
    if size_t == 0 {
        size_t = 1;
    }

    // Significant bits: prefer rounded bits-per-pixel from the "bits" axis.
    let sig = if bits_per_pixel != 0 {
        bits_per_pixel as u8
    } else if hdr.significant_bits != 0 {
        hdr.significant_bits
    } else {
        8
    };

    let pixel_type = pixel_type_from_ics(sig, &hdr.format, &hdr.sign);

    // imageCount = sizeZ * sizeT, times sizeC only when not RGB.
    let mut image_count = size_z * size_t;
    if !is_rgb {
        image_count *= size_c;
    }
    let _ = stored_rgb;

    let mut series_metadata: HashMap<String, MetadataValue> = hdr
        .extra
        .iter()
        .map(|(k, v)| (k.clone(), MetadataValue::String(v.clone())))
        .collect();
    series_metadata.insert(
        "ics_version".into(),
        MetadataValue::Float(hdr.version as f64),
    );

    // Endianness (ICSReader.java):
    //   littleEndian = real ? first==1 : first!=1
    // i.e. for INTEGER ics, first==1 means BIG-endian.
    let real = hdr.format == "real";
    let mut little_endian = true;
    if let Some(&first) = hdr.byte_order.first() {
        little_endian = if real { first == 1 } else { first != 1 };
    }
    // Sub-32-bit pixels: endianness is unconditionally flipped.
    if (sig as u32) < 32 {
        little_endian = !little_endian;
    }

    Ok(ImageMetadata {
        size_x,
        size_y,
        size_z,
        size_c,
        size_t,
        pixel_type,
        bits_per_pixel: sig,
        image_count,
        dimension_order,
        is_rgb,
        is_interleaved: is_rgb,
        is_indexed: false,
        is_little_endian: little_endian,
        resolution_count: 1,
        series_metadata,
        lookup_table: None,
        modulo_z: None,
        modulo_c: None,
        modulo_t: None,
    })
}

// ---- reader -----------------------------------------------------------------

pub struct IcsReader {
    path: Option<PathBuf>,
    meta: Option<ImageMetadata>,
    header: Option<IcsHeader>,
}

impl IcsReader {
    pub fn new() -> Self {
        IcsReader {
            path: None,
            meta: None,
            header: None,
        }
    }

    fn data_path(ics_path: &Path, hdr: &IcsHeader) -> PathBuf {
        if hdr.version < 2.0 {
            // ICS1: companion data file, named explicitly when available.
            if let Some(filename) = &hdr.filename {
                if filename.is_absolute() {
                    filename.clone()
                } else {
                    ics_path
                        .parent()
                        .unwrap_or_else(|| Path::new(""))
                        .join(filename)
                }
            } else {
                let stem = ics_path.file_stem().unwrap_or_default();
                ics_path.with_file_name(format!("{}.ids", stem.to_string_lossy()))
            }
        } else {
            ics_path.to_path_buf()
        }
    }

    fn normalize_endianness(&self, mut buf: Vec<u8>) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let bps = meta.pixel_type.bytes_per_sample();
        if !meta.is_little_endian && bps > 1 {
            for chunk in buf.chunks_exact_mut(bps) {
                chunk.reverse();
            }
        }
        Ok(buf)
    }

    fn load_raw_data(&self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let hdr = self
            .header
            .as_ref()
            .ok_or(BioFormatsError::NotInitialized)?;
        let ics_path = self.path.as_ref().ok_or(BioFormatsError::NotInitialized)?;

        let bytes_per_sample = meta.pixel_type.bytes_per_sample();
        let plane_bytes = (meta.size_x * meta.size_y * meta.size_c) as usize * bytes_per_sample;
        let plane_offset = plane_index as u64 * plane_bytes as u64;

        let data_path = Self::data_path(ics_path, hdr);
        let data_offset = hdr.data_offset + plane_offset;

        let mut f = File::open(&data_path).map_err(BioFormatsError::Io)?;

        if hdr.gzip_compressed {
            // Decompress all then seek; gzip doesn't support random access
            f.seek(SeekFrom::Start(hdr.data_offset))
                .map_err(BioFormatsError::Io)?;
            let mut dec = flate2::read::GzDecoder::new(f);
            let mut all = Vec::new();
            dec.read_to_end(&mut all).map_err(BioFormatsError::Io)?;
            let start = plane_offset as usize;
            let end = start + plane_bytes;
            if end > all.len() {
                return Err(BioFormatsError::InvalidData(
                    "plane out of range in ICS data".into(),
                ));
            }
            self.normalize_endianness(all[start..end].to_vec())
        } else {
            f.seek(SeekFrom::Start(data_offset))
                .map_err(BioFormatsError::Io)?;
            let mut buf = vec![0u8; plane_bytes];
            f.read_exact(&mut buf).map_err(BioFormatsError::Io)?;
            self.normalize_endianness(buf)
        }
    }
}

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

impl FormatReader for IcsReader {
    fn is_this_type_by_name(&self, path: &Path) -> bool {
        path.extension()
            .and_then(|e| e.to_str())
            .map(|e| e.eq_ignore_ascii_case("ics"))
            .unwrap_or(false)
    }

    fn is_this_type_by_bytes(&self, header: &[u8]) -> bool {
        // ICS header starts with "ics_version" or whitespace-then-ics_version
        let s = std::str::from_utf8(&header[..header.len().min(64)]).unwrap_or("");
        s.trim_start().starts_with("ics_version")
    }

    fn set_id(&mut self, path: &Path) -> Result<()> {
        let hdr = IcsHeader::parse(path)?;
        let meta = build_metadata(&hdr)?;
        self.path = Some(path.to_path_buf());
        self.header = Some(hdr);
        self.meta = Some(meta);
        Ok(())
    }

    fn close(&mut self) -> Result<()> {
        self.path = None;
        self.meta = None;
        self.header = None;
        Ok(())
    }

    fn series_count(&self) -> usize {
        1
    }
    fn set_series(&mut self, s: usize) -> Result<()> {
        if s != 0 {
            Err(BioFormatsError::SeriesOutOfRange(s))
        } else {
            Ok(())
        }
    }
    fn series(&self) -> usize {
        0
    }

    fn metadata(&self) -> &ImageMetadata {
        self.meta.as_ref().expect("set_id not called")
    }

    fn open_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let count = self.meta.as_ref().map(|m| m.image_count).unwrap_or(0);
        if plane_index >= count {
            return Err(BioFormatsError::PlaneOutOfRange(plane_index));
        }
        self.load_raw_data(plane_index)
    }

    fn open_bytes_region(
        &mut self,
        plane_index: u32,
        x: u32,
        y: u32,
        w: u32,
        h: u32,
    ) -> Result<Vec<u8>> {
        let full = self.open_bytes(plane_index)?;
        let meta = self.meta.as_ref().unwrap();
        let spp = meta.size_c as usize;
        let bps = meta.pixel_type.bytes_per_sample();
        let row_bytes = meta.size_x as usize * spp * bps;
        let out_row = w as usize * spp * bps;
        let mut out = Vec::with_capacity(h as usize * out_row);
        for row in 0..h as usize {
            let src = &full[(y as usize + row) * row_bytes..];
            let s = x as usize * spp * bps;
            out.extend_from_slice(&src[s..s + out_row]);
        }
        Ok(out)
    }

    fn open_thumb_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let (tw, th) = (meta.size_x.min(256), meta.size_y.min(256));
        let (tx, ty) = ((meta.size_x - tw) / 2, (meta.size_y - th) / 2);
        self.open_bytes_region(plane_index, tx, ty, tw, th)
    }
}

// ---- writer -----------------------------------------------------------------

pub struct IcsWriter {
    path: Option<PathBuf>,
    meta: Option<ImageMetadata>,
    planes: Vec<Vec<u8>>,
}

impl IcsWriter {
    pub fn new() -> Self {
        IcsWriter {
            path: None,
            meta: None,
            planes: Vec::new(),
        }
    }
}

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

impl FormatWriter for IcsWriter {
    fn is_this_type(&self, path: &Path) -> bool {
        path.extension()
            .and_then(|e| e.to_str())
            .map(|e| e.eq_ignore_ascii_case("ics"))
            .unwrap_or(false)
    }

    fn set_metadata(&mut self, meta: &ImageMetadata) -> Result<()> {
        self.meta = Some(meta.clone());
        Ok(())
    }

    fn set_id(&mut self, path: &Path) -> Result<()> {
        self.meta
            .as_ref()
            .ok_or_else(|| BioFormatsError::Format("set_metadata first".into()))?;
        self.path = Some(path.to_path_buf());
        self.planes.clear();
        Ok(())
    }

    fn save_bytes(&mut self, _idx: u32, data: &[u8]) -> Result<()> {
        self.planes.push(data.to_vec());
        Ok(())
    }

    fn close(&mut self) -> Result<()> {
        let meta = self.meta.take().ok_or(BioFormatsError::NotInitialized)?;
        let path = self.path.take().ok_or(BioFormatsError::NotInitialized)?;

        // Write ICS2 format: header + "end\r\n" + raw binary (all in one .ics file)
        let mut f = File::create(&path).map_err(BioFormatsError::Io)?;

        let bps = meta.pixel_type.bytes_per_sample() * 8;
        let (format_str, sign_str) = match meta.pixel_type {
            PixelType::Float32 | PixelType::Float64 => ("real", "signed"),
            PixelType::Int8 | PixelType::Int16 | PixelType::Int32 => ("integer", "signed"),
            _ => ("integer", "unsigned"),
        };

        writeln!(f, "ics_version\t2.0").map_err(BioFormatsError::Io)?;
        writeln!(
            f,
            "filename\t{}",
            path.file_stem().unwrap_or_default().to_string_lossy()
        )
        .map_err(BioFormatsError::Io)?;
        writeln!(
            f,
            "layout\tparameters\t{}",
            4 + if meta.size_z > 1 { 1 } else { 0 } + if meta.size_t > 1 { 1 } else { 0 }
        )
        .map_err(BioFormatsError::Io)?;

        let mut order_parts = vec!["bits", "x", "y"];
        let mut size_parts = vec![
            bps.to_string(),
            meta.size_x.to_string(),
            meta.size_y.to_string(),
        ];
        if meta.size_z > 1 {
            order_parts.push("z");
            size_parts.push(meta.size_z.to_string());
        }
        if meta.size_t > 1 {
            order_parts.push("t");
            size_parts.push(meta.size_t.to_string());
        }
        if meta.size_c > 1 {
            order_parts.push("ch");
            size_parts.push(meta.size_c.to_string());
        }

        writeln!(f, "layout\torder\t{}", order_parts.join(" ")).map_err(BioFormatsError::Io)?;
        writeln!(f, "layout\tsizes\t{}", size_parts.join(" ")).map_err(BioFormatsError::Io)?;
        writeln!(f, "layout\tsignificant_bits\t{}", bps).map_err(BioFormatsError::Io)?;
        writeln!(f, "representation\tformat\t{}", format_str).map_err(BioFormatsError::Io)?;
        writeln!(f, "representation\tsign\t{}", sign_str).map_err(BioFormatsError::Io)?;
        writeln!(f, "representation\tbyte_order\t1 2 3 4").map_err(BioFormatsError::Io)?;
        writeln!(f, "representation\tcompression\tuncompressed").map_err(BioFormatsError::Io)?;
        writeln!(f, "end\r").map_err(BioFormatsError::Io)?;

        for plane in &self.planes {
            f.write_all(plane).map_err(BioFormatsError::Io)?;
        }
        self.planes.clear();
        Ok(())
    }

    fn can_do_stacks(&self) -> bool {
        true
    }
}