source: trunk/exports/G2export_examples.py @ 3793

Last change on this file since 3793 was 3223, checked in by toby, 7 years ago

fix histogram export file naming

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 13.1 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3########### SVN repository information ###################
4# $Date: 2018-01-14 17:28:10 +0000 (Sun, 14 Jan 2018) $
5# $Author: toby $
6# $Revision: 3223 $
7# $URL: trunk/exports/G2export_examples.py $
8# $Id: G2export_examples.py 3223 2018-01-14 17:28:10Z 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'''
22from __future__ import division, print_function
23import os
24import numpy as np
25import GSASIIpath
26GSASIIpath.SetVersionNumber("$Revision: 3223 $")
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 = 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'}[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                    else:
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            else:
226                self.Write(94*'=')
227                hklfmt = "{:.0f},{:.0f},{:.0f}"
228                hfmt = "{:>8s} {:>8s} {:>12s} {:>12s} {:>7s} {:>6s} {:>8s} {:>8s} {:>8s} {:>8s}"
229                if 'T' in phasDict['Type']:
230                    fmt = "{:>8s} {:8.3f} {:12.3f} {:12.3f} {:7.2f} {:6.0f} {:8.3f} {:8.3f} {:8.3f} {:8.4f}"
231                else:
232                    fmt = "{:>8s} {:8.3f} {:12.3f} {:12.3f} {:7.2f} {:6.0f} {:8.5f} {:8.5f} {:8.5f} {:8.4f}"
233                self.Write(hfmt.format("h,k,l",tname,"F_obs","F_calc","phase","mult","sig","gam","FWHM","Prfo"))
234                self.Write(94*'=')
235                refList = phasDict['RefList']
236                for refItem in refList:
237                    if 'T' in phasDict['Type']:
238                        h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,x,x,x,x,prfo = refItem[:16]
239                        FWHM = G2pwd.getgamFW(gam,sig)
240                        self.Write(fmt.format(hklfmt.format(h,k,l),pos,Fobs,Fcalc,phase,mult,np.sqrt(max(sig,0.0001)),gam,FWHM,prfo))
241                    else:
242                        h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,x,prfo = refItem[:13]
243                        g = gam/100.    #centideg -> deg
244                        s = np.sqrt(max(sig,0.0001))/100.   #var -> sig in deg
245                        FWHM = G2pwd.getgamFW(g,s)
246                        self.Write(fmt.format(hklfmt.format(h,k,l),pos,Fobs,Fcalc,phase,mult,   \
247                            s,g,FWHM,prfo))
248        self.CloseFile()
249        print(hist+'reflections written to file '+self.fullpath)                       
250
251class ExportSingleText(G2IO.ExportBaseclass):
252    '''Used to create a text file with single crystal reflection data
253    skips user rejected & space group extinct reflections
254
255    :param wx.Frame G2frame: reference to main GSAS-II frame
256    '''
257    def __init__(self,G2frame):
258        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
259            G2frame=G2frame,
260            formatName = 'Text file',
261            extension='.txt',
262            longFormatName = 'Export reflection list as a text file'
263            )
264        self.exporttype = ['single']
265        self.multiple = False # only allow one histogram to be selected
266
267    def Exporter(self,event=None):
268        '''Export a set of single crystal data as a text file
269        '''
270        # the export process starts here
271        self.InitExport(event)
272        # load all of the tree into a set of dicts
273        self.loadTree()
274        if self.ExportSelect( # set export parameters
275            AskFile='default' # base name on the GPX file name
276            ): return 
277        self.OpenFile()
278        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
279        histblk = self.Histograms[hist]
280        hklfmt = "{:.0f},{:.0f},{:.0f}"
281        hfmt = "{:>10s} {:>8s} {:>12s} {:>12s} {:>12s} {:>7s} {:>6s}"
282        fmt = "{:>10s} {:8.3f} {:12.2f} {:12.4f} {:12.2f} {:7.2f} {:6.0f}"
283        self.Write(80*'=')
284        self.Write(hfmt.format("h,k,l","d-space","F_obs","sig(Fobs)","F_calc","phase","twin"))
285        self.Write(80*'=')
286        for (
287            h,k,l,twin,dsp,Fobs,sigFobs,Fcalc,FobsT,FcalcT,phase,Icorr
288            ) in histblk['Data']['RefList']:
289            if twin > 0:
290                self.Write(fmt.format(hklfmt.format(h,k,l),dsp,Fobs,sigFobs,Fcalc,phase,twin))
291        self.CloseFile()
292        print(hist+' written to file '+self.fullpath)                       
293
Note: See TracBrowser for help on using the repository browser.