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