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
//! Module for handling and retrieving complete NIFTI-1 objects.

use crate::error::NiftiError;
use crate::error::Result;
use crate::extension::{Extender, ExtensionSequence};
use crate::header::NiftiHeader;
use crate::header::MAGIC_CODE_NI1;
use crate::util::{into_img_file_gz, is_gz_file, open_file_maybe_gz};
use crate::volume::inmem::InMemNiftiVolume;
use crate::volume::streamed::StreamedNiftiVolume;
use crate::volume::{FromSource, FromSourceOptions, NiftiVolume};
use byteordered::ByteOrdered;
use flate2::bufread::GzDecoder;
use std::fs::File;
use std::io::{self, BufReader, Read};
use std::path::Path;

pub use crate::util::{GzDecodedFile, MaybeGzDecodedFile};

/// Options and flags which can be used to configure how a NIfTI image is read.
#[derive(Debug, Clone, PartialEq)]
pub struct ReaderOptions {
    /// Whether to automatically fix value in the header
    fix_header: bool,
}

impl ReaderOptions {
    /// Creates a blank new set of options ready for configuration.
    ///
    /// All options are initially set to `false`.
    pub fn new() -> ReaderOptions {
        ReaderOptions { fix_header: false }
    }

    /// Sets the options to fix some known header problems.
    pub fn fix_header(&mut self, fix_header: bool) -> &mut Self {
        self.fix_header = fix_header;
        self
    }

    /// Retrieve the full contents of a NIFTI object.
    ///
    /// The given file system path is used as reference. If the file only contains the header, this
    /// method will look for the corresponding file with the extension ".img", or ".img.gz" if the
    /// former wasn't found.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nifti::{NiftiObject, ReaderOptions};
    ///
    /// let obj = ReaderOptions::new().read_file("minimal.nii.gz")?;
    /// # Ok::<(), nifti::NiftiError>(())
    /// ```
    pub fn read_file<P>(&self, path: P) -> Result<InMemNiftiObject>
    where
        P: AsRef<Path>,
    {
        let file = BufReader::new(File::open(&path)?);
        let mut obj = if is_gz_file(&path) {
            InMemNiftiObject::from_file_impl(path, GzDecoder::new(file), Default::default())
        } else {
            InMemNiftiObject::from_file_impl(path, file, Default::default())
        }?;
        if self.fix_header {
            obj.header.fix();
        }
        Ok(obj)
    }

    /// Retrieve a NIFTI object as separate header and volume files.
    ///
    /// This method is useful when file names are not conventional for a NIFTI file pair.
    pub fn read_file_pair<P, Q>(&self, hdr_path: P, vol_path: Q) -> Result<InMemNiftiObject>
    where
        P: AsRef<Path>,
        Q: AsRef<Path>,
    {
        let file = BufReader::new(File::open(&hdr_path)?);
        let mut obj = if is_gz_file(&hdr_path) {
            InMemNiftiObject::from_file_pair_impl(
                GzDecoder::new(file),
                vol_path,
                Default::default(),
            )
        } else {
            InMemNiftiObject::from_file_pair_impl(file, vol_path, Default::default())
        }?;
        if self.fix_header {
            obj.header.fix();
        }
        Ok(obj)
    }
}

/// Options and flags which can be used to configure how a NIfTI image is read and iterated.
#[derive(Debug, Clone, PartialEq)]
pub struct ReaderStreamedOptions {
    /// Whether to automatically fix value in the header
    fix_header: bool,
}

impl ReaderStreamedOptions {
    /// Creates a blank new set of options ready for configuration.
    ///
    /// All options are initially set to `false`.
    pub fn new() -> ReaderStreamedOptions {
        ReaderStreamedOptions { fix_header: false }
    }

    /// Sets the options to fix some known header problems.
    pub fn fix_header(&mut self, fix_header: bool) -> &mut Self {
        self.fix_header = fix_header;
        self
    }

