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 sys |
---|
9 | import re |
---|
10 | import logging |
---|
11 | from abc import abstractmethod |
---|
12 | |
---|
13 | import numpy as np |
---|
14 | from .loader_exceptions import NoKnownLoaderException, FileContentsException,\ |
---|
15 | DataReaderException, DefaultReaderException |
---|
16 | from .data_info import Data1D, Data2D, DataInfo, plottable_1D, plottable_2D,\ |
---|
17 | combine_data_info_with_plottable |
---|
18 | |
---|
19 | logger = logging.getLogger(__name__) |
---|
20 | |
---|
21 | if sys.version_info[0] < 3: |
---|
22 | def decode(s): |
---|
23 | return s |
---|
24 | else: |
---|
25 | def decode(s): |
---|
26 | return s.decode() if isinstance(s, bytes) else s |
---|
27 | |
---|
28 | class FileReader(object): |
---|
29 | # List of Data1D and Data2D objects to be sent back to data_loader |
---|
30 | output = [] |
---|
31 | # Current plottable_(1D/2D) object being loaded in |
---|
32 | current_dataset = None |
---|
33 | # Current DataInfo object being loaded in |
---|
34 | current_datainfo = None |
---|
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)"] |
---|
39 | # List of allowed extensions |
---|
40 | ext = ['.txt'] |
---|
41 | # Bypass extension check and try to load anyway |
---|
42 | allow_all = False |
---|
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 |
---|
49 | |
---|
50 | def read(self, filepath): |
---|
51 | """ |
---|
52 | Basic file reader |
---|
53 | |
---|
54 | :param filepath: The full or relative path to a file to be loaded |
---|
55 | """ |
---|
56 | if os.path.isfile(filepath): |
---|
57 | basename, extension = os.path.splitext(os.path.basename(filepath)) |
---|
58 | self.extension = extension.lower() |
---|
59 | # If the file type is not allowed, return nothing |
---|
60 | if self.extension in self.ext or self.allow_all: |
---|
61 | # Try to load the file, but raise an error if unable to. |
---|
62 | try: |
---|
63 | self.f_open = open(filepath, 'rb') |
---|
64 | self.get_file_contents() |
---|
65 | |
---|
66 | except DataReaderException as e: |
---|
67 | self.handle_error_message(e.message) |
---|
68 | except OSError as e: |
---|
69 | # If the file cannot be opened |
---|
70 | msg = "Unable to open file: {}\n".format(filepath) |
---|
71 | msg += e.message |
---|
72 | self.handle_error_message(msg) |
---|
73 | finally: |
---|
74 | # Close the file handle if it is open |
---|
75 | if not self.f_open.closed: |
---|
76 | self.f_open.close() |
---|
77 | if len(self.output) > 0: |
---|
78 | # Sort the data that's been loaded |
---|
79 | self.sort_one_d_data() |
---|
80 | self.sort_two_d_data() |
---|
81 | else: |
---|
82 | msg = "Unable to find file at: {}\n".format(filepath) |
---|
83 | msg += "Please check your file path and try again." |
---|
84 | self.handle_error_message(msg) |
---|
85 | |
---|
86 | # Return a list of parsed entries that data_loader can manage |
---|
87 | return self.output |
---|
88 | |
---|
89 | def nextline(self): |
---|
90 | """ |
---|
91 | Returns the next line in the file as a string. |
---|
92 | """ |
---|
93 | #return self.f_open.readline() |
---|
94 | return decode(self.f_open.readline()) |
---|
95 | |
---|
96 | def nextlines(self): |
---|
97 | """ |
---|
98 | Returns the next line in the file as a string. |
---|
99 | """ |
---|
100 | for line in self.f_open: |
---|
101 | #yield line |
---|
102 | yield decode(line) |
---|
103 | |
---|
104 | def readall(self): |
---|
105 | """ |
---|
106 | Returns the entire file as a string. |
---|
107 | """ |
---|
108 | #return self.f_open.read() |
---|
109 | return decode(self.f_open.read()) |
---|
110 | |
---|
111 | def handle_error_message(self, msg): |
---|
112 | """ |
---|
113 | Generic error handler to add an error to the current datainfo to |
---|
114 | propogate the error up the error chain. |
---|
115 | :param msg: Error message |
---|
116 | """ |
---|
117 | if len(self.output) > 0: |
---|
118 | self.output[-1].errors.append(msg) |
---|
119 | elif isinstance(self.current_datainfo, DataInfo): |
---|
120 | self.current_datainfo.errors.append(msg) |
---|
121 | else: |
---|
122 | logger.warning(msg) |
---|
123 | |
---|
124 | def send_to_output(self): |
---|
125 | """ |
---|
126 | Helper that automatically combines the info and set and then appends it |
---|
127 | to output |
---|
128 | """ |
---|
129 | data_obj = combine_data_info_with_plottable(self.current_dataset, |
---|
130 | self.current_datainfo) |
---|
131 | self.output.append(data_obj) |
---|
132 | |
---|
133 | def sort_one_d_data(self): |
---|
134 | """ |
---|
135 | Sort 1D data along the X axis for consistency |
---|
136 | """ |
---|
137 | for data in self.output: |
---|
138 | if isinstance(data, Data1D): |
---|
139 | # Normalize the units for |
---|
140 | data.x_unit = self.format_unit(data.x_unit) |
---|
141 | data.y_unit = self.format_unit(data.y_unit) |
---|
142 | # Sort data by increasing x and remove 1st point |
---|
143 | ind = np.lexsort((data.y, data.x)) |
---|
144 | data.x = np.asarray([data.x[i] for i in ind]).astype(np.float64) |
---|
145 | data.y = np.asarray([data.y[i] for i in ind]).astype(np.float64) |
---|
146 | if data.dx is not None: |
---|
147 | if len(data.dx) == 0: |
---|
148 | data.dx = None |
---|
149 | continue |
---|
150 | data.dx = np.asarray([data.dx[i] for i in ind]).astype(np.float64) |
---|
151 | if data.dxl is not None: |
---|
152 | data.dxl = np.asarray([data.dxl[i] for i in ind]).astype(np.float64) |
---|
153 | if data.dxw is not None: |
---|
154 | data.dxw = np.asarray([data.dxw[i] for i in ind]).astype(np.float64) |
---|
155 | if data.dy is not None: |
---|
156 | if len(data.dy) == 0: |
---|
157 | data.dy = None |
---|
158 | continue |
---|
159 | data.dy = np.asarray([data.dy[i] for i in ind]).astype(np.float64) |
---|
160 | if data.lam is not None: |
---|
161 | data.lam = np.asarray([data.lam[i] for i in ind]).astype(np.float64) |
---|
162 | if data.dlam is not None: |
---|
163 | data.dlam = np.asarray([data.dlam[i] for i in ind]).astype(np.float64) |
---|
164 | if len(data.x) > 0: |
---|
165 | data.xmin = np.min(data.x) |
---|
166 | data.xmax = np.max(data.x) |
---|
167 | data.ymin = np.min(data.y) |
---|
168 | data.ymax = np.max(data.y) |
---|
169 | |
---|
170 | def sort_two_d_data(self): |
---|
171 | for dataset in self.output: |
---|
172 | if isinstance(dataset, Data2D): |
---|
173 | # Normalize the units for |
---|
174 | dataset.x_unit = self.format_unit(dataset.Q_unit) |
---|
175 | dataset.y_unit = self.format_unit(dataset.I_unit) |
---|
176 | dataset.data = dataset.data.astype(np.float64) |
---|
177 | dataset.qx_data = dataset.qx_data.astype(np.float64) |
---|
178 | dataset.xmin = np.min(dataset.qx_data) |
---|
179 | dataset.xmax = np.max(dataset.qx_data) |
---|
180 | dataset.qy_data = dataset.qy_data.astype(np.float64) |
---|
181 | dataset.ymin = np.min(dataset.qy_data) |
---|
182 | dataset.ymax = np.max(dataset.qy_data) |
---|
183 | dataset.q_data = np.sqrt(dataset.qx_data * dataset.qx_data |
---|
184 | + dataset.qy_data * dataset.qy_data) |
---|
185 | if dataset.err_data is not None: |
---|
186 | dataset.err_data = dataset.err_data.astype(np.float64) |
---|
187 | if dataset.dqx_data is not None: |
---|
188 | dataset.dqx_data = dataset.dqx_data.astype(np.float64) |
---|
189 | if dataset.dqy_data is not None: |
---|
190 | dataset.dqy_data = dataset.dqy_data.astype(np.float64) |
---|
191 | if dataset.mask is not None: |
---|
192 | dataset.mask = dataset.mask.astype(dtype=bool) |
---|
193 | |
---|
194 | if len(dataset.data.shape) == 2: |
---|
195 | n_rows, n_cols = dataset.data.shape |
---|
196 | dataset.y_bins = dataset.qy_data[0::int(n_cols)] |
---|
197 | dataset.x_bins = dataset.qx_data[:int(n_cols)] |
---|
198 | dataset.data = dataset.data.flatten() |
---|
199 | if len(dataset.data) > 0: |
---|
200 | dataset.xmin = np.min(dataset.qx_data) |
---|
201 | dataset.xmax = np.max(dataset.qx_data) |
---|
202 | dataset.ymin = np.min(dataset.qy_data) |
---|
203 | dataset.ymax = np.max(dataset.qx_data) |
---|
204 | |
---|
205 | def format_unit(self, unit=None): |
---|
206 | """ |
---|
207 | Format units a common way |
---|
208 | :param unit: |
---|
209 | :return: |
---|
210 | """ |
---|
211 | if unit: |
---|
212 | split = unit.split("/") |
---|
213 | if len(split) == 1: |
---|
214 | return unit |
---|
215 | elif split[0] == '1': |
---|
216 | return "{0}^".format(split[1]) + "{-1}" |
---|
217 | else: |
---|
218 | return "{0}*{1}^".format(split[0], split[1]) + "{-1}" |
---|
219 | |
---|
220 | def set_all_to_none(self): |
---|
221 | """ |
---|
222 | Set all mutable values to None for error handling purposes |
---|
223 | """ |
---|
224 | self.current_dataset = None |
---|
225 | self.current_datainfo = None |
---|
226 | self.output = [] |
---|
227 | |
---|
228 | def data_cleanup(self): |
---|
229 | """ |
---|
230 | Clean up the data sets and refresh everything |
---|
231 | :return: None |
---|
232 | """ |
---|
233 | self.remove_empty_q_values() |
---|
234 | self.send_to_output() # Combine datasets with DataInfo |
---|
235 | self.current_datainfo = DataInfo() # Reset DataInfo |
---|
236 | |
---|
237 | def remove_empty_q_values(self): |
---|
238 | """ |
---|
239 | Remove any point where Q == 0 |
---|
240 | """ |
---|
241 | if isinstance(self.current_dataset, plottable_1D): |
---|
242 | # Booleans for resolutions |
---|
243 | has_error_dx = self.current_dataset.dx is not None |
---|
244 | has_error_dxl = self.current_dataset.dxl is not None |
---|
245 | has_error_dxw = self.current_dataset.dxw is not None |
---|
246 | has_error_dy = self.current_dataset.dy is not None |
---|
247 | # Create arrays of zeros for non-existent resolutions |
---|
248 | if has_error_dxw and not has_error_dxl: |
---|
249 | array_size = self.current_dataset.dxw.size - 1 |
---|
250 | self.current_dataset.dxl = np.append(self.current_dataset.dxl, |
---|
251 | np.zeros([array_size])) |
---|
252 | has_error_dxl = True |
---|
253 | elif has_error_dxl and not has_error_dxw: |
---|
254 | array_size = self.current_dataset.dxl.size - 1 |
---|
255 | self.current_dataset.dxw = np.append(self.current_dataset.dxw, |
---|
256 | np.zeros([array_size])) |
---|
257 | has_error_dxw = True |
---|
258 | elif not has_error_dxl and not has_error_dxw and not has_error_dx: |
---|
259 | array_size = self.current_dataset.x.size - 1 |
---|
260 | self.current_dataset.dx = np.append(self.current_dataset.dx, |
---|
261 | np.zeros([array_size])) |
---|
262 | has_error_dx = True |
---|
263 | if not has_error_dy: |
---|
264 | array_size = self.current_dataset.y.size - 1 |
---|
265 | self.current_dataset.dy = np.append(self.current_dataset.dy, |
---|
266 | np.zeros([array_size])) |
---|
267 | has_error_dy = True |
---|
268 | |
---|
269 | # Remove points where q = 0 |
---|
270 | x = self.current_dataset.x |
---|
271 | self.current_dataset.x = self.current_dataset.x[x != 0] |
---|
272 | self.current_dataset.y = self.current_dataset.y[x != 0] |
---|
273 | if has_error_dy: |
---|
274 | self.current_dataset.dy = self.current_dataset.dy[x != 0] |
---|
275 | if has_error_dx: |
---|
276 | self.current_dataset.dx = self.current_dataset.dx[x != 0] |
---|
277 | if has_error_dxl: |
---|
278 | self.current_dataset.dxl = self.current_dataset.dxl[x != 0] |
---|
279 | if has_error_dxw: |
---|
280 | self.current_dataset.dxw = self.current_dataset.dxw[x != 0] |
---|
281 | elif isinstance(self.current_dataset, plottable_2D): |
---|
282 | has_error_dqx = self.current_dataset.dqx_data is not None |
---|
283 | has_error_dqy = self.current_dataset.dqy_data is not None |
---|
284 | has_error_dy = self.current_dataset.err_data is not None |
---|
285 | has_mask = self.current_dataset.mask is not None |
---|
286 | x = self.current_dataset.qx_data |
---|
287 | self.current_dataset.data = self.current_dataset.data[x != 0] |
---|
288 | self.current_dataset.qx_data = self.current_dataset.qx_data[x != 0] |
---|
289 | self.current_dataset.qy_data = self.current_dataset.qy_data[x != 0] |
---|
290 | self.current_dataset.q_data = np.sqrt( |
---|
291 | np.square(self.current_dataset.qx_data) + np.square( |
---|
292 | self.current_dataset.qy_data)) |
---|
293 | if has_error_dy: |
---|
294 | self.current_dataset.err_data = self.current_dataset.err_data[x != 0] |
---|
295 | if has_error_dqx: |
---|
296 | self.current_dataset.dqx_data = self.current_dataset.dqx_data[x != 0] |
---|
297 | if has_error_dqy: |
---|
298 | self.current_dataset.dqy_data = self.current_dataset.dqy_data[x != 0] |
---|
299 | if has_mask: |
---|
300 | self.current_dataset.mask = self.current_dataset.mask[x != 0] |
---|
301 | |
---|
302 | def reset_data_list(self, no_lines=0): |
---|
303 | """ |
---|
304 | Reset the plottable_1D object |
---|
305 | """ |
---|
306 | # Initialize data sets with arrays the maximum possible size |
---|
307 | x = np.zeros(no_lines) |
---|
308 | y = np.zeros(no_lines) |
---|
309 | dx = np.zeros(no_lines) |
---|
310 | dy = np.zeros(no_lines) |
---|
311 | self.current_dataset = plottable_1D(x, y, dx, dy) |
---|
312 | |
---|
313 | @staticmethod |
---|
314 | def splitline(line): |
---|
315 | """ |
---|
316 | Splits a line into pieces based on common delimeters |
---|
317 | :param line: A single line of text |
---|
318 | :return: list of values |
---|
319 | """ |
---|
320 | # Initial try for CSV (split on ,) |
---|
321 | toks = line.split(',') |
---|
322 | # Now try SCSV (split on ;) |
---|
323 | if len(toks) < 2: |
---|
324 | toks = line.split(';') |
---|
325 | # Now go for whitespace |
---|
326 | if len(toks) < 2: |
---|
327 | toks = line.split() |
---|
328 | return toks |
---|
329 | |
---|
330 | @abstractmethod |
---|
331 | def get_file_contents(self): |
---|
332 | """ |
---|
333 | Reader specific class to access the contents of the file |
---|
334 | All reader classes that inherit from FileReader must implement |
---|
335 | """ |
---|
336 | pass |
---|