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

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

Make suggested changes for unit test fixes.

  • Property mode set to 100644
File size: 9.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 re
9import logging
10import numpy as np
11from abc import abstractmethod
12from loader_exceptions import NoKnownLoaderException, FileContentsException,\
13    DataReaderException, DefaultReaderException
14from data_info import Data1D, Data2D, DataInfo, plottable_1D, plottable_2D,\
15    combine_data_info_with_plottable
16
17logger = logging.getLogger(__name__)
18
19
20class FileReader(object):
21    # List of Data1D and Data2D objects to be sent back to data_loader
22    output = []
23    # Current plottable_(1D/2D) object being loaded in
24    current_dataset = None
25    # Current DataInfo object being loaded in
26    current_datainfo = None
27    # String to describe the type of data this reader can load
28    type_name = "ASCII"
29    # Wildcards to display
30    type = ["Text files (*.txt|*.TXT)"]
31    # List of allowed extensions
32    ext = ['.txt']
33    # Bypass extension check and try to load anyway
34    allow_all = False
35    # Able to import the unit converter
36    has_converter = True
37    # Open file handle
38    f_open = None
39    # Default value of zero
40    _ZERO = 1e-16
41
42    def read(self, filepath):
43        """
44        Basic file reader
45
46        :param filepath: The full or relative path to a file to be loaded
47        """
48        if os.path.isfile(filepath):
49            basename, extension = os.path.splitext(os.path.basename(filepath))
50            self.extension = extension.lower()
51            # If the file type is not allowed, return nothing
52            if self.extension in self.ext or self.allow_all:
53                # Try to load the file, but raise an error if unable to.
54                try:
55                    self.f_open = open(filepath, 'rb')
56                    self.get_file_contents()
57
58                except DataReaderException as e:
59                    self.handle_error_message(e.message)
60                except OSError as e:
61                    # If the file cannot be opened
62                    msg = "Unable to open file: {}\n".format(filepath)
63                    msg += e.message
64                    self.handle_error_message(msg)
65                finally:
66                    # Close the file handle if it is open
67                    if not self.f_open.closed:
68                        self.f_open.close()
69                    if len(self.output) > 0:
70                        # Sort the data that's been loaded
71                        self.sort_one_d_data()
72                        self.sort_two_d_data()
73        else:
74            msg = "Unable to find file at: {}\n".format(filepath)
75            msg += "Please check your file path and try again."
76            self.handle_error_message(msg)
77
78        # Return a list of parsed entries that data_loader can manage
79        return self.output
80
81    def handle_error_message(self, msg):
82        """
83        Generic error handler to add an error to the current datainfo to
84        propogate the error up the error chain.
85        :param msg: Error message
86        """
87        if len(self.output) > 0:
88            self.output[-1].errors.append(msg)
89        elif isinstance(self.current_datainfo, DataInfo):
90            self.current_datainfo.errors.append(msg)
91        else:
92            logger.warning(msg)
93
94    def send_to_output(self):
95        """
96        Helper that automatically combines the info and set and then appends it
97        to output
98        """
99        data_obj = combine_data_info_with_plottable(self.current_dataset,
100                                                    self.current_datainfo)
101        self.output.append(data_obj)
102
103    def sort_one_d_data(self):
104        """
105        Sort 1D data along the X axis for consistency
106        """
107        for data in self.output:
108            if isinstance(data, Data1D):
109                # Normalize the units for
110                data.x_unit = self.format_unit(data.x_unit)
111                data.y_unit = self.format_unit(data.y_unit)
112                # Sort data by increasing x and remove 1st point
113                ind = np.lexsort((data.y, data.x))
114                data.x = np.asarray([data.x[i] for i in ind]).astype(np.float64)
115                data.y = np.asarray([data.y[i] for i in ind]).astype(np.float64)
116                if data.dx is not None:
117                    data.dx = np.asarray([data.dx[i] for i in ind]).astype(np.float64)
118                if data.dxl is not None:
119                    data.dxl = np.asarray([data.dxl[i] for i in ind]).astype(np.float64)
120                if data.dxw is not None:
121                    data.dxw = np.asarray([data.dxw[i] for i in ind]).astype(np.float64)
122                if data.dy is not None:
123                    data.dy = np.asarray([data.dy[i] for i in ind]).astype(np.float64)
124                if data.lam is not None:
125                    data.lam = np.asarray([data.lam[i] for i in ind]).astype(np.float64)
126                if data.dlam is not None:
127                    data.dlam = np.asarray([data.dlam[i] for i in ind]).astype(np.float64)
128                if len(data.x) > 0:
129                    data.xmin = np.min(data.x)
130                    data.xmax = np.max(data.x)
131                    data.ymin = np.min(data.y)
132                    data.ymax = np.max(data.y)
133
134    def sort_two_d_data(self):
135        for dataset in self.output:
136            if isinstance(dataset, Data2D):
137                # Normalize the units for
138                dataset.x_unit = self.format_unit(dataset.Q_unit)
139                dataset.y_unit = self.format_unit(dataset.I_unit)
140                dataset.data = dataset.data.astype(np.float64)
141                dataset.qx_data = dataset.qx_data.astype(np.float64)
142                dataset.xmin = np.min(dataset.qx_data)
143                dataset.xmax = np.max(dataset.qx_data)
144                dataset.qy_data = dataset.qy_data.astype(np.float64)
145                dataset.ymin = np.min(dataset.qy_data)
146                dataset.ymax = np.max(dataset.qy_data)
147                dataset.q_data = np.sqrt(dataset.qx_data * dataset.qx_data
148                                         + dataset.qy_data * dataset.qy_data)
149                if dataset.err_data is not None:
150                    dataset.err_data = dataset.err_data.astype(np.float64)
151                if dataset.dqx_data is not None:
152                    dataset.dqx_data = dataset.dqx_data.astype(np.float64)
153                if dataset.dqy_data is not None:
154                    dataset.dqy_data = dataset.dqy_data.astype(np.float64)
155                if dataset.mask is not None:
156                    dataset.mask = dataset.mask.astype(dtype=bool)
157
158                if len(dataset.data.shape) == 2:
159                    n_rows, n_cols = dataset.data.shape
160                    dataset.y_bins = dataset.qy_data[0::int(n_cols)]
161                    dataset.x_bins = dataset.qx_data[:int(n_cols)]
162                dataset.data = dataset.data.flatten()
163
164    def format_unit(self, unit=None):
165        """
166        Format units a common way
167        :param unit:
168        :return:
169        """
170        if unit:
171            split = unit.split("/")
172            if len(split) == 1:
173                return unit
174            elif split[0] == '1':
175                return "{0}^".format(split[1]) + "{-1}"
176            else:
177                return "{0}*{1}^".format(split[0], split[1]) + "{-1}"
178
179    def set_all_to_none(self):
180        """
181        Set all mutable values to None for error handling purposes
182        """
183        self.current_dataset = None
184        self.current_datainfo = None
185        self.output = []
186
187    def remove_empty_q_values(self, has_error_dx=False, has_error_dy=False):
188        """
189        Remove any point where Q == 0
190        """
191        x = self.current_dataset.x
192        self.current_dataset.x = self.current_dataset.x[x != 0]
193        self.current_dataset.y = self.current_dataset.y[x != 0]
194        self.current_dataset.dy = self.current_dataset.dy[x != 0] if \
195            has_error_dy else np.zeros(len(self.current_dataset.y))
196        self.current_dataset.dx = self.current_dataset.dx[x != 0] if \
197            has_error_dx else np.zeros(len(self.current_dataset.x))
198
199    def reset_data_list(self, no_lines=0):
200        """
201        Reset the plottable_1D object
202        """
203        # Initialize data sets with arrays the maximum possible size
204        x = np.zeros(no_lines)
205        y = np.zeros(no_lines)
206        dy = np.zeros(no_lines)
207        dx = np.zeros(no_lines)
208        self.current_dataset = plottable_1D(x, y, dx, dy)
209
210    @staticmethod
211    def splitline(line):
212        """
213        Splits a line into pieces based on common delimeters
214        :param line: A single line of text
215        :return: list of values
216        """
217        # Initial try for CSV (split on ,)
218        toks = line.split(',')
219        # Now try SCSV (split on ;)
220        if len(toks) < 2:
221            toks = line.split(';')
222        # Now go for whitespace
223        if len(toks) < 2:
224            toks = line.split()
225        return toks
226
227    @abstractmethod
228    def get_file_contents(self):
229        """
230        Reader specific class to access the contents of the file
231        All reader classes that inherit from FileReader must implement
232        """
233        pass
Note: See TracBrowser for help on using the repository browser.