source: trunk/exports/G2export_examples.py @ 1115

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

rework exports for new types

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 9.9 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3########### SVN repository information ###################
4# $Date: 2013-10-18 21:00:32 +0000 (Fri, 18 Oct 2013) $
5# $Author: toby $
6# $Revision: 1115 $
7# $URL: trunk/exports/G2export_examples.py $
8# $Id: G2export_examples.py 1115 2013-10-18 21:00:32Z toby $
9########### SVN repository information ###################
10'''Code to demonstrate how GSAS-II data export routines are created
11'''
12import os.path
13import GSASIIpath
14GSASIIpath.SetVersionNumber("$Revision: 1115 $")
15import GSASIIIO as G2IO
16#import GSASIIgrid as G2gd
17#import GSASIIstrIO as G2stIO
18import GSASIImath as G2mth
19#import GSASIIlattice as G2lat
20#import GSASIIspc as G2spc
21#import GSASIIphsGUI as G2pg
22#import GSASIIstrMain as G2stMn
23
24class ExportPhaseText(G2IO.ExportBaseclass):
25    '''Used to create a text file for a phase
26
27    :param wx.Frame G2frame: reference to main GSAS-II frame
28    '''
29    def __init__(self,G2frame):
30        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
31            G2frame=G2frame,
32            formatName = 'Text file',
33            extension='.txt',
34            longFormatName = 'Export phase as text file'
35            )
36        self.exporttype = ['phase']
37        self.multiple = True # allow multiple phases to be selected
38
39    def Exporter(self,event=None):
40        '''Export a phase as a text file
41        '''
42        # the export process starts here
43        self.InitExport(event)
44        # load all of the tree into a set of dicts
45        self.loadTree()
46        # create a dict with refined values and their uncertainties
47        self.loadParmDict()
48        if self.ExportSelect( # set export parameters
49            AskFile=True     # prompt the user for a file name
50            ): return 
51        self.OpenFile(self.filename)
52        # if more than one format is selected, put them into a single file
53        for phasenam in self.phasenam:
54            phasedict = self.Phases[phasenam] # pointer to current phase info           
55            i = self.Phases[phasenam]['pId']
56            self.Write('\n'+80*'=')
57            self.Write("Phase "+str(phasenam)+" from "+str(self.G2frame.GSASprojectfile))
58            self.Write("\nSpace group = "+str(phasedict['General']['SGData']['SpGrp'].strip()))
59            # get cell parameters & print them
60            cellList,cellSig = self.GetCell(phasenam)
61            prevsig = 0
62            for lbl,defsig,val,sig in zip(
63                ['a','b','c','alpha','beta ','gamma','volume'],
64                3*[-0.00001] + 3*[-0.001] + [-0.01], # sign values to use when no sigma
65                cellList,cellSig
66                ):
67                if sig:
68                    txt = G2mth.ValEsd(val,sig)
69                    prevsig = -sig # use this as the significance for next value
70                else:
71                    txt = G2mth.ValEsd(val,min(defsig,prevsig),True)
72                self.Write(lbl+' = '+txt)
73            # get atoms and print them in nice columns
74            AtomsList = self.GetAtoms(phasenam)
75            fmt = "{:8s} {:4s} {:4s} {:12s} {:12s} {:12s} {:10s} {:10s}"
76            self.Write('\nAtoms\n'+80*'-')
77            self.Write(fmt.format("label","elem","mult","x","y","z","frac","Uiso"))
78            self.Write(80*'-')
79            aniso = False
80            for lbl,typ,mult,xyz,td in AtomsList:
81                vals = [lbl,typ,str(mult)]
82                if xyz[3][0] == 0: continue
83                for val,sig in xyz:
84                    vals.append(G2mth.ValEsd(val,sig))
85                if len(td) == 1:
86                    vals.append(G2mth.ValEsd(td[0][0],td[0][1]))
87                else:
88                    vals.append("aniso")
89                    aniso = True
90                self.Write(fmt.format(*vals))
91            # print anisotropic values, if any
92            if aniso:
93                self.Write('\nAnisotropic parameters')
94                self.Write(80*'-')
95                fmt = "{:8s} {:4s} {:10s} {:10s} {:10s} {:10s} {:10s} {:10s}"
96                self.Write(fmt.format("label","elem",'U11','U22','U33','U12','U13','U23'))
97                self.Write(80*'-')
98                for lbl,typ,mult,xyz,td in AtomsList:
99                    if len(td) == 1: continue
100                    if xyz[3][0] == 0: continue
101                    vals = [lbl,typ]
102                    for val,sig in td:
103                        vals.append(G2mth.ValEsd(val,sig))
104                    self.Write(fmt.format(*vals))
105            print('Phase '+str(phasenam)+' written to file '+str(self.filename))                       
106        self.CloseFile()
107
108class ExportPowderText(G2IO.ExportBaseclass):
109    '''Used to create a text file for a powder data set
110
111    :param wx.Frame G2frame: reference to main GSAS-II frame
112    '''
113    def __init__(self,G2frame):
114        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
115            G2frame=G2frame,
116            formatName = 'Text file',
117            extension='.txt',
118            longFormatName = 'Export powder data as text file'
119            )
120        self.exporttype = ['powder']
121        self.multiple = False # only allow one histogram to be selected
122
123    def Exporter(self,event=None):
124        '''Export a set of powder data as a text file
125        '''
126        # the export process starts here
127        self.InitExport(event)
128        # load all of the tree into a set of dicts
129        self.loadTree()
130        if self.ExportSelect( # set export parameters
131            AskFile=False # use the default file name
132            #AskFile=True
133            ): return 
134        self.OpenFile()
135        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
136        histblk = self.Histograms[hist]
137        fmt = 2*"{:12.3f} " + "{:12.5f} " + 2*"{:12.3f} "
138        hfmt = 5*"{:>12s} "
139        self.Write(hfmt.format("x","y_obs","weight","y_calc","y_bkg"))
140        for x,yobs,yw,ycalc,ybkg,obsmcalc in zip(histblk['Data'][0],
141                                                 histblk['Data'][1],
142                                                 histblk['Data'][2],
143                                                 histblk['Data'][3],
144                                                 histblk['Data'][4],
145                                                 histblk['Data'][5],
146                                                 ):
147            self.Write(fmt.format(x,yobs,yw,ycalc,ybkg))
148        self.CloseFile()
149        print(str(hist)+' written to file '+str(self.filename))                       
150
151class ExportPowderReflText(G2IO.ExportBaseclass):
152    '''Used to create a text file of reflections from a powder data set
153
154    :param wx.Frame G2frame: reference to main GSAS-II frame
155    '''
156    def __init__(self,G2frame):
157        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
158            G2frame=G2frame,
159            formatName = 'reflection list as text',
160            extension='.txt',
161            longFormatName = 'Export powder reflection list as a text file'
162            )
163        self.exporttype = ['powder']
164        self.multiple = False # only allow one histogram to be selected
165
166    def Exporter(self,event=None):
167        '''Export a set of powder reflections as a text file
168        '''
169        self.InitExport(event)
170        # load all of the tree into a set of dicts
171        self.loadTree()
172        if self.ExportSelect( # set export parameters
173            AskFile=False # use the default file name
174            #AskFile=True
175            ): return 
176        self.OpenFile()
177        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
178        histblk = self.Histograms[hist]
179        hklfmt = "{:.0f},{:.0f},{:.0f}"
180        hfmt = "{:>8s} {:>8s} {:>12s} {:>12s} {:>7s} {:>6s}"
181        fmt = "{:>8s} {:8.3f} {:12.3f} {:12.3f} {:7.2f} {:6.0f}"
182        for phasenam in histblk['Reflection Lists']:
183            self.Write('\nPhase '+str(phasenam))
184            self.Write(80*'=')
185            self.Write(hfmt.format("h,k,l","2-theta","F_obs","F_calc","phase","mult"))
186            self.Write(80*'=')
187            for (
188                h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,eqlist,phaselist,Icorr,FFdict
189                ) in histblk['Reflection Lists'][phasenam]:
190                self.Write(fmt.format(hklfmt.format(h,k,l),pos,Fobs,Fcalc,phase,mult))
191        self.CloseFile()
192        print(str(hist)+'reflections written to file '+str(self.filename))                       
193
194class ExportSingleText(G2IO.ExportBaseclass):
195    '''Used to create a text file with single crystal reflection data
196
197    :param wx.Frame G2frame: reference to main GSAS-II frame
198    '''
199    def __init__(self,G2frame):
200        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
201            G2frame=G2frame,
202            formatName = 'Text file',
203            extension='.txt',
204            longFormatName = 'Export reflection list as a text file'
205            )
206        self.exporttype = ['single']
207        self.multiple = False # only allow one histogram to be selected
208
209    def Exporter(self,event=None):
210        '''Export a set of single crystal data as a text file
211        '''
212        # the export process starts here
213        self.InitExport(event)
214        # load all of the tree into a set of dicts
215        self.loadTree()
216        if self.ExportSelect( # set export parameters
217            AskFile=False # use the default file name
218            #AskFile=True
219            ): return 
220        self.OpenFile()
221        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
222        histblk = self.Histograms[hist]
223        hklfmt = "{:.0f},{:.0f},{:.0f}"
224        hfmt = "{:>10s} {:>8s} {:>12s} {:>12s} {:>12s} {:>7s} {:>6s}"
225        fmt = "{:>10s} {:8.3f} {:12.2f} {:12.4f} {:12.2f} {:7.2f} {:6.0f}"
226        self.Write(80*'=')
227        self.Write(hfmt.format("h,k,l","d-space","F_obs","sig(Fobs)","F_calc","phase","mult"))
228        self.Write(80*'=')
229        for (
230            h,k,l,mult,dsp,Fobs,sigFobs,Fcalc,FobsT,FcalcT,phase,eqlist,phaselist,Icorr,FFdict
231            ) in histblk['Data']:
232            self.Write(fmt.format(hklfmt.format(h,k,l),dsp,Fobs,sigFobs,Fcalc,phase,mult))
233        self.CloseFile()
234        print(str(hist)+' written to file '+str(self.filename))                       
235
Note: See TracBrowser for help on using the repository browser.