source: trunk/exports/G2export_csv.py

Last change on this file was 5150, checked in by toby, 14 months ago

add CSV seq exports; fix multiphase seq CIF exports

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 27.2 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3########### SVN repository information ###################
4# $Date: 2022-01-21 19:37:39 +0000 (Fri, 21 Jan 2022) $
5# $Author: vondreele $
6# $Revision: 5150 $
7# $URL: trunk/exports/G2export_csv.py $
8# $Id: G2export_csv.py 5150 2022-01-21 19:37:39Z vondreele $
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: 5150 $")
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,mode='w'):
178        #print filename
179        self.OpenFile(filename,mode=mode)
180        self.Write('"Histogram","'+TreeName+'"')
181        histblk = self.Histograms[TreeName]
182        Parms = self.Histograms[TreeName]['Instrument Parameters'][0]
183        for parm in Parms:
184            if parm in ['Type','Source',]:
185                line = '"Instparm: %s","%s"'%(parm,Parms[parm][0])
186            elif parm in ['Lam','Zero',]:
187                line = '"Instparm: %s",%10.6f'%(parm,Parms[parm][1])
188            else:
189                line = '"Instparm: %s",%10.2f'%(parm,Parms[parm][1])
190            self.Write(line)
191        Samp = self.Histograms[TreeName]['Sample Parameters']
192        for samp in Samp:
193            if samp in ['InstrName','Type']:
194                line = '"Samparm: %s",%s'%(samp,Samp[samp])
195            elif samp in ['Azimuth','Chi','Gonio. radius','Omega','Phi','Pressure','Temperature','Time']:
196                line = '"Samparm: %s",%10.2f'%(samp,Samp[samp])
197            elif samp in ['DisplaceX','DisplaceY','Scale','Shift','SurfRoughA','SurfRoughB','Transparency']:
198                line = '"Samparm: %s",%10.2f'%(samp,Samp[samp][0])
199            else:
200                continue
201            self.Write(line)
202        WriteList(self,("x","y_obs","weight","y_calc","y_bkg","Q"))
203        digitList = 2*((13,3),) + ((13,5),) + 3*((13,3),)
204        for vallist in zip(histblk['Data'][0],
205                       histblk['Data'][1],
206                       histblk['Data'][2],
207                       histblk['Data'][3],
208                       histblk['Data'][4],
209                       #histblk['Data'][5],
210                       2*np.pi/G2lat.Pos2dsp(Parms,histblk['Data'][0])
211                       ):
212            line = ""
213            for val,digits in zip(vallist,digitList):
214                if line: line += ','
215                line += '%.6g'%val
216#                line += G2py3.FormatValue(val,digits)
217            self.Write(line)
218        if mode == 'w':
219            print('Powder data written to CSV file '+self.fullpath)
220        self.CloseFile()
221       
222    def Exporter(self,event=None):
223        '''Export a set of powder data as a csv file
224        '''
225        # the export process starts here
226        self.InitExport(event)
227        # load all of the tree into a set of dicts
228        self.loadTree()
229        if self.ExportSelect( # set export parameters
230            AskFile='single' # get a file name/directory to save in
231            ): return
232        filenamelist = []
233        for hist in self.histnam:
234            if len(self.histnam) == 1:
235                name = self.filename
236            else:    # multiple files: create a unique name from the histogram
237                name = self.MakePWDRfilename(hist)
238            fileroot = os.path.splitext(G2obj.MakeUniqueLabel(name,filenamelist))[0]
239            # create the file
240            self.filename = os.path.join(self.dirname,fileroot + self.extension)
241            self.Writer(hist)
242            print('Histogram '+hist+' written to file '+self.fullpath)
243
244class ExportMultiPowderCSV(G2IO.ExportBaseclass):
245    '''Used to create a csv file for a stack of powder data sets suitable for display
246    purposes only; no y-calc or weights are exported only x & y-obs
247    :param wx.Frame G2frame: reference to main GSAS-II frame
248    '''
249    def __init__(self,G2frame):
250        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
251            G2frame=G2frame,
252            formatName = 'stacked CSV file',
253            extension='.csv',
254            longFormatName = 'Export powder data sets as a (csv) file - x,y-o1,y-o2,... only'
255            )
256        self.exporttype = ['powder']
257        #self.multiple = False # only allow one histogram to be selected
258        self.multiple = True
259
260    def Exporter(self,event=None):
261        '''Export a set of powder data as a single csv file
262        '''
263        # the export process starts here
264        self.InitExport(event)
265        # load all of the tree into a set of dicts
266        self.loadTree()
267        if self.ExportSelect( # set export parameters
268            AskFile='ask' # only one file is ever written
269            ): return
270        csvData = []
271        headList = ["x",]
272        digitList = []
273        self.filename = os.path.join(self.dirname,os.path.splitext(self.filename)[0]
274                                     + self.extension)
275        for ihst,hist in enumerate(self.histnam):
276            histblk = self.Histograms[hist]
277            headList.append('y_obs_'+G2obj.StripUnicode(hist[5:].replace(' ','_')))
278            if not ihst:
279                digitList = [(13,3),]
280                csvData.append(histblk['Data'][0])
281            digitList += [(13,3),]
282            csvData.append(histblk['Data'][1])
283            print('Histogram '+hist+' added to file...')
284        self.OpenFile()
285        WriteList(self,headList)
286        for vallist in np.array(csvData).T:
287            line = ""
288            for val,digits in zip(vallist,digitList):
289                if line: line += ','
290                line += '%.6g'%val
291#                line += G2py3.FormatValue(val,digits)
292            self.Write(line)
293        self.CloseFile()
294        print('...file '+self.fullpath+' written')
295
296class ExportPowderReflCSV(G2IO.ExportBaseclass):
297    '''Used to create a csv file of reflections from a powder data set
298
299    :param wx.Frame G2frame: reference to main GSAS-II frame
300    '''
301    def __init__(self,G2frame):
302        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
303            G2frame=G2frame,
304            formatName = 'reflection list CSV file',
305            extension='.csv',
306            longFormatName = 'Export powder reflection list as a comma-separated (csv) file'
307            )
308        self.exporttype = ['powder']
309        self.multiple = False # only allow one histogram to be selected
310
311    def Writer(self,TreeName,filename=None,mode='w'):
312        self.OpenFile(filename,mode=mode)
313        histblk = self.Histograms[TreeName]
314        self.write(TreeName,histblk)
315        self.CloseFile()
316        if mode == "w": print(TreeName+' reflections written to file '+self.fullpath)
317       
318    def Exporter(self,event=None):
319        '''Export a set of powder reflections as a csv file
320        '''
321        self.InitExport(event)
322        # load all of the tree into a set of dicts
323        self.loadTree()
324        if self.ExportSelect(): return  # set export parameters, get file name
325        hist = list(self.histnam)[0] # there should only be one histogram, in any case take the 1st
326        histblk = self.Histograms[hist]
327        self.OpenFile()
328        self.write(hist,histblk)
329        self.CloseFile()
330        print(hist+' reflections written to file '+self.fullpath)
331       
332    def write(self,hist,histblk):
333        self.Write('"Histogram","'+hist+'"')
334        self.Write('')
335        # table of phases
336        self.Write('"Phase name","phase #"')
337        for i,phasenam in enumerate(sorted(histblk['Reflection Lists'])):
338            self.Write('"'+str(phasenam)+'",'+str(i))
339        self.Write('')
340        # note addition of a phase # flag at end (i)
341        for i,phasenam in enumerate(sorted(histblk['Reflection Lists'])):
342            phasDict = histblk['Reflection Lists'][phasenam]
343            tname = {'T':'TOF','C':'2-theta','B':'2-theta'}[phasDict['Type'][2]]
344            if phasDict.get('Super',False):
345                WriteList(self,("h","k","l","m","d-sp",tname,"F_obs","F_calc","phase","mult","sig","gam","FWHM","Prfo","phase #"))
346                if 'T' in phasDict['Type']:
347                    fmt = "{:.0f},{:.0f},{:.0f},{:.0f},{:.5f},{:.3f},{:.3f},{:.3f},{:.2f},{:.0f},{:.3f},{:.3f},{:.3f},{:.4f},{:d}"
348                else:
349                    fmt = "{:.0f},{:.0f},{:.0f},{:.0f},{:.5f},{:.3f},{:.3f},{:.3f},{:.2f},{:.0f},{:.5f},{:.5f},{:.5f},{:.4f},{:d}"
350                refList = phasDict['RefList']
351                for refItem in refList:
352                    if 'T' in phasDict['Type']:
353                        h,k,l,m,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr,x,x,x,Prfo = refItem[:17]
354                        FWHM = G2pwd.getgamFW(gam,sig)
355                        self.Write(fmt.format(h,k,l,m,dsp,pos,Fobs,Fcalc,phase,mult,sig,gam,FWHM,i))
356                    elif 'C' in phasDict['Type']:        #convert to deg       
357                        h,k,l,m,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr,Prfo = refItem[:14]
358                        s = np.sqrt(max(sig,0.0001))/100.   #var -> sig in deg
359                        g = gam/100.    #-> deg
360                        FWHM = G2pwd.getgamFW(g,s)
361                        self.Write(fmt.format(h,k,l,m,dsp,pos,Fobs,Fcalc,phase,mult,s,g,FWHM,i))
362                    elif 'B' in phasDict['Type']:        #convert to deg       
363                        h,k,l,m,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr,x,x,x,Prfo = refItem[:17]
364                        s = np.sqrt(max(sig,0.0001))/100.   #var -> sig in deg
365                        g = gam/100.    #-> deg
366                        FWHM = G2pwd.getgamFW(g,s)
367                        self.Write(fmt.format(h,k,l,m,dsp,pos,Fobs,Fcalc,phase,mult,s,g,FWHM,i))
368            else:
369                WriteList(self,("h","k","l","d-sp",tname,"F_obs","F_calc","phase","mult","sig","gam","FWHM","Prfo","phase #"))
370                if 'T' in phasDict['Type']:
371                    fmt = "{:.0f},{:.0f},{:.0f},{:.5f},{:.3f},{:.3f},{:.3f},{:.2f},{:.0f},{:.3f},{:.3f},{:.3f},{:.4f},{:d}"
372                else:
373                    fmt = "{:.0f},{:.0f},{:.0f},{:.5f},{:.3f},{:.3f},{:.3f},{:.2f},{:.0f},{:.5f},{:.5f},{:.5f},{:.4f},{:d}"
374                refList = phasDict['RefList']
375                for refItem in refList:
376                    if 'T' in phasDict['Type']:
377                        h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr,x,x,x,Prfo = refItem[:16]
378                        FWHM = G2pwd.getgamFW(gam,sig)
379                        self.Write(fmt.format(h,k,l,dsp,pos,Fobs,Fcalc,phase,mult,sig,gam,FWHM,Prfo,i))
380                    elif 'C' in phasDict['Type']:        #convert to deg       
381                        h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr,Prfo = refItem[:13]
382                        g = gam/100.
383                        s = np.sqrt(max(sig,0.0001))/100.
384                        FWHM = G2pwd.getgamFW(g,s)
385                        self.Write(fmt.format(h,k,l,dsp,pos,Fobs,Fcalc,phase,mult,s,g,FWHM,Prfo,i))
386                    elif 'B' in phasDict['Type']:        #convert to deg       
387                        h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr,x,x,x,Prfo = refItem[:16]
388                        g = gam/100.
389                        s = np.sqrt(max(sig,0.0001))/100.
390                        FWHM = G2pwd.getgamFW(g,s)
391                        self.Write(fmt.format(h,k,l,dsp,pos,Fobs,Fcalc,phase,mult,s,g,FWHM,Prfo,i))
392       
393class ExportSASDCSV(G2IO.ExportBaseclass):
394    '''Used to create a csv file for a small angle data set
395
396    :param wx.Frame G2frame: reference to main GSAS-II frame
397    '''
398    def __init__(self,G2frame):
399        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
400            G2frame=G2frame,
401            formatName = 'CSV file',
402            extension='.csv',
403            longFormatName = 'Export small angle data as comma-separated (csv) file'
404            )
405        self.exporttype = ['sasd']
406        #self.multiple = False # only allow one histogram to be selected
407        self.multiple = True
408
409    def Writer(self,TreeName,filename=None):
410        self.OpenFile(filename)
411        histblk = self.Histograms[TreeName]
412        if len(self.Histograms[TreeName]['Models']['Size']['Distribution']):
413            self.Write('"Size Distribution"')
414            Distr = np.array(self.Histograms[TreeName]['Models']['Size']['Distribution'])
415            WriteList(self,("bin_pos","bin_width","bin_value"))
416            digitList = 2*((13,3),)+((13,4,'g'),)
417            for bindata in Distr.T:
418                line = ""
419                for val,digits in zip(bindata,digitList):
420                    if line: line += ','
421                    line += G2py3.FormatValue(val,digits)
422                self.Write(line)           
423        self.Write('"Small angle data"')
424        Parms = self.Histograms[TreeName]['Instrument Parameters'][0]
425        for parm in Parms:
426            if parm in ['Type','Source',]:
427                line = '"Instparm: %s","%s"'%(parm,Parms[parm][0])
428            elif parm in ['Lam',]:
429                line = '"Instparm: %s",%10.6f'%(parm,Parms[parm][1])
430            else:
431                line = '"Instparm: %s",%10.2f'%(parm,Parms[parm][1])
432            self.Write(line)
433        WriteList(self,("q","y_obs","y_sig","y_calc","y_bkg"))
434        digitList = 5*((13,5,'g'),)
435        for vallist in zip(histblk['Data'][0],
436                       histblk['Data'][1],
437                       1./np.sqrt(histblk['Data'][2]),
438                       histblk['Data'][3],
439                       histblk['Data'][4],
440                       ):
441            line = ""
442            for val,digits in zip(vallist,digitList):
443                if line: line += ','
444                line += '%.6g'%val
445#                line += G2py3.FormatValue(val,digits)
446            self.Write(line)
447        self.CloseFile()
448       
449    def Exporter(self,event=None):
450        '''Export a set of small angle data as a csv file
451        '''
452        # the export process starts here
453        self.InitExport(event)
454        # load all of the tree into a set of dicts
455        self.loadTree()
456        if self.ExportSelect( # set export parameters
457            AskFile='single' # get a file name/directory to save in
458            ): return
459        filenamelist = []
460        for hist in self.histnam:
461            if len(self.histnam) == 1:
462                name = self.filename
463            else:    # multiple files: create a unique name from the histogram
464                name = self.MakePWDRfilename(hist)
465            fileroot = os.path.splitext(G2obj.MakeUniqueLabel(name,filenamelist))[0]
466            # create the file
467            self.filename = os.path.join(self.dirname,fileroot + self.extension)
468            self.Writer(hist)
469            print('Histogram '+hist+' written to file '+self.fullpath)
470
471class ExportREFDCSV(G2IO.ExportBaseclass):
472    '''Used to create a csv file for a reflectometry data set
473
474    :param wx.Frame G2frame: reference to main GSAS-II frame
475    '''
476    def __init__(self,G2frame):
477        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
478            G2frame=G2frame,
479            formatName = 'CSV file',
480            extension='.csv',
481            longFormatName = 'Export reflectometry data as comma-separated (csv) file'
482            )
483        self.exporttype = ['refd']
484        #self.multiple = False # only allow one histogram to be selected
485        self.multiple = True
486
487    def Writer(self,TreeName,filename=None):
488        self.OpenFile(filename)
489        histblk = self.Histograms[TreeName]
490        self.Write('"Reflectometry data"')
491        Parms = self.Histograms[TreeName]['Instrument Parameters'][0]
492        for parm in Parms:
493            if parm in ['Type','Source',]:
494                line = '"Instparm: %s","%s"'%(parm,Parms[parm][0])
495            elif parm in ['Lam',]:
496                line = '"Instparm: %s",%10.6f'%(parm,Parms[parm][1])
497            else:
498                line = '"Instparm: %s",%10.2f'%(parm,Parms[parm][1])
499            self.Write(line)
500        WriteList(self,("q","y_obs","y_sig","y_calc","y_bkg"))
501        digitList = 5*((13,5,'g'),)
502        for vallist in zip(histblk['Data'][0],
503                       histblk['Data'][1],
504                       1./np.sqrt(histblk['Data'][2]),
505                       histblk['Data'][3],
506                       histblk['Data'][4],
507                       ):
508            line = ""
509            for val,digits in zip(vallist,digitList):
510                if line: line += ','
511                line += '%.6g'%val
512#                line += G2py3.FormatValue(val,digits)
513            self.Write(line)
514        self.CloseFile()
515       
516    def Exporter(self,event=None):
517        '''Export a set of reflectometry data as a csv file
518        '''
519        # the export process starts here
520        self.InitExport(event)
521        # load all of the tree into a set of dicts
522        self.loadTree()
523        if self.ExportSelect( # set export parameters
524            AskFile='single' # get a file name/directory to save in
525            ): return
526        filenamelist = []
527        for hist in self.histnam:
528            if len(self.histnam) == 1:
529                name = self.filename
530            else:    # multiple files: create a unique name from the histogram
531                name = self.MakePWDRfilename(hist)
532            fileroot = os.path.splitext(G2obj.MakeUniqueLabel(name,filenamelist))[0]
533            # create the file
534            self.filename = os.path.join(self.dirname,fileroot + self.extension)
535            self.Writer(hist)
536            print('Histogram '+hist+' written to file '+self.fullpath)
537
538class ExportSingleCSV(G2IO.ExportBaseclass):
539    '''Used to create a csv file with single crystal reflection data
540
541    :param wx.Frame G2frame: reference to main GSAS-II frame
542    '''
543    def __init__(self,G2frame):
544        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
545            G2frame=G2frame,
546            formatName = 'CSV file',
547            extension='.csv',
548            longFormatName = 'Export reflection list as a comma-separated (csv) file'
549            )
550        self.exporttype = ['single']
551        self.multiple = False # only allow one histogram to be selected
552
553    def Exporter(self,event=None):
554        '''Export a set of single crystal data as a csv file
555        '''
556        # the export process starts here
557        self.InitExport(event)
558        # load all of the tree into a set of dicts
559        self.loadTree()
560        if self.ExportSelect(): return  # set export parameters, get file name
561        self.OpenFile()
562        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
563        histblk = self.Histograms[hist]
564        for i,phasenam in enumerate(sorted(histblk['Reflection Lists'])):
565            phasDict = histblk['Reflection Lists'][phasenam]
566            tname = {'T':'TOF','C':'2-theta'}[phasDict['Type'][2]]
567            if phasDict.get('Super',False):
568                WriteList(self,("h","k","l","m",'d-sp',tname,"F_obs","F_calc","phase","mult","phase #"))
569                fmt = "{:.0f},{:.0f},{:.0f},{:.0f},{:.5f},{:.3f},{:.3f},{:.3f},{:.2f},{:.0f},{:d}"
570                refList = phasDict['RefList']
571                for refItem in refList:
572                    h,k,l,m,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr = refItem[:13]
573                    self.Write(fmt.format(h,k,l,m,dsp,pos,Fobs,Fcalc,phase,mult,i))               
574            else:
575                WriteList(self,("h","k","l",'d-sp',tname,"F_obs","F_calc","phase","mult","phase #"))
576                fmt = "{:.0f},{:.0f},{:.0f},{:.5f},{:.3f},{:.3f},{:.3f},{:.2f},{:.0f},{:d}"
577                refList = phasDict['RefList']
578                for refItem in refList:
579                    h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,Icorr = refItem[:12]
580                    self.Write(fmt.format(h,k,l,dsp,pos,Fobs,Fcalc,phase,mult,i))
581        self.CloseFile()
582        print(hist+' written to file '+self.fullname)                       
583
584class ExportStrainCSV(G2IO.ExportBaseclass):
585    '''Used to create a csv file with single crystal reflection data
586
587    :param wx.Frame G2frame: reference to main GSAS-II frame
588    '''
589    def __init__(self,G2frame):
590        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
591            G2frame=G2frame,
592            formatName = 'Strain CSV file',
593            extension='.csv',
594            longFormatName = 'Export strain results as a comma-separated (csv) file'
595            )
596        self.exporttype = ['image']
597        self.multiple = False # only allow one histogram to be selected
598
599    def Exporter(self,event=None):
600        '''Export a set of single crystal data as a csv file
601        '''
602        # the export process starts here
603        self.InitExport(event)
604        # load all of the tree into a set of dicts
605        self.loadTree()
606        if self.ExportSelect(): return  # set export parameters, get file name
607        self.OpenFile()
608        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
609        histblk = self.Histograms[hist]
610        StrSta = histblk['Stress/Strain']
611        WriteList(self,("Dset","Dcalc","e11","sig(e11)","e12","sig(e12)","e22","sig(e22)"))
612        fmt = 2*"{:.5f},"+6*"{:.0f},"
613        fmt1 = "{:.5f}"
614        fmt2 = "{:.2f},{:.5f},{:.5f}"
615        for item in StrSta['d-zero']:
616            Emat = item['Emat']
617            Esig = item['Esig']
618            self.Write(fmt.format(item['Dset'],item['Dcalc'],Emat[0],Esig[0],Emat[1],Esig[1],Emat[2],Esig[2]))
619        for item in StrSta['d-zero']:
620            WriteList(self,("Azm","dobs","dcalc","Dset="+fmt1.format(item['Dset'])))
621            ring = np.vstack((item['ImtaObs'],item['ImtaCalc']))
622            for dat in ring.T:
623                self.Write(fmt2.format(dat[1],dat[0],dat[2]))           
624        self.CloseFile()
625        print(hist+' written to file '+self.fullpath)
Note: See TracBrowser for help on using the repository browser.