    /// Retrieve the NIfTI object and prepare the volume for streamed reading.
    ///
    /// The given file system path is used as reference. If the file only contains the header, this
    /// method will look for the corresponding file with the extension ".img", or ".img.gz" if the
    /// former wasn't found.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nifti::{NiftiObject, ReaderStreamedOptions};
    ///
    /// let obj = ReaderStreamedOptions::new().read_file("minimal.nii.gz")?;
    ///
    /// let volume = obj.into_volume();
    /// for slice in volume {
    ///     let slice = slice?;
    ///     // manipulate slice here
    /// }
    /// # Ok::<(), nifti::NiftiError>(())
    /// ```
    pub fn read_file<P>(&self, path: P) -> Result<StreamedNiftiObject<MaybeGzDecodedFile>>
    where
        P: AsRef<Path>,
    {
        let reader = open_file_maybe_gz(&path)?;
        let mut obj = StreamedNiftiObject::from_file_impl(path, reader, None)?;
        if self.fix_header {
            obj.header.fix();
        }
        Ok(obj)
    }

    /// Retrieve the NIfTI object and prepare the volume for streamed reading,
    /// using `slice_rank` as the dimensionality of each slice.
    ///
    /// The given file system path is used as reference. If the file only contains the header, this
    /// method will look for the corresponding file with the extension ".img", or ".img.gz" if the
    /// former wasn't found.
    pub fn read_file_rank<P>(
        &self,
        path: P,
        slice_rank: u16,
    ) -> Result<StreamedNiftiObject<MaybeGzDecodedFile>>
    where
        P: AsRef<Path>,
    {
        let reader = open_file_maybe_gz(&path)?;
        let mut obj = StreamedNiftiObject::from_file_impl(path, reader, Some(slice_rank))?;
        if self.fix_header {
            obj.header.fix();
        }
        Ok(obj)
    }

    /// Retrieve a NIfTI object as separate header and volume files, for streamed volume reading.
    ///
    /// This method is useful when file names are not conventional for a NIfTI file pair.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nifti::{NiftiObject, ReaderStreamedOptions};
    ///
    /// let obj = ReaderStreamedOptions::new().read_file_pair("abc.hdr", "abc.img.gz")?;
    ///
    /// let volume = obj.into_volume();
    /// for slice in volume {
    ///     let slice = slice?;
    ///     // manipulate slice here
    /// }
    /// # Ok::<(), nifti::NiftiError>(())
    /// ```
    pub fn read_file_pair<P, Q>(
        &self,
        hdr_path: P,
        vol_path: Q,
    ) -> Result<StreamedNiftiObject<MaybeGzDecodedFile>>
    where
        P: AsRef<Path>,
        Q: AsRef<Path>,
    {
        let reader = open_file_maybe_gz(hdr_path)?;
        let mut obj =
            StreamedNiftiObject::from_file_pair_impl(reader, vol_path, Default::default())?;
        if self.fix_header {
            obj.header.fix();
        }
        Ok(obj)
    }

    /// Retrieve a NIfTI object as separate header and volume files, for streamed volume reading,
    /// using `slice_rank` as the dimensionality of each slice.
    ///
    /// This method is useful when file names are not conventional for a NIfTI file pair.
    pub fn read_file_pair_rank<P, Q>(
        &self,
        hdr_path: P,
        vol_path: Q,
        slice_rank: u16,
    ) -> Result<StreamedNiftiObject<MaybeGzDecodedFile>>
    where
        P: AsRef<Path>,
        Q: AsRef<Path>,
    {
        let reader = open_file_maybe_gz(hdr_path)?;
        let mut obj = StreamedNiftiObject::from_file_pair_impl(reader, vol_path, Some(slice_rank))?;
        if self.fix_header {
            obj.header.fix();
        }
        Ok(obj)
    }
}

/// Trait type for all possible implementations of
/// owning NIFTI-1 objects. Objects contain a NIFTI header,
/// a volume, and a possibly empty extension sequence.
pub trait NiftiObject {
    /// The concrete type of the volume.
    type Volume: NiftiVolume;

