source: sasview/src/sas/sascalc/dataloader/file_reader_base_class.py @ 814ee32

Last change on this file since 814ee32 was 814ee32, checked in by Paul Kienzle <pkienzle@…>, 6 years ago

remove infinite loop from sesans reader

  • Property mode set to 100644
File size: 13.8 KB
Line 
1"""
2This is the base file reader class most file readers should inherit from.
3All generic functionality required for a file loader/reader is built into this
4class
5"""
6
7import os
8import sys
9import re
10import logging
11from abc import abstractmethod
12
13import numpy as np
14from .loader_exceptions import NoKnownLoaderException, FileContentsException,\
15    DataReaderException, DefaultReaderException
16from .data_info import Data1D, Data2D, DataInfo, plottable_1D, plottable_2D,\
17    combine_data_info_with_plottable
18
19logger = logging.getLogger(__name__)
20
21if sys.version_info[0] < 3:
22    def decode(s):
23        return s
24else:
25    def decode(s):
26        return s.decode() if isinstance(s, bytes) else s
27
28class FileReader(object):
29    # List of Data1D and Data2D objects to be sent back to data_loader
30    output = []
31    # Current plottable_(1D/2D) object being loaded in
32    current_dataset = None
33    # Current DataInfo object being loaded in
34    current_datainfo = None
35    # String to describe the type of data this reader can load
36    type_name = "ASCII"
37    # Wildcards to display
38    type = ["Text files (*.txt|*.TXT)"]
39    # List of allowed extensions
40    ext = ['.txt']
41    # Bypass extension check and try to load anyway
42    allow_all = False
43    # Able to import the unit converter
44    has_converter = True
45    # Open file handle
46    f_open = None
47    # Default value of zero
48    _ZERO = 1e-16
49
50    def read(self, filepath):
51        """
52        Basic file reader
53
54        :param filepath: The full or relative path to a file to be loaded
55        """
56        self.filepath = filepath
57        if os.path.isfile(filepath):
58            basename, extension = os.path.splitext(os.path.basename(filepath))
59            self.extension = extension.lower()
60            # If the file type is not allowed, return nothing
61            if self.extension in self.ext or self.allow_all:
62                # Try to load the file, but raise an error if unable to.
63                try:
64                    self.f_open = open(filepath, 'rb')
65                    self.get_file_contents()
66
67                except DataReaderException as e:
68                    self.handle_error_message(e.message)
69                except OSError as e:
70                    # If the file cannot be opened
71                    msg = "Unable to open file: {}\n".format(filepath)
72                    msg += e.message
73                    self.handle_error_message(msg)
74                finally:
75                    # Close the file handle if it is open
76                    if not self.f_open.closed:
77                        self.f_open.close()
78                    if len(self.output) > 0:
79                        # Sort the data that's been loaded
80                        self.sort_one_d_data()
81                        self.sort_two_d_data()
82        else:
83            msg = "Unable to find file at: {}\n".format(filepath)
84            msg += "Please check your file path and try again."
85            self.handle_error_message(msg)
86
87        # Return a list of parsed entries that data_loader can manage
88        final_data = self.output
89        self.reset_state()
90        return final_data
91
92    def reset_state(self):
93        """
94        Resets the class state to a base case when loading a new data file so previous
95        data files do not appear a second time
96        """
97        self.current_datainfo = None
98        self.current_dataset = None
99        self.output = []
100
101    def nextline(self):
102        """
103        Returns the next line in the file as a string.
104        """
105        #return self.f_open.readline()
106        return decode(self.f_open.readline())
107
108    def nextlines(self):
109        """
110        Returns the next line in the file as a string.
111        """
112        for line in self.f_open:
113            #yield line
114            yield decode(line)
115
116    def readall(self):
117        """
118        Returns the entire file as a string.
119        """
120        #return self.f_open.read()
121        return decode(self.f_open.read())
122
123    def handle_error_message(self, msg):
124        """
125        Generic error handler to add an error to the current datainfo to
126        propagate the error up the error chain.
127        :param msg: Error message
128        """
129        if len(self.output) > 0:
130            self.output[-1].errors.append(msg)
131        elif isinstance(self.current_datainfo, DataInfo):
132            self.current_datainfo.errors.append(msg)
133        else:
134            logger.warning(msg)
135
136    def send_to_output(self):
137        """
138        Helper that automatically combines the info and set and then appends it
139        to output
140        """
141        data_obj = combine_data_info_with_plottable(self.current_dataset,
142                                                    self.current_datainfo)
143        self.output.append(data_obj)
144
145    def sort_one_d_data(self):
146        """
147        Sort 1D data along the X axis for consistency
148        """
149        for data in self.output:
150            if isinstance(data, Data1D):
151                # Normalize the units for
152                data.x_unit = self.format_unit(data.x_unit)
153                data.y_unit = self.format_unit(data.y_unit)
154                # Sort data by increasing x and remove 1st point
155                ind = np.lexsort((data.y, data.x))
156                data.x = np.asarray([data.x[i] for i in ind]).astype(np.float64)
157                data.y = np.asarray([data.y[i] for i in ind]).astype(np.float64)
158                if data.dx is not None:
159                    if len(data.dx) == 0:
160                        data.dx = None
161                        continue
162                    data.dx = np.asarray([data.dx[i] for i in ind]).astype(np.float64)
163                if data.dxl is not None:
164                    data.dxl = np.asarray([data.dxl[i] for i in ind]).astype(np.float64)
165                if data.dxw is not None:
166                    data.dxw = np.asarray([data.dxw[i] for i in ind]).astype(np.float64)
167                if data.dy is not None:
168                    if len(data.dy) == 0:
169                        data.dy = None
170                        continue
171                    data.dy = np.asarray([data.dy[i] for i in ind]).astype(np.float64)
172                if data.lam is not None:
173                    data.lam = np.asarray([data.lam[i] for i in ind]).astype(np.float64)
174                if data.dlam is not None:
175                    data.dlam = np.asarray([data.dlam[i] for i in ind]).astype(np.float64)
176                if len(data.x) > 0:
177                    data.xmin = np.min(data.x)
178                    data.xmax = np.max(data.x)
179                    data.ymin = np.min(data.y)
180                    data.ymax = np.max(data.y)
181
182    def sort_two_d_data(self):
183        for dataset in self.output:
184            if isinstance(dataset, Data2D):
185                # Normalize the units for
186                dataset.x_unit = self.format_unit(dataset.Q_unit)
187                dataset.y_unit = self.format_unit(dataset.I_unit)
188                dataset.data = dataset.data.astype(np.float64)
189                dataset.qx_data = dataset.qx_data.astype(np.float64)
190                dataset.xmin = np.min(dataset.qx_data)
191                dataset.xmax = np.max(dataset.qx_data)
192                dataset.qy_data = dataset.qy_data.astype(np.float64)
193                dataset.ymin = np.min(dataset.qy_data)
194                dataset.ymax = np.max(dataset.qy_data)
195                dataset.q_data = np.sqrt(dataset.qx_data * dataset.qx_data
196                                         + dataset.qy_data * dataset.qy_data)
197                if dataset.err_data is not None:
198                    dataset.err_data = dataset.err_data.astype(np.float64)
199                if dataset.dqx_data is not None:
200                    dataset.dqx_data = dataset.dqx_data.astype(np.float64)
201                if dataset.dqy_data is not None:
202                    dataset.dqy_data = dataset.dqy_data.astype(np.float64)
203                if dataset.mask is not None:
204                    dataset.mask = dataset.mask.astype(dtype=bool)
205
206                if len(dataset.data.shape) == 2:
207                    n_rows, n_cols = dataset.data.shape
208                    dataset.y_bins = dataset.qy_data[0::int(n_cols)]
209                    dataset.x_bins = dataset.qx_data[:int(n_cols)]
210                dataset.data = dataset.data.flatten()
211                if len(dataset.data) > 0:
212                    dataset.xmin = np.min(dataset.qx_data)
213                    dataset.xmax = np.max(dataset.qx_data)
214                    dataset.ymin = np.min(dataset.qy_data)
215                    dataset.ymax = np.max(dataset.qx_data)
216
217    def format_unit(self, unit=None):
218        """
219        Format units a common way
220        :param unit:
221        :return:
222        """
223        if unit:
224            split = unit.split("/")
225            if len(split) == 1:
226                return unit
227            elif split[0] == '1':
228                return "{0}^".format(split[1]) + "{-1}"
229            else:
230                return "{0}*{1}^".format(split[0], split[1]) + "{-1}"
231
232    def set_all_to_none(self):
233        """
234        Set all mutable values to None for error handling purposes
235        """
236        self.current_dataset = None
237        self.current_datainfo = None
238        self.output = []
239
240    def data_cleanup(self):
241        """
242        Clean up the data sets and refresh everything
243        :return: None
244        """
245        self.remove_empty_q_values()
246        self.send_to_output()  # Combine datasets with DataInfo
247        self.current_datainfo = DataInfo()  # Reset DataInfo
248
249    def remove_empty_q_values(self):
250        """
251        Remove any point where Q == 0
252        """
253        if isinstance(self.current_dataset, plottable_1D):
254            # Booleans for resolutions
255            has_error_dx = self.current_dataset.dx is not None
256            has_error_dxl = self.current_dataset.dxl is not None
257            has_error_dxw = self.current_dataset.dxw is not None
258            has_error_dy = self.current_dataset.dy is not None
259            # Create arrays of zeros for non-existent resolutions
260            if has_error_dxw and not has_error_dxl:
261                array_size = self.current_dataset.dxw.size - 1
262                self.current_dataset.dxl = np.append(self.current_dataset.dxl,
263                                                    np.zeros([array_size]))
264                has_error_dxl = True
265            elif has_error_dxl and not has_error_dxw:
266                array_size = self.current_dataset.dxl.size - 1
267                self.current_dataset.dxw = np.append(self.current_dataset.dxw,
268                                                    np.zeros([array_size]))
269                has_error_dxw = True
270            elif not has_error_dxl and not has_error_dxw and not has_error_dx:
271                array_size = self.current_dataset.x.size - 1
272                self.current_dataset.dx = np.append(self.current_dataset.dx,
273                                                    np.zeros([array_size]))
274                has_error_dx = True
275            if not has_error_dy:
276                array_size = self.current_dataset.y.size - 1
277                self.current_dataset.dy = np.append(self.current_dataset.dy,
278                                                    np.zeros([array_size]))
279                has_error_dy = True
280
281            # Remove points where q = 0
282            x = self.current_dataset.x
283            self.current_dataset.x = self.current_dataset.x[x != 0]
284            self.current_dataset.y = self.current_dataset.y[x != 0]
285            if has_error_dy:
286                self.current_dataset.dy = self.current_dataset.dy[x != 0]
287            if has_error_dx:
288                self.current_dataset.dx = self.current_dataset.dx[x != 0]
289            if has_error_dxl:
290                self.current_dataset.dxl = self.current_dataset.dxl[x != 0]
291            if has_error_dxw:
292                self.current_dataset.dxw = self.current_dataset.dxw[x != 0]
293        elif isinstance(self.current_dataset, plottable_2D):
294            has_error_dqx = self.current_dataset.dqx_data is not None
295            has_error_dqy = self.current_dataset.dqy_data is not None
296            has_error_dy = self.current_dataset.err_data is not None
297            has_mask = self.current_dataset.mask is not None
298            x = self.current_dataset.qx_data
299            self.current_dataset.data = self.current_dataset.data[x != 0]
300            self.current_dataset.qx_data = self.current_dataset.qx_data[x != 0]
301            self.current_dataset.qy_data = self.current_dataset.qy_data[x != 0]
302            self.current_dataset.q_data = np.sqrt(
303                np.square(self.current_dataset.qx_data) + np.square(
304                    self.current_dataset.qy_data))
305            if has_error_dy:
306                self.current_dataset.err_data = self.current_dataset.err_data[x != 0]
307            if has_error_dqx:
308                self.current_dataset.dqx_data = self.current_dataset.dqx_data[x != 0]
309            if has_error_dqy:
310                self.current_dataset.dqy_data = self.current_dataset.dqy_data[x != 0]
311            if has_mask:
312                self.current_dataset.mask = self.current_dataset.mask[x != 0]
313
314    def reset_data_list(self, no_lines=0):
315        """
316        Reset the plottable_1D object
317        """
318        # Initialize data sets with arrays the maximum possible size
319        x = np.zeros(no_lines)
320        y = np.zeros(no_lines)
321        dx = np.zeros(no_lines)
322        dy = np.zeros(no_lines)
323        self.current_dataset = plottable_1D(x, y, dx, dy)
324
325    @staticmethod
326    def splitline(line):
327        """
328        Splits a line into pieces based on common delimiters
329        :param line: A single line of text
330        :return: list of values
331        """
332        # Initial try for CSV (split on ,)
333        toks = line.split(',')
334        # Now try SCSV (split on ;)
335        if len(toks) < 2:
336            toks = line.split(';')
337        # Now go for whitespace
338        if len(toks) < 2:
339            toks = line.split()
340        return toks
341
342    @abstractmethod
343    def get_file_contents(self):
344        """
345        Reader specific class to access the contents of the file
346        All reader classes that inherit from FileReader must implement
347        """
348        pass
Note: See TracBrowser for help on using the repository browser.