source: trunk/exports/G2export_examples.py @ 3011

Last change on this file since 3011 was 3000, checked in by toby, 4 years ago

make the two frame version the trunk as we hit version 3000

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 12.8 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3########### SVN repository information ###################
4# $Date: 2017-08-11 22:34:54 +0000 (Fri, 11 Aug 2017) $
5# $Author: odonnell $
6# $Revision: 3000 $
7# $URL: trunk/exports/G2export_examples.py $
8# $Id: G2export_examples.py 3000 2017-08-11 22:34:54Z odonnell $
9########### SVN repository information ###################
10'''
11*Module G2export_examples: Examples*
12-------------------------------------------
13
14Code to demonstrate how GSAS-II data export routines are created. The
15classes defined here, :class:`ExportPhaseText`,
16:class:`ExportSingleText`, :class:`ExportPowderReflText`,
17and :class:`ExportPowderText` each demonstrate a different type
18of export. Also see :class:`G2export_map.ExportMapASCII` for an
19example of a map export.
20
21'''
22import os.path
23import numpy as np
24import GSASIIpath
25GSASIIpath.SetVersionNumber("$Revision: 3000 $")
26import GSASIIIO as G2IO
27import GSASIIpy3 as G2py3
28#import GSASIIstrIO as G2stIO
29import GSASIImath as G2mth
30import GSASIIpwd as G2pwd
31#import GSASIIlattice as G2lat
32#import GSASIIspc as G2spc
33#import GSASIIphsGUI as G2pg
34#import GSASIIstrMain as G2stMn
35
36class ExportPhaseText(G2IO.ExportBaseclass):
37    '''Used to create a text file for a phase
38
39    :param wx.Frame G2frame: reference to main GSAS-II frame
40    '''
41    def __init__(self,G2frame):
42        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
43            G2frame=G2frame,
44            formatName = 'Text file',
45            extension='.txt',
46            longFormatName = 'Export phase as text file'
47            )
48        self.exporttype = ['phase']
49        self.multiple = True # allow multiple phases to be selected
50
51    def Exporter(self,event=None):
52        '''Export a phase as a text file
53        '''
54        # the export process starts here
55        self.InitExport(event)
56        # load all of the tree into a set of dicts
57        self.loadTree()
58        # create a dict with refined values and their uncertainties
59        self.loadParmDict()
60        if self.ExportSelect(): return # set export parameters; prompt for file name
61        self.OpenFile()
62        # if more than one format is selected, put them into a single file
63        for phasenam in self.phasenam:
64            phasedict = self.Phases[phasenam] # pointer to current phase info           
65            i = self.Phases[phasenam]['pId']
66            self.Write('\n'+80*'=')
67            self.Write("Phase "+str(phasenam)+" from "+str(self.G2frame.GSASprojectfile))
68            self.Write("\nSpace group = "+str(phasedict['General']['SGData']['SpGrp'].strip()))
69            # get cell parameters & print them
70            cellList,cellSig = self.GetCell(phasenam)
71            prevsig = 0
72            for lbl,defsig,val,sig in zip(
73                ['a','b','c','alpha','beta ','gamma','volume'],
74                3*[-0.00001] + 3*[-0.001] + [-0.01], # sign values to use when no sigma
75                cellList,cellSig
76                ):
77                if sig:
78                    txt = G2mth.ValEsd(val,sig)
79                    prevsig = -sig # use this as the significance for next value
80                else:
81                    txt = G2mth.ValEsd(val,min(defsig,prevsig),True)
82                self.Write(lbl+' = '+txt)
83            # get atoms and print them in nice columns
84            AtomsList = self.GetAtoms(phasenam)
85            fmt = "{:8s} {:4s} {:4s} {:12s} {:12s} {:12s} {:10s} {:10s}"
86            self.Write('\nAtoms\n'+80*'-')
87            self.Write(fmt.format("label","elem","mult","x","y","z","frac","Uiso"))
88            self.Write(80*'-')
89            aniso = False
90            for lbl,typ,mult,xyz,td in AtomsList:
91                vals = [lbl,typ,str(mult)]
92                if xyz[3][0] == 0: continue
93                for val,sig in xyz:
94                    vals.append(G2mth.ValEsd(val,sig))
95                if len(td) == 1:
96                    vals.append(G2mth.ValEsd(td[0][0],td[0][1]))
97                else:
98                    vals.append("aniso")
99                    aniso = True
100                self.Write(fmt.format(*vals))
101            # print anisotropic values, if any
102            if aniso:
103                self.Write('\nAnisotropic parameters')
104                self.Write(80*'-')
105                fmt = "{:8s} {:4s} {:10s} {:10s} {:10s} {:10s} {:10s} {:10s}"
106                self.Write(fmt.format("label","elem",'U11','U22','U33','U12','U13','U23'))
107                self.Write(80*'-')
108                for lbl,typ,mult,xyz,td in AtomsList:
109                    if len(td) == 1: continue
110                    if xyz[3][0] == 0: continue
111                    vals = [lbl,typ]
112                    for val,sig in td:
113                        vals.append(G2mth.ValEsd(val,sig))
114                    self.Write(fmt.format(*vals))
115            print('Phase '+phasenam+' written to file '+self.fullpath)
116        self.CloseFile()
117
118class ExportPowderText(G2IO.ExportBaseclass):
119    '''Used to create a text file for a powder data set
120
121    :param wx.Frame G2frame: reference to main GSAS-II frame
122    '''
123    def __init__(self,G2frame):
124        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
125            G2frame=G2frame,
126            formatName = 'Text file',
127            extension='.txt',
128            longFormatName = 'Export powder data as text file'
129            )
130        self.exporttype = ['powder']
131        self.multiple = False # only allow one histogram to be selected
132
133    def Writer(self,TreeName,filename=None):
134        self.OpenFile(filename)
135        histblk = self.Histograms[TreeName]
136        hfmt = 5*"{:12s} "
137        digitList = 2*((13,3),) + ((13,5),) + 2*((13,3),)
138       
139        self.Write(hfmt.format("x","y_obs","weight","y_calc","y_bkg"))
140        for vallist in zip(histblk['Data'][0],
141                           histblk['Data'][1],
142                           histblk['Data'][2],
143                           histblk['Data'][3],
144                           histblk['Data'][4],
145                           #histblk['Data'][5],
146                           ):
147            strg = ''
148            for val,digits in zip(vallist,digitList):
149                strg += G2py3.FormatPadValue(val,digits)
150            self.Write(strg)
151        self.CloseFile()
152       
153    def Exporter(self,event=None):
154        '''Export a set of powder data as a text file
155        '''
156        # the export process starts here
157        self.InitExport(event)
158        # load all of the tree into a set of dicts
159        self.loadTree()
160        if self.ExportSelect( # set export parameters
161            AskFile='default' # base name on the GPX file name
162            ): return 
163        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
164        self.Writer(hist)
165        print(hist+' written to file '+self.fullpath)
166       
167class ExportPowderReflText(G2IO.ExportBaseclass):
168    '''Used to create a text file of reflections from a powder data set
169
170    :param wx.Frame G2frame: reference to main GSAS-II frame
171    '''
172    def __init__(self,G2frame):
173        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
174            G2frame=G2frame,
175            formatName = 'reflection list as text',
176            extension='.txt',
177            longFormatName = 'Export powder reflection list as a text file'
178            )
179        self.exporttype = ['powder']
180        self.multiple = False # only allow one histogram to be selected
181
182    def Exporter(self,event=None):
183        '''Export a set of powder reflections as a text file
184        '''
185        self.InitExport(event)
186        # load all of the tree into a set of dicts
187        self.loadTree()
188        if self.ExportSelect( # set export parameters
189            AskFile='default' # base name on the GPX file name
190            ): return 
191        self.OpenFile()
192        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
193        self.Write('\nHistogram '+hist)
194        histblk = self.Histograms[hist]
195        for phasenam in histblk['Reflection Lists']:
196            phasDict = histblk['Reflection Lists'][phasenam]
197            tname = {'T':'TOF','C':'2-theta'}[phasDict['Type'][2]]
198            self.Write('\nPhase '+str(phasenam))
199            if phasDict.get('Super',False):
200                self.Write(96*'=')
201                hklfmt = "{:.0f},{:.0f},{:.0f},{:.0f}"
202                hfmt = "{:>10s} {:>8s} {:>12s} {:>12s} {:>7s} {:>6s} {:>8s} {:>8s} {:>8s} {:>8s}"
203                if 'T' in phasDict['Type']:
204                    fmt = "{:>10s} {:8.3f} {:12.3f} {:12.3f} {:7.2f} {:6.0f} {:8.3f} {:8.3f} {:8.3f} {:8.4f}"
205                else:
206                    fmt = "{:>10s} {:8.3f} {:12.3f} {:12.3f} {:7.2f} {:6.0f} {:8.5f} {:8.5f} {:8.5f} {:8.4f}"
207                self.Write(hfmt.format("h,k,l,m",tname,"F_obs","F_calc","phase","mult","sig","gam","FWHM","Prfo"))
208                self.Write(96*'=')
209                refList = phasDict['RefList']
210                for refItem in refList:
211                    if 'T' in phasDict['Type']:
212                        h,k,l,m,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,x,x,x,x,prfo = refItem[:17]
213                        FWHM = G2pwd.getgamFW(gam,sig)
214                        self.Write(fmt.format(hklfmt.format(h,k,l,m),pos,Fobs,Fcalc,phase,mult,sig,gam,FWHM,prfo))
215                    else:
216                        h,k,l,m,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,x,prfo = refItem[:14]
217                        g = gam/100.    #centideg -> deg
218                        s = np.sqrt(max(sig,0.0001))/100.   #var -> sig in deg
219                        FWHM = G2pwd.getgamFW(g,s)  #FWHM
220                        self.Write(fmt.format(hklfmt.format(h,k,l,m),pos,Fobs,Fcalc,phase,mult,s,g,FWHM,prfo))
221            else:
222                self.Write(94*'=')
223                hklfmt = "{:.0f},{:.0f},{:.0f}"
224                hfmt = "{:>8s} {:>8s} {:>12s} {:>12s} {:>7s} {:>6s} {:>8s} {:>8s} {:>8s} {:>8s}"
225                if 'T' in phasDict['Type']:
226                    fmt = "{:>8s} {:8.3f} {:12.3f} {:12.3f} {:7.2f} {:6.0f} {:8.3f} {:8.3f} {:8.3f} {:8.4f}"
227                else:
228                    fmt = "{:>8s} {:8.3f} {:12.3f} {:12.3f} {:7.2f} {:6.0f} {:8.5f} {:8.5f} {:8.5f} {:8.4f}"
229                self.Write(hfmt.format("h,k,l",tname,"F_obs","F_calc","phase","mult","sig","gam","FWHM","Prfo"))
230                self.Write(94*'=')
231                refList = phasDict['RefList']
232                for refItem in refList:
233                    if 'T' in phasDict['Type']:
234                        h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,x,x,x,x,prfo = refItem[:16]
235                        FWHM = G2pwd.getgamFW(gam,sig)
236                        self.Write(fmt.format(hklfmt.format(h,k,l),pos,Fobs,Fcalc,phase,mult,np.sqrt(max(sig,0.0001)),gam,FWHM,prfo))
237                    else:
238                        h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,x,prfo = refItem[:13]
239                        g = gam/100.    #centideg -> deg
240                        s = np.sqrt(max(sig,0.0001))/100.   #var -> sig in deg
241                        FWHM = G2pwd.getgamFW(g,s)
242                        self.Write(fmt.format(hklfmt.format(h,k,l),pos,Fobs,Fcalc,phase,mult,   \
243                            s,g,FWHM,prfo))
244        self.CloseFile()
245        print(hist+'reflections written to file '+self.fullpath)                       
246
247class ExportSingleText(G2IO.ExportBaseclass):
248    '''Used to create a text file with single crystal reflection data
249    skips user rejected & space group extinct reflections
250
251    :param wx.Frame G2frame: reference to main GSAS-II frame
252    '''
253    def __init__(self,G2frame):
254        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
255            G2frame=G2frame,
256            formatName = 'Text file',
257            extension='.txt',
258            longFormatName = 'Export reflection list as a text file'
259            )
260        self.exporttype = ['single']
261        self.multiple = False # only allow one histogram to be selected
262
263    def Exporter(self,event=None):
264        '''Export a set of single crystal data as a text file
265        '''
266        # the export process starts here
267        self.InitExport(event)
268        # load all of the tree into a set of dicts
269        self.loadTree()
270        if self.ExportSelect( # set export parameters
271            AskFile='default' # base name on the GPX file name
272            ): return 
273        self.OpenFile()
274        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
275        histblk = self.Histograms[hist]
276        hklfmt = "{:.0f},{:.0f},{:.0f}"
277        hfmt = "{:>10s} {:>8s} {:>12s} {:>12s} {:>12s} {:>7s} {:>6s}"
278        fmt = "{:>10s} {:8.3f} {:12.2f} {:12.4f} {:12.2f} {:7.2f} {:6.0f}"
279        self.Write(80*'=')
280        self.Write(hfmt.format("h,k,l","d-space","F_obs","sig(Fobs)","F_calc","phase","twin"))
281        self.Write(80*'=')
282        for (
283            h,k,l,twin,dsp,Fobs,sigFobs,Fcalc,FobsT,FcalcT,phase,Icorr
284            ) in histblk['Data']['RefList']:
285            if twin > 0:
286                self.Write(fmt.format(hklfmt.format(h,k,l),dsp,Fobs,sigFobs,Fcalc,phase,twin))
287        self.CloseFile()
288        print(hist+' written to file '+self.fullpath)                       
289
Note: See TracBrowser for help on using the repository browser.