msr-reader 0.2.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.
msr_reader/__init__.py ADDED
@@ -0,0 +1 @@
1
+ from .obffile import OBFFile
msr_reader/obffile.py ADDED
@@ -0,0 +1,315 @@
1
+ import struct
2
+ from collections import namedtuple
3
+ from zlib import decompress
4
+
5
+ import numpy as np
6
+
7
+ MAXIMAL_NUMBER_OF_DIMENSIONS = 15
8
+ MAGIC_FILE_HEADER = b'OMAS_BF\n\xff\xff'
9
+ MAGIC_STACK_HEADER = b'OMAS_BF_STACK\n\xff\xff'
10
+
11
+ OBFHeader = namedtuple('OBFHeader', ['format_version', 'description', 'first_stack_position', 'metadata_position', 'metadata'])
12
+
13
+ OBFStackHeader = namedtuple('OBFStackHeader',
14
+ ['stack_version', 'size', 'length', 'offset', 'dtype', 'compressed', 'name',
15
+ 'description', 'data_position', 'data_length', 'next_stack_position'])
16
+
17
+ OBFSIFraction = namedtuple('OBFSIFraction', ['numerator', 'denominator'])
18
+ OBFSIUnit = namedtuple('OBFSIUnit', ['meters', 'kilograms', 'seconds', 'amperes', 'kelvin', 'moles',
19
+ 'candela', 'radian', 'steradian', 'scale_factor'])
20
+
21
+ OBFStackFooter = namedtuple('OBFStackFooter', ['size', 'has_col_positions', 'has_col_labels', 'metadata', 'si_value', 'si_dimensions',
22
+ 'flush_positions', 'flush_block_size', 'tag_dictionary', 'stack_end_disk',
23
+ 'min_format_version', 'stack_end_used_disk', 'samples_written', 'num_chunk_positions',
24
+ 'dimension_labels'])
25
+
26
+ StackSizes = namedtuple('StackSizes', ['name', 'sizes', 'dimension_names'])
27
+
28
+ def _read_file_header(fd):
29
+ header_fmt = '<10sLQL'
30
+ magic_header, format_version, first_stack_pos, descr_len = struct.unpack(header_fmt, fd.read(struct.calcsize(header_fmt)))
31
+
32
+ if not magic_header == MAGIC_FILE_HEADER:
33
+ raise ValueError('Can not parse file, no magic header found')
34
+
35
+ descr = fd.read(descr_len).decode('utf-8')
36
+ if format_version > 1:
37
+ (meta_data_position, ) = struct.unpack('<Q', fd.read(struct.calcsize('<Q')))
38
+ fd.seek(meta_data_position)
39
+ metadata = _read_tag_dict(fd)
40
+ else:
41
+ meta_data_position, metadata = None, None
42
+
43
+ return OBFHeader(format_version, descr, first_stack_pos, meta_data_position, metadata)
44
+
45
+
46
+ def _read_stack_header(fd, position):
47
+
48
+ fd.seek(position)
49
+
50
+ stack_header_fmt1 = '<16sLL'
51
+ magic_header, version, rank = struct.unpack(stack_header_fmt1, fd.read(struct.calcsize(stack_header_fmt1)))
52
+
53
+ if not magic_header == MAGIC_STACK_HEADER:
54
+ raise ValueError('Can not parse stack, no magic header found')
55
+
56
+ if version < 5:
57
+ raise ValueError('stack versions <5 not implemented yet')
58
+
59
+ size = struct.unpack(f'<{MAXIMAL_NUMBER_OF_DIMENSIONS}L', fd.read(struct.calcsize(f'<{MAXIMAL_NUMBER_OF_DIMENSIONS}L')))[:rank]
60
+ length = struct.unpack(f'<{MAXIMAL_NUMBER_OF_DIMENSIONS}d', fd.read(struct.calcsize(f'<{MAXIMAL_NUMBER_OF_DIMENSIONS}d')))[:rank]
61
+ offset = struct.unpack(f'<{MAXIMAL_NUMBER_OF_DIMENSIONS}d', fd.read(struct.calcsize(f'<{MAXIMAL_NUMBER_OF_DIMENSIONS}d')))[:rank]
62
+
63
+ stack_header_fmt2 = '<LLLLLQQQ'
64
+ data_type, compression_type, compression_level, name_len, descr_len, _, data_len, next_stack_pos = struct.unpack(stack_header_fmt2, fd.read(struct.calcsize(stack_header_fmt2)))
65
+
66
+ name = fd.read(name_len).decode('utf-8')
67
+ descr = fd.read(descr_len).decode('utf-8')
68
+
69
+ data_pos = fd.tell()
70
+
71
+ return OBFStackHeader(version, size, length, offset, data_type, compression_type>0, name, descr, data_pos, data_len, next_stack_pos)
72
+
73
+ def _parse_dtype(dtype_flags: int):
74
+
75
+ # parse complex flag
76
+ is_complex = (dtype_flags & 0x40000000) > 0
77
+ if is_complex:
78
+ dtype_flags ^= 0x40000000
79
+
80
+ if dtype_flags == 0:
81
+ raise ValueError('automatic data type determination is not supported yet')
82
+ elif dtype_flags == 1:
83
+ dtype, samples_per_pixel = np.uint8, 1
84
+ elif dtype_flags == 2:
85
+ dtype, samples_per_pixel = np.int8, 1
86
+ elif dtype_flags == 4:
87
+ dtype, samples_per_pixel = np.uint16, 1
88
+ elif dtype_flags == 8:
89
+ dtype, samples_per_pixel = np.int16, 1
90
+ elif dtype_flags == 16:
91
+ dtype, samples_per_pixel = np.uint32, 1
92
+ elif dtype_flags == 32:
93
+ dtype, samples_per_pixel = np.int32, 1
94
+ elif dtype_flags == 64:
95
+ dtype, samples_per_pixel = np.float32, 1
96
+ elif dtype_flags == 128:
97
+ dtype, samples_per_pixel = np.float64, 1
98
+ elif dtype_flags == 0x00000400:
99
+ dtype, samples_per_pixel = np.uint8, 3
100
+ elif dtype_flags == 0x00000800:
101
+ dtype, samples_per_pixel = np.uint8, 4
102
+ elif dtype_flags == 0x00001000:
103
+ dtype, samples_per_pixel = np.uint64, 1
104
+ elif dtype_flags == 0x00002000:
105
+ dtype, samples_per_pixel = np.int64, 1
106
+ elif dtype_flags == 0x00010000:
107
+ dtype, samples_per_pixel = np.bool_, 1
108
+ else:
109
+ raise ValueError(f'unknown data type with flag {dtype_flags}')
110
+
111
+ # promote float/double to complex versions, error on other dtypes
112
+ if is_complex and dtype == np.float32:
113
+ dtype = np.complex64
114
+ elif is_complex and dtype == np.float64:
115
+ dtype = np.complex128
116
+ elif is_complex:
117
+ raise ValueError(f'complex data is only supported for float and double.')
118
+
119
+ return dtype, samples_per_pixel
120
+
121
+ def _read_stack(fd, stack_header: OBFStackHeader):
122
+ fd.seek(stack_header.data_position)
123
+ buffer = fd.read(stack_header.data_length)
124
+
125
+ # zlib-decompress if necessary
126
+ if stack_header.compressed:
127
+ buffer = decompress(buffer)
128
+
129
+ dtype, samples_per_pixel = _parse_dtype(stack_header.dtype)
130
+
131
+ return np.frombuffer(buffer, dtype=dtype).reshape(stack_header.size[::-1] + (samples_per_pixel, )).squeeze()
132
+
133
+ def _read_tag_dict(buffer):
134
+ tag_dict = {}
135
+ # Tag dictionary is of form key_length(uint32) key value_length(uint32) value
136
+ # key, value are utf8-encoded strings
137
+ # the end of the tag dictionary is indicated by a 0-valued uint32
138
+ # TODO: check length (stored in footer) to make sure we do not run into infinite loops?
139
+ while True:
140
+ # read key length, if it is zero, we are at the end
141
+ len_key, = struct.unpack('<L', buffer.read(4))
142
+ if len_key == 0:
143
+ break
144
+ key = buffer.read(len_key)
145
+ len_val, = struct.unpack('<L', buffer.read(4))
146
+ val = buffer.read(len_val)
147
+ tag_dict[key.decode('utf8')] = val.decode('utf8')
148
+ return tag_dict
149
+
150
+ def _to_si_unit(unpack_output):
151
+ # unpack output should be 9x2 int32 (numerator, denominator) pairs and one double scale factor
152
+ unit_fractions = [OBFSIFraction(n, d) for n,d in zip(unpack_output[::2], unpack_output[1::2])]
153
+ return OBFSIUnit(*unit_fractions, unpack_output[-1])
154
+
155
+
156
+ def _read_stack_footer(fd, stack_header: OBFStackHeader):
157
+
158
+ fd.seek(stack_header.data_position + stack_header.data_length)
159
+
160
+ (size,) = struct.unpack(f'<L', fd.read(struct.calcsize(f'<L')))
161
+
162
+ has_col_info_fmt = f'<{MAXIMAL_NUMBER_OF_DIMENSIONS}L'
163
+ has_col_positions = struct.unpack(has_col_info_fmt, fd.read(struct.calcsize(has_col_info_fmt)))[:len(stack_header.size)]
164
+ has_col_labels = struct.unpack(has_col_info_fmt, fd.read(struct.calcsize(has_col_info_fmt)))[:len(stack_header.size)]
165
+
166
+ (metadata_length,) = struct.unpack(f'<L', fd.read(struct.calcsize(f'<L')))
167
+
168
+ si_fmt = '<18ld'
169
+ si_value = _to_si_unit(struct.unpack(si_fmt, fd.read(struct.calcsize(si_fmt))))
170
+ si_dimensions = []
171
+ for _ in range(MAXIMAL_NUMBER_OF_DIMENSIONS):
172
+ si_dimensions.append(_to_si_unit(struct.unpack(si_fmt, fd.read(struct.calcsize(si_fmt)))))
173
+
174
+ if stack_header.stack_version > 5:
175
+ stack_footer_fmt = '<QQQQLQQQ'
176
+ unpack_out = struct.unpack(stack_footer_fmt, fd.read(struct.calcsize(stack_footer_fmt)))
177
+ (num_flush_points, flush_block_size, tag_dictionary_length,
178
+ stack_end_disk, min_format_version, stack_end_used_disk, samples_written, num_chunk_positions) = unpack_out
179
+ else:
180
+ stack_footer_fmt = '<QQQQL'
181
+ unpack_out = struct.unpack(stack_footer_fmt, fd.read(struct.calcsize(stack_footer_fmt)))
182
+ (num_flush_points, flush_block_size, tag_dictionary_length,
183
+ stack_end_disk, min_format_version, stack_end_used_disk, samples_written, num_chunk_positions) = unpack_out + (None, None, None)
184
+
185
+ labels = []
186
+ for _ in range(len(stack_header.size)):
187
+ (n,) = struct.unpack(f'<L', fd.read(struct.calcsize(f'<L')))
188
+ (s,) = struct.unpack(f'<{n}s', fd.read(struct.calcsize(f'<{n}s')))
189
+ labels.append(s.decode('utf8'))
190
+
191
+ # TODO: handle col_positions, col_labels, chunked storage
192
+ if any(has_col_labels) or any(has_col_positions):
193
+ raise ValueError('col_label and col_position parsing not implemented yet')
194
+ if num_chunk_positions is not None and num_chunk_positions > 0:
195
+ raise ValueError('chunked storage not implemented yet')
196
+
197
+ metadata = fd.read(metadata_length).decode('utf-8')
198
+
199
+ # FLUSH POSITIONS
200
+ flush_positions = []
201
+ for _ in range(num_flush_points):
202
+ (fp,) = struct.unpack(f'<Q', fd.read(struct.calcsize(f'<Q')))
203
+ flush_positions.append(fp)
204
+
205
+ # tag_dict_buf = BytesIO(fd.read(tag_dictionary_length))
206
+ tag_dict = _read_tag_dict(fd)
207
+
208
+
209
+ return OBFStackFooter(size, has_col_positions, has_col_labels, metadata, si_value, si_dimensions, flush_positions,
210
+ flush_block_size, tag_dict, stack_end_disk, min_format_version, stack_end_used_disk,
211
+ samples_written, num_chunk_positions, labels)
212
+
213
+
214
+ class OBFFile:
215
+
216
+ """
217
+ Pure Python reader for OBF files (basis of Imspector MSR) as described at:
218
+ https://imspectordocs.readthedocs.io/en/latest/fileformat.html
219
+ """
220
+
221
+ def __init__(self, path):
222
+ self.fd = open(path, 'rb')
223
+ self._parse_headers()
224
+ self.stack_names = [s.name for s in self.stack_headers]
225
+
226
+ def _parse_headers(self):
227
+ self.main_header = _read_file_header(self.fd)
228
+ self.stack_headers = []
229
+ self.stack_footers = []
230
+ next_position = self.main_header.first_stack_position
231
+ while next_position > 0:
232
+ stack_header = _read_stack_header(self.fd, next_position)
233
+ self.stack_headers.append(stack_header)
234
+ next_position = stack_header.next_stack_position
235
+
236
+ stack_footer = _read_stack_footer(self.fd, stack_header)
237
+ self.stack_footers.append(stack_footer)
238
+
239
+ def read_stack(self, idx):
240
+ return _read_stack(self.fd, self.stack_headers[idx])
241
+
242
+ @property
243
+ def num_stacks(self):
244
+ return len(self.stack_headers)
245
+
246
+ @property
247
+ def shapes(self):
248
+ shapes = []
249
+ for i in range(self.num_stacks):
250
+ header_i : OBFStackHeader = self.stack_headers[i]
251
+ footer_i : OBFStackFooter = self.stack_footers[i]
252
+
253
+ sizes_stack = []
254
+ dimension_labels = []
255
+ for siz, label in zip(reversed(header_i.size), reversed(footer_i.dimension_labels)):
256
+ if siz > 1:
257
+ sizes_stack.append(siz)
258
+ dimension_labels.append(label)
259
+ shapes.append(StackSizes(header_i.name, sizes_stack, dimension_labels))
260
+ return shapes
261
+
262
+
263
+ @property
264
+ def pixel_sizes(self):
265
+ pixel_sizes = []
266
+ for i in range(self.num_stacks):
267
+ header_i : OBFStackHeader = self.stack_headers[i]
268
+ footer_i : OBFStackFooter = self.stack_footers[i]
269
+
270
+ sizes_stack = []
271
+ dimension_labels = []
272
+ for siz, length, label in zip(reversed(header_i.size), reversed(header_i.length), reversed(footer_i.dimension_labels)):
273
+ if siz > 1:
274
+ sizes_stack.append(length / siz)
275
+ dimension_labels.append(label)
276
+ pixel_sizes.append(StackSizes(header_i.name, sizes_stack, dimension_labels))
277
+ return pixel_sizes
278
+
279
+ def shape(self, stack_idx):
280
+ """
281
+ get size in pixels (array shape) of stack with index stack_idx
282
+ """
283
+ return self.shapes[stack_idx].sizes
284
+
285
+ def pixel_size(self, stack_idx):
286
+ """
287
+ get pixel size (in meters) of stack with index stack_idx
288
+ """
289
+ return self.pixel_sizes[stack_idx].sizes
290
+
291
+ def get_xml_metadata(self, stack_idx):
292
+ """
293
+ get XML metadata string of stack with index stack_idx
294
+ """
295
+
296
+ # get footer of stack_idx
297
+ stack_footer = self.stack_footers[stack_idx]
298
+
299
+ # check if we actually have metadata for our stack (some like rescue_info don't seem to have it)
300
+ # return empty string if no metadata is present
301
+ if 'imspector' in stack_footer.tag_dictionary:
302
+ xml_imspector_metadata = stack_footer.tag_dictionary['imspector']
303
+ else:
304
+ xml_imspector_metadata = ''
305
+
306
+ return xml_imspector_metadata
307
+
308
+ def close(self):
309
+ self.fd.close()
310
+
311
+ def __enter__(self):
312
+ return self
313
+
314
+ def __exit__(self, type, value, traceback):
315
+ self.close()
@@ -0,0 +1,54 @@
1
+ Metadata-Version: 2.3
2
+ Name: msr-reader
3
+ Version: 0.2.0
4
+ Summary: Pure Python reader for MSR/OBF (Imspector) image data
5
+ Project-URL: Homepage, https://github.com/hoerlteam/msr-reader
6
+ Project-URL: Bug Tracker, https://github.com/hoerlteam/msr-reader/issues
7
+ Author-email: David Hörl <hoerldavid@gmail.com>
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Requires-Python: >=3.7
14
+ Requires-Dist: numpy
15
+ Description-Content-Type: text/markdown
16
+
17
+ # msr
18
+
19
+ Pure Python and cross-platform reader for MSR/OBF image files as created by Imspector.
20
+
21
+ Implementation follows the description at: https://imspectordocs.readthedocs.io/en/latest/fileformat.html
22
+
23
+ **WARNING:** Only tested on data from our own Abberior Expert Line STED microscope with a narrow range of Imspector versions.
24
+
25
+ ## Installation
26
+
27
+ ```
28
+ pip install msr-reader
29
+ ```
30
+
31
+ ## Usage
32
+
33
+ ```python
34
+ from msr_reader import OBFFile
35
+ from xml.etree import ElementTree
36
+
37
+ with OBFFile('file_path.msr') as f:
38
+
39
+ # reading image data
40
+ idx = 0
41
+ img = f.read_stack(idx) # read stack with index idx into numpy array
42
+
43
+ # metadata
44
+ stack_shapes = f.shapes # list of stack shapes, including stack and dimension names
45
+ pixel_sizes = f.pixel_sizes # like sizes, but with pixel sizes (unit: meters)
46
+
47
+ # imspector metadata as xml string
48
+ xml_imspector_metadata = f.get_xml_metadata(idx)
49
+
50
+ # can be parsed with ElementTree, for example
51
+ et = ElementTree.fromstring(xml_imspector_metadata)
52
+ # find, e.g. x pixel size in XML
53
+ et.find('doc/ExpControl/scan/range/x/psz').text
54
+ ```
@@ -0,0 +1,6 @@
1
+ msr_reader/__init__.py,sha256=8TYIgPz9LbYZEc6NrF75OJELeifccBM4tKdwsEnhKig,28
2
+ msr_reader/obffile.py,sha256=lprKSJbtV5gedCH5OmpLzCvGS6CG8cGzEaX9txLFjEo,12781
3
+ msr_reader-0.2.0.dist-info/METADATA,sha256=qCSVhwtjfYGErvY0Uy7UEVBVGJjPa6BJOeL7WV2ouuM,1696
4
+ msr_reader-0.2.0.dist-info/WHEEL,sha256=as-1oFTWSeWBgyzh0O_qF439xqBe6AbBgt4MfYe5zwY,87
5
+ msr_reader-0.2.0.dist-info/licenses/LICENSE,sha256=D4f0-E9YKGq3zQjavuI_R0K3Bk2drh5EX5VB-MwYR5U,1059
6
+ msr_reader-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.22.5
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,7 @@
1
+ Copyright 2023 David Hoerl
2
+
3
+ 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:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ 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.