source: trunk/exports/G2export_examples.py @ 1102

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

change exports to always have lists of phases & histograms; new export examples; CIF export fixes

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 10.0 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3########### SVN repository information ###################
4# $Date: 2013-10-13 03:47:06 +0000 (Sun, 13 Oct 2013) $
5# $Author: toby $
6# $Revision: 1102 $
7# $URL: trunk/exports/G2export_examples.py $
8# $Id: G2export_examples.py 1102 2013-10-13 03:47:06Z toby $
9########### SVN repository information ###################
10'''Code to demonstrate how export routines are created
11'''
12import os.path
13import GSASIIpath
14GSASIIpath.SetVersionNumber("$Revision: 1102 $")
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',
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        # load all of the tree into a set of dicts
44        self.loadTree()
45        # create a dict with refined values and their uncertainties
46        self.loadParmDict()
47        if self.SetupExport( # set export parameters
48            event,                         
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',
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        # load all of the tree into a set of dicts
128        self.loadTree()
129        print 'Exporter',self.defaultSaveFile()
130        if self.SetupExport( # set export parameters
131            event,
132            AskFile=False # use the default file name
133            #AskFile=True
134            ): return 
135        self.OpenFile()
136        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
137        histblk = self.Histograms[hist]
138        #inst = histblk['Instrument Parameters'][0]
139        #hId = histblk['hId']
140        #pfx = ':' + str(hId) + ':'
141        fmt = 2*"{:12.3f} " + "{:12.5f} " + 2*"{:12.3f} "
142        hfmt = 5*"{:>12s} "
143        self.Write(hfmt.format("x","y_obs","weight","y_calc","y_bkg"))
144        for x,yobs,yw,ycalc,ybkg,obsmcalc in zip(histblk['Data'][0],
145                                                 histblk['Data'][1],
146                                                 histblk['Data'][2],
147                                                 histblk['Data'][3],
148                                                 histblk['Data'][4],
149                                                 histblk['Data'][5],
150                                                 ):
151            self.Write(fmt.format(x,yobs,yw,ycalc,ybkg))
152        self.CloseFile()
153        print(str(hist)+' written to file '+str(self.filename))                       
154
155class ExportPowderReflText(G2IO.ExportBaseclass):
156    '''Used to create a text file of reflections from a powder data set
157
158    :param wx.Frame G2frame: reference to main GSAS-II frame
159    '''
160    def __init__(self,G2frame):
161        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
162            G2frame=G2frame,
163            formatName = 'reflection list as text',
164            extension='.txt',
165            longFormatName = 'Export powder reflection list as a text file'
166            )
167        self.exporttype = ['powder']
168        self.multiple = False # only allow one histogram to be selected
169
170    def Exporter(self,event=None):
171        '''Export a set of powder reflections as a text file
172        '''
173        # load all of the tree into a set of dicts
174        self.loadTree()
175        if self.SetupExport( # set export parameters
176            event,
177            AskFile=False # use the default file name
178            #AskFile=True
179            ): return 
180        self.OpenFile()
181        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
182        histblk = self.Histograms[hist]
183        hklfmt = "{:.0f},{:.0f},{:.0f}"
184        hfmt = "{:>8s} {:>8s} {:>12s} {:>12s} {:>7s} {:>6s}"
185        fmt = "{:>8s} {:8.3f} {:12.3f} {:12.3f} {:7.2f} {:6.0f}"
186        for phasenam in histblk['Reflection Lists']:
187            self.Write('\nPhase '+str(phasenam))
188            self.Write(80*'=')
189            self.Write(hfmt.format("h,k,l","2-theta","F_obs","F_calc","phase","mult"))
190            self.Write(80*'=')
191            for (
192                h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,eqlist,phaselist,Icorr,FFdict
193                ) in histblk['Reflection Lists'][phasenam]:
194                self.Write(fmt.format(hklfmt.format(h,k,l),pos,Fobs,Fcalc,phase,mult))
195        self.CloseFile()
196        print(str(hist)+'reflections written to file '+str(self.filename))                       
197
198class ExportSingleText(G2IO.ExportBaseclass):
199    '''Used to create a text file with single crystal reflection data
200
201    :param wx.Frame G2frame: reference to main GSAS-II frame
202    '''
203    def __init__(self,G2frame):
204        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
205            G2frame=G2frame,
206            formatName = 'reflection list as text',
207            extension='.txt',
208            longFormatName = 'Export reflection list as a text file'
209            )
210        self.exporttype = ['single']
211        self.multiple = False # only allow one histogram to be selected
212
213    def Exporter(self,event=None):
214        '''Export a set of single crystal data as a text file
215        '''
216        # the export process starts here
217        # load all of the tree into a set of dicts
218        self.loadTree()
219        if self.SetupExport( # set export parameters
220            event,
221            AskFile=False # use the default file name
222            #AskFile=True
223            ): return 
224        self.OpenFile()
225        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
226        histblk = self.Histograms[hist]
227        hklfmt = "{:.0f},{:.0f},{:.0f}"
228        hfmt = "{:>10s} {:>8s} {:>12s} {:>12s} {:>12s} {:>7s} {:>6s}"
229        fmt = "{:>10s} {:8.3f} {:12.2f} {:12.4f} {:12.2f} {:7.2f} {:6.0f}"
230        self.Write(80*'=')
231        self.Write(hfmt.format("h,k,l","d-space","F_obs","sig(Fobs)","F_calc","phase","mult"))
232        self.Write(80*'=')
233        for (
234            h,k,l,mult,dsp,Fobs,sigFobs,Fcalc,FobsT,FcalcT,phase,eqlist,phaselist,Icorr,FFdict
235            ) in histblk['Data']:
236            self.Write(fmt.format(hklfmt.format(h,k,l),dsp,Fobs,sigFobs,Fcalc,phase,mult))
237        self.CloseFile()
238        print(str(hist)+' written to file '+str(self.filename))                       
239
Note: See TracBrowser for help on using the repository browser.