source: trunk/exports/G2export_examples.py

Last change on this file was 5791, checked in by toby, 11 months ago

Sync to git d607de5; includes plot rings on image, HKLF script export; kvec work

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