source: trunk/exports/G2export_examples.py @ 4522

Last change on this file since 4522 was 4522, checked in by vondreele, 3 years ago

fix exporters for pink reflection data

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