source: trunk/exports/G2export_examples.py @ 1997

Last change on this file since 1997 was 1997, checked in by toby, 6 years ago

Add API for direct image read (G2IO.ExportPowderList?) and powder exports w/o GUI (G2IO.ExportPowderList?); redo export to add new method (Writer)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 12.6 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3########### SVN repository information ###################
4# $Date: 2015-10-10 16:58:12 +0000 (Sat, 10 Oct 2015) $
5# $Author: toby $
6# $Revision: 1997 $
7# $URL: trunk/exports/G2export_examples.py $
8# $Id: G2export_examples.py 1997 2015-10-10 16:58:12Z toby $
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: 1997 $")
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 Writer(self,TreeName,filename=None):
135        self.OpenFile(filename)
136        histblk = self.Histograms[TreeName]
137        hfmt = 5*"{:12s} "
138        digitList = 2*((13,3),) + ((13,5),) + 2*((13,3),)
139       
140        self.Write(hfmt.format("x","y_obs","weight","y_calc","y_bkg"))
141        for vallist in zip(histblk['Data'][0],
142                           histblk['Data'][1],
143                           histblk['Data'][2],
144                           histblk['Data'][3],
145                           histblk['Data'][4],
146                           #histblk['Data'][5],
147                           ):
148            strg = ''
149            for val,digits in zip(vallist,digitList):
150                strg += G2py3.FormatPadValue(val,digits)
151            self.Write(strg)
152        self.CloseFile()
153       
154    def Exporter(self,event=None):
155        '''Export a set of powder data as a text file
156        '''
157        # the export process starts here
158        self.InitExport(event)
159        # load all of the tree into a set of dicts
160        self.loadTree()
161        if self.ExportSelect( # set export parameters
162            AskFile='default' # base name on the GPX file name
163            ): return 
164        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
165        self.Writer(hist)
166        print(str(hist)+' written to file '+str(self.fullpath))
167       
168class ExportPowderReflText(G2IO.ExportBaseclass):
169    '''Used to create a text file of reflections from a powder data set
170
171    :param wx.Frame G2frame: reference to main GSAS-II frame
172    '''
173    def __init__(self,G2frame):
174        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
175            G2frame=G2frame,
176            formatName = 'reflection list as text',
177            extension='.txt',
178            longFormatName = 'Export powder reflection list as a text file'
179            )
180        self.exporttype = ['powder']
181        self.multiple = False # only allow one histogram to be selected
182
183    def Exporter(self,event=None):
184        '''Export a set of powder reflections as a text file
185        '''
186        self.InitExport(event)
187        # load all of the tree into a set of dicts
188        self.loadTree()
189        if self.ExportSelect( # set export parameters
190            AskFile='default' # base name on the GPX file name
191            ): return 
192        self.OpenFile()
193        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
194        self.Write('\nHistogram '+hist)
195        histblk = self.Histograms[hist]
196        for phasenam in histblk['Reflection Lists']:
197            phasDict = histblk['Reflection Lists'][phasenam]
198            tname = {'T':'TOF','C':'2-theta'}[phasDict['Type'][2]]
199            self.Write('\nPhase '+str(phasenam))
200            if phasDict.get('Super',False):
201                self.Write(96*'=')
202                hklfmt = "{:.0f},{:.0f},{:.0f},{:.0f}"
203                hfmt = "{:>10s} {:>8s} {:>12s} {:>12s} {:>7s} {:>6s} {:>8s} {:>8s} {:>8s} {:>8s}"
204                if 'T' in phasDict['Type']:
205                    fmt = "{:>10s} {:8.3f} {:12.3f} {:12.3f} {:7.2f} {:6.0f} {:8.3f} {:8.3f} {:8.3f} {:8.4f}"
206                else:
207                    fmt = "{:>10s} {:8.3f} {:12.3f} {:12.3f} {:7.2f} {:6.0f} {:8.5f} {:8.5f} {:8.5f} {:8.4f}"
208                self.Write(hfmt.format("h,k,l,m",tname,"F_obs","F_calc","phase","mult","sig","gam","FWHM","Prfo"))
209                self.Write(96*'=')
210                refList = phasDict['RefList']
211                for refItem in refList:
212                    if 'T' in phasDict['Type']:
213                        h,k,l,m,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,x,x,x,x,prfo = refItem[:17]
214                        FWHM = 2.*G2pwd.getgamFW(gam,sig)
215                        self.Write(fmt.format(hklfmt.format(h,k,l,m),pos,Fobs,Fcalc,phase,mult,sig,gam,FWHM,prfo))
216                    else:
217                        h,k,l,m,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,x,prfo = refItem[:14]
218                        FWHM = 2.*G2pwd.getgamFW(gam,sig)
219                        self.Write(fmt.format(hklfmt.format(h,k,l,m),pos,Fobs,Fcalc,phase,mult, \
220                            np.sqrt(max(sig,0.0001))/100.,gam/100.,FWHM/100.,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 = 2.*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                        FWHM = 2.*G2pwd.getgamFW(gam,sig)
240                        self.Write(fmt.format(hklfmt.format(h,k,l),pos,Fobs,Fcalc,phase,mult,   \
241                            np.sqrt(max(sig,0.0001))/100.,gam/100.,FWHM/100.,prfo))
242        self.CloseFile()
243        print(str(hist)+'reflections written to file '+str(self.fullpath))                       
244
245class ExportSingleText(G2IO.ExportBaseclass):
246    '''Used to create a text file with single crystal reflection data
247
248    :param wx.Frame G2frame: reference to main GSAS-II frame
249    '''
250    def __init__(self,G2frame):
251        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
252            G2frame=G2frame,
253            formatName = 'Text file',
254            extension='.txt',
255            longFormatName = 'Export reflection list as a text file'
256            )
257        self.exporttype = ['single']
258        self.multiple = False # only allow one histogram to be selected
259
260    def Exporter(self,event=None):
261        '''Export a set of single crystal data as a text file
262        '''
263        # the export process starts here
264        self.InitExport(event)
265        # load all of the tree into a set of dicts
266        self.loadTree()
267        if self.ExportSelect( # set export parameters
268            AskFile='default' # base name on the GPX file name
269            ): return 
270        self.OpenFile()
271        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
272        histblk = self.Histograms[hist]
273        hklfmt = "{:.0f},{:.0f},{:.0f}"
274        hfmt = "{:>10s} {:>8s} {:>12s} {:>12s} {:>12s} {:>7s} {:>6s}"
275        fmt = "{:>10s} {:8.3f} {:12.2f} {:12.4f} {:12.2f} {:7.2f} {:6.0f}"
276        self.Write(80*'=')
277        self.Write(hfmt.format("h,k,l","d-space","F_obs","sig(Fobs)","F_calc","phase","mult"))
278        self.Write(80*'=')
279        for (
280            h,k,l,mult,dsp,Fobs,sigFobs,Fcalc,FobsT,FcalcT,phase,Icorr
281            ) in histblk['Data']['RefList']:
282            self.Write(fmt.format(hklfmt.format(h,k,l),dsp,Fobs,sigFobs,Fcalc,phase,mult))
283        self.CloseFile()
284        print(str(hist)+' written to file '+str(self.fullpath))                       
285
Note: See TracBrowser for help on using the repository browser.