source: trunk/imports/G2img_CBF.py @ 3136

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

make GSAS-II python 3.6 compliant & preserve python 2.7 use;changes:
do from future import division, print_function for all GSAS-II py sources
all menu items revised to be py 2.7/3.6 compliant
all wx.OPEN --> wx.FD_OPEN in file dialogs
all integer divides (typically for image pixel math) made explicit with ; ambiguous ones made floats as appropriate
all print "stuff" --> print (stuff)
all print >> pFile,'stuff' --> pFile.writeCIFtemplate('stuff')
all read file opens made explicit 'r' or 'rb'
all cPickle imports made for py2.7 or 3.6 as cPickle or _pickle; test for '2' platform.version_tuple[0] for py 2.7
define cPickleload to select load(fp) or load(fp,encoding='latin-1') for loading gpx files; provides cross compatibility between py 2.7/3.6 gpx files
make dict.keys() as explicit list(dict.keys()) as needed (NB: possible source of remaining py3.6 bugs)
make zip(a,b) as explicit list(zip(a,b)) as needed (NB: possible source of remaining py3.6 bugs)
select unichr/chr according test for '2' platform.version_tuple[0] for py 2.7 (G2pwdGUI * G2plot) for special characters
select wg.EVT_GRID_CELL_CHANGE (classic) or wg.EVT_GRID_CELL_CHANGED (phoenix) in grid Bind
maxint --> maxsize; used in random number stuff
raise Exception,"stuff" --> raise Exception("stuff")
wx 'classic' sizer.DeleteWindows?() or 'phoenix' sizer.Clear(True)
wx 'classic' SetToolTipString?(text) or 'phoenix' SetToolTip?(wx.ToolTip?(text)); define SetToolTipString?(self,text) to handle the choice in plots
status.SetFields? --> status.SetStatusText?
'classic' AddSimpleTool? or 'phoenix' self.AddTool? for plot toolbar; Bind different as well
define GetItemPydata? as it doesn't exist in wx 'phoenix'
allow python versions 2.7 & 3.6 to run GSAS-II
Bind override commented out - no logging capability (NB: remove all logging code?)
all import ContentsValidator? open filename & test if valid then close; filepointer removed from Reader
binary importers (mostly images) test for 'byte' type & convert as needed to satisfy py 3.6 str/byte rules

File size: 3.7 KB
Line 
1# -*- coding: utf-8 -*-
2########### SVN repository information ###################
3# $Date: 2016-01-22 13:05:12 -0600 (Fri, 22 Jan 2016) $
4# $Author: toby $
5# $Revision: 2133 $
6# $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/imports/G2img_CBF.py $
7# $Id: G2img_CBF.py 2133 2016-01-22 19:05:12Z toby $
8########### SVN repository information ###################
9'''
10*Module G2img_CBF: .cbf cif image file*
11---------------------------------------
12
13'''
14
15from __future__ import division, print_function
16import time
17import GSASIIobj as G2obj
18import GSASIIpath
19import unpack_cbf as cbf
20GSASIIpath.SetVersionNumber("$Revision: 2133 $")
21class CBF_ReaderClass(G2obj.ImportImage):
22    '''Routine to read a Read cif image data .cbf file.
23    This is used by Pilatus.
24    '''
25    def __init__(self):
26        super(self.__class__,self).__init__( # fancy way to self-reference
27            extensionlist=('.cbf',),
28            strictExtension=True,
29            formatName = 'CBF image',
30            longFormatName = 'CIF Binary Data Format image file (NB: Slow!)'
31            )
32
33    def ContentsValidator(self, filename):       
34        '''no test used at this time
35        '''
36        return True
37       
38    def Reader(self,filename, ParentFrame=None, **unused):
39        '''Read using Bob's routine :func:`GetCbfData`
40        '''
41        self.Comments,self.Data,self.Npix,self.Image = GetCbfData(self,filename)
42        if self.Npix == 0 or not self.Comments:
43            return False
44        self.LoadImage(ParentFrame,filename)
45        return True
46       
47def GetCbfData(self,filename):   
48    'Read cif binarydetector data cbf file'
49   
50    import numpy as np
51    if GSASIIpath.GetConfigValue('debug'):
52        print ('Read cif binary detector data cbf file: '+filename)
53    File = open(filename,'rb')
54    sizexy = [0,0]
55    pixSize = [154,154]     #Pixium4700?
56    cent = [0,0]
57    wave = 1.54187  #default <CuKa>
58    dist = 1000.
59    byteOrd = '<'
60    stream = File.read()
61    if 'bytes' in str(type(stream)):
62        stream = stream.decode('latin-1')
63    starter = '\x0c\x1a\x04\xd5'
64    imageBeg = stream.find(starter)+4
65    head = stream[:imageBeg]
66    term = '\r\n'       #CR-LF
67    if term in head:
68        pass
69    else:
70        term = '\n' #LF only
71    head = head.split(term)
72    for line in head:
73        fields = line.split()
74        if 'Wavelength' in line:
75            wave = float(fields[2])
76        elif 'Detector_distance' in line:
77            dist = float(fields[2])*1000.
78        elif 'Pixel_size' in line:
79            pixSize = [float(fields[2])*1.e6,float(fields[5])*1.e6]
80        elif 'Beam_xy' in line:
81            cent = [float(fields[2].strip('(').strip(',')),float(fields[3].strip(')'))]
82        elif 'X-Binary-Size:' in line:
83            compImageSize = int(fields[1])
84        elif 'BIG_ENDIAN' in line:
85            byteOrd = '>'
86        elif 'Fastest-Dimension' in line:
87            sizexy[0] = int(fields[1])
88        elif 'Second-Dimension' in line:
89            sizexy[1] = int(fields[1])
90        elif 'Number-of-Elements' in line:
91            Npix = int(fields[1])
92    nxy = sizexy[0]*sizexy[1]
93    image = np.zeros(nxy,dtype=np.int32)
94    cent = [cent[0]*pixSize[0]/1000.,cent[1]*pixSize[1]/1000.]
95    compImage = stream[imageBeg:imageBeg+compImageSize]
96#    GSASIIpath.IPyBreak()
97    time0 = time.time()
98    nimg = len(compImage)
99    image = cbf.unpack_cbf(nimg,compImage,nxy,image)
100    image = np.reshape(image,(sizexy[1],sizexy[0]))
101    print ('import time: %.3f'%(time.time()-time0))
102    data = {'pixelSize':pixSize,'wavelength':wave,'distance':dist,'center':cent,'size':sizexy}
103    Npix = sizexy[0]*sizexy[1]
104   
105    return head,data,Npix,image
106       
Note: See TracBrowser for help on using the repository browser.