source: trunk/imports/G2img_HDF5.py @ 2284

Last change on this file since 2284 was 2284, checked in by vondreele, 7 years ago

update binwin64 (probably no different from previous one)
add Stacking Fault-III to tutorial list
fixup HDF5 importer for images - now recovers wavelength, distance, pixel size, etc.
fix float/integer incompatibility in Flat Bkg values
enable/disable if calibrant/nocalibrant for both Calibrate & Recalibrate
fix a float/int error in mouse positioning on image

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