Debian Codegraph @

mrcz/ioDM.py

raw
1 # -*- coding: utf-8 -*-
2
3 from __future__ import division, print_function, absolute_import, unicode_literals
4 import numpy as np
5
6 # Executor for writing compressed blocks to disk
7 try:
8 from concurrent.futures import ThreadPoolExecutor
9 except ImportError as e:
10 if sys.version_info > (3,0):
11 raise ImportError('Get the backport for `concurrent.futures` for Py2.7 as `pip install futures`')
12 raise e
13 from mrcz.__version__ import __version__
14
15 _asyncExecutor = ThreadPoolExecutor(max_workers = 1)
16
17 class DMImage(object):
18 """
19 This structure-like class is for storing 2D image or 3D image stack
20 information, since Digital Micrograph likes to have more than one in a
21 file. Stores Calibrations, Data, and ImageTags.
22
23 The NumPy array reference is stored in `imageData` and the meta-data is
24 stored in a dictionary `imageInfo`.
25 """
26 def __init__( self ):
27 self.imageInfo = {} # Calibrations, tags, all in a dictionary
28 self.shape = [] # necessary for unraveling
29 self.imageData = np.zeros(1)
30
31
32 class readDM4(object):
33 """
34 A fast DM4 file reader to strip the data out of the large movie-mode files
35 generated by K2 detectors along with important tags. Due to the emphasis on
36 speed it's not a general file parser with dynamic allocation, so if Gatan
37 changes the format a lot it will break the script.
38
39 Parameters
40 ----------
41 filename: str
42 the
43 verbose: bool
44 whether to output debugging info or not.
45
46 Example
47 -------
48
49 dm4struct = readDM4( filename, verbose=False)
50
51 dm4struct holds the (multiple) images in the DM4. Typically the zeroth image
52 is the thumbnail. To convert to MRCZ::
53
54 imageData = dm4struct.im[1].imageData
55
56 is a NumPy array containing image intensities::
57
58 imageInfo = dm4struct.im[1].imageInfo
59
60 is a dict containing meta-data.
61
62 Note
63 ----
64
65 Chris Boothroyd provides some information on the structure of .DM4 files here:
66
67 http://www.er-c.org/cbb/info/dmformat/
68
69 The directory structure of the file is tracked by passing the path of the
70 parent to each tag parser. Gatan likes to have empty tag directories, so
71 they are auto-numbered when present.
72
73 One can examine file structure by setting ``verbose=True``, if you need to add
74 some more tags to the dictionary generated by the parseTag function, for example.
75 """
76
77 def __init__(self, filename, verbose=False):
78 self.f = open(filename, 'rb')
79
80 if verbose:
81 print("Opening DM4 file: %s" % filename)
82
83 # Instatiate class fields
84 self._unnamedIndices = np.zeros( 20, dtype='int' ) # maximum number of nested tags
85 self.im = [] # list of DMImage class objects
86 self.verbose = verbose
87
88 # version = struct.unpack( '>I', f.read(4) )
89 version = np.fromfile( self.f, dtype='>i4', count=1 )[0]
90 if( version != 4):
91 print( "Warning: Only DM4 is supported, will probably crash spectacularly" )
92 np.fromfile( self.f, dtype='>i8', count=1 )[0] # rootlen
93 byteord = np.fromfile( self.f, dtype='>i4', count=1 )[0] # 1 = little endian, generally it always is
94 if byteord != 1:
95 print( "Error: only little endian data ordering supported at present" )
96 return
97
98 np.fromfile( self.f, dtype='i1', count=1 )[0] # 1 = sorted
99 np.fromfile( self.f, dtype='i1', count=1 )[0] # 1 = open structure
100 ntags_root = np.fromfile( self.f, dtype='>i8', count=1 )[0] # number of tags
101
102 if self.verbose: print( "DM version %d, byte order %d" %(version, byteord) )
103 # Now the tags start
104 for J in np.arange( 0, ntags_root ):
105
106 tag_type = np.fromfile( self.f, dtype='i1', count=1 )[0] # 20 = tag directory, 21 = tag base, 0 == EOF
107
108 #print( "DEBUG: root tag: %d" % tag_type )
109 if( tag_type == 20 ):
110
111 loc_tagstart = self.f.tell()
112 tag_namelen = np.fromfile( self.f, dtype='>i2', count=1 )[0]
113
114 if tag_namelen > 0:
115 tag_name = self.f.read( tag_namelen )
116 else:
117 tag_name = b""
118
119 tag_fieldlen = np.fromfile( self.f, dtype='>i8', count=1 )[0]
120 #print( "rootTag: tag_name: %s has length %d and field length %d" %(tag_name, tag_namelen, tag_fieldlen ))
121
122 if tag_name == b"ImageList":
123 self.f.seek( loc_tagstart )
124 # So each image is an unnamed tag directory, composed of /ImageData and /ImageTags and /UniqueID
125 self.parseTagDir( b"/" )
126 # We currently do not care about any tag but ImageList
127 break
128 else:
129 # Go to next tag/tagdir
130 self.f.seek( self.f.tell() + tag_fieldlen )
131
132 elif( tag_type == 21 ):
133 # throw away tags in root because we don't care for them
134 self.discardTag()
135 elif( tag_type == 0 ):
136 break # EOF
137 pass
138 self.f.close()
139
140 # Unravel images
141 for mage in self.im:
142 # FYI: Gatan stores image stacks [z,y,x] which is opposite to how they store the dimensions (but is Numpy and C convention)
143 mage.shape = np.flipud( np.array( mage.shape ) )
144 # This y-flip [:,::-1,...] puts us on the same origin-standard for data as MRC
145 # Gatan uses a different standard for the origin location inside DM4 files.
146 mage.imageData = np.reshape( mage.imageData, mage.shape, order='C' )[:,::-1,...]
147 # Image data is now compatible with MRCs saved in GMS, IMOD, EMAN2, etc.
148 # Clean up anything else
149
150 def parseTag( self, parent ):
151 """ Parse a tag at the given file handle location """
152 tag_namelen = np.fromfile( self.f, dtype='>i2', count=1 )[0]
153
154 if tag_namelen > 0:
155 # tag_name = np.fromfile( self.f, dtype='S%d'% tag_namelen, count=1 )[0]
156 tag_name = self.f.read( tag_namelen )
157 else:
158 tag_name = b""
159
160 tag_fieldlen = np.fromfile( self.f, dtype='>i8', count=1 )[0]
161 # print( "parseTag: tag_name: %s has length %d and field length %d" %(tag_name, tag_namelen, tag_fieldlen ))
162 loc_tag = self.f.tell() # Save location so we can seek to end of tag later
163 self.f.read(4) # Throw away %%%% seperator
164 tag_ninfo = np.fromfile( self.f, dtype='>i8', count=1 )[0]
165 if self.verbose:
166 print( "Found tag: %s%s with %d elements" % (parent, tag_name, tag_ninfo) )
167
168 split_tag_name = (parent + tag_name).split( b'/' )
169
170 # Skip ImageList
171
172 imageIndex = np.int64( split_tag_name[2] )
173
174 # Check to see if self.im[imageIndex] exists
175 try:
176 self.im[imageIndex]
177 except IndexError:
178 self.im.append( DMImage() )
179
180 if split_tag_name[3] == b'ImageData':
181 dimCount = 0
182 if split_tag_name[4] == b'Calibrations':
183 # No calibrations saved at present
184 # /ImageList/1/ImageData/Calibrations/Brightness/Origin
185 # /ImageList/1/ImageData/Calibrations/Brightness/Scale
186 # /ImageList/1/ImageData/Calibrations/Brightness/Units
187 # /ImageList/1/ImageData/Calibrations/Dimension/[0-2]/Origin
188 # /ImageList/1/ImageData/Calibrations/Dimension/[0-2]/Scale
189 # /ImageList/1/ImageData/Calibrations/Dimension/[0-2]/Units
190 if split_tag_name[5] == b'Brightness':
191 if split_tag_name[6] == b'Origin':
192 self.im[imageIndex].imageInfo['IntensityOrigin'] = self.retrieveTagData( tag_ninfo )
193 elif split_tag_name[6] == b'Scale':
194 self.im[imageIndex].imageInfo['IntensityScale'] = self.retrieveTagData( tag_ninfo )
195 elif split_tag_name[6] == b'Units':
196 # unicode_array = self.retrieveTagData( f, tag_ninfo )
197 # self.im[imageIndex].imageInfo['IntensityUnits'] = "".join([chr(item) for item in unicode_array])
198 self.im[imageIndex].imageInfo['IntensityUnits'] = self.retrieveTagData( tag_ninfo ).astype(np.uint8).tostring().decode('utf-8')
199
200 elif split_tag_name[5] == b'Dimension':
201 # 0 = x, 1 = y, 2 = z for split_tag_name[6]
202 #print( split_tag_name[6] )
203 #print( np.frombuffer( split_tag_name[6], dtype='>i8' ) )
204 #print( np.frombuffer( split_tag_name[6], dtype='<i8' ) )
205
206 if np.int64( split_tag_name[6] ) == 0:
207 currDim = 'X'
208 elif np.int64( split_tag_name[6] ) == 1:
209 currDim = 'Y'
210 elif np.int64( split_tag_name[6]) == 2:
211 currDim = 'Z'
212 else:
213 raise ValueError( "DM4Import: Unknown dimension " + str(split_tag_name[6]) + " at location " + hex(self.f.tell()) )
214
215 # Units is stored as uint16 array, which is actually unicode?
216 if split_tag_name[7] == b'Origin':
217 self.im[imageIndex].imageInfo['Dim'+currDim+'Origin'] = self.retrieveTagData( tag_ninfo )
218 elif split_tag_name[7] == b'Scale':
219 self.im[imageIndex].imageInfo['Dim'+currDim+'Scale'] = self.retrieveTagData( tag_ninfo )
220 elif split_tag_name[7] == b'Units':
221 # Sometimes we have wierd characters in the Units tag
222 try:
223 self.im[imageIndex].imageInfo['Dim'+currDim+'Units']= self.retrieveTagData( tag_ninfo ).astype(np.int16).tostring().decode('utf-8')
224 except:
225 try:
226 # "ISO-8859-1"
227 # 'windows-1252'
228 self.im[imageIndex].imageInfo['Dim'+currDim+'Units']= self.retrieveTagData( tag_ninfo ).astype(np.int16).tostring().decode("ISO-8859-1")
229 except:
230 pass
231
232 pass
233 elif split_tag_name[4] == b'Data':
234 if self.verbose:
235 print( "Found image %d"%imageIndex + " at offset : " + str(self.f.tell() ) )
236 self.im[imageIndex].imageData = self.retrieveTagData( tag_ninfo)
237 pass
238 elif split_tag_name[4] == b'Dimensions':
239 self.im[imageIndex].shape.append( self.retrieveTagData( tag_ninfo ) )
240 dimCount += 1
241 pass
242 pass
243 elif split_tag_name[3] == b'ImageTags':
244
245 if split_tag_name[4] == b'Acquisition':
246 ### Find image flips ###
247 # Here is where we can save any tags that we care for, like image rotations
248 # /ImageList/1/ImageTags/Acquisition/Frame/Area/Transform/Transform List/0/Transpose/Horizontal Flip
249 if split_tag_name[-1] == b"Horizontal Flip" and split_tag_name[-4] == b'Device':
250 # So annoyingly there are several of these tags, only some of which are the true flips.
251 self.im[imageIndex].imageInfo['HorzFlip'] = self.retrieveTagData( tag_ninfo )
252 elif split_tag_name[-1] == b"Vertical Flip" and split_tag_name[-4] == b'Device':
253 self.im[imageIndex].imageInfo['VertFlip'] = self.retrieveTagData( tag_ninfo )
254 elif split_tag_name[-1] == b"Diagonal Flip" and split_tag_name[-4] == b'Device':
255 self.im[imageIndex].imageInfo['DiagFlip'] = self.retrieveTagData( tag_ninfo )
256
257 # Pixel size seems to be complex, not sure if I'm retrieving it correctly (only important for non-square pixel detectors)
258 elif split_tag_name[-1] == b"Pixel Size (um)" and split_tag_name[-3] == b'Device':
259 self.im[imageIndex].imageInfo['DetectorPixelSize'] = self.retrieveTagData( tag_ninfo )
260 elif split_tag_name[-1] == b"Exposure" and split_tag_name[-2] == b'Detector':
261 self.im[imageIndex].imageInfo['Exposure'] = self.retrieveTagData( tag_ninfo )
262 elif split_tag_name[-1] == b"hbin" and split_tag_name[-2] == b'Detector':
263 self.im[imageIndex].imageInfo['HorzBin'] = self.retrieveTagData( tag_ninfo )
264 elif split_tag_name[-1] == b"vbin" and split_tag_name[-2] == b'Detector':
265 self.im[imageIndex].imageInfo['VertBin'] = self.retrieveTagData( tag_ninfo )
266
267 elif split_tag_name[4] == b'Calibration':
268
269 if split_tag_name[5] == b'Dose Rate':
270 if split_tag_name[6] == b'Calibration':
271 if not 'DoseRateCalibration' in self.im[imageIndex].imageInfo:
272 self.im[imageIndex].imageInfo['DoseRateCalibration'] = []
273
274 try:
275 self.im[imageIndex].imageInfo['DoseRateCalibration'].append( self.retrieveTagData( tag_ninfo ) )
276 except:
277 print( "FAILED TO IMPORT DOSERATECALIBRATION" )
278
279
280 elif split_tag_name[4] == b'Microscope Info':
281 if split_tag_name[5] == b'Actual Magnification':
282 self.im[imageIndex].imageInfo['ActualMag'] = self.retrieveTagData( tag_ninfo )
283 elif split_tag_name[5] == b'Indicated Magnification':
284 self.im[imageIndex].imageInfo['NominalMag'] = self.retrieveTagData( tag_ninfo )
285 elif split_tag_name[5] == b'Cs(mm)':
286 self.im[imageIndex].imageInfo['C3'] = self.retrieveTagData( tag_ninfo )
287 elif split_tag_name[5] == b'Voltage':
288 self.im[imageIndex].imageInfo['Voltage'] = self.retrieveTagData( tag_ninfo )
289 elif split_tag_name[5] == b'Mode':
290 self.im[imageIndex].imageInfo['MicroscopeMode'] = self.retrieveTagData( tag_ninfo ).astype(np.uint8).tostring().decode('ascii')
291 pass
292 elif split_tag_name[4] == b'EELS Spectrometer':
293 if split_tag_name[5] == b'Aperture index':
294 self.im[imageIndex].imageInfo['EELSApertureIndex'] = self.retrieveTagData( tag_ninfo )
295 elif split_tag_name[5] == b'Aperture label':
296 self.im[imageIndex].imageInfo['EELSApertureLabel'] = self.retrieveTagData( tag_ninfo ).astype(np.uint8).tostring().decode('ascii')
297 elif split_tag_name[5] == b'Energy loss (eV)':
298 self.im[imageIndex].imageInfo['EELSEnergyLoss'] = self.retrieveTagData( tag_ninfo )
299 elif split_tag_name[5] == b'Slit inserted':
300 self.im[imageIndex].imageInfo['EELSSlitIn'] = self.retrieveTagData( tag_ninfo )
301 elif split_tag_name[5] == b'Slit width (eV)':
302 self.im[imageIndex].imageInfo['EELSSlitWidth'] = self.retrieveTagData( tag_ninfo )
303 elif split_tag_name[4] == b"Latitude-S":
304 if split_tag_name[5] == b"Distance To Focus Position":
305 self.im[imageIndex].imageInfo['LatSDistanceToFocus'] = self.retrieveTagData( tag_ninfo )
306 elif split_tag_name[5] == b"Intended Defocus":
307 self.im[imageIndex].imageInfo['LatSIntendedDefocus'] = self.retrieveTagData( tag_ninfo )
308 elif split_tag_name[5] == b"Beam Diameter (nm)":
309 self.im[imageIndex].imageInfo['LatSBeamDiameter'] = self.retrieveTagData( tag_ninfo )
310 # Go to next location
311 self.f.seek( loc_tag + tag_fieldlen )
312 return
313
314 def getTagDType( self, bytecode ):
315 if bytecode == 2:
316 return 'int16'
317 elif bytecode == 3:
318 return 'int32'
319 elif bytecode == 4:
320 return 'uint16'
321 elif bytecode == 5:
322 return 'uint32'
323 elif bytecode == 6:
324 return 'float32'
325 elif bytecode == 7:
326 return 'float64'
327 elif bytecode == 8:
328 return 'bool'
329 elif bytecode == 11:
330 return 'int64'
331 else:
332 return ''
333
334 def retrieveTagData( self, tag_ninfo):
335 """ Get the actual data from the tag, which is then stored in one of the dicts or imageData """
336 # Here is basically where we should check tag_name to see if it's important...
337 tag_loc = self.f.tell()
338 tag_infos = np.fromfile( self.f, dtype='>i8', count=tag_ninfo )
339 for K in np.arange(0, tag_infos.size):
340 if tag_infos[K] == 15: # struct
341 # Structs are organized really strangely in the file, they are essentially in the tag header so
342 # our reading doesn't work properly with them. In essence we need to go back to where
343 # we think the struct should be.
344 # print( "Correct struct ??? location: " + str( tag_loc + 8*K + 16 ) )
345 self.f.seek( tag_loc + 8*K + 16 )
346 struct_fieldcount = np.fromfile( self.f, dtype='>i8', count=1 )
347 struct_fielddtype = []
348 struct_fieldval = []
349 for J in np.arange(0,struct_fieldcount):
350 np.fromfile( self.f, dtype='>i8', count=1 ) # Zero
351 struct_fielddtype.append( self.getTagDType( np.fromfile( self.f, dtype='>i8', count=1 ) ) )
352 # print( str(J) + ": field dtype = " + str( struct_fielddtype[J] ) )
353 for J in np.arange(0,struct_fieldcount):
354 struct_fieldval.append( np.fromfile(self.f, dtype=struct_fielddtype[J], count=1)[0] )
355 # print( str(J) + ": field val = " + str( struct_fieldval[J] ) )
356 return struct_fieldval
357 elif tag_infos[K] == 20: # array
358 if self.verbose: print( "Found array" )
359 try:
360 K += 1 # Warning: sometimes arrays are empty
361 array_dtype = self.getTagDType(tag_infos[K])
362 K += 1
363 array_ncount = tag_infos[K]
364 if self.verbose: print( "Array dtype: " + array_dtype + ", array ncount: " + str(array_ncount) )
365 if( array_ncount > 0 ):
366 return np.fromfile(self.f, dtype=array_dtype, count=array_ncount)
367 except IndexError:
368 pass
369 pass
370 elif tag_infos[K] == 9: # string
371 tag_char = self.f.read(1)
372 if self.verbose: print( "Found char: " + tag_char )
373 pass
374 elif tag_infos[K] == 18: # string
375 # str_len =
376 if self.verbose: print( "FIXME Found string" )
377 pass
378 else: # singleton
379 tag_dtype = self.getTagDType( tag_infos[K] )
380 if tag_dtype != '':
381 tag_data = np.fromfile( self.f, dtype = tag_dtype, count=1 )[0]
382 # if self.verbose: print( "Singleton: " + tag_dtype + ": " + str(tag_data) ):
383 if self.verbose: print( "Singleton: " + tag_dtype + ": " + str(tag_data) )
384 return tag_data
385 pass
386
387 def discardTag(self):
388 """ Quickly parse to the end of tag that we don't care about its information """
389 tag_namelen = np.fromfile( self.f, dtype='>i2', count=1 )[0]
390 self.f.seek( self.f.tell() + tag_namelen )
391 tag_fieldlen = np.fromfile( self.f, dtype='>i8', count=1 )[0]
392 self.f.seek( self.f.tell() + tag_fieldlen )
393 return
394
395 def parseTagDir(self, parent):
396 """ Parse a tag directory at the given file handle location """
397 try:
398 tag_namelen = np.fromfile( self.f, dtype='>i2', count=1 )[0]
399
400 if tag_namelen > 0:
401 tag_name = self.f.read( tag_namelen )
402 # tag_name = np.fromfile( self.f, dtype='S%d'%tag_namelen, count=1 )[0]
403 else:
404 tag_name = b""
405
406 tag_fieldlen = np.fromfile( self.f, dtype='>i8', count=1 )[0]
407 # print( "parseTagDir: tag_name: %s has length %d and field length %d" %(tag_name, tag_namelen, tag_fieldlen ))
408
409 except IndexError:
410 if self.verbose: print( "Caught IndexError, trying to recover position in file" )
411 # f.seek( f.tell() )
412 return self.f
413
414 # Handle empty tag_name by giving it an auto-generated number
415 if not bool(tag_name):
416 if( self.verbose ) : print( "Found empty tag" )
417 tag_depth = int( parent.count( b'/') - 1 )
418
419 # This is kind of mental gymnastics to maintain portablity between Python 2 and 3
420 tag_name = bytearray( str(self._unnamedIndices[ tag_depth ]).encode('ascii') )
421 # print( "Gymnastics " + str(self._unnamedIndices[ tag_depth ]) + " -> " + str(tag_name) )
422 self._unnamedIndices[ tag_depth ] += 1
423 # Reset all higher indices
424 self._unnamedIndices[ tag_depth+1:] = 0
425 loc_tagdir = self.f.tell()
426 self.f.read( 2 ) # Throw away sorted and closed
427 ntags_dir = np.fromfile( self.f, dtype='>i8', count=1 )[0]
428 if self.verbose:
429 print( "Found tag dir " + str(parent) + str(tag_name) + " with " + str(ntags_dir) + " tags" )
430
431 # So typically ImageList has two empty name tag directories, of which one is various stuff and the other is the data
432 for I in np.arange(0, ntags_dir ):
433 try:
434 subtag_type = np.fromfile( self.f, dtype='i1', count=1 )[0] # 20 = tag directory, 21 = tag base, 0 == EOF
435 except IndexError:
436 if self.verbose:
437 print( "Caught IndexError, trying to recover" )
438 break
439 if( subtag_type == 20 ):
440 self.parseTagDir( bytes(parent) + bytes(tag_name) + b"/" )
441 elif( subtag_type == 21 ):
442 self.parseTag( bytes(parent) + bytes(tag_name) + b"/" )
443 elif( subtag_type == 0 ):
444 break # EOF
445 # Go to next tag in root directory
446 self.f.seek( loc_tagdir + tag_fieldlen )
447 return
448
449
450
451 def asyncReadDM4(*args, **kwargs):
452 '''
453 Calls `readDM4` in a separate thread and executes it in the background.
454
455 Parameters
456 ----------
457 Valid arguments are as for `readDM4()`.
458
459 Returns
460 -------
461 future
462 A ``concurrent.futures.Future()`` object. Calling ``future.result()``
463 will halt until the read is finished and returns the image and meta-data
464 as per a normal call to `readMRC`.
465
466 Example
467 -------
468
469 worker = asyncReadMRC( 'someones_file.mrc' )
470 # Do some work
471 mrcImage, mrcMeta = worker.result()
472 '''
473 return _asyncExecutor.submit(readDM4, *args, **kwargs)