source: sasview/src/sas/sascalc/dataloader/file_reader_base_class.py @ 340291a

magnetic_scattrelease-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 340291a was 340291a, checked in by krzywon, 6 years ago

Fix nan removal code to truncate search through and truncate 2D mask data.

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