source: trunk/imports/G2pwd_xye.py @ 1544

Last change on this file since 1544 was 1544, checked in by toby, 9 years ago

allow blank lines in XYE files

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 5.2 KB
Line 
1# -*- coding: utf-8 -*-
2########### SVN repository information ###################
3# $Date: 2014-10-26 20:36:02 +0000 (Sun, 26 Oct 2014) $
4# $Author: toby $
5# $Revision: 1544 $
6# $URL: trunk/imports/G2pwd_xye.py $
7# $Id: G2pwd_xye.py 1544 2014-10-26 20:36:02Z toby $
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
17import sys
18import os.path as ospath
19import numpy as np
20import GSASIIIO as G2IO
21import GSASIIpath
22GSASIIpath.SetVersionNumber("$Revision: 1544 $")
23class xye_ReaderClass(G2IO.ImportPowderData):
24    'Routines to import powder data from a .xye file'
25    def __init__(self):
26        super(self.__class__,self).__init__( # fancy way to self-reference
27            extensionlist=('.xye',),
28            strictExtension=False,
29            formatName = 'Topas xye',
30            longFormatName = 'Topas .xye powder data file'
31            )
32
33    # Validate the contents -- make sure we only have valid lines
34    def ContentsValidator(self, filepointer):
35        'Look through the file for expected types of lines in a valid Topas file'
36        gotCcomment = False
37        begin = True
38        self.GSAS = False
39        for i,S in enumerate(filepointer):
40            if i > 1000: break
41            if begin:
42                if gotCcomment and S.find('*/') > -1:
43                    begin = False
44                    continue
45                if S.strip().startswith('/*'):
46                    gotCcomment = True
47                    continue   
48                if S[0] == '#':
49                    continue       #ignore comments, if any
50                else:
51                    begin = False
52                # valid line to read?
53            vals = S.split()
54            if len(vals) == 2 or len(vals) == 3:
55                continue
56            else:
57                self.errors = 'Unexpected information in line: '+str(i+1)
58                self.errors += '  '+str(S)
59                return False
60        return True # no errors encountered
61
62    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
63        'Read a Topas file'
64        x = []
65        y = []
66        w = []
67        try:
68            gotCcomment = False
69            begin = True
70            for i,S in enumerate(filepointer):
71                self.errors = 'Error reading line: '+str(i+1)
72                # or a block of comments delimited by /* and */
73                # or (GSAS style) each line can begin with '#'
74                if begin:
75                    if gotCcomment and S.find('*/') > -1:
76                        self.comments.append(S[:-1])
77                        begin = False
78                        continue
79                    if S.strip().startswith('/*'):
80                        self.comments.append(S[:-1])
81                        gotCcomment = True
82                        continue   
83                    if S[0] == '#':
84                        self.comments.append(S[:-1])
85                        continue       #ignore comments, if any
86                    else:
87                        begin = False
88                # valid line to read
89                vals = S.split()
90                if len(vals) < 2:
91                    print 'Line '+str(i+1)+' cannot be read:\n\t'+S
92                    continue
93                try:
94                    x.append(float(vals[0]))
95                    f = float(vals[1])
96                    if f <= 0.0:
97                        y.append(0.0)
98                        w.append(0.0)
99                    elif len(vals) == 3:
100                        y.append(float(vals[1]))
101                        w.append(1.0/float(vals[2])**2)
102                    else:
103                        y.append(float(vals[1]))
104                        w.append(1.0/float(vals[1]))
105                except ValueError:
106                    msg = 'Error parsing number in line '+str(i+1)
107                    print msg
108                    print S
109                    break
110                except:
111                    msg = 'Error in line '+str(i+1)
112                    print msg
113                    print S
114                    break
115            N = len(x)
116            self.powderdata = [
117                np.array(x), # x-axis values
118                np.array(y), # powder pattern intensities
119                np.array(w), # 1/sig(intensity)^2 values (weights)
120                np.zeros(N), # calc. intensities (zero)
121                np.zeros(N), # calc. background (zero)
122                np.zeros(N), # obs-calc profiles
123                ]
124            self.powderentry[0] = filename
125            #self.powderentry[1] = pos # bank offset (N/A here)
126            self.powderentry[2] = 1 # xye file only has one bank
127            self.idstring = ospath.basename(filename)
128            # scan comments for temperature
129            Temperature = 300
130            for S in self.comments:
131                if 'Temp' in S.split('=')[0]:
132                    try:
133                        Temperature = float(S.split('=')[1])
134                    except:
135                        pass
136            self.Sample['Temperature'] = Temperature
137
138            return True
139        except Exception as detail:
140            self.errors += '\n  '+str(detail)
141            print self.formatName+' read error:'+str(detail) # for testing
142            import traceback
143            traceback.print_exc(file=sys.stdout)
144            return False
145
Note: See TracBrowser for help on using the repository browser.