source: trunk/imports/G2img_GE.py @ 2461

Last change on this file since 2461 was 2461, checked in by vondreele, 6 years ago

magnetic space group determination done

  • 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: 2016-09-08 14:09:47 +0000 (Thu, 08 Sep 2016) $
4# $Author: vondreele $
5# $Revision: 2461 $
6# $URL: trunk/imports/G2img_GE.py $
7# $Id: G2img_GE.py 2461 2016-09-08 14:09:47Z 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: 2461 $")
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 filename.split('.')[-1] in ['sum',]:
124        head = ['GE detector sum  data from APS 1-ID',]
125        sizexy = [2048,2048]
126        Npix = sizexy[0]*sizexy[1]
127        image = np.array(np.frombuffer(File.read(4*Npix),dtype=np.float32),dtype=np.int32)
128#        image = np.array(ar.array('f',File.read(4*Npix)),dtype=np.int32)
129    elif filename.split('.')[-1] in ['avg','cor']:
130        File.seek(0,2)
131        last = File.tell()
132        pos = last-2*(2048**2)
133        File.seek(pos)
134        head = ['GE detector avg or cor data from APS 1-ID',]
135        sizexy = [2048,2048]
136        Npix = sizexy[0]*sizexy[1]
137        image = np.array(np.frombuffer(File.read(2*Npix),dtype=np.int16),dtype=np.int32)
138#        image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
139    else:
140        head = ['GE detector raw data',]
141        File.seek(18)
142        size,nframes = st.unpack('<ih',File.read(6))
143        # number of frames seems to be 3 for single-image files
144        if size != 2048:
145            print('Warning GE image size unexpected: '+str(size))
146            return 0,0,0,0,False # probably should quit now
147        if imagenum > nframes:
148            print('Error: attempt to read image #'+str(imagenum)+
149                  ' from file with '+str(nframes)+' images.')
150            return 0,0,0,0,False
151        elif imagenum < nframes:
152            more = True
153        sizexy = [2048,2048]
154        Npix = sizexy[0]*sizexy[1]
155        pos = 8192 + (imagenum-1)*2*Npix
156        File.seek(pos)
157        image = np.array(np.frombuffer(File.read(2*Npix),dtype=np.int16),dtype=np.int32)
158#        image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
159        if len(image) != sizexy[1]*sizexy[0]:
160            print('not enough images while reading GE file: '+filename+'image #'+str(imagenum))
161            return 0,0,0,0,False           
162        head += ['file: '+filename+' image #'+str(imagenum),]
163        if sum:    #will ignore imagenum
164            print 'Frames to read %d'%(nframes),
165            while nframes > 1: #OK, this will sum the frames.
166                try:
167                    image += np.array(np.frombuffer(File.read(2*Npix),dtype=np.int16),dtype=np.int32)
168#                    image += np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
169                except ValueError:
170                    break
171                nframes -= 1
172                print '%d'%(nframes),
173            print ''   
174            more = False
175            filename = os.path.splitext(filename)[0]+'.G2img'
176            File = open(filename,'wb')
177            Data = {'pixelSize':[200,200],'wavelength':0.15,'distance':250.0,'center':[204.8,204.8],'size':sizexy}
178            image = np.reshape(image,(sizexy[1],sizexy[0]))
179            cPickle.dump([head,Data,Npix,image],File,1)
180            File.close()
181            self.sumfile = filename
182            self.formatName = 'GSAS-II image'
183            sum = False
184    image = np.reshape(image,(sizexy[1],sizexy[0]))
185    data = {'pixelSize':[200,200],'wavelength':0.15,'distance':250.0,'center':[204.8,204.8],'size':sizexy}
186    File.close()
187    if GSASIIpath.GetConfigValue('debug'):
188        print 'Read GE file: '+filename+' image #'+'%04d'%(imagenum)
189    return head,data,Npix,image,more
Note: See TracBrowser for help on using the repository browser.