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