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