    /// Obtain a reference to the NIFTI header.
    fn header(&self) -> &NiftiHeader;

    /// Obtain a mutable reference to the NIFTI header.
    fn header_mut(&mut self) -> &mut NiftiHeader;

    /// Obtain a reference to the object's extensions.
    fn extensions(&self) -> &ExtensionSequence;

    /// Obtain a reference to the object's volume.
    fn volume(&self) -> &Self::Volume;

    /// Move the volume out of the object, discarding the
    /// header and extensions.
    fn into_volume(self) -> Self::Volume;
}

/// Generic data type for a NIfTI object.
#[derive(Debug, PartialEq, Clone)]
pub struct GenericNiftiObject<V> {
    header: NiftiHeader,
    extensions: ExtensionSequence,
    volume: V,
}

impl<V> NiftiObject for GenericNiftiObject<V>
where
    V: NiftiVolume,
{
    type Volume = V;

    fn header(&self) -> &NiftiHeader {
        &self.header
    }

    fn header_mut(&mut self) -> &mut NiftiHeader {
        &mut self.header
    }

    fn extensions(&self) -> &ExtensionSequence {
        &self.extensions
    }

    fn volume(&self) -> &Self::Volume {
        &self.volume
    }

    fn into_volume(self) -> Self::Volume {
        self.volume
    }
}

/// A NIfTI object containing an in-memory volume.
pub type InMemNiftiObject = GenericNiftiObject<InMemNiftiVolume>;

impl InMemNiftiObject {
    /// Retrieve the full contents of a NIFTI object.
    /// The given file system path is used as reference.
    /// If the file only contains the header, this method will
    /// look for the corresponding file with the extension ".img",
    /// or ".img.gz" if the former wasn't found.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nifti::{NiftiObject, InMemNiftiObject};
    ///
    /// let obj = InMemNiftiObject::from_file("minimal.nii.gz")?;
    /// # Ok::<(), nifti::NiftiError>(())
    /// ```
    #[deprecated(
        since = "0.10.0",
        note = "use `read_file` from `ReaderOptions` instead"
    )]
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let gz = is_gz_file(&path);

        let file = BufReader::new(File::open(&path)?);
        if gz {
            Self::from_file_impl(path, GzDecoder::new(file), Default::default())
        } else {
            Self::from_file_impl(path, file, Default::default())
        }
    }

    /// Retrieve a NIFTI object as separate header and volume files.
    /// This method is useful when file names are not conventional for a
    /// NIFTI file pair.
    #[deprecated(
        since = "0.10.0",
        note = "use `read_file_pair` from `ReaderOptions` instead"
    )]
    pub fn from_file_pair<P, Q>(hdr_path: P, vol_path: Q) -> Result<Self>
    where
        P: AsRef<Path>,
        Q: AsRef<Path>,
    {
        let gz = is_gz_file(&hdr_path);

        let file = BufReader::new(File::open(&hdr_path)?);
        if gz {
            Self::from_file_pair_impl(GzDecoder::new(file), vol_path, Default::default())
        } else {
            Self::from_file_pair_impl(file, vol_path, Default::default())
        }
    }
}

/// A NIfTI object containing a [streamed volume].
///
/// [streamed volume]: ../volume/streamed/index.html
pub type StreamedNiftiObject<R> = GenericNiftiObject<StreamedNiftiVolume<R>>;

