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

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 a78433dd was a78433dd, checked in by lewis, 7 years ago

Ensure loaded data is always sorted correctly

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