source: sasview/DataLoader/readers/ascii_reader.py @ 37d9521

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 37d9521 was 4d2a0d1, checked in by Mathieu Doucet <doucetm@…>, 16 years ago

modified output when no errors are found

  • Property mode set to 100644
File size: 4.1 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
15class Reader:
16    """
17        Class to load ascii files (2 or 3 columns)
18    """
19    ## File type
20    type = ["ASCII files (*.txt)|*.txt",
21            "ASCII files (*.dat)|*.dat"]
22    ## List of allowed extensions
23    ext=['.txt', '.TXT', '.dat', '.DAT'] 
24   
25    def read(self, path):
26        """
27            Load data file
28           
29            @param path: file path
30            @return: Data1D object, or None
31            @raise RuntimeError: when the file can't be opened
32            @raise ValueError: when the length of the data vectors are inconsistent
33        """
34        if os.path.isfile(path):
35            basename  = os.path.basename(path)
36            root, extension = os.path.splitext(basename)
37            if extension.lower() in self.ext:
38                try:
39                    input_f =  open(path,'r')
40                except :
41                    raise  RuntimeError, "ascii_reader: cannot open %s" % path
42                buff = input_f.read()
43                lines = buff.split('\n')
44                x  = numpy.zeros(0)
45                y  = numpy.zeros(0)
46                dy = numpy.zeros(0)
47                output = Data1D(x, y, dy=dy)
48                self.filename = output.filename = basename
49               
50                # The first good line of data will define whether
51                # we have 2-column or 3-column ascii
52                has_error = None
53               
54                for line in lines:
55                    toks = line.split()
56                    try:
57                        _x = float(toks[0])
58                        _y = float(toks[1])
59                       
60                        # If we have an extra token, check
61                        # whether it can be interpreted as a
62                        # third column.
63                        _dy = None
64                        if len(toks)>2:
65                            try:
66                                _dy = float(toks[2])
67                            except:
68                                # The third column is not a float, skip it.
69                                pass
70                           
71                        # If we haven't set the 3rd column
72                        # flag, set it now.
73                        if has_error == None:
74                            has_error = False if _dy == None else True
75
76                        x  = numpy.append(x,   _x) 
77                        y  = numpy.append(y,   _y)
78                        if has_error == True:
79                            dy = numpy.append(dy, _dy)
80                       
81                    except:
82                        # Couldn't parse this line, skip it
83                        pass
84                         
85                     
86                # Sanity check
87                if has_error == True and not len(y) == len(dy):
88                    raise ValueError, "ascii_reader: y and dy have different length"
89
90                # If the data length is zero, consider this as
91                # though we were not able to read the file.
92                if len(x)==0:
93                    raise ValueError, "ascii_reader: could not load file"
94               
95                output.x = x
96                output.y = y
97                output.dy = dy if has_error == True else None
98                output.xaxis("\\rm{Q}", 'A^{-1}')
99                output.yaxis("\\rm{I(Q)}","cm^{-1}")
100               
101               
102                return output
103        else:
104            raise RuntimeError, "%s is not a file" % path
105        return None
106   
107if __name__ == "__main__": 
108    reader = Reader()
109    #print reader.read("../test/test_3_columns.txt")
110    print reader.read("../test/empty.txt")
111   
112   
113                       
Note: See TracBrowser for help on using the repository browser.