source: trunk/exports/G2export_examples.py @ 1773

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

provide sig,gam & FWHM in export of PWDR reflection set as csv & txt files
add penalty fxn stuff for sph. harm. preferred orientation correction
allow editing of ODF coeff.
fix reading of fcf files

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 11.2 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3########### SVN repository information ###################
4# $Date: 2015-04-02 15:56:59 +0000 (Thu, 02 Apr 2015) $
5# $Author: vondreele $
6# $Revision: 1773 $
7# $URL: trunk/exports/G2export_examples.py $
8# $Id: G2export_examples.py 1773 2015-04-02 15:56:59Z 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 GSASIIpath
24GSASIIpath.SetVersionNumber("$Revision: 1773 $")
25import GSASIIIO as G2IO
26import GSASIIpy3 as G2py3
27#import GSASIIgrid as G2gd
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 '+str(phasenam)+' written to file '+str(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 Exporter(self,event=None):
134        '''Export a set of powder data as a text file
135        '''
136        # the export process starts here
137        self.InitExport(event)
138        # load all of the tree into a set of dicts
139        self.loadTree()
140        if self.ExportSelect( # set export parameters
141            AskFile='default' # base name on the GPX file name
142            ): return 
143        self.OpenFile()
144        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
145        histblk = self.Histograms[hist]
146        hfmt = 5*"{:12s} "
147        digitList = 2*((13,3),) + ((13,5),) + 2*((13,3),)
148       
149        self.Write(hfmt.format("x","y_obs","weight","y_calc","y_bkg"))
150        for vallist in zip(histblk['Data'][0],
151                           histblk['Data'][1],
152                           histblk['Data'][2],
153                           histblk['Data'][3],
154                           histblk['Data'][4],
155                           #histblk['Data'][5],
156                           ):
157            strg = ''
158            for val,digits in zip(vallist,digitList):
159                strg += G2py3.FormatPadValue(val,digits)
160            self.Write(strg)
161        self.CloseFile()
162        print(str(hist)+' written to file '+str(self.fullpath))
163       
164class ExportPowderReflText(G2IO.ExportBaseclass):
165    '''Used to create a text file of reflections from a powder data set
166
167    :param wx.Frame G2frame: reference to main GSAS-II frame
168    '''
169    def __init__(self,G2frame):
170        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
171            G2frame=G2frame,
172            formatName = 'reflection list as text',
173            extension='.txt',
174            longFormatName = 'Export powder reflection list as a text file'
175            )
176        self.exporttype = ['powder']
177        self.multiple = False # only allow one histogram to be selected
178
179    def Exporter(self,event=None):
180        '''Export a set of powder reflections as a text file
181        '''
182        self.InitExport(event)
183        # load all of the tree into a set of dicts
184        self.loadTree()
185        if self.ExportSelect( # set export parameters
186            AskFile='default' # base name on the GPX file name
187            ): return 
188        self.OpenFile()
189        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
190        histblk = self.Histograms[hist]
191        for phasenam in histblk['Reflection Lists']:
192            phasDict = histblk['Reflection Lists'][phasenam]
193            tname = {'T':'TOF','C':'2-theta'}[phasDict['Type'][2]]
194            self.Write('\nPhase '+str(phasenam))
195            if phasDict.get('Super',False):
196                self.Write(87*'=')
197                hklfmt = "{:.0f},{:.0f},{:.0f},{:.0f}"
198                hfmt = "{:>10s} {:>8s} {:>12s} {:>12s} {:>7s} {:>6s} {:>8s} {:>8s} {:>8s}"
199                fmt = "{:>10s} {:8.3f} {:12.3f} {:12.3f} {:7.2f} {:6.0f} {:8.3f} {:8.3f} {:8.3f}"
200                self.Write(hfmt.format("h,k,l,m",tname,"F_obs","F_calc","phase","mult","sig","gam","FWHM"))
201                self.Write(87*'=')
202                refList = phasDict['RefList']
203                for refItem in refList:
204                    h,k,l,m,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase = refItem[:12]
205                    FWHM = G2pwd.getgamFW(gam,sig)
206                    self.Write(fmt.format(hklfmt.format(h,k,l,m),pos,Fobs,Fcalc,phase,mult,sig,gam,FWHM))
207            else:
208                self.Write(85*'=')
209                hklfmt = "{:.0f},{:.0f},{:.0f}"
210                hfmt = "{:>8s} {:>8s} {:>12s} {:>12s} {:>7s} {:>6s} {:>8s} {:>8s} {:>8s}"
211                fmt = "{:>8s} {:8.3f} {:12.3f} {:12.3f} {:7.2f} {:6.0f} {:8.3f} {:8.3f} {:8.3f}"
212                self.Write(hfmt.format("h,k,l",tname,"F_obs","F_calc","phase","mult","sig","gam","FWHM"))
213                self.Write(85*'=')
214                refList = phasDict['RefList']
215                for refItem in refList:
216                    h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase = refItem[:11]
217                    FWHM = G2pwd.getgamFW(gam,sig)
218                    self.Write(fmt.format(hklfmt.format(h,k,l),pos,Fobs,Fcalc,phase,mult,sig,gam,FWHM))
219        self.CloseFile()
220        print(str(hist)+'reflections written to file '+str(self.fullpath))                       
221
222class ExportSingleText(G2IO.ExportBaseclass):
223    '''Used to create a text file with single crystal reflection data
224
225    :param wx.Frame G2frame: reference to main GSAS-II frame
226    '''
227    def __init__(self,G2frame):
228        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
229            G2frame=G2frame,
230            formatName = 'Text file',
231            extension='.txt',
232            longFormatName = 'Export reflection list as a text file'
233            )
234        self.exporttype = ['single']
235        self.multiple = False # only allow one histogram to be selected
236
237    def Exporter(self,event=None):
238        '''Export a set of single crystal data as a text file
239        '''
240        # the export process starts here
241        self.InitExport(event)
242        # load all of the tree into a set of dicts
243        self.loadTree()
244        if self.ExportSelect( # set export parameters
245            AskFile='default' # base name on the GPX file name
246            ): return 
247        self.OpenFile()
248        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
249        histblk = self.Histograms[hist]
250        hklfmt = "{:.0f},{:.0f},{:.0f}"
251        hfmt = "{:>10s} {:>8s} {:>12s} {:>12s} {:>12s} {:>7s} {:>6s}"
252        fmt = "{:>10s} {:8.3f} {:12.2f} {:12.4f} {:12.2f} {:7.2f} {:6.0f}"
253        self.Write(80*'=')
254        self.Write(hfmt.format("h,k,l","d-space","F_obs","sig(Fobs)","F_calc","phase","mult"))
255        self.Write(80*'=')
256        for (
257            h,k,l,mult,dsp,Fobs,sigFobs,Fcalc,FobsT,FcalcT,phase,Icorr
258            ) in histblk['Data']['RefList']:
259            self.Write(fmt.format(hklfmt.format(h,k,l),dsp,Fobs,sigFobs,Fcalc,phase,mult))
260        self.CloseFile()
261        print(str(hist)+' written to file '+str(self.fullpath))                       
262
Note: See TracBrowser for help on using the repository browser.