source: sasview/DataLoader/readers/ascii_reader.py @ e390933

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 e390933 was 99d1af6, checked in by Mathieu Doucet <doucetm@…>, 16 years ago

Update to readers, with unit conversion

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