source: trunk/imports/G2img_GE.py @ 3151

Last change on this file since 3151 was 3151, checked in by vondreele, 4 years ago

male all default image pixel sizes [200.,200.] so ValidatedTxtCtrl? treats them as floats.
Fix crash when data is deleted from tree.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 7.5 KB
Line 
1# -*- coding: utf-8 -*-
2########### SVN repository information ###################
3# $Date: 2017-11-06 22:32:17 +0000 (Mon, 06 Nov 2017) $
4# $Author: vondreele $
5# $Revision: 3151 $
6# $URL: trunk/imports/G2img_GE.py $
7# $Id: G2img_GE.py 3151 2017-11-06 22:32:17Z vondreele $
8########### SVN repository information ###################
9'''
10*Module G2img_GE: summed GE image file*
11---------------------------------------
12
13This shows an example of an importer that will handle files with
14more than a single image.
15
16'''
17
18from __future__ import division, print_function
19import os
20import numpy as np
21import GSASIIobj as G2obj
22import GSASIIpath
23GSASIIpath.SetVersionNumber("$Revision: 3151 $")
24class GE_ReaderClass(G2obj.ImportImage):
25    '''Routine to read a GE image, typically from APS Sector 1.
26       
27        The image files may be of form .geX (where X is ' ', 1, 2, 3 or 4),
28        which is a raw image from the detector. These files may contain more
29        than one image and have a rudimentary header.
30        Files with extension .sum or .cor are 4 byte integers/pixel, one image/file.
31        Files with extension .avg are 2 byte integers/pixel, one image/file.
32    '''
33
34    def __init__(self):
35        super(self.__class__,self).__init__( # fancy way to self-reference
36            extensionlist=('.sum','.cor','.avg','.ge','.ge1','.ge2','.ge3','.ge4'),
37            strictExtension=True,
38            formatName = 'GE image',
39            longFormatName = 'Summed GE image file'
40            )
41
42    def ContentsValidator(self, filename):
43        '''just a test on file size
44        '''
45        if '.sum' not in str(filename):
46            try:
47                fp = open(filename,'rb')
48                statinfo = os.stat(str(fp).split("'")[1])
49                fsize = statinfo.st_size
50                self.nimages = (fsize-8192)/(2*2048**2)
51                fp.close()
52            except:
53                return False    #bad file size
54        return True
55       
56    def Reader(self,filename, ParentFrame=None, **kwarg):
57        '''Read using GE file reader, :func:`GetGEsumData`
58        '''
59        #rdbuffer = kwarg.get('buffer')
60        imagenum = kwarg.get('blocknum')
61        #sum = kwarg.get('sum')
62        if imagenum is None: imagenum = 1
63        self.Comments,self.Data,self.Npix,self.Image,more = \
64            GetGEsumData(self,filename,imagenum=imagenum)
65        if self.Npix == 0 or not self.Comments:
66            return False
67        self.LoadImage(ParentFrame,filename,imagenum)
68        self.repeatcount = imagenum
69        self.repeat = more
70        return True
71
72class GEsum_ReaderClass(G2obj.ImportImage):
73    '''Routine to read multiple GE images & sum them, typically from APS Sector 1.
74       
75        The image files may be of form .geX (where X is ' ', 1, 2, 3 or 4),
76        which is a raw image from the detector. These files may contain more
77        than one image and have a rudimentary header.
78        Files with extension .sum or .cor are 4 byte integers/pixel, one image/file.
79        Files with extension .avg are 2 byte integers/pixel, one image/file.
80    '''
81
82    def __init__(self):
83        super(self.__class__,self).__init__( # fancy way to self-reference
84            extensionlist=('.ge1','.ge2','.ge3','.ge4'),
85            strictExtension=True,
86            formatName = 'sum GE multi-image',
87            longFormatName = 'sum of GE multi-image file'
88            )
89
90    def ContentsValidator(self, filename):
91        '''just a test on file size
92        '''
93        try:
94            fp = open(filename,'rb')
95            statinfo = os.stat(str(fp).split("'")[1])
96            fsize = statinfo.st_size
97            nimages = (fsize-8192)/(2*2048**2)
98            fp.close()
99        except:
100            return False    #bad file size
101        return True
102       
103    def Reader(self,filename, ParentFrame=None, **kwarg):
104        '''Read using GE file reader, :func:`GetGEsumData`
105        '''
106        #rdbuffer = kwarg.get('buffer')
107        imagenum = kwarg.get('blocknum')
108        if imagenum is None: imagenum = 1
109        self.Comments,self.Data,self.Npix,self.Image,more = \
110            GetGEsumData(self,filename,imagenum=imagenum,sum=True)
111        if self.Npix == 0 or not self.Comments:
112            return False
113        self.LoadImage(ParentFrame,filename,imagenum)
114        self.repeatcount = imagenum
115        self.repeat = more
116        return True
117
118def GetGEsumData(self,filename,imagenum=1,sum=False):
119    '''Read G.E. detector images from various files as produced at 1-ID and
120    with Detector Pool detector. Also sums multiple image files if desired
121    '''
122    import struct as st
123    import platform
124    if '2' in platform.python_version_tuple()[0]:
125        import cPickle
126    else:
127        import _pickle as cPickle
128    import time
129    more = False
130    time0 = time.time()
131    File = open(filename,'rb')
132    if filename.split('.')[-1] in ['sum',]:
133        head = ['GE detector sum  data from APS 1-ID',]
134        sizexy = [2048,2048]
135        Npix = sizexy[0]*sizexy[1]
136        image = np.array(np.frombuffer(File.read(4*Npix),dtype=np.float32),dtype=np.int32)
137    elif filename.split('.')[-1] in ['avg','cor']:
138        File.seek(0,2)
139        last = File.tell()
140        pos = last-2*(2048**2)
141        File.seek(pos)
142        head = ['GE detector avg or cor data from APS 1-ID',]
143        sizexy = [2048,2048]
144        Npix = sizexy[0]*sizexy[1]
145        image = np.array(np.frombuffer(File.read(2*Npix),dtype=np.int16),dtype=np.int32)
146    else:
147        head = ['GE detector raw data',]
148        File.seek(18)
149        size,nframes = st.unpack('<ih',File.read(6))
150        # number of frames seems to be 3 for single-image files
151        if size != 2048:
152            print('Warning GE image size unexpected: '+str(size))
153            return 0,0,0,0,False # probably should quit now
154        if imagenum > nframes:
155            print('Error: attempt to read image #'+str(imagenum)+
156                  ' from file with '+str(nframes)+' images.')
157            return 0,0,0,0,False
158        elif imagenum < nframes:
159            more = True
160        sizexy = [2048,2048]
161        Npix = sizexy[0]*sizexy[1]
162        pos = 8192 + (imagenum-1)*2*Npix
163        File.seek(pos)
164        image = np.array(np.frombuffer(File.read(2*Npix),dtype=np.int16),dtype=np.int32)
165        if len(image) != sizexy[1]*sizexy[0]:
166            print('not enough images while reading GE file: '+filename+'image #'+str(imagenum))
167            return 0,0,0,0,False           
168        head += ['file: '+filename+' image #'+str(imagenum),]
169        if sum:    #will ignore imagenum
170            print ('Frames to read %d,'%(nframes),end='')
171            while nframes > 1: #OK, this will sum the frames.
172                try:
173                    image += np.array(np.frombuffer(File.read(2*Npix),dtype=np.int16),dtype=np.int32)
174                except ValueError:
175                    break
176                nframes -= 1
177                print ('%d,'%(nframes),end='')
178            print ('') 
179            more = False
180            filename = os.path.splitext(filename)[0]+'.G2img'
181            File = open(filename,'wb')
182            Data = {'pixelSize':[200.,200.],'wavelength':0.15,'distance':250.0,'center':[204.8,204.8],'size':sizexy}
183            image = np.reshape(image,(sizexy[1],sizexy[0]))
184            cPickle.dump([head,Data,Npix,image],File,1)
185            File.close()
186            self.sumfile = filename
187            self.formatName = 'GSAS-II image'
188            sum = False
189    image = np.reshape(image,(sizexy[1],sizexy[0]))
190    data = {'pixelSize':[200.,200.],'wavelength':0.15,'distance':250.0,'center':[204.8,204.8],'size':sizexy}
191    File.close()
192    print ('Image read time %.2fs'%(time.time()-time0))
193    if GSASIIpath.GetConfigValue('debug'):
194        print ('Read GE file: '+filename+' image #'+'%04d'%(imagenum))
195    return head,data,Npix,image,more
Note: See TracBrowser for help on using the repository browser.