source: sasview/DataLoader/readers/ascii_reader.py @ 00c3aac

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 00c3aac was de1da34, checked in by Jae Cho <jhjcho@…>, 16 years ago

Added load-ability to get dQ (for smear) if exists, and capability to sort the data by Q as a key

  • Property mode set to 100644
File size: 7.8 KB
RevLine 
[8bd8ea4]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
[daa56d0]15# Check whether we have a converter available
[99d1af6]16has_converter = True
17try:
18    from data_util.nxsunit import Converter
19except:
20    has_converter = False
21
[8bd8ea4]22class Reader:
23    """
24        Class to load ascii files (2 or 3 columns)
25    """
[8780e9a]26    ## File type
27    type = ["ASCII files (*.txt)|*.txt",
28            "ASCII files (*.dat)|*.dat"]
[8bd8ea4]29    ## List of allowed extensions
30    ext=['.txt', '.TXT', '.dat', '.DAT'] 
31   
32    def read(self, path):
33        """
34            Load data file
35           
36            @param path: file path
37            @return: Data1D object, or None
38            @raise RuntimeError: when the file can't be opened
39            @raise ValueError: when the length of the data vectors are inconsistent
40        """
41        if os.path.isfile(path):
42            basename  = os.path.basename(path)
43            root, extension = os.path.splitext(basename)
44            if extension.lower() in self.ext:
45                try:
46                    input_f =  open(path,'r')
47                except :
48                    raise  RuntimeError, "ascii_reader: cannot open %s" % path
49                buff = input_f.read()
50                lines = buff.split('\n')
51                x  = numpy.zeros(0)
52                y  = numpy.zeros(0)
53                dy = numpy.zeros(0)
[de1da34]54                dx = numpy.zeros(0)
55               
56               #temp. space to sort data
57                tx  = numpy.zeros(0)
58                ty  = numpy.zeros(0)
59                tdy = numpy.zeros(0)
60                tdx = numpy.zeros(0)
61               
62                output = Data1D(x, y, dy=dy, dx=dx)
[8bd8ea4]63                self.filename = output.filename = basename
[99d1af6]64           
65                data_conv_q = None
66                data_conv_i = None
67               
[ca10d8e]68                if has_converter == True and output.x_unit != '1/A':
69                    data_conv_q = Converter('1/A')
[99d1af6]70                    # Test it
71                    data_conv_q(1.0, output.x_unit)
72                   
[ca10d8e]73                if has_converter == True and output.y_unit != '1/cm':
74                    data_conv_i = Converter('1/cm')
[99d1af6]75                    # Test it
76                    data_conv_i(1.0, output.y_unit)
77           
[8bd8ea4]78               
79                # The first good line of data will define whether
80                # we have 2-column or 3-column ascii
[de1da34]81                has_error_dx = None
82                has_error_dy = None
[8bd8ea4]83               
84                for line in lines:
85                    toks = line.split()
86                    try:
87                        _x = float(toks[0])
88                        _y = float(toks[1])
89                       
[99d1af6]90                        if data_conv_q is not None:
91                            _x = data_conv_q(_x, units=output.x_unit)
92                           
93                        if data_conv_i is not None:
94                            _y = data_conv_i(_y, units=output.y_unit)                       
95                       
[8bd8ea4]96                        # If we have an extra token, check
97                        # whether it can be interpreted as a
98                        # third column.
99                        _dy = None
100                        if len(toks)>2:
101                            try:
102                                _dy = float(toks[2])
[99d1af6]103                               
104                                if data_conv_i is not None:
105                                    _dy = data_conv_i(_dy, units=output.y_unit)
106                               
[8bd8ea4]107                            except:
108                                # The third column is not a float, skip it.
109                                pass
110                           
111                        # If we haven't set the 3rd column
112                        # flag, set it now.
[de1da34]113                        if has_error_dy == None:
114                            has_error_dy = False if _dy == None else True
115                           
116                        #Check for dx
117                        _dx = None
118                        if len(toks)>3:
119                            try:
120                                _dx = float(toks[3])
121                               
122                                if data_conv_i is not None:
123                                    _dx = data_conv_i(_dx, units=output.x_unit)
124                               
125                            except:
126                                # The 4th column is not a float, skip it.
127                                pass
128                           
129                        # If we haven't set the 3rd column
130                        # flag, set it now.
131                        if has_error_dx == None:
132                            has_error_dx = False if _dx == None else True
[8bd8ea4]133
134                        x  = numpy.append(x,   _x) 
135                        y  = numpy.append(y,   _y)
[de1da34]136                        if has_error_dy == True:
[8bd8ea4]137                            dy = numpy.append(dy, _dy)
[de1da34]138                        if has_error_dx == True:
139                            dx = numpy.append(dx, _dx)
140                           
141                        #Same for temp.
142                        tx  = numpy.append(tx,   _x) 
143                        ty  = numpy.append(ty,   _y)
144                        if has_error_dy == True:
145                            tdy = numpy.append(tdy, _dy)
146                        if has_error_dx == True:
147                            tdx = numpy.append(tdx, _dx)
[8bd8ea4]148                       
149                    except:
150                        # Couldn't parse this line, skip it
151                        pass
152                         
153                     
154                # Sanity check
[de1da34]155                if has_error_dy == True and not len(y) == len(dy):
156                    raise RuntimeError, "ascii_reader: y and dy have different length"
157                if has_error_dx == True and not len(x) == len(dx):
[daa56d0]158                    raise RuntimeError, "ascii_reader: y and dy have different length"
[8bd8ea4]159
160                # If the data length is zero, consider this as
161                # though we were not able to read the file.
162                if len(x)==0:
[daa56d0]163                    raise RuntimeError, "ascii_reader: could not load file"
[de1da34]164               
165                #Let's reoder the data
166                ind = numpy.lexsort((ty,tx))
167                for i in ind:
168                    x[i] = tx[ind[i]]
169                    y[i] = ty[ind[i]]
170                    if has_error_dy == True:
171                        dy[i] = tdy[ind[i]]
172                    if has_error_dx == True:
173                        dx[i] = tdx[ind[i]]
174                   
[8bd8ea4]175                output.x = x
176                output.y = y
[de1da34]177                output.dy = dy if has_error_dy == True else None
178                output.dx = dx if has_error_dx == True else None
179               
[99d1af6]180                if data_conv_q is not None:
181                    output.xaxis("\\rm{Q}", output.x_unit)
182                else:
183                    output.xaxis("\\rm{Q}", 'A^{-1}')
184                if data_conv_i is not None:
185                    output.yaxis("\\{I(Q)}", output.y_unit)
186                else:
187                    output.yaxis("\\rm{I(Q)}","cm^{-1}")
[8bd8ea4]188               
189                return output
190        else:
191            raise RuntimeError, "%s is not a file" % path
192        return None
193   
194if __name__ == "__main__": 
195    reader = Reader()
196    #print reader.read("../test/test_3_columns.txt")
197    print reader.read("../test/empty.txt")
198   
199   
200                       
Note: See TracBrowser for help on using the repository browser.