source: trunk/exports/G2export_examples.py @ 1236

Last change on this file since 1236 was 1236, checked in by toby, 8 years ago

Add FXYE & XYE exporters; allow multiple powder exports; fix formatting of float32 intensities (which should be gone); minor sequential refinement changes; remove old export patterns items; new padded format routine

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 10.2 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3########### SVN repository information ###################
4# $Date: 2014-03-05 19:51:53 +0000 (Wed, 05 Mar 2014) $
5# $Author: toby $
6# $Revision: 1236 $
7# $URL: trunk/exports/G2export_examples.py $
8# $Id: G2export_examples.py 1236 2014-03-05 19:51:53Z 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 GSASIIpath
24GSASIIpath.SetVersionNumber("$Revision: 1236 $")
25import GSASIIIO as G2IO
26import GSASIIpy3 as G2py3
27#import GSASIIgrid as G2gd
28#import GSASIIstrIO as G2stIO
29import GSASIImath as G2mth
30#import GSASIIlattice as G2lat
31#import GSASIIspc as G2spc
32#import GSASIIphsGUI as G2pg
33#import GSASIIstrMain as G2stMn
34
35class ExportPhaseText(G2IO.ExportBaseclass):
36    '''Used to create a text file for a phase
37
38    :param wx.Frame G2frame: reference to main GSAS-II frame
39    '''
40    def __init__(self,G2frame):
41        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
42            G2frame=G2frame,
43            formatName = 'Text file',
44            extension='.txt',
45            longFormatName = 'Export phase as text file'
46            )
47        self.exporttype = ['phase']
48        self.multiple = True # allow multiple phases to be selected
49
50    def Exporter(self,event=None):
51        '''Export a phase as a text file
52        '''
53        # the export process starts here
54        self.InitExport(event)
55        # load all of the tree into a set of dicts
56        self.loadTree()
57        # create a dict with refined values and their uncertainties
58        self.loadParmDict()
59        if self.ExportSelect( # set export parameters
60            AskFile=True     # prompt the user for a file name
61            ): return 
62        self.OpenFile(self.filename)
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.filename))                       
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 Exporter(self,event=None):
135        '''Export a set of powder data as a text file
136        '''
137        # the export process starts here
138        self.InitExport(event)
139        # load all of the tree into a set of dicts
140        self.loadTree()
141        if self.ExportSelect( # set export parameters
142            AskFile=False # use the default file name
143            #AskFile=True
144            ): return 
145        self.OpenFile()
146        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
147        histblk = self.Histograms[hist]
148        hfmt = 5*"{:12s} "
149        digitList = 2*((13,3),) + ((13,5),) + 2*((13,3),)
150       
151        self.Write(hfmt.format("x","y_obs","weight","y_calc","y_bkg"))
152        for vallist in zip(histblk['Data'][0],
153                           histblk['Data'][1],
154                           histblk['Data'][2],
155                           histblk['Data'][3],
156                           histblk['Data'][4],
157                           #histblk['Data'][5],
158                           ):
159            strg = ''
160            for val,digits in zip(vallist,digitList):
161                strg += G2py3.FormatPadValue(val,digits)
162            self.Write(strg)
163        self.CloseFile()
164        print(str(hist)+' written to file '+str(self.filename))
165       
166class ExportPowderReflText(G2IO.ExportBaseclass):
167    '''Used to create a text file of reflections from a powder data set
168
169    :param wx.Frame G2frame: reference to main GSAS-II frame
170    '''
171    def __init__(self,G2frame):
172        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
173            G2frame=G2frame,
174            formatName = 'reflection list as text',
175            extension='.txt',
176            longFormatName = 'Export powder reflection list as a text file'
177            )
178        self.exporttype = ['powder']
179        self.multiple = False # only allow one histogram to be selected
180
181    def Exporter(self,event=None):
182        '''Export a set of powder reflections as a text file
183        '''
184        self.InitExport(event)
185        # load all of the tree into a set of dicts
186        self.loadTree()
187        if self.ExportSelect( # set export parameters
188            AskFile=False # use the default file name
189            #AskFile=True
190            ): return 
191        self.OpenFile()
192        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
193        histblk = self.Histograms[hist]
194        hklfmt = "{:.0f},{:.0f},{:.0f}"
195        hfmt = "{:>8s} {:>8s} {:>12s} {:>12s} {:>7s} {:>6s}"
196        fmt = "{:>8s} {:8.3f} {:12.3f} {:12.3f} {:7.2f} {:6.0f}"
197        for phasenam in histblk['Reflection Lists']:
198            self.Write('\nPhase '+str(phasenam))
199            self.Write(80*'=')
200            self.Write(hfmt.format("h,k,l","2-theta","F_obs","F_calc","phase","mult"))
201            self.Write(80*'=')
202            for (
203                h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr
204                ) in histblk['Reflection Lists'][phasenam]['RefList']:
205                self.Write(fmt.format(hklfmt.format(h,k,l),pos,Fobs,Fcalc,phase,mult))
206        self.CloseFile()
207        print(str(hist)+'reflections written to file '+str(self.filename))                       
208
209class ExportSingleText(G2IO.ExportBaseclass):
210    '''Used to create a text file with single crystal reflection data
211
212    :param wx.Frame G2frame: reference to main GSAS-II frame
213    '''
214    def __init__(self,G2frame):
215        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
216            G2frame=G2frame,
217            formatName = 'Text file',
218            extension='.txt',
219            longFormatName = 'Export reflection list as a text file'
220            )
221        self.exporttype = ['single']
222        self.multiple = False # only allow one histogram to be selected
223
224    def Exporter(self,event=None):
225        '''Export a set of single crystal data as a text file
226        '''
227        # the export process starts here
228        self.InitExport(event)
229        # load all of the tree into a set of dicts
230        self.loadTree()
231        if self.ExportSelect( # set export parameters
232            AskFile=False # use the default file name
233            #AskFile=True
234            ): return 
235        self.OpenFile()
236        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
237        histblk = self.Histograms[hist]
238        hklfmt = "{:.0f},{:.0f},{:.0f}"
239        hfmt = "{:>10s} {:>8s} {:>12s} {:>12s} {:>12s} {:>7s} {:>6s}"
240        fmt = "{:>10s} {:8.3f} {:12.2f} {:12.4f} {:12.2f} {:7.2f} {:6.0f}"
241        self.Write(80*'=')
242        self.Write(hfmt.format("h,k,l","d-space","F_obs","sig(Fobs)","F_calc","phase","mult"))
243        self.Write(80*'=')
244        for (
245            h,k,l,mult,dsp,Fobs,sigFobs,Fcalc,FobsT,FcalcT,phase,Icorr
246            ) in histblk['Data']['RefList']:
247            self.Write(fmt.format(hklfmt.format(h,k,l),dsp,Fobs,sigFobs,Fcalc,phase,mult))
248        self.CloseFile()
249        print(str(hist)+' written to file '+str(self.filename))                       
250
Note: See TracBrowser for help on using the repository browser.