source: trunk/exports/G2export_csv.py @ 1261

Last change on this file since 1261 was 1261, checked in by toby, 9 years ago

reorg exports to implement directory selection

  • 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-03-24 22:22:41 +0000 (Mon, 24 Mar 2014) $
5# $Author: toby $
6# $Revision: 1261 $
7# $URL: trunk/exports/G2export_csv.py $
8# $Id: G2export_csv.py 1261 2014-03-24 22:22:41Z 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: 1261 $")
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 ExportPowderReflCSV(G2IO.ExportBaseclass):
164    '''Used to create a csv file of reflections from a powder data set
165
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 = 'reflection list as CSV',
172            extension='.csv',
173            longFormatName = 'Export powder reflection list as a comma-separated (csv) file'
174            )
175        self.exporttype = ['powder']
176        self.multiple = False # only allow one histogram to be selected
177
178    def Exporter(self,event=None):
179        '''Export a set of powder reflections as a csv file
180        '''
181        self.InitExport(event)
182        # load all of the tree into a set of dicts
183        self.loadTree()
184        if self.ExportSelect(): return  # set export parameters, get file name
185        self.OpenFile()
186        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
187        histblk = self.Histograms[hist]
188        # table of phases
189        self.Write('"Phase name","phase #"')
190        for i,phasenam in enumerate(sorted(histblk['Reflection Lists'])):
191            self.Write('"'+str(phasenam)+'",'+str(i))
192        self.Write('')
193        # note addition of a phase # flag at end (i)
194        WriteList(self,("h","k","l","2-theta","F_obs","F_calc","phase","mult","phase #"))
195        fmt = "{:.0f},{:.0f},{:.0f},{:.3f},{:.3f},{:.3f},{:.2f},{:.0f},{:d}"
196        for i,phasenam in enumerate(sorted(histblk['Reflection Lists'])):
197            for (
198                h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr
199                ) in histblk['Reflection Lists'][phasenam]['RefList']:
200                self.Write(fmt.format(h,k,l,pos,Fobs,Fcalc,phase,mult,i))
201        self.CloseFile()
202        print(str(hist)+'reflections written to file '+str(self.fullpath))
203
204class ExportSingleCSV(G2IO.ExportBaseclass):
205    '''Used to create a csv file with single crystal reflection data
206
207    :param wx.Frame G2frame: reference to main GSAS-II frame
208    '''
209    def __init__(self,G2frame):
210        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
211            G2frame=G2frame,
212            formatName = 'CSV file',
213            extension='.csv',
214            longFormatName = 'Export reflection list as a comma-separated (csv) file'
215            )
216        self.exporttype = ['single']
217        self.multiple = False # only allow one histogram to be selected
218
219    def Exporter(self,event=None):
220        '''Export a set of single crystal data as a csv file
221        '''
222        # the export process starts here
223        self.InitExport(event)
224        # load all of the tree into a set of dicts
225        self.loadTree()
226        if self.ExportSelect(): return  # set export parameters, get file name
227        self.OpenFile()
228        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
229        histblk = self.Histograms[hist]
230        WriteList(self,("h","k","l","d-space","F_obs","sig(Fobs)","F_calc","phase","mult"))
231        fmt = "{:.0f},{:.0f},{:.0f},{:.3f},{:.2f},{:.4f},{:.2f},{:.2f},{:.0f}"
232        for (
233            h,k,l,mult,dsp,Fobs,sigFobs,Fcalc,FobsT,FcalcT,phase,Icorr
234            ) in histblk['Data']['RefList']:
235            self.Write(fmt.format(h,k,l,dsp,Fobs,sigFobs,Fcalc,phase,mult))
236        self.CloseFile()
237        print(str(hist)+' written to file '+str(self.fullname))                       
238
239class ExportStrainCSV(G2IO.ExportBaseclass):
240    '''Used to create a csv file with single crystal reflection data
241
242    :param wx.Frame G2frame: reference to main GSAS-II frame
243    '''
244    def __init__(self,G2frame):
245        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
246            G2frame=G2frame,
247            formatName = 'Strain CSV file',
248            extension='.csv',
249            longFormatName = 'Export strain results as a comma-separated (csv) file'
250            )
251        self.exporttype = ['image']
252        self.multiple = False # only allow one histogram to be selected
253
254    def Exporter(self,event=None):
255        '''Export a set of single crystal data as a csv file
256        '''
257        # the export process starts here
258        self.InitExport(event)
259        # load all of the tree into a set of dicts
260        self.loadTree()
261        if self.ExportSelect(): return  # set export parameters, get file name
262        self.OpenFile()
263        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
264        histblk = self.Histograms[hist]
265        StrSta = histblk['Stress/Strain']
266        WriteList(self,("Dset","Dcalc","e11","sig(e11)","e12","sig(e12)","e22","sig(e22)"))
267        fmt = 2*"{:.5f},"+6*"{:.0f},"
268        fmt1 = "{:.5f}"
269        fmt2 = "{:.2f},{:.5f},{:.5f}"
270        for item in StrSta['d-zero']:
271            Emat = item['Emat']
272            Esig = item['Esig']
273            self.Write(fmt.format(item['Dset'],item['Dcalc'],Emat[0],Esig[0],Emat[1],Esig[1],Emat[2],Esig[2]))
274        for item in StrSta['d-zero']:
275            WriteList(self,("Azm","dobs","dcalc","Dset="+fmt1.format(item['Dset'])))
276            ring = np.vstack((item['ImtaObs'],item['ImtaCalc']))
277            for dat in ring.T:
278                self.Write(fmt2.format(dat[1],dat[0],dat[2]))           
279        self.CloseFile()
280        print(str(hist)+' written to file '+str(self.fullpath))
Note: See TracBrowser for help on using the repository browser.