source: trunk/imports/G2phase_INS.py @ 3136

Last change on this file since 3136 was 3136, checked in by vondreele, 4 years ago

make GSAS-II python 3.6 compliant & preserve python 2.7 use;changes:
do from future import division, print_function for all GSAS-II py sources
all menu items revised to be py 2.7/3.6 compliant
all wx.OPEN --> wx.FD_OPEN in file dialogs
all integer divides (typically for image pixel math) made explicit with ; ambiguous ones made floats as appropriate
all print "stuff" --> print (stuff)
all print >> pFile,'stuff' --> pFile.writeCIFtemplate('stuff')
all read file opens made explicit 'r' or 'rb'
all cPickle imports made for py2.7 or 3.6 as cPickle or _pickle; test for '2' platform.version_tuple[0] for py 2.7
define cPickleload to select load(fp) or load(fp,encoding='latin-1') for loading gpx files; provides cross compatibility between py 2.7/3.6 gpx files
make dict.keys() as explicit list(dict.keys()) as needed (NB: possible source of remaining py3.6 bugs)
make zip(a,b) as explicit list(zip(a,b)) as needed (NB: possible source of remaining py3.6 bugs)
select unichr/chr according test for '2' platform.version_tuple[0] for py 2.7 (G2pwdGUI * G2plot) for special characters
select wg.EVT_GRID_CELL_CHANGE (classic) or wg.EVT_GRID_CELL_CHANGED (phoenix) in grid Bind
maxint --> maxsize; used in random number stuff
raise Exception,"stuff" --> raise Exception("stuff")
wx 'classic' sizer.DeleteWindows?() or 'phoenix' sizer.Clear(True)
wx 'classic' SetToolTipString?(text) or 'phoenix' SetToolTip?(wx.ToolTip?(text)); define SetToolTipString?(self,text) to handle the choice in plots
status.SetFields? --> status.SetStatusText?
'classic' AddSimpleTool? or 'phoenix' self.AddTool? for plot toolbar; Bind different as well
define GetItemPydata? as it doesn't exist in wx 'phoenix'
allow python versions 2.7 & 3.6 to run GSAS-II
Bind override commented out - no logging capability (NB: remove all logging code?)
all import ContentsValidator? open filename & test if valid then close; filepointer removed from Reader
binary importers (mostly images) test for 'byte' type & convert as needed to satisfy py 3.6 str/byte rules

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