source: trunk/exports/G2export_examples.py @ 1630

Last change on this file since 1630 was 1261, checked in by toby, 11 years ago

reorg exports to implement directory selection

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 10.1 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3########### SVN repository information ###################
4# $Date: 2014-03-24 22:22:41 +0000 (Mon, 24 Mar 2014) $
5# $Author: vondreele $
6# $Revision: 1261 $
7# $URL: trunk/exports/G2export_examples.py $
8# $Id: G2export_examples.py 1261 2014-03-24 22:22:41Z 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: 1261 $")
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(): return # set export parameters; prompt for file name
60        self.OpenFile()
61        # if more than one format is selected, put them into a single file
62        for phasenam in self.phasenam:
63            phasedict = self.Phases[phasenam] # pointer to current phase info           
64            i = self.Phases[phasenam]['pId']
65            self.Write('\n'+80*'=')
66            self.Write("Phase "+str(phasenam)+" from "+str(self.G2frame.GSASprojectfile))
67            self.Write("\nSpace group = "+str(phasedict['General']['SGData']['SpGrp'].strip()))
68            # get cell parameters & print them
69            cellList,cellSig = self.GetCell(phasenam)
70            prevsig = 0
71            for lbl,defsig,val,sig in zip(
72                ['a','b','c','alpha','beta ','gamma','volume'],
73                3*[-0.00001] + 3*[-0.001] + [-0.01], # sign values to use when no sigma
74                cellList,cellSig
75                ):
76                if sig:
77                    txt = G2mth.ValEsd(val,sig)
78                    prevsig = -sig # use this as the significance for next value
79                else:
80                    txt = G2mth.ValEsd(val,min(defsig,prevsig),True)
81                self.Write(lbl+' = '+txt)
82            # get atoms and print them in nice columns
83            AtomsList = self.GetAtoms(phasenam)
84            fmt = "{:8s} {:4s} {:4s} {:12s} {:12s} {:12s} {:10s} {:10s}"
85            self.Write('\nAtoms\n'+80*'-')
86            self.Write(fmt.format("label","elem","mult","x","y","z","frac","Uiso"))
87            self.Write(80*'-')
88            aniso = False
89            for lbl,typ,mult,xyz,td in AtomsList:
90                vals = [lbl,typ,str(mult)]
91                if xyz[3][0] == 0: continue
92                for val,sig in xyz:
93                    vals.append(G2mth.ValEsd(val,sig))
94                if len(td) == 1:
95                    vals.append(G2mth.ValEsd(td[0][0],td[0][1]))
96                else:
97                    vals.append("aniso")
98                    aniso = True
99                self.Write(fmt.format(*vals))
100            # print anisotropic values, if any
101            if aniso:
102                self.Write('\nAnisotropic parameters')
103                self.Write(80*'-')
104                fmt = "{:8s} {:4s} {:10s} {:10s} {:10s} {:10s} {:10s} {:10s}"
105                self.Write(fmt.format("label","elem",'U11','U22','U33','U12','U13','U23'))
106                self.Write(80*'-')
107                for lbl,typ,mult,xyz,td in AtomsList:
108                    if len(td) == 1: continue
109                    if xyz[3][0] == 0: continue
110                    vals = [lbl,typ]
111                    for val,sig in td:
112                        vals.append(G2mth.ValEsd(val,sig))
113                    self.Write(fmt.format(*vals))
114            print('Phase '+str(phasenam)+' written to file '+str(self.fullpath))
115        self.CloseFile()
116
117class ExportPowderText(G2IO.ExportBaseclass):
118    '''Used to create a text file for a powder data set
119
120    :param wx.Frame G2frame: reference to main GSAS-II frame
121    '''
122    def __init__(self,G2frame):
123        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
124            G2frame=G2frame,
125            formatName = 'Text file',
126            extension='.txt',
127            longFormatName = 'Export powder data as text file'
128            )
129        self.exporttype = ['powder']
130        self.multiple = False # only allow one histogram to be selected
131
132    def Exporter(self,event=None):
133        '''Export a set of powder data as a text file
134        '''
135        # the export process starts here
136        self.InitExport(event)
137        # load all of the tree into a set of dicts
138        self.loadTree()
139        if self.ExportSelect( # set export parameters
140            AskFile='default' # base name on the GPX file name
141            ): return 
142        self.OpenFile()
143        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
144        histblk = self.Histograms[hist]
145        hfmt = 5*"{:12s} "
146        digitList = 2*((13,3),) + ((13,5),) + 2*((13,3),)
147       
148        self.Write(hfmt.format("x","y_obs","weight","y_calc","y_bkg"))
149        for vallist in zip(histblk['Data'][0],
150                           histblk['Data'][1],
151                           histblk['Data'][2],
152                           histblk['Data'][3],
153                           histblk['Data'][4],
154                           #histblk['Data'][5],
155                           ):
156            strg = ''
157            for val,digits in zip(vallist,digitList):
158                strg += G2py3.FormatPadValue(val,digits)
159            self.Write(strg)
160        self.CloseFile()
161        print(str(hist)+' written to file '+str(self.fullpath))
162       
163class ExportPowderReflText(G2IO.ExportBaseclass):
164    '''Used to create a text file of reflections from a powder data set
165
166    :param wx.Frame G2frame: reference to main GSAS-II frame
167    '''
168    def __init__(self,G2frame):
169        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
170            G2frame=G2frame,
171            formatName = 'reflection list as text',
172            extension='.txt',
173            longFormatName = 'Export powder reflection list as a text file'
174            )
175        self.exporttype = ['powder']
176        self.multiple = False # only allow one histogram to be selected
177
178    def Exporter(self,event=None):
179        '''Export a set of powder reflections as a text file
180        '''
181        self.InitExport(event)
182        # load all of the tree into a set of dicts
183        self.loadTree()
184        if self.ExportSelect( # set export parameters
185            AskFile='default' # base name on the GPX file name
186            ): return 
187        self.OpenFile()
188        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
189        histblk = self.Histograms[hist]
190        hklfmt = "{:.0f},{:.0f},{:.0f}"
191        hfmt = "{:>8s} {:>8s} {:>12s} {:>12s} {:>7s} {:>6s}"
192        fmt = "{:>8s} {:8.3f} {:12.3f} {:12.3f} {:7.2f} {:6.0f}"
193        for phasenam in histblk['Reflection Lists']:
194            self.Write('\nPhase '+str(phasenam))
195            self.Write(80*'=')
196            self.Write(hfmt.format("h,k,l","2-theta","F_obs","F_calc","phase","mult"))
197            self.Write(80*'=')
198            for (
199                h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr
200                ) in histblk['Reflection Lists'][phasenam]['RefList']:
201                self.Write(fmt.format(hklfmt.format(h,k,l),pos,Fobs,Fcalc,phase,mult))
202        self.CloseFile()
203        print(str(hist)+'reflections written to file '+str(self.fullpath))                       
204
205class ExportSingleText(G2IO.ExportBaseclass):
206    '''Used to create a text file with single crystal reflection data
207
208    :param wx.Frame G2frame: reference to main GSAS-II frame
209    '''
210    def __init__(self,G2frame):
211        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
212            G2frame=G2frame,
213            formatName = 'Text file',
214            extension='.txt',
215            longFormatName = 'Export reflection list as a text file'
216            )
217        self.exporttype = ['single']
218        self.multiple = False # only allow one histogram to be selected
219
220    def Exporter(self,event=None):
221        '''Export a set of single crystal data as a text file
222        '''
223        # the export process starts here
224        self.InitExport(event)
225        # load all of the tree into a set of dicts
226        self.loadTree()
227        if self.ExportSelect( # set export parameters
228            AskFile='default' # base name on the GPX file name
229            ): return 
230        self.OpenFile()
231        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
232        histblk = self.Histograms[hist]
233        hklfmt = "{:.0f},{:.0f},{:.0f}"
234        hfmt = "{:>10s} {:>8s} {:>12s} {:>12s} {:>12s} {:>7s} {:>6s}"
235        fmt = "{:>10s} {:8.3f} {:12.2f} {:12.4f} {:12.2f} {:7.2f} {:6.0f}"
236        self.Write(80*'=')
237        self.Write(hfmt.format("h,k,l","d-space","F_obs","sig(Fobs)","F_calc","phase","mult"))
238        self.Write(80*'=')
239        for (
240            h,k,l,mult,dsp,Fobs,sigFobs,Fcalc,FobsT,FcalcT,phase,Icorr
241            ) in histblk['Data']['RefList']:
242            self.Write(fmt.format(hklfmt.format(h,k,l),dsp,Fobs,sigFobs,Fcalc,phase,mult))
243        self.CloseFile()
244        print(str(hist)+' written to file '+str(self.fullpath))                       
245
Note: See TracBrowser for help on using the repository browser.