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
RevLine 
[beba407]1"""
[b09095a]2This is the base file reader class most file readers should inherit from.
[beba407]3All generic functionality required for a file loader/reader is built into this
4class
5"""
6
7import os
[7b50f14]8import sys
[a78a02f]9import re
[beba407]10import logging
11from abc import abstractmethod
[574adc7]12
13import numpy as np
14from .loader_exceptions import NoKnownLoaderException, FileContentsException,\
[da8bb53]15    DataReaderException, DefaultReaderException
[574adc7]16from .data_info import Data1D, Data2D, DataInfo, plottable_1D, plottable_2D,\
[beba407]17    combine_data_info_with_plottable
18
19logger = logging.getLogger(__name__)
20
[7b50f14]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
[beba407]27
28class FileReader(object):
29    # List of Data1D and Data2D objects to be sent back to data_loader
30    output = []
[b09095a]31    # Current plottable_(1D/2D) object being loaded in
[beba407]32    current_dataset = None
[b09095a]33    # Current DataInfo object being loaded in
[beba407]34    current_datainfo = None
[b09095a]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)"]
[beba407]39    # List of allowed extensions
40    ext = ['.txt']
41    # Bypass extension check and try to load anyway
42    allow_all = False
[b09095a]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
[beba407]49
50    def read(self, filepath):
51        """
[bc570f4]52        Basic file reader
53
[beba407]54        :param filepath: The full or relative path to a file to be loaded
55        """
[814ee32]56        self.filepath = filepath
[beba407]57        if os.path.isfile(filepath):
58            basename, extension = os.path.splitext(os.path.basename(filepath))
[da8bb53]59            self.extension = extension.lower()
[beba407]60            # If the file type is not allowed, return nothing
[da8bb53]61            if self.extension in self.ext or self.allow_all:
[beba407]62                # Try to load the file, but raise an error if unable to.
63                try:
[b09095a]64                    self.f_open = open(filepath, 'rb')
65                    self.get_file_contents()
[0b79323]66
[bc570f4]67                except DataReaderException as e:
[da8bb53]68                    self.handle_error_message(e.message)
[beba407]69                except OSError as e:
[b09095a]70                    # If the file cannot be opened
[beba407]71                    msg = "Unable to open file: {}\n".format(filepath)
72                    msg += e.message
73                    self.handle_error_message(msg)
[b09095a]74                finally:
[da8bb53]75                    # Close the file handle if it is open
[b09095a]76                    if not self.f_open.closed:
77                        self.f_open.close()
[248ff73]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()
[beba407]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)
[a78433dd]86
[b09095a]87        # Return a list of parsed entries that data_loader can manage
[1576693]88        final_data = self.output
89        self.reset_state()
90        return final_data
[beba407]91
[61f329f0]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
[26183bf]101    def nextline(self):
102        """
103        Returns the next line in the file as a string.
104        """
105        #return self.f_open.readline()
[7b50f14]106        return decode(self.f_open.readline())
[26183bf]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
[7b50f14]114            yield decode(line)
[26183bf]115
116    def readall(self):
117        """
118        Returns the entire file as a string.
119        """
120        #return self.f_open.read()
[7b50f14]121        return decode(self.f_open.read())
[26183bf]122
[beba407]123    def handle_error_message(self, msg):
124        """
125        Generic error handler to add an error to the current datainfo to
[20fa5fe]126        propagate the error up the error chain.
[beba407]127        :param msg: Error message
128        """
[dcb91cf]129        if len(self.output) > 0:
130            self.output[-1].errors.append(msg)
131        elif isinstance(self.current_datainfo, DataInfo):
[beba407]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
[b09095a]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):
[a78a02f]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)
[7477fb9]154                # Sort data by increasing x and remove 1st point
[b09095a]155                ind = np.lexsort((data.y, data.x))
[9d786e5]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)
[b09095a]158                if data.dx is not None:
[4660990]159                    if len(data.dx) == 0:
160                        data.dx = None
161                        continue
[9d786e5]162                    data.dx = np.asarray([data.dx[i] for i in ind]).astype(np.float64)
[b09095a]163                if data.dxl is not None:
[9d786e5]164                    data.dxl = np.asarray([data.dxl[i] for i in ind]).astype(np.float64)
[b09095a]165                if data.dxw is not None:
[9d786e5]166                    data.dxw = np.asarray([data.dxw[i] for i in ind]).astype(np.float64)
[b09095a]167                if data.dy is not None:
[4660990]168                    if len(data.dy) == 0:
169                        data.dy = None
170                        continue
[9d786e5]171                    data.dy = np.asarray([data.dy[i] for i in ind]).astype(np.float64)
[b09095a]172                if data.lam is not None:
[9d786e5]173                    data.lam = np.asarray([data.lam[i] for i in ind]).astype(np.float64)
[b09095a]174                if data.dlam is not None:
[9d786e5]175                    data.dlam = np.asarray([data.dlam[i] for i in ind]).astype(np.float64)
[dcb91cf]176                if len(data.x) > 0:
[248ff73]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)
[b09095a]181
[0b79323]182    def sort_two_d_data(self):
183        for dataset in self.output:
[9d786e5]184            if isinstance(dataset, Data2D):
[a78a02f]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)
[9d786e5]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)]
[2f85af7]210                dataset.data = dataset.data.flatten()
[deaa0c6]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)
[0b79323]216
[a78a02f]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
[da8bb53]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
[7b07fbe]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):
[ad92c5a]250        """
251        Remove any point where Q == 0
252        """
[7b07fbe]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]
[deaa0c6]302            self.current_dataset.q_data = np.sqrt(
303                np.square(self.current_dataset.qx_data) + np.square(
304                    self.current_dataset.qy_data))
[7b07fbe]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]
[ad92c5a]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)
[4660990]321        dx = np.zeros(no_lines)
322        dy = np.zeros(no_lines)
323        self.current_dataset = plottable_1D(x, y, dx, dy)
[ad92c5a]324
[b09095a]325    @staticmethod
326    def splitline(line):
327        """
[20fa5fe]328        Splits a line into pieces based on common delimiters
[b09095a]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
[beba407]342    @abstractmethod
[b09095a]343    def get_file_contents(self):
[beba407]344        """
[ad92c5a]345        Reader specific class to access the contents of the file
[b09095a]346        All reader classes that inherit from FileReader must implement
[beba407]347        """
348        pass
Note: See TracBrowser for help on using the repository browser.