1 | # -*- coding: utf-8 -*- |
---|
2 | ########### SVN repository information ################### |
---|
3 | # $Date: 2017-04-24 02:30:38 +0000 (Mon, 24 Apr 2017) $ |
---|
4 | # $Author: toby $ |
---|
5 | # $Revision: 2802 $ |
---|
6 | # $URL: trunk/imports/G2img_HDF5.py $ |
---|
7 | # $Id: G2img_HDF5.py 2802 2017-04-24 02:30:38Z toby $ |
---|
8 | ########### SVN repository information ################### |
---|
9 | ''' |
---|
10 | *Module G2img_HDF5: summed HDF5 image file* |
---|
11 | ------------------------------------------- |
---|
12 | |
---|
13 | Reads all images found in a HDF5 file. |
---|
14 | |
---|
15 | ''' |
---|
16 | |
---|
17 | try: |
---|
18 | import h5py |
---|
19 | except ImportError: |
---|
20 | h5py = None |
---|
21 | import GSASIIIO as G2IO |
---|
22 | import GSASIIpath |
---|
23 | GSASIIpath.SetVersionNumber("$Revision: 2802 $") |
---|
24 | |
---|
25 | class HDF5_Reader(G2IO.ImportImage): |
---|
26 | '''Routine to read a HD5 image, typically from APS Sector 6. |
---|
27 | B. Frosik/SDM. |
---|
28 | ''' |
---|
29 | dsetlist = [] |
---|
30 | buffer = {} |
---|
31 | init = False |
---|
32 | |
---|
33 | def __init__(self): |
---|
34 | if h5py is None: |
---|
35 | self.UseReader = False |
---|
36 | print('HDF5 Reader skipped because h5py library is not installed') |
---|
37 | import os,sys |
---|
38 | os.path.split(sys.executable)[0] |
---|
39 | conda = os.path.join(os.path.split(sys.executable)[0],'conda') |
---|
40 | if os.path.exists(conda): |
---|
41 | print('To fix this use command:\n\t'+conda+' install h5py hdf5') |
---|
42 | super(self.__class__,self).__init__( # fancy way to self-reference |
---|
43 | extensionlist=('.hdf5','.hd5','.h5','.hdf'), |
---|
44 | strictExtension=True, |
---|
45 | formatName = 'HDF5 image', |
---|
46 | longFormatName = 'HDF5 image file' |
---|
47 | ) |
---|
48 | |
---|
49 | def ContentsValidator(self, filepointer): |
---|
50 | '''Test if valid by seeing if the HDF5 library recognizes the file. |
---|
51 | ''' |
---|
52 | try: |
---|
53 | f = h5py.File(filepointer.name, 'r') |
---|
54 | f.close() |
---|
55 | return True |
---|
56 | except IOError: |
---|
57 | return False |
---|
58 | |
---|
59 | def Reader(self, filename, filepointer, ParentFrame=None, **kwarg): |
---|
60 | '''Scan file structure using :meth:`visit` and map out locations of image(s) |
---|
61 | then read one image using :meth:`readDataset`. Save map of file structure in |
---|
62 | buffer arg, if used. |
---|
63 | ''' |
---|
64 | imagenum = kwarg.get('blocknum') |
---|
65 | if imagenum is None: imagenum = 1 |
---|
66 | self.buffer = kwarg.get('buffer',{}) |
---|
67 | try: |
---|
68 | fp = h5py.File(filename, 'r') |
---|
69 | if not self.buffer.get('init'): |
---|
70 | self.buffer['init'] = True |
---|
71 | self.Comments = self.visit(fp) |
---|
72 | if imagenum > len(self.buffer['imagemap']): |
---|
73 | self.errors = 'No valid images found in file' |
---|
74 | return False |
---|
75 | |
---|
76 | self.Data,self.Npix,self.Image = self.readDataset(fp,imagenum) |
---|
77 | if self.Npix == 0: |
---|
78 | self.errors = 'No valid images found in file' |
---|
79 | return False |
---|
80 | self.LoadImage(ParentFrame,filename,imagenum) |
---|
81 | self.repeatcount = imagenum |
---|
82 | self.repeat = imagenum < len(self.buffer['imagemap']) |
---|
83 | if GSASIIpath.GetConfigValue('debug'): print('Read image #'+str(imagenum)+' from file '+filename) |
---|
84 | return True |
---|
85 | except IOError: |
---|
86 | print 'cannot open file ', filename |
---|
87 | return False |
---|
88 | finally: |
---|
89 | fp.close() |
---|
90 | |
---|
91 | def visit(self, fp): |
---|
92 | '''Recursively visit each node in an HDF5 file. For nodes |
---|
93 | ending in 'data' look at dimensions of contents. If the shape is |
---|
94 | length 2 or 4 assume an image and index in self.buffer['imagemap'] |
---|
95 | ''' |
---|
96 | datakeyword = 'data' |
---|
97 | head = [] |
---|
98 | def func(name, dset): |
---|
99 | if not hasattr(dset,'shape'): return # not array, can't be image |
---|
100 | if isinstance(dset, h5py.Dataset): |
---|
101 | if len(dset.shape) < 2: |
---|
102 | head.append('%s: %s'%(dset.name,str(dset[()][0]))) |
---|
103 | if dset.name.endswith(datakeyword): |
---|
104 | dims = dset.shape |
---|
105 | if len(dims) == 4: |
---|
106 | self.buffer['imagemap'] += [(dset.name,i) for i in range(dims[1])] |
---|
107 | elif len(dims) == 3: |
---|
108 | self.buffer['imagemap'] += [(dset.name,i) for i in range(dims[0])] |
---|
109 | elif len(dims) == 2: |
---|
110 | self.buffer['imagemap'] += [(dset.name,None)] |
---|
111 | else: |
---|
112 | print('Skipping entry '+str(dset.name)+'. Shape is '+str(dims)) |
---|
113 | #if GSASIIpath.GetConfigValue('debug'): print 'visit' |
---|
114 | self.buffer['imagemap'] = [] |
---|
115 | fp.visititems(func) |
---|
116 | return head |
---|
117 | |
---|
118 | def readDataset(self,fp,imagenum=1): |
---|
119 | '''Read a specified image number from a file |
---|
120 | ''' |
---|
121 | name,num = self.buffer['imagemap'][imagenum-1] # look up in map |
---|
122 | dset = fp[name] |
---|
123 | if num is None: |
---|
124 | image = dset[()] |
---|
125 | elif len(dset.shape) == 4: |
---|
126 | image = dset[0,num,...] |
---|
127 | elif len(dset.shape) == 3: |
---|
128 | image = dset[num,...] |
---|
129 | else: |
---|
130 | msg = 'Unexpected image dimensions '+name |
---|
131 | print(msg) |
---|
132 | raise Exception(msg) |
---|
133 | sizexy = list(image.shape) |
---|
134 | Npix = sizexy[0]*sizexy[1] |
---|
135 | data = {'pixelSize':[200.,200.],'wavelength':0.15,'distance':1000., |
---|
136 | 'center':[sizexy[0]*0.1,sizexy[1]*0.1],'size':sizexy} |
---|
137 | for item in self.Comments: |
---|
138 | name,val = item.split(':',1) |
---|
139 | if 'wavelength' in name and 'spread' not in name: |
---|
140 | try: |
---|
141 | data['wavelength'] = float(val) |
---|
142 | except ValueError: |
---|
143 | pass |
---|
144 | elif 'distance' in name: |
---|
145 | data['distance'] = float(val) |
---|
146 | elif 'x_pixel_size' in name: |
---|
147 | data['pixelSize'][0] = float(val)*1000. |
---|
148 | elif 'y_pixel_size' in name: |
---|
149 | data['pixelSize'][1] = float(val)*1000. |
---|
150 | elif 'beam_center_x' in name: |
---|
151 | data['center'][0] = float(val) |
---|
152 | elif 'beam_center_y' in name: |
---|
153 | data['center'][1] = float(val) |
---|
154 | return data,Npix,image.T |
---|