impl StreamedNiftiObject<MaybeGzDecodedFile> {
    /// Retrieve the NIfTI object and prepare the volume for streamed reading.
    /// The given file system path is used as reference.
    /// If the file only contains the header, this method will
    /// look for the corresponding file with the extension ".img",
    /// or ".img.gz" if the former wasn't found.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nifti::{NiftiObject, StreamedNiftiObject};
    ///
    /// let obj = StreamedNiftiObject::from_file("minimal.nii.gz")?;
    ///
    /// let volume = obj.into_volume();
    /// for slice in volume {
    ///     let slice = slice?;
    ///     // manipulate slice here
    /// }
    /// # Ok::<(), nifti::NiftiError>(())
    /// ```
    #[deprecated(
        since = "0.10.0",
        note = "use `read_file` from `ReaderStreamedOptions` instead"
    )]
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let reader = open_file_maybe_gz(&path)?;
        Self::from_file_impl(path, reader, None)
    }

    /// Retrieve the NIfTI object and prepare the volume for streamed reading,
    /// using `slice_rank` as the dimensionality of each slice.
    /// The given file system path is used as reference.
    /// If the file only contains the header, this method will
    /// look for the corresponding file with the extension ".img",
    /// or ".img.gz" if the former wasn't found.
    #[deprecated(
        since = "0.10.0",
        note = "use `read_file_rank` from `ReaderStreamedOptions` instead"
    )]
    pub fn from_file_rank<P: AsRef<Path>>(path: P, slice_rank: u16) -> Result<Self> {
        let reader = open_file_maybe_gz(&path)?;
        Self::from_file_impl(path, reader, Some(slice_rank))
    }

    /// Retrieve a NIfTI object as separate header and volume files, for
    /// streamed volume reading. This method is useful when file names are not
    /// conventional for a NIfTI file pair.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nifti::{NiftiObject, StreamedNiftiObject};
    ///
    /// let obj = StreamedNiftiObject::from_file_pair("abc.hdr", "abc.img.gz")?;
    ///
    /// let volume = obj.into_volume();
    /// for slice in volume {
    ///     let slice = slice?;
    ///     // manipulate slice here
    /// }
    /// # Ok::<(), nifti::NiftiError>(())
    /// ```
    #[deprecated(
        since = "0.10.0",
        note = "use `read_file_pair` from `ReaderStreamedOptions` instead"
    )]
    pub fn from_file_pair<P, Q>(hdr_path: P, vol_path: Q) -> Result<Self>
    where
        P: AsRef<Path>,
        Q: AsRef<Path>,
    {
        let reader = open_file_maybe_gz(hdr_path)?;
        Self::from_file_pair_impl(reader, vol_path, Default::default())
    }

    /// Retrieve a NIfTI object as separate header and volume files, for
    /// streamed volume reading, using `slice_rank` as the dimensionality of
    /// each slice. This method is useful when file names are not conventional
    /// for a NIfTI file pair.
    #[deprecated(
        since = "0.10.0",
        note = "use `read_file_pair_rank` from `ReaderStreamedOptions` instead"
    )]
    pub fn from_file_pair_rank<P, Q>(hdr_path: P, vol_path: Q, slice_rank: u16) -> Result<Self>
    where
        P: AsRef<Path>,
        Q: AsRef<Path>,
    {
        let reader = open_file_maybe_gz(hdr_path)?;
        Self::from_file_pair_impl(reader, vol_path, Some(slice_rank))
    }
}

impl<V> GenericNiftiObject<V> {
    /// Construct a NIfTI object from a data reader, first by fetching the
    /// header, the extensions, and then the volume.
    ///
    /// # Errors
    ///
    /// - `NiftiError::NoVolumeData` if the source only contains (or claims to contain)
    /// a header.
    pub fn from_reader<R>(mut source: R) -> Result<Self>
    where
        R: Read,
        V: FromSource<R>,
    {
        let header = NiftiHeader::from_reader(&mut source)?;
        if &header.magic == MAGIC_CODE_NI1 {
            return Err(NiftiError::NoVolumeData);
        }
        let extender = Extender::from_reader(&mut source)?;

        let (volume, extensions) = GenericNiftiObject::from_reader_with_extensions(
            source,
            &header,
            extender,
            Default::default(),
        )?;

        Ok(GenericNiftiObject {
            header,
            extensions,
            volume,
        })
    }

