source: trunk/imports/G2pwd_FP.py @ 3757

Last change on this file since 3757 was 3757, checked in by toby, 4 years ago

fix reading of FullProf? & WinPLOTR-2006 files

File size: 6.6 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 fp_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 > 100: 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                if i > 2:
68                    fp.close()
69                    return False
70        fp.close()
71        return True # no errors encountered
72
73    def Reader(self,filename, ParentFrame=None, **unused):
74        'Read a FullProf file'
75        x = []
76        y = []
77        w = []
78        gotCcomment = False
79        begin = True
80        steps = False
81        Stop = False
82        N = 0
83        fp = open(filename,'r')
84        for i,S in enumerate(fp):
85            self.errors = 'Error reading line: '+str(i+1)
86            # or a block of comments delimited by /* and */
87            # or (GSAS style) each line can begin with '#' or '!'
88            if begin:
89                if gotCcomment and S.find('*/') > -1:
90                    self.comments.append(S[:-1])
91                    begin = False
92                    continue
93                if S.strip().startswith('/*'):
94                    self.comments.append(S[:-1])
95                    gotCcomment = True
96                    continue   
97                if S.lstrip()[0] in ["'",'#','!',]:
98                    self.comments.append(S[:-1])
99                    continue       #ignore comments, if any
100                else:
101                    begin = False
102            # valid line to read
103            if not steps:
104                vals = S.replace(',',' ').split(None,4)
105                if 'lambda' in S:
106                    self.instdict['wave'] = float(vals[1])
107                    continue
108                elif len(vals) >= 3:
109                    try:
110                        steps = True
111                        start = float(vals[0])
112                        step = float(vals[1])
113                        stop = float(vals[2])
114                        if len(vals) > 3:
115                            self.comments.append(vals[3][:-1])
116                    except:
117                        print('Skipping line ',S)
118                    continue
119                elif i<3:
120                    print('Skipping header line ',S)
121                    continue
122            vals = S.split()    #data strings
123            try:
124                for j in range(len(vals)):
125                    x.append(start+N*step)
126                    f = float(vals[j])
127                    if f <= 0.0:
128                        y.append(0.0)
129                        w.append(0.0)
130                    else:
131                        y.append(float(vals[j]))
132                        w.append(1.0/float(vals[j]))
133                    if x[-1] >= stop:
134                        Stop = True
135                        break
136                    N += 1
137                if Stop:
138                    break
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        fp.close()
152        N = len(x)
153        if N <= 1: return False
154        self.powderdata = [
155            np.array(x), # x-axis values
156            np.array(y), # powder pattern intensities
157            np.array(w), # 1/sig(intensity)^2 values (weights)
158            np.zeros(N), # calc. intensities (zero)
159            np.zeros(N), # calc. background (zero)
160            np.zeros(N), # obs-calc profiles
161            ]
162        self.powderentry[0] = filename
163        #self.powderentry[1] = pos # bank offset (N/A here)
164        #self.powderentry[2] = 1 # xye file only has one bank
165        self.idstring = ospath.basename(filename)
166        # scan comments for temperature
167        Temperature = 300
168        for S in self.comments:
169            if 'Temp' in S.split('=')[0]:
170                try:
171                    Temperature = float(S.split('=')[1])
172                except:
173                    pass
174        self.Sample['Temperature'] = Temperature
175
176        return True
177
Note: See TracBrowser for help on using the repository browser.