source: trunk/imports/G2sad_xye.py @ 1299

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

Set conf flags consistently for .py files

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 15.9 KB
Line 
1# -*- coding: utf-8 -*-
2########### SVN repository information ###################
3# $Date: 2014-04-23 22:23:37 +0000 (Wed, 23 Apr 2014) $
4# $Author: toby $
5# $Revision: 1299 $
6# $URL: trunk/imports/G2sad_xye.py $
7# $Id: G2sad_xye.py 1299 2014-04-23 22:23:37Z toby $
8########### SVN repository information ###################
9'''
10*Module G2sad_xye: read small angle data*
11------------------------------------------------
12
13Routines to read in small angle data from an .xye type file, with
14two-theta or Q steps.
15
16'''
17
18import sys
19import os.path as ospath
20import numpy as np
21import GSASIIIO as G2IO
22import GSASIIpath
23GSASIIpath.SetVersionNumber("$Revision: 1299 $")
24npasind = lambda x: 180.*np.arcsin(x)/np.pi
25
26class txt_XRayReaderClass(G2IO.ImportSmallAngleData):
27    'Routines to import X-ray q SAXD data from a .xsad or .xdat file'
28    def __init__(self):
29        super(self.__class__,self).__init__( # fancy way to self-reference
30            extensionlist=('.xsad','.xdat'),
31            strictExtension=False,
32            formatName = 'q (A-1) step X-ray QIE data',
33            longFormatName = 'q (A-1) stepped X-ray text data file in Q,I,E order; E optional'
34            )
35
36    # Validate the contents -- make sure we only have valid lines
37    def ContentsValidator(self, filepointer):
38        'Look through the file for expected types of lines in a valid q-step file'
39        Ndata = 0
40        for i,S in enumerate(filepointer):
41            vals = S.split()
42            if len(vals) >= 2:
43                try:
44                    data = [float(val) for val in vals]
45                    Ndata += 1
46                except ValueError:
47                    pass
48        if not Ndata:     
49            self.errors = 'No 2 or more column numeric data found'
50            return False
51        return True # no errors encountered
52
53    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
54        print 'Read a q-step text file'
55        x = []
56        y = []
57        w = []
58        try:
59            wave = 1.5428   #Cuka default
60            Temperature = 300
61            Ndata = 0
62            for i,S in enumerate(filepointer):
63                if len(S) == 1:     #skip blank line
64                    continue
65                if '=' in S:
66                    self.comments.append(S[:-1])
67                    if 'wave' in S.split('=')[0].lower():
68                        try:
69                            wave = float(S.split('=')[1])
70                        except:
71                            pass
72                    continue
73                vals = S.split()
74                if len(vals) >= 2:
75                    try:
76                        data = [float(val) for val in vals]
77                        x.append(float(data[0]))
78                        f = float(data[1])
79                        if f <= 0.0:
80                            del x[-1]
81                            continue
82                        elif len(vals) > 2:
83                            y.append(float(data[1]))
84                            w.append(1.0/float(data[2])**2)
85                        else:
86                            y.append(float(data[1]))
87                            w.append(1.0/float(data[1]))
88                    except ValueError:
89                        msg = 'Error in line '+str(i+1)
90                        print msg
91                        continue
92            N = len(x)
93            for S in self.comments:
94                if 'Temp' in S.split('=')[0]:
95                    try:
96                        Temperature = float(S.split('=')[1])
97                    except:
98                        pass
99            self.instdict['wave'] = wave
100            self.instdict['type'] = 'LXC'
101            x = np.array(x)
102            self.smallangledata = [
103                x, # x-axis values q
104                np.array(y), # small angle pattern intensities
105                np.array(w), # 1/sig(intensity)^2 values (weights)
106                np.zeros(N), # calc. intensities (zero)
107                np.zeros(N), # obs-calc profiles
108                ]
109            self.smallangleentry[0] = filename
110            self.smallangleentry[2] = 1 # xye file only has one bank
111            self.idstring = ospath.basename(filename)
112            # scan comments for temperature
113            self.Sample['Temperature'] = Temperature
114   
115            return True
116        except Exception as detail:
117            self.errors += '\n  '+str(detail)
118            print self.formatName+' read error:'+str(detail) # for testing
119            import traceback
120            traceback.print_exc(file=sys.stdout)
121            return False
122
123class txt_nmXRayReaderClass(G2IO.ImportSmallAngleData):
124    'Routines to import X-ray q SAXD data from a .xsad or .xdat file, q in nm-1'
125    def __init__(self):
126        super(self.__class__,self).__init__( # fancy way to self-reference
127            extensionlist=('.xsad','.xdat'),
128            strictExtension=False,
129            formatName = 'q (nm-1) step X-ray QIE data',
130            longFormatName = 'q (nm-1) stepped X-ray text data file in Q,I,E order; E optional'
131            )
132
133    # Validate the contents -- make sure we only have valid lines
134    def ContentsValidator(self, filepointer):
135        'Look through the file for expected types of lines in a valid q-step file'
136        Ndata = 0
137        for i,S in enumerate(filepointer):
138            vals = S.split()
139            if len(vals) >= 2:
140                try:
141                    data = [float(val) for val in vals]
142                    Ndata += 1
143                except ValueError:
144                    pass
145        if not Ndata:     
146            self.errors = 'No 2 or more column numeric data found'
147            return False
148        return True # no errors encountered
149
150    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
151        print 'Read a q-step text file'
152        x = []
153        y = []
154        w = []
155        try:
156            wave = 1.5428   #Cuka default
157            Temperature = 300
158            Ndata = 0
159            for i,S in enumerate(filepointer):
160                if len(S) == 1:     #skip blank line
161                    continue
162                if '=' in S:
163                    self.comments.append(S[:-1])
164                    if 'wave' in S.split('=')[0].lower():
165                        try:
166                            wave = float(S.split('=')[1])
167                        except:
168                            pass
169                    continue
170                vals = S.split()
171                if len(vals) >= 2:
172                    try:
173                        data = [float(val) for val in vals]
174                        x.append(float(data[0])/10.)        #convert nm-1 to A-1
175                        f = float(data[1])
176                        if f <= 0.0:
177                            x.pop()
178                            continue
179                        elif len(vals) > 2:
180                            y.append(float(data[1]))
181                            w.append(1.0/float(data[2])**2)
182                        else:
183                            y.append(float(data[1]))
184                            w.append(1.0/float(data[1]))
185                    except ValueError:
186                        msg = 'Error in line '+str(i+1)
187                        print msg
188                        continue
189            N = len(x)
190            for S in self.comments:
191                if 'Temp' in S.split('=')[0]:
192                    try:
193                        Temperature = float(S.split('=')[1])
194                    except:
195                        pass
196            self.instdict['wave'] = wave
197            self.instdict['type'] = 'LXC'
198            x = np.array(x)
199            self.smallangledata = [
200                x, # x-axis values q
201                np.array(y), # small angle pattern intensities
202                np.array(w), # 1/sig(intensity)^2 values (weights)
203                np.zeros(N), # calc. intensities (zero)
204                np.zeros(N), # obs-calc profiles
205                ]
206            self.smallangleentry[0] = filename
207            self.smallangleentry[2] = 1 # xye file only has one bank
208            self.idstring = ospath.basename(filename)
209            # scan comments for temperature
210            self.Sample['Temperature'] = Temperature
211   
212            return True
213        except Exception as detail:
214            self.errors += '\n  '+str(detail)
215            print self.formatName+' read error:'+str(detail) # for testing
216            import traceback
217            traceback.print_exc(file=sys.stdout)
218            return False
219
220class txt_CWNeutronReaderClass(G2IO.ImportSmallAngleData):
221    'Routines to import neutron CW q SAXD data from a .nsad or .ndat file'
222    def __init__(self):
223        super(self.__class__,self).__init__( # fancy way to self-reference
224            extensionlist=('.nsad','.ndat'),
225            strictExtension=False,
226            formatName = 'q (A-1) step neutron CW QIE data',
227            longFormatName = 'q (A-1) stepped neutron CW text data file in Q,I,E order; E optional'
228            )
229
230    # Validate the contents -- make sure we only have valid lines
231    def ContentsValidator(self, filepointer):
232        'Look through the file for expected types of lines in a valid q-step file'
233        Ndata = 0
234        for i,S in enumerate(filepointer):
235            vals = S.split()
236            if len(vals) >= 2:
237                try:
238                    data = [float(val) for val in vals]
239                    Ndata += 1
240                except ValueError:
241                    pass
242        if not Ndata:     
243            self.errors = 'No 2 or more column numeric data found'
244            return False
245        return True # no errors encountered
246
247    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
248        print 'Read a q-step text file'
249        x = []
250        y = []
251        w = []
252        try:
253            wave = 1.5428   #Cuka default
254            Temperature = 300
255            Ndata = 0
256            for i,S in enumerate(filepointer):
257                if len(S) == 1:     #skip blank line
258                    continue
259                if '=' in S:
260                    self.comments.append(S[:-1])
261                    if 'wave' in S.split('=')[0].lower():
262                        try:
263                            wave = float(S.split('=')[1])
264                        except:
265                            pass
266                    continue
267                vals = S.split()
268                if len(vals) >= 2:
269                    try:
270                        data = [float(val) for val in vals]
271                        x.append(float(data[0]))
272                        f = float(data[1])
273                        if f <= 0.0:
274                            y.append(0.0)
275                            w.append(1.0)
276                        elif len(vals) > 2:
277                            y.append(float(data[1]))
278                            w.append(1.0/float(data[2])**2)
279                        else:
280                            y.append(float(data[1]))
281                            w.append(1.0/float(data[1]))
282                    except ValueError:
283                        msg = 'Error in line '+str(i+1)
284                        print msg
285                        continue
286            N = len(x)
287            for S in self.comments:
288                if 'Temp' in S.split('=')[0]:
289                    try:
290                        Temperature = float(S.split('=')[1])
291                    except:
292                        pass
293            self.instdict['wave'] = wave
294            self.instdict['type'] = 'LNC'
295            x = np.array(x)
296            if np.any(x > 2.):         #q must be nm-1
297                x /= 10.
298            self.smallangledata = [
299                x, # x-axis values q
300                np.array(y), # small angle pattern intensities
301                np.array(w), # 1/sig(intensity)^2 values (weights)
302                np.zeros(N), # calc. intensities (zero)
303                np.zeros(N), # obs-calc profiles
304                ]
305            self.smallangleentry[0] = filename
306            self.smallangleentry[2] = 1 # xye file only has one bank
307            self.idstring = ospath.basename(filename)
308            # scan comments for temperature
309            self.Sample['Temperature'] = Temperature
310   
311            return True
312        except Exception as detail:
313            self.errors += '\n  '+str(detail)
314            print self.formatName+' read error:'+str(detail) # for testing
315            import traceback
316            traceback.print_exc(file=sys.stdout)
317            return False
318
319class txt_nmCWNeutronReaderClass(G2IO.ImportSmallAngleData):
320    'Routines to import neutron CW q in nm-1 SAXD data from a .nsad or .ndat file'
321    def __init__(self):
322        super(self.__class__,self).__init__( # fancy way to self-reference
323            extensionlist=('.nsad','.ndat'),
324            strictExtension=False,
325            formatName = 'q (nm-1) step neutron CW QIE data',
326            longFormatName = 'q (nm-1) stepped neutron CW text data file in Q,I,E order; E optional'
327            )
328
329    # Validate the contents -- make sure we only have valid lines
330    def ContentsValidator(self, filepointer):
331        'Look through the file for expected types of lines in a valid q-step file'
332        Ndata = 0
333        for i,S in enumerate(filepointer):
334            vals = S.split()
335            if len(vals) >= 2:
336                try:
337                    data = [float(val) for val in vals]
338                    Ndata += 1
339                except ValueError:
340                    pass
341        if not Ndata:     
342            self.errors = 'No 2 or more column numeric data found'
343            return False
344        return True # no errors encountered
345
346    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
347        print 'Read a q-step text file'
348        x = []
349        y = []
350        w = []
351        try:
352            wave = 1.5428   #Cuka default
353            Temperature = 300
354            Ndata = 0
355            for i,S in enumerate(filepointer):
356                if len(S) == 1:     #skip blank line
357                    continue
358                if '=' in S:
359                    self.comments.append(S[:-1])
360                    if 'wave' in S.split('=')[0].lower():
361                        try:
362                            wave = float(S.split('=')[1])
363                        except:
364                            pass
365                    continue
366                vals = S.split()
367                if len(vals) >= 2:
368                    try:
369                        data = [float(val) for val in vals]
370                        x.append(float(data[0])/10.)    #convert to A-1
371                        f = float(data[1])
372                        if f <= 0.0:
373                            y.append(0.0)
374                            w.append(1.0)
375                        elif len(vals) > 2:
376                            y.append(float(data[1]))
377                            w.append(1.0/float(data[2])**2)
378                        else:
379                            y.append(float(data[1]))
380                            w.append(1.0/float(data[1]))
381                    except ValueError:
382                        msg = 'Error in line '+str(i+1)
383                        print msg
384                        continue
385            N = len(x)
386            for S in self.comments:
387                if 'Temp' in S.split('=')[0]:
388                    try:
389                        Temperature = float(S.split('=')[1])
390                    except:
391                        pass
392            self.instdict['wave'] = wave
393            self.instdict['type'] = 'LNC'
394            x = np.array(x)
395            self.smallangledata = [
396                x, # x-axis values q
397                np.array(y), # small angle pattern intensities
398                np.array(w), # 1/sig(intensity)^2 values (weights)
399                np.zeros(N), # calc. intensities (zero)
400                np.zeros(N), # obs-calc profiles
401                ]
402            self.smallangleentry[0] = filename
403            self.smallangleentry[2] = 1 # xye file only has one bank
404            self.idstring = ospath.basename(filename)
405            # scan comments for temperature
406            self.Sample['Temperature'] = Temperature
407   
408            return True
409        except Exception as detail:
410            self.errors += '\n  '+str(detail)
411            print self.formatName+' read error:'+str(detail) # for testing
412            import traceback
413            traceback.print_exc(file=sys.stdout)
414            return False
Note: See TracBrowser for help on using the repository browser.