source: trunk/imports/G2pwd_FP.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

File size: 6.2 KB
Line 
1# -*- coding: utf-8 -*-
2########### SVN repository information ###################
3# $Date: 2014-12-27 11:14:59 -0600 (Sat, 27 Dec 2014) $
4# $Author: vondreele $
5# $Revision: 1620 $
6# $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/imports/G2pwd_xye.py $
7# $Id: G2pwd_xye.py 1620 2014-12-27 17:14:59Z vondreele $
8########### SVN repository information ###################
9'''
10*Module G2pwd_FP: FullProf .dat data*
11-------------------------------------
12
13Routine to read in powder data from a FullProf .dat 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: 1620 $")
23class xye_ReaderClass(G2obj.ImportPowderData):
24    'Routines to import powder data from a FullProf 1-10 column .dat file'
25    def __init__(self):
26        super(self.__class__,self).__init__( # fancy way to self-reference
27            extensionlist=('.dat',),
28            strictExtension=False,
29            formatName = 'FullProf .dat',
30            longFormatName = 'FullProf 1-10 column .dat 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 FullProf file'
37        gotCcomment = False
38        begin = True
39        self.GSAS = False
40        fp = open(filename,'r')
41        for i,S in enumerate(fp):
42            if i > 1000: break
43            if begin:
44                if gotCcomment and S.find('*/') > -1:
45                    begin = False
46                    continue
47                if S.strip().startswith('/*'):
48                    gotCcomment = True
49                    continue   
50                if S.lstrip()[0] in ["'",'#','!',]:
51                    continue       #ignore comments, if any
52                else:
53                    begin = False
54                # valid line to read?
55            vals = S.split()
56            try:    #look for start,step,stop card
57                for j,val in enumerate(vals):
58                    num = float(val)
59                    if j == 2:
60                        break
61            except ValueError:
62                self.errors = 'Unexpected information in line: '+str(i+1)
63                if all([ord(c) < 128 and ord(c) != 0 for c in str(S)]): # show only if ASCII
64                    self.errors += '  '+str(S)
65                else: 
66                    self.errors += '  (binary)'
67                fp.close()
68                return False
69        fp.close()
70        return True # no errors encountered
71
72    def Reader(self,filename, ParentFrame=None, **unused):
73        'Read a FullProf file'
74        x = []
75        y = []
76        w = []
77        gotCcomment = False
78        begin = True
79        steps = False
80        Stop = False
81        N = 0
82        fp = open(filename,'r')
83        for i,S in enumerate(fp):
84            self.errors = 'Error reading line: '+str(i+1)
85            # or a block of comments delimited by /* and */
86            # or (GSAS style) each line can begin with '#' or '!'
87            if begin:
88                if gotCcomment and S.find('*/') > -1:
89                    self.comments.append(S[:-1])
90                    begin = False
91                    continue
92                if S.strip().startswith('/*'):
93                    self.comments.append(S[:-1])
94                    gotCcomment = True
95                    continue   
96                if S.lstrip()[0] in ["'",'#','!',]:
97                    self.comments.append(S[:-1])
98                    continue       #ignore comments, if any
99                else:
100                    begin = False
101            # valid line to read
102            if not steps:
103                vals = S.split(None,4)
104                if len(vals) >= 3:
105                    steps = True
106                    start = float(vals[0])
107                    step = float(vals[1])
108                    stop = float(vals[2])
109                    if len(vals) > 3:
110                        self.comments.append(vals[3][:-1])
111                    continue
112            vals = S.split()    #data strings
113            try:
114                for j in range(len(vals)):
115                    x.append(start+N*step)
116                    f = float(vals[j])
117                    if f <= 0.0:
118                        y.append(0.0)
119                        w.append(0.0)
120                    else:
121                        y.append(float(vals[j]))
122                        w.append(1.0/float(vals[j]))
123                    if x[-1] >= stop:
124                        Stop = True
125                        break
126                    N += 1
127                if Stop:
128                    break
129            except ValueError:
130                msg = 'Error parsing number in line '+str(i+1)
131                if GSASIIpath.GetConfigValue('debug'):
132                    print (msg)
133                    print (S.strip())
134                break
135            except:
136                msg = 'Error in line '+str(i+1)
137                if GSASIIpath.GetConfigValue('debug'):
138                    print (msg)
139                    print (S.strip())
140                break
141        fp.close()
142        N = len(x)
143        if N <= 1: return False
144        self.powderdata = [
145            np.array(x), # x-axis values
146            np.array(y), # powder pattern intensities
147            np.array(w), # 1/sig(intensity)^2 values (weights)
148            np.zeros(N), # calc. intensities (zero)
149            np.zeros(N), # calc. background (zero)
150            np.zeros(N), # obs-calc profiles
151            ]
152        self.powderentry[0] = filename
153        #self.powderentry[1] = pos # bank offset (N/A here)
154        #self.powderentry[2] = 1 # xye file only has one bank
155        self.idstring = ospath.basename(filename)
156        # scan comments for temperature
157        Temperature = 300
158        for S in self.comments:
159            if 'Temp' in S.split('=')[0]:
160                try:
161                    Temperature = float(S.split('=')[1])
162                except:
163                    pass
164        self.Sample['Temperature'] = Temperature
165
166        return True
167
Note: See TracBrowser for help on using the repository browser.