source: trunk/exports/G2export_csv.py @ 1123

Last change on this file since 1123 was 1123, checked in by toby, 10 years ago

add import and export routines to sphinx

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