source: trunk/exports/G2export_csv.py @ 1236

Last change on this file since 1236 was 1236, checked in by toby, 8 years ago

Add FXYE & XYE exporters; allow multiple powder exports; fix formatting of float32 intensities (which should be gone); minor sequential refinement changes; remove old export patterns items; new padded format routine

  • 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-05 19:51:53 +0000 (Wed, 05 Mar 2014) $
5# $Author: toby $
6# $Revision: 1236 $
7# $URL: trunk/exports/G2export_csv.py $
8# $Id: G2export_csv.py 1236 2014-03-05 19:51:53Z 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: 1236 $")
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( # set export parameters
64            AskFile=True     # prompt the user for a file name
65            ): return 
66        self.OpenFile(self.filename)
67        # if more than one format is selected, put them into a single file
68        for phasenam in self.phasenam:
69            phasedict = self.Phases[phasenam] # pointer to current phase info           
70            i = self.Phases[phasenam]['pId']
71            self.Write('"'+"Phase "+str(phasenam)+" from "+str(self.G2frame.GSASprojectfile)+'"')
72            self.Write('\n"Space group:","'+str(phasedict['General']['SGData']['SpGrp'].strip())+'"')
73            # get cell parameters & print them
74            cellList,cellSig = self.GetCell(phasenam)
75            WriteList(self,['a','b','c','alpha','beta','gamma','volume'])
76
77            line = ''
78            for defsig,val in zip(
79                3*[-0.00001] + 3*[-0.001] + [-0.01], # sign values to use when no sigma
80                cellList
81                ):
82                txt = G2mth.ValEsd(val,defsig)
83                if line: line += ','
84                line += txt
85            self.Write(line)
86               
87            # get atoms and print separated by commas
88            AtomsList = self.GetAtoms(phasenam)
89            # check for aniso atoms
90            aniso = False
91            for lbl,typ,mult,xyz,td in AtomsList:
92                if len(td) != 1: aniso = True               
93            lbllist = ["label","elem","mult","x","y","z","frac","Uiso"]
94            if aniso: lbllist += ['U11','U22','U33','U12','U13','U23']
95            WriteList(self,lbllist)
96               
97            for lbl,typ,mult,xyz,td in AtomsList:
98                line = '"' + lbl + '","' + typ + '",' + str(mult) + ','
99                for val,sig in xyz:
100                    line += G2mth.ValEsd(val,-abs(sig))
101                    line += ","
102                if len(td) == 1:
103                    line += G2mth.ValEsd(td[0][0],-abs(td[0][1]))
104                else:
105                    line += ","
106                    for val,sig in td:
107                        line += G2mth.ValEsd(val,-abs(sig))
108                        line += ","
109                self.Write(line)
110            print('Phase '+str(phasenam)+' written to file '+str(self.filename))                       
111        self.CloseFile()
112
113class ExportPowderCSV(G2IO.ExportBaseclass):
114    '''Used to create a csv file for a powder data set
115
116    :param wx.Frame G2frame: reference to main GSAS-II frame
117    '''
118    def __init__(self,G2frame):
119        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
120            G2frame=G2frame,
121            formatName = 'CSV file',
122            extension='.csv',
123            longFormatName = 'Export powder data as comma-separated (csv) file'
124            )
125        self.exporttype = ['powder']
126        #self.multiple = False # only allow one histogram to be selected
127        self.multiple = True
128
129    def Exporter(self,event=None):
130        '''Export a set of powder data as a csv file
131        '''
132        # the export process starts here
133        self.InitExport(event)
134        # load all of the tree into a set of dicts
135        self.loadTree()
136        if self.ExportSelect( # set export parameters
137            AskFile=False # use the default file name, which is ignored
138            ): return
139        filenamelist = []
140        for hist in self.histnam:
141            fileroot = G2obj.MakeUniqueLabel(self.MakePWDRfilename(hist),filenamelist)
142            self.filename = fileroot + self.extension
143            self.OpenFile()
144            histblk = self.Histograms[hist]
145            WriteList(self,("x","y_obs","weight","y_calc","y_bkg"))
146            digitList = 2*((13,3),) + ((13,5),) + 2*((13,3),)
147            for vallist 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                line = ""
155                for val,digits in zip(vallist,digitList):
156                    if line: line += ','
157                    line += G2py3.FormatValue(val,digits)
158                self.Write(line)
159            self.CloseFile()
160            print('Histogram '+str(hist)+' written to file '+str(self.filename))
161
162class ExportPowderReflCSV(G2IO.ExportBaseclass):
163    '''Used to create a csv file of reflections from a powder data set
164
165    :param wx.Frame G2frame: reference to main GSAS-II frame
166    '''
167    def __init__(self,G2frame):
168        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
169            G2frame=G2frame,
170            formatName = 'reflection list as CSV',
171            extension='.csv',
172            longFormatName = 'Export powder reflection list as a comma-separated (csv) file'
173            )
174        self.exporttype = ['powder']
175        self.multiple = False # only allow one histogram to be selected
176
177    def Exporter(self,event=None):
178        '''Export a set of powder reflections as a csv file
179        '''
180        self.InitExport(event)
181        # load all of the tree into a set of dicts
182        self.loadTree()
183        if self.ExportSelect( # set export parameters
184            AskFile=False # use the default file name
185            ): return 
186        self.OpenFile()
187        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
188        histblk = self.Histograms[hist]
189        # table of phases
190        self.Write('"Phase name","phase #"')
191        for i,phasenam in enumerate(sorted(histblk['Reflection Lists'])):
192            self.Write('"'+str(phasenam)+'",'+str(i))
193        self.Write('')
194        # note addition of a phase # flag at end (i)
195        WriteList(self,("h","k","l","2-theta","F_obs","F_calc","phase","mult","phase #"))
196        fmt = "{:.0f},{:.0f},{:.0f},{:.3f},{:.3f},{:.3f},{:.2f},{:.0f},{:d}"
197        for i,phasenam in enumerate(sorted(histblk['Reflection Lists'])):
198            for (
199                h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr
200                ) in histblk['Reflection Lists'][phasenam]['RefList']:
201                self.Write(fmt.format(h,k,l,pos,Fobs,Fcalc,phase,mult,i))
202        self.CloseFile()
203        print(str(hist)+'reflections written to file '+str(self.filename))
204
205class ExportSingleCSV(G2IO.ExportBaseclass):
206    '''Used to create a csv file with single crystal reflection data
207
208    :param wx.Frame G2frame: reference to main GSAS-II frame
209    '''
210    def __init__(self,G2frame):
211        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
212            G2frame=G2frame,
213            formatName = 'CSV file',
214            extension='.csv',
215            longFormatName = 'Export reflection list as a comma-separated (csv) file'
216            )
217        self.exporttype = ['single']
218        self.multiple = False # only allow one histogram to be selected
219
220    def Exporter(self,event=None):
221        '''Export a set of single crystal data as a csv file
222        '''
223        # the export process starts here
224        self.InitExport(event)
225        # load all of the tree into a set of dicts
226        self.loadTree()
227        if self.ExportSelect( # set export parameters
228            AskFile=False # use the default file name
229            ): return 
230        self.OpenFile()
231        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
232        histblk = self.Histograms[hist]
233        WriteList(self,("h","k","l","d-space","F_obs","sig(Fobs)","F_calc","phase","mult"))
234        fmt = "{:.0f},{:.0f},{:.0f},{:.3f},{:.2f},{:.4f},{:.2f},{:.2f},{:.0f}"
235        for (
236            h,k,l,mult,dsp,Fobs,sigFobs,Fcalc,FobsT,FcalcT,phase,Icorr
237            ) in histblk['Data']['RefList']:
238            self.Write(fmt.format(h,k,l,dsp,Fobs,sigFobs,Fcalc,phase,mult))
239        self.CloseFile()
240        print(str(hist)+' written to file '+str(self.filename))                       
241
242class ExportStrainCSV(G2IO.ExportBaseclass):
243    '''Used to create a csv file with single crystal reflection data
244
245    :param wx.Frame G2frame: reference to main GSAS-II frame
246    '''
247    def __init__(self,G2frame):
248        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
249            G2frame=G2frame,
250            formatName = 'Strain CSV file',
251            extension='.csv',
252            longFormatName = 'Export strain results as a comma-separated (csv) file'
253            )
254        self.exporttype = ['image']
255        self.multiple = False # only allow one histogram to be selected
256
257    def Exporter(self,event=None):
258        '''Export a set of single crystal data as a csv file
259        '''
260        # the export process starts here
261        self.InitExport(event)
262        # load all of the tree into a set of dicts
263        self.loadTree()
264        if self.ExportSelect( # set export parameters
265            AskFile=True # use the default file name
266            ): return 
267        self.OpenFile()
268        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
269        histblk = self.Histograms[hist]
270        StrSta = histblk['Stress/Strain']
271        WriteList(self,("Dset","Dcalc","e11","sig(e11)","e12","sig(e12)","e22","sig(e22)"))
272        fmt = 2*"{:.5f},"+6*"{:.0f},"
273        fmt1 = "{:.5f}"
274        fmt2 = "{:.2f},{:.5f},{:.5f}"
275        for item in StrSta['d-zero']:
276            Emat = item['Emat']
277            Esig = item['Esig']
278            self.Write(fmt.format(item['Dset'],item['Dcalc'],Emat[0],Esig[0],Emat[1],Esig[1],Emat[2],Esig[2]))
279        for item in StrSta['d-zero']:
280            WriteList(self,("Azm","dobs","dcalc","Dset="+fmt1.format(item['Dset'])))
281            ring = np.vstack((item['ImtaObs'],item['ImtaCalc']))
282            for dat in ring.T:
283                self.Write(fmt2.format(dat[1],dat[0],dat[2]))           
284        self.CloseFile()
285        print(str(hist)+' written to file '+str(self.filename))                       
286
Note: See TracBrowser for help on using the repository browser.