source: trunk/imports/G2sfact.py @ 1453

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

get HKLF data type into RefDict?
create a SetDefaultDData routine in GSASII.py
fix copyflags for sc extinction coeff
fix neutron resonant ff for TOF
fix error in making Hessian v-cov matrix - now matches the Jabobian one
put names in the Es, Ep & Eg sc extinction coeff
fix errors in SCExtinction - still problem with derivatives

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 11.0 KB
Line 
1# -*- coding: utf-8 -*-
2########### SVN repository information ###################
3# $Date: 2014-08-01 20:19:48 +0000 (Fri, 01 Aug 2014) $
4# $Author: vondreele $
5# $Revision: 1453 $
6# $URL: trunk/imports/G2sfact.py $
7# $Id: G2sfact.py 1453 2014-08-01 20:19:48Z 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: 1453 $")
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.RefDict['Type'] = 'SXC'
78            self.UpdateParameters(Type='SXC',Wave=None) # histogram type
79            return True
80        except Exception as detail:
81            self.errors += '\n  '+str(detail)
82            print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
83            import traceback
84            traceback.print_exc(file=sys.stdout)
85            return False
86
87class HKLF2_ReaderClass(G2IO.ImportStructFactor):
88    'Routines to import F**2, sig(F**2) reflections from a HKLF file'
89    def __init__(self):
90        super(self.__class__,self).__init__( # fancy way to self-reference
91            extensionlist=('.hkl','.HKL'),
92            strictExtension=False,
93            formatName = u'HKL F\u00b2',
94            longFormatName = u'Simple [hkl, Fo\u00b2, sig(Fo\u00b2)] Structure factor text file'
95            )
96
97    def ContentsValidator(self, filepointer):
98        'Make sure file contains the expected columns on numbers'
99        return ColumnValidator(self, filepointer)
100
101    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
102        'Read the file'
103        try:
104            for line,S in enumerate(filepointer):
105                self.errors = '  Error reading line '+str(line+1)
106                if S[0] == '#': continue       #ignore comments, if any
107                h,k,l,Fo,sigFo = S.split()
108                h,k,l = [int(h),int(k),int(l)]
109                if not any([h,k,l]):
110                    break
111                Fo = float(Fo)
112                sigFo = float(sigFo)
113                # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
114                self.RefDict['RefList'].append([h,k,l,0,0,Fo,sigFo,0,Fo,0,0,0])
115                #self.RefDict['FF'].append({}) # now done in OnImportSfact
116            self.errors = 'Error after reading reflections (unexpected!)'
117            self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
118            self.RefDict['Type'] = 'SXC'
119            self.UpdateParameters(Type='SXC',Wave=None) # histogram type
120            return True
121        except Exception as detail:
122            self.errors += '\n  '+str(detail)
123            print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
124            import traceback
125            traceback.print_exc(file=sys.stdout)
126            return False
127
128class NT_HKLF2_ReaderClass(G2IO.ImportStructFactor):
129    'Routines to import neutron TOF F**2, sig(F**2) reflections from a HKLF file'
130    def __init__(self):
131        super(self.__class__,self).__init__( # fancy way to self-reference
132            extensionlist=('.hkl','.HKL'),
133            strictExtension=False,
134            formatName = u'Neutron TOF HKL F\u00b2',
135            longFormatName = u'Neutron TOF [hkl, Fo\u00b2, sig(Fo\u00b2),...] Structure factor text file'
136            )
137
138    def ContentsValidator(self, filepointer):
139        'Make sure file contains the expected columns on numbers & count number of data blocks - "Banks"'
140        oldNo = -1
141        for line,S in enumerate(filepointer):
142            if not S:   #empty line terminates read
143                break
144            if S[0] == '#': continue       #ignore comments, if any
145            if S.split()[:3] == ['0','0','0']:
146                break
147            bankNo = S.split()[5]
148            if bankNo != oldNo:
149                self.Banks.append({'RefDict':{'RefList':[],}})
150                oldNo = bankNo
151        filepointer.seek(0)
152        return ColumnValidator(self, filepointer,nCol=8)
153
154    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
155        'Read the file'
156        filepointer.seek(0)
157        try:
158            for line,S in enumerate(filepointer):
159                self.errors = '  Error reading line '+str(line+1)
160                if S[0] == '#': continue       #ignore comments, if any
161                data = S.split()
162                h,k,l,Fo,sigFo,bN,wave,tbar = data[:8]  #bN = 1..., 6 dir cos next                   
163                h,k,l = [int(h),int(k),int(l)]
164                if not any([h,k,l]):
165                    break
166                Fo = float(Fo)
167                sigFo = float(sigFo)
168                wave = float(wave)
169                tbar = float(tbar)
170                if len(self.Banks):
171                    self.Banks[int(bN)-1]['RefDict']['RefList'].append([h,k,l,0,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
172                else:
173                # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
174                    self.RefDict['RefList'].append([h,k,l,0,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
175            if len(self.Banks):
176                self.UpdateParameters(Type='SNT',Wave=None) # histogram type
177                for Bank in self.Banks:
178                    Bank['RefDict']['RefList'] = np.array(Bank['RefDict']['RefList'])
179                    Bank['RefDict']['Type'] = 'SNT'                   
180            else:
181                self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
182                self.RefDict['Type'] = 'SNT'
183                self.errors = 'Error after reading reflections (unexpected!)'
184                self.UpdateParameters(Type='SNT',Wave=None) # histogram type
185            return True
186        except Exception as detail:
187            self.errors += '\n  '+str(detail)
188            print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
189            import traceback
190            traceback.print_exc(file=sys.stdout)
191            return False
192
193class NT_JANA2K_ReaderClass(G2IO.ImportStructFactor):
194    'Routines to import neutron TOF F**2, sig(F**2) reflections from a JANA2000 file'
195    def __init__(self):
196        super(self.__class__,self).__init__( # fancy way to self-reference
197            extensionlist=('.int','.INT'),
198            strictExtension=False,
199            formatName = u'Neutron TOF JANA2000 F\u00b2',
200            longFormatName = u'Neutron TOF [hkl, Fo\u00b2, sig(Fo\u00b2),...] Structure factor text file'
201            )
202
203    def ContentsValidator(self, filepointer):
204        'Make sure file contains the expected columns on numbers & count number of data blocks - "Banks"'
205        oldNo = -1
206        for line,S in enumerate(filepointer):
207            if not S:   #empty line terminates read
208                break
209            if S[0] in ['#','(']: continue       #ignore comments & fortran format line
210            bankNo = S.split()[5]
211            if bankNo != oldNo:
212                self.Banks.append({'RefDict':{'RefList':[],}})
213                oldNo = bankNo
214        filepointer.seek(0)
215        return ColumnValidator(self, filepointer,nCol=10)
216
217    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
218        'Read the file'
219        filepointer.seek(0)
220        try:
221            for line,S in enumerate(filepointer):
222                self.errors = '  Error reading line '+str(line+1)
223                if S[0] in ['#','(']: continue       #ignore comments & fortran format line
224                data = S.split()
225                h,k,l,Fo,sigFo,bN,wave,x,x,tbar = data[:10]  #bN = 1..., 6 dir cos next                   
226                h,k,l = [int(h),int(k),int(l)]
227                if not any([h,k,l]):
228                    break
229                Fo = float(Fo)
230                sigFo = float(sigFo)
231                wave = float(wave)
232                tbar = float(tbar)
233                if len(self.Banks):
234                    self.Banks[int(bN)-1]['RefDict']['RefList'].append([h,k,l,0,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
235                else:
236                # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
237                    self.RefDict['RefList'].append([h,k,l,0,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
238            if len(self.Banks):
239                self.UpdateParameters(Type='SNT',Wave=None) # histogram type
240                for Bank in self.Banks:
241                    Bank['RefDict']['RefList'] = np.array(Bank['RefDict']['RefList'])
242                    Bank['RefDict']['Type'] = 'SNT'                   
243            else:
244                self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
245                self.RefDict['Type'] = 'SNT'
246                self.errors = 'Error after reading reflections (unexpected!)'
247                self.UpdateParameters(Type='SNT',Wave=None) # histogram type
248            return True
249        except Exception as detail:
250            self.errors += '\n  '+str(detail)
251            print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
252            import traceback
253            traceback.print_exc(file=sys.stdout)
254            return False
255
Note: See TracBrowser for help on using the repository browser.