source: trunk/exports/G2export_pwdr.py @ 3136

Last change on this file since 3136 was 3136, checked in by vondreele, 4 years ago

make GSAS-II python 3.6 compliant & preserve python 2.7 use;changes:
do from future import division, print_function for all GSAS-II py sources
all menu items revised to be py 2.7/3.6 compliant
all wx.OPEN --> wx.FD_OPEN in file dialogs
all integer divides (typically for image pixel math) made explicit with ; ambiguous ones made floats as appropriate
all print "stuff" --> print (stuff)
all print >> pFile,'stuff' --> pFile.writeCIFtemplate('stuff')
all read file opens made explicit 'r' or 'rb'
all cPickle imports made for py2.7 or 3.6 as cPickle or _pickle; test for '2' platform.version_tuple[0] for py 2.7
define cPickleload to select load(fp) or load(fp,encoding='latin-1') for loading gpx files; provides cross compatibility between py 2.7/3.6 gpx files
make dict.keys() as explicit list(dict.keys()) as needed (NB: possible source of remaining py3.6 bugs)
make zip(a,b) as explicit list(zip(a,b)) as needed (NB: possible source of remaining py3.6 bugs)
select unichr/chr according test for '2' platform.version_tuple[0] for py 2.7 (G2pwdGUI * G2plot) for special characters
select wg.EVT_GRID_CELL_CHANGE (classic) or wg.EVT_GRID_CELL_CHANGED (phoenix) in grid Bind
maxint --> maxsize; used in random number stuff
raise Exception,"stuff" --> raise Exception("stuff")
wx 'classic' sizer.DeleteWindows?() or 'phoenix' sizer.Clear(True)
wx 'classic' SetToolTipString?(text) or 'phoenix' SetToolTip?(wx.ToolTip?(text)); define SetToolTipString?(self,text) to handle the choice in plots
status.SetFields? --> status.SetStatusText?
'classic' AddSimpleTool? or 'phoenix' self.AddTool? for plot toolbar; Bind different as well
define GetItemPydata? as it doesn't exist in wx 'phoenix'
allow python versions 2.7 & 3.6 to run GSAS-II
Bind override commented out - no logging capability (NB: remove all logging code?)
all import ContentsValidator? open filename & test if valid then close; filepointer removed from Reader
binary importers (mostly images) test for 'byte' type & convert as needed to satisfy py 3.6 str/byte rules

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 7.0 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3########### SVN repository information ###################
4# $Date: 2017-10-23 16:39:16 +0000 (Mon, 23 Oct 2017) $
5# $Author: vondreele $
6# $Revision: 3136 $
7# $URL: trunk/exports/G2export_pwdr.py $
8# $Id: G2export_pwdr.py 3136 2017-10-23 16:39:16Z vondreele $
9########### SVN repository information ###################
10'''
11*Module G2export_pwdr: Export powder input files*
12-------------------------------------------------
13
14Creates files used by GSAS (FXYE) & TOPAS (XYE) as input
15
16'''
17from __future__ import division, print_function
18import os.path
19import numpy as np
20import GSASIIpath
21GSASIIpath.SetVersionNumber("$Revision: 3136 $")
22import GSASIIIO as G2IO
23import GSASIIpy3 as G2py3
24import GSASIIobj as G2obj
25
26class ExportPowderFXYE(G2IO.ExportBaseclass):
27    '''Used to create a FXYE file for a powder data set
28
29    :param wx.Frame G2frame: reference to main GSAS-II frame
30    '''
31    def __init__(self,G2frame):
32        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
33            G2frame=G2frame,
34            formatName = 'GSAS FXYE file',
35            extension='.fxye',
36            longFormatName = 'Export powder data as GSAS FXYE (column) file'
37            )
38        self.exporttype = ['powder']
39        self.multiple = True
40
41    def WriteInstFile(self,hist,Inst):
42        '''Write an instrument parameter file
43        '''
44        prmname = os.path.splitext(self.filename)[0] + '.prm'
45        prmname = os.path.join(self.dirname,prmname)
46        self.OpenFile(prmname)
47        self.Write( '            123456789012345678901234567890123456789012345678901234567890        ')
48        self.Write( 'INS   BANK      1                                                               ')
49        self.Write(('INS   HTYPE   %sR                                                              ')%(Inst['Type'][0]))
50        if 'Lam1' in Inst:              #Ka1 & Ka2
51            self.Write(('INS  1 ICONS%10.7f%10.7f    0.0000               0.990    0     0.500   ')%(Inst['Lam1'][0],Inst['Lam2'][0]))
52        elif 'Lam' in Inst:             #single wavelength
53            self.Write(('INS  1 ICONS%10.7f%10.7f    0.0000               0.990    0     0.500   ')%(Inst['Lam'][1],0.0))
54        self.Write( 'INS  1 IRAD     0                                                               ')
55        self.Write( 'INS  1I HEAD                                                                    ')
56        self.Write( 'INS  1I ITYP    0    0.0000  180.0000         1                                 ')
57        self.Write(('INS  1DETAZM%10.3f                                                          ')%(Inst['Azimuth'][0]))
58        self.Write( 'INS  1PRCF1     3    8   0.00100                                                ')
59        self.Write(('INS  1PRCF11%15.6e%15.6e%15.6e%15.6e   ')%(Inst['U'][1],Inst['V'][1],Inst['W'][1],0.0))
60        self.Write(('INS  1PRCF12%15.6e%15.6e%15.6e%15.6e   ')%(Inst['X'][1],Inst['Y'][1],Inst['SH/L'][1]/2.,Inst['SH/L'][1]/2.))
61        self.CloseFile()
62        print('Parameters from '+hist+' written to file '+prmname)
63        return prmname
64
65    def Writer(self,TreeName,filename=None,prmname=''):
66        '''Write a single PWDR entry to a FXYE file
67        '''
68        histblk = self.Histograms[TreeName]
69        self.OpenFile(filename)
70        self.Write(TreeName[5:])
71        if prmname: self.Write('Instrument parameter file:'+os.path.split(prmname)[1])
72        x = 100*np.array(histblk['Data'][0])
73        # convert weights to sigmas; use largest weight as minimum esd
74        s = np.sqrt(np.maximum(0.,np.array(histblk['Data'][2])))
75        s[s==0] = np.max(s)
76        s = 1./s
77        self.Write('BANK 1 %d %d CONS %.2f %.2f 0 0 FXYE' % (
78            len(x),len(x),x[0],(x[1]-x[0])
79            ))
80#            for X,Y,S in zip(x,histblk['Data'][1],s):
81#                self.Write("{:15.6g} {:15.6g} {:15.6g}".format(X,Y,S))
82        for XYS in zip(x,histblk['Data'][1],s):
83            line = ''
84            for val in XYS:
85                line += G2py3.FormatPadValue(val,(15,6))
86            self.Write(line)
87        self.CloseFile()
88       
89    def Exporter(self,event=None):
90        '''Export one or more sets of powder data as FXYE file(s)
91        '''
92        # the export process starts here
93        self.InitExport(event)
94        self.loadTree() # load all of the tree into a set of dicts
95        if self.ExportSelect( # set export parameters
96            AskFile='single' # get a file name/directory to save in
97            ): return
98        filenamelist = []
99        for hist in self.histnam:
100            # multiple files: create a unique name from the histogram
101            fileroot = G2obj.MakeUniqueLabel(self.MakePWDRfilename(hist),filenamelist)
102            # create an instrument parameter file
103            self.filename = os.path.join(self.dirname,fileroot + self.extension)
104            histblk = self.Histograms[hist]
105            prmname = self.WriteInstFile(hist,histblk['Instrument Parameters'][0])
106            self.Writer(hist,prmname=prmname)
107            print('Histogram '+hist+' written to file '+self.fullpath)
108
109class ExportPowderXYE(G2IO.ExportBaseclass):
110    '''Used to create a Topas XYE file for a powder data set
111
112    :param wx.Frame G2frame: reference to main GSAS-II frame
113    '''
114    def __init__(self,G2frame):
115        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
116            G2frame=G2frame,
117            formatName = 'Topas XYE file',
118            extension='.xye',
119            longFormatName = 'Export powder data as Topas XYE (column) file'
120            )
121        self.exporttype = ['powder']
122        self.multiple = True
123       
124    def Writer(self,TreeName,filename=None):
125        self.OpenFile(filename)
126        histblk = self.Histograms[TreeName]
127        self.Write('/*')    #The ugly c comment delimiter used in topas!
128        self.Write('# '+TreeName[5:])  #evidently this by itself fails in topas
129        self.Write('*/')
130        x = np.array(histblk['Data'][0])
131        # convert weights to sigmas; use largest weight as minimum esd
132        s = np.sqrt(np.maximum(0.,np.array(histblk['Data'][2])))
133        s[s==0] = np.max(s)
134        s = 1./s
135        for XYS in zip(x,histblk['Data'][1],s):
136            line = ''
137            for val in XYS:
138                line += G2py3.FormatPadValue(val,(15,6))
139            self.Write(line)
140        self.CloseFile()
141
142    def Exporter(self,event=None):
143        '''Export one or more sets of powder data as XYE file(s)
144        '''
145        # the export process starts here
146        self.InitExport(event)
147        # load all of the tree into a set of dicts
148        self.loadTree()
149        if self.ExportSelect( # set export parameters
150            AskFile='single' # get a file name/directory to save in
151            ): return
152        filenamelist = []
153        for hist in self.histnam:
154            # multiple files: create a unique name from the histogram
155            fileroot = G2obj.MakeUniqueLabel(self.MakePWDRfilename(hist),filenamelist)
156            # create an instrument parameter file
157            self.filename = os.path.join(self.dirname,fileroot + self.extension)
158            self.Writer(hist)
159            print('Histogram '+hist+' written to file '+self.fullpath)
Note: See TracBrowser for help on using the repository browser.