source: trunk/imports/G2pwd_xye.py @ 3098

Last change on this file since 3098 was 3098, checked in by toby, 6 years ago

fix powder data import errors with G2scriptable

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