source: trunk/imports/G2sfact.py @ 2079

Last change on this file since 2079 was 2079, checked in by vondreele, 7 years ago

new importer for hk6 files from 15ID

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 29.6 KB
Line 
1# -*- coding: utf-8 -*-
2########### SVN repository information ###################
3# $Date: 2015-12-03 21:09:45 +0000 (Thu, 03 Dec 2015) $
4# $Author: vondreele $
5# $Revision: 2079 $
6# $URL: trunk/imports/G2sfact.py $
7# $Id: G2sfact.py 2079 2015-12-03 21:09:45Z 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: 2079 $")
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,1,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 HKLMF_ReaderClass(G2IO.ImportStructFactor):
88    'Routines to import F, reflections from a REMOS HKLMF file'
89    def __init__(self):
90        super(self.__class__,self).__init__( # fancy way to self-reference
91            extensionlist=('.fo','.FO'),
92            strictExtension=False,
93            formatName = 'HKLM F',
94            longFormatName = 'REMOS [hklm, Fo] 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,m,Fo= S.split()
108                h,k,l,m = [int(h),int(k),int(l),int(m)]
109                if h == 999 or not any([h,k,l]):
110                    break
111                Fo = float(Fo)
112                sigFo2 = Fo
113                if Fo < 1.0:
114                    sigFo2 = 1.0
115               # h,k,l,m,tw,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
116                self.RefDict['RefList'].append([h,k,l,m,1,0,Fo**2,sigFo2,0,Fo**2,0,0,0])
117            self.errors = 'Error after reading reflections (unexpected!)'
118            self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
119            self.RefDict['Type'] = 'SXC'
120            self.RefDict['Super'] = 1
121            self.UpdateParameters(Type='SXC',Wave=None) # histogram type
122            return True
123        except Exception as detail:
124            self.errors += '\n  '+str(detail)
125            print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
126            import traceback
127            traceback.print_exc(file=sys.stdout)
128            return False
129
130class SHELX4_ReaderClass(G2IO.ImportStructFactor):
131    'Routines to import F**2, sig(F**2) reflections from a Shelx HKLF 4 file'
132    def __init__(self):
133        if 'linux' in sys.platform:  # wx 3.0.0.0 on gtk does not like Unicode in menus
134            formatName = 'HKLF 4'
135            longFormatName = 'Shelx HKLF 4 [hkl, Fo2, sig(Fo2)] Structure factor text file'
136        else:
137            formatName = u'Shelx HKLF 4 F\u00b2'
138            longFormatName = u'Shelx HKLF 4 [hkl, Fo\u00b2, sig(Fo\u00b2)] Structure factor text file'
139        super(self.__class__,self).__init__( # fancy way to self-reference
140            extensionlist=('.hkl','.HKL'),
141            strictExtension=False,
142            formatName=formatName,
143            longFormatName=longFormatName)
144
145    def ContentsValidator(self, filepointer):
146        'Make sure file contains the expected columns on numbers'
147        return ColumnValidator(self, filepointer)
148
149    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
150        'Read the file'
151        try:
152            for line,S in enumerate(filepointer):
153                self.errors = '  Error reading line '+str(line+1)
154                if S[0] == '#': continue       #ignore comments, if any
155                h,k,l,Fo,sigFo = S[:4],S[4:8],S[8:12],S[12:20],S[20:28]
156                h,k,l = [int(h),int(k),int(l)]
157                if not any([h,k,l]):
158                    break
159                Fo = float(Fo)
160                sigFo = float(sigFo)
161                # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
162                self.RefDict['RefList'].append([h,k,l,1,0,Fo,sigFo,0,Fo,0,0,0])
163                #self.RefDict['FF'].append({}) # now done in OnImportSfact
164            self.errors = 'Error after reading reflections (unexpected!)'
165            self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
166            self.RefDict['Type'] = 'SXC'
167            self.RefDict['Super'] = 0
168            self.UpdateParameters(Type='SXC',Wave=None) # histogram type
169            return True
170        except Exception as detail:
171            self.errors += '\n  '+str(detail)
172            print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
173            import traceback
174            traceback.print_exc(file=sys.stdout)
175            return False
176           
177class SHELX5_ReaderClass(G2IO.ImportStructFactor):
178    'Routines to import F**2, sig(F**2) twin/incommensurate reflections from a fixed format SHELX HKLF5 file'
179    def __init__(self):
180        if 'linux' in sys.platform:  # wx 3.0.0.0 on gtk does not like Unicode in menus
181            formatName = 'Shelx HKLF 5 F2 Tw/Incom'
182            longFormatName = 'Shelx HKLF 5 [hklm, Fo2, sig(Fo2), Tind] Twin/incommensurate structure factor text file'
183        else:
184            formatName = u'Shelx HKLF 5 F\u00b2 Tw/Incom'
185            longFormatName = u'Shelx HKLF 5 [hklm, Fo\u00b2, sig(Fo\u00b2), Tind] Twin/incommensurate structure factor text file'       
186        super(self.__class__,self).__init__( # fancy way to self-reference
187            extensionlist=('.hkl','.HKL'),
188            strictExtension=False,
189            formatName=formatName,
190            longFormatName=longFormatName)
191        self.Super = 0
192
193    def ContentsValidator(self, filepointer):
194        '''Discover how many columns before F^2 are in the SHELX HKL5 file
195        - could be 3-6 depending on satellites'''
196        numCols = 0
197        for i,line in enumerate(filepointer):
198            for j,item in enumerate(line.split()):  #find 1st col with '.'; has F^2
199                if '.' in item:
200                    numCols = max(numCols,j)
201                    break
202            if i > 20:
203                break
204        self.Super = numCols-3     #= 0,1,2,or 3
205        if self.Super > 1:
206            raise self.ImportException("Supersymmetry too high; GSAS-II limited to (3+1) supersymmetry")           
207        return True
208
209    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
210        'Read the file'
211        TwDict = {}
212        TwSet = {}
213        TwMax = [-1,[]]
214        first = True
215        try:
216            for line,S in enumerate(filepointer):
217                self.errors = '  Error reading line '+str(line+1)
218                if self.Super == 0:
219                    h,k,l,Fo,sigFo,Tw = S[:4],S[4:8],S[8:12],S[12:20],S[20:28],S[28:32]
220                    h,k,l = [int(h),int(k),int(l)]
221                elif self.Super == 1:
222                    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]
223                    h,k,l,m1 = [int(h),int(k),int(l),int(m1)]
224                Tw = Tw.strip()
225                if Tw in ['','0']:
226                    Tw = '1'
227                if not any([h,k,l]):
228                    break
229                if '-' in Tw:
230                    if Tw == '-1':  #fix reversed twin ids
231                        Tw = '-2'
232                        if first:
233                            self.warnings += '\nPrimary twin id changed to 1'
234                            first = False
235                    TwId = -int(Tw)-1
236                    TwSet[TwId] = np.array([h,k,l])
237                    if TwId not in TwMax[1]:
238                        TwMax[1].append(TwId)
239                else:
240                    if Tw != '1':  #fix reversed twin ids
241                        if first:
242                            self.warnings += '\nPrimary twin id changed to 1\nNB: multiple primary twins not working'
243                            first = False
244                        Tw = '1'
245                    TwId = int(Tw)-1
246                    if TwSet:
247                        TwDict[len(self.RefDict['RefList'])] = TwSet
248                        TwSet = {}   
249                    Fo = float(Fo)
250                    sigFo = float(sigFo)
251                    # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
252                    if self.Super == 0:
253                        self.RefDict['RefList'].append([h,k,l,int(Tw),0,Fo,sigFo,0,Fo,0,0,0])
254                    elif self.Super == 1:
255                        self.RefDict['RefList'].append([h,k,l,m1,int(Tw),0,Fo,sigFo,0,Fo,0,0,0])
256                TwMax[0] = max(TwMax[0],TwId)
257            self.errors = 'Error after reading reflections (unexpected!)'
258            self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
259            self.RefDict['Type'] = 'SXC'
260            self.RefDict['Super'] = self.Super
261            self.RefDict['TwDict'] = TwDict
262            self.RefDict['TwMax'] = TwMax
263            self.UpdateParameters(Type='SXC',Wave=None) # histogram type
264            return True
265        except Exception as detail:
266            self.errors += '\n  '+str(detail)
267            print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
268            import traceback
269            traceback.print_exc(file=sys.stdout)
270            return False
271
272class SHELX6_ReaderClass(G2IO.ImportStructFactor):
273    'Routines to import F**2, sig(F**2) twin/incommensurate reflections from a fixed format SHELX HKLF6 file'
274    def __init__(self):
275        if 'linux' in sys.platform:  # wx 3.0.0.0 on gtk does not like Unicode in menus
276            formatName = 'Shelx HKLF 6 F2 Tw/Incom'
277            longFormatName = 'Shelx HKLF 6 [hklm, Fo2, sig(Fo2), Tind] Twin/incommensurate structure factor text file'
278        else:
279            formatName = u'Shelx HKLF 6 F\u00b2 Tw/Incom'
280            longFormatName = u'Shelx HKLF 6 [hklm, Fo\u00b2, sig(Fo\u00b2), Tind] Twin/incommensurate structure factor text file'       
281        super(self.__class__,self).__init__( # fancy way to self-reference
282            extensionlist=('.hk6','.HK6'),
283            strictExtension=False,
284            formatName=formatName,
285            longFormatName=longFormatName)
286        self.Super = 0
287
288    def ContentsValidator(self, filepointer):
289        '''Discover how many columns before F^2 are in the SHELX HKL5 file
290        - could be 3-6 depending on satellites'''
291        numCols = 0
292        for i,line in enumerate(filepointer):
293            for j,item in enumerate(line.split()):  #find 1st col with '.'; has F^2
294                if '.' in item:
295                    numCols = max(numCols,j)
296                    break
297            if i > 20:
298                break
299        if numCols != 6:
300            self.warnings += '\nInvalid hk6 file; wrong number of columns'
301            raise self.ImportException('Invalid hk6 file; wrong number of columns')
302        self.Super = 1
303        return True
304
305    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
306        'Read the file'
307        TwDict = {}
308        TwSet = {}
309        TwMax = [-1,[]]
310        first = True
311        try:
312            for line,S in enumerate(filepointer):
313                self.errors = '  Error reading line '+str(line+1)
314                h,k,l,m1,m2,m3,Fo,sigFo,Tw = S[:4],S[4:8],S[8:12],S[12:16],S[16:20],S[20:24],S[24:32],S[32:40],S[40:44]
315                h,k,l,m1,m2,m3 = [int(h),int(k),int(l),int(m1),int(m2),int(m3)]
316                if m2 or m3:
317                    self.warnings += '\n(3+2) & (3+3) Supersymmetry not allowed in GSAS-II. Reformulate as twinned (3+1) supersymmetry'
318                    raise self.ImportException("Supersymmetry too high; GSAS-II limited to (3+1) supersymmetry")                               
319                Tw = Tw.strip()
320                if Tw in ['','0']:
321                    Tw = '1'
322                if not any([h,k,l]):    #look for 0 0 0 or blank line
323                    break
324                if '-' in Tw:
325                    if Tw == '-1':  #fix reversed twin ids
326                        Tw = '-2'
327                        if first:
328                            self.warnings += '\nPrimary twin id changed to 1'
329                            first = False
330                    TwId = -int(Tw)-1
331                    TwSet[TwId] = np.array([h,k,l])
332                    if TwId not in TwMax[1]:
333                        TwMax[1].append(TwId)
334                else:
335                    if Tw != '1':  #fix reversed twin ids
336                        if first:
337                            self.warnings += '\nPrimary twin id changed to 1\nNB: multiple primary twins not working'
338                            first = False
339                        Tw = '1'
340                    TwId = int(Tw)-1
341                    if TwSet:
342                        TwDict[len(self.RefDict['RefList'])] = TwSet
343                        TwSet = {}   
344                    Fo = float(Fo)
345                    sigFo = float(sigFo)
346                    # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
347                    self.RefDict['RefList'].append([h,k,l,m1,int(Tw),0,Fo,sigFo,0,Fo,0,0,0])
348                TwMax[0] = max(TwMax[0],TwId)
349            self.errors = 'Error after reading reflections (unexpected!)'
350            self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
351            self.RefDict['Type'] = 'SXC'
352            self.RefDict['Super'] = self.Super
353            self.RefDict['TwDict'] = TwDict
354            self.RefDict['TwMax'] = TwMax
355            self.UpdateParameters(Type='SXC',Wave=None) # histogram type
356            return True
357        except Exception as detail:
358            self.errors += '\n  '+str(detail)
359            print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
360            import traceback
361            traceback.print_exc(file=sys.stdout)
362            return False
363
364class M90_ReaderClass(G2IO.ImportStructFactor):
365    'Routines to import F**2, sig(F**2) reflections from a JANA M90 file'
366    def __init__(self):
367        if 'linux' in sys.platform:  # wx 3.0.0.0 on gtk does not like Unicode in menus
368            longFormatName = 'JANA [hkl, Fo2, sig(Fo2)] Structure factor text file'
369        else:
370            longFormatName = u'JANA [hkl, Fo\u00b2, sig(Fo\u00b2)] Structure factor text file'
371        super(self.__class__,self).__init__( # fancy way to self-reference
372            extensionlist=('.m90','.M90'),
373            strictExtension=False,
374            formatName = u'JANA M90',
375            longFormatName = longFormatName
376            )
377        self.Super = 0
378
379    def ContentsValidator(self, filepointer):
380        'Discover how many columns are in the m90 file - could be 9-12 depending on satellites'
381        numCols = 0
382        for i,line in enumerate(filepointer):
383            if 'Data' in line:
384                startData = i
385                break
386        for i,line in enumerate(filepointer):
387            if i > startData:
388                numCols = max(numCols,len(line.split()))
389            if i > startData+20:
390                break
391        self.Super = numCols-9     #= 0,1,2,or 3
392        if self.Super > 1:
393            raise self.ImportException("Supersymmetry too high; GSAS-II limited to (3+1) supersymmetry")           
394        return True #ColumnValidator(self, filepointer)
395
396    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
397        'Read the file'
398        try:
399            for line,S in enumerate(filepointer):
400                self.errors = '  Error reading line '+str(line+1)
401                if S[0] == '#': continue       #ignore comments, if any
402                try:
403                    if self.Super == 0:
404                        h,k,l,Fo,sigFo = S.split()[:5]
405                        h,k,l = [int(h),int(k),int(l)]
406                    elif self.Super == 1:
407                        h,k,l,m1,Fo,sigFo = S.split()[:6]
408                        h,k,l,m1 = [int(h),int(k),int(l),int(m1)]
409                except ValueError:  #skipping text at front
410                    if not S:
411                        break
412                    text = S.split()
413                    if text[0] == 'lambda':
414                        wave = float(text[1])
415                    continue
416                Fo = float(Fo)
417                sigFo = float(sigFo)
418                # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
419                if self.Super == 0:
420                    self.RefDict['RefList'].append([h,k,l,1,0,Fo,sigFo,0,Fo,0,0,0])
421                elif self.Super == 1:
422                    self.RefDict['RefList'].append([h,k,l,m1,1,0,Fo,sigFo,0,Fo,0,0,0])
423            self.errors = 'Error after reading reflections (unexpected!)'
424            self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
425            self.RefDict['Type'] = 'SXC'
426            self.RefDict['Super'] = self.Super
427            self.UpdateParameters(Type='SXC',Wave=wave) # histogram type
428            return True
429        except Exception as detail:
430            self.errors += '\n  '+str(detail)
431            print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
432            import traceback
433            traceback.print_exc(file=sys.stdout)
434            return False
435           
436class NT_HKLF2_ReaderClass(G2IO.ImportStructFactor):
437    'Routines to import neutron TOF F**2, sig(F**2) reflections from a HKLF file'
438    def __init__(self):
439        if 'linux' in sys.platform:  # wx 3.0.0.0 on gtk does not like Unicode in menus
440            formatName = 'Neutron TOF HKL F2'
441            longFormatName = 'Neutron TOF [hkl, Fo2, sig(Fo2),...] Structure factor text file'
442        else:
443            formatName = u'Neutron TOF HKL F\u00b2'
444            longFormatName = u'Neutron TOF [hkl, Fo\u00b2, sig(Fo\u00b2),...] Structure factor text file'
445        super(self.__class__,self).__init__( # fancy way to self-reference
446            extensionlist=('.hkl','.HKL'),
447            strictExtension=False,
448            formatName=formatName,
449            longFormatName=longFormatName)
450
451    def ContentsValidator(self, filepointer):
452        'Make sure file contains the expected columns on numbers & count number of data blocks - "Banks"'
453        oldNo = -1
454        for line,S in enumerate(filepointer):
455            if not S:   #empty line terminates read
456                break
457            if S[0] == '#': continue       #ignore comments, if any
458            if S.split()[:3] == ['0','0','0']:
459                break
460            bankNo = S.split()[5]
461            if bankNo != oldNo:
462                self.Banks.append({'RefDict':{'RefList':[],}})
463                oldNo = bankNo
464        filepointer.seek(0)
465        return ColumnValidator(self, filepointer,nCol=8)
466
467    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
468        'Read the file'
469        filepointer.seek(0)
470        try:
471            for line,S in enumerate(filepointer):
472                self.errors = '  Error reading line '+str(line+1)
473                if S[0] == '#': continue       #ignore comments, if any
474                data = S.split()
475                h,k,l,Fo,sigFo,bN,wave,tbar = data[:8]  #bN = 1..., 6 dir cos next                   
476                h,k,l = [int(h),int(k),int(l)]
477                if not any([h,k,l]):
478                    break
479                Fo = float(Fo)
480                sigFo = float(sigFo)
481                wave = float(wave)
482                tbar = float(tbar)
483                if len(self.Banks):
484                    self.Banks[int(bN)-1]['RefDict']['RefList'].append([h,k,l,1,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
485                else:
486                # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
487                    self.RefDict['RefList'].append([h,k,l,1,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
488            if len(self.Banks):
489                self.UpdateParameters(Type='SNT',Wave=None) # histogram type
490                for Bank in self.Banks:
491                    Bank['RefDict']['RefList'] = np.array(Bank['RefDict']['RefList'])
492                    Bank['RefDict']['Type'] = 'SNT'                   
493                    Bank['RefDict']['Super'] = 0
494            else:
495                self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
496                self.RefDict['Type'] = 'SNT'
497                self.RefDict['Super'] = 0
498                self.errors = 'Error after reading reflections (unexpected!)'
499                self.UpdateParameters(Type='SNT',Wave=None) # histogram type
500            return True
501        except Exception as detail:
502            self.errors += '\n  '+str(detail)
503            print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
504            import traceback
505            traceback.print_exc(file=sys.stdout)
506            return False
507
508class NT_JANA2K_ReaderClass(G2IO.ImportStructFactor):
509    'Routines to import neutron TOF F**2, sig(F**2) reflections from a JANA2000 file'
510    def __init__(self):
511        if 'linux' in sys.platform:  # wx 3.0.0.0 on gtk does not like Unicode in menus
512            formatName = 'Neutron TOF JANA2000 F2'
513            longFormatName = 'Neutron TOF [hkl, Fo2, sig(Fo2),...] Structure factor text file'
514        else:
515            formatName = u'Neutron TOF JANA2000 F\u00b2'
516            longFormatName = u'Neutron TOF [hkl, Fo\u00b2, sig(Fo\u00b2),...] Structure factor text file'
517        super(self.__class__,self).__init__( # fancy way to self-reference
518            extensionlist=('.int','.INT'),
519            strictExtension=False,
520            formatName=formatName,
521            longFormatName=longFormatName)
522
523    def ContentsValidator(self, filepointer):
524        'Make sure file contains the expected columns on numbers & count number of data blocks - "Banks"'
525        oldNo = -1
526        for line,S in enumerate(filepointer):
527            if not S:   #empty line terminates read
528                break
529            if S[0] in ['#','(']: continue       #ignore comments & fortran format line
530            bankNo = S.split()[5]
531            if bankNo != oldNo:
532                self.Banks.append({'RefDict':{'RefList':[],}})
533                oldNo = bankNo
534        filepointer.seek(0)
535        return ColumnValidator(self, filepointer,nCol=10)
536
537    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
538        'Read the file'
539        filepointer.seek(0)
540        try:
541            for line,S in enumerate(filepointer):
542                self.errors = '  Error reading line '+str(line+1)
543                if S[0] in ['#','(']: continue       #ignore comments & fortran format line
544                data = S.split()
545                h,k,l,Fo,sigFo,bN,wave,x,x,tbar = data[:10]  #bN = 1..., 6 dir cos next                   
546                h,k,l = [int(h),int(k),int(l)]
547                if not any([h,k,l]):
548                    break
549                Fo = float(Fo)
550                sigFo = float(sigFo)
551                wave = float(wave)
552                tbar = float(tbar)
553                if len(self.Banks):
554                    self.Banks[int(bN)-1]['RefDict']['RefList'].append([h,k,l,1,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
555                else:
556                # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
557                    self.RefDict['RefList'].append([h,k,l,1,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
558            if len(self.Banks):
559                self.UpdateParameters(Type='SNT',Wave=None) # histogram type
560                for Bank in self.Banks:
561                    Bank['RefDict']['RefList'] = np.array(Bank['RefDict']['RefList'])
562                    Bank['RefDict']['Type'] = 'SNT'                   
563                    Bank['RefDict']['Super'] = 0        #for now                   
564            else:
565                self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
566                self.RefDict['Type'] = 'SNT'
567                self.RefDict['Super'] = 0   #for now
568                self.errors = 'Error after reading reflections (unexpected!)'
569                self.UpdateParameters(Type='SNT',Wave=None) # histogram type
570            return True
571        except Exception as detail:
572            self.errors += '\n  '+str(detail)
573            print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
574            import traceback
575            traceback.print_exc(file=sys.stdout)
576            return False
577
578class ISIS_SXD_INT_ReaderClass(G2IO.ImportStructFactor):
579    'Routines to import neutron TOF F**2, sig(F**2) reflections from a ISIS int file'
580    def __init__(self):
581        if 'linux' in sys.platform:  # wx 3.0.0.0 on gtk does not like Unicode in menus
582            formatName = u'Neutron SXD TOF HKL F2'
583            longFormatName = u'Neutron SXD TOF [hkl, Fo2, sig(Fo2),...] Structure factor text file'
584        else:
585            formatName = u'Neutron SXD TOF HKL F\u00b2'
586            longFormatName = u'Neutron SXD TOF [hkl, Fo\u00b2, sig(Fo\u00b2),...] Structure factor text file'
587        super(self.__class__,self).__init__( # fancy way to self-reference
588            extensionlist=('.int','.INT'),
589            strictExtension=False,
590            formatName=formatName,
591            longFormatName=longFormatName)
592
593    def ContentsValidator(self, filepointer):
594        'Make sure file contains the expected columns on numbers & count number of data blocks - "Banks"'
595        oldNo = -1
596        for line,S in enumerate(filepointer):
597            if not S:   #empty line terminates read
598                break
599            if S[0] == '#': continue       #ignore comments, if any
600            if S[0] == '(': continue        #ignore format line
601            bankNo = S.split()[5]
602            if bankNo != oldNo:
603                self.Banks.append({'RefDict':{'RefList':[],}})
604                oldNo = bankNo
605        filepointer.seek(0)
606        return ColumnValidator(self, filepointer,nCol=8)
607
608    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
609        'Read the file'
610        filepointer.seek(0)
611        try:
612            for line,S in enumerate(filepointer):
613                self.errors = '  Error reading line '+str(line+1)
614                if S[0] == '#': continue       #ignore comments, if any
615                if S[0] == '(': continue        #ignore the format line
616                data = S.split()
617                h,k,l,Fo,sigFo,bN,wave,x,x,tbar = data[:10]                   
618                h,k,l = [int(h),int(k),int(l)]
619                if not any([h,k,l]):
620                    break
621                Fo = float(Fo)
622                sigFo = float(sigFo)
623                wave = float(wave)
624                tbar = float(tbar)
625                if len(self.Banks):
626                    self.Banks[int(bN)-1]['RefDict']['RefList'].append([h,k,l,1,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
627                else:
628                # h,k,l,m,dsp,Fo2,sig,Fc2,Fot2,Fct2,phase,...
629                    self.RefDict['RefList'].append([h,k,l,1,0,Fo,sigFo,0,Fo,0,0,0,wave,tbar])
630            if len(self.Banks):
631                self.UpdateParameters(Type='SNT',Wave=None) # histogram type
632                for Bank in self.Banks:
633                    Bank['RefDict']['RefList'] = np.array(Bank['RefDict']['RefList'])
634                    Bank['RefDict']['Type'] = 'SNT'                   
635                    Bank['RefDict']['Super'] = 0
636            else:
637                self.RefDict['RefList'] = np.array(self.RefDict['RefList'])
638                self.RefDict['Type'] = 'SNT'
639                self.RefDict['Super'] = 0
640                self.errors = 'Error after reading reflections (unexpected!)'
641                self.UpdateParameters(Type='SNT',Wave=None) # histogram type
642            return True
643        except Exception as detail:
644            self.errors += '\n  '+str(detail)
645            print '\n\n'+self.formatName+' read error: '+str(detail) # for testing
646            import traceback
647            traceback.print_exc(file=sys.stdout)
648            return False
649
Note: See TracBrowser for help on using the repository browser.