source: trunk/imports/G2phase.py @ 3266

Last change on this file since 3266 was 3266, checked in by vondreele, 5 years ago

change modulated wave type assignments so one for each kind of wave (pos, frac, etc).
implement optional display of PNT data set positions on pole figure plots. Picker displays histo. name.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 32.5 KB
Line 
1# -*- coding: utf-8 -*-
2########### SVN repository information ###################
3# $Date: 2018-02-08 19:31:55 +0000 (Thu, 08 Feb 2018) $
4# $Author: vondreele $
5# $Revision: 3266 $
6# $URL: trunk/imports/G2phase.py $
7# $Id: G2phase.py 3266 2018-02-08 19:31:55Z vondreele $
8########### SVN repository information ###################
9#
10'''
11*Module G2phase: PDB, .EXP & JANA m40,m50*
12-------------------------------------------
13
14A set of short routines to read in phases using routines that were
15previously implemented in GSAS-II: PDB, GSAS .EXP and JANA m40-m50 file formats
16
17'''
18
19from __future__ import division, print_function
20import sys
21import os.path
22import math
23import random as ran
24import numpy as np
25try:
26    import wx
27except ImportError:
28    wx = None
29import GSASIIobj as G2obj
30import GSASIIspc as G2spc
31import GSASIIlattice as G2lat
32import GSASIIpath
33GSASIIpath.SetVersionNumber("$Revision: 3266 $")
34R2pisq = 1./(2.*np.pi**2)
35
36class PDB_ReaderClass(G2obj.ImportPhase):
37    'Routine to import Phase information from a PDB file'
38    def __init__(self):
39        super(self.__class__,self).__init__( # fancy way to say ImportPhase.__init__
40            extensionlist=('.pdb','.ent','.PDB','.ENT'),
41            strictExtension=True,
42            formatName = 'PDB',
43            longFormatName = 'Original Protein Data Bank (.pdb file) import'
44            )
45    def ContentsValidator(self, filename):
46        '''Taking a stab a validating a PDB file
47        (look for cell & at least one atom)
48        '''
49        fp = open(filename,'r')
50        for i,l in enumerate(fp):
51            if l.startswith('CRYST1'):
52                break
53        else:
54            self.errors = 'no CRYST1 record found'
55            fp.close()
56            return False
57        for i,l in enumerate(fp):
58            if l.startswith('ATOM'):
59                fp.close()
60                return True
61        self.errors = 'no ATOM records found after CRYST1 record'
62        fp.close()
63        return False
64
65    def Reader(self,filename, ParentFrame=None, **unused):
66        'Read a PDF file using :meth:`ReadPDBPhase`'
67        self.Phase = self.ReadPDBPhase(filename, ParentFrame)
68        return True
69       
70    def ReadPDBPhase(self,filename,parent=None):
71        '''Read a phase from a PDB file.
72        '''
73        EightPiSq = 8.*math.pi**2
74        self.errors = 'Error opening file'
75        file = open(filename, 'Ur')
76        Phase = {}
77        Title = ''
78        Compnd = ''
79        Atoms = []
80        A = np.zeros(shape=(3,3))
81        S = file.readline()
82        line = 1
83        SGData = None
84        cell = None
85        while S:
86            self.errors = 'Error reading at line '+str(line)
87            Atom = []
88            if 'TITLE' in S[:5]:
89                Title = S[10:72].strip()
90            elif 'COMPND    ' in S[:10]:
91                Compnd = S[10:72].strip()
92            elif 'CRYST' in S[:5]:
93                abc = S[7:34].split()
94                angles = S[34:55].split()
95                cell=[float(abc[0]),float(abc[1]),float(abc[2]),
96                    float(angles[0]),float(angles[1]),float(angles[2])]
97                Volume = G2lat.calc_V(G2lat.cell2A(cell))
98                AA,AB = G2lat.cell2AB(cell)
99                SpGrp = S[55:65]
100                E,SGData = G2spc.SpcGroup(SpGrp)
101                # space group processing failed, try to look up name in table
102                if E:
103                    SpGrpNorm = G2spc.StandardizeSpcName(SpGrp)
104                    if SpGrpNorm:
105                        E,SGData = G2spc.SpcGroup(SpGrpNorm)
106                while E:
107                    dlg = wx.TextEntryDialog(parent,
108                        SpGrp[:-1]+' is invalid \nN.B.: make sure spaces separate axial fields in symbol',
109                        'ERROR in space group symbol','',style=wx.OK)
110                    if dlg.ShowModal() == wx.ID_OK:
111                        SpGrp = dlg.GetValue()
112                        E,SGData = G2spc.SpcGroup(SpGrp)
113                    else:
114                        SGData = G2obj.P1SGData # P 1
115                        self.warnings += '\nThe space group was not interpreted and has been set to "P 1".'
116                        self.warnings += "Change this in phase's General tab."           
117                    dlg.Destroy()
118#                SGlines = G2spc.SGPrint(SGData)
119#                for l in SGlines: print (l)
120            elif 'SCALE' in S[:5]:
121                V = S[10:41].split()
122                A[int(S[5])-1] = [float(V[0]),float(V[1]),float(V[2])]
123            elif 'ATOM' in S[:4] or 'HETATM' in S[:6]:
124                if not SGData:
125                    self.warnings += '\nThe space group was not read before atoms and has been set to "P 1". '
126                    self.warnings += "Change this in phase's General tab."
127                    SGData = G2obj.P1SGData # P 1
128                XYZ = [float(S[31:39]),float(S[39:47]),float(S[47:55])]
129                XYZ = np.inner(AB,XYZ)
130                XYZ = np.where(abs(XYZ)<0.00001,0,XYZ)
131                SytSym,Mult = G2spc.SytSym(XYZ,SGData)[:2]
132                Uiso = float(S[61:67])/EightPiSq
133                Type = S[76:78].lower()
134                Atom = [S[22:27].strip(),S[17:20].upper(),S[20:22],
135                    S[12:17].strip(),Type.strip().capitalize(),'',XYZ[0],XYZ[1],XYZ[2],
136                    float(S[55:61]),SytSym,Mult,'I',Uiso,0,0,0,0,0,0]
137                if S[16] in [' ','A','B']:      #remove disorered residues - can't handle them just now
138#                    Atom[3] = Atom[3][:3]
139                    Atom.append(ran.randint(0,sys.maxsize))
140                    Atoms.append(Atom)
141            elif 'ANISOU' in S[:6]:
142                Uij = S[30:72].split()
143                Uij = [float(Uij[0])/10000.,float(Uij[1])/10000.,float(Uij[2])/10000.,
144                    float(Uij[3])/10000.,float(Uij[4])/10000.,float(Uij[5])/10000.]
145                Atoms[-1] = Atoms[-1][:14]+Uij
146                Atoms[-1][12] = 'A'
147                Atoms[-1].append(ran.randint(0,sys.maxsize))
148            S = file.readline()
149            line += 1
150        file.close()
151        self.errors = 'Error after read complete'
152        if Title:
153            PhaseName = Title
154        elif Compnd:
155            PhaseName = Compnd
156        else:
157            PhaseName = 'None'
158        if not SGData:
159            raise self.ImportException("No space group (CRYST entry) found")
160        if not cell:
161            raise self.ImportException("No cell (CRYST entry) found")
162        Phase = G2obj.SetNewPhase(Name=PhaseName,SGData=SGData,cell=cell+[Volume,])
163        Phase['General']['Type'] = 'macromolecular'
164        Phase['General']['AtomPtrs'] = [6,4,10,12]
165        Phase['Atoms'] = Atoms
166        return Phase
167
168class EXP_ReaderClass(G2obj.ImportPhase):
169    'Routine to import Phase information from GSAS .EXP files'
170    def __init__(self):
171        super(self.__class__,self).__init__( # fancy way to say ImportPhase.__init__
172            extensionlist=('.EXP','.exp'),
173            strictExtension=True,
174            formatName = 'GSAS .EXP',
175            longFormatName = 'GSAS Experiment (.EXP file) import'
176            )
177       
178    def ContentsValidator(self, filename):
179        'Look for a VERSION tag in 1st line' 
180        fp = open(filename,'r')
181        if fp.read(13) == '     VERSION ':
182            fp.close()
183            return True
184        self.errors = 'File does not begin with VERSION tag'
185        fp.close()
186        return False
187
188    def Reader(self,filename,ParentFrame=None,usedRanIdList=[],**unused):
189        'Read a phase from a GSAS .EXP file using :meth:`ReadEXPPhase`'
190        self.Phase = G2obj.SetNewPhase(Name='new phase') # create a new empty phase dict
191        while self.Phase['ranId'] in usedRanIdList:
192            self.Phase['ranId'] = ran.randint(0,sys.maxsize)
193        # make sure the ranId is really unique!
194        self.MPhase = G2obj.SetNewPhase(Name='new phase') # create a new empty phase dict
195        while self.MPhase['ranId'] in usedRanIdList:
196            self.MPhase['ranId'] = ran.randint(0,sys.maxsize)
197        fp = open(filename,'r')
198        self.ReadEXPPhase(ParentFrame, fp)
199        fp.close()
200        return True
201
202    def ReadEXPPhase(self, G2frame,filepointer):
203        '''Read a phase from a GSAS .EXP file.
204        '''
205        shModels = ['cylindrical','none','shear - 2/m','rolling - mmm']
206        textureData = {'Order':0,'Model':'cylindrical','Sample omega':[False,0.0],
207            'Sample chi':[False,0.0],'Sample phi':[False,0.0],'SH Coeff':[False,{}],
208            'SHShow':False,'PFhkl':[0,0,1],'PFxyz':[0,0,1],'PlotType':'Pole figure'}
209        shNcof = 0
210        S = 1
211        NPhas = []
212        Expr = [{},{},{},{},{},{},{},{},{}] # GSAS can have at most 9 phases
213        for line,S in enumerate(filepointer):
214            self.errors = 'Error reading at line '+str(line+1)
215            if 'EXPR NPHAS' in S[:12]:
216                NPhas = S[12:-1].split()
217            if 'CRS' in S[:3]:
218                N = int(S[3:4])-1
219                Expr[N][S[:12]] = S[12:-1]
220        PNames = []
221        if not NPhas:
222            raise self.ImportException("No EXPR NPHAS record found")
223        self.errors = 'Error interpreting file'
224        for n,N in enumerate(NPhas):
225            if N != '0':
226                result = n
227                key = 'CRS'+str(n+1)+'    PNAM'
228                PNames.append(Expr[n][key])
229        if len(PNames) == 0:
230            raise self.ImportException("No phases found")           
231        elif len(PNames) > 1:
232            dlg = wx.SingleChoiceDialog(G2frame, 'Which phase to read?', 'Read phase data', PNames, wx.CHOICEDLG_STYLE)
233            try:
234                if dlg.ShowModal() == wx.ID_OK:
235                    result = dlg.GetSelection() # I think this breaks is there are skipped phases. Cant this happen?
236            finally:
237                dlg.Destroy()       
238        EXPphase = Expr[result]
239        keyList = list(EXPphase.keys())
240        keyList.sort()
241        SGData = {}
242        MPtype = ''
243        if NPhas[result] == '1':
244            Ptype = 'nuclear'
245        elif NPhas[result] =='2':
246            Ptype = 'nuclear'
247            MPtype = 'magnetic'
248            MagDmin = 1.0
249        elif NPhas[result] =='3':
250            Ptype = 'magnetic'
251            MagDmin = 1.0
252        elif NPhas[result] == '4':
253            Ptype = 'macromolecular'
254        elif NPhas[result] == '10':
255            Ptype = 'Pawley'
256        else:
257            raise self.ImportException("Phase type not recognized") 
258           
259        for key in keyList:
260            if 'PNAM' in key:
261               PhaseName = EXPphase[key].strip()
262            elif 'ABC   ' in key:
263                abc = [float(EXPphase[key][:10]),float(EXPphase[key][10:20]),float(EXPphase[key][20:30])]                       
264            elif 'ANGLES' in key:
265                angles = [float(EXPphase[key][:10]),float(EXPphase[key][10:20]),float(EXPphase[key][20:30])]                                               
266            elif 'SG SYM' in key:
267                SpGrp = EXPphase[key][:15].strip()
268                E,SGData = G2spc.SpcGroup(SpGrp)
269                if E:
270                    SGData = G2obj.P1SGData # P 1 -- unlikely to need this!
271                    self.warnings += '\nThe GSAS space group was not interpreted(!) and has been set to "P 1".'
272                    self.warnings += "Change this in phase's General tab."                       
273            elif 'SPNFLP' in key:
274                SpnFlp = np.array([int(float(s)) for s in EXPphase[key].split()])
275                SpnFlp = np.where(SpnFlp==0,1,SpnFlp)
276                if SGData['SpGrp'][0] in ['A','B','C','I','R','F']:
277                    SpnFlp = list(SpnFlp)+[1,1,1,1]
278            elif 'MXDSTR' in key:
279                MagDmin = float(EXPphase[key][:10])               
280            elif 'OD    ' in key:
281                SHdata = EXPphase[key].split() # may not have all 9 values
282                SHvals = 9*[0]
283                for i in range(9):
284                    try:
285                        float(SHdata[i])
286                        SHvals[i] = SHdata[i]
287                    except:
288                        pass
289                textureData['Order'] = int(SHvals[0])
290                textureData['Model'] = shModels[int(SHvals[2])]
291                textureData['Sample omega'] = [False,float(SHvals[6])]
292                textureData['Sample chi'] = [False,float(SHvals[7])]
293                textureData['Sample phi'] = [False,float(SHvals[8])]
294                shNcof = int(SHvals[1])
295        Volume = G2lat.calc_V(G2lat.cell2A(abc+angles))
296
297        Atoms = []
298        MAtoms = []
299        Bmat = G2lat.cell2AB(abc+angles)[1]
300        if Ptype == 'macromolecular':
301            for key in keyList:
302                if 'AT' in key[6:8]:
303                    S = EXPphase[key]
304                    Atom = [S[56:60].strip(),S[50:54].strip().upper(),S[54:56],
305                        S[46:51].strip(),S[:8].strip().capitalize(),'',
306                        float(S[16:24]),float(S[24:32]),float(S[32:40]),
307                        float(S[8:16]),'1',1,'I',float(S[40:46]),0,0,0,0,0,0]
308                    XYZ = Atom[6:9]
309                    Atom[10],Atom[11] = G2spc.SytSym(XYZ,SGData)[:2]
310                    Atom.append(ran.randint(0,sys.maxsize))
311                    Atoms.append(Atom)
312        else:
313            for key in keyList:
314                if 'AT' in key:
315                    if key[11:] == 'A':
316                        S = EXPphase[key]
317                    elif key[11:] == 'B':
318                        S1 = EXPphase[key]
319                        Atom = [S[50:58].strip(),S[:10].strip().capitalize(),'',
320                            float(S[10:20]),float(S[20:30]),float(S[30:40]),
321                            float(S[40:50]),'',int(S[60:62]),S1[62:63]]
322                            #float(S[40:50]),'',int(S[60:62]),S1[130:131]]
323                        if Atom[9] == 'I':
324                            Atom += [float(S1[0:10]),0.,0.,0.,0.,0.,0.]
325                        elif Atom[9] == 'A':
326                            Atom += [0.0,
327                                float(S1[ 0:10]),float(S1[10:20]),
328                                float(S1[20:30]),float(S1[30:40]),
329                                float(S1[40:50]),float(S1[50:60])]
330                        else:
331                            print('Error in line with key: '+key)
332                            Atom += [0.,0.,0.,0.,0.,0.,0.]
333                        XYZ = Atom[3:6]
334                        Atom[7],Atom[8] = G2spc.SytSym(XYZ,SGData)[:2]
335                        Atom.append(ran.randint(0,sys.maxsize))
336                        Atoms.append(Atom)
337                    elif key[11:] == 'M' and key[6:8] == 'AT':
338                        S = EXPphase[key]
339                        mom = np.array([float(S[:10]),float(S[10:20]),float(S[20:30])])
340                        mag = np.sqrt(np.sum(mom**2))
341                        mom = np.inner(Bmat,mom)*mag
342                        MAtoms.append(Atom)
343                        MAtoms[-1] = Atom[:7]+list(mom)+Atom[7:]
344                       
345        if shNcof:
346            shCoef = {}
347            nRec = [i+1 for i in range((shNcof-1)//6+1)]
348            for irec in nRec:
349                ODkey = keyList[0][:6]+'OD'+'%3dA'%(irec)
350                indx = EXPphase[ODkey].split()
351                ODkey = ODkey[:-1]+'B'
352                vals = EXPphase[ODkey].split()
353                for i,val in enumerate(vals):
354                    key = 'C(%s,%s,%s)'%(indx[3*i],indx[3*i+1],indx[3*i+2])
355                    shCoef[key] = float(val)
356            textureData['SH Coeff'] = [False,shCoef]
357           
358        if not SGData:
359            raise self.ImportException("No space group found in phase")
360        if not abc:
361            raise self.ImportException("No cell lengths found in phase")
362        if not angles:
363            raise self.ImportException("No cell angles found in phase")
364        if not Atoms:
365            raise self.ImportException("No atoms found in phase")
366           
367        self.Phase['General'].update({'Type':Ptype,'Name':PhaseName,'Cell':[False,]+abc+angles+[Volume,],'SGData':SGData})
368        if MPtype == 'magnetic':
369            self.MPhase['General'].update({'Type':'magnetic','Name':PhaseName+' mag','Cell':[False,]+abc+angles+[Volume,],'SGData':SGData})
370        else:
371            self.MPhase = None
372           
373        if Ptype =='macromolecular':
374            self.Phase['General']['AtomPtrs'] = [6,4,10,12]
375            self.Phase['Atoms'] = Atoms
376        elif Ptype == 'magnetic':
377            self.Phase['General']['AtomPtrs'] = [3,1,10,12]
378            self.Phase['General']['SGData']['SGSpin'] = SpnFlp
379            self.Phase['General']['MagDmin'] = MagDmin
380            self.Phase['Atoms'] = MAtoms           
381        else:   #nuclear
382            self.Phase['General']['AtomPtrs'] = [3,1,7,9]   
383            self.Phase['General']['SH Texture'] = textureData
384            self.Phase['Atoms'] = Atoms
385        if MPtype =='magnetic':
386            self.MPhase['General']['AtomPtrs'] = [3,1,10,12]
387            self.MPhase['General']['SGData']['SGSpin'] = SpnFlp
388            self.MPhase['General']['MagDmin'] = MagDmin
389            self.MPhase['Atoms'] = MAtoms
390
391class JANA_ReaderClass(G2obj.ImportPhase):
392    'Routine to import Phase information from a JANA2006 file'
393    def __init__(self):
394        super(self.__class__,self).__init__( # fancy way to say ImportPhase.__init__
395            extensionlist=('.m50','.M50'),
396            strictExtension=True,
397            formatName = 'JANA m50',
398            longFormatName = 'JANA2006 phase import'
399            )
400    def ContentsValidator(self, filename):
401        '''Taking a stab a validating a .m50 file
402        (look for cell & at least one atom)
403        '''
404        fp = open(filename,'r')
405        for i,l in enumerate(fp):
406            if l.startswith('cell'):
407                break
408        else:
409            self.errors = 'no cell record found'
410            fp.close()
411            return False
412        for i,l in enumerate(fp):
413            if l.startswith('spgroup'):
414                fp.close()
415                return True
416        self.errors = 'no spgroup record found after cell record'
417        fp.close()
418        return False
419       
420    def Reader(self,filename, ParentFrame=None, **unused):
421        'Read a m50 file using :meth:`ReadJANAPhase`'
422        self.Phase = self.ReadJANAPhase(filename, ParentFrame)
423        return True
424       
425    def ReadJANAPhase(self,filename,parent=None):
426        '''Read a phase from a JANA2006 m50 & m40 files.
427        '''
428        self.errors = 'Error opening file'
429        fp = open(filename, 'Ur') #contains only cell & spcgroup
430        Phase = {}
431        Title = os.path.basename(filename)
432        Type = 'nuclear'
433        Atoms = []
434        Atypes = []
435        SuperVec = [[0,0,.1],False,4]
436        S = fp.readline()
437        line = 1
438        SGData = None
439        SuperSg = ''
440        cell = None
441        nqi = 0
442        version = '2000'
443        while S:
444            self.errors = 'Error reading at line '+str(line)
445            if 'title' in S and S != 'title\n':
446                Title = S.split()[1]
447            elif 'Jana2006' in S:
448                self.warnings += '\nJana2006 file detected'
449                version = '2006'
450            elif 'cell' in S[:4]:
451                cell = S[5:].split()
452                cell=[float(cell[0]),float(cell[1]),float(cell[2]),
453                    float(cell[3]),float(cell[4]),float(cell[5])]
454                Volume = G2lat.calc_V(G2lat.cell2A(cell))
455                G,g = G2lat.cell2Gmat(cell)
456                ast = np.sqrt(np.diag(G))
457                Mast = np.multiply.outer(ast,ast)   
458               
459            elif 'spgroup' in S:
460                if 'X' in S:
461                    raise self.ImportException("Ad hoc Supersymmetry centering "+S+" not allowed in GSAS-II")           
462                SpGrp = S.split()[1]
463                SuperSg = ''
464                if '(' in SpGrp:    #supercell symmetry - split in 2
465                    SuperStr = SpGrp.split('(')
466                    SpGrp = SuperStr[0]
467                    SuperSg = '('+SuperStr[1]
468                SpGrpNorm = G2spc.StandardizeSpcName(SpGrp)
469                E,SGData = G2spc.SpcGroup(SpGrpNorm)
470                # space group processing failed, try to look up name in table
471                while E:
472                    print (G2spc.SGErrors(E))
473                    dlg = wx.TextEntryDialog(parent,
474                        SpGrp[:-1]+' is invalid \nN.B.: make sure spaces separate axial fields in symbol',
475                        'ERROR in space group symbol','',style=wx.OK)
476                    if dlg.ShowModal() == wx.ID_OK:
477                        SpGrp = dlg.GetValue()
478                        E,SGData = G2spc.SpcGroup(SpGrp)
479                    else:
480                        SGData = G2obj.P1SGData # P 1
481                        self.warnings += '\nThe space group was not interpreted and has been set to "P 1".'
482                        self.warnings += "Change this in phase's General tab."           
483                    dlg.Destroy()
484                G2spc.SGPrint(SGData) #silent check of space group symbol
485            elif 'qi' in S[:2]:
486                if nqi:
487                    raise self.ImportException("Supersymmetry too high; GSAS-II limited to (3+1) supersymmetry")           
488                vec = S.split()[1:]
489                SuperVec = [[float(vec[i]) for i in range(3)],False,4]
490                nqi += 1
491            elif 'atom' in S[:4]:
492                Atypes.append(S.split()[1])
493            S = fp.readline()
494            line += 1
495        fp.close()
496        #read atoms from m40 file
497        if not SGData:
498            self.warnings += '\nThe space group was not read before atoms and has been set to "P 1". '
499            self.warnings += "Change this in phase's General tab."
500            SGData = G2obj.P1SGData # P 1
501        waveTypes = ['Fourier','Sawtooth','ZigZag',]
502        filename2 = os.path.splitext(filename)[0]+'.m40'
503        file2 = open(filename2,'Ur')
504        S = file2.readline()
505        line = 1
506        self.errors = 'Error reading at line '+str(line)
507        nAtoms = int(S.split()[0])
508        for i in range(4):
509            S = file2.readline()           
510        for i in range(nAtoms):
511            S1 = file2.readline()
512            S1N = S1.split()[-3:]   # no. occ, no. pos waves, no. ADP waves
513            S1N = [int(i) for i in S1N]
514            S1T = list(S1[60:63])
515            waveType = waveTypes[int(S1T[1])]
516            Spos = []
517            Sadp = []
518            Sfrac = []
519            Smag = []
520            XYZ = [float(S1[27:36]),float(S1[36:45]),float(S1[45:54])]
521            SytSym,Mult = G2spc.SytSym(XYZ,SGData)[:2]
522            aType = Atypes[int(S1[9:11])-1]
523            Name = S1[:8].strip()
524            if S1[11:15].strip() == '1':
525                S2 = file2.readline()
526                Uiso = S2[:9]
527                if version == '2000':
528                    Uiso = R2pisq*float(Uiso)/4.      #Biso -> Uiso
529                Uij = [0,0,0,0,0,0]
530                IA = 'I'
531            elif S1[11:15].strip() == '2':
532                S2 = file2.readline()
533                IA = 'A'
534                Uiso = 0.
535                Uij = [float(S2[:9]),float(S2[9:18]),float(S2[18:27]),
536                    float(S2[27:36]),float(S2[36:45]),float(S2[45:54])] #Uij in Jana2006!
537                if version == '2000':
538                    Uij = R2pisq*G2lat.UijtoU6(G2lat.U6toUij(Uij)/Mast) #these things are betaij in Jana2000! need to convert to Uij
539            for i in range(S1N[0]):
540                if not i:
541                    FS = file2.readline()
542                    Sfrac.append(FS[:9])    #'O' or 'delta' = 'length' for crenel
543                    if int(S1T[0]):  #"", "Legendre" or "Xharm" in 18:27 for "crenel"!
544                        waveType = 'Crenel/Fourier' #all waves 'Fourier' no other choice
545                Sfrac.append(file2.readline()[:18]) #if not crenel = Osin & Ocos
546                # else Osin & Ocos except last one is X40 = 'Center'
547            for i in range(S1N[1]): 
548                Spos.append(file2.readline()[:54])
549            for i in range(S1N[2]):
550                Sadp.append(file2.readline()[:54]+file2.readline())
551            if sum(S1N):    #if any waves: skip mystery line?
552                file2.readline()
553            for i,it in enumerate(Sfrac):
554                print (i,it)
555                if not i:
556                    if 'Crenel' in waveType:
557                        vals = [float(it),float(Sfrac[-1][:9])]
558                    else:
559                        vals = [float(it),]
560                else:
561                    vals = [float(it[:9]),float(it[9:18])]
562                if 'Crenel' in waveType and i == len(Sfrac)-1:
563                    del Sfrac[-1]
564                    break               
565                Sfrac[i] = [vals,False]
566                print (Sfrac[i])
567            for i,it in enumerate(Spos):
568                if waveType in ['Sawtooth',] and not i:
569                    vals = [float(it[:9]),float(it[9:18]),float(it[18:27]),float(it[27:36])]
570                else:
571                    vals = [float(it[:9]),float(it[9:18]),float(it[18:27]),float(it[27:36]),float(it[36:45]),float(it[45:54])]
572                Spos[i] = [vals,False]
573            for i,it in enumerate(Sadp):
574                vals = [float(it[:9]),float(it[9:18]),float(it[18:27]),float(it[27:36]),float(it[36:45]),float(it[45:54]),
575                    float(it[54:63]),float(it[63:72]),float(it[72:81]),float(it[81:90]),float(it[90:99]),float(it[99:108])]
576                #these are betaij modulations in Jana2000! need to convert to Uij modulations
577                if version == '2000':               
578                    vals[:6] = R2pisq*G2lat.UijtoU6(G2lat.U6toUij(vals[:6])/Mast)    #convert sin bij to Uij
579                    vals[6:] = R2pisq*G2lat.UijtoU6(G2lat.U6toUij(vals[6:])/Mast)    #convert cos bij to Uij
580                Sadp[i] = [vals,False]
581            Atom = [Name,aType,'',XYZ[0],XYZ[1],XYZ[2],1.0,SytSym,Mult,IA,Uiso]
582            Atom += Uij
583            Atom.append(ran.randint(0,sys.maxsize))
584            Atom.append([])
585            Atom.append([])
586            Atom.append({'SS1':{'Sfrac':[waveType,]+Sfrac,'Spos':[waveType,]+Spos,'Sadp':['Fourier',]+Sadp,'Smag':['Fourier',]+Smag}})    #SS2 is for (3+2), etc.
587            Atoms.append(Atom)
588        file2.close()
589        self.errors = 'Error after read complete'
590        if not SGData:
591            raise self.ImportException("No space group (spcgroup entry) found")
592        if not cell:
593            raise self.ImportException("No cell found")
594        Phase = G2obj.SetNewPhase(Name=Title,SGData=SGData,cell=cell+[Volume,])
595        Phase['General']['Type'] = Type
596        Phase['General']['Modulated'] = True
597        Phase['General']['Super'] = nqi
598        Phase['General']['SuperVec'] = SuperVec
599        Phase['General']['SuperSg'] = SuperSg
600        if SuperSg:
601            Phase['General']['SSGData'] = G2spc.SSpcGroup(SGData,SuperSg)[1]
602        Phase['General']['AtomPtrs'] = [3,1,7,9]
603        Phase['Atoms'] = Atoms
604        return Phase
605   
606class PDF_ReaderClass(G2obj.ImportPhase):
607    'Routine to import Phase information from ICDD PDF Card files'
608    def __init__(self):
609        super(self.__class__,self).__init__( # fancy way to say ImportPhase.__init__
610            extensionlist=('.str',),
611            strictExtension=True,
612            formatName = 'ICDD .str',
613            longFormatName = 'ICDD PDF Card (.str file) import'
614            )
615       
616    def ContentsValidator(self, filename):
617        'Look for a str tag in 1st line' 
618        fp = open(filename,'r')
619        if fp.read(3) == 'str':
620            fp.close()
621            return True
622        self.errors = 'File does not begin with str tag'
623        fp.close()
624        return False
625
626    def Reader(self,filename, ParentFrame=None, **unused):
627        'Read phase from a ICDD .str file using :meth:`ReadPDFPhase`'
628        fp = open(filename,'r')
629        self.Phase = self.ReadPDFPhase(ParentFrame, fp)
630        fp.close()
631        return True
632
633    def ReadPDFPhase(self, G2frame,fp):
634        '''Read a phase from a ICDD .str file.
635        '''
636        EightPiSq = 8.*math.pi**2
637        self.errors = 'Error opening file'
638        Phase = {}
639        Atoms = []
640        S = fp.readline()
641        line = 1
642        SGData = None
643        cell = []
644        cellkey = []
645        while S:
646            if 'space_group' in S:
647                break
648            S = fp.readline()                   
649        while S:
650            self.errors = 'Error reading at line '+str(line)
651            if 'phase_name' in S:
652                Title = S.split('"')[1]
653            elif 'Space group (HMS)' in S:
654                SpGrp = S.split()[-1]
655                SpGrpNorm = G2spc.StandardizeSpcName(SpGrp)
656                E,SGData = G2spc.SpcGroup(SpGrpNorm)
657                # space group processing failed, try to look up name in table
658                while E:
659                    print (G2spc.SGErrors(E))
660                    dlg = wx.TextEntryDialog(G2frame,
661                        SpGrp[:-1]+' is invalid \nN.B.: make sure spaces separate axial fields in symbol',
662                        'ERROR in space group symbol','',style=wx.OK)
663                    if dlg.ShowModal() == wx.ID_OK:
664                        SpGrp = dlg.GetValue()
665                        E,SGData = G2spc.SpcGroup(SpGrp)
666                    else:
667                        SGData = G2obj.P1SGData # P 1
668                        self.warnings += '\nThe space group was not interpreted and has been set to "P 1".'
669                        self.warnings += "Change this in phase's General tab."           
670                    dlg.Destroy()
671                G2spc.SGPrint(SGData) #silent check of space group symbol
672            elif 'a a_' in S[:7]:
673                data = S.split()
674                cell.append(float(data[2]))
675                cellkey.append(data[1])
676            elif 'b b_' in S[:7]:
677                data = S.split()
678                cell.append(float(data[2]))
679                cellkey.append(data[1])
680            elif 'b =' in S[:6]:
681                data = S.split('=')
682                indx = cellkey.index(data[1].split(';')[0])
683                cell.append(cell[indx])
684            elif 'c c_' in S[:7]:
685                data = S.split()
686                cell.append(float(data[2]))
687            elif 'c =' in S[:6]:
688                data = S.split('=')
689                indx = cellkey.index(data[1].split(';')[0])
690                cell.append(cell[indx])
691            elif 'al' in S[:5]:
692                cell.append(float(S.split()[1]))
693            elif 'be' in S[:5]:
694                cell.append(float(S.split()[1]))
695            elif 'ga' in S[:5]:
696                cell.append(float(S.split()[1]))
697                Volume = G2lat.calc_V(G2lat.cell2A(cell))
698                break
699            S = fp.readline()
700        S = fp.readline()
701        while S:
702            if '/*' in S[:5]:
703                break
704            if 'site' in S[:7]:
705                atom = []
706                xyzkey = []
707                data = S.split()
708                atom.append(data[1])    #name
709                pos = data.index('occ')+1
710                atom.append(data[pos])  #type
711                atom.append('')         #refine
712                for xid in ['x =','y =','z =']:
713                    if xid in S:
714                        xpos = S.index(xid)+3
715                        xend = xpos+S[xpos:].index(';')
716                        if S[xpos:xend] in xyzkey:
717                            atom.append(atom[3+xyzkey.index(S[xpos:xend])])
718                        else:
719                            atom.append(eval(S[xpos:xend]+'.'))
720                    else:
721                        xpos = data.index(xid[0])+2
722                        xyzkey.append(data[xpos-1][1:])
723                        atom.append(float(data[xpos]))
724                atom.append(float(data[pos+2]))
725                SytSym,Mult = G2spc.SytSym(np.array(atom[3:6]),SGData)[:2]
726                atom.append(SytSym)
727                atom.append(Mult)
728                if 'beq' in S:
729                    atom.append('I')
730                    upos = data.index('beq')
731                    atom.append(float(data[upos+2])/EightPiSq)
732                    atom += [0.,0.,0.,0.,0.,0.,]
733                elif 'ADPs' in S:
734                    upos = data.index('ADPs')
735                    atom.append('A')
736                    atom.append(0.0)
737                    for uid in ['Bani11','Bani22','Bani33','Bani12','Bani13','Bani23']:
738                        upos = data.index(uid)+1
739                        atom.append(float(data[upos])/EightPiSq)
740                else:
741                    atom.append('I')
742                    atom += [0.02,0.,0.,0.,0.,0.,0.,]                   
743                atom.append(ran.randint(0,sys.maxsize))
744                Atoms.append(atom)
745            S = fp.readline()               
746        fp.close()
747        self.errors = 'Error after read complete'
748        if not SGData:
749            raise self.ImportException("No space group (spcgroup entry) found")
750        if not cell:
751            raise self.ImportException("No cell found")
752        Phase = G2obj.SetNewPhase(Name=Title,SGData=SGData,cell=cell+[Volume,])
753        Phase['General']['Type'] = 'nuclear'
754        Phase['General']['AtomPtrs'] = [3,1,7,9]
755        Phase['Atoms'] = Atoms
756        return Phase
Note: See TracBrowser for help on using the repository browser.