Debian Codegraph @

mrcfile/utils.py

raw
1 # Copyright (c) 2016, Science and Technology Facilities Council
2 # This software is distributed under a BSD licence. See LICENSE.txt.
3
4 """
5 utils
6 -----
7
8 Utility functions used by the other modules in the mrcfile package.
9
10 Functions
11 ---------
12
13 * :func:`data_dtype_from_header`: Work out the data :class:`dtype
14 <numpy.dtype>` from an MRC header.
15 * :func:`data_shape_from_header`: Work out the data array shape from an MRC
16 header
17 * :func:`mode_from_dtype`: Convert a :class:`numpy dtype <numpy.dtype>` to an
18 MRC mode number.
19 * :func:`dtype_from_mode`: Convert an MRC mode number to a :class:`numpy dtype
20 <numpy.dtype>`.
21 * :func:`pretty_machine_stamp`: Get a nicely-formatted string from a machine
22 stamp.
23 * :func:`machine_stamp_from_byte_order`: Get a machine stamp from a byte order
24 indicator.
25 * :func:`byte_orders_equal`: Compare two byte order indicators for equal
26 endianness.
27 * :func:`normalise_byte_order`: Convert a byte order indicator to ``<`` or
28 ``>``.
29 * :func:`spacegroup_is_volume_stack`: Identify if a space group number
30 represents a volume stack.
31
32 """
33
34 # Import Python 3 features for future-proofing
35 from __future__ import (absolute_import, division, print_function,
36 unicode_literals)
37
38 import string
39 import sys
40
41 import numpy as np
42
43 from .constants import IMAGE_STACK_SPACEGROUP
44
45
46 def data_dtype_from_header(header):
47 """Return the data dtype indicated by the given header.
48
49 This function calls :func:`dtype_from_mode` to get the basic dtype, and
50 then makes sure that the byte order of the new dtype matches the byte order
51 of the header's ``mode`` field.
52
53 Args:
54 header: An MRC header as a :class:`numpy record array
55 <numpy.recarray>`.
56
57 Returns:
58 The :class:`numpy dtype <numpy.dtype>` object for the data array
59 corresponding to the given header.
60
61 Raises:
62 :exc:`ValueError`: If there is no corresponding dtype for the given
63 mode.
64 """
65 mode = header.mode
66 return dtype_from_mode(mode).newbyteorder(mode.dtype.byteorder)
67
68
69 def data_shape_from_header(header):
70 """Return the data shape indicated by the given header.
71
72 Args:
73 header: An MRC header as a :class:`numpy record array
74 <numpy.recarray>`.
75
76 Returns:
77 The shape tuple for the data array corresponding to the given header.
78 """
79 nx = int(header.nx)
80 ny = int(header.ny)
81 nz = int(header.nz)
82 mz = int(header.mz)
83
84 if spacegroup_is_volume_stack(header.ispg):
85 shape = (nz // mz, mz, ny, nx)
86 elif header.ispg == IMAGE_STACK_SPACEGROUP and nz == 1:
87 # Use a 2D array for a single image
88 shape = (ny, nx)
89 else:
90 shape = (nz, ny, nx)
91
92 return shape
93
94
95 _dtype_to_mode = dict(f2=12, f4=2, i1=0, i2=1, u1=6, u2=6, c8=4)
96
97 def mode_from_dtype(dtype):
98 """Return the MRC mode number corresponding to the given :class:`numpy
99 dtype <numpy.dtype>`.
100
101 The conversion is as follows:
102
103 * float16 -> mode 12
104 * float32 -> mode 2
105 * int8 -> mode 0
106 * int16 -> mode 1
107 * uint8 -> mode 6 (data will be widened to 16 bits in the file)
108 * uint16 -> mode 6
109 * complex64 -> mode 4
110
111 Note that there is no numpy dtype which corresponds to MRC mode 3.
112
113 Args:
114 dtype: A :class:`numpy dtype <numpy.dtype>` object.
115
116 Returns:
117 The MRC mode number.
118
119 Raises:
120 :exc:`ValueError`: If there is no corresponding MRC mode for the given
121 dtype.
122 """
123 kind_and_size = dtype.kind + str(dtype.itemsize)
124 if kind_and_size in _dtype_to_mode:
125 return _dtype_to_mode[kind_and_size]
126 raise ValueError("dtype '{0}' cannot be converted "
127 "to an MRC file mode".format(dtype))
128
129
130 _mode_to_dtype = { 0: np.int8,
131 1: np.int16,
132 2: np.float32,
133 4: np.complex64,
134 6: np.uint16,
135 12: np.float16 }
136
137 def dtype_from_mode(mode):
138 """Return the :class:`numpy dtype <numpy.dtype>` corresponding to the given
139 MRC mode number.
140
141 The mode parameter may be given as a Python scalar, numpy scalar or
142 single-item numpy array.
143
144 The conversion is as follows:
145
146 * mode 0 -> int8
147 * mode 1 -> int16
148 * mode 2 -> float32
149 * mode 4 -> complex64
150 * mode 6 -> uint16
151 * mode 12 -> float16
152
153 Note that modes 3 and 101 are not supported as there is no matching numpy dtype.
154
155 Args:
156 mode: The MRC mode number. This may be given as any type which can be
157 converted to an int, for example a Python scalar (``int`` or
158 ``float``), a numpy scalar or a single-item numpy array.
159
160 Returns:
161 The :class:`numpy dtype <numpy.dtype>` object corresponding to the
162 given mode.
163
164 Raises:
165 :exc:`ValueError`: If there is no corresponding dtype for the given
166 mode, or if ``mode`` is an array and does not contain exactly one
167 item.
168 """
169 if isinstance(mode, np.ndarray):
170 if mode.size != 1:
171 raise ValueError("Mode array should contain exactly one item")
172 mode = mode.item()
173 if mode in _mode_to_dtype:
174 return np.dtype(_mode_to_dtype[mode])
175 else:
176 raise ValueError("Unrecognised mode '{0}'".format(mode))
177
178
179 def pretty_machine_stamp(machst):
180 """Return a human-readable hex string for a machine stamp."""
181 return " ".join("0x{:02x}".format(byte) for byte in machst)
182
183
184 def byte_order_from_machine_stamp(machst):
185 """Return the byte order corresponding to the given machine stamp.
186
187 Args:
188 machst: The machine stamp, as a :class:`bytearray` or a :class:`numpy
189 array <numpy.ndarray>` of bytes.
190
191 Returns:
192 ``<`` if the machine stamp represents little-endian data, or ``>`` if
193 it represents big-endian.
194
195 Raises:
196 :exc:`ValueError`: If the machine stamp is invalid.
197 """
198 if machst[0] == 0x44 and machst[1] in (0x44, 0x41):
199 return '<'
200 elif (machst[0] == 0x11 and machst[1] == 0x11):
201 return '>'
202 else:
203 pretty_bytes = pretty_machine_stamp(machst)
204 raise ValueError("Unrecognised machine stamp: " + pretty_bytes)
205
206
207 _byte_order_to_machine_stamp = {'<': bytearray((0x44, 0x44, 0, 0)),
208 '>': bytearray((0x11, 0x11, 0, 0))}
209
210 def machine_stamp_from_byte_order(byte_order='='):
211 """Return the machine stamp corresponding to the given byte order
212 indicator.
213
214 Args:
215 byte_order: The byte order indicator: one of ``=``, ``<`` or ``>``, as
216 defined and used by numpy dtype objects.
217
218 Returns:
219 The machine stamp which corresponds to the given byte order, as a
220 :class:`bytearray`. This will be either ``(0x44, 0x44, 0, 0)`` for
221 little-endian or ``(0x11, 0x11, 0, 0)`` for big-endian. If the given
222 byte order indicator is ``=``, the native byte order is used.
223
224 Raises:
225 :exc:`ValueError`: If the byte order indicator is unrecognised.
226 """
227 # If byte order is '=', replace it with the system-native order
228 byte_order = normalise_byte_order(byte_order)
229 return _byte_order_to_machine_stamp[byte_order]
230
231 def byte_orders_equal(a, b):
232 """Work out if the byte order indicators represent the same endianness.
233
234 Args:
235 a: The first byte order indicator: one of ``=``, ``<`` or ``>``, as
236 defined and used by :class:`numpy dtype <numpy.dtype>` objects.
237 b: The second byte order indicator.
238
239 Returns:
240 :data:`True` if the byte order indicators represent the same
241 endianness.
242
243 Raises:
244 :exc:`ValueError`: If the byte order indicator is not recognised.
245 """
246 return normalise_byte_order(a) == normalise_byte_order(b)
247
248 def normalise_byte_order(byte_order):
249 """Convert a numpy byte order indicator to one of ``<`` or ``>``.
250
251 Args:
252 byte_order: One of ``=``, ``<`` or ``>``.
253
254 Returns:
255 ``<`` if the byte order indicator represents little-endian data, or
256 ``>`` if it represents big-endian. Therefore on a little-endian
257 machine, ``=`` will be converted to ``<``, but on a big-endian machine
258 it will be converted to ``>``.
259
260 Raises:
261 :exc:`ValueError`: If ``byte_order`` is not one of ``=``, ``<`` or
262 ``>``.
263 """
264 if byte_order not in ('<', '>', '='):
265 raise ValueError("Unrecognised byte order indicator '{0}'"
266 .format(byte_order))
267 if byte_order == '=':
268 return '<' if sys.byteorder == 'little' else '>'
269 return byte_order
270
271 def spacegroup_is_volume_stack(ispg):
272 """Identify if the given space group number represents a volume stack.
273
274 Args:
275 ispg: The space group number, as an integer, numpy scalar or single-
276 element numpy array.
277
278 Returns:
279 :data:`True` if the space group number is in the range 401--630.
280 """
281 return 401 <= ispg <= 630
282
283
284 printable_chars = ' ' + string.ascii_letters + string.digits + string.punctuation
285
286
287 def is_printable_ascii(string_):
288 """Check if a string is entirely composed of printable ASCII characters."""
289 try:
290 # Python 3 version
291 return str.isprintable(string_) and str.isascii(string_)
292 except AttributeError:
293 # Probably Python 2, fall back to checking characters individually
294 try:
295 return all(char in printable_chars for char in string_)
296 except UnicodeDecodeError:
297 return False
298
299
300 def printable_string_from_bytes(bytes_):
301 """Convert bytes into a printable ASCII string by removing non-printable characters.
302 """
303 string_ = bytes.decode(bytes_, encoding='ascii', errors='ignore')
304 if not is_printable_ascii(string_):
305 string_ = "".join(list(s for s in string_ if is_printable_ascii(s)))
306 return string_
307
308
309 def bytes_from_string(string_):
310 """Convert a string to bytes.
311
312 Even though this is a one-liner, the details are tricky to get right so things work
313 properly in both Python 2 and 3. It's broken out as a separate function so it can be
314 thoroughly tested.
315
316 Raises:
317 UnicodeError: If the input contains non-ASCII characters.
318 """
319 return str.encode(str(string_), encoding='ascii', errors='strict')