source: trunk/exports/G2export_shelx.py @ 3465

Last change on this file since 3465 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

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 4.9 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3########### SVN repository information ###################
4# $Date: 2017-10-23 16:39:16 +0000 (Mon, 23 Oct 2017) $
5# $Author: vondreele $
6# $Revision: 3136 $
7# $URL: trunk/exports/G2export_shelx.py $
8# $Id: G2export_shelx.py 3136 2017-10-23 16:39:16Z vondreele $
9########### SVN repository information ###################
10'''
11*Module G2export_shelx: Examples*
12-------------------------------------------
13
14Code to export coordinates in the SHELX .ins format
15(as best as I can makes sense of it).
16
17'''
18from __future__ import division, print_function
19import os.path
20import GSASIIpath
21GSASIIpath.SetVersionNumber("$Revision: 3136 $")
22import GSASIIIO as G2IO
23import GSASIIspc as G2spc
24
25class ExportPhaseShelx(G2IO.ExportBaseclass):
26    '''Used to create a SHELX .ins file for a phase
27
28    :param wx.Frame G2frame: reference to main GSAS-II frame
29    '''
30    def __init__(self,G2frame):
31        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
32            G2frame=G2frame,
33            formatName = 'SHELX .ins',
34            extension='.ins',
35            longFormatName = 'Export phase as SHELX .ins file'
36            )
37        self.exporttype = ['phase']
38        self.multiple = True
39
40    def Exporter(self,event=None):
41        '''Export as a SHELX .ins file
42        '''
43        import re
44        # the export process starts here
45        self.InitExport(event)
46        # load all of the tree into a set of dicts
47        self.loadTree()
48        # create a dict with refined values and their uncertainties
49        self.loadParmDict()
50        if self.ExportSelect(): return  # set export parameters;
51        filename = self.filename
52        for phasenam in self.phasenam:
53            phasedict = self.Phases[phasenam] # pointer to current phase info           
54            i = self.Phases[phasenam]['pId']
55            if len(self.phasenam) > 1: # if more than one filename is included, add a phase #
56                self.filename = os.path.splitext(filename)[1] + "_" + str(i) + self.extension
57            fp = self.OpenFile()
58            # title line
59            self.Write("TITL from "+str(self.G2frame.GSASprojectfile)+", phase "+str(phasenam))
60            # get & write cell parameters
61            cell,sig = self.GetCell(phasenam)
62            self.Write("CELL 0.5 {:.5f} {:.5f} {:.5f} {:.3f} {:.3f} {:.3f}".format(*cell[:6]))
63            # Shelx lattice number
64            lattnum = {'P':1,'I':2,'R':2,'F':3,'A':4,'B':5,'C':6}.get(phasedict['General']['SGData']['SGLatt'],0)
65            if not phasedict['General']['SGData']['SGInv']: lattnum *= -1
66            self.Write("LATT "+str(lattnum))
67            # generate symmetry operations not including centering and center of symmetry
68            for Opr in phasedict['General']['SGData']['SGOps']:
69                sym = G2spc.MT2text(Opr).lower().replace(" ,",", ")
70                self.Write('SYMM '+G2IO.trim(sym))
71            # scan through atom types, count the number of times that each element occurs
72            AtomsList = self.GetAtoms(phasenam)
73            maxmult = 0
74            elemtypes = {}
75            for lbl,typ,mult,xyz,td in AtomsList:
76                maxmult = max(maxmult,mult)
77                typ = re.search('[A-Za-z]+',typ).group(0)
78                typ = typ[0:2]
79                typ = typ[0].upper()+typ[1:].lower()
80                if elemtypes.get(typ) is None:
81                    elemtypes[typ] = 1
82                else:
83                    elemtypes[typ] += 1
84            # create scattering factor record
85            s = "SFAC"
86            elemlist = sorted(elemtypes)
87            for elem in elemlist:
88                s += " " + elem
89            self.Write(s)
90            # handle atom records
91            count = {}
92            for lbl,typ,mult,xyz,td in AtomsList:
93                typ = re.search('[A-Za-z]+',typ).group(0)
94                typ = typ[0:2]
95                typ = typ[0].upper()+typ[1:].lower()
96                if count.get(typ) is None:
97                    count[typ] = 0
98                else:
99                    count[typ] += 1
100                # make a unique <=4 character label, if possible
101                if elemtypes[typ] <= 99:
102                    lbl = "{:s}{:d}".format(typ,count[typ])
103                else: # more than 99 atoms, use hexadecimal notation
104                    lbl = typ + "{:X}".format(count[typ])[-2:]
105                sfnum = elemlist.index(typ)+1 # element number in scattering factor list
106                l = lbl+" "+str(sfnum)
107                l += " {:.5f} {:.5f} {:.5f}".format(*[x[0] for x in xyz[:3]])
108                if mult == maxmult:
109                    m = 1
110                else:
111                    m = 1.*mult/maxmult
112                if xyz[3][0] == 1: # frac
113                    occ = 10 + m
114                else:
115                    occ = m * xyz[3][0]
116                l += " {:.3f}".format(occ)
117                for val,sig in td:
118                    l += " {:.3f}".format(val)                   
119                self.Write(l)
120            self.Write('END')
121            self.CloseFile()
122            print('Phase '+phasenam+' written to file '+self.fullpath)
Note: See TracBrowser for help on using the repository browser.