source: trunk/exports/G2export_csv.py @ 1773

Last change on this file since 1773 was 1773, checked in by vondreele, 10 years ago

provide sig,gam & FWHM in export of PWDR reflection set as csv & txt files
add penalty fxn stuff for sph. harm. preferred orientation correction
allow editing of ODF coeff.
fix reading of fcf files

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