source: trunk/imports/G2sfact.py @ 1446

Last change on this file since 1446 was 1446, checked in by vondreele, 9 years ago

add new import routine for JANA2000 single xtal files from ISIS

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 10.7 KB
Line 
1# -*- coding: utf-8 -*-
2########### SVN repository information ###################
3# $Date: 2014-07-30 16:36:23 +0000 (Wed, 30 Jul 2014) $
4# $Author: vondreele $
5# $Revision: 1446 $
6# $URL: trunk/imports/G2sfact.py $
7# $Id: G2sfact.py 1446 2014-07-30 16:36:23Z vondreele $
8########### SVN repository information ###################
9'''
10*Module G2sfact: simple HKL import*
11-----------------------------------
12Read structure factors from a simple hkl file. Two routines are
13provided to read from files containing F or F\ :sup:`2` values.
14
15'''
16import sys
17import numpy as np
18import copy
19import GSASIIIO as G2IO
20import GSASIIpath
21GSASIIpath.SetVersionNumber("$Revision: 1446 $")
22
23def ColumnValidator(parent, filepointer,nCol=5):
24    'Validate a file to check that it contains columns of numbers'
25    l = filepointer.readline()
26    line = 1
27    while l[0] in ['#','(']:        #get past comments & fortran formats, if any
28        l = filepointer.readline()       
29        line += 1
30    for i in range(10): # scan a few lines
31        S = l.split()
32        if len(S) < nCol:
33            parent.errors = 'line '+str(line)+': invalid input\n'+l
34            return False
35        for v in S[:nCol]:
36            try:
37                float(v)
38            except ValueError:
39                parent.errors = 'line '+str(line)+': string found where a number is expected\n'+l
40                return False           
41        l = filepointer.readline()
42        line += 1
43    return True
44
45
46class HKLF_ReaderClass(G2IO.ImportStructFactor):
47    'Routines to import F, sig(F) reflections from a HKLF file'
48    def __init__(self):
49        super(self.__class__,self).__init__( # fancy way to self-reference
50            extensionlist=('.hkl','.HKL'),
51            strictExtension=False,
52            formatName = 'HKL F',
53            longFormatName = 'Simple [hkl, Fo, sig(Fo)] Structure factor text file'
54            )
55
56    def ContentsValidator(self, filepointer):
57        'Make sure file contains the expected columns on numbers'
58        return ColumnValidator(self, filepointer)
59
60    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
61        'Read the file'
62        try:
63            for line,S in enumerate(filepointer):
64                self.errors = '  Error reading line '+str(line+1)
65                if S[0] == '#': continue       #ignore comments, if any
66                h,k,l,Fo,sigFo = S.split()
67                h,k,l = [int(h),int(k),int(l)]
68                if not any([h,k,l]):
69                    break
70                Fo = float(Fo)
71                sigFo = float(sigFo)
72                # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
73                self.RefDict['RefList'].append([h,k,l,0,0,Fo**2,2.*Fo*sigFo,0,Fo**2,0,0,0])
74                #self.RefDict['FF'].append({}) # now done in OnImportSfact
75            self.errors = 'Error after reading reflections (unexpected!)'
76            self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
77            self.UpdateParameters(Type='SXC',Wave=None) # histogram type
78            return True
79        except Exception as detail:
80            self.errors += '\n  '+str(detail)
81            print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
82            import traceback
83            traceback.print_exc(file=sys.stdout)
84            return False
85
86class HKLF2_ReaderClass(G2IO.ImportStructFactor):
87    'Routines to import F**2, sig(F**2) reflections from a HKLF file'
88    def __init__(self):
89        super(self.__class__,self).__init__( # fancy way to self-reference
90            extensionlist=('.hkl','.HKL'),
91            strictExtension=False,
92            formatName = u'HKL F\u00b2',
93            longFormatName = u'Simple [hkl, Fo\u00b2, sig(Fo\u00b2)] Structure factor text file'
94            )
95
96    def ContentsValidator(self, filepointer):
97        'Make sure file contains the expected columns on numbers'
98        return ColumnValidator(self, filepointer)
99
100    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
101        'Read the file'
102        try:
103            for line,S in enumerate(filepointer):
104                self.errors = '  Error reading line '+str(line+1)
105                if S[0] == '#': continue       #ignore comments, if any
106                h,k,l,Fo,sigFo = S.split()
107                h,k,l = [int(h),int(k),int(l)]
108                if not any([h,k,l]):
109                    break
110                Fo = float(Fo)
111                sigFo = float(sigFo)
112                # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
113                self.RefDict['RefList'].append([h,k,l,0,0,Fo,sigFo,0,Fo,0,0,0])
114                #self.RefDict['FF'].append({}) # now done in OnImportSfact
115            self.errors = 'Error after reading reflections (unexpected!)'
116            self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
117            self.UpdateParameters(Type='SXC',Wave=None) # histogram type
118            return True
119        except Exception as detail:
120            self.errors += '\n  '+str(detail)
121            print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
122            import traceback
123            traceback.print_exc(file=sys.stdout)
124            return False
125
126class NT_HKLF2_ReaderClass(G2IO.ImportStructFactor):
127    'Routines to import neutron TOF F**2, sig(F**2) reflections from a HKLF file'
128    def __init__(self):
129        super(self.__class__,self).__init__( # fancy way to self-reference
130            extensionlist=('.hkl','.HKL'),
131            strictExtension=False,
132            formatName = u'Neutron TOF HKL F\u00b2',
133            longFormatName = u'Neutron TOF [hkl, Fo\u00b2, sig(Fo\u00b2),...] Structure factor text file'
134            )
135
136    def ContentsValidator(self, filepointer):
137        'Make sure file contains the expected columns on numbers & count number of data blocks - "Banks"'
138        oldNo = -1
139        for line,S in enumerate(filepointer):
140            if not S:   #empty line terminates read
141                break
142            if S[0] == '#': continue       #ignore comments, if any
143            if S.split()[:3] == ['0','0','0']:
144                break
145            bankNo = S.split()[5]
146            if bankNo != oldNo:
147                self.Banks.append({'RefDict':{'RefList':[],}})
148                oldNo = bankNo
149        filepointer.seek(0)
150        return ColumnValidator(self, filepointer,nCol=8)
151
152    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
153        'Read the file'
154        filepointer.seek(0)
155        try:
156            for line,S in enumerate(filepointer):
157                self.errors = '  Error reading line '+str(line+1)
158                if S[0] == '#': continue       #ignore comments, if any
159                data = S.split()
160                h,k,l,Fo,sigFo,bN,wave,tbar = data[:8]  #bN = 1..., 6 dir cos next                   
161                h,k,l = [int(h),int(k),int(l)]
162                if not any([h,k,l]):
163                    break
164                Fo = float(Fo)
165                sigFo = float(sigFo)
166                wave = float(wave)
167                tbar = float(tbar)
168                if len(self.Banks):
169                    self.Banks[int(bN)-1]['RefDict']['RefList'].append([h,k,l,0,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
170                else:
171                # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
172                    self.RefDict['RefList'].append([h,k,l,0,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
173            if len(self.Banks):
174                self.UpdateParameters(Type='SNT',Wave=None) # histogram type
175                for Bank in self.Banks:
176                    Bank['RefDict']['RefList'] = np.array(Bank['RefDict']['RefList'])                   
177            else:
178                self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
179                self.errors = 'Error after reading reflections (unexpected!)'
180                self.UpdateParameters(Type='SNT',Wave=None) # histogram type
181            return True
182        except Exception as detail:
183            self.errors += '\n  '+str(detail)
184            print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
185            import traceback
186            traceback.print_exc(file=sys.stdout)
187            return False
188
189class NT_JANA2K_ReaderClass(G2IO.ImportStructFactor):
190    'Routines to import neutron TOF F**2, sig(F**2) reflections from a JANA2000 file'
191    def __init__(self):
192        super(self.__class__,self).__init__( # fancy way to self-reference
193            extensionlist=('.int','.INT'),
194            strictExtension=False,
195            formatName = u'Neutron TOF JANA2000 F\u00b2',
196            longFormatName = u'Neutron TOF [hkl, Fo\u00b2, sig(Fo\u00b2),...] Structure factor text file'
197            )
198
199    def ContentsValidator(self, filepointer):
200        'Make sure file contains the expected columns on numbers & count number of data blocks - "Banks"'
201        oldNo = -1
202        for line,S in enumerate(filepointer):
203            if not S:   #empty line terminates read
204                break
205            if S[0] in ['#','(']: continue       #ignore comments & fortran format line
206            bankNo = S.split()[5]
207            if bankNo != oldNo:
208                self.Banks.append({'RefDict':{'RefList':[],}})
209                oldNo = bankNo
210        filepointer.seek(0)
211        return ColumnValidator(self, filepointer,nCol=10)
212
213    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
214        'Read the file'
215        filepointer.seek(0)
216        try:
217            for line,S in enumerate(filepointer):
218                self.errors = '  Error reading line '+str(line+1)
219                if S[0] in ['#','(']: continue       #ignore comments & fortran format line
220                data = S.split()
221                h,k,l,Fo,sigFo,bN,wave,x,x,tbar = data[:10]  #bN = 1..., 6 dir cos next                   
222                h,k,l = [int(h),int(k),int(l)]
223                if not any([h,k,l]):
224                    break
225                Fo = float(Fo)
226                sigFo = float(sigFo)
227                wave = float(wave)
228                tbar = float(tbar)
229                if len(self.Banks):
230                    self.Banks[int(bN)-1]['RefDict']['RefList'].append([h,k,l,0,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
231                else:
232                # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
233                    self.RefDict['RefList'].append([h,k,l,0,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
234            if len(self.Banks):
235                self.UpdateParameters(Type='SNT',Wave=None) # histogram type
236                for Bank in self.Banks:
237                    Bank['RefDict']['RefList'] = np.array(Bank['RefDict']['RefList'])                   
238            else:
239                self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
240                self.errors = 'Error after reading reflections (unexpected!)'
241                self.UpdateParameters(Type='SNT',Wave=None) # histogram type
242            return True
243        except Exception as detail:
244            self.errors += '\n  '+str(detail)
245            print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
246            import traceback
247            traceback.print_exc(file=sys.stdout)
248            return False
249
Note: See TracBrowser for help on using the repository browser.