source: sasview/src/sas/sascalc/dataloader/file_reader_base_class.py @ 8475d16

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

Coerce all nan values to 0 when loading data files. refs #1037

  • Property mode set to 100644
File size: 14.1 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
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.ind = None
105        self.output = []
106
107    def nextline(self):
108        """
109        Returns the next line in the file as a string.
110        """
111        #return self.f_open.readline()
112        return decode(self.f_open.readline())
113
114    def nextlines(self):
115        """
116        Returns the next line in the file as a string.
117        """
118        for line in self.f_open:
119            #yield line
120            yield decode(line)
121
122    def readall(self):
123        """
124        Returns the entire file as a string.
125        """
126        #return self.f_open.read()
127        return decode(self.f_open.read())
128
129    def handle_error_message(self, msg):
130        """
131        Generic error handler to add an error to the current datainfo to
132        propagate the error up the error chain.
133        :param msg: Error message
134        """
135        if len(self.output) > 0:
136            self.output[-1].errors.append(msg)
137        elif isinstance(self.current_datainfo, DataInfo):
138            self.current_datainfo.errors.append(msg)
139        else:
140            logger.warning(msg)
141
142    def send_to_output(self):
143        """
144        Helper that automatically combines the info and set and then appends it
145        to output
146        """
147        data_obj = combine_data_info_with_plottable(self.current_dataset,
148                                                    self.current_datainfo)
149        self.output.append(data_obj)
150
151    def sort_one_d_data(self):
152        """
153        Sort 1D data along the X axis for consistency
154        """
155        for data in self.output:
156            if isinstance(data, Data1D):
157                # Normalize the units for
158                data.x_unit = self.format_unit(data.x_unit)
159                data.y_unit = self.format_unit(data.y_unit)
160                # Sort data by increasing x and remove 1st point
161                self.ind = np.lexsort((data.y, data.x))
162                data.x = self.sort_1d_array(data.x)
163                data.y = self.sort_1d_array(data.y)
164                if data.dx is not None:
165                    if len(data.dx) == 0:
166                        data.dx = None
167                        continue
168                    data.dx = self.sort_1d_array(data.dx)
169                if data.dxl is not None:
170                    data.dxl = self.sort_1d_array(data.dxl)
171                if data.dxw is not None:
172                    data.dxw = self.sort_1d_array(data.dxw)
173                if data.dy is not None:
174                    if len(data.dy) == 0:
175                        data.dy = None
176                        continue
177                    data.dy = self.sort_1d_array(data.dy)
178                if data.lam is not None:
179                    data.lam = self.sort_1d_array(data.lam)
180                if data.dlam is not None:
181                    data.dlam = self.sort_1d_array(data.dlam)
182                if len(data.x) > 0:
183                    data.xmin = np.min(data.x)
184                    data.xmax = np.max(data.x)
185                    data.ymin = np.min(data.y)
186                    data.ymax = np.max(data.y)
187
188    def sort_1d_array(self, array=[]):
189        if array.any():
190            for i in self.ind:
191                if math.isnan(array[i]):
192                    array[i] = 0
193            array = np.asarray([array[i] for i in self.ind]).astype(np.float64)
194        return array
195
196    def sort_two_d_data(self):
197        for dataset in self.output:
198            if isinstance(dataset, Data2D):
199                # Normalize the units for
200                dataset.x_unit = self.format_unit(dataset.Q_unit)
201                dataset.y_unit = self.format_unit(dataset.I_unit)
202                dataset.data = dataset.data.astype(np.float64)
203                dataset.qx_data = dataset.qx_data.astype(np.float64)
204                dataset.xmin = np.min(dataset.qx_data)
205                dataset.xmax = np.max(dataset.qx_data)
206                dataset.qy_data = dataset.qy_data.astype(np.float64)
207                dataset.ymin = np.min(dataset.qy_data)
208                dataset.ymax = np.max(dataset.qy_data)
209                dataset.q_data = np.sqrt(dataset.qx_data * dataset.qx_data
210                                         + dataset.qy_data * dataset.qy_data)
211                if dataset.err_data is not None:
212                    dataset.err_data = dataset.err_data.astype(np.float64)
213                if dataset.dqx_data is not None:
214                    dataset.dqx_data = dataset.dqx_data.astype(np.float64)
215                if dataset.dqy_data is not None:
216                    dataset.dqy_data = dataset.dqy_data.astype(np.float64)
217                if dataset.mask is not None:
218                    dataset.mask = dataset.mask.astype(dtype=bool)
219
220                if len(dataset.data.shape) == 2:
221                    n_rows, n_cols = dataset.data.shape
222                    dataset.y_bins = dataset.qy_data[0::int(n_cols)]
223                    dataset.x_bins = dataset.qx_data[:int(n_cols)]
224                dataset.data = dataset.data.flatten()
225                if len(dataset.data) > 0:
226                    dataset.xmin = np.min(dataset.qx_data)
227                    dataset.xmax = np.max(dataset.qx_data)
228                    dataset.ymin = np.min(dataset.qy_data)
229                    dataset.ymax = np.max(dataset.qx_data)
230
231    def format_unit(self, unit=None):
232        """
233        Format units a common way
234        :param unit:
235        :return:
236        """
237        if unit:
238            split = unit.split("/")
239            if len(split) == 1:
240                return unit
241            elif split[0] == '1':
242                return "{0}^".format(split[1]) + "{-1}"
243            else:
244                return "{0}*{1}^".format(split[0], split[1]) + "{-1}"
245
246    def set_all_to_none(self):
247        """
248        Set all mutable values to None for error handling purposes
249        """
250        self.current_dataset = None
251        self.current_datainfo = None
252        self.output = []
253
254    def data_cleanup(self):
255        """
256        Clean up the data sets and refresh everything
257        :return: None
258        """
259        self.remove_empty_q_values()
260        self.send_to_output()  # Combine datasets with DataInfo
261        self.current_datainfo = DataInfo()  # Reset DataInfo
262
263    def remove_empty_q_values(self):
264        """
265        Remove any point where Q == 0
266        """
267        if isinstance(self.current_dataset, plottable_1D):
268            # Booleans for resolutions
269            has_error_dx = self.current_dataset.dx is not None
270            has_error_dxl = self.current_dataset.dxl is not None
271            has_error_dxw = self.current_dataset.dxw is not None
272            has_error_dy = self.current_dataset.dy is not None
273            # Create arrays of zeros for non-existent resolutions
274            if has_error_dxw and not has_error_dxl:
275                array_size = self.current_dataset.dxw.size - 1
276                self.current_dataset.dxl = np.append(self.current_dataset.dxl,
277                                                    np.zeros([array_size]))
278                has_error_dxl = True
279            elif has_error_dxl and not has_error_dxw:
280                array_size = self.current_dataset.dxl.size - 1
281                self.current_dataset.dxw = np.append(self.current_dataset.dxw,
282                                                    np.zeros([array_size]))
283                has_error_dxw = True
284            elif not has_error_dxl and not has_error_dxw and not has_error_dx:
285                array_size = self.current_dataset.x.size - 1
286                self.current_dataset.dx = np.append(self.current_dataset.dx,
287                                                    np.zeros([array_size]))
288                has_error_dx = True
289            if not has_error_dy:
290                array_size = self.current_dataset.y.size - 1
291                self.current_dataset.dy = np.append(self.current_dataset.dy,
292                                                    np.zeros([array_size]))
293                has_error_dy = True
294
295            # Remove points where q = 0
296            x = self.current_dataset.x
297            self.current_dataset.x = self.current_dataset.x[x != 0]
298            self.current_dataset.y = self.current_dataset.y[x != 0]
299            if has_error_dy:
300                self.current_dataset.dy = self.current_dataset.dy[x != 0]
301            if has_error_dx:
302                self.current_dataset.dx = self.current_dataset.dx[x != 0]
303            if has_error_dxl:
304                self.current_dataset.dxl = self.current_dataset.dxl[x != 0]
305            if has_error_dxw:
306                self.current_dataset.dxw = self.current_dataset.dxw[x != 0]
307        elif isinstance(self.current_dataset, plottable_2D):
308            has_error_dqx = self.current_dataset.dqx_data is not None
309            has_error_dqy = self.current_dataset.dqy_data is not None
310            has_error_dy = self.current_dataset.err_data is not None
311            has_mask = self.current_dataset.mask is not None
312            x = self.current_dataset.qx_data
313            self.current_dataset.data = self.current_dataset.data[x != 0]
314            self.current_dataset.qx_data = self.current_dataset.qx_data[x != 0]
315            self.current_dataset.qy_data = self.current_dataset.qy_data[x != 0]
316            self.current_dataset.q_data = np.sqrt(
317                np.square(self.current_dataset.qx_data) + np.square(
318                    self.current_dataset.qy_data))
319            if has_error_dy:
320                self.current_dataset.err_data = self.current_dataset.err_data[x != 0]
321            if has_error_dqx:
322                self.current_dataset.dqx_data = self.current_dataset.dqx_data[x != 0]
323            if has_error_dqy:
324                self.current_dataset.dqy_data = self.current_dataset.dqy_data[x != 0]
325            if has_mask:
326                self.current_dataset.mask = self.current_dataset.mask[x != 0]
327
328    def reset_data_list(self, no_lines=0):
329        """
330        Reset the plottable_1D object
331        """
332        # Initialize data sets with arrays the maximum possible size
333        x = np.zeros(no_lines)
334        y = np.zeros(no_lines)
335        dx = np.zeros(no_lines)
336        dy = np.zeros(no_lines)
337        self.current_dataset = plottable_1D(x, y, dx, dy)
338
339    @staticmethod
340    def splitline(line):
341        """
342        Splits a line into pieces based on common delimiters
343        :param line: A single line of text
344        :return: list of values
345        """
346        # Initial try for CSV (split on ,)
347        toks = line.split(',')
348        # Now try SCSV (split on ;)
349        if len(toks) < 2:
350            toks = line.split(';')
351        # Now go for whitespace
352        if len(toks) < 2:
353            toks = line.split()
354        return toks
355
356    @abstractmethod
357    def get_file_contents(self):
358        """
359        Reader specific class to access the contents of the file
360        All reader classes that inherit from FileReader must implement
361        """
362        pass
Note: See TracBrowser for help on using the repository browser.