source: trunk/exports/G2export_csv.py @ 1115

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

rework exports for new types

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 9.4 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3########### SVN repository information ###################
4# $Date: 2013-10-18 21:00:32 +0000 (Fri, 18 Oct 2013) $
5# $Author: toby $
6# $Revision: 1115 $
7# $URL: trunk/exports/G2export_csv.py $
8# $Id: G2export_csv.py 1115 2013-10-18 21:00:32Z toby $
9########### SVN repository information ###################
10'''Code to create .csv (comma-seaparate variable) files for
11GSAS-II data export
12'''
13import os.path
14import GSASIIpath
15GSASIIpath.SetVersionNumber("$Revision: 1115 $")
16import GSASIIIO as G2IO
17#import GSASIIgrid as G2gd
18#import GSASIIstrIO as G2stIO
19import GSASIImath as G2mth
20#import GSASIIlattice as G2lat
21#import GSASIIspc as G2spc
22#import GSASIIphsGUI as G2pg
23#import GSASIIstrMain as G2stMn
24
25def WriteList(obj,headerItems):
26    '''Write a CSV header
27
28    :param object obj: Exporter object
29    :param list headerItems: items to write as a header
30    '''
31    line = ''
32    for lbl in headerItems:
33        if line: line += ','
34        line += '"'+lbl+'"'
35    obj.Write(line)
36
37class ExportPhaseCSV(G2IO.ExportBaseclass):
38    '''Used to create a csv file for a phase
39
40    :param wx.Frame G2frame: reference to main GSAS-II frame
41    '''
42    def __init__(self,G2frame):
43        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
44            G2frame=G2frame,
45            formatName = 'CSV file',
46            extension='.csv',
47            longFormatName = 'Export phase as comma-separated (csv) file'
48            )
49        self.exporttype = ['phase']
50        self.multiple = True # allow multiple phases to be selected
51
52    def Exporter(self,event=None):
53        '''Export a phase as a csv file
54        '''
55        # the export process starts here
56        self.InitExport(event)
57        # load all of the tree into a set of dicts
58        self.loadTree()
59        # create a dict with refined values and their uncertainties
60        self.loadParmDict()
61        if self.ExportSelect( # set export parameters
62            AskFile=True     # prompt the user for a file name
63            ): return 
64        self.OpenFile(self.filename)
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.filename))                       
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
126    def Exporter(self,event=None):
127        '''Export a set of powder data as a csv file
128        '''
129        # the export process starts here
130        self.InitExport(event)
131        # load all of the tree into a set of dicts
132        self.loadTree()
133        if self.ExportSelect( # set export parameters
134            AskFile=False # use the default file name
135            ): return 
136        self.OpenFile()
137        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
138        histblk = self.Histograms[hist]
139        WriteList(self,("x","y_obs","weight","y_calc","y_bkg"))
140        fmt = 2*"{:.3f}," + "{:.5f}," + 2*"{:.3f},"
141        for x,yobs,yw,ycalc,ybkg,obsmcalc in zip(histblk['Data'][0],
142                                                 histblk['Data'][1],
143                                                 histblk['Data'][2],
144                                                 histblk['Data'][3],
145                                                 histblk['Data'][4],
146                                                 histblk['Data'][5],
147                                                 ):
148            self.Write(fmt.format(x,yobs,yw,ycalc,ybkg))
149        self.CloseFile()
150        print(str(hist)+' written to file '+str(self.filename))                       
151
152class ExportPowderReflCSV(G2IO.ExportBaseclass):
153    '''Used to create a csv file of reflections from a powder data set
154
155    :param wx.Frame G2frame: reference to main GSAS-II frame
156    '''
157    def __init__(self,G2frame):
158        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
159            G2frame=G2frame,
160            formatName = 'reflection list as CSV',
161            extension='.csv',
162            longFormatName = 'Export powder reflection list as a comma-separated (csv) file'
163            )
164        self.exporttype = ['powder']
165        self.multiple = False # only allow one histogram to be selected
166
167    def Exporter(self,event=None):
168        '''Export a set of powder reflections as a csv file
169        '''
170        self.InitExport(event)
171        # load all of the tree into a set of dicts
172        self.loadTree()
173        if self.ExportSelect( # set export parameters
174            AskFile=False # use the default file name
175            ): return 
176        self.OpenFile()
177        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
178        histblk = self.Histograms[hist]
179        # table of phases
180        self.Write('"Phase name","phase #"')
181        for i,phasenam in enumerate(sorted(histblk['Reflection Lists'])):
182            self.Write('"'+str(phasenam)+'",'+str(i))
183        self.Write('')
184        # note addition of a phase # flag at end (i)
185        WriteList(self,("h","k","l","2-theta","F_obs","F_calc","phase","mult","phase #"))
186        fmt = "{:.0f},{:.0f},{:.0f},{:.3f},{:.3f},{:.3f},{:.2f},{:.0f},{:d}"
187        for i,phasenam in enumerate(sorted(histblk['Reflection Lists'])):
188            for (
189                h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,eqlist,phaselist,Icorr,FFdict
190                ) in histblk['Reflection Lists'][phasenam]:
191                self.Write(fmt.format(h,k,l,pos,Fobs,Fcalc,phase,mult,i))
192        self.CloseFile()
193        print(str(hist)+'reflections written to file '+str(self.filename))
194
195class ExportSingleCSV(G2IO.ExportBaseclass):
196    '''Used to create a csv file with single crystal reflection data
197
198    :param wx.Frame G2frame: reference to main GSAS-II frame
199    '''
200    def __init__(self,G2frame):
201        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
202            G2frame=G2frame,
203            formatName = 'CSV file',
204            extension='.csv',
205            longFormatName = 'Export reflection list as a comma-separated (csv) file'
206            )
207        self.exporttype = ['single']
208        self.multiple = False # only allow one histogram to be selected
209
210    def Exporter(self,event=None):
211        '''Export a set of single crystal data as a csv file
212        '''
213        # the export process starts here
214        self.InitExport(event)
215        # load all of the tree into a set of dicts
216        self.loadTree()
217        if self.ExportSelect( # set export parameters
218            AskFile=False # use the default file name
219            ): return 
220        self.OpenFile()
221        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
222        histblk = self.Histograms[hist]
223        WriteList(self,("h","k","l","d-space","F_obs","sig(Fobs)","F_calc","phase","mult"))
224        fmt = "{:.0f},{:.0f},{:.0f},{:.3f},{:.2f},{:.4f},{:.2f},{:.2f},{:.0f}"
225        for (
226            h,k,l,mult,dsp,Fobs,sigFobs,Fcalc,FobsT,FcalcT,phase,eqlist,phaselist,Icorr,FFdict
227            ) in histblk['Data']:
228            self.Write(fmt.format(h,k,l,dsp,Fobs,sigFobs,Fcalc,phase,mult))
229        self.CloseFile()
230        print(str(hist)+' written to file '+str(self.filename))                       
231
Note: See TracBrowser for help on using the repository browser.