csa-header 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- csa_header/__about__.py +4 -0
- csa_header/__init__.py +12 -0
- csa_header/ascii/__init__.py +3 -0
- csa_header/ascii/ascconv.py +285 -0
- csa_header/ascii/header.py +82 -0
- csa_header/ascii/messages.py +9 -0
- csa_header/exceptions.py +6 -0
- csa_header/header.py +331 -0
- csa_header/messages.py +20 -0
- csa_header/unpacker.py +125 -0
- csa_header/utils.py +56 -0
- csa_header-1.0.0.dist-info/METADATA +312 -0
- csa_header-1.0.0.dist-info/RECORD +15 -0
- csa_header-1.0.0.dist-info/WHEEL +4 -0
- csa_header-1.0.0.dist-info/licenses/LICENSE.txt +9 -0
csa_header/__about__.py
ADDED
csa_header/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""
|
|
2
|
+
CSA headers are Siemens-specific private data elements that are embedded
|
|
3
|
+
in some DICOM headers, specifically as the (0029, 1010)/`"CSA Image Header
|
|
4
|
+
Info"` and (0029, 1020)/`"CSA Series Header Info"` tags. For more information
|
|
5
|
+
see `this
|
|
6
|
+
<https://nipy.org/nibabel/dicom/siemens_csa.html#siemens-format-dicom-with-csa-header>`_
|
|
7
|
+
`NiBabel <https://nipy.org/nibabel/index.html>`_ article.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from csa_header.header import CsaHeader
|
|
11
|
+
|
|
12
|
+
__all__ = ["CsaHeader"]
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Parse the "ASCCONV" meta data format found in a variety of Siemens MR files.
|
|
3
|
+
|
|
4
|
+
Many Siemens files have a private data element that includes text, sandwiched
|
|
5
|
+
between ``### ASCCONV`` ``BEGIN`` and ``END`` lines.
|
|
6
|
+
|
|
7
|
+
Here are some example lines from that text::
|
|
8
|
+
|
|
9
|
+
sGroupArray.lSize = 1
|
|
10
|
+
sGroupArray.anMember[1] = 1
|
|
11
|
+
sGroupArray.sPSat.ulShape = 1
|
|
12
|
+
sWipMemBlock.tFree = ""WIP_Identifier: WIP#919B(Fri Feb 10 09:46:48 2017)""
|
|
13
|
+
sWipMemBlock.alFree.__attribute__.size = 64
|
|
14
|
+
sWipMemBlock.alFree[0] = 2
|
|
15
|
+
sDiffusion.sFreeDiffusionData.sComment.0 = 0x41 # 'A'
|
|
16
|
+
|
|
17
|
+
Notice that the names are in Hungarian-like notation, with a lower-case prefix
|
|
18
|
+
giving the object type (``s`` for Struct, ``a`` for Array, ``l`` for Long).
|
|
19
|
+
Notice too that we can't ignore these because variables may only differ in
|
|
20
|
+
their prefix, as in ``tFree`` and ``alFree`` above.
|
|
21
|
+
|
|
22
|
+
The ``ASCCONV`` text looks very much like standard Python assignment syntax,
|
|
23
|
+
with a few exceptions. Specifically:
|
|
24
|
+
|
|
25
|
+
* The string quotes may or may not be doubled, as in ``""``, and as in the
|
|
26
|
+
examples above.
|
|
27
|
+
* The last example line above is invalid Python syntax, because of the integer
|
|
28
|
+
attribute name.
|
|
29
|
+
|
|
30
|
+
We deal with the first two exceptions by string replacements before parsing.
|
|
31
|
+
|
|
32
|
+
We can then parse the text with the Python AST parser.
|
|
33
|
+
|
|
34
|
+
The last problem for assignment is that lines like ``sWipMemBlock.alFree[0] =
|
|
35
|
+
2`` look like list assignment, but there may also be prior lines like
|
|
36
|
+
``sWipMemBlock.alFree.__attribute__.size = 64``, implying object assignment.
|
|
37
|
+
|
|
38
|
+
We deal with this by dropping any assignments containing ``__attribute__``.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
from __future__ import annotations
|
|
42
|
+
|
|
43
|
+
import ast
|
|
44
|
+
import re
|
|
45
|
+
from collections.abc import Sequence
|
|
46
|
+
from typing import Callable, cast
|
|
47
|
+
|
|
48
|
+
from csa_header.ascii import messages
|
|
49
|
+
|
|
50
|
+
#: ASCCONV text block regular expression pattern.
|
|
51
|
+
ASCCONV_PATTERN = r"### ASCCONV BEGIN((?:\s*[^=\s]+=[^=\s]+)*) ###\n(.*?)\n### ASCCONV END ###"
|
|
52
|
+
|
|
53
|
+
#: Regular expression to extract ASCCONV text block.
|
|
54
|
+
ASCCONV_RE = re.compile(ASCCONV_PATTERN, flags=re.M | re.S)
|
|
55
|
+
|
|
56
|
+
#: Terminal integer identifer regular expression pattern.
|
|
57
|
+
TERMINAL_DIGIT_PATTERN = r"^(.*)\.(\d+)(\s+=)"
|
|
58
|
+
|
|
59
|
+
#: Regular expression to replace terminal integer identifiers.
|
|
60
|
+
TERMINAL_DIGIT_RE = re.compile(TERMINAL_DIGIT_PATTERN, re.M)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class AscconvParseError(Exception):
|
|
64
|
+
"""
|
|
65
|
+
Error parsing ascconv file.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class NoValue:
|
|
70
|
+
"""
|
|
71
|
+
Signals no value present.
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def assign_to_atoms(assign_ast: ast.Assign, default_class: type = int) -> Sequence[tuple[ast.expr, type, str | int]]:
|
|
76
|
+
"""
|
|
77
|
+
Parse single assignment ast from ascconv line into atoms.
|
|
78
|
+
|
|
79
|
+
Parameters
|
|
80
|
+
----------
|
|
81
|
+
assign_ast : assignment statement ast
|
|
82
|
+
ast derived from single line of ascconv file
|
|
83
|
+
default_class : class, optional
|
|
84
|
+
Class that will create an object where we cannot yet know the object
|
|
85
|
+
type in the assignment
|
|
86
|
+
|
|
87
|
+
Returns
|
|
88
|
+
-------
|
|
89
|
+
atoms : list
|
|
90
|
+
List of length 3 tuples, where tuple values represent ``(target,
|
|
91
|
+
obj_type, obj_id)``. Defines left to right sequence of assignment in
|
|
92
|
+
`line_ast`
|
|
93
|
+
"""
|
|
94
|
+
n_targets = len(assign_ast.targets)
|
|
95
|
+
if n_targets != 1:
|
|
96
|
+
message = messages.AST_N_TARGETS.format(n_targets=n_targets)
|
|
97
|
+
raise AscconvParseError(message)
|
|
98
|
+
target = assign_ast.targets[0]
|
|
99
|
+
atoms: list[tuple[ast.expr, type, str | int]] = []
|
|
100
|
+
prev_target_type: type = default_class # Placeholder for any scalar value
|
|
101
|
+
while True:
|
|
102
|
+
if isinstance(target, ast.Name):
|
|
103
|
+
atoms.append((target, prev_target_type, target.id))
|
|
104
|
+
break
|
|
105
|
+
if isinstance(target, ast.Attribute):
|
|
106
|
+
atoms.append((target, prev_target_type, target.attr))
|
|
107
|
+
target = target.value
|
|
108
|
+
prev_target_type = dict
|
|
109
|
+
elif isinstance(target, ast.Subscript):
|
|
110
|
+
# Python 3.9+: slice is always ast.Constant for constant indices
|
|
111
|
+
index: int = target.slice.value # type: ignore[attr-defined]
|
|
112
|
+
atoms.append((target, prev_target_type, index))
|
|
113
|
+
target = target.value
|
|
114
|
+
prev_target_type = list
|
|
115
|
+
else:
|
|
116
|
+
message = messages.UNEXPECTED_LHS.format(target=target)
|
|
117
|
+
raise AscconvParseError(message)
|
|
118
|
+
return atoms[::-1]
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _create_obj_in(maker: Callable, name: str, root: dict) -> dict | list:
|
|
122
|
+
"""
|
|
123
|
+
Find or create object `maker` in dict-like `root` with given `name`.
|
|
124
|
+
|
|
125
|
+
Returns corresponding value if there is already a key matching `name` in
|
|
126
|
+
`root`. Otherwise, create new object with `maker`, insert into dictionary,
|
|
127
|
+
and return new object.
|
|
128
|
+
|
|
129
|
+
Can therefore modify `root` in place.
|
|
130
|
+
"""
|
|
131
|
+
obj = root.get(name, NoValue)
|
|
132
|
+
if obj is not NoValue:
|
|
133
|
+
return obj # type: ignore[no-any-return]
|
|
134
|
+
obj = maker()
|
|
135
|
+
root[name] = obj
|
|
136
|
+
return obj # type: ignore[no-any-return]
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _create_subscript_in(maker: Callable, index: int, root: list) -> dict | list:
|
|
140
|
+
"""
|
|
141
|
+
Find or create and insert object of type `maker` in `root` at `index`.
|
|
142
|
+
|
|
143
|
+
If `root` is long enough to contain this `index`, return the object at that
|
|
144
|
+
index. Otherwise, extend `root` with None elements to contain index
|
|
145
|
+
`index`, then create a new object by calling `maker`, insert at the end of
|
|
146
|
+
the list, and return this object.
|
|
147
|
+
|
|
148
|
+
Can therefore modify `root` in place.
|
|
149
|
+
"""
|
|
150
|
+
curr_n = len(root)
|
|
151
|
+
if curr_n > index:
|
|
152
|
+
return root[index] # type: ignore[no-any-return]
|
|
153
|
+
obj = maker()
|
|
154
|
+
root += [None] * (index - curr_n) + [obj]
|
|
155
|
+
return obj # type: ignore[no-any-return]
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def obj_from_atoms(
|
|
159
|
+
atoms: Sequence[tuple[ast.expr, type, str | int]], namespace: dict
|
|
160
|
+
) -> tuple[dict | list | None, str | int | None]:
|
|
161
|
+
"""
|
|
162
|
+
Return object defined by list `atoms` in dict-like `namespace`.
|
|
163
|
+
|
|
164
|
+
Parameters
|
|
165
|
+
----------
|
|
166
|
+
atoms : Iterable
|
|
167
|
+
Iterable of atoms, where atoms are length 3 tuples of (target,
|
|
168
|
+
obj_type, obj_id)
|
|
169
|
+
namespace : dict-like
|
|
170
|
+
Namespace in which object will be defined
|
|
171
|
+
|
|
172
|
+
Returns
|
|
173
|
+
-------
|
|
174
|
+
obj_root : object
|
|
175
|
+
Namespace such that we can set a desired value to the object defined in
|
|
176
|
+
`atoms` with ``obj_root[obj_key] = value``. `None` signals that the
|
|
177
|
+
function wants to discard this assignment
|
|
178
|
+
obj_key : str or int or None
|
|
179
|
+
Index into list or key into dictionary for `obj_root`. If function
|
|
180
|
+
rejects assignment, and `obj_root` is None, `obj_key` should be `None`
|
|
181
|
+
"""
|
|
182
|
+
root_obj: dict | list = namespace
|
|
183
|
+
atoms = list(atoms)
|
|
184
|
+
# Discard __attribute__ lines.
|
|
185
|
+
if any(e for e in atoms if e[2] == "__attribute__"):
|
|
186
|
+
return None, None
|
|
187
|
+
prev_root: dict | list = namespace
|
|
188
|
+
name: str | int = ""
|
|
189
|
+
for el in atoms:
|
|
190
|
+
prev_root = root_obj
|
|
191
|
+
target, maker, name = el
|
|
192
|
+
if isinstance(target, (ast.Attribute, ast.Name)):
|
|
193
|
+
root_obj = _create_obj_in(maker, name, root_obj) # type: ignore[arg-type]
|
|
194
|
+
elif isinstance(target, ast.Subscript):
|
|
195
|
+
root_obj = _create_subscript_in(maker, name, root_obj) # type: ignore[arg-type]
|
|
196
|
+
else:
|
|
197
|
+
message = messages.UNEXPECTED_TARGET.format(target=target, el=el)
|
|
198
|
+
raise AscconvParseError(message)
|
|
199
|
+
if not isinstance(root_obj, maker):
|
|
200
|
+
message = messages.BAD_ASCCONV_TYPE.format(el=el, maker=maker, expected_type=type(root_obj))
|
|
201
|
+
raise AscconvParseError(message)
|
|
202
|
+
return prev_root, name
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _get_value(assign: ast.Assign) -> int | float | str:
|
|
206
|
+
value = assign.value
|
|
207
|
+
if isinstance(value, ast.Num):
|
|
208
|
+
return value.n # type: ignore[return-value]
|
|
209
|
+
if isinstance(value, ast.Str):
|
|
210
|
+
return value.s # type: ignore[return-value]
|
|
211
|
+
if isinstance(value, ast.UnaryOp) and isinstance(value.op, ast.USub):
|
|
212
|
+
return -value.operand.n # type: ignore[attr-defined,no-any-return]
|
|
213
|
+
message = messages.UNEXPECTED_RHS.format(value=value)
|
|
214
|
+
raise AscconvParseError(message)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def parse_ascconv_text(content: str, delimiter: str = '"') -> dict:
|
|
218
|
+
"""
|
|
219
|
+
Parse ASCCONV text format from `content` string.
|
|
220
|
+
|
|
221
|
+
Parameters
|
|
222
|
+
----------
|
|
223
|
+
content : str
|
|
224
|
+
The string we are parsing
|
|
225
|
+
delimiter : str
|
|
226
|
+
String delimiter, typically '"' or '""'
|
|
227
|
+
|
|
228
|
+
Returns
|
|
229
|
+
-------
|
|
230
|
+
prot_dict : dict
|
|
231
|
+
Meta data pulled from the ASCCONV section
|
|
232
|
+
|
|
233
|
+
Raises
|
|
234
|
+
------
|
|
235
|
+
AsconvParseError
|
|
236
|
+
A line of the ASCCONV section could not be parsed
|
|
237
|
+
"""
|
|
238
|
+
# Normalize string start / end markers to something Python understands
|
|
239
|
+
content = content.replace(delimiter, '"""').replace("\\", "\\\\")
|
|
240
|
+
# Invalid digit identifiers to list
|
|
241
|
+
content = TERMINAL_DIGIT_RE.sub(r"\1[\2]\3", content)
|
|
242
|
+
# Use Python's own parser to parse modified ASCCONV assignments
|
|
243
|
+
tree = ast.parse(content)
|
|
244
|
+
|
|
245
|
+
prot_dict: dict = {}
|
|
246
|
+
for stmt in tree.body:
|
|
247
|
+
if not isinstance(stmt, ast.Assign):
|
|
248
|
+
continue
|
|
249
|
+
atoms = assign_to_atoms(stmt)
|
|
250
|
+
obj_to_index, key = obj_from_atoms(atoms, prot_dict)
|
|
251
|
+
if obj_to_index is not None and key is not None: # None if obj_from_atoms rejected atoms.
|
|
252
|
+
obj_to_index[key] = _get_value(stmt) # type: ignore[index]
|
|
253
|
+
return prot_dict
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def parse_ascconv(ascconv_str: str, delimiter: str = '"') -> tuple[dict, dict[str, str]]:
|
|
257
|
+
"""
|
|
258
|
+
Extract and parse the ASCCONV format from `ascconv_str`.
|
|
259
|
+
|
|
260
|
+
Parameters
|
|
261
|
+
----------
|
|
262
|
+
ascconv_str : str
|
|
263
|
+
The string we are parsing
|
|
264
|
+
delimiter : str, optional
|
|
265
|
+
String delimiter. Typically '"' or '""'
|
|
266
|
+
|
|
267
|
+
Returns
|
|
268
|
+
-------
|
|
269
|
+
prot_dict : dict
|
|
270
|
+
Meta data pulled from the ASCCONV section
|
|
271
|
+
attrs : dict
|
|
272
|
+
Any attributes stored in the 'ASCCONV BEGIN' line
|
|
273
|
+
|
|
274
|
+
Raises
|
|
275
|
+
------
|
|
276
|
+
AsconvParseError
|
|
277
|
+
A line of the ASCCONV section could not be parsed
|
|
278
|
+
"""
|
|
279
|
+
match = ASCCONV_RE.search(ascconv_str)
|
|
280
|
+
if match is None:
|
|
281
|
+
message = "No ASCCONV section found"
|
|
282
|
+
raise AscconvParseError(message)
|
|
283
|
+
attrs, content = match.groups()
|
|
284
|
+
attrs = dict(cast(tuple[str, str], tuple(x.split("="))) for x in attrs.split())
|
|
285
|
+
return parse_ascconv_text(content, delimiter), attrs
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Definition of the :class:`CsaAsciiHeader`.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from csa_header.ascii.ascconv import parse_ascconv
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class CsaAsciiHeader:
|
|
11
|
+
"""
|
|
12
|
+
Represents and handles the parsing of
|
|
13
|
+
`CSA header <https://nipy.org/nibabel/dicom/siemens_csa.html>`_ values
|
|
14
|
+
returned by `pydicom <https://github.com/pydicom/pydicom>`_ as bytes.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
__slots__ = ('_header', '_parsed')
|
|
18
|
+
|
|
19
|
+
#: The header's ASCII-based character encoding.
|
|
20
|
+
ENCODING = "ISO-8859-1"
|
|
21
|
+
|
|
22
|
+
def __init__(self, header: str | bytes):
|
|
23
|
+
"""
|
|
24
|
+
Decodes the header and sets empty property caches to be overriden on
|
|
25
|
+
request.
|
|
26
|
+
|
|
27
|
+
Parameters
|
|
28
|
+
----------
|
|
29
|
+
header : Union[str, bytes]
|
|
30
|
+
String or bytes containing ASCCONV header information.
|
|
31
|
+
"""
|
|
32
|
+
if isinstance(header, bytes):
|
|
33
|
+
header = header.decode(self.ENCODING)
|
|
34
|
+
self._header = header
|
|
35
|
+
|
|
36
|
+
# Property cache
|
|
37
|
+
self._parsed: dict[str, dict] = {}
|
|
38
|
+
|
|
39
|
+
def parse(self) -> dict:
|
|
40
|
+
"""
|
|
41
|
+
Parses ``ASCCONV`` header values as dict of dicts / list / scalars.
|
|
42
|
+
:class:`~csa_header.ascii.element.CsaAsciiElement`
|
|
43
|
+
instances (or all if left None) as a dictionary.
|
|
44
|
+
|
|
45
|
+
Parameters
|
|
46
|
+
----------
|
|
47
|
+
elements : list, optional
|
|
48
|
+
:class:`~csa_header.ascii.element.CsaAsciiElement`
|
|
49
|
+
instances, by default None
|
|
50
|
+
|
|
51
|
+
Returns
|
|
52
|
+
-------
|
|
53
|
+
dict
|
|
54
|
+
Header information as a dictionary
|
|
55
|
+
"""
|
|
56
|
+
return parse_ascconv(self._header, '""')[0]
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def parsed(self) -> dict:
|
|
60
|
+
"""
|
|
61
|
+
Caches the parsed dictionary as a private attribute.
|
|
62
|
+
|
|
63
|
+
Returns
|
|
64
|
+
-------
|
|
65
|
+
dict
|
|
66
|
+
Header information as dictionary
|
|
67
|
+
"""
|
|
68
|
+
if not self._parsed:
|
|
69
|
+
self._parsed = self.parse()
|
|
70
|
+
return self._parsed
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def n_slices(self) -> int:
|
|
74
|
+
"""
|
|
75
|
+
Returns the number of slices (tiles) in a mosaic.
|
|
76
|
+
|
|
77
|
+
Returns
|
|
78
|
+
-------
|
|
79
|
+
int
|
|
80
|
+
Number of slices encoded as a 2D mosaic
|
|
81
|
+
"""
|
|
82
|
+
return self.parsed["sSliceArray"]["lSize"] # type: ignore[no-any-return]
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Messages for the :mod:`~csa_header.ascii` module.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
AST_N_TARGETS: str = "Invalid number of AST assignment targets! Expected 1, got {n_targets}."
|
|
6
|
+
BAD_ASCCONV_TYPE: str = "Atom {el} has type {maker}, but expecting type {expected_type}"
|
|
7
|
+
UNEXPECTED_LHS: str = "Unexpected LHS element: {target}"
|
|
8
|
+
UNEXPECTED_RHS: str = "Unexpected RHS of assignment: {value}"
|
|
9
|
+
UNEXPECTED_TARGET: str = "Unexpected target {target} in {el}"
|
csa_header/exceptions.py
ADDED
csa_header/header.py
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
"""Definition of the :class:`CsaHeader` class."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from csa_header.ascii import CsaAsciiHeader
|
|
9
|
+
from csa_header.exceptions import CsaReadError
|
|
10
|
+
from csa_header.messages import INVALID_CHECK_BIT, READ_OVERREACH, TOO_MANY_ITEMS
|
|
11
|
+
from csa_header.unpacker import Unpacker
|
|
12
|
+
from csa_header.utils import VR_TO_TYPE, decode_latin1, strip_to_null
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class CsaHeader:
|
|
16
|
+
"""
|
|
17
|
+
Represents a full CSA header data element, i.e. either
|
|
18
|
+
(0029, 1010)/`"CSA Image Header Info"` or (0029, 1020)/`"CSA Series Header
|
|
19
|
+
Info"`, and provides access to the header as a parsed dictionary.
|
|
20
|
+
This implementation is heavily based on `dicom2nifti`_'s code
|
|
21
|
+
(particularly `this module`_).
|
|
22
|
+
|
|
23
|
+
.. _dicom2nifti:
|
|
24
|
+
https://github.com/icometrix/dicom2nifti
|
|
25
|
+
.. _this module:
|
|
26
|
+
https://github.com/icometrix/dicom2nifti/blob/6722420a7673d36437e4358ce3cb2a7c77c91820/dicom2nifti/convert_siemens.py#L342
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
__slots__ = ('raw', 'header_size', '_first_tag_n_items', '_csa_type')
|
|
30
|
+
|
|
31
|
+
CSA_TYPE_1: int = 1
|
|
32
|
+
CSA_TYPE_2: int = 2
|
|
33
|
+
|
|
34
|
+
#: Byte alignment boundary for CSA item values.
|
|
35
|
+
BYTE_ALIGNMENT: int = 4
|
|
36
|
+
|
|
37
|
+
#: Used to determine whether the CSA header is of type 1 or 2.
|
|
38
|
+
TYPE_2_IDENTIFIER: bytes = b"SV10"
|
|
39
|
+
|
|
40
|
+
#: Endian format used to parse the CSA header information (little-endian).
|
|
41
|
+
ENDIAN: str = "<"
|
|
42
|
+
|
|
43
|
+
#: Format string used to unpack a single tag.
|
|
44
|
+
TAG_FORMAT_STRING: str = "64si4s3i"
|
|
45
|
+
|
|
46
|
+
#: Number of tags unpacking format characters (2 unsigned integers).
|
|
47
|
+
PREFIX_FORMAT: str = "2I"
|
|
48
|
+
|
|
49
|
+
#: Item value unpacking format characters (4 integers).
|
|
50
|
+
ITEM_FORMAT: str = "4i"
|
|
51
|
+
|
|
52
|
+
#: Valid values for the CSA element's check bit.
|
|
53
|
+
VALID_CHECK_BIT_VALUES: frozenset[int] = frozenset({77, 205})
|
|
54
|
+
|
|
55
|
+
#: ASCII header tag names.
|
|
56
|
+
ASCII_HEADER_TAGS: frozenset[str] = frozenset({"MrPhoenixProtocol"})
|
|
57
|
+
|
|
58
|
+
def __init__(self, raw: bytes):
|
|
59
|
+
"""
|
|
60
|
+
Initialize a new `CsaHeader` instance.
|
|
61
|
+
|
|
62
|
+
Parameters
|
|
63
|
+
----------
|
|
64
|
+
raw : bytes
|
|
65
|
+
Raw CSA header as read by *pydicom*
|
|
66
|
+
"""
|
|
67
|
+
self.raw = raw
|
|
68
|
+
self.header_size = len(self.raw)
|
|
69
|
+
# Initialize CSA type 1 length fix
|
|
70
|
+
self._first_tag_n_items: int | None = None
|
|
71
|
+
# Cache CSA type at initialization - it never changes for an instance
|
|
72
|
+
self._csa_type = self.check_csa_type()
|
|
73
|
+
|
|
74
|
+
def skip_prefix(self, unpacker: Unpacker) -> None:
|
|
75
|
+
"""
|
|
76
|
+
Skip the CSA type 2 header prefix.
|
|
77
|
+
|
|
78
|
+
See Also
|
|
79
|
+
--------
|
|
80
|
+
* :attr:`TYPE_2_IDENTIFIER`
|
|
81
|
+
|
|
82
|
+
Parameters
|
|
83
|
+
----------
|
|
84
|
+
unpacker : Unpacker
|
|
85
|
+
Stream-like header reader
|
|
86
|
+
"""
|
|
87
|
+
if self.is_type_2:
|
|
88
|
+
prefix_length = len(self.TYPE_2_IDENTIFIER)
|
|
89
|
+
unpacker.pointer = prefix_length
|
|
90
|
+
unpacker.read(prefix_length)
|
|
91
|
+
|
|
92
|
+
def validate_check_bit(self, i_tag: int, value: int) -> None:
|
|
93
|
+
"""
|
|
94
|
+
Validates a single CSA header tag's check-bit.
|
|
95
|
+
|
|
96
|
+
See Also
|
|
97
|
+
--------
|
|
98
|
+
* :attr:`VALID_CHECK_BIT_VALUES`
|
|
99
|
+
|
|
100
|
+
Parameters
|
|
101
|
+
----------
|
|
102
|
+
i_tag : int
|
|
103
|
+
Index of the parsed tag
|
|
104
|
+
value : int
|
|
105
|
+
Check-bit value
|
|
106
|
+
|
|
107
|
+
Raises
|
|
108
|
+
------
|
|
109
|
+
CsaReadError
|
|
110
|
+
Invalid check-bit value
|
|
111
|
+
"""
|
|
112
|
+
if value not in self.VALID_CHECK_BIT_VALUES:
|
|
113
|
+
message = INVALID_CHECK_BIT.format(
|
|
114
|
+
i_tag=i_tag,
|
|
115
|
+
check_bit=value,
|
|
116
|
+
valid_values=self.VALID_CHECK_BIT_VALUES,
|
|
117
|
+
)
|
|
118
|
+
raise CsaReadError(message)
|
|
119
|
+
|
|
120
|
+
def _parse_csa1_item_length(self, unpacker: Unpacker, x0: int) -> tuple[int, bool]:
|
|
121
|
+
"""
|
|
122
|
+
Calculate item length for CSA Type 1 headers.
|
|
123
|
+
|
|
124
|
+
Parameters
|
|
125
|
+
----------
|
|
126
|
+
unpacker : Unpacker
|
|
127
|
+
Stream-like header reader
|
|
128
|
+
x0 : int
|
|
129
|
+
First value from ITEM_FORMAT unpacking
|
|
130
|
+
|
|
131
|
+
Returns
|
|
132
|
+
-------
|
|
133
|
+
tuple[int, bool]
|
|
134
|
+
Item length and whether to break parsing (invalid length)
|
|
135
|
+
"""
|
|
136
|
+
# For CSA Type 1, _first_tag_n_items is set when parsing the first tag
|
|
137
|
+
# It should never be None at this point, but we check for type safety
|
|
138
|
+
if self._first_tag_n_items is None:
|
|
139
|
+
return 0, True # Invalid state, break parsing
|
|
140
|
+
|
|
141
|
+
item_len = x0 - self._first_tag_n_items
|
|
142
|
+
destination = unpacker.pointer + item_len
|
|
143
|
+
negative_length = item_len < 0
|
|
144
|
+
overreach = destination > self.header_size
|
|
145
|
+
should_break = negative_length or overreach
|
|
146
|
+
return item_len, should_break
|
|
147
|
+
|
|
148
|
+
def _parse_csa2_item_length(self, unpacker: Unpacker, x1: int) -> int:
|
|
149
|
+
"""
|
|
150
|
+
Calculate item length for CSA Type 2 headers.
|
|
151
|
+
|
|
152
|
+
Parameters
|
|
153
|
+
----------
|
|
154
|
+
unpacker : Unpacker
|
|
155
|
+
Stream-like header reader
|
|
156
|
+
x1 : int
|
|
157
|
+
Second value from ITEM_FORMAT unpacking
|
|
158
|
+
|
|
159
|
+
Returns
|
|
160
|
+
-------
|
|
161
|
+
int
|
|
162
|
+
Item length
|
|
163
|
+
|
|
164
|
+
Raises
|
|
165
|
+
------
|
|
166
|
+
CsaReadError
|
|
167
|
+
If reading would exceed header size
|
|
168
|
+
"""
|
|
169
|
+
item_len = x1
|
|
170
|
+
destination = unpacker.pointer + item_len
|
|
171
|
+
if destination > self.header_size:
|
|
172
|
+
message = READ_OVERREACH.format(
|
|
173
|
+
destination=destination, max_length=self.header_size, pointer=unpacker.pointer
|
|
174
|
+
)
|
|
175
|
+
raise CsaReadError(message)
|
|
176
|
+
return item_len
|
|
177
|
+
|
|
178
|
+
def parse_items(self, unpacker: Unpacker, n_items: int, vr: str, vm: int) -> Any:
|
|
179
|
+
"""
|
|
180
|
+
Parses a single header element's value.
|
|
181
|
+
|
|
182
|
+
Parameters
|
|
183
|
+
----------
|
|
184
|
+
unpacker : Unpacker
|
|
185
|
+
Stream-like header reader
|
|
186
|
+
n_items : int
|
|
187
|
+
Number of items in this element's value as described in the header
|
|
188
|
+
information
|
|
189
|
+
vr : str
|
|
190
|
+
Value representation
|
|
191
|
+
vm : int
|
|
192
|
+
Value multiplicity
|
|
193
|
+
|
|
194
|
+
Returns
|
|
195
|
+
-------
|
|
196
|
+
Any
|
|
197
|
+
CSA header element value
|
|
198
|
+
|
|
199
|
+
Raises
|
|
200
|
+
------
|
|
201
|
+
CsaReadError
|
|
202
|
+
Invalid element value
|
|
203
|
+
"""
|
|
204
|
+
n_values = vm or n_items
|
|
205
|
+
converter = VR_TO_TYPE.get(vr)
|
|
206
|
+
items: list[Any] = []
|
|
207
|
+
# Cache frequently accessed attributes to avoid repeated lookups in loop
|
|
208
|
+
csa_type = self.csa_type
|
|
209
|
+
byte_alignment = self.BYTE_ALIGNMENT
|
|
210
|
+
|
|
211
|
+
for i_item in range(n_items):
|
|
212
|
+
x0, x1, _, _ = unpacker.unpack(self.ITEM_FORMAT)
|
|
213
|
+
|
|
214
|
+
# Calculate item length based on CSA type
|
|
215
|
+
if csa_type == 1:
|
|
216
|
+
item_len, should_break = self._parse_csa1_item_length(unpacker, x0)
|
|
217
|
+
if should_break:
|
|
218
|
+
if i_item < vm:
|
|
219
|
+
items.append("")
|
|
220
|
+
break
|
|
221
|
+
else: # CSA Type 2
|
|
222
|
+
item_len = self._parse_csa2_item_length(unpacker, x1)
|
|
223
|
+
|
|
224
|
+
if i_item >= n_values:
|
|
225
|
+
if item_len != 0:
|
|
226
|
+
message = TOO_MANY_ITEMS.format(expected=n_values, vm=vm, i_item=i_item)
|
|
227
|
+
raise CsaReadError(message)
|
|
228
|
+
continue
|
|
229
|
+
|
|
230
|
+
item_raw = strip_to_null(unpacker.read(item_len))
|
|
231
|
+
item_str = decode_latin1(item_raw)
|
|
232
|
+
item: float | int | str
|
|
233
|
+
|
|
234
|
+
if converter:
|
|
235
|
+
# We may have fewer real items than are given in
|
|
236
|
+
# n_items, but we don't know how many - assume that
|
|
237
|
+
# we've reached the end when we hit an empty item
|
|
238
|
+
if item_len == 0:
|
|
239
|
+
n_values = i_item
|
|
240
|
+
continue
|
|
241
|
+
item = converter(item_str)
|
|
242
|
+
else:
|
|
243
|
+
item = item_str
|
|
244
|
+
items.append(item)
|
|
245
|
+
|
|
246
|
+
# Align to byte boundary
|
|
247
|
+
remainder = item_len % byte_alignment
|
|
248
|
+
if remainder != 0:
|
|
249
|
+
unpacker.pointer += byte_alignment - remainder
|
|
250
|
+
|
|
251
|
+
if items:
|
|
252
|
+
return items if len(items) > 1 else items.pop()
|
|
253
|
+
|
|
254
|
+
def parse_tag(self, unpacker: Unpacker, i_tag: int) -> dict[str, Any]:
|
|
255
|
+
# 4th element (SyngoDT) seems to be a numeric representation of the
|
|
256
|
+
# datatype, which is already provided as the VR.
|
|
257
|
+
name_raw, vm, vr_raw, _, n_items, check_bit = unpacker.unpack(self.TAG_FORMAT_STRING)
|
|
258
|
+
self.validate_check_bit(i_tag, check_bit)
|
|
259
|
+
name_result = strip_to_null(name_raw)
|
|
260
|
+
vr_result = strip_to_null(vr_raw)
|
|
261
|
+
# strip_to_null returns str when null found, bytes otherwise - ensure we have str
|
|
262
|
+
name = decode_latin1(name_result)
|
|
263
|
+
vr = decode_latin1(vr_result)
|
|
264
|
+
tag: dict[str, Any] = {
|
|
265
|
+
"name": name,
|
|
266
|
+
"index": i_tag,
|
|
267
|
+
"VR": vr,
|
|
268
|
+
"VM": vm,
|
|
269
|
+
}
|
|
270
|
+
# CSA1-specific length modifier
|
|
271
|
+
if i_tag == 1:
|
|
272
|
+
self._first_tag_n_items = n_items
|
|
273
|
+
tag["value"] = self.parse_items(unpacker, n_items, vr, vm)
|
|
274
|
+
if name in self.ASCII_HEADER_TAGS:
|
|
275
|
+
tag["value"] = CsaAsciiHeader(tag["value"]).parse()
|
|
276
|
+
return tag
|
|
277
|
+
|
|
278
|
+
def read(self) -> dict[str, dict[str, Any]]:
|
|
279
|
+
unpacker = Unpacker(self.raw, endian=self.ENDIAN)
|
|
280
|
+
self.skip_prefix(unpacker)
|
|
281
|
+
n_tags, _ = unpacker.unpack(self.PREFIX_FORMAT)
|
|
282
|
+
result: dict[str, dict[str, Any]] = {}
|
|
283
|
+
for i_tag in range(n_tags):
|
|
284
|
+
tag = self.parse_tag(unpacker, i_tag)
|
|
285
|
+
name = tag.pop("name")
|
|
286
|
+
result[name] = tag
|
|
287
|
+
return result
|
|
288
|
+
|
|
289
|
+
def check_csa_type(self) -> int:
|
|
290
|
+
"""
|
|
291
|
+
Checks whether the given CSA header is of type 1 or 2.
|
|
292
|
+
|
|
293
|
+
See Also
|
|
294
|
+
--------
|
|
295
|
+
* :func:`csa_type`
|
|
296
|
+
|
|
297
|
+
Returns
|
|
298
|
+
-------
|
|
299
|
+
int
|
|
300
|
+
CSA header type (1 or 2)
|
|
301
|
+
"""
|
|
302
|
+
is_type_2 = self.raw[:4] == self.TYPE_2_IDENTIFIER
|
|
303
|
+
return self.CSA_TYPE_2 if is_type_2 else self.CSA_TYPE_1
|
|
304
|
+
|
|
305
|
+
@property
|
|
306
|
+
def csa_type(self) -> int:
|
|
307
|
+
"""
|
|
308
|
+
Checks whether the given CSA header is of type 1 or 2.
|
|
309
|
+
|
|
310
|
+
See Also
|
|
311
|
+
--------
|
|
312
|
+
* :func:`check_csa_type`
|
|
313
|
+
|
|
314
|
+
Returns
|
|
315
|
+
-------
|
|
316
|
+
int
|
|
317
|
+
CSA header type (1 or 2)
|
|
318
|
+
"""
|
|
319
|
+
return self._csa_type
|
|
320
|
+
|
|
321
|
+
@property
|
|
322
|
+
def is_type_2(self) -> bool:
|
|
323
|
+
"""
|
|
324
|
+
Returns whether this header if CSA type 2 or not (1).
|
|
325
|
+
|
|
326
|
+
Returns
|
|
327
|
+
-------
|
|
328
|
+
bool
|
|
329
|
+
CSA type 2 or not
|
|
330
|
+
"""
|
|
331
|
+
return self._csa_type == self.CSA_TYPE_2
|
csa_header/messages.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Messages for the :mod:`csa_header` library.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
INVALID_CHECK_BIT: str = (
|
|
6
|
+
"CSA element #{i_tag} has an invalid check bit value: {check_bit}!\n"
|
|
7
|
+
"Valid values are {valid_values}\n"
|
|
8
|
+
"This may indicate a corrupted or invalid CSA header."
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
READ_OVERREACH: str = (
|
|
12
|
+
"Invalid item length! Destination {destination} is beyond the maximal length ({max_length}).\n"
|
|
13
|
+
"This indicates a corrupted CSA header or parsing error at byte position {pointer}."
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
TOO_MANY_ITEMS: str = (
|
|
17
|
+
"Too many items in CSA header element.\n"
|
|
18
|
+
"Expected {expected} items (VM={vm}) but found more non-empty items at index {i_item}.\n"
|
|
19
|
+
"This may indicate a malformed CSA header."
|
|
20
|
+
)
|
csa_header/unpacker.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Based on NiBabel's `nicom` module.
|
|
3
|
+
|
|
4
|
+
References
|
|
5
|
+
----------
|
|
6
|
+
* https://github.com/nipy/nibabel/blob/4703f4d8e32be4cec30e829c2d93ebe54759bb62/nibabel/nicom/structreader.py
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from struct import Struct
|
|
12
|
+
|
|
13
|
+
#: Valid Endian codes.
|
|
14
|
+
ENDIAN_CODES = "@=<>!"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Unpacker:
|
|
18
|
+
"""
|
|
19
|
+
Class to unpack values from buffer object.
|
|
20
|
+
|
|
21
|
+
The buffer object is usually a string. Caches compiled :mod:`struct`
|
|
22
|
+
format strings so that repeated unpacking with the same format
|
|
23
|
+
string should be faster than using ``struct.unpack`` directly.
|
|
24
|
+
|
|
25
|
+
Examples
|
|
26
|
+
--------
|
|
27
|
+
>>> a = b'1234567890'
|
|
28
|
+
>>> upk = Unpacker(a)
|
|
29
|
+
>>> upk.unpack('2s') == (b'12',)
|
|
30
|
+
True
|
|
31
|
+
>>> upk.unpack('2s') == (b'34',)
|
|
32
|
+
True
|
|
33
|
+
>>> upk.ptr
|
|
34
|
+
4
|
|
35
|
+
>>> upk.read(3) == b'567'
|
|
36
|
+
True
|
|
37
|
+
>>> upk.ptr
|
|
38
|
+
7
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
__slots__ = ('buffer', 'pointer', 'endian', '_cache')
|
|
42
|
+
|
|
43
|
+
def __init__(self, buffer: bytes, pointer: int = 0, endian: str | None = None):
|
|
44
|
+
"""
|
|
45
|
+
Initialize unpacker instance.
|
|
46
|
+
|
|
47
|
+
Parameters
|
|
48
|
+
----------
|
|
49
|
+
buffer : bytes
|
|
50
|
+
Object implementing buffer protocol (e.g., bytes)
|
|
51
|
+
pointer : int
|
|
52
|
+
Offset at which to begin reads from `buffer`, default is 0
|
|
53
|
+
endian : str or None
|
|
54
|
+
Endian code to prepend to format, as for ``unpack`` endian
|
|
55
|
+
codes. None (the default) corresponds to the default
|
|
56
|
+
behavior of ``struct`` - assuming system endian unless you
|
|
57
|
+
specify the byte order specifically in the format string
|
|
58
|
+
passed to ``unpack``
|
|
59
|
+
"""
|
|
60
|
+
self.buffer = buffer
|
|
61
|
+
self.pointer = pointer
|
|
62
|
+
self.endian = endian
|
|
63
|
+
self._cache: dict[str, Struct] = {}
|
|
64
|
+
|
|
65
|
+
def unpack(self, format_string: str) -> tuple:
|
|
66
|
+
"""
|
|
67
|
+
Unpack values from contained buffer.
|
|
68
|
+
|
|
69
|
+
Unpacks values from ``self.buffer`` and updates ``self.pointer`` to the
|
|
70
|
+
position after the read data.
|
|
71
|
+
|
|
72
|
+
Parameters
|
|
73
|
+
----------
|
|
74
|
+
format_string : str
|
|
75
|
+
Format string as for ``unpack``
|
|
76
|
+
|
|
77
|
+
Returns
|
|
78
|
+
-------
|
|
79
|
+
values : tuple
|
|
80
|
+
Values as unpacked from ``self.buffer`` according to `format_string`
|
|
81
|
+
"""
|
|
82
|
+
# Try and get a struct corresponding to the format string from
|
|
83
|
+
# the cache.
|
|
84
|
+
packed_struct = self._cache.get(format_string)
|
|
85
|
+
if packed_struct is None: # struct not in cache
|
|
86
|
+
# if we've not got a default endian, or the format has an
|
|
87
|
+
# explicit endianness, then we make a new struct directly
|
|
88
|
+
# from the format string
|
|
89
|
+
if self.endian is None or format_string[0] in ENDIAN_CODES:
|
|
90
|
+
packed_struct = Struct(format_string)
|
|
91
|
+
else: # we're going to modify the endianness with our
|
|
92
|
+
# default.
|
|
93
|
+
endian_format_string = self.endian + format_string
|
|
94
|
+
packed_struct = Struct(endian_format_string)
|
|
95
|
+
# add an entry in the cache for the modified format
|
|
96
|
+
# string as well as (below) the unmodified format
|
|
97
|
+
# string, in case we get a format string with the same
|
|
98
|
+
# endianness as default, but specified explicitly.
|
|
99
|
+
self._cache[endian_format_string] = packed_struct
|
|
100
|
+
self._cache[format_string] = packed_struct
|
|
101
|
+
values = packed_struct.unpack_from(self.buffer, self.pointer)
|
|
102
|
+
self.pointer += packed_struct.size
|
|
103
|
+
return values
|
|
104
|
+
|
|
105
|
+
def read(self, n_bytes: int = -1) -> bytes:
|
|
106
|
+
"""
|
|
107
|
+
Return byte string of length `n_bytes` at current position.
|
|
108
|
+
|
|
109
|
+
Returns sub-string from ``self.buffer`` and updates ``self.pointer`` to the
|
|
110
|
+
position after the read data.
|
|
111
|
+
|
|
112
|
+
Parameters
|
|
113
|
+
----------
|
|
114
|
+
n_bytes : int, optional
|
|
115
|
+
Number of bytes to read. Can be -1 (the default) in which
|
|
116
|
+
case we return all the remaining bytes in ``self.buffer``
|
|
117
|
+
|
|
118
|
+
Returns
|
|
119
|
+
-------
|
|
120
|
+
s : byte string
|
|
121
|
+
"""
|
|
122
|
+
start = self.pointer
|
|
123
|
+
end = len(self.buffer) if n_bytes == -1 else start + n_bytes
|
|
124
|
+
self.pointer = end
|
|
125
|
+
return self.buffer[start:end]
|
csa_header/utils.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Utilities for the :mod:`csa_header` library.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
# DICOM VR code to Python type
|
|
8
|
+
VR_TO_TYPE: dict[str, type[float] | type[int]] = {
|
|
9
|
+
"FL": float, # float
|
|
10
|
+
"FD": float, # double
|
|
11
|
+
"DS": float, # decimal string
|
|
12
|
+
"SS": int, # signed short
|
|
13
|
+
"US": int, # unsigned short
|
|
14
|
+
"SL": int, # signed long
|
|
15
|
+
"UL": int, # unsigned long
|
|
16
|
+
"IS": int, # integer string
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
ENCODING: str = "latin-1"
|
|
20
|
+
NULL: bytes = b"\x00"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def strip_to_null(string: bytes) -> bytes | str:
|
|
24
|
+
"""
|
|
25
|
+
Strip string to first null.
|
|
26
|
+
|
|
27
|
+
Parameters
|
|
28
|
+
----------
|
|
29
|
+
s : bytes
|
|
30
|
+
|
|
31
|
+
Returns
|
|
32
|
+
-------
|
|
33
|
+
sdash : str
|
|
34
|
+
s stripped to first occurrence of null (0)
|
|
35
|
+
"""
|
|
36
|
+
zero_position = string.find(NULL)
|
|
37
|
+
if zero_position == -1:
|
|
38
|
+
return string
|
|
39
|
+
return string[:zero_position].decode(ENCODING)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def decode_latin1(value: bytes | str) -> str:
|
|
43
|
+
"""
|
|
44
|
+
Decode bytes to string using latin-1 encoding if necessary.
|
|
45
|
+
|
|
46
|
+
Parameters
|
|
47
|
+
----------
|
|
48
|
+
value : bytes | str
|
|
49
|
+
Value to decode (if bytes) or return as-is (if already str)
|
|
50
|
+
|
|
51
|
+
Returns
|
|
52
|
+
-------
|
|
53
|
+
str
|
|
54
|
+
Decoded string value
|
|
55
|
+
"""
|
|
56
|
+
return value if isinstance(value, str) else value.decode(ENCODING)
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: csa_header
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Parse Siemens CSA header information
|
|
5
|
+
Project-URL: Documentation, https://github.com/open-dicom/csa_header#readme
|
|
6
|
+
Project-URL: Issues, https://github.com/open-dicom/csa_header/issues
|
|
7
|
+
Project-URL: Source, https://github.com/open-dicom/csa_header
|
|
8
|
+
Author-email: Zvi Baratz <z.baratz@gmail.com>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE.txt
|
|
11
|
+
Keywords: CSA,DICOM,MRI,Siemens,metadata
|
|
12
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
13
|
+
Classifier: Programming Language :: Python
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
20
|
+
Requires-Python: >=3.9
|
|
21
|
+
Requires-Dist: numpy>=1.20.0
|
|
22
|
+
Requires-Dist: pydicom<4.0,>=2.2.0
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: ipython; extra == 'dev'
|
|
25
|
+
Requires-Dist: pre-commit; extra == 'dev'
|
|
26
|
+
Provides-Extra: examples
|
|
27
|
+
Requires-Dist: nibabel>=3.0.0; extra == 'examples'
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
# CSA Header
|
|
31
|
+
|
|
32
|
+
Parse CSA header information from Siemens MRI acquisitions with Python.
|
|
33
|
+
|
|
34
|
+
[](https://pypi.org/project/csa_header)
|
|
35
|
+
[](https://pypi.org/project/csa_header)
|
|
36
|
+
[](https://github.com/open-dicom/csa_header/actions/workflows/tests.yml)
|
|
37
|
+
[](https://codecov.io/gh/open-dicom/csa_header)
|
|
38
|
+
[](https://results.pre-commit.ci/latest/github/open-dicom/csa_header/main)
|
|
39
|
+
[](https://opensource.org/licenses/MIT)
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
Some Siemens MRI scans may include CSA headers that provide valuable information about the acquisition and storage of the data. These headers are stored as [private data elements](https://dicom.nema.org/medical/dicom/current/output/html/part05.html#sect_7.8), usually looking something like:
|
|
44
|
+
|
|
45
|
+
```
|
|
46
|
+
(0029, 1010) CSA Image Header Type OB: 'IMAGE NUM 4'
|
|
47
|
+
(0029, 1010) CSA Image Header Version OB: '20100114'
|
|
48
|
+
(0029, 1010) CSA Image Header Info OB: Array of 11560 bytes
|
|
49
|
+
(0029, 1020) CSA Series Header Type OB: 'MR'
|
|
50
|
+
(0029, 1020) CSA Series Header Version OB: '20100114'
|
|
51
|
+
(0029, 1020) CSA Series Header Info OB: Array of 80248 bytes
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
The _CSA Image Header Info_ and _CSA Series Header Info_ elements contain encoded information which is crucial for the correct interpretation of the associated acquisition data.
|
|
55
|
+
|
|
56
|
+
> For a detailed explanation on the CSA encoding scheme, please see [this](https://nipy.org/nibabel/dicom/siemens_csa.html) excellent article from [NiBabel](https://github.com/nipy/nibabel)'s documentation site.
|
|
57
|
+
|
|
58
|
+
## Features
|
|
59
|
+
|
|
60
|
+
- **Fast and Lightweight**: Minimal dependencies (numpy, pydicom)
|
|
61
|
+
- **Comprehensive Parsing**: Supports both CSA header types (Type 1 and Type 2)
|
|
62
|
+
- **ASCCONV Support**: Automatic parsing of embedded ASCCONV protocol parameters
|
|
63
|
+
- **Type-Safe**: Complete type hints for all public APIs
|
|
64
|
+
- **Well-Tested**: 96% test coverage with 161 tests
|
|
65
|
+
- **Python 3.9+**: Modern Python with support through Python 3.13
|
|
66
|
+
- **NiBabel Compatible**: Integrates seamlessly with neuroimaging workflows
|
|
67
|
+
|
|
68
|
+
**Table of Contents**
|
|
69
|
+
|
|
70
|
+
- [Features](#features)
|
|
71
|
+
- [Installation](#installation)
|
|
72
|
+
- [Quickstart](#quickstart)
|
|
73
|
+
- [Advanced Usage](#advanced-usage)
|
|
74
|
+
- [Extracting ASCCONV Protocol](#extracting-ascconv-protocol)
|
|
75
|
+
- [Diffusion MRI (DWI) Parameters](#diffusion-mri-dwi-parameters)
|
|
76
|
+
- [Functional MRI (fMRI) Parameters](#functional-mri-fmri-parameters)
|
|
77
|
+
- [Integration with NiBabel](#integration-with-nibabel)
|
|
78
|
+
- [Examples](#examples)
|
|
79
|
+
- [Tests](#tests)
|
|
80
|
+
- [Contributing](#contributing)
|
|
81
|
+
- [License](#license)
|
|
82
|
+
|
|
83
|
+
## Installation
|
|
84
|
+
|
|
85
|
+
```console
|
|
86
|
+
pip install csa_header
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### Optional Dependencies
|
|
90
|
+
|
|
91
|
+
For working with the provided [NiBabel integration examples](#integration-with-nibabel):
|
|
92
|
+
|
|
93
|
+
```console
|
|
94
|
+
pip install csa_header[examples]
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
For development (includes pre-commit hooks and IPython):
|
|
98
|
+
|
|
99
|
+
```console
|
|
100
|
+
pip install csa_header[dev]
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Quickstart
|
|
104
|
+
|
|
105
|
+
Use [`pydicom`](https://github.com/pydicom/pydicom) to read a DICOM header:
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
>>> import pydicom
|
|
109
|
+
>>> dcm = pydicom.dcmread("/path/to/file.dcm")
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Extract a data element containing a CSA header, e.g., for _CSA Series Header Info_:
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
>>> data_element = dcm.get((0x29, 0x1020))
|
|
116
|
+
>>> data_element
|
|
117
|
+
(0029, 1020) [CSA Series Header Info] OB: Array of 180076 elements
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Read the raw byte array from the data element:
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
>>> raw_csa = data_element.value
|
|
124
|
+
>>> raw_csa
|
|
125
|
+
b'SV10\x04\x03\x02\x01O\x00\x00\x00M\x00\x00\x00UsedPatientWeight\x00 <Visible> "true" \n \n <ParamStr\x01\x00\x00\x00IS\x00\x00\x06...'
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
Parse the contents of the CSA header with the `CsaHeader` class:
|
|
129
|
+
|
|
130
|
+
```python
|
|
131
|
+
>>> from csa_header import CsaHeader
|
|
132
|
+
>>> parsed_csa = CsaHeader(raw_csa).read()
|
|
133
|
+
>>> parsed_csa
|
|
134
|
+
{
|
|
135
|
+
'NumberOfPrescans': {'index': 1, 'VR': 'IS', 'VM': 1, 'value': 0},
|
|
136
|
+
'TransmitterCalibration': {'index': 2, 'VR': 'DS', 'VM': 1, 'value': 247.102},
|
|
137
|
+
'PhaseGradientAmplitude': {'index': 3, 'VR': 'DS', 'VM': 1, 'value': 0.0},
|
|
138
|
+
'ReadoutGradientAmplitude': {'index': 4, 'VR': 'DS', 'VM': 1, 'value': 0.0},
|
|
139
|
+
'SelectionGradientAmplitude': {'index': 5, 'VR': 'DS', 'VM': 1, 'value': 0.0},
|
|
140
|
+
'GradientDelayTime': {'index': 6,
|
|
141
|
+
'VR': 'DS',
|
|
142
|
+
'VM': 3,
|
|
143
|
+
'value': [36.0, 35.0, 31.0]},
|
|
144
|
+
'RfWatchdogMask': {'index': 7, 'VR': 'IS', 'VM': 1, 'value': 0},
|
|
145
|
+
'RfPowerErrorIndicator': {'index': 8, 'VR': 'DS', 'VM': 1, 'value': None},
|
|
146
|
+
'SarWholeBody': {'index': 9, 'VR': 'DS', 'VM': 3, 'value': None},
|
|
147
|
+
'Sed': {'index': 10,
|
|
148
|
+
'VR': 'DS',
|
|
149
|
+
'VM': 3,
|
|
150
|
+
'value': [1000000.0, 324.74800987, 324.74800832]}
|
|
151
|
+
...
|
|
152
|
+
}
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
## Advanced Usage
|
|
156
|
+
|
|
157
|
+
### Extracting ASCCONV Protocol
|
|
158
|
+
|
|
159
|
+
CSA headers often contain the complete scanner protocol in ASCCONV format under the `MrPhoenixProtocol` tag. This is automatically parsed into a nested dictionary:
|
|
160
|
+
|
|
161
|
+
```python
|
|
162
|
+
>>> parsed_csa = CsaHeader(raw_csa).read()
|
|
163
|
+
>>> protocol = parsed_csa.get('MrPhoenixProtocol')
|
|
164
|
+
>>> if protocol:
|
|
165
|
+
... # Access protocol parameters
|
|
166
|
+
... tr = protocol['alTR'][0] # Repetition time
|
|
167
|
+
... te = protocol['alTE'][0] # Echo time
|
|
168
|
+
... print(f"TR: {tr} ms, TE: {te} ms")
|
|
169
|
+
TR: 2000 ms, TE: 30 ms
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
### Diffusion MRI (DWI) Parameters
|
|
173
|
+
|
|
174
|
+
Extract diffusion-specific parameters for DTI/DWI analysis:
|
|
175
|
+
|
|
176
|
+
```python
|
|
177
|
+
>>> # From image header (0x0029, 0x1020)
|
|
178
|
+
>>> image_header = CsaHeader(dcm[0x0029, 0x1020].value).read()
|
|
179
|
+
>>> b_value = image_header.get('B_value')
|
|
180
|
+
>>> gradient = image_header.get('DiffusionGradientDirection')
|
|
181
|
+
>>> print(f"B-value: {b_value}, Gradient: {gradient}")
|
|
182
|
+
B-value: 1000, Gradient: [0.707, 0.707, 0.0]
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
### Functional MRI (fMRI) Parameters
|
|
186
|
+
|
|
187
|
+
Extract slice timing for slice timing correction:
|
|
188
|
+
|
|
189
|
+
```python
|
|
190
|
+
>>> # From series header (0x0029, 0x1010)
|
|
191
|
+
>>> series_header = CsaHeader(dcm[0x0029, 0x1010].value).read()
|
|
192
|
+
>>> slice_times = series_header.get('MosaicRefAcqTimes')
|
|
193
|
+
>>> n_slices = series_header.get('NumberOfImagesInMosaic')
|
|
194
|
+
>>> print(f"Slice times: {slice_times[:3]}... ({n_slices} slices)")
|
|
195
|
+
Slice times: [0.0, 52.5, 105.0]... (64 slices)
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
## Integration with NiBabel
|
|
199
|
+
|
|
200
|
+
`csa_header` works seamlessly with [NiBabel](https://nipy.org/nibabel/) for comprehensive neuroimaging workflows:
|
|
201
|
+
|
|
202
|
+
```python
|
|
203
|
+
import nibabel as nib
|
|
204
|
+
import pydicom
|
|
205
|
+
from csa_header import CsaHeader
|
|
206
|
+
|
|
207
|
+
# Load DICOM with both pydicom and NiBabel
|
|
208
|
+
dcm = pydicom.dcmread('scan.dcm')
|
|
209
|
+
nib_img = nib.load('scan.dcm')
|
|
210
|
+
|
|
211
|
+
# Extract CSA header information
|
|
212
|
+
if (0x0029, 0x1010) in dcm:
|
|
213
|
+
csa = CsaHeader(dcm[0x0029, 0x1010].value)
|
|
214
|
+
csa_info = csa.read()
|
|
215
|
+
|
|
216
|
+
# Use NiBabel for image data
|
|
217
|
+
data = nib_img.get_fdata()
|
|
218
|
+
|
|
219
|
+
# Use CSA for metadata
|
|
220
|
+
slice_times = csa_info.get('MosaicRefAcqTimes', [])
|
|
221
|
+
|
|
222
|
+
print(f"Image shape: {data.shape}")
|
|
223
|
+
print(f"Slice timing from CSA: {len(slice_times)} time points")
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
### Use Cases with NiBabel
|
|
227
|
+
|
|
228
|
+
- **Slice Timing Correction**: Extract `MosaicRefAcqTimes` for accurate fMRI preprocessing
|
|
229
|
+
- **Diffusion Imaging**: Get b-values and gradient directions for DTI analysis
|
|
230
|
+
- **Protocol Verification**: Confirm acquisition parameters match expected values
|
|
231
|
+
- **Quality Assurance**: Extract technical parameters for QA pipelines
|
|
232
|
+
- **BIDS Conversion**: Generate complete metadata for BIDS-compliant datasets
|
|
233
|
+
|
|
234
|
+
See [examples/nibabel_integration.py](examples/nibabel_integration.py) for complete integration examples.
|
|
235
|
+
|
|
236
|
+
## Examples
|
|
237
|
+
|
|
238
|
+
The [examples/](examples/) directory contains comprehensive usage examples:
|
|
239
|
+
|
|
240
|
+
- **[nibabel_integration.py](examples/nibabel_integration.py)**: Complete workflow combining csa_header with NiBabel
|
|
241
|
+
- Extract DWI parameters (b-values, gradients)
|
|
242
|
+
- Extract fMRI parameters (slice timing, TR/TE)
|
|
243
|
+
- Parse ASCCONV protocol parameters
|
|
244
|
+
- Batch processing multiple DICOM files
|
|
245
|
+
|
|
246
|
+
Run examples:
|
|
247
|
+
```bash
|
|
248
|
+
python examples/nibabel_integration.py path/to/siemens_dicom.dcm
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
## Tests
|
|
252
|
+
|
|
253
|
+
This package uses [`hatch`](https://hatch.pypa.io/) to manage development and packaging. To run the tests, simply run:
|
|
254
|
+
|
|
255
|
+
```
|
|
256
|
+
hatch run test
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
### Coverage
|
|
260
|
+
|
|
261
|
+
To run the tests with [`coverage`](https://coverage.readthedocs.io/), run:
|
|
262
|
+
|
|
263
|
+
```
|
|
264
|
+
hatch run cov
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
Or, to automatically generate an HTML report and open it in your default browser:
|
|
268
|
+
|
|
269
|
+
```hatch
|
|
270
|
+
hatch run cov-show
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
## Contributing
|
|
274
|
+
|
|
275
|
+
Contributions are welcome! This project is community-maintained and aims to be a reliable tool for the medical imaging community.
|
|
276
|
+
|
|
277
|
+
### How to Contribute
|
|
278
|
+
|
|
279
|
+
1. **Report Issues**: Found a bug or have a feature request? [Open an issue](https://github.com/open-dicom/csa_header/issues/new/choose)
|
|
280
|
+
2. **Submit Pull Requests**: See [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines
|
|
281
|
+
3. **Improve Documentation**: Help make the docs better
|
|
282
|
+
4. **Share Examples**: Contribute integration examples or use cases
|
|
283
|
+
|
|
284
|
+
### Development Setup
|
|
285
|
+
|
|
286
|
+
```bash
|
|
287
|
+
# Clone the repository
|
|
288
|
+
git clone https://github.com/open-dicom/csa_header.git
|
|
289
|
+
cd csa_header
|
|
290
|
+
|
|
291
|
+
# Install hatch
|
|
292
|
+
pip install hatch
|
|
293
|
+
|
|
294
|
+
# Run tests
|
|
295
|
+
hatch run test:test
|
|
296
|
+
|
|
297
|
+
# Run linting
|
|
298
|
+
hatch run lint:all
|
|
299
|
+
|
|
300
|
+
# Install pre-commit hooks
|
|
301
|
+
hatch run pre-commit install
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for complete development guidelines including:
|
|
305
|
+
- Code style requirements
|
|
306
|
+
- Testing requirements (90%+ coverage)
|
|
307
|
+
- Commit message conventions
|
|
308
|
+
- Pull request process
|
|
309
|
+
|
|
310
|
+
## License
|
|
311
|
+
|
|
312
|
+
`csa_header` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html) license.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
csa_header/__about__.py,sha256=XE96PktL1NN2fiqPdXFudMMouSJ4ZkSQ4koqYR0WulE,126
|
|
2
|
+
csa_header/__init__.py,sha256=VhygT9pIiR0oZWWPuq1-Clyl-OWmhZp3amQxFMDMg1M,457
|
|
3
|
+
csa_header/exceptions.py,sha256=AGX8UZAfl1HgujoggTM09XVR9I3qOVHBPgqu0cr8NaE,77
|
|
4
|
+
csa_header/header.py,sha256=VqNpKuCMXCxhpwWLAJ7_57HQeilbNnmawlPFImRsH-s,10406
|
|
5
|
+
csa_header/messages.py,sha256=X611Iw7M82dYL7elxPNYHf0CRjxjumyQOxO9slwj6w8,686
|
|
6
|
+
csa_header/unpacker.py,sha256=Sn3zBcDwtnBBjBS90m39nG0ZhD_TA2YfY6lE8A8MiKM,4153
|
|
7
|
+
csa_header/utils.py,sha256=03bHa2YlNKH7S5OviiGYuabzsrVEdJUDonm_quI0N80,1228
|
|
8
|
+
csa_header/ascii/__init__.py,sha256=dRl7f8gk-vfmwpLEQVKReIlT3pLg88-53nrnepb1qno,81
|
|
9
|
+
csa_header/ascii/ascconv.py,sha256=tp_EASOXZ3posWUGSE96OmVDjLS5XYWLpwKEXh2XflY,10086
|
|
10
|
+
csa_header/ascii/header.py,sha256=c7zrURH0x5Yq4ixOBpcHI3jKWBpex7m1JgQ5ZA4dw_I,2174
|
|
11
|
+
csa_header/ascii/messages.py,sha256=m18XObDQLVOiCOvhy3HxkiZzwHeur0fNZwFY_m8cDWo,423
|
|
12
|
+
csa_header-1.0.0.dist-info/METADATA,sha256=Cy63BBoq22VOjaExO9EFOGK8rwjyINCwMspkfdU8yoI,10791
|
|
13
|
+
csa_header-1.0.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
14
|
+
csa_header-1.0.0.dist-info/licenses/LICENSE.txt,sha256=joN6MPqkUHxiysN_hPwOT7iTmXj8QR4EFXTuXXc1MdA,1096
|
|
15
|
+
csa_header-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023-present Zvi Baratz <z.baratz@gmail.com>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|