source: trunk/imports/G2sfact.py @ 1909

Last change on this file since 1909 was 1909, checked in by vondreele, 8 years ago

fix import names for HKLF files - now explicit Shelx names
fix importing problems with run-on numbers in Shelx HKLF 4 & 5 files
fix issues with importing structure factors before importing a phase

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 21.9 KB
Line 
1# -*- coding: utf-8 -*-
2########### SVN repository information ###################
3# $Date: 2015-06-26 15:39:44 +0000 (Fri, 26 Jun 2015) $
4# $Author: vondreele $
5# $Revision: 1909 $
6# $URL: trunk/imports/G2sfact.py $
7# $Id: G2sfact.py 1909 2015-06-26 15:39:44Z 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: 1909 $")
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.errors = 'Error after reading reflections (unexpected!)'
75            self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
76            self.RefDict['Type'] = 'SXC'
77            self.RefDict['Super'] = 0
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 HKLF4_ReaderClass(G2IO.ImportStructFactor):
88    'Routines to import F**2, sig(F**2) reflections from a HKLF 4 file'
89    def __init__(self):
90        if 'linux' in sys.platform:  # wx 3.0.0.0 on gtk does not like Unicode in menus
91            formatName = 'HKLF 4'
92            longFormatName = 'Shelx HKLF 4 [hkl, Fo2, sig(Fo2)] Structure factor text file'
93        else:
94            formatName = u'Shelx HKLF 4 F\u00b2'
95            longFormatName = u'Shelx HKLF 4 [hkl, Fo\u00b2, sig(Fo\u00b2)] Structure factor text file'
96        super(self.__class__,self).__init__( # fancy way to self-reference
97            extensionlist=('.hkl','.HKL'),
98            strictExtension=False,
99            formatName=formatName,
100            longFormatName=longFormatName)
101
102    def ContentsValidator(self, filepointer):
103        'Make sure file contains the expected columns on numbers'
104        return ColumnValidator(self, filepointer)
105
106    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
107        'Read the file'
108        try:
109            for line,S in enumerate(filepointer):
110                self.errors = '  Error reading line '+str(line+1)
111                if S[0] == '#': continue       #ignore comments, if any
112                h,k,l,Fo,sigFo = S.split()[:5]
113                h,k,l = [int(h),int(k),int(l)]
114                if not any([h,k,l]):
115                    break
116                Fo = float(Fo)
117                sigFo = float(sigFo)
118                # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
119                self.RefDict['RefList'].append([h,k,l,0,0,Fo,sigFo,0,Fo,0,0,0])
120                #self.RefDict['FF'].append({}) # now done in OnImportSfact
121            self.errors = 'Error after reading reflections (unexpected!)'
122            self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
123            self.RefDict['Type'] = 'SXC'
124            self.RefDict['Super'] = 0
125            self.UpdateParameters(Type='SXC',Wave=None) # histogram type
126            return True
127        except Exception as detail:
128            self.errors += '\n  '+str(detail)
129            print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
130            import traceback
131            traceback.print_exc(file=sys.stdout)
132            return False
133           
134class M90_ReaderClass(G2IO.ImportStructFactor):
135    'Routines to import F**2, sig(F**2) reflections from a JANA M90 file'
136    def __init__(self):
137        if 'linux' in sys.platform:  # wx 3.0.0.0 on gtk does not like Unicode in menus
138            longFormatName = 'JANA [hkl, Fo2, sig(Fo2)] Structure factor text file'
139        else:
140            longFormatName = u'JANA [hkl, Fo\u00b2, sig(Fo\u00b2)] Structure factor text file'
141        super(self.__class__,self).__init__( # fancy way to self-reference
142            extensionlist=('.m90','.M90'),
143            strictExtension=False,
144            formatName = u'JANA M90',
145            longFormatName = longFormatName
146            )
147        self.Super = 0
148
149    def ContentsValidator(self, filepointer):
150        'Discover how many columns are in the m90 file - could be 9-12 depending on satellites'
151        numCols = 0
152        for i,line in enumerate(filepointer):
153            if 'Data' in line:
154                startData = i
155                break
156        for i,line in enumerate(filepointer):
157            if i > startData:
158                numCols = max(numCols,len(line.split()))
159            if i > startData+20:
160                break
161        self.Super = numCols-9     #= 0,1,2,or 3
162        if self.Super > 1:
163            raise self.ImportException("Supersymmetry too high; GSAS-II limited to (3+1) supersymmetry")           
164        return True #ColumnValidator(self, filepointer)
165
166    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
167        'Read the file'
168        try:
169            for line,S in enumerate(filepointer):
170                self.errors = '  Error reading line '+str(line+1)
171                if S[0] == '#': continue       #ignore comments, if any
172                try:
173                    if self.Super == 0:
174                        h,k,l,Fo,sigFo = S.split()[:5]
175                        h,k,l = [int(h),int(k),int(l)]
176                    elif self.Super == 1:
177                        h,k,l,m1,Fo,sigFo = S.split()[:6]
178                        h,k,l,m1 = [int(h),int(k),int(l),int(m1)]
179                except ValueError:  #skipping text at front
180                    if not S:
181                        break
182                    text = S.split()
183                    if text[0] == 'lambda':
184                        wave = float(text[1])
185                    continue
186                Fo = float(Fo)
187                sigFo = float(sigFo)
188                # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
189                if self.Super == 0:
190                    self.RefDict['RefList'].append([h,k,l,0,0,Fo,sigFo,0,Fo,0,0,0])
191                elif self.Super == 1:
192                    self.RefDict['RefList'].append([h,k,l,m1,0,0,Fo,sigFo,0,Fo,0,0,0])
193            self.errors = 'Error after reading reflections (unexpected!)'
194            self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
195            self.RefDict['Type'] = 'SXC'
196            self.RefDict['Super'] = self.Super
197            self.UpdateParameters(Type='SXC',Wave=wave) # histogram type
198            return True
199        except Exception as detail:
200            self.errors += '\n  '+str(detail)
201            print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
202            import traceback
203            traceback.print_exc(file=sys.stdout)
204            return False
205           
206class SHELX5_ReaderClass(G2IO.ImportStructFactor):
207    'Routines to import F**2, sig(F**2) twin index reflections from a fixed format SHELX HKLF5 file'
208    def __init__(self):
209        if 'linux' in sys.platform:  # wx 3.0.0.0 on gtk does not like Unicode in menus
210            formatName = 'SHELX HKLF 5 F2'
211            longFormatName = 'SHELX HKLF 5 [hklm, Fo2, sig(Fo2), Tind] Structure factor text file'
212        else:
213            formatName = u'SHELX HKLF 5 F\u00b2'
214            longFormatName = u'SHELX HKLF 5 [hklm, Fo\u00b2, sig(Fo\u00b2), Tind] Structure factor text file'       
215        super(self.__class__,self).__init__( # fancy way to self-reference
216            extensionlist=('.hkl','.HKL'),
217            strictExtension=False,
218            formatName=formatName,
219            longFormatName=longFormatName)
220        self.Super = 0
221
222    def ContentsValidator(self, filepointer):
223        'Discover how many characters are in the SHELX file - could be 32-44 depending on satellites'
224        numCols = 0
225        for i,line in enumerate(filepointer):
226            numCols = max(numCols,len(line.split()))
227            if i > 20:
228                break
229        self.Super = numCols-6     #= 0,1,2,or 3
230        if self.Super > 1:
231            raise self.ImportException("Supersymmetry too high; GSAS-II limited to (3+1) supersymmetry")           
232        return True #ColumnValidator(self, filepointer)
233
234    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
235        'Read the file'
236        try:
237            for line,S in enumerate(filepointer):
238                self.errors = '  Error reading line '+str(line+1)
239                if self.Super == 0:
240                    h,k,l,Fo,sigFo,Tw = S[:4],S[4:8],S[8:12],S[12:20],S[20:28],S[28:32]
241                    h,k,l = [int(h),int(k),int(l)]
242                elif self.Super == 1:
243                    h,k,l,m1,Fo,sigFo,Tw = S[:4],S[4:8],S[8:12],S[12:16],S[16:24],S[24:32],S[32:36]
244                    h,k,l,m1 = [int(h),int(k),int(l),int(m1)]
245                if not any([h,k,l]):
246                    break
247                Fo = float(Fo)
248                sigFo = float(sigFo)
249                # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
250                if self.Super == 0:
251                    self.RefDict['RefList'].append([h,k,l,0,0,Fo,sigFo,0,Fo,0,0,0])
252                elif self.Super == 1:
253                    self.RefDict['RefList'].append([h,k,l,m1,0,0,Fo,sigFo,0,Fo,0,0,0])
254                #self.RefDict['FF'].append({}) # now done in OnImportSfact
255            self.errors = 'Error after reading reflections (unexpected!)'
256            self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
257            self.RefDict['Type'] = 'SXC'
258            self.RefDict['Super'] = self.Super
259            self.UpdateParameters(Type='SXC',Wave=None) # histogram type
260            return True
261        except Exception as detail:
262            self.errors += '\n  '+str(detail)
263            print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
264            import traceback
265            traceback.print_exc(file=sys.stdout)
266            return False
267
268class NT_HKLF2_ReaderClass(G2IO.ImportStructFactor):
269    'Routines to import neutron TOF F**2, sig(F**2) reflections from a HKLF file'
270    def __init__(self):
271        if 'linux' in sys.platform:  # wx 3.0.0.0 on gtk does not like Unicode in menus
272            formatName = 'Neutron TOF HKL F2'
273            longFormatName = 'Neutron TOF [hkl, Fo2, sig(Fo2),...] Structure factor text file'
274        else:
275            formatName = u'Neutron TOF HKL F\u00b2'
276            longFormatName = u'Neutron TOF [hkl, Fo\u00b2, sig(Fo\u00b2),...] Structure factor text file'
277        super(self.__class__,self).__init__( # fancy way to self-reference
278            extensionlist=('.hkl','.HKL'),
279            strictExtension=False,
280            formatName=formatName,
281            longFormatName=longFormatName)
282
283    def ContentsValidator(self, filepointer):
284        'Make sure file contains the expected columns on numbers & count number of data blocks - "Banks"'
285        oldNo = -1
286        for line,S in enumerate(filepointer):
287            if not S:   #empty line terminates read
288                break
289            if S[0] == '#': continue       #ignore comments, if any
290            if S.split()[:3] == ['0','0','0']:
291                break
292            bankNo = S.split()[5]
293            if bankNo != oldNo:
294                self.Banks.append({'RefDict':{'RefList':[],}})
295                oldNo = bankNo
296        filepointer.seek(0)
297        return ColumnValidator(self, filepointer,nCol=8)
298
299    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
300        'Read the file'
301        filepointer.seek(0)
302        try:
303            for line,S in enumerate(filepointer):
304                self.errors = '  Error reading line '+str(line+1)
305                if S[0] == '#': continue       #ignore comments, if any
306                data = S.split()
307                h,k,l,Fo,sigFo,bN,wave,tbar = data[:8]  #bN = 1..., 6 dir cos next                   
308                h,k,l = [int(h),int(k),int(l)]
309                if not any([h,k,l]):
310                    break
311                Fo = float(Fo)
312                sigFo = float(sigFo)
313                wave = float(wave)
314                tbar = float(tbar)
315                if len(self.Banks):
316                    self.Banks[int(bN)-1]['RefDict']['RefList'].append([h,k,l,0,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
317                else:
318                # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
319                    self.RefDict['RefList'].append([h,k,l,0,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
320            if len(self.Banks):
321                self.UpdateParameters(Type='SNT',Wave=None) # histogram type
322                for Bank in self.Banks:
323                    Bank['RefDict']['RefList'] = np.array(Bank['RefDict']['RefList'])
324                    Bank['RefDict']['Type'] = 'SNT'                   
325                    Bank['RefDict']['Super'] = 0
326            else:
327                self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
328                self.RefDict['Type'] = 'SNT'
329                self.RefDict['Super'] = 0
330                self.errors = 'Error after reading reflections (unexpected!)'
331                self.UpdateParameters(Type='SNT',Wave=None) # histogram type
332            return True
333        except Exception as detail:
334            self.errors += '\n  '+str(detail)
335            print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
336            import traceback
337            traceback.print_exc(file=sys.stdout)
338            return False
339
340class NT_JANA2K_ReaderClass(G2IO.ImportStructFactor):
341    'Routines to import neutron TOF F**2, sig(F**2) reflections from a JANA2000 file'
342    def __init__(self):
343        if 'linux' in sys.platform:  # wx 3.0.0.0 on gtk does not like Unicode in menus
344            formatName = 'Neutron TOF JANA2000 F2'
345            longFormatName = 'Neutron TOF [hkl, Fo2, sig(Fo2),...] Structure factor text file'
346        else:
347            formatName = u'Neutron TOF JANA2000 F\u00b2'
348            longFormatName = u'Neutron TOF [hkl, Fo\u00b2, sig(Fo\u00b2),...] Structure factor text file'
349        super(self.__class__,self).__init__( # fancy way to self-reference
350            extensionlist=('.int','.INT'),
351            strictExtension=False,
352            formatName=formatName,
353            longFormatName=longFormatName)
354
355    def ContentsValidator(self, filepointer):
356        'Make sure file contains the expected columns on numbers & count number of data blocks - "Banks"'
357        oldNo = -1
358        for line,S in enumerate(filepointer):
359            if not S:   #empty line terminates read
360                break
361            if S[0] in ['#','(']: continue       #ignore comments & fortran format line
362            bankNo = S.split()[5]
363            if bankNo != oldNo:
364                self.Banks.append({'RefDict':{'RefList':[],}})
365                oldNo = bankNo
366        filepointer.seek(0)
367        return ColumnValidator(self, filepointer,nCol=10)
368
369    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
370        'Read the file'
371        filepointer.seek(0)
372        try:
373            for line,S in enumerate(filepointer):
374                self.errors = '  Error reading line '+str(line+1)
375                if S[0] in ['#','(']: continue       #ignore comments & fortran format line
376                data = S.split()
377                h,k,l,Fo,sigFo,bN,wave,x,x,tbar = data[:10]  #bN = 1..., 6 dir cos next                   
378                h,k,l = [int(h),int(k),int(l)]
379                if not any([h,k,l]):
380                    break
381                Fo = float(Fo)
382                sigFo = float(sigFo)
383                wave = float(wave)
384                tbar = float(tbar)
385                if len(self.Banks):
386                    self.Banks[int(bN)-1]['RefDict']['RefList'].append([h,k,l,0,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
387                else:
388                # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
389                    self.RefDict['RefList'].append([h,k,l,0,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
390            if len(self.Banks):
391                self.UpdateParameters(Type='SNT',Wave=None) # histogram type
392                for Bank in self.Banks:
393                    Bank['RefDict']['RefList'] = np.array(Bank['RefDict']['RefList'])
394                    Bank['RefDict']['Type'] = 'SNT'                   
395                    Bank['RefDict']['Super'] = 0        #for now                   
396            else:
397                self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
398                self.RefDict['Type'] = 'SNT'
399                self.RefDict['Super'] = 0   #for now
400                self.errors = 'Error after reading reflections (unexpected!)'
401                self.UpdateParameters(Type='SNT',Wave=None) # histogram type
402            return True
403        except Exception as detail:
404            self.errors += '\n  '+str(detail)
405            print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
406            import traceback
407            traceback.print_exc(file=sys.stdout)
408            return False
409
410class ISIS_SXD_INT_ReaderClass(G2IO.ImportStructFactor):
411    'Routines to import neutron TOF F**2, sig(F**2) reflections from a ISIS int file'
412    def __init__(self):
413        if 'linux' in sys.platform:  # wx 3.0.0.0 on gtk does not like Unicode in menus
414            formatName = u'Neutron SXD TOF HKL F2'
415            longFormatName = u'Neutron SXD TOF [hkl, Fo2, sig(Fo2),...] Structure factor text file'
416        else:
417            formatName = u'Neutron SXD TOF HKL F\u00b2'
418            longFormatName = u'Neutron SXD TOF [hkl, Fo\u00b2, sig(Fo\u00b2),...] Structure factor text file'
419        super(self.__class__,self).__init__( # fancy way to self-reference
420            extensionlist=('.int','.INT'),
421            strictExtension=False,
422            formatName=formatName,
423            longFormatName=longFormatName)
424
425    def ContentsValidator(self, filepointer):
426        'Make sure file contains the expected columns on numbers & count number of data blocks - "Banks"'
427        oldNo = -1
428        for line,S in enumerate(filepointer):
429            if not S:   #empty line terminates read
430                break
431            if S[0] == '#': continue       #ignore comments, if any
432            if S[0] == '(': continue        #ignore format line
433            bankNo = S.split()[5]
434            if bankNo != oldNo:
435                self.Banks.append({'RefDict':{'RefList':[],}})
436                oldNo = bankNo
437        filepointer.seek(0)
438        return ColumnValidator(self, filepointer,nCol=8)
439
440    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
441        'Read the file'
442        filepointer.seek(0)
443        try:
444            for line,S in enumerate(filepointer):
445                self.errors = '  Error reading line '+str(line+1)
446                if S[0] == '#': continue       #ignore comments, if any
447                if S[0] == '(': continue        #ignore the format line
448                data = S.split()
449                h,k,l,Fo,sigFo,bN,wave,x,x,tbar = data[:10]                   
450                h,k,l = [int(h),int(k),int(l)]
451                if not any([h,k,l]):
452                    break
453                Fo = float(Fo)
454                sigFo = float(sigFo)
455                wave = float(wave)
456                tbar = float(tbar)
457                if len(self.Banks):
458                    self.Banks[int(bN)-1]['RefDict']['RefList'].append([h,k,l,0,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
459                else:
460                # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
461                    self.RefDict['RefList'].append([h,k,l,0,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
462            if len(self.Banks):
463                self.UpdateParameters(Type='SNT',Wave=None) # histogram type
464                for Bank in self.Banks:
465                    Bank['RefDict']['RefList'] = np.array(Bank['RefDict']['RefList'])
466                    Bank['RefDict']['Type'] = 'SNT'                   
467                    Bank['RefDict']['Super'] = 0
468            else:
469                self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
470                self.RefDict['Type'] = 'SNT'
471                self.RefDict['Super'] = 0
472                self.errors = 'Error after reading reflections (unexpected!)'
473                self.UpdateParameters(Type='SNT',Wave=None) # histogram type
474            return True
475        except Exception as detail:
476            self.errors += '\n  '+str(detail)
477            print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
478            import traceback
479            traceback.print_exc(file=sys.stdout)
480            return False
481
Note: See TracBrowser for help on using the repository browser.