source: sasview/src/sas/sascalc/dataloader/file_reader_base_class.py @ 163c3e0

Last change on this file since 163c3e0 was 163c3e0, checked in by krzywon, 6 years ago

Set self.filepath to None on init and after read.

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