source: trunk/exports/G2export_csv.py @ 4573

Last change on this file since 4573 was 4549, checked in by vondreele, 16 months ago

use AddToNotebook? in Refine - remove wx.CallAfter? for self.ReloadFrom? GPX so AddToNotebook? would work
Add csv Exporter for reflectometry data
replace all calls to G2py3.FormatValue? with explicit %.6g formats in G2export_csv - FormatValue? screwed up values.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 27.1 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3########### SVN repository information ###################
4# $Date: 2020-08-19 19:53:47 +0000 (Wed, 19 Aug 2020) $
5# $Author: toby $
6# $Revision: 4549 $
7# $URL: trunk/exports/G2export_csv.py $
8# $Id: G2export_csv.py 4549 2020-08-19 19:53:47Z 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'''
18from __future__ import division, print_function
19import os.path
20import numpy as np
21import GSASIIpath
22GSASIIpath.SetVersionNumber("$Revision: 4549 $")
23import GSASIIIO as G2IO
24import GSASIIpy3 as G2py3
25import GSASIIobj as G2obj
26import GSASIImath as G2mth
27import GSASIIpwd as G2pwd
28import GSASIIlattice as G2lat
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 Writer(self,hist,phasenam,mode='w'):
58        self.OpenFile(mode=mode)
59        # test for aniso atoms
60        aniso = False
61        AtomsList = self.GetAtoms(phasenam)
62        for lbl,typ,mult,xyz,td in AtomsList:
63            if len(td) != 1:
64                aniso = True
65                break
66        if mode == 'w':
67            lbllist = ['hist','phase','a','b','c','alpha','beta','gamma','volume']
68            lbllist += ["atm label","elem","mult","x","y","z","frac","Uiso"]
69            if aniso: lbllist += ['U11','U22','U33','U12','U13','U23']
70            WriteList(self,lbllist)
71           
72        cellList,cellSig = self.GetCell(phasenam)
73        line = '"' + str(hist)+ '","' + str(phasenam) + '"'
74        for defsig,val in zip(
75            3*[-0.00001] + 3*[-0.001] + [-0.01], # sets sig. figs.
76            cellList
77            ):
78            txt = G2mth.ValEsd(val,defsig)
79            if line: line += ','
80            line += txt
81        self.Write(line)
82
83        # get atoms and print separated by commas
84        AtomsList = self.GetAtoms(phasenam)
85        for lbl,typ,mult,xyz,td in AtomsList:
86            line = ",,,,,,,,,"
87            line += '"' + lbl + '","' + typ + '",' + str(mult) + ','
88            for val,sig in xyz:
89                line += G2mth.ValEsd(val,-abs(sig))
90                line += ","
91            if len(td) == 1:
92                line += G2mth.ValEsd(td[0][0],-abs(td[0][1]))
93            else:
94                line += ","
95                for val,sig in td:
96                    line += G2mth.ValEsd(val,-abs(sig))
97                    line += ","
98            self.Write(line)
99
100        if mode == 'w':
101            print('Phase '+phasenam+' written to file '+self.fullpath)
102        self.CloseFile()
103   
104    def Exporter(self,event=None):
105        '''Export a phase as a csv file
106        '''
107        # the export process starts here
108        self.InitExport(event)
109        # load all of the tree into a set of dicts
110        self.loadTree()
111        # create a dict with refined values and their uncertainties
112        self.loadParmDict()
113        if self.ExportSelect(): return # set export parameters; get file name
114        self.OpenFile()
115        # if more than one phase is selected, put them into a single file
116        for phasenam in self.phasenam:
117            phasedict = self.Phases[phasenam] # pointer to current phase info           
118            i = self.Phases[phasenam]['pId']
119            self.Write('"'+"Phase "+str(phasenam)+" from "+str(self.G2frame.GSASprojectfile)+'"')
120            self.Write('\n"Space group:","'+str(phasedict['General']['SGData']['SpGrp'].strip())+'"')
121            # get cell parameters & print them
122            cellList,cellSig = self.GetCell(phasenam)
123            WriteList(self,['a','b','c','alpha','beta','gamma','volume'])
124
125            line = ''
126            for defsig,val in zip(
127                3*[-0.00001] + 3*[-0.001] + [-0.01], # sign values to use when no sigma
128                cellList
129                ):
130                txt = G2mth.ValEsd(val,defsig)
131                if line: line += ','
132                line += txt
133            self.Write(line)
134               
135            # get atoms and print separated by commas
136            AtomsList = self.GetAtoms(phasenam)
137            # check for aniso atoms
138            aniso = False
139            for lbl,typ,mult,xyz,td in AtomsList:
140                if len(td) != 1: aniso = True               
141            lbllist = ["label","elem","mult","x","y","z","frac","Uiso"]
142            if aniso: lbllist += ['U11','U22','U33','U12','U13','U23']
143            WriteList(self,lbllist)
144               
145            for lbl,typ,mult,xyz,td in AtomsList:
146                line = '"' + lbl + '","' + typ + '",' + str(mult) + ','
147                for val,sig in xyz:
148                    line += G2mth.ValEsd(val,-abs(sig))
149                    line += ","
150                if len(td) == 1:
151                    line += G2mth.ValEsd(td[0][0],-abs(td[0][1]))
152                else:
153                    line += ","
154                    for val,sig in td:
155                        line += G2mth.ValEsd(val,-abs(sig))
156                        line += ","
157                self.Write(line)
158            print('Phase '+phasenam+' written to file '+self.fullpath)
159        self.CloseFile()
160
161class ExportPowderCSV(G2IO.ExportBaseclass):
162    '''Used to create a csv file for a powder data set
163
164    :param wx.Frame G2frame: reference to main GSAS-II frame
165    '''
166    def __init__(self,G2frame):
167        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
168            G2frame=G2frame,
169            formatName = 'histogram CSV file',
170            extension='.csv',
171            longFormatName = 'Export powder data as comma-separated (csv) file'
172            )
173        self.exporttype = ['powder']
174        #self.multiple = False # only allow one histogram to be selected
175        self.multiple = True
176
177    def Writer(self,TreeName,filename=None):
178        #print filename
179        self.OpenFile(filename)
180        histblk = self.Histograms[TreeName]
181        Parms = self.Histograms[TreeName]['Instrument Parameters'][0]
182        for parm in Parms:
183            if parm in ['Type','Source',]:
184                line = '"Instparm: %s","%s"'%(parm,Parms[parm][0])
185            elif parm in ['Lam','Zero',]:
186                line = '"Instparm: %s",%10.6f'%(parm,Parms[parm][1])
187            else:
188                line = '"Instparm: %s",%10.2f'%(parm,Parms[parm][1])
189            self.Write(line)
190        Samp = self.Histograms[TreeName]['Sample Parameters']
191        for samp in Samp:
192            if samp in ['InstrName','Type']:
193                line = '"Samparm: %s",%s'%(samp,Samp[samp])
194            elif samp in ['Azimuth','Chi','Gonio. radius','Omega','Phi','Pressure','Temperature','Time']:
195                line = '"Samparm: %s",%10.2f'%(samp,Samp[samp])
196            elif samp in ['DisplaceX','DisplaceY','Scale','Shift','SurfRoughA','SurfRoughB','Transparency']:
197                line = '"Samparm: %s",%10.2f'%(samp,Samp[samp][0])
198            else:
199                continue
200            self.Write(line)
201        WriteList(self,("x","y_obs","weight","y_calc","y_bkg","Q"))
202        digitList = 2*((13,3),) + ((13,5),) + 3*((13,3),)
203        for vallist in zip(histblk['Data'][0],
204                       histblk['Data'][1],
205                       histblk['Data'][2],
206                       histblk['Data'][3],
207                       histblk['Data'][4],
208                       #histblk['Data'][5],
209                       2*np.pi/G2lat.Pos2dsp(Parms,histblk['Data'][0])
210                       ):
211            line = ""
212            for val,digits in zip(vallist,digitList):
213                if line: line += ','
214                line += '%.6g'%val
215#                line += G2py3.FormatValue(val,digits)
216            self.Write(line)
217        self.CloseFile()
218       
219    def Exporter(self,event=None):
220        '''Export a set of powder 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( # set export parameters
227            AskFile='single' # get a file name/directory to save in
228            ): return
229        filenamelist = []
230        for hist in self.histnam:
231            if len(self.histnam) == 1:
232                name = self.filename
233            else:    # multiple files: create a unique name from the histogram
234                name = self.MakePWDRfilename(hist)
235            fileroot = os.path.splitext(G2obj.MakeUniqueLabel(name,filenamelist))[0]
236            # create the file
237            self.filename = os.path.join(self.dirname,fileroot + self.extension)
238            self.Writer(hist)
239            print('Histogram '+hist+' written to file '+self.fullpath)
240
241class ExportMultiPowderCSV(G2IO.ExportBaseclass):
242    '''Used to create a csv file for a stack of powder data sets suitable for display
243    purposes only; no y-calc or weights are exported only x & y-obs
244    :param wx.Frame G2frame: reference to main GSAS-II frame
245    '''
246    def __init__(self,G2frame):
247        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
248            G2frame=G2frame,
249            formatName = 'stacked CSV file',
250            extension='.csv',
251            longFormatName = 'Export powder data sets as a (csv) file - x,y-o1,y-o2,... only'
252            )
253        self.exporttype = ['powder']
254        #self.multiple = False # only allow one histogram to be selected
255        self.multiple = True
256
257    def Exporter(self,event=None):
258        '''Export a set of powder data as a single 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='ask' # only one file is ever written
266            ): return
267        csvData = []
268        headList = ["x",]
269        digitList = []
270        self.filename = os.path.join(self.dirname,os.path.splitext(self.filename)[0]
271                                     + self.extension)
272        for ihst,hist in enumerate(self.histnam):
273            histblk = self.Histograms[hist]
274            headList.append('y_obs_'+G2obj.StripUnicode(hist[5:].replace(' ','_')))
275            if not ihst:
276                digitList = [(13,3),]
277                csvData.append(histblk['Data'][0])
278            digitList += [(13,3),]
279            csvData.append(histblk['Data'][1])
280            print('Histogram '+hist+' added to file...')
281        self.OpenFile()
282        WriteList(self,headList)
283        for vallist in np.array(csvData).T:
284            line = ""
285            for val,digits in zip(vallist,digitList):
286                if line: line += ','
287                line += '%.6g'%val
288#                line += G2py3.FormatValue(val,digits)
289            self.Write(line)
290        self.CloseFile()
291        print('...file '+self.fullpath+' written')
292
293class ExportPowderReflCSV(G2IO.ExportBaseclass):
294    '''Used to create a csv file of reflections from a powder data set
295
296    :param wx.Frame G2frame: reference to main GSAS-II frame
297    '''
298    def __init__(self,G2frame):
299        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
300            G2frame=G2frame,
301            formatName = 'reflection list as CSV',
302            extension='.csv',
303            longFormatName = 'Export powder reflection list as a comma-separated (csv) file'
304            )
305        self.exporttype = ['powder']
306        self.multiple = False # only allow one histogram to be selected
307
308    def Writer(self,TreeName,filename=None):
309        print(filename)
310        self.OpenFile(filename)
311        histblk = self.Histograms[TreeName]
312        self.write(TreeName,histblk)
313        self.CloseFile()
314        print(TreeName+' reflections written to file '+self.fullpath)
315       
316    def Exporter(self,event=None):
317        '''Export a set of powder reflections as a csv file
318        '''
319        self.InitExport(event)
320        # load all of the tree into a set of dicts
321        self.loadTree()
322        if self.ExportSelect(): return  # set export parameters, get file name
323        hist = list(self.histnam)[0] # there should only be one histogram, in any case take the 1st
324        histblk = self.Histograms[hist]
325        self.OpenFile()
326        self.write(hist,histblk)
327        self.CloseFile()
328        print(hist+' reflections written to file '+self.fullpath)
329       
330    def write(self,hist,histblk):
331        self.Write('"Histogram"')
332        self.Write('"'+hist+'"')
333        self.Write('')
334        # table of phases
335        self.Write('"Phase name","phase #"')
336        for i,phasenam in enumerate(sorted(histblk['Reflection Lists'])):
337            self.Write('"'+str(phasenam)+'",'+str(i))
338        self.Write('')
339        # note addition of a phase # flag at end (i)
340        for i,phasenam in enumerate(sorted(histblk['Reflection Lists'])):
341            phasDict = histblk['Reflection Lists'][phasenam]
342            tname = {'T':'TOF','C':'2-theta','B':'2-theta'}[phasDict['Type'][2]]
343            if phasDict.get('Super',False):
344                WriteList(self,("h","k","l","m","d-sp",tname,"F_obs","F_calc","phase","mult","sig","gam","FWHM","Prfo","phase #"))
345                if 'T' in phasDict['Type']:
346                    fmt = "{:.0f},{:.0f},{:.0f},{:.0f},{:.5f},{:.3f},{:.3f},{:.3f},{:.2f},{:.0f},{:.3f},{:.3f},{:.3f},{:.4f},{:d}"
347                else:
348                    fmt = "{:.0f},{:.0f},{:.0f},{:.0f},{:.5f},{:.3f},{:.3f},{:.3f},{:.2f},{:.0f},{:.5f},{:.5f},{:.5f},{:.4f},{:d}"
349                refList = phasDict['RefList']
350                for refItem in refList:
351                    if 'T' in phasDict['Type']:
352                        h,k,l,m,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr,x,x,x,Prfo = refItem[:17]
353                        FWHM = G2pwd.getgamFW(gam,sig)
354                        self.Write(fmt.format(h,k,l,m,dsp,pos,Fobs,Fcalc,phase,mult,sig,gam,FWHM,i))
355                    elif 'C' in phasDict['Type']:        #convert to deg       
356                        h,k,l,m,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr,Prfo = refItem[:14]
357                        s = np.sqrt(max(sig,0.0001))/100.   #var -> sig in deg
358                        g = gam/100.    #-> deg
359                        FWHM = G2pwd.getgamFW(g,s)
360                        self.Write(fmt.format(h,k,l,m,dsp,pos,Fobs,Fcalc,phase,mult,s,g,FWHM,i))
361                    elif 'B' in phasDict['Type']:        #convert to deg       
362                        h,k,l,m,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr,x,x,x,Prfo = refItem[:17]
363                        s = np.sqrt(max(sig,0.0001))/100.   #var -> sig in deg
364                        g = gam/100.    #-> deg
365                        FWHM = G2pwd.getgamFW(g,s)
366                        self.Write(fmt.format(h,k,l,m,dsp,pos,Fobs,Fcalc,phase,mult,s,g,FWHM,i))
367            else:
368                WriteList(self,("h","k","l","d-sp",tname,"F_obs","F_calc","phase","mult","sig","gam","FWHM","Prfo","phase #"))
369                if 'T' in phasDict['Type']:
370                    fmt = "{:.0f},{:.0f},{:.0f},{:.5f},{:.3f},{:.3f},{:.3f},{:.2f},{:.0f},{:.3f},{:.3f},{:.3f},{:.4f},{:d}"
371                else:
372                    fmt = "{:.0f},{:.0f},{:.0f},{:.5f},{:.3f},{:.3f},{:.3f},{:.2f},{:.0f},{:.5f},{:.5f},{:.5f},{:.4f},{:d}"
373                refList = phasDict['RefList']
374                for refItem in refList:
375                    if 'T' in phasDict['Type']:
376                        h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr,x,x,x,Prfo = refItem[:16]
377                        FWHM = G2pwd.getgamFW(gam,sig)
378                        self.Write(fmt.format(h,k,l,dsp,pos,Fobs,Fcalc,phase,mult,sig,gam,FWHM,Prfo,i))
379                    elif 'C' in phasDict['Type']:        #convert to deg       
380                        h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr,Prfo = refItem[:13]
381                        g = gam/100.
382                        s = np.sqrt(max(sig,0.0001))/100.
383                        FWHM = G2pwd.getgamFW(g,s)
384                        self.Write(fmt.format(h,k,l,dsp,pos,Fobs,Fcalc,phase,mult,s,g,FWHM,Prfo,i))
385                    elif 'B' in phasDict['Type']:        #convert to deg       
386                        h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr,x,x,x,Prfo = refItem[:16]
387                        g = gam/100.
388                        s = np.sqrt(max(sig,0.0001))/100.
389                        FWHM = G2pwd.getgamFW(g,s)
390                        self.Write(fmt.format(h,k,l,dsp,pos,Fobs,Fcalc,phase,mult,s,g,FWHM,Prfo,i))
391       
392class ExportSASDCSV(G2IO.ExportBaseclass):
393    '''Used to create a csv file for a small angle data set
394
395    :param wx.Frame G2frame: reference to main GSAS-II frame
396    '''
397    def __init__(self,G2frame):
398        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
399            G2frame=G2frame,
400            formatName = 'CSV file',
401            extension='.csv',
402            longFormatName = 'Export small angle data as comma-separated (csv) file'
403            )
404        self.exporttype = ['sasd']
405        #self.multiple = False # only allow one histogram to be selected
406        self.multiple = True
407
408    def Writer(self,TreeName,filename=None):
409        self.OpenFile(filename)
410        histblk = self.Histograms[TreeName]
411        if len(self.Histograms[TreeName]['Models']['Size']['Distribution']):
412            self.Write('"Size Distribution"')
413            Distr = np.array(self.Histograms[TreeName]['Models']['Size']['Distribution'])
414            WriteList(self,("bin_pos","bin_width","bin_value"))
415            digitList = 2*((13,3),)+((13,4,'g'),)
416            for bindata in Distr.T:
417                line = ""
418                for val,digits in zip(bindata,digitList):
419                    if line: line += ','
420                    line += G2py3.FormatValue(val,digits)
421                self.Write(line)           
422        self.Write('"Small angle data"')
423        Parms = self.Histograms[TreeName]['Instrument Parameters'][0]
424        for parm in Parms:
425            if parm in ['Type','Source',]:
426                line = '"Instparm: %s","%s"'%(parm,Parms[parm][0])
427            elif parm in ['Lam',]:
428                line = '"Instparm: %s",%10.6f'%(parm,Parms[parm][1])
429            else:
430                line = '"Instparm: %s",%10.2f'%(parm,Parms[parm][1])
431            self.Write(line)
432        WriteList(self,("q","y_obs","y_sig","y_calc","y_bkg"))
433        digitList = 5*((13,5,'g'),)
434        for vallist in zip(histblk['Data'][0],
435                       histblk['Data'][1],
436                       1./np.sqrt(histblk['Data'][2]),
437                       histblk['Data'][3],
438                       histblk['Data'][4],
439                       ):
440            line = ""
441            for val,digits in zip(vallist,digitList):
442                if line: line += ','
443                line += '%.6g'%val
444#                line += G2py3.FormatValue(val,digits)
445            self.Write(line)
446        self.CloseFile()
447       
448    def Exporter(self,event=None):
449        '''Export a set of small angle data as a csv file
450        '''
451        # the export process starts here
452        self.InitExport(event)
453        # load all of the tree into a set of dicts
454        self.loadTree()
455        if self.ExportSelect( # set export parameters
456            AskFile='single' # get a file name/directory to save in
457            ): return
458        filenamelist = []
459        for hist in self.histnam:
460            if len(self.histnam) == 1:
461                name = self.filename
462            else:    # multiple files: create a unique name from the histogram
463                name = self.MakePWDRfilename(hist)
464            fileroot = os.path.splitext(G2obj.MakeUniqueLabel(name,filenamelist))[0]
465            # create the file
466            self.filename = os.path.join(self.dirname,fileroot + self.extension)
467            self.Writer(hist)
468            print('Histogram '+hist+' written to file '+self.fullpath)
469
470class ExportREFDCSV(G2IO.ExportBaseclass):
471    '''Used to create a csv file for a reflectometry data set
472
473    :param wx.Frame G2frame: reference to main GSAS-II frame
474    '''
475    def __init__(self,G2frame):
476        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
477            G2frame=G2frame,
478            formatName = 'CSV file',
479            extension='.csv',
480            longFormatName = 'Export reflectometry data as comma-separated (csv) file'
481            )
482        self.exporttype = ['refd']
483        #self.multiple = False # only allow one histogram to be selected
484        self.multiple = True
485
486    def Writer(self,TreeName,filename=None):
487        self.OpenFile(filename)
488        histblk = self.Histograms[TreeName]
489        self.Write('"Reflectometry data"')
490        Parms = self.Histograms[TreeName]['Instrument Parameters'][0]
491        for parm in Parms:
492            if parm in ['Type','Source',]:
493                line = '"Instparm: %s","%s"'%(parm,Parms[parm][0])
494            elif parm in ['Lam',]:
495                line = '"Instparm: %s",%10.6f'%(parm,Parms[parm][1])
496            else:
497                line = '"Instparm: %s",%10.2f'%(parm,Parms[parm][1])
498            self.Write(line)
499        WriteList(self,("q","y_obs","y_sig","y_calc","y_bkg"))
500        digitList = 5*((13,5,'g'),)
501        for vallist in zip(histblk['Data'][0],
502                       histblk['Data'][1],
503                       1./np.sqrt(histblk['Data'][2]),
504                       histblk['Data'][3],
505                       histblk['Data'][4],
506                       ):
507            line = ""
508            for val,digits in zip(vallist,digitList):
509                if line: line += ','
510                line += '%.6g'%val
511#                line += G2py3.FormatValue(val,digits)
512            self.Write(line)
513        self.CloseFile()
514       
515    def Exporter(self,event=None):
516        '''Export a set of reflectometry data as a csv file
517        '''
518        # the export process starts here
519        self.InitExport(event)
520        # load all of the tree into a set of dicts
521        self.loadTree()
522        if self.ExportSelect( # set export parameters
523            AskFile='single' # get a file name/directory to save in
524            ): return
525        filenamelist = []
526        for hist in self.histnam:
527            if len(self.histnam) == 1:
528                name = self.filename
529            else:    # multiple files: create a unique name from the histogram
530                name = self.MakePWDRfilename(hist)
531            fileroot = os.path.splitext(G2obj.MakeUniqueLabel(name,filenamelist))[0]
532            # create the file
533            self.filename = os.path.join(self.dirname,fileroot + self.extension)
534            self.Writer(hist)
535            print('Histogram '+hist+' written to file '+self.fullpath)
536
537class ExportSingleCSV(G2IO.ExportBaseclass):
538    '''Used to create a csv file with single crystal reflection data
539
540    :param wx.Frame G2frame: reference to main GSAS-II frame
541    '''
542    def __init__(self,G2frame):
543        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
544            G2frame=G2frame,
545            formatName = 'CSV file',
546            extension='.csv',
547            longFormatName = 'Export reflection list as a comma-separated (csv) file'
548            )
549        self.exporttype = ['single']
550        self.multiple = False # only allow one histogram to be selected
551
552    def Exporter(self,event=None):
553        '''Export a set of single crystal data as a csv file
554        '''
555        # the export process starts here
556        self.InitExport(event)
557        # load all of the tree into a set of dicts
558        self.loadTree()
559        if self.ExportSelect(): return  # set export parameters, get file name
560        self.OpenFile()
561        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
562        histblk = self.Histograms[hist]
563        for i,phasenam in enumerate(sorted(histblk['Reflection Lists'])):
564            phasDict = histblk['Reflection Lists'][phasenam]
565            tname = {'T':'TOF','C':'2-theta'}[phasDict['Type'][2]]
566            if phasDict.get('Super',False):
567                WriteList(self,("h","k","l","m",'d-sp',tname,"F_obs","F_calc","phase","mult","phase #"))
568                fmt = "{:.0f},{:.0f},{:.0f},{:.0f},{:.5f},{:.3f},{:.3f},{:.3f},{:.2f},{:.0f},{:d}"
569                refList = phasDict['RefList']
570                for refItem in refList:
571                    h,k,l,m,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr = refItem[:13]
572                    self.Write(fmt.format(h,k,l,m,dsp,pos,Fobs,Fcalc,phase,mult,i))               
573            else:
574                WriteList(self,("h","k","l",'d-sp',tname,"F_obs","F_calc","phase","mult","phase #"))
575                fmt = "{:.0f},{:.0f},{:.0f},{:.5f},{:.3f},{:.3f},{:.3f},{:.2f},{:.0f},{:d}"
576                refList = phasDict['RefList']
577                for refItem in refList:
578                    h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr = refItem[:12]
579                    self.Write(fmt.format(h,k,l,dsp,pos,Fobs,Fcalc,phase,mult,i))
580        self.CloseFile()
581        print(hist+' written to file '+self.fullname)                       
582
583class ExportStrainCSV(G2IO.ExportBaseclass):
584    '''Used to create a csv file with single crystal reflection data
585
586    :param wx.Frame G2frame: reference to main GSAS-II frame
587    '''
588    def __init__(self,G2frame):
589        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
590            G2frame=G2frame,
591            formatName = 'Strain CSV file',
592            extension='.csv',
593            longFormatName = 'Export strain results as a comma-separated (csv) file'
594            )
595        self.exporttype = ['image']
596        self.multiple = False # only allow one histogram to be selected
597
598    def Exporter(self,event=None):
599        '''Export a set of single crystal data as a csv file
600        '''
601        # the export process starts here
602        self.InitExport(event)
603        # load all of the tree into a set of dicts
604        self.loadTree()
605        if self.ExportSelect(): return  # set export parameters, get file name
606        self.OpenFile()
607        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
608        histblk = self.Histograms[hist]
609        StrSta = histblk['Stress/Strain']
610        WriteList(self,("Dset","Dcalc","e11","sig(e11)","e12","sig(e12)","e22","sig(e22)"))
611        fmt = 2*"{:.5f},"+6*"{:.0f},"
612        fmt1 = "{:.5f}"
613        fmt2 = "{:.2f},{:.5f},{:.5f}"
614        for item in StrSta['d-zero']:
615            Emat = item['Emat']
616            Esig = item['Esig']
617            self.Write(fmt.format(item['Dset'],item['Dcalc'],Emat[0],Esig[0],Emat[1],Esig[1],Emat[2],Esig[2]))
618        for item in StrSta['d-zero']:
619            WriteList(self,("Azm","dobs","dcalc","Dset="+fmt1.format(item['Dset'])))
620            ring = np.vstack((item['ImtaObs'],item['ImtaCalc']))
621            for dat in ring.T:
622                self.Write(fmt2.format(dat[1],dat[0],dat[2]))           
623        self.CloseFile()
624        print(hist+' written to file '+self.fullpath)
Note: See TracBrowser for help on using the repository browser.