source: trunk/imports/G2img_GE.py @ 2409

Last change on this file since 2409 was 2409, checked in by vondreele, 5 years ago

fix GE image importer

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