source: trunk/exports/G2export_csv.py @ 2103

Last change on this file since 2103 was 2103, checked in by toby, 7 years ago

start on Andrey's bug list: 2.Trying to out put multiple CHI-files fails; saving image table does not offer *.imtbl

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 16.6 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3########### SVN repository information ###################
4# $Date: 2015-12-23 19:17:37 +0000 (Wed, 23 Dec 2015) $
5# $Author: toby $
6# $Revision: 2103 $
7# $URL: trunk/exports/G2export_csv.py $
8# $Id: G2export_csv.py 2103 2015-12-23 19:17:37Z toby $
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: 2103 $")
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 Writer(self,TreeName,filename=None):
129        self.OpenFile(filename)
130        histblk = self.Histograms[TreeName]
131        WriteList(self,("x","y_obs","weight","y_calc","y_bkg"))
132        digitList = 2*((13,3),) + ((13,5),) + 2*((13,3),)
133        for vallist in zip(histblk['Data'][0],
134                       histblk['Data'][1],
135                       histblk['Data'][2],
136                       histblk['Data'][3],
137                       histblk['Data'][4],
138                       #histblk['Data'][5],
139                       ):
140            line = ""
141            for val,digits in zip(vallist,digitList):
142                if line: line += ','
143                line += G2py3.FormatValue(val,digits)
144            self.Write(line)
145        self.CloseFile()
146       
147    def Exporter(self,event=None):
148        '''Export a set of powder data as a csv file
149        '''
150        # the export process starts here
151        self.InitExport(event)
152        # load all of the tree into a set of dicts
153        self.loadTree()
154        if self.ExportSelect( # set export parameters
155            AskFile='single' # get a file name/directory to save in
156            ): return
157        filenamelist = []
158        for hist in self.histnam:
159            #if len(self.histnam) > 1:
160            #    # multiple files: create a unique name from the histogram
161            #    fileroot = G2obj.MakeUniqueLabel(self.MakePWDRfilename(hist),filenamelist)
162            #    # create an instrument parameter file
163            #    self.filename = os.path.join(self.dirname,fileroot + self.extension)
164            self.Writer(hist)
165            print('Histogram '+str(hist)+' written to file '+str(self.fullpath))
166
167class ExportMultiPowderCSV(G2IO.ExportBaseclass):
168    '''Used to create a csv file for a stack of powder data sets suitable for display
169    purposes only; no y-calc or weights are exported only x & y-obs
170    :param wx.Frame G2frame: reference to main GSAS-II frame
171    '''
172    def __init__(self,G2frame):
173        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
174            G2frame=G2frame,
175            formatName = 'stacked CSV file',
176            extension='.csv',
177            longFormatName = 'Export powder data sets as a (csv) file - x,y-o1,y-o2,... only'
178            )
179        self.exporttype = ['powder']
180        #self.multiple = False # only allow one histogram to be selected
181        self.multiple = True
182
183    def Exporter(self,event=None):
184        '''Export a set of powder data as a csv file
185        '''
186        # the export process starts here
187        self.InitExport(event)
188        # load all of the tree into a set of dicts
189        self.loadTree()
190        if self.ExportSelect( # set export parameters
191            AskFile='single' # get a file name/directory to save in
192            ): return
193        filenamelist = []
194        csvData = []
195        headList = ["x",]
196        digitList = []
197        fileroot = G2obj.MakeUniqueLabel(self.MakePWDRfilename(self.histnam[0]),filenamelist)
198        # create a file
199        self.filename = os.path.join(self.dirname,fileroot + self.extension)
200        for ihst,hist in enumerate(self.histnam):
201            histblk = self.Histograms[hist]
202            headList.append('y_obs_'+str(ihst))
203            if not ihst:
204                digitList = [(13,3),]
205                csvData.append(histblk['Data'][0])
206            digitList += [(13,3),]
207            csvData.append(histblk['Data'][1])
208            print('Histogram '+str(hist)+' written to file '+str(self.fullpath))
209        self.OpenFile()
210        WriteList(self,headList)
211        for vallist in np.array(csvData).T:
212            line = ""
213            for val,digits in zip(vallist,digitList):
214                if line: line += ','
215                line += G2py3.FormatValue(val,digits)
216            self.Write(line)
217        self.CloseFile()
218
219class ExportPowderReflCSV(G2IO.ExportBaseclass):
220    '''Used to create a csv file of reflections from a powder data set
221
222    :param wx.Frame G2frame: reference to main GSAS-II frame
223    '''
224    def __init__(self,G2frame):
225        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
226            G2frame=G2frame,
227            formatName = 'reflection list as CSV',
228            extension='.csv',
229            longFormatName = 'Export powder reflection list as a comma-separated (csv) file'
230            )
231        self.exporttype = ['powder']
232        self.multiple = False # only allow one histogram to be selected
233
234    def Exporter(self,event=None):
235        '''Export a set of powder reflections as a csv file
236        '''
237        self.InitExport(event)
238        # load all of the tree into a set of dicts
239        self.loadTree()
240        if self.ExportSelect(): return  # set export parameters, get file name
241        self.OpenFile()
242        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
243        histblk = self.Histograms[hist]
244        self.Write('"Histogram"')
245        self.Write('"'+hist+'"')
246        self.Write('')
247        # table of phases
248        self.Write('"Phase name","phase #"')
249        for i,phasenam in enumerate(sorted(histblk['Reflection Lists'])):
250            self.Write('"'+str(phasenam)+'",'+str(i))
251        self.Write('')
252        # note addition of a phase # flag at end (i)
253        for i,phasenam in enumerate(sorted(histblk['Reflection Lists'])):
254            phasDict = histblk['Reflection Lists'][phasenam]
255            tname = {'T':'TOF','C':'2-theta'}[phasDict['Type'][2]]
256            if phasDict.get('Super',False):
257                WriteList(self,("h","k","l","m",tname,"F_obs","F_calc","phase","mult","sig","gam","FWHM","Prfo","phase #"))
258                if 'T' in phasDict['Type']:
259                    fmt = "{:.0f},{:.0f},{:.0f},{:.0f},{:.3f},{:.3f},{:.3f},{:.2f},{:.0f},{:.3f},{:.3f},{:.3f},{:.4f},{:d}"
260                else:
261                    fmt = "{:.0f},{:.0f},{:.0f},{:.0f},{:.3f},{:.3f},{:.3f},{:.2f},{:.0f},{:.5f},{:.5f},{:.5f},{:.4f},{:d}"
262                refList = phasDict['RefList']
263                for refItem in refList:
264                    if 'T' in phasDict['Type']:
265                        h,k,l,m,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr,x,x,x,Prfo = refItem[:17]
266                        FWHM = G2pwd.getgamFW(gam,sig)
267                        self.Write(fmt.format(h,k,l,m,pos,Fobs,Fcalc,phase,mult,sig,gam,FWHM,i))
268                    else:        #convert to deg       
269                        h,k,l,m,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr,Prfo = refItem[:14]
270                        FWHM = G2pwd.getgamFW(gam,sig)
271                        self.Write(fmt.format(h,k,l,m,pos,Fobs,Fcalc,phase,mult,    \
272                            np.sqrt(max(sig,0.0001))/100.,gam/100.,FWHM/100.,i))
273            else:
274                WriteList(self,("h","k","l",tname,"F_obs","F_calc","phase","mult","sig","gam","FWHM","Prfo","phase #"))
275                if 'T' in phasDict['Type']:
276                    fmt = "{:.0f},{:.0f},{:.0f},{:.3f},{:.3f},{:.3f},{:.2f},{:.0f},{:.3f},{:.3f},{:.3f},{:.4f},{:d}"
277                else:
278                    fmt = "{:.0f},{:.0f},{:.0f},{:.3f},{:.3f},{:.3f},{:.2f},{:.0f},{:.5f},{:.5f},{:.5f},{:.4f},{:d}"
279                refList = phasDict['RefList']
280                for refItem in refList:
281                    if 'T' in phasDict['Type']:
282                        h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr,x,x,x,Prfo = refItem[:16]
283                        FWHM = G2pwd.getgamFW(gam,sig)
284                        self.Write(fmt.format(h,k,l,pos,Fobs,Fcalc,phase,mult,sig,gam,FWHM,Prfo,i))
285                    else:        #convert to deg       
286                        h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr,Prfo = refItem[:13]
287                        FWHM = G2pwd.getgamFW(gam,sig)
288                        self.Write(fmt.format(h,k,l,pos,Fobs,Fcalc,phase,mult,  \
289                            np.sqrt(max(sig,0.0001))/100.,gam/100.,FWHM/100.,Prfo,i))
290        self.CloseFile()
291        print(str(hist)+'reflections written to file '+str(self.fullpath))
292
293class ExportSingleCSV(G2IO.ExportBaseclass):
294    '''Used to create a csv file with single crystal reflection data
295
296    :param wx.Frame G2frame: reference to main GSAS-II frame
297    '''
298    def __init__(self,G2frame):
299        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
300            G2frame=G2frame,
301            formatName = 'CSV file',
302            extension='.csv',
303            longFormatName = 'Export reflection list as a comma-separated (csv) file'
304            )
305        self.exporttype = ['single']
306        self.multiple = False # only allow one histogram to be selected
307
308    def Exporter(self,event=None):
309        '''Export a set of single crystal data as a csv file
310        '''
311        # the export process starts here
312        self.InitExport(event)
313        # load all of the tree into a set of dicts
314        self.loadTree()
315        if self.ExportSelect(): return  # set export parameters, get file name
316        self.OpenFile()
317        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
318        histblk = self.Histograms[hist]
319        for i,phasenam in enumerate(sorted(histblk['Reflection Lists'])):
320            phasDict = histblk['Reflection Lists'][phasenam]
321            tname = {'T':'TOF','C':'2-theta'}[phasDict['Type'][2]]
322            if phasDict.get('Super',False):
323                WriteList(self,("h","k","l","m",tname,"F_obs","F_calc","phase","mult","phase #"))
324                fmt = "{:.0f},{:.0f},{:.0f},{:.0f},{:.3f},{:.3f},{:.3f},{:.2f},{:.0f},{:d}"
325                refList = phasDict['RefList']
326                for refItem in refList:
327                    h,k,l,m,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr = refItem[:13]
328                    self.Write(fmt.format(h,k,l,m,pos,Fobs,Fcalc,phase,mult,i))               
329            else:
330                WriteList(self,("h","k","l",tname,"F_obs","F_calc","phase","mult","phase #"))
331                fmt = "{:.0f},{:.0f},{:.0f},{:.3f},{:.3f},{:.3f},{:.2f},{:.0f},{:d}"
332                refList = phasDict['RefList']
333                for refItem in refList:
334                    h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr = refItem[:12]
335                    self.Write(fmt.format(h,k,l,pos,Fobs,Fcalc,phase,mult,i))
336        self.CloseFile()
337        print(str(hist)+' written to file '+str(self.fullname))                       
338
339class ExportStrainCSV(G2IO.ExportBaseclass):
340    '''Used to create a csv file with single crystal reflection data
341
342    :param wx.Frame G2frame: reference to main GSAS-II frame
343    '''
344    def __init__(self,G2frame):
345        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
346            G2frame=G2frame,
347            formatName = 'Strain CSV file',
348            extension='.csv',
349            longFormatName = 'Export strain results as a comma-separated (csv) file'
350            )
351        self.exporttype = ['image']
352        self.multiple = False # only allow one histogram to be selected
353
354    def Exporter(self,event=None):
355        '''Export a set of single crystal data as a csv file
356        '''
357        # the export process starts here
358        self.InitExport(event)
359        # load all of the tree into a set of dicts
360        self.loadTree()
361        if self.ExportSelect(): return  # set export parameters, get file name
362        self.OpenFile()
363        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
364        histblk = self.Histograms[hist]
365        StrSta = histblk['Stress/Strain']
366        WriteList(self,("Dset","Dcalc","e11","sig(e11)","e12","sig(e12)","e22","sig(e22)"))
367        fmt = 2*"{:.5f},"+6*"{:.0f},"
368        fmt1 = "{:.5f}"
369        fmt2 = "{:.2f},{:.5f},{:.5f}"
370        for item in StrSta['d-zero']:
371            Emat = item['Emat']
372            Esig = item['Esig']
373            self.Write(fmt.format(item['Dset'],item['Dcalc'],Emat[0],Esig[0],Emat[1],Esig[1],Emat[2],Esig[2]))
374        for item in StrSta['d-zero']:
375            WriteList(self,("Azm","dobs","dcalc","Dset="+fmt1.format(item['Dset'])))
376            ring = np.vstack((item['ImtaObs'],item['ImtaCalc']))
377            for dat in ring.T:
378                self.Write(fmt2.format(dat[1],dat[0],dat[2]))           
379        self.CloseFile()
380        print(str(hist)+' written to file '+str(self.fullpath))
Note: See TracBrowser for help on using the repository browser.