-
Notifications
You must be signed in to change notification settings - Fork 260
/
Copy pathnifti1.py
2092 lines (1859 loc) · 75.3 KB
/
nifti1.py
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
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the NiBabel package for the
# copyright and license terms.
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
''' Read / write access to NIfTI1 image format
NIfTI1 format defined at http://nifti.nimh.nih.gov/nifti-1/
'''
from __future__ import division, print_function
import warnings
from io import BytesIO
from six import string_types
import numpy as np
import numpy.linalg as npl
from .py3k import asstr
from .volumeutils import Recoder, make_dt_codes, endian_codes
from .spatialimages import HeaderDataError, ImageFileError
from .batteryrunners import Report
from .quaternions import fillpositive, quat2mat, mat2quat
from . import analyze # module import
from .spm99analyze import SpmAnalyzeHeader
from .casting import have_binary128
from .pydicom_compat import have_dicom, pydicom as pdcm
from .testing import setup_test # flake8: noqa F401
# nifti1 flat header definition for Analyze-like first 348 bytes
# first number in comments indicates offset in file header in bytes
header_dtd = [
('sizeof_hdr', 'i4'), # 0; must be 348
('data_type', 'S10'), # 4; unused
('db_name', 'S18'), # 14; unused
('extents', 'i4'), # 32; unused
('session_error', 'i2'), # 36; unused
('regular', 'S1'), # 38; unused
('dim_info', 'u1'), # 39; MRI slice ordering code
('dim', 'i2', (8,)), # 40; data array dimensions
('intent_p1', 'f4'), # 56; first intent parameter
('intent_p2', 'f4'), # 60; second intent parameter
('intent_p3', 'f4'), # 64; third intent parameter
('intent_code', 'i2'), # 68; NIFTI intent code
('datatype', 'i2'), # 70; it's the datatype
('bitpix', 'i2'), # 72; number of bits per voxel
('slice_start', 'i2'), # 74; first slice index
('pixdim', 'f4', (8,)), # 76; grid spacings (units below)
('vox_offset', 'f4'), # 108; offset to data in image file
('scl_slope', 'f4'), # 112; data scaling slope
('scl_inter', 'f4'), # 116; data scaling intercept
('slice_end', 'i2'), # 120; last slice index
('slice_code', 'u1'), # 122; slice timing order
('xyzt_units', 'u1'), # 123; units of pixdim[1..4]
('cal_max', 'f4'), # 124; max display intensity
('cal_min', 'f4'), # 128; min display intensity
('slice_duration', 'f4'), # 132; time for 1 slice
('toffset', 'f4'), # 136; time axis shift
('glmax', 'i4'), # 140; unused
('glmin', 'i4'), # 144; unused
('descrip', 'S80'), # 148; any text
('aux_file', 'S24'), # 228; auxiliary filename
('qform_code', 'i2'), # 252; xform code
('sform_code', 'i2'), # 254; xform code
('quatern_b', 'f4'), # 256; quaternion b param
('quatern_c', 'f4'), # 260; quaternion c param
('quatern_d', 'f4'), # 264; quaternion d param
('qoffset_x', 'f4'), # 268; quaternion x shift
('qoffset_y', 'f4'), # 272; quaternion y shift
('qoffset_z', 'f4'), # 276; quaternion z shift
('srow_x', 'f4', (4,)), # 280; 1st row affine transform
('srow_y', 'f4', (4,)), # 296; 2nd row affine transform
('srow_z', 'f4', (4,)), # 312; 3rd row affine transform
('intent_name', 'S16'), # 328; name or meaning of data
('magic', 'S4') # 344; must be 'ni1\0' or 'n+1\0'
]
# Full header numpy dtype
header_dtype = np.dtype(header_dtd)
# datatypes not in analyze format, with codes
if have_binary128():
# Only enable 128 bit floats if we really have IEEE binary 128 longdoubles
_float128t = np.longdouble
_complex256t = np.longcomplex
else:
_float128t = np.void
_complex256t = np.void
_dtdefs = ( # code, label, dtype definition, niistring
(0, 'none', np.void, ""),
(1, 'binary', np.void, ""),
(2, 'uint8', np.uint8, "NIFTI_TYPE_UINT8"),
(4, 'int16', np.int16, "NIFTI_TYPE_INT16"),
(8, 'int32', np.int32, "NIFTI_TYPE_INT32"),
(16, 'float32', np.float32, "NIFTI_TYPE_FLOAT32"),
(32, 'complex64', np.complex64, "NIFTI_TYPE_COMPLEX64"),
(64, 'float64', np.float64, "NIFTI_TYPE_FLOAT64"),
(128, 'RGB', np.dtype([('R', 'u1'),
('G', 'u1'),
('B', 'u1')]), "NIFTI_TYPE_RGB24"),
(255, 'all', np.void, ''),
(256, 'int8', np.int8, "NIFTI_TYPE_INT8"),
(512, 'uint16', np.uint16, "NIFTI_TYPE_UINT16"),
(768, 'uint32', np.uint32, "NIFTI_TYPE_UINT32"),
(1024, 'int64', np.int64, "NIFTI_TYPE_INT64"),
(1280, 'uint64', np.uint64, "NIFTI_TYPE_UINT64"),
(1536, 'float128', _float128t, "NIFTI_TYPE_FLOAT128"),
(1792, 'complex128', np.complex128, "NIFTI_TYPE_COMPLEX128"),
(2048, 'complex256', _complex256t, "NIFTI_TYPE_COMPLEX256"),
(2304, 'RGBA', np.dtype([('R', 'u1'),
('G', 'u1'),
('B', 'u1'),
('A', 'u1')]), "NIFTI_TYPE_RGBA32"),
)
# Make full code alias bank, including dtype column
data_type_codes = make_dt_codes(_dtdefs)
# Transform (qform, sform) codes
xform_codes = Recoder(( # code, label, niistring
(0, 'unknown', "NIFTI_XFORM_UNKNOWN"),
(1, 'scanner', "NIFTI_XFORM_SCANNER_ANAT"),
(2, 'aligned', "NIFTI_XFORM_ALIGNED_ANAT"),
(3, 'talairach', "NIFTI_XFORM_TALAIRACH"),
(4, 'mni', "NIFTI_XFORM_MNI_152")), fields=('code', 'label', 'niistring'))
# unit codes
unit_codes = Recoder(( # code, label
(0, 'unknown'),
(1, 'meter'),
(2, 'mm'),
(3, 'micron'),
(8, 'sec'),
(16, 'msec'),
(24, 'usec'),
(32, 'hz'),
(40, 'ppm'),
(48, 'rads')), fields=('code', 'label'))
slice_order_codes = Recoder(( # code, label
(0, 'unknown'),
(1, 'sequential increasing', 'seq inc'),
(2, 'sequential decreasing', 'seq dec'),
(3, 'alternating increasing', 'alt inc'),
(4, 'alternating decreasing', 'alt dec'),
(5, 'alternating increasing 2', 'alt inc 2'),
(6, 'alternating decreasing 2', 'alt dec 2')), fields=('code', 'label'))
intent_codes = Recoder((
# code, label, parameters description tuple
(0, 'none', (), "NIFTI_INTENT_NONE"),
(2, 'correlation', ('p1 = DOF',), "NIFTI_INTENT_CORREL"),
(3, 't test', ('p1 = DOF',), "NIFTI_INTENT_TTEST"),
(4, 'f test', ('p1 = numerator DOF', 'p2 = denominator DOF'),
"NIFTI_INTENT_FTEST"),
(5, 'z score', (), "NIFTI_INTENT_ZSCORE"),
(6, 'chi2', ('p1 = DOF',), "NIFTI_INTENT_CHISQ"),
# two parameter beta distribution
(7, 'beta',
('p1=a', 'p2=b'),
"NIFTI_INTENT_BETA"),
# Prob(x) = (p1 choose x) * p2^x * (1-p2)^(p1-x), for x=0,1,...,p1
(8, 'binomial',
('p1 = number of trials', 'p2 = probability per trial'),
"NIFTI_INTENT_BINOM"),
# 2 parameter gamma
# Density(x) proportional to # x^(p1-1) * exp(-p2*x)
(9, 'gamma',
('p1 = shape, p2 = scale', 2),
"NIFTI_INTENT_GAMMA"),
(10, 'poisson',
('p1 = mean',),
"NIFTI_INTENT_POISSON"),
(11, 'normal',
('p1 = mean', 'p2 = standard deviation',),
"NIFTI_INTENT_NORMAL"),
(12, 'non central f test',
('p1 = numerator DOF',
'p2 = denominator DOF',
'p3 = numerator noncentrality parameter',),
"NIFTI_INTENT_FTEST_NONC"),
(13, 'non central chi2',
('p1 = DOF', 'p2 = noncentrality parameter',),
"NIFTI_INTENT_CHISQ_NONC"),
(14, 'logistic',
('p1 = location', 'p2 = scale',),
"NIFTI_INTENT_LOGISTIC"),
(15, 'laplace',
('p1 = location', 'p2 = scale'),
"NIFTI_INTENT_LAPLACE"),
(16, 'uniform',
('p1 = lower end', 'p2 = upper end'),
"NIFTI_INTENT_UNIFORM"),
(17, 'non central t test',
('p1 = DOF', 'p2 = noncentrality parameter'),
"NIFTI_INTENT_TTEST_NONC"),
(18, 'weibull',
('p1 = location', 'p2 = scale, p3 = power'),
"NIFTI_INTENT_WEIBULL"),
# p1 = 1 = 'half normal' distribution
# p1 = 2 = Rayleigh distribution
# p1 = 3 = Maxwell-Boltzmann distribution.
(19, 'chi', ('p1 = DOF',), "NIFTI_INTENT_CHI"),
(20, 'inverse gaussian',
('pi = mu', 'p2 = lambda'),
"NIFTI_INTENT_INVGAUSS"),
(21, 'extreme value 1',
('p1 = location', 'p2 = scale'),
"NIFTI_INTENT_EXTVAL"),
(22, 'p value', (), "NIFTI_INTENT_PVAL"),
(23, 'log p value', (), "NIFTI_INTENT_LOGPVAL"),
(24, 'log10 p value', (), "NIFTI_INTENT_LOG10PVAL"),
(1001, 'estimate', (), "NIFTI_INTENT_ESTIMATE"),
(1002, 'label', (), "NIFTI_INTENT_LABEL"),
(1003, 'neuroname', (), "NIFTI_INTENT_NEURONAME"),
(1004, 'general matrix',
('p1 = M', 'p2 = N'),
"NIFTI_INTENT_GENMATRIX"),
(1005, 'symmetric matrix', ('p1 = M',), "NIFTI_INTENT_SYMMATRIX"),
(1006, 'displacement vector', (), "NIFTI_INTENT_DISPVECT"),
(1007, 'vector', (), "NIFTI_INTENT_VECTOR"),
(1008, 'pointset', (), "NIFTI_INTENT_POINTSET"),
(1009, 'triangle', (), "NIFTI_INTENT_TRIANGLE"),
(1010, 'quaternion', (), "NIFTI_INTENT_QUATERNION"),
(1011, 'dimensionless', (), "NIFTI_INTENT_DIMLESS"),
(2001, 'time series',
(),
"NIFTI_INTENT_TIME_SERIES",
"NIFTI_INTENT_TIMESERIES"), # this mis-spell occurs in the wild
(2002, 'node index', (), "NIFTI_INTENT_NODE_INDEX"),
(2003, 'rgb vector', (), "NIFTI_INTENT_RGB_VECTOR"),
(2004, 'rgba vector', (), "NIFTI_INTENT_RGBA_VECTOR"),
(2005, 'shape', (), "NIFTI_INTENT_SHAPE"),
# FSL-specific intent codes - codes used by FNIRT
# ($FSLDIR/warpfns/fnirt_file_reader.h:104)
(2006, 'fnirt disp field', (), 'FSL_FNIRT_DISPLACEMENT_FIELD'),
(2007, 'fnirt cubic spline coef', (), 'FSL_CUBIC_SPLINE_COEFFICIENTS'),
(2008, 'fnirt dct coef', (), 'FSL_DCT_COEFFICIENTS'),
(2009, 'fnirt quad spline coef', (), 'FSL_QUADRATIC_SPLINE_COEFFICIENTS'),
# FSL-specific intent codes - codes used by TOPUP
# ($FSLDIR/topup/topup_file_io.h:104)
(2016, 'topup cubic spline coef ', (),
'FSL_TOPUP_CUBIC_SPLINE_COEFFICIENTS'),
(2017, 'topup quad spline coef', (),
'FSL_TOPUP_QUADRATIC_SPLINE_COEFFICIENTS'),
(2018, 'topup field', (), 'FSL_TOPUP_FIELD'),
), fields=('code', 'label', 'parameters', 'niistring'))
class Nifti1Extension(object):
"""Baseclass for NIfTI1 header extensions.
This class is sufficient to handle very simple text-based extensions, such
as `comment`. More sophisticated extensions should/will be supported by
dedicated subclasses.
"""
def __init__(self, code, content):
"""
Parameters
----------
code : int or str
Canonical extension code as defined in the NIfTI standard, given
either as integer or corresponding label
(see :data:`~nibabel.nifti1.extension_codes`)
content : str
Extension content as read from the NIfTI file header. This content is
converted into a runtime representation.
"""
try:
self._code = extension_codes.code[code]
except KeyError:
# XXX or fail or at least complain?
self._code = code
self._content = self._unmangle(content)
def _unmangle(self, value):
"""Convert the extension content into its runtime representation.
The default implementation does nothing at all.
Parameters
----------
value : str
Extension content as read from file.
Returns
-------
The same object that was passed as `value`.
Notes
-----
Subclasses should reimplement this method to provide the desired
unmangling procedure and may return any type of object.
"""
return value
def _mangle(self, value):
"""Convert the extension content into NIfTI file header representation.
The default implementation does nothing at all.
Parameters
----------
value : str
Extension content in runtime form.
Returns
-------
str
Notes
-----
Subclasses should reimplement this method to provide the desired
mangling procedure.
"""
return value
def get_code(self):
"""Return the canonical extension type code."""
return self._code
def get_content(self):
"""Return the extension content in its runtime representation."""
return self._content
def get_sizeondisk(self):
"""Return the size of the extension in the NIfTI file.
"""
# need raw value size plus 8 bytes for esize and ecode
size = len(self._mangle(self._content))
size += 8
# extensions size has to be a multiple of 16 bytes
if size % 16 != 0:
size += 16 - (size % 16)
return size
def __repr__(self):
try:
code = extension_codes.label[self._code]
except KeyError:
# deal with unknown codes
code = self._code
s = "Nifti1Extension('%s', '%s')" % (code, self._content)
return s
def __eq__(self, other):
return (self._code, self._content) == (other._code, other._content)
def __ne__(self, other):
return not self == other
def write_to(self, fileobj, byteswap):
''' Write header extensions to fileobj
Write starts at fileobj current file position.
Parameters
----------
fileobj : file-like object
Should implement ``write`` method
byteswap : boolean
Flag if byteswapping the data is required.
Returns
-------
None
'''
extstart = fileobj.tell()
rawsize = self.get_sizeondisk()
# write esize and ecode first
extinfo = np.array((rawsize, self._code), dtype=np.int32)
if byteswap:
extinfo = extinfo.byteswap()
fileobj.write(extinfo.tostring())
# followed by the actual extension content
# XXX if mangling upon load is implemented, it should be reverted here
fileobj.write(self._mangle(self._content))
# be nice and zero out remaining part of the extension till the
# next 16 byte border
fileobj.write(b'\x00' * (extstart + rawsize - fileobj.tell()))
class Nifti1DicomExtension(Nifti1Extension):
"""NIfTI1 DICOM header extension
This class is a thin wrapper around pydicom to read a binary DICOM
byte string. If pydicom is available, content is exposed as a Dicom Dataset.
Otherwise, this silently falls back to the standard NiftiExtension class
and content is the raw bytestring loaded directly from the nifti file
header.
"""
def __init__(self, code, content, parent_hdr=None):
"""
Parameters
----------
code : int or str
Canonical extension code as defined in the NIfTI standard, given
either as integer or corresponding label
(see :data:`~nibabel.nifti1.extension_codes`)
content : bytes or pydicom Dataset or None
Extension content - either a bytestring as read from the NIfTI file
header or an existing pydicom Dataset. If a bystestring, the content
is converted into a Dataset on initialization. If None, a new empty
Dataset is created.
parent_hdr : :class:`~nibabel.nifti1.Nifti1Header`, optional
If a dicom extension belongs to an existing
:class:`~nibabel.nifti1.Nifti1Header`, it may be provided here to
ensure that the DICOM dataset is written with correctly corresponding
endianness; otherwise it is assumed the dataset is little endian.
Notes
-----
code should always be 2 for DICOM.
"""
self._code = code
if parent_hdr:
self._is_little_endian = parent_hdr.endianness == '<'
else:
self._is_little_endian = True
if isinstance(content, pdcm.dataset.Dataset):
self._is_implicit_VR = False
self._raw_content = self._mangle(content)
self._content = content
elif isinstance(content, bytes): # Got a byte string - unmangle it
self._raw_content = content
self._is_implicit_VR = self._guess_implicit_VR()
ds = self._unmangle(content, self._is_implicit_VR,
self._is_little_endian)
self._content = ds
elif content is None: # initialize a new dicom dataset
self._is_implicit_VR = False
self._content = pdcm.dataset.Dataset()
else:
raise TypeError("content must be either a bytestring or a pydicom "
"Dataset. Got %s" % content.__class__)
def _guess_implicit_VR(self):
"""Try to guess DICOM syntax by checking for valid VRs.
Without a DICOM Transfer Syntax, it's difficult to tell if Value
Representations (VRs) are included in the DICOM encoding or not.
This reads where the first VR would be and checks it against a list of
valid VRs
"""
potential_vr = self._raw_content[4:6].decode()
if potential_vr in pdcm.values.converters.keys():
implicit_VR = False
else:
implicit_VR = True
return implicit_VR
def _unmangle(self, value, is_implicit_VR=False, is_little_endian=True):
bio = BytesIO(value)
ds = pdcm.filereader.read_dataset(bio,
is_implicit_VR,
is_little_endian)
return ds
def _mangle(self, dataset):
bio = BytesIO()
dio = pdcm.filebase.DicomFileLike(bio)
dio.is_implicit_VR = self._is_implicit_VR
dio.is_little_endian = self._is_little_endian
ds_len = pdcm.filewriter.write_dataset(dio, dataset)
dio.seek(0)
return dio.read(ds_len)
# NIfTI header extension type codes (ECODE)
# see nifti1_io.h for a complete list of all known extensions and
# references to their description or contacts of the respective
# initiators
extension_codes = Recoder((
(0, "ignore", Nifti1Extension),
(2, "dicom", Nifti1DicomExtension if have_dicom else Nifti1Extension),
(4, "afni", Nifti1Extension),
(6, "comment", Nifti1Extension),
(8, "xcede", Nifti1Extension),
(10, "jimdiminfo", Nifti1Extension),
(12, "workflow_fwds", Nifti1Extension),
(14, "freesurfer", Nifti1Extension),
(16, "pypickle", Nifti1Extension),
), fields=('code', 'label', 'handler'))
class Nifti1Extensions(list):
"""Simple extension collection, implemented as a list-subclass.
"""
def count(self, ecode):
"""Returns the number of extensions matching a given *ecode*.
Parameters
----------
code : int | str
The ecode can be specified either literal or as numerical value.
"""
count = 0
code = extension_codes.code[ecode]
for e in self:
if e.get_code() == code:
count += 1
return count
def get_codes(self):
"""Return a list of the extension code of all available extensions"""
return [e.get_code() for e in self]
def get_sizeondisk(self):
"""Return the size of the complete header extensions in the NIfTI file.
"""
return np.sum([e.get_sizeondisk() for e in self])
def __repr__(self):
s = "Nifti1Extensions(%s)" % ', '.join(str(e) for e in self)
return s
def __cmp__(self, other):
return cmp(list(self), list(other))
def write_to(self, fileobj, byteswap):
''' Write header extensions to fileobj
Write starts at fileobj current file position.
Parameters
----------
fileobj : file-like object
Should implement ``write`` method
byteswap : boolean
Flag if byteswapping the data is required.
Returns
-------
None
'''
for e in self:
e.write_to(fileobj, byteswap)
@classmethod
def from_fileobj(klass, fileobj, size, byteswap):
'''Read header extensions from a fileobj
Parameters
----------
fileobj : file-like object
We begin reading the extensions at the current file position
size : int
Number of bytes to read. If negative, fileobj will be read till its
end.
byteswap : boolean
Flag if byteswapping the read data is required.
Returns
-------
An extension list. This list might be empty in case not extensions
were present in fileobj.
'''
# make empty extension list
extensions = klass()
# assume the file pointer is at the beginning of any extensions.
# read until the whole header is parsed (each extension is a multiple
# of 16 bytes) or in case of a separate header file till the end
# (break inside the body)
while size >= 16 or size < 0:
# the next 8 bytes should have esize and ecode
ext_def = fileobj.read(8)
# nothing was read and instructed to read till the end
# -> assume all extensions where parsed and break
if not len(ext_def) and size < 0:
break
# otherwise there should be a full extension header
if not len(ext_def) == 8:
raise HeaderDataError('failed to read extension header')
ext_def = np.fromstring(ext_def, dtype=np.int32)
if byteswap:
ext_def = ext_def.byteswap()
# be extra verbose
ecode = ext_def[1]
esize = ext_def[0]
if esize % 16:
warnings.warn(
'Extension size is not a multiple of 16 bytes; '
'Assuming size is correct and hoping for the best',
UserWarning)
# read extension itself; esize includes the 8 bytes already read
evalue = fileobj.read(int(esize - 8))
if not len(evalue) == esize - 8:
raise HeaderDataError('failed to read extension content')
# note that we read a full extension
size -= esize
# store raw extension content, but strip trailing NULL chars
evalue = evalue.rstrip(b'\x00')
# 'extension_codes' also knows the best implementation to handle
# a particular extension type
try:
ext = extension_codes.handler[ecode](ecode, evalue)
except KeyError:
# unknown extension type
# XXX complain or fail or go with a generic extension
ext = Nifti1Extension(ecode, evalue)
extensions.append(ext)
return extensions
class Nifti1Header(SpmAnalyzeHeader):
''' Class for NIfTI1 header
The NIfTI1 header has many more coded fields than the simpler Analyze
variants. NIfTI1 headers also have extensions.
Nifti allows the header to be a separate file, as part of a nifti image /
header pair, or to precede the data in a single file. The object needs to
know which type it is, in order to manage the voxel offset pointing to the
data, extension reading, and writing the correct magic string.
This class handles the header-preceding-data case.
'''
# Copies of module level definitions
template_dtype = header_dtype
_data_type_codes = data_type_codes
# fields with recoders for their values
_field_recoders = {'datatype': data_type_codes,
'qform_code': xform_codes,
'sform_code': xform_codes,
'intent_code': intent_codes,
'slice_code': slice_order_codes}
# data scaling capabilities
has_data_slope = True
has_data_intercept = True
# Extension class; should implement __call__ for construction, and
# ``from_fileobj`` for reading from file
exts_klass = Nifti1Extensions
# Signal whether this is single (header + data) file
is_single = True
# Default voxel data offsets for single and pair
pair_vox_offset = 0
single_vox_offset = 352
# Magics for single and pair
pair_magic = b'ni1'
single_magic = b'n+1'
# Quaternion threshold near 0, based on float32 precision
quaternion_threshold = -np.finfo(np.float32).eps * 3
def __init__(self,
binaryblock=None,
endianness=None,
check=True,
extensions=()):
''' Initialize header from binary data block and extensions
'''
super(Nifti1Header, self).__init__(binaryblock,
endianness,
check)
self.extensions = self.exts_klass(extensions)
def copy(self):
''' Return copy of header
Take reference to extensions as well as copy of header contents
'''
return self.__class__(
self.binaryblock,
self.endianness,
False,
self.extensions)
@classmethod
def from_fileobj(klass, fileobj, endianness=None, check=True):
raw_str = fileobj.read(klass.template_dtype.itemsize)
hdr = klass(raw_str, endianness, check)
# Read next 4 bytes to see if we have extensions. The nifti standard
# has this as a 4 byte string; if the first value is not zero, then we
# have extensions.
extension_status = fileobj.read(4)
# Need to test *slice* of extension_status to preserve byte string type
# on Python 3
if len(extension_status) < 4 or extension_status[0:1] == b'\x00':
return hdr
# If this is a detached header file read to end
if not klass.is_single:
extsize = -1
else: # otherwise read until the beginning of the data
extsize = hdr._structarr['vox_offset'] - fileobj.tell()
byteswap = endian_codes['native'] != hdr.endianness
hdr.extensions = klass.exts_klass.from_fileobj(fileobj, extsize,
byteswap)
return hdr
def write_to(self, fileobj):
# First check that vox offset is large enough; set if necessary
if self.is_single:
vox_offset = self._structarr['vox_offset']
min_vox_offset = (self.single_vox_offset +
self.extensions.get_sizeondisk())
if vox_offset == 0: # vox offset unset; set as necessary
self._structarr['vox_offset'] = min_vox_offset
elif vox_offset < min_vox_offset:
raise HeaderDataError(
'vox offset set to {0}, but need at least {1}'.format(
vox_offset, min_vox_offset))
super(Nifti1Header, self).write_to(fileobj)
# Write extensions
if len(self.extensions) == 0:
# If single file, write required 0 stream to signal no extensions
if self.is_single:
fileobj.write(b'\x00' * 4)
return
# Signal there are extensions that follow
fileobj.write(b'\x01\x00\x00\x00')
byteswap = endian_codes['native'] != self.endianness
self.extensions.write_to(fileobj, byteswap)
def get_best_affine(self):
''' Select best of available transforms '''
hdr = self._structarr
if hdr['sform_code'] != 0:
return self.get_sform()
if hdr['qform_code'] != 0:
return self.get_qform()
return self.get_base_affine()
@classmethod
def default_structarr(klass, endianness=None):
''' Create empty header binary block with given endianness '''
hdr_data = super(Nifti1Header, klass).default_structarr(endianness)
if klass.is_single:
hdr_data['magic'] = klass.single_magic
else:
hdr_data['magic'] = klass.pair_magic
return hdr_data
@classmethod
def from_header(klass, header=None, check=True):
''' Class method to create header from another header
Extend Analyze header copy by copying extensions from other Nifti
types.
Parameters
----------
header : ``Header`` instance or mapping
a header of this class, or another class of header for
conversion to this type
check : {True, False}
whether to check header for integrity
Returns
-------
hdr : header instance
fresh header instance of our own class
'''
new_hdr = super(Nifti1Header, klass).from_header(header, check)
if isinstance(header, Nifti1Header):
new_hdr.extensions[:] = header.extensions[:]
return new_hdr
def get_data_shape(self):
''' Get shape of data
Examples
--------
>>> hdr = Nifti1Header()
>>> hdr.get_data_shape()
(0,)
>>> hdr.set_data_shape((1,2,3))
>>> hdr.get_data_shape()
(1, 2, 3)
Expanding number of dimensions gets default zooms
>>> hdr.get_zooms()
(1.0, 1.0, 1.0)
Notes
-----
Applies freesurfer hack for large vectors described in `issue 100`_ and
`save_nifti.m <save77_>`_.
Allows for freesurfer hack for 7th order icosahedron surface described
in `issue 309`_, load_nifti.m_, and `save_nifti.m <save50_>`_.
'''
shape = super(Nifti1Header, self).get_data_shape()
# Apply freesurfer hack for large vectors
if shape[:3] == (-1, 1, 1):
vec_len = int(self._structarr['glmin'])
if vec_len == 0:
raise HeaderDataError('-1 in dim[1] but 0 in glmin; '
'inconsistent freesurfer type header?')
return (vec_len, 1, 1) + shape[3:]
# Apply freesurfer hack for ico7 surface
elif shape[:3] == (27307, 1, 6):
return (163842, 1, 1) + shape[3:]
else: # Normal case
return shape
def set_data_shape(self, shape):
''' Set shape of data # noqa
If ``ndims == len(shape)`` then we set zooms for dimensions higher than
``ndims`` to 1.0
Nifti1 images can have up to seven dimensions. For FreeSurfer-variant
Nifti surface files, the first dimension is assumed to correspond to
vertices/nodes on a surface, and dimensions two and three are
constrained to have depth of 1. Dimensions 4-7 are constrained only by
type bounds.
Parameters
----------
shape : sequence
sequence of integers specifying data array shape
Notes
-----
Applies freesurfer hack for large vectors described in `issue 100`_ and
`save_nifti.m <save77_>`_.
Allows for freesurfer hack for 7th order icosahedron surface described
in `issue 309`_, load_nifti.m_, and `save_nifti.m <save50_>`_.
The Nifti1 `standard header`_ allows for the following "point set"
definition of a surface, not currently implemented in nibabel.
::
To signify that the vector value at each voxel is really a
spatial coordinate (e.g., the vertices or nodes of a surface mesh):
- dataset must have a 5th dimension
- intent_code must be NIFTI_INTENT_POINTSET
- dim[0] = 5
- dim[1] = number of points
- dim[2] = dim[3] = dim[4] = 1
- dim[5] must be the dimensionality of space (e.g., 3 => 3D space).
- intent_name may describe the object these points come from
(e.g., "pial", "gray/white" , "EEG", "MEG").
.. _issue 100: https://github.com/nipy/nibabel/issues/100
.. _issue 309: https://github.com/nipy/nibabel/issues/309
.. _save77:
https://github.com/fieldtrip/fieldtrip/blob/428798b/external/freesurfer/save_nifti.m#L77-L82
.. _save50:
https://github.com/fieldtrip/fieldtrip/blob/428798b/external/freesurfer/save_nifti.m#L50-L56
.. _load_nifti.m:
https://github.com/fieldtrip/fieldtrip/blob/428798b/external/freesurfer/load_nifti.m#L86-L89
.. _standard header: http://nifti.nimh.nih.gov/pub/dist/src/niftilib/nifti1.h
'''
hdr = self._structarr
shape = tuple(shape)
# Apply freesurfer hack for ico7 surface
if shape[:3] == (163842, 1, 1):
shape = (27307, 1, 6) + shape[3:]
# Apply freesurfer hack for large vectors
elif (len(shape) >= 3 and shape[1:3] == (1, 1) and
shape[0] > np.iinfo(hdr['dim'].dtype.base).max):
try:
hdr['glmin'] = shape[0]
except OverflowError:
overflow = True
else:
overflow = hdr['glmin'] != shape[0]
if overflow:
raise HeaderDataError('shape[0] %s does not fit in glmax '
'datatype' % shape[0])
warnings.warn('Using large vector Freesurfer hack; header will '
'not be compatible with SPM or FSL', stacklevel=2)
shape = (-1, 1, 1) + shape[3:]
super(Nifti1Header, self).set_data_shape(shape)
def get_qform_quaternion(self):
''' Compute quaternion from b, c, d of quaternion
Fills a value by assuming this is a unit quaternion
'''
hdr = self._structarr
bcd = [hdr['quatern_b'], hdr['quatern_c'], hdr['quatern_d']]
# Adjust threshold to precision of stored values in header
return fillpositive(bcd, self.quaternion_threshold)
def get_qform(self, coded=False):
""" Return 4x4 affine matrix from qform parameters in header
Parameters
----------
coded : bool, optional
If True, return {affine or None}, and qform code. If False, just
return affine. {affine or None} means, return None if qform code
== 0, and affine otherwise.
Returns
-------
affine : None or (4,4) ndarray
If `coded` is False, always return affine reconstructed from qform
quaternion. If `coded` is True, return None if qform code is 0,
else return the affine.
code : int
Qform code. Only returned if `coded` is True.
"""
hdr = self._structarr
code = int(hdr['qform_code'])
if code == 0 and coded:
return None, 0
quat = self.get_qform_quaternion()
R = quat2mat(quat)
vox = hdr['pixdim'][1:4].copy()
if np.any(vox < 0):
raise HeaderDataError('pixdims[1,2,3] should be positive')
qfac = hdr['pixdim'][0]
if qfac not in (-1, 1):
raise HeaderDataError('qfac (pixdim[0]) should be 1 or -1')
vox[-1] *= qfac
S = np.diag(vox)
M = np.dot(R, S)
out = np.eye(4)
out[0:3, 0:3] = M
out[0:3, 3] = [hdr['qoffset_x'], hdr['qoffset_y'], hdr['qoffset_z']]
if coded:
return out, code
return out
def set_qform(self, affine, code=None, strip_shears=True):
''' Set qform header values from 4x4 affine
Parameters
----------
affine : None or 4x4 array
affine transform to write into sform. If None, only set code.
code : None, string or integer, optional
String or integer giving meaning of transform in *affine*.
The default is None. If code is None, then:
* If affine is None, `code`-> 0
* If affine not None and existing qform code in header == 0,
`code`-> 2 (aligned)
* If affine not None and existing qform code in header != 0,
`code`-> existing qform code in header
strip_shears : bool, optional
Whether to strip shears in `affine`. If True, shears will be
silently stripped. If False, the presence of shears will raise a
``HeaderDataError``
Notes
-----
The qform transform only encodes translations, rotations and
zooms. If there are shear components to the `affine` transform, and
`strip_shears` is True (the default), the written qform gives the
closest approximation where the rotation matrix is orthogonal. This is
to allow quaternion representation. The orthogonal representation
enforces orthogonal axes.
Examples
--------
>>> hdr = Nifti1Header()
>>> int(hdr['qform_code']) # gives 0 - unknown
0
>>> affine = np.diag([1,2,3,1])
>>> np.all(hdr.get_qform() == affine)
False
>>> hdr.set_qform(affine)
>>> np.all(hdr.get_qform() == affine)
True
>>> int(hdr['qform_code']) # gives 2 - aligned
2
>>> hdr.set_qform(affine, code='talairach')
>>> int(hdr['qform_code'])
3
>>> hdr.set_qform(affine, code=None)
>>> int(hdr['qform_code'])
3
>>> hdr.set_qform(affine, code='scanner')
>>> int(hdr['qform_code'])
1
>>> hdr.set_qform(None)
>>> int(hdr['qform_code'])
0
'''
hdr = self._structarr
old_code = hdr['qform_code']
if code is None:
if affine is None:
code = 0
elif old_code == 0:
code = 2 # aligned
else: