Skip to content

Commit

Permalink
ENH: Update Nifti extension codes, implement JSON type
Browse files Browse the repository at this point in the history
  • Loading branch information
effigies committed Jun 9, 2024
1 parent 2c26fa5 commit 63f0647
Showing 1 changed file with 31 additions and 1 deletion.
32 changes: 31 additions & 1 deletion nibabel/nifti1.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

from __future__ import annotations

import json
import warnings
from io import BytesIO

Expand Down Expand Up @@ -377,7 +378,7 @@ def __repr__(self):
# deal with unknown codes
code = self._code

s = f"Nifti1Extension('{code}', '{self._content}')"
s = f"{self.__class__.__name__}('{code}', '{self._content}')"

Check warning on line 381 in nibabel/nifti1.py

View check run for this annotation

Codecov / codecov/patch

nibabel/nifti1.py#L381

Added line #L381 was not covered by tests
return s

def __eq__(self, other):
Expand Down Expand Up @@ -505,6 +506,20 @@ def _mangle(self, dataset):
return dio.read(ds_len)


class NiftiJSONExtension(Nifti1Extension):
"""Generic JSON-based NIfTI header extension
This class handles serialization and deserialization of JSON contents
without any further validation or processing.
"""

def _unmangle(self, value: bytes) -> dict:
return json.loads(value.decode('utf-8'))

Check warning on line 517 in nibabel/nifti1.py

View check run for this annotation

Codecov / codecov/patch

nibabel/nifti1.py#L517

Added line #L517 was not covered by tests

def _mangle(self, value: dict) -> bytes:
return json.dumps(value).encode('utf-8')

Check warning on line 520 in nibabel/nifti1.py

View check run for this annotation

Codecov / codecov/patch

nibabel/nifti1.py#L520

Added line #L520 was not covered by tests


# 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
Expand All @@ -520,6 +535,21 @@ def _mangle(self, dataset):
(12, 'workflow_fwds', Nifti1Extension),
(14, 'freesurfer', Nifti1Extension),
(16, 'pypickle', Nifti1Extension),
(18, 'mind_ident', Nifti1Extension),
(20, 'b_value', Nifti1Extension),
(22, 'spherical_direction', Nifti1Extension),
(24, 'dt_component', Nifti1Extension),
(26, 'shc_degreeorder', Nifti1Extension),
(28, 'voxbo', Nifti1Extension),
(30, 'caret', Nifti1Extension),
## Defined in nibabel.cifti2.parse_cifti2
# (32, 'cifti', Cifti2Extension),
(34, 'variable_frame_timing', Nifti1Extension),
(36, 'unassigned', Nifti1Extension),
(38, 'eval', Nifti1Extension),
(40, 'matlab', Nifti1Extension),
(42, 'quantiphyse', Nifti1Extension),
(44, 'mrs', NiftiJSONExtension),
),
fields=('code', 'label', 'handler'),
)
Expand Down

0 comments on commit 63f0647

Please sign in to comment.