source: trunk/imports/G2phase_INS.py @ 2470

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

magnetic structure editing/drawing work - includes site symm restrictions

File size: 6.5 KB
Line 
1# -*- coding: utf-8 -*-
2########### SVN repository information ###################
3# $Date: 2015-04-27 13:22:06 -0500 (Mon, 27 Apr 2015) $
4# $Author: vondreele $
5# $Revision: 1812 $
6# $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/imports/G2phase_GPX.py $
7# $Id: G2phase_GPX.py 1812 2015-04-27 18:22:06Z vondreele $
8########### SVN repository information ###################
9'''
10*Module G2phase_INS: Import phase from SHELX INS file*
11--------------------------------------------------------
12
13Copies a phase from SHELX ins file into the
14current project.
15
16'''
17import sys
18import traceback
19import math
20import numpy as np
21import random as ran
22import GSASIIIO as G2IO
23import GSASIIspc as G2spc
24import GSASIIlattice as G2lat
25import GSASIIpath
26GSASIIpath.SetVersionNumber("$Revision: 1812 $")
27
28class PhaseReaderClass(G2IO.ImportPhase):
29    'Opens a .INS file and pulls out a selected phase'
30    def __init__(self):
31        super(self.__class__,self).__init__( # fancy way to say ImportPhase.__init__
32            extensionlist=('.ins','.INS','.res','.RES'),
33            strictExtension=True,
34            formatName = 'SHELX ins, res',
35            longFormatName = 'SHELX input (*.ins, *.res) file import'
36            )
37       
38    def ContentsValidator(self, filepointer):
39        "Test if the ins file has a CELL record"
40        for i,l in enumerate(filepointer):
41            if l.startswith('CELL'):
42                break
43        else:
44            self.errors = 'no CELL record found'
45            self.errors = 'This is not a valid .ins file.'
46            return False
47        return True
48
49    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
50        'Read a ins file using :meth:`ReadINSPhase`'
51        try:
52            self.Phase = self.ReadINSPhase(filename, ParentFrame)
53            return True
54        except Exception as detail:
55            self.errors += '\n  '+str(detail)
56            print 'INS read error:',detail # for testing
57            traceback.print_exc(file=sys.stdout)
58            return False
59
60    def ReadINSPhase(self,filename,parent=None):
61        '''Read a phase from a INS file.
62        '''
63        Shelx = ['TITL','CELL','ZERR','LATT','SYMM','SFAC','DISP','UNIT','LAUE','EADP',
64            'MORE','TIME','END ','HKLF','OMIT','SHEL','BASF','TWIN','EXTI','SWAT',
65            'HOPE','MERG','SPEC','RESI','RTAB','MPLA','HFIX','MOVE','ANIS','AFIX',
66            'FRAG','FEND','EXYZ','EDAP','EQIV','CONN','PART','BIND','FREE','DFIX','DANG',
67            'BUMP','SAME','SADI','CHIV','FLAT','DELU','SIMU','DEFS','ISOR','NCSY',
68            'SUMP','L.S.','CGLS','BLOC','DAMP','STIR','WGHT','FVAR','BOND','CONF','MPLA',
69            'HTAB','LIST','ACTA','SIZE','TEMP','WPDB','FMAP','GRID','PLAN','MOLE']
70        EightPiSq = 8.*math.pi**2
71        self.errors = 'Error opening file'
72        file = open(filename, 'Ur')
73        Phase = {}
74        Title = ''
75        Compnd = ''
76        Atoms = []
77        aTypes = []
78        A = np.zeros(shape=(3,3))
79        S = file.readline()
80        line = 1
81        SGData = None
82        cell = None
83        numbs = [str(i) for i in range(10)]
84        while S:
85            if '!' in S:
86                S = S.split('!')[0]
87            self.errors = 'Error reading at line '+str(line)
88            Atom = []
89            Aindx = [ch in numbs for ch in S[:4]]   #False for all letters
90            if 'TITL' in S[:4].upper():
91                Title = S[4:72].strip()
92            elif not S.strip():
93                pass
94            elif 'CELL' in S[:4].upper():
95                cellRec = S.split()
96                abc = cellRec[2:5]
97                angles = cellRec[5:8]
98                cell=[float(abc[0]),float(abc[1]),float(abc[2]),
99                    float(angles[0]),float(angles[1]),float(angles[2])]
100                Volume = G2lat.calc_V(G2lat.cell2A(cell))
101                AA,AB = G2lat.cell2AB(cell)
102                SpGrp = 'P 1'
103                SGData = G2IO.SGData # P 1
104                self.warnings += '\nThe space group is not given in an ins file and has been set to "P 1".'
105                self.warnings += "\nChange this in phase's General tab; NB: it might be in the Phase name."
106            elif S[:4].upper() in 'SFAC':
107                aTypes = S[4:].split()
108                if 'H' in aTypes:
109                    self.warnings += '\n\nHydrogen atoms found; consider replacing them with stereochemically tied ones'
110                    self.warnings += '\nas Shelx constraints & HFIX commands are ignored.'
111                    self.warnings += "\nDo 'Edit/Insert H atoms' in this phase's Atoms tab after deleting the old ones."
112            elif S[0] == 'Q':
113                pass
114            elif '\x1a' in S[:4]:
115                pass
116            elif S[:3].upper() == 'REM':
117                pass
118            elif S[:4].upper() not in Shelx:   #this will find an atom record!
119                AtRec = S.split()
120                Atype = aTypes[int(AtRec[1])-1]
121                Aname = AtRec[0]
122                Afrac = abs(float(AtRec[5]))%10.
123                x,y,z = AtRec[2:5]
124                XYZ = np.array([float(x),float(y),float(z)])
125                XYZ = np.where(np.abs(XYZ)<0.00001,0,XYZ)
126                SytSym,Mult = G2spc.SytSym(XYZ,SGData)[:2]
127                if '=' not in S:
128                    IA = 'I'
129                    Uiso = float(AtRec[6])
130                    if Uiso < 0. or Uiso > 1.0:
131                        Uiso = 0.025
132                    Uij = [0. for i in range(6)]
133                else:
134                    IA = 'A'
135                    Uiso = 0.
136                    Ustr = AtRec[6:8]
137                    S = file.readline()
138                    if '!' in S:
139                        S = S.split('!')[0]
140                    AtRec = S.split()
141                    line += 1
142                    Ustr += AtRec
143                    Uij = [float(Ustr[i]) for i in range(6)]
144                    Uij = Uij[0:3]+[Uij[5],Uij[4],Uij[3]]
145                Atom = [Aname,Atype,'',XYZ[0],XYZ[1],XYZ[2],Afrac,SytSym,Mult,IA,Uiso]
146                Atom += Uij
147                Atom.append(ran.randint(0,sys.maxint))
148                Atoms.append(Atom)
149            S = file.readline()
150            line += 1
151        file.close()
152        self.errors = 'Error after read complete'
153        Phase = G2IO.SetNewPhase(Name='ShelX phase',SGData=SGData,cell=cell+[Volume,])
154        Phase['General']['Name'] = Title
155        Phase['General']['Type'] = 'nuclear'
156        Phase['General']['AtomPtrs'] = [3,1,7,9]
157        Phase['Atoms'] = Atoms
158        return Phase
Note: See TracBrowser for help on using the repository browser.