source: trunk/exports/G2export_examples.py @ 1836

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

add Prfo to export powder reflections as txt & csv
fix G2ctrls (remove a couple of G2Gs)

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