source: sasview/DataLoader/readers/ascii_reader.py @ 1d64748

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 1d64748 was 892f246, checked in by Jae Cho <jhjcho@…>, 15 years ago

enabled to read data only with more than 3 continuous lines unless that is the only data.

  • Property mode set to 100644
File size: 12.8 KB
Line 
1"""
2This software was developed by the University of Tennessee as part of the
3Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
4project funded by the US National Science Foundation.
5
6See the license text in license.txt
7
8copyright 2008, University of Tennessee
9"""
10
11import numpy
12import os
13from DataLoader.data_info import Data1D
14
15# Check whether we have a converter available
16has_converter = True
17try:
18    from data_util.nxsunit import Converter
19except:
20    has_converter = False
21
22class Reader:
23    """
24        Class to load ascii files (2 or 3 columns)
25    """
26    ## File type
27    type_name = "ASCII"
28   
29    ## Wildcards
30    type = ["ASCII files (*.txt)|*.txt",
31            "ASCII files (*.dat)|*.dat",
32            "ASCII files (*.abs)|*.abs"]
33    ## List of allowed extensions
34    ext=['.txt', '.TXT', '.dat', '.DAT', '.abs', '.ABS'] 
35   
36    def read(self, path):
37        """
38            Load data file
39           
40            @param path: file path
41            @return: Data1D object, or None
42            @raise RuntimeError: when the file can't be opened
43            @raise ValueError: when the length of the data vectors are inconsistent
44        """
45        if os.path.isfile(path):
46            basename  = os.path.basename(path)
47            root, extension = os.path.splitext(basename)
48            if extension.lower() in self.ext:
49                try:
50                    input_f =  open(path,'r')
51                except :
52                    raise  RuntimeError, "ascii_reader: cannot open %s" % path
53                buff = input_f.read()
54                lines = buff.split('\n')
55               
56                #Jae could not find python universal line spliter: keep the below for now
57                # some ascii data has \r line separator, try it when it has only one line
58                if len(lines) < 2 : 
59                    lines = buff.split('\r')
60                 
61                x  = numpy.zeros(0)
62                y  = numpy.zeros(0)
63                dy = numpy.zeros(0)
64                dx = numpy.zeros(0)
65               
66               #temp. space to sort data
67                tx  = numpy.zeros(0)
68                ty  = numpy.zeros(0)
69                tdy = numpy.zeros(0)
70                tdx = numpy.zeros(0)
71               
72                output = Data1D(x, y, dy=dy, dx=dx)
73                self.filename = output.filename = basename
74           
75                data_conv_q = None
76                data_conv_i = None
77               
78                if has_converter == True and output.x_unit != '1/A':
79                    data_conv_q = Converter('1/A')
80                    # Test it
81                    data_conv_q(1.0, output.x_unit)
82                   
83                if has_converter == True and output.y_unit != '1/cm':
84                    data_conv_i = Converter('1/cm')
85                    # Test it
86                    data_conv_i(1.0, output.y_unit)
87           
88               
89                # The first good line of data will define whether
90                # we have 2-column or 3-column ascii
91                has_error_dx = None
92                has_error_dy = None
93               
94                #Initialize counters for data lines and header lines.
95                is_data = False #Has more than 3 lines
96                mum_data_lines = 3 # More than "3" lines of data is considered as actual data unless there is only less lines of data
97
98                i=-1  # To count # of current data candidate lines
99                i1=-1 # To count total # of previous data candidate lines
100                j=-1  # To count # of header lines
101                j1=-1 # Helps to count # of header lines
102               
103                for line in lines:
104                    toks = line.split()
105                   
106                    try:
107                       
108                        _x = float(toks[0])
109                        _y = float(toks[1])
110                       
111                        #Reset the header line counters
112                        if j == j1:
113                            j = 0
114                            j1 = 0
115                           
116                        if i > 1:
117                            is_data = True
118                           
119                        if data_conv_q is not None:
120                            _x = data_conv_q(_x, units=output.x_unit)
121                           
122                        if data_conv_i is not None:
123                            _y = data_conv_i(_y, units=output.y_unit)                       
124                       
125                        # If we have an extra token, check
126                        # whether it can be interpreted as a
127                        # third column.
128                        _dy = None
129                        if len(toks)>2:
130                            try:
131                                _dy = float(toks[2])
132                               
133                                if data_conv_i is not None:
134                                    _dy = data_conv_i(_dy, units=output.y_unit)
135                               
136                            except:
137                                # The third column is not a float, skip it.
138                                pass
139                           
140                        # If we haven't set the 3rd column
141                        # flag, set it now.
142                        if has_error_dy == None:
143                            has_error_dy = False if _dy == None else True
144                           
145                        #Check for dx
146                        _dx = None
147                        if len(toks)>3:
148                            try:
149                                _dx = float(toks[3])
150                               
151                                if data_conv_i is not None:
152                                    _dx = data_conv_i(_dx, units=output.x_unit)
153                               
154                            except:
155                                # The 4th column is not a float, skip it.
156                                pass
157                           
158                        # If we haven't set the 3rd column
159                        # flag, set it now.
160                        if has_error_dx == None:
161                            has_error_dx = False if _dx == None else True
162                       
163                        #Delete the previously stored lines of data candidates if is not data.
164                        if i < 0 and -1< i1 < mum_data_lines and is_data == False:
165                            try:
166                                x= numpy.zeros(0)
167                                y= numpy.zeros(0)
168                               
169                            except:
170                                pass
171                           
172                        x  = numpy.append(x,   _x) 
173                        y  = numpy.append(y,   _y)
174                       
175                        if has_error_dy == True:
176                            #Delete the previously stored lines of data candidates if is not data.
177                            if i < 0 and -1< i1 < mum_data_lines and is_data== False:
178                                try:
179                                    dy = numpy.zeros(0) 
180                                except:
181                                    pass                                                               
182                            dy = numpy.append(dy, _dy)
183                           
184                        if has_error_dx == True:
185                            #Delete the previously stored lines of data candidates if is not data.
186                            if i < 0 and -1< i1 < mum_data_lines and is_data== False:
187                                try:
188                                    dx = numpy.zeros(0)                           
189                                except:
190                                    pass                                                               
191                            dx = numpy.append(dx, _dx)
192                           
193                        #Same for temp.
194                        #Delete the previously stored lines of data candidates if is not data.
195                        if i < 0 and -1< i1 < mum_data_lines and is_data== False:
196                            try:
197                                tx = numpy.zeros(0)
198                                ty = numpy.zeros(0)
199                            except:
200                                pass                                                               
201
202                        tx  = numpy.append(tx,   _x) 
203                        ty  = numpy.append(ty,   _y)
204                       
205                        if has_error_dy == True:
206                            #Delete the previously stored lines of data candidates if is not data.
207                            if i < 0 and -1<i1 < mum_data_lines and is_data== False:
208                                try:
209                                    tdy = numpy.zeros(0)
210                                except:
211                                    pass                                                                                                               
212                            tdy = numpy.append(tdy, _dy)
213                        if has_error_dx == True:
214                            #Delete the previously stored lines of data candidates if is not data.
215                            if i < 0 and -1< i1 < mum_data_lines and is_data== False:
216                                try:
217                                    tdx = numpy.zeros(0)
218                                except:
219                                    pass                                                                                                             
220                            tdx = numpy.append(tdx, _dx)
221                       
222                        #Reset # of header lines and counts # of data candidate lines   
223                        if j == 0 and j1 ==0:
224                            i1 = i + 1                           
225                        i+=1
226                       
227                    except:
228
229                        # It is data and meet non - number, then stop reading
230                        if is_data == True:
231                            break   
232                        #Counting # of header lines                   
233                        j+=1
234                        if j == j1+1:
235                            j1 = j                           
236                        else:                           
237                            j = -1
238                        #Reset # of lines of data candidates
239                        i = -1
240                       
241                        # Couldn't parse this line, skip it
242                        pass
243                   
244   
245                     
246                # Sanity check
247                if has_error_dy == True and not len(y) == len(dy):
248                    raise RuntimeError, "ascii_reader: y and dy have different length"
249                if has_error_dx == True and not len(x) == len(dx):
250                    raise RuntimeError, "ascii_reader: y and dy have different length"
251
252                # If the data length is zero, consider this as
253                # though we were not able to read the file.
254                if len(x)==0:
255                    raise RuntimeError, "ascii_reader: could not load file"
256               
257                #Let's re-order the data to make cal. curve look better some cases
258                ind = numpy.lexsort((ty,tx))
259                for i in ind:
260                    x[i] = tx[ind[i]]
261                    y[i] = ty[ind[i]]
262                    if has_error_dy == True:
263                        dy[i] = tdy[ind[i]]
264                    if has_error_dx == True:
265                        dx[i] = tdx[ind[i]]
266               
267                #Data   
268                output.x = x
269                output.y = y
270                output.dy = dy if has_error_dy == True else None
271                output.dx = dx if has_error_dx == True else None
272               
273                if data_conv_q is not None:
274                    output.xaxis("\\rm{Q}", output.x_unit)
275                else:
276                    output.xaxis("\\rm{Q}", 'A^{-1}')
277                if data_conv_i is not None:
278                    output.yaxis("\\rm{Intensity}", output.y_unit)
279                else:
280                    output.yaxis("\\rm{Intensity}","cm^{-1}")
281
282                return output
283           
284        else:
285            raise RuntimeError, "%s is not a file" % path
286        return None
287   
288if __name__ == "__main__": 
289    reader = Reader()
290    #print reader.read("../test/test_3_columns.txt")
291    print reader.read("../test/empty.txt")
292   
293   
294                       
Note: See TracBrowser for help on using the repository browser.