nd2-rs 0.1.6

Pure Rust library for reading Nikon ND2 microscopy files
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
# Agent Development Notes


This document contains information for AI coding agents (Claude, Cursor, etc.) working on the nd2-rs project.

## Project Context


**Project:** nd2-rs - Pure Rust ND2 file reader  
**Language:** Rust (Edition 2021, MSRV 1.70)  
**Purpose:** Read metadata and pixel data from Nikon ND2 microscopy files  
**Repository:** https://github.com/keejkrej/nd2-rs  
**Status:** ✅ Metadata + image data (sizes, read_frame, read_frame_2d). Inspired by [nd2-py](https://github.com/tlambert03/nd2).

---

## Quick Start for Agents


### Building the Project


```bash
cd nd2-rs
cargo build
cargo test         # Unit + integration (integration skips unless ND2_TEST_FILE is set)
cargo clippy -- -D warnings
```

### Running the CLI


```bash
cargo run -- info path/to/file.nd2

# Or install and run

cargo install --path .
nd2-rs info path/to/file.nd2
```

Prints version, attributes, text_info, and experiment as JSON.

### Running Examples


```bash
cargo run --example read_metadata path/to/file.nd2
```

### Project Structure Reference


```
nd2-rs/
├── src/
│   ├── lib.rs              # Public API
│   ├── main.rs             # CLI (info subcommand, outputs JSON)
│   ├── reader.rs           # Nd2File: sizes, loop_indices, read_frame, read_frame_2d
│   ├── error.rs
│   ├── constants.rs
│   ├── chunk/              # ChunkMap, headers
│   ├── parse/clx_lite.rs   # CLX Lite TLV parser
│   ├── types/              # Attributes, ExpLoop, TextInfo, Metadata
│   └── metadata/           # parse_attributes, parse_experiment, parse_text_info (loaded via meta_parse)
├── tests/
│   ├── integration.rs     # ND2_TEST_FILE for full tests
│   └── unit.rs
├── examples/read_metadata.rs
├── Cargo.toml
├── README.md
├── DATASTRUCTURE.md
└── AGENTS.md
```

### Core API


- `sizes()` → HashMap P,T,C,Z,Y,X
- `read_frame_2d(p, t, c, z)` → Vec<u16> Y×X (preferred for frame access)
- `read_frame(seq_index)` → Vec<u16> C×Y×X

---

## Development Guidelines


### Code Style


- **Idiomatic Rust**: Follow standard Rust conventions
- **Error handling**: Use `Result<T>` with `?` operator, avoid panics
- **Documentation**: Use `///` for public items, `//` for internal
- **Imports**: Group std, external crates, internal modules
- **Naming**: `snake_case` for functions/variables, `PascalCase` for types

**Example:**
```rust
use std::fs::File;
use std::io::Read;

use byteorder::{LittleEndian, ReadBytesExt};

use crate::error::{Nd2Error, Result};
use crate::constants::ND2_CHUNK_MAGIC;

/// Read a chunk header from the given reader.
pub fn read_chunk_header<R: Read>(reader: &mut R) -> Result<ChunkHeader> {
    let magic = reader.read_u32::<LittleEndian>()?;
    if magic != ND2_CHUNK_MAGIC {
        return Err(Nd2Error::InvalidMagic {
            expected: ND2_CHUNK_MAGIC,
            actual: magic,
        });
    }
    // ...
}
```

### Dependencies


**Current dependencies** (keep minimal):
- `thiserror` - Error types
- `byteorder` - Binary I/O
- `serde` - Serialization framework
- `flate2` - Zlib decompression

**Dev dependencies:**
- `serde_json` - JSON serialization for examples

**When adding dependencies:**
1. Check if it's truly needed (prefer std when possible)
2. Verify license compatibility (MIT/Apache-2.0)
3. Check maintenance status (last update, open issues)
4. Add to appropriate section in `Cargo.toml`

### Error Handling


**Use `thiserror` for error types:**
```rust
#[derive(Error, Debug)]

pub enum Nd2Error {
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    #[error("Invalid magic number: expected 0x{expected:08X}, got 0x{actual:08X}")]
    InvalidMagic { expected: u32, actual: u32 },
}
```

**Return `Result<T>` everywhere:**
```rust
pub fn parse_attributes(clx: ClxValue) -> Result<Attributes> {
    let obj = clx.as_object()
        .ok_or_else(|| Nd2Error::MetadataParse("Expected object".to_string()))?;
    // ...
}
```

**Avoid unwrap/expect:**
```rust
// ❌ Bad
let value = map.get("key").unwrap();

// ✅ Good
let value = map.get("key")
    .ok_or_else(|| Nd2Error::MetadataParse("Missing key".to_string()))?;
```

### Testing Strategy


**Unit tests** (when added):
```rust
#[cfg(test)]

mod tests {
    use super::*;

    #[test]
    fn test_chunk_header_parsing() {
        let data = vec![0xDA, 0xCE, 0xBE, 0x0A, ...];
        let header = ChunkHeader::read(&mut Cursor::new(data)).unwrap();
        assert_eq!(header.magic, ND2_CHUNK_MAGIC);
    }
}
```

**Integration tests:** See `tests/integration.rs`. Set `ND2_TEST_FILE` to run against a real ND2.

---

## Common Tasks


### Adding a New Metadata Type


**Example: Adding ROI (Region of Interest) support**

1. **Define the type** in `src/types/roi.rs`:
```rust
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ROI {
    pub id: u32,
    pub name: String,
    pub shape_type: ShapeType,
    pub points: Vec<Point>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ShapeType {
    Rectangle,
    Ellipse,
    Polygon,
}
```

2. **Add parser** in `src/metadata/roi.rs`:
```rust
use crate::error::{Nd2Error, Result};
use crate::parse::ClxValue;
use crate::types::ROI;

pub fn parse_rois(clx: ClxValue) -> Result<Vec<ROI>> {
    let obj = clx.as_object()
        .ok_or_else(|| Nd2Error::MetadataParse("Expected object".to_string()))?;

    let mut rois = Vec::new();
    // ... parsing logic
    Ok(rois)
}
```

3. **Export from modules**:
```rust
// src/types/mod.rs
pub mod roi;
pub use roi::*;

// src/metadata/mod.rs
pub mod roi;
pub use roi::*;
```

4. **Add to Nd2File** in `src/reader.rs`:
```rust
pub struct Nd2File {
    // ... existing fields
    rois: Option<Vec<ROI>>,
}

impl Nd2File {
    pub fn rois(&mut self) -> Result<&Vec<ROI>> {
        if self.rois.is_none() {
            let chunk_name: &[u8] = b"CustomData|RoiMetadata_v1!";
            let data = read_chunk(&mut self.reader, &self.chunkmap, chunk_name)?;
            let parser = ClxLiteParser::new(false);
            let clx = parser.parse(&data)?;
            self.rois = Some(parse_rois(clx)?);
        }
        Ok(self.rois.as_ref().unwrap())
    }
}
```

### Image Data


**Implemented:** `read_frame(index)` returns C×Y×X u16; `read_frame_2d(p,t,c,z)` returns Y×X. Uncompressed and zlib supported.

### Performance Optimization


**When performance becomes an issue:**

1. **Memory-mapped I/O:**
   ```rust
   // Add to Cargo.toml: memmap2 = "0.9"
   use memmap2::Mmap;

   let file = File::open(path)?;
   let mmap = unsafe { Mmap::map(&file)? };
   ```

2. **Parallel chunk loading:**
   ```rust
   // Add to Cargo.toml: rayon = "1.10"
   use rayon::prelude::*;
   ```

3. **Reduce allocations:**
   - Reuse buffers
   - Use `&str` instead of `String` where possible
   - Consider `Cow<'a, str>` for mixed owned/borrowed strings

---

## Debugging


### Enable Detailed Error Messages


```rust
// In development, use unwrap() alternatives that show context
let value = map.get("key")
    .expect("Missing key 'key' in attributes");
```

### Inspect Binary Data


```rust
// Dump chunk data to file
let data = nd2.read_raw_chunk(b"ImageAttributesLV!")?;
std::fs::write("chunk_dump.bin", data)?;

// Print hex dump
for chunk in data.chunks(16) {
    println!("{:02X?}", chunk);
}
```

### Debug CLX Parsing


```rust
use nd2_rs::parse::{ClxLiteParser, ClxValue};

let parser = ClxLiteParser::new(false);
let clx = parser.parse(&data)?;

// Pretty-print with Debug
println!("{:#?}", clx);

// Or serialize to JSON
#[cfg(feature = "json")]

{
    println!("{}", serde_json::to_string_pretty(&clx)?);
}
```

---

## Git Workflow


### Commit Messages


Follow conventional commits:
```
feat: add ROI metadata parsing
fix: correct chunk offset calculation
docs: update DATASTRUCTURE.md
test: add CLX parser unit tests
refactor: simplify experiment loop parsing
perf: use memory-mapped I/O for large files
```

### Branch Naming


```
feature/roi-support
fix/chunk-alignment-issue
docs/api-examples
```

---

## API Design Principles


### 1. Lazy Loading with Caching


```rust
// ✅ Good: Load on first access, cache result
pub fn attributes(&mut self) -> Result<&Attributes> {
    if self.attributes.is_none() {
        self.attributes = Some(load_attributes(...)?);
    }
    Ok(self.attributes.as_ref().unwrap())
}

// ❌ Bad: Load every time
pub fn attributes(&mut self) -> Result<Attributes> {
    load_attributes(...)
}
```

### 2. Borrow When Possible


```rust
// ✅ Good: Return reference to cached data
pub fn attributes(&mut self) -> Result<&Attributes>

// ❌ Bad: Clone on every call
pub fn attributes(&mut self) -> Result<Attributes>
```

### 3. Error Context


```rust
// ✅ Good: Specific error with context
.ok_or_else(|| Nd2Error::MetadataParse("Missing uiWidth field".to_string()))?

// ❌ Bad: Generic error
.ok_or_else(|| Nd2Error::MetadataParse("Parse error".to_string()))?
```

### 4. Type Safety


```rust
// ✅ Good: Use enums for fixed values
pub enum CompressionType {
    Lossless,
    Lossy,
    None,
}

// ❌ Bad: Use strings
pub compression_type: String  // Could be "lossless", "Lossless", "LOSSLESS", etc.
```

---

## Known Limitations


- ✅ Metadata (attributes, text_info, experiment), sizes, loop_indices
- ✅ Image data: read_frame, read_frame_2d (uncompressed + zlib)
- ❌ Legacy ND2 v1.0 (JPEG2000)
- ❌ ROI metadata, binary masks
- **Platform:** Windows, Linux, macOS (CI); little-endian assumed

---

## Future Roadmap


- ✅ Metadata, sizes, loop_indices
- ✅ Image data (read_frame, read_frame_2d)
- 🔲 Channel metadata, ROI, binary masks
- 🔲 Memory-mapped I/O, parallel loading
- 🔲 Python bindings (PyO3), WebAssembly

---

## Useful Commands


```bash
# Build

cargo build
cargo build --release

# Test

cargo test
cargo test -- --nocapture  # Show println! output

# Check without building

cargo check

# Format code

cargo fmt

# Lint (CI uses -D warnings)

cargo clippy -- -D warnings

# Documentation

cargo doc --open

# Benchmarks (when added)

cargo bench

# Tree view of dependencies

cargo tree
```

---

## Reference Files


When implementing new features, refer to these Python source files:

| Component | Python Reference |
|-----------|------------------|
| Chunk parsing | `nd2/src/nd2/_parse/_chunk_decode.py` |
| CLX Lite | `nd2/src/nd2/_parse/_clx_lite.py` |
| CLX XML | `nd2/src/nd2/_parse/_clx_xml.py` |
| Data structures | `nd2/src/nd2/structures.py` |
| SDK types | `nd2/src/nd2/_sdk_types.py` |
| Modern reader | `nd2/src/nd2/_readers/_modern/modern_reader.py` |
| Main API | `nd2/src/nd2/_nd2file.py` |

---

## Questions & Clarifications


### Why separate `types/` and `metadata/` modules?


- `types/`: Pure data structures (Rust types)
- `metadata/`: Conversion logic (ClxValue → Rust types)

This separation allows:
- Types to be used independently of parsing
- Multiple parsers for the same type (XML, binary)
- Clear boundary between data and logic

### Why `&mut self` for getters?


Metadata is loaded lazily and cached. The first call loads data (mutation), subsequent calls return cached reference.

### Why not use `once_cell` or `lazy_static`?


Could be added later for true lazy initialization, but current caching approach is simpler and sufficient.

### Why `BufReader` instead of `mmap`?


- Simpler implementation
- Works on all platforms
- Good enough performance for metadata
- Can add `mmap` later for image data

---

## Contact & Resources


- **Repository:** https://github.com/keejkrej/nd2-rs
- **Python nd2 (reference):** https://github.com/tlambert03/nd2
- **Rust docs:** https://doc.rust-lang.org/
- **Serde:** https://serde.rs/