source: trunk/imports/G2sfact.py @ 1884

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

remove some unused imports
add merohedral/pseudomerohedral Twin Laws to G2ddataGUI and G2strIO (not in G2strmath yet).
allow ReImport? atoms to fill otherwise empty Atom List
clarify HKL importers as Shelx HKL 4 & HKL 5 files.

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