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

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

Ensure dxl and dxw and the same length as each other and as x.

  • Property mode set to 100644
File size: 9.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 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                    if len(data.dx) == 0:
118                        data.dx = None
119                        continue
120                    data.dx = np.asarray([data.dx[i] for i in ind]).astype(np.float64)
121                if data.dxl is not None:
122                    data.dxl = np.asarray([data.dxl[i] for i in ind]).astype(np.float64)
123                if data.dxw is not None:
124                    data.dxw = np.asarray([data.dxw[i] for i in ind]).astype(np.float64)
125                if data.dy is not None:
126                    if len(data.dy) == 0:
127                        data.dy = None
128                        continue
129                    data.dy = np.asarray([data.dy[i] for i in ind]).astype(np.float64)
130                if data.lam is not None:
131                    data.lam = np.asarray([data.lam[i] for i in ind]).astype(np.float64)
132                if data.dlam is not None:
133                    data.dlam = np.asarray([data.dlam[i] for i in ind]).astype(np.float64)
134                if len(data.x) > 0:
135                    data.xmin = np.min(data.x)
136                    data.xmax = np.max(data.x)
137                    data.ymin = np.min(data.y)
138                    data.ymax = np.max(data.y)
139
140    def sort_two_d_data(self):
141        for dataset in self.output:
142            if isinstance(dataset, Data2D):
143                # Normalize the units for
144                dataset.x_unit = self.format_unit(dataset.Q_unit)
145                dataset.y_unit = self.format_unit(dataset.I_unit)
146                dataset.data = dataset.data.astype(np.float64)
147                dataset.qx_data = dataset.qx_data.astype(np.float64)
148                dataset.xmin = np.min(dataset.qx_data)
149                dataset.xmax = np.max(dataset.qx_data)
150                dataset.qy_data = dataset.qy_data.astype(np.float64)
151                dataset.ymin = np.min(dataset.qy_data)
152                dataset.ymax = np.max(dataset.qy_data)
153                dataset.q_data = np.sqrt(dataset.qx_data * dataset.qx_data
154                                         + dataset.qy_data * dataset.qy_data)
155                if dataset.err_data is not None:
156                    dataset.err_data = dataset.err_data.astype(np.float64)
157                if dataset.dqx_data is not None:
158                    dataset.dqx_data = dataset.dqx_data.astype(np.float64)
159                if dataset.dqy_data is not None:
160                    dataset.dqy_data = dataset.dqy_data.astype(np.float64)
161                if dataset.mask is not None:
162                    dataset.mask = dataset.mask.astype(dtype=bool)
163
164                if len(dataset.data.shape) == 2:
165                    n_rows, n_cols = dataset.data.shape
166                    dataset.y_bins = dataset.qy_data[0::int(n_cols)]
167                    dataset.x_bins = dataset.qx_data[:int(n_cols)]
168                dataset.data = dataset.data.flatten()
169
170    def format_unit(self, unit=None):
171        """
172        Format units a common way
173        :param unit:
174        :return:
175        """
176        if unit:
177            split = unit.split("/")
178            if len(split) == 1:
179                return unit
180            elif split[0] == '1':
181                return "{0}^".format(split[1]) + "{-1}"
182            else:
183                return "{0}*{1}^".format(split[0], split[1]) + "{-1}"
184
185    def set_all_to_none(self):
186        """
187        Set all mutable values to None for error handling purposes
188        """
189        self.current_dataset = None
190        self.current_datainfo = None
191        self.output = []
192
193    def remove_empty_q_values(self, has_error_dx=False, has_error_dy=False,
194                              has_error_dxl=False, has_error_dxw=False):
195        """
196        Remove any point where Q == 0
197        """
198        x = self.current_dataset.x
199        self.current_dataset.x = self.current_dataset.x[x != 0]
200        self.current_dataset.y = self.current_dataset.y[x != 0]
201        if has_error_dy:
202            self.current_dataset.dy = self.current_dataset.dy[x != 0]
203        if has_error_dx:
204            self.current_dataset.dx = self.current_dataset.dx[x != 0]
205        if has_error_dxl:
206            self.current_dataset.dxl = self.current_dataset.dxl[x != 0]
207        if has_error_dxw:
208            self.current_dataset.dxw = self.current_dataset.dxw[x != 0]
209
210    def reset_data_list(self, no_lines=0):
211        """
212        Reset the plottable_1D object
213        """
214        # Initialize data sets with arrays the maximum possible size
215        x = np.zeros(no_lines)
216        y = np.zeros(no_lines)
217        dx = np.zeros(no_lines)
218        dy = np.zeros(no_lines)
219        self.current_dataset = plottable_1D(x, y, dx, dy)
220
221    @staticmethod
222    def splitline(line):
223        """
224        Splits a line into pieces based on common delimeters
225        :param line: A single line of text
226        :return: list of values
227        """
228        # Initial try for CSV (split on ,)
229        toks = line.split(',')
230        # Now try SCSV (split on ;)
231        if len(toks) < 2:
232            toks = line.split(';')
233        # Now go for whitespace
234        if len(toks) < 2:
235            toks = line.split()
236        return toks
237
238    @abstractmethod
239    def get_file_contents(self):
240        """
241        Reader specific class to access the contents of the file
242        All reader classes that inherit from FileReader must implement
243        """
244        pass
Note: See TracBrowser for help on using the repository browser.