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