source: trunk/imports/G2sfact.py @ 1762

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

fix exports of reflection csv & txt files to work for CW & TOF data as well as
3 & (3+1) symmetries
fix Det-X --> Det-Y
remove a Yield - caused crash
fix c-unique & a-unique monoclinit cell refinement & display
fix cif readers for phase

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