source: trunk/imports/G2img_GE.py @ 3828

Last change on this file since 3828 was 3828, checked in by toby, 4 years ago

fix cif export w/unused histogram; switch 3.x imports to pickle w/warn if _pickle not available; doc fixes; scriptable enhancements

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