source: trunk/exports/G2export_csv.py @ 1761

Last change on this file since 1761 was 1761, checked in by vondreele, 9 years ago

better fix to export csv reflections
change default I/Ib for strain picking
fix bugs in powder extinction calcs.
remove stray line in G2strMath

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 14.2 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3########### SVN repository information ###################
4# $Date: 2015-03-24 21:10:52 +0000 (Tue, 24 Mar 2015) $
5# $Author: vondreele $
6# $Revision: 1761 $
7# $URL: trunk/exports/G2export_csv.py $
8# $Id: G2export_csv.py 1761 2015-03-24 21:10:52Z vondreele $
9########### SVN repository information ###################
10'''
11*Module G2export_csv: Spreadsheet export*
12-------------------------------------------
13
14Code to create .csv (comma-separated variable) files for
15GSAS-II data export to a spreadsheet program, etc.
16
17'''
18import os.path
19import numpy as np
20import GSASIIpath
21GSASIIpath.SetVersionNumber("$Revision: 1761 $")
22import GSASIIIO as G2IO
23import GSASIIpy3 as G2py3
24import GSASIIobj as G2obj
25import GSASIImath as G2mth
26
27def WriteList(obj,headerItems):
28    '''Write a CSV header
29
30    :param object obj: Exporter object
31    :param list headerItems: items to write as a header
32    '''
33    line = ''
34    for lbl in headerItems:
35        if line: line += ','
36        line += '"'+lbl+'"'
37    obj.Write(line)
38
39class ExportPhaseCSV(G2IO.ExportBaseclass):
40    '''Used to create a csv file for a phase
41
42    :param wx.Frame G2frame: reference to main GSAS-II frame
43    '''
44    def __init__(self,G2frame):
45        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
46            G2frame=G2frame,
47            formatName = 'CSV file',
48            extension='.csv',
49            longFormatName = 'Export phase as comma-separated (csv) file'
50            )
51        self.exporttype = ['phase']
52        self.multiple = True # allow multiple phases to be selected
53
54    def Exporter(self,event=None):
55        '''Export a phase as a csv file
56        '''
57        # the export process starts here
58        self.InitExport(event)
59        # load all of the tree into a set of dicts
60        self.loadTree()
61        # create a dict with refined values and their uncertainties
62        self.loadParmDict()
63        if self.ExportSelect(): return # set export parameters; get file name
64        self.OpenFile()
65        # if more than one format is selected, put them into a single file
66        for phasenam in self.phasenam:
67            phasedict = self.Phases[phasenam] # pointer to current phase info           
68            i = self.Phases[phasenam]['pId']
69            self.Write('"'+"Phase "+str(phasenam)+" from "+str(self.G2frame.GSASprojectfile)+'"')
70            self.Write('\n"Space group:","'+str(phasedict['General']['SGData']['SpGrp'].strip())+'"')
71            # get cell parameters & print them
72            cellList,cellSig = self.GetCell(phasenam)
73            WriteList(self,['a','b','c','alpha','beta','gamma','volume'])
74
75            line = ''
76            for defsig,val in zip(
77                3*[-0.00001] + 3*[-0.001] + [-0.01], # sign values to use when no sigma
78                cellList
79                ):
80                txt = G2mth.ValEsd(val,defsig)
81                if line: line += ','
82                line += txt
83            self.Write(line)
84               
85            # get atoms and print separated by commas
86            AtomsList = self.GetAtoms(phasenam)
87            # check for aniso atoms
88            aniso = False
89            for lbl,typ,mult,xyz,td in AtomsList:
90                if len(td) != 1: aniso = True               
91            lbllist = ["label","elem","mult","x","y","z","frac","Uiso"]
92            if aniso: lbllist += ['U11','U22','U33','U12','U13','U23']
93            WriteList(self,lbllist)
94               
95            for lbl,typ,mult,xyz,td in AtomsList:
96                line = '"' + lbl + '","' + typ + '",' + str(mult) + ','
97                for val,sig in xyz:
98                    line += G2mth.ValEsd(val,-abs(sig))
99                    line += ","
100                if len(td) == 1:
101                    line += G2mth.ValEsd(td[0][0],-abs(td[0][1]))
102                else:
103                    line += ","
104                    for val,sig in td:
105                        line += G2mth.ValEsd(val,-abs(sig))
106                        line += ","
107                self.Write(line)
108            print('Phase '+str(phasenam)+' written to file '+str(self.fullpath))
109        self.CloseFile()
110
111class ExportPowderCSV(G2IO.ExportBaseclass):
112    '''Used to create a csv file for a powder data set
113
114    :param wx.Frame G2frame: reference to main GSAS-II frame
115    '''
116    def __init__(self,G2frame):
117        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
118            G2frame=G2frame,
119            formatName = 'CSV file',
120            extension='.csv',
121            longFormatName = 'Export powder data as comma-separated (csv) file'
122            )
123        self.exporttype = ['powder']
124        #self.multiple = False # only allow one histogram to be selected
125        self.multiple = True
126
127    def Exporter(self,event=None):
128        '''Export a set of powder data as a csv file
129        '''
130        # the export process starts here
131        self.InitExport(event)
132        # load all of the tree into a set of dicts
133        self.loadTree()
134        if self.ExportSelect( # set export parameters
135            AskFile='single' # get a file name/directory to save in
136            ): return
137        filenamelist = []
138        for hist in self.histnam:
139            if len(self.histnam) > 1:
140                # multiple files: create a unique name from the histogram
141                fileroot = G2obj.MakeUniqueLabel(self.MakePWDRfilename(hist),filenamelist)
142                # create an instrument parameter file
143                self.filename = os.path.join(self.dirname,fileroot + self.extension)
144            self.OpenFile()
145            histblk = self.Histograms[hist]
146            WriteList(self,("x","y_obs","weight","y_calc","y_bkg"))
147            digitList = 2*((13,3),) + ((13,5),) + 2*((13,3),)
148            for vallist in zip(histblk['Data'][0],
149                           histblk['Data'][1],
150                           histblk['Data'][2],
151                           histblk['Data'][3],
152                           histblk['Data'][4],
153                           #histblk['Data'][5],
154                           ):
155                line = ""
156                for val,digits in zip(vallist,digitList):
157                    if line: line += ','
158                    line += G2py3.FormatValue(val,digits)
159                self.Write(line)
160            self.CloseFile()
161            print('Histogram '+str(hist)+' written to file '+str(self.fullpath))
162
163class ExportMultiPowderCSV(G2IO.ExportBaseclass):
164    '''Used to create a csv file for a stack of powder data sets suitable for display
165    purposes only; no y-calc or weights are exported only x & y-obs
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 = 'stacked CSV file',
172            extension='.csv',
173            longFormatName = 'Export powder data sets as a (csv) file - x,y-o1,y-o2,... only'
174            )
175        self.exporttype = ['powder']
176        #self.multiple = False # only allow one histogram to be selected
177        self.multiple = True
178
179    def Exporter(self,event=None):
180        '''Export a set of powder data as a csv file
181        '''
182        # the export process starts here
183        self.InitExport(event)
184        # load all of the tree into a set of dicts
185        self.loadTree()
186        if self.ExportSelect( # set export parameters
187            AskFile='single' # get a file name/directory to save in
188            ): return
189        filenamelist = []
190        csvData = []
191        headList = ["x",]
192        digitList = []
193        fileroot = G2obj.MakeUniqueLabel(self.MakePWDRfilename(self.histnam[0]),filenamelist)
194        # create an instrument parameter file
195        self.filename = os.path.join(self.dirname,fileroot + self.extension)
196        for ihst,hist in enumerate(self.histnam):
197            histblk = self.Histograms[hist]
198            headList.append('y_obs_'+str(ihst))
199            if not ihst:
200                digitList = [(13,3),]
201                csvData.append(histblk['Data'][0])
202            digitList += [(13,3),]
203            csvData.append(histblk['Data'][1])
204            print('Histogram '+str(hist)+' written to file '+str(self.fullpath))
205        self.OpenFile()
206        WriteList(self,headList)
207        for vallist in np.array(csvData).T:
208            line = ""
209            for val,digits in zip(vallist,digitList):
210                if line: line += ','
211                line += G2py3.FormatValue(val,digits)
212            self.Write(line)
213        self.CloseFile()
214
215class ExportPowderReflCSV(G2IO.ExportBaseclass):
216    '''Used to create a csv file of reflections from a powder data set
217
218    :param wx.Frame G2frame: reference to main GSAS-II frame
219    '''
220    def __init__(self,G2frame):
221        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
222            G2frame=G2frame,
223            formatName = 'reflection list as CSV',
224            extension='.csv',
225            longFormatName = 'Export powder reflection list as a comma-separated (csv) file'
226            )
227        self.exporttype = ['powder']
228        self.multiple = False # only allow one histogram to be selected
229
230    def Exporter(self,event=None):
231        '''Export a set of powder reflections as a csv file
232        '''
233        self.InitExport(event)
234        # load all of the tree into a set of dicts
235        self.loadTree()
236        if self.ExportSelect(): return  # set export parameters, get file name
237        self.OpenFile()
238        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
239        histblk = self.Histograms[hist]
240        # table of phases
241        self.Write('"Phase name","phase #"')
242        for i,phasenam in enumerate(sorted(histblk['Reflection Lists'])):
243            self.Write('"'+str(phasenam)+'",'+str(i))
244        self.Write('')
245        # note addition of a phase # flag at end (i)
246        for i,phasenam in enumerate(sorted(histblk['Reflection Lists'])):
247            phasDict = histblk['Reflection Lists'][phasenam]
248            if phasDict['Super']:
249                WriteList(self,("h","k","l","m","2-theta","F_obs","F_calc","phase","mult","phase #"))
250                fmt = "{:.0f},{:.0f},{:.0f},{:.0f},{:.3f},{:.3f},{:.3f},{:.2f},{:.0f},{:d}"
251                refList = phasDict['RefList']
252                for refItem in refList:
253                    h,k,l,m,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr = refItem[:12]
254                    self.Write(fmt.format(h,k,l,m,pos,Fobs,Fcalc,phase,mult,i))               
255            else:
256                WriteList(self,("h","k","l","2-theta","F_obs","F_calc","phase","mult","phase #"))
257                fmt = "{:.0f},{:.0f},{:.0f},{:.3f},{:.3f},{:.3f},{:.2f},{:.0f},{:d}"
258                refList = phasDict['RefList']
259                for refItem in refList:
260                    h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr = refItem[:11]
261                    self.Write(fmt.format(h,k,l,pos,Fobs,Fcalc,phase,mult,i))
262        self.CloseFile()
263        print(str(hist)+'reflections written to file '+str(self.fullpath))
264
265class ExportSingleCSV(G2IO.ExportBaseclass):
266    '''Used to create a csv file with single crystal reflection data
267
268    :param wx.Frame G2frame: reference to main GSAS-II frame
269    '''
270    def __init__(self,G2frame):
271        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
272            G2frame=G2frame,
273            formatName = 'CSV file',
274            extension='.csv',
275            longFormatName = 'Export reflection list as a comma-separated (csv) file'
276            )
277        self.exporttype = ['single']
278        self.multiple = False # only allow one histogram to be selected
279
280    def Exporter(self,event=None):
281        '''Export a set of single crystal data as a csv file
282        '''
283        # the export process starts here
284        self.InitExport(event)
285        # load all of the tree into a set of dicts
286        self.loadTree()
287        if self.ExportSelect(): return  # set export parameters, get file name
288        self.OpenFile()
289        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
290        histblk = self.Histograms[hist]
291        WriteList(self,("h","k","l","d-space","F_obs","sig(Fobs)","F_calc","phase","mult"))
292        fmt = "{:.0f},{:.0f},{:.0f},{:.3f},{:.2f},{:.4f},{:.2f},{:.2f},{:.0f}"
293        for (
294            h,k,l,mult,dsp,Fobs,sigFobs,Fcalc,FobsT,FcalcT,phase,Icorr
295            ) in histblk['Data']['RefList']:
296            self.Write(fmt.format(h,k,l,dsp,Fobs,sigFobs,Fcalc,phase,mult))
297        self.CloseFile()
298        print(str(hist)+' written to file '+str(self.fullname))                       
299
300class ExportStrainCSV(G2IO.ExportBaseclass):
301    '''Used to create a csv file with single crystal reflection data
302
303    :param wx.Frame G2frame: reference to main GSAS-II frame
304    '''
305    def __init__(self,G2frame):
306        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
307            G2frame=G2frame,
308            formatName = 'Strain CSV file',
309            extension='.csv',
310            longFormatName = 'Export strain results as a comma-separated (csv) file'
311            )
312        self.exporttype = ['image']
313        self.multiple = False # only allow one histogram to be selected
314
315    def Exporter(self,event=None):
316        '''Export a set of single crystal data as a csv file
317        '''
318        # the export process starts here
319        self.InitExport(event)
320        # load all of the tree into a set of dicts
321        self.loadTree()
322        if self.ExportSelect(): return  # set export parameters, get file name
323        self.OpenFile()
324        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
325        histblk = self.Histograms[hist]
326        StrSta = histblk['Stress/Strain']
327        WriteList(self,("Dset","Dcalc","e11","sig(e11)","e12","sig(e12)","e22","sig(e22)"))
328        fmt = 2*"{:.5f},"+6*"{:.0f},"
329        fmt1 = "{:.5f}"
330        fmt2 = "{:.2f},{:.5f},{:.5f}"
331        for item in StrSta['d-zero']:
332            Emat = item['Emat']
333            Esig = item['Esig']
334            self.Write(fmt.format(item['Dset'],item['Dcalc'],Emat[0],Esig[0],Emat[1],Esig[1],Emat[2],Esig[2]))
335        for item in StrSta['d-zero']:
336            WriteList(self,("Azm","dobs","dcalc","Dset="+fmt1.format(item['Dset'])))
337            ring = np.vstack((item['ImtaObs'],item['ImtaCalc']))
338            for dat in ring.T:
339                self.Write(fmt2.format(dat[1],dat[0],dat[2]))           
340        self.CloseFile()
341        print(str(hist)+' written to file '+str(self.fullpath))
Note: See TracBrowser for help on using the repository browser.