source: trunk/exports/G2export_csv.py @ 1191

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

CSV exporter for strain results

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 11.5 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3########### SVN repository information ###################
4# $Date: 2014-01-10 20:46:36 +0000 (Fri, 10 Jan 2014) $
5# $Author: vondreele $
6# $Revision: 1191 $
7# $URL: trunk/exports/G2export_csv.py $
8# $Id: G2export_csv.py 1191 2014-01-10 20:46:36Z 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: 1191 $")
22import GSASIIIO as G2IO
23#import GSASIIgrid as G2gd
24#import GSASIIstrIO as G2stIO
25import GSASIImath as G2mth
26#import GSASIIlattice as G2lat
27#import GSASIIspc as G2spc
28#import GSASIIphsGUI as G2pg
29#import GSASIIstrMain as G2stMn
30
31def WriteList(obj,headerItems):
32    '''Write a CSV header
33
34    :param object obj: Exporter object
35    :param list headerItems: items to write as a header
36    '''
37    line = ''
38    for lbl in headerItems:
39        if line: line += ','
40        line += '"'+lbl+'"'
41    obj.Write(line)
42
43class ExportPhaseCSV(G2IO.ExportBaseclass):
44    '''Used to create a csv file for a phase
45
46    :param wx.Frame G2frame: reference to main GSAS-II frame
47    '''
48    def __init__(self,G2frame):
49        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
50            G2frame=G2frame,
51            formatName = 'CSV file',
52            extension='.csv',
53            longFormatName = 'Export phase as comma-separated (csv) file'
54            )
55        self.exporttype = ['phase']
56        self.multiple = True # allow multiple phases to be selected
57
58    def Exporter(self,event=None):
59        '''Export a phase as a csv file
60        '''
61        # the export process starts here
62        self.InitExport(event)
63        # load all of the tree into a set of dicts
64        self.loadTree()
65        # create a dict with refined values and their uncertainties
66        self.loadParmDict()
67        if self.ExportSelect( # set export parameters
68            AskFile=True     # prompt the user for a file name
69            ): return 
70        self.OpenFile(self.filename)
71        # if more than one format is selected, put them into a single file
72        for phasenam in self.phasenam:
73            phasedict = self.Phases[phasenam] # pointer to current phase info           
74            i = self.Phases[phasenam]['pId']
75            self.Write('"'+"Phase "+str(phasenam)+" from "+str(self.G2frame.GSASprojectfile)+'"')
76            self.Write('\n"Space group:","'+str(phasedict['General']['SGData']['SpGrp'].strip())+'"')
77            # get cell parameters & print them
78            cellList,cellSig = self.GetCell(phasenam)
79            WriteList(self,['a','b','c','alpha','beta','gamma','volume'])
80
81            line = ''
82            for defsig,val in zip(
83                3*[-0.00001] + 3*[-0.001] + [-0.01], # sign values to use when no sigma
84                cellList
85                ):
86                txt = G2mth.ValEsd(val,defsig)
87                if line: line += ','
88                line += txt
89            self.Write(line)
90               
91            # get atoms and print separated by commas
92            AtomsList = self.GetAtoms(phasenam)
93            # check for aniso atoms
94            aniso = False
95            for lbl,typ,mult,xyz,td in AtomsList:
96                if len(td) != 1: aniso = True               
97            lbllist = ["label","elem","mult","x","y","z","frac","Uiso"]
98            if aniso: lbllist += ['U11','U22','U33','U12','U13','U23']
99            WriteList(self,lbllist)
100               
101            for lbl,typ,mult,xyz,td in AtomsList:
102                line = '"' + lbl + '","' + typ + '",' + str(mult) + ','
103                for val,sig in xyz:
104                    line += G2mth.ValEsd(val,-abs(sig))
105                    line += ","
106                if len(td) == 1:
107                    line += G2mth.ValEsd(td[0][0],-abs(td[0][1]))
108                else:
109                    line += ","
110                    for val,sig in td:
111                        line += G2mth.ValEsd(val,-abs(sig))
112                        line += ","
113                self.Write(line)
114            print('Phase '+str(phasenam)+' written to file '+str(self.filename))                       
115        self.CloseFile()
116
117class ExportPowderCSV(G2IO.ExportBaseclass):
118    '''Used to create a csv file for a powder data set
119
120    :param wx.Frame G2frame: reference to main GSAS-II frame
121    '''
122    def __init__(self,G2frame):
123        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
124            G2frame=G2frame,
125            formatName = 'CSV file',
126            extension='.csv',
127            longFormatName = 'Export powder data as comma-separated (csv) file'
128            )
129        self.exporttype = ['powder']
130        self.multiple = False # only allow one histogram to be selected
131
132    def Exporter(self,event=None):
133        '''Export a set of powder data as a csv file
134        '''
135        # the export process starts here
136        self.InitExport(event)
137        # load all of the tree into a set of dicts
138        self.loadTree()
139        if self.ExportSelect( # set export parameters
140            AskFile=False # use the default file name
141            ): return 
142        self.OpenFile()
143        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
144        histblk = self.Histograms[hist]
145        WriteList(self,("x","y_obs","weight","y_calc","y_bkg"))
146        fmt = 2*"{:.3f}," + "{:.5f}," + 2*"{:.3f},"
147        for x,yobs,yw,ycalc,ybkg,obsmcalc in zip(histblk['Data'][0],
148                                                 histblk['Data'][1],
149                                                 histblk['Data'][2],
150                                                 histblk['Data'][3],
151                                                 histblk['Data'][4],
152                                                 histblk['Data'][5],
153                                                 ):
154            self.Write(fmt.format(x,yobs,yw,ycalc,ybkg))
155        self.CloseFile()
156        print(str(hist)+' written to file '+str(self.filename))                       
157
158class ExportPowderReflCSV(G2IO.ExportBaseclass):
159    '''Used to create a csv file of reflections from a powder data set
160
161    :param wx.Frame G2frame: reference to main GSAS-II frame
162    '''
163    def __init__(self,G2frame):
164        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
165            G2frame=G2frame,
166            formatName = 'reflection list as CSV',
167            extension='.csv',
168            longFormatName = 'Export powder reflection list as a comma-separated (csv) file'
169            )
170        self.exporttype = ['powder']
171        self.multiple = False # only allow one histogram to be selected
172
173    def Exporter(self,event=None):
174        '''Export a set of powder reflections as a csv file
175        '''
176        self.InitExport(event)
177        # load all of the tree into a set of dicts
178        self.loadTree()
179        if self.ExportSelect( # set export parameters
180            AskFile=False # use the default file name
181            ): return 
182        self.OpenFile()
183        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
184        histblk = self.Histograms[hist]
185        # table of phases
186        self.Write('"Phase name","phase #"')
187        for i,phasenam in enumerate(sorted(histblk['Reflection Lists'])):
188            self.Write('"'+str(phasenam)+'",'+str(i))
189        self.Write('')
190        # note addition of a phase # flag at end (i)
191        WriteList(self,("h","k","l","2-theta","F_obs","F_calc","phase","mult","phase #"))
192        fmt = "{:.0f},{:.0f},{:.0f},{:.3f},{:.3f},{:.3f},{:.2f},{:.0f},{:d}"
193        for i,phasenam in enumerate(sorted(histblk['Reflection Lists'])):
194            for (
195                h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr
196                ) in histblk['Reflection Lists'][phasenam]['RefList']:
197                self.Write(fmt.format(h,k,l,pos,Fobs,Fcalc,phase,mult,i))
198        self.CloseFile()
199        print(str(hist)+'reflections written to file '+str(self.filename))
200
201class ExportSingleCSV(G2IO.ExportBaseclass):
202    '''Used to create a csv file with single crystal reflection data
203
204    :param wx.Frame G2frame: reference to main GSAS-II frame
205    '''
206    def __init__(self,G2frame):
207        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
208            G2frame=G2frame,
209            formatName = 'CSV file',
210            extension='.csv',
211            longFormatName = 'Export reflection list as a comma-separated (csv) file'
212            )
213        self.exporttype = ['single']
214        self.multiple = False # only allow one histogram to be selected
215
216    def Exporter(self,event=None):
217        '''Export a set of single crystal data as a csv file
218        '''
219        # the export process starts here
220        self.InitExport(event)
221        # load all of the tree into a set of dicts
222        self.loadTree()
223        if self.ExportSelect( # set export parameters
224            AskFile=False # use the default file name
225            ): return 
226        self.OpenFile()
227        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
228        histblk = self.Histograms[hist]
229        WriteList(self,("h","k","l","d-space","F_obs","sig(Fobs)","F_calc","phase","mult"))
230        fmt = "{:.0f},{:.0f},{:.0f},{:.3f},{:.2f},{:.4f},{:.2f},{:.2f},{:.0f}"
231        for (
232            h,k,l,mult,dsp,Fobs,sigFobs,Fcalc,FobsT,FcalcT,phase,Icorr
233            ) in histblk['Data']['RefList']:
234            self.Write(fmt.format(h,k,l,dsp,Fobs,sigFobs,Fcalc,phase,mult))
235        self.CloseFile()
236        print(str(hist)+' written to file '+str(self.filename))                       
237
238class ExportStrainCSV(G2IO.ExportBaseclass):
239    '''Used to create a csv file with single crystal reflection data
240
241    :param wx.Frame G2frame: reference to main GSAS-II frame
242    '''
243    def __init__(self,G2frame):
244        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
245            G2frame=G2frame,
246            formatName = 'Strain CSV file',
247            extension='.csv',
248            longFormatName = 'Export strain results as a comma-separated (csv) file'
249            )
250        self.exporttype = ['image']
251        self.multiple = False # only allow one histogram to be selected
252
253    def Exporter(self,event=None):
254        '''Export a set of single crystal data as a csv file
255        '''
256        # the export process starts here
257        self.InitExport(event)
258        # load all of the tree into a set of dicts
259        self.loadTree()
260        if self.ExportSelect( # set export parameters
261            AskFile=True # use the default file name
262            ): return 
263        self.OpenFile()
264        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
265        histblk = self.Histograms[hist]
266        StrSta = histblk['Stress/Strain']
267        WriteList(self,("Dset","Dcalc","e11","sig(e11)","e12","sig(e12)","e22","sig(e22)"))
268        fmt = 2*"{:.5f},"+6*"{:.0f},"
269        fmt1 = "{:.5f}"
270        fmt2 = "{:.2f},{:.5f},{:.5f}"
271        for item in StrSta['d-zero']:
272            Emat = item['Emat']
273            Esig = item['Esig']
274            self.Write(fmt.format(item['Dset'],item['Dcalc'],Emat[0],Esig[0],Emat[1],Esig[1],Emat[2],Esig[2]))
275        for item in StrSta['d-zero']:
276            WriteList(self,("Azm","dobs","dcalc","Dset="+fmt1.format(item['Dset'])))
277            ring = np.vstack((item['ImtaObs'],item['ImtaCalc']))
278            for dat in ring.T:
279                self.Write(fmt2.format(dat[1],dat[0],dat[2]))           
280        self.CloseFile()
281        print(str(hist)+' written to file '+str(self.filename))                       
282
Note: See TracBrowser for help on using the repository browser.