source: trunk/imports/G2pwd_xye.py @ 3136

Last change on this file since 3136 was 3136, checked in by vondreele, 6 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: 6.2 KB
Line 
1# -*- coding: utf-8 -*-
2########### SVN repository information ###################
3# $Date: 2017-10-23 16:39:16 +0000 (Mon, 23 Oct 2017) $
4# $Author: vondreele $
5# $Revision: 3136 $
6# $URL: trunk/imports/G2pwd_xye.py $
7# $Id: G2pwd_xye.py 3136 2017-10-23 16:39:16Z vondreele $
8########### SVN repository information ###################
9'''
10*Module G2pwd_xye: Topas .xye data*
11------------------------------------
12
13Routine to read in powder data from a Topas-compatible .xye file
14
15'''
16
17from __future__ import division, print_function
18import os.path as ospath
19import numpy as np
20import GSASIIobj as G2obj
21import GSASIIpath
22GSASIIpath.SetVersionNumber("$Revision: 3136 $")
23class xye_ReaderClass(G2obj.ImportPowderData):
24    'Routines to import powder data from a .xye/.chi file'
25    def __init__(self):
26        super(self.__class__,self).__init__( # fancy way to self-reference
27            extensionlist=('.xye','.chi',),
28            strictExtension=False,
29            formatName = 'Topas xye or 2th Fit2D chi',
30            longFormatName = 'Topas .xye or 2th Fit2D .chi powder data file'
31            )
32        self.scriptable = True
33
34    # Validate the contents -- make sure we only have valid lines
35    def ContentsValidator(self, filename):
36        'Look through the file for expected types of lines in a valid Topas file'
37        gotCcomment = False
38        begin = True
39        self.GSAS = False
40        self.Chi = False
41        fp = open(filename,'r')
42        if '.chi' in filename:
43            self.Chi = True
44        if2theta = False
45        for i,S in enumerate(fp):
46            if not S:
47                break
48            if i > 1000: break
49            if begin:
50                if self.Chi:
51                    if i < 4:
52                        if  '2-theta' in S.lower():
53                            if2theta = True
54                        continue
55                    else:
56                        begin = False
57                else:
58                    if2theta = True
59                    if gotCcomment and S.find('*/') > -1:
60                        begin = False
61                        continue
62                    if S.strip().startswith('/*'):
63                        gotCcomment = True
64                        continue   
65                    if S[0] in ["'",'#']:
66                        continue       #ignore comments, if any
67                    else:
68                        begin = False
69                # valid line to read?
70            #vals = S.split()
71            if not if2theta:
72                self.errors = 'Not a 2-theta chi file'
73                fp.close()
74                return False
75            vals = S.replace(',',' ').replace(';',' ').split()
76            if len(vals) == 2 or len(vals) == 3:
77                continue
78            else:
79                self.errors = 'Unexpected information in line: '+str(i+1)
80                if all([ord(c) < 128 and ord(c) != 0 for c in str(S)]): # show only if ASCII
81                    self.errors += '  '+str(S)
82                else: 
83                    self.errors += '  (binary)'
84                fp.close()
85                return False
86        fp.close()
87        return True # no errors encountered
88
89    def Reader(self,filename, ParentFrame=None, **unused):
90        'Read a Topas file'
91        x = []
92        y = []
93        w = []
94        gotCcomment = False
95        begin = True
96        fp = open(filename,'r')
97        for i,S in enumerate(fp):
98            self.errors = 'Error reading line: '+str(i+1)
99            # or a block of comments delimited by /* and */
100            # or (GSAS style) each line can begin with '#'
101            if begin:
102                if self.Chi:
103                    if i < 4:
104                        continue
105                    else:
106                        begin = False
107                else:       
108                    if gotCcomment and S.find('*/') > -1:
109                        self.comments.append(S[:-1])
110                        begin = False
111                        continue
112                    if S.strip().startswith('/*'):
113                        self.comments.append(S[:-1])
114                        gotCcomment = True
115                        continue   
116                    if S[0] in ["'",'#']:
117                        self.comments.append(S[:-1])
118                        continue       #ignore comments, if any
119                    else:
120                        begin = False
121            # valid line to read
122            #vals = S.split()
123            vals = S.replace(',',' ').replace(';',' ').split()
124            if len(vals) < 2:
125                print ('Line '+str(i+1)+' cannot be read:\n\t'+S)
126                continue
127            try:
128                x.append(float(vals[0]))
129                f = float(vals[1])
130                if f <= 0.0:
131                    y.append(0.0)
132                    w.append(0.0)
133                elif len(vals) == 3:
134                    y.append(float(vals[1]))
135                    w.append(1.0/float(vals[2])**2)
136                else:
137                    y.append(float(vals[1]))
138                    w.append(1.0/float(vals[1]))
139            except ValueError:
140                msg = 'Error parsing number in line '+str(i+1)
141                if GSASIIpath.GetConfigValue('debug'):
142                    print (msg)
143                    print (S.strip())
144                break
145            except:
146                msg = 'Error in line '+str(i+1)
147                if GSASIIpath.GetConfigValue('debug'):
148                    print (msg)
149                    print (S.strip())
150                break
151        N = len(x)
152        self.powderdata = [
153            np.array(x), # x-axis values
154            np.array(y), # powder pattern intensities
155            np.array(w), # 1/sig(intensity)^2 values (weights)
156            np.zeros(N), # calc. intensities (zero)
157            np.zeros(N), # calc. background (zero)
158            np.zeros(N), # obs-calc profiles
159            ]
160        self.powderentry[0] = filename
161        #self.powderentry[1] = pos # bank offset (N/A here)
162        #self.powderentry[2] = 1 # xye file only has one bank
163        self.idstring = ospath.basename(filename)
164        # scan comments for temperature
165        Temperature = 300
166        for S in self.comments:
167            if 'Temp' in S.split('=')[0]:
168                try:
169                    Temperature = float(S.split('=')[1])
170                except:
171                    pass
172        self.Sample['Temperature'] = Temperature
173        fp.close()
174        return True
Note: See TracBrowser for help on using the repository browser.