    /// Read a NIFTI volume, and extensions, from a data reader. The header,
    /// extender code and expected byte order of the volume's data must be
    /// known in advance.
    fn from_reader_with_extensions<R>(
        mut source: R,
        header: &NiftiHeader,
        extender: Extender,
        options: <V as FromSourceOptions>::Options,
    ) -> Result<(V, ExtensionSequence)>
    where
        R: Read,
        V: FromSource<R>,
    {
        // fetch extensions
        let len = header.vox_offset as usize;
        let len = if len < 352 { 0 } else { len - 352 };

        let ext = {
            let source = ByteOrdered::runtime(&mut source, header.endianness);
            ExtensionSequence::from_reader(extender, source, len)?
        };

        // fetch volume (rest of file)
        Ok((V::from_reader(source, &header, options)?, ext))
    }

    fn from_file_impl<P, R>(
        path: P,
        mut stream: R,
        options: <V as FromSourceOptions>::Options,
    ) -> Result<Self>
    where
        P: AsRef<Path>,
        R: Read,
        V: FromSource<R>,
        V: FromSource<MaybeGzDecodedFile>,
    {
        let header = NiftiHeader::from_reader(&mut stream)?;
        let (volume, ext) = if &header.magic == MAGIC_CODE_NI1 {
            // extensions and volume are in another file

            // extender is optional
            let extender = Extender::from_reader_optional(&mut stream)?.unwrap_or_default();

            // look for corresponding img file
            let img_path = path.as_ref().to_path_buf();
            let mut img_path_gz = into_img_file_gz(img_path);

            Self::from_file_with_extensions(&img_path_gz, &header, extender, options.clone())
                .or_else(|e| {
                    match e {
                        NiftiError::Io(ref io_e) if io_e.kind() == io::ErrorKind::NotFound => {
                            // try .img file instead (remove .gz extension)
                            let has_ext = img_path_gz.set_extension("");
                            debug_assert!(has_ext);
                            Self::from_file_with_extensions(img_path_gz, &header, extender, options)
                        }
                        e => Err(e),
                    }
                })
                .map_err(|e| {
                    if let NiftiError::Io(io_e) = e {
                        NiftiError::MissingVolumeFile(io_e)
                    } else {
                        e
                    }
                })?
        } else {
            // extensions and volume are in the same source

            let extender = Extender::from_reader(&mut stream)?;
            let len = header.vox_offset as usize;
            let len = if len < 352 { 0 } else { len - 352 };

            let ext = {
                let stream = ByteOrdered::runtime(&mut stream, header.endianness);
                ExtensionSequence::from_reader(extender, stream, len)?
            };

            let volume = FromSource::from_reader(stream, &header, options)?;

            (volume, ext)
        };

        Ok(GenericNiftiObject {
            header,
            extensions: ext,
            volume,
        })
    }

    fn from_file_pair_impl<S, Q>(
        mut hdr_stream: S,
        vol_path: Q,
        options: <V as FromSourceOptions>::Options,
    ) -> Result<Self>
    where
        S: Read,
        Q: AsRef<Path>,
        V: FromSource<MaybeGzDecodedFile>,
    {
        let header = NiftiHeader::from_reader(&mut hdr_stream)?;
        let extender = Extender::from_reader_optional(hdr_stream)?.unwrap_or_default();
        let (volume, extensions) =
            Self::from_file_with_extensions(vol_path, &header, extender, options)?;

        Ok(GenericNiftiObject {
            header,
            extensions,
            volume,
        })
    }

    /// Read a NIFTI volume, along with the extensions, from an image file. NIFTI-1 volume
    /// files usually have the extension ".img" or ".img.gz". In the latter case, the file
    /// is automatically decoded as a Gzip stream.
    fn from_file_with_extensions<P>(
        path: P,
        header: &NiftiHeader,
        extender: Extender,
        options: <V as FromSourceOptions>::Options,
    ) -> Result<(V, ExtensionSequence)>
    where
        P: AsRef<Path>,
        V: FromSource<MaybeGzDecodedFile>,
    {
        let reader = open_file_maybe_gz(path)?;
        Self::from_reader_with_extensions(reader, &header, extender, options)
    }
}