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

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

Move state reset to end of file read to be more thread friendly.

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