[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 |
---|
[beba407] | 87 | return self.output |
---|
| 88 | |
---|
[26183bf] | 89 | def nextline(self): |
---|
| 90 | """ |
---|
| 91 | Returns the next line in the file as a string. |
---|
| 92 | """ |
---|
| 93 | #return self.f_open.readline() |
---|
[7b50f14] | 94 | return decode(self.f_open.readline()) |
---|
[26183bf] | 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 |
---|
[7b50f14] | 102 | yield decode(line) |
---|
[26183bf] | 103 | |
---|
| 104 | def readall(self): |
---|
| 105 | """ |
---|
| 106 | Returns the entire file as a string. |
---|
| 107 | """ |
---|
| 108 | #return self.f_open.read() |
---|
[7b50f14] | 109 | return decode(self.f_open.read()) |
---|
[26183bf] | 110 | |
---|
[beba407] | 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 | """ |
---|
[dcb91cf] | 117 | if len(self.output) > 0: |
---|
| 118 | self.output[-1].errors.append(msg) |
---|
| 119 | elif isinstance(self.current_datainfo, DataInfo): |
---|
[beba407] | 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 | |
---|
[b09095a] | 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): |
---|
[a78a02f] | 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) |
---|
[7477fb9] | 142 | # Sort data by increasing x and remove 1st point |
---|
[b09095a] | 143 | ind = np.lexsort((data.y, data.x)) |
---|
[9d786e5] | 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) |
---|
[b09095a] | 146 | if data.dx is not None: |
---|
[4660990] | 147 | if len(data.dx) == 0: |
---|
| 148 | data.dx = None |
---|
| 149 | continue |
---|
[9d786e5] | 150 | data.dx = np.asarray([data.dx[i] for i in ind]).astype(np.float64) |
---|
[b09095a] | 151 | if data.dxl is not None: |
---|
[9d786e5] | 152 | data.dxl = np.asarray([data.dxl[i] for i in ind]).astype(np.float64) |
---|
[b09095a] | 153 | if data.dxw is not None: |
---|
[9d786e5] | 154 | data.dxw = np.asarray([data.dxw[i] for i in ind]).astype(np.float64) |
---|
[b09095a] | 155 | if data.dy is not None: |
---|
[4660990] | 156 | if len(data.dy) == 0: |
---|
| 157 | data.dy = None |
---|
| 158 | continue |
---|
[9d786e5] | 159 | data.dy = np.asarray([data.dy[i] for i in ind]).astype(np.float64) |
---|
[b09095a] | 160 | if data.lam is not None: |
---|
[9d786e5] | 161 | data.lam = np.asarray([data.lam[i] for i in ind]).astype(np.float64) |
---|
[b09095a] | 162 | if data.dlam is not None: |
---|
[9d786e5] | 163 | data.dlam = np.asarray([data.dlam[i] for i in ind]).astype(np.float64) |
---|
[dcb91cf] | 164 | if len(data.x) > 0: |
---|
[248ff73] | 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) |
---|
[b09095a] | 169 | |
---|
[0b79323] | 170 | def sort_two_d_data(self): |
---|
| 171 | for dataset in self.output: |
---|
[9d786e5] | 172 | if isinstance(dataset, Data2D): |
---|
[a78a02f] | 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) |
---|
[9d786e5] | 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)] |
---|
[2f85af7] | 198 | dataset.data = dataset.data.flatten() |
---|
[0b79323] | 199 | |
---|
[a78a02f] | 200 | def format_unit(self, unit=None): |
---|
| 201 | """ |
---|
| 202 | Format units a common way |
---|
| 203 | :param unit: |
---|
| 204 | :return: |
---|
| 205 | """ |
---|
| 206 | if unit: |
---|
| 207 | split = unit.split("/") |
---|
| 208 | if len(split) == 1: |
---|
| 209 | return unit |
---|
| 210 | elif split[0] == '1': |
---|
| 211 | return "{0}^".format(split[1]) + "{-1}" |
---|
| 212 | else: |
---|
| 213 | return "{0}*{1}^".format(split[0], split[1]) + "{-1}" |
---|
| 214 | |
---|
[da8bb53] | 215 | def set_all_to_none(self): |
---|
| 216 | """ |
---|
| 217 | Set all mutable values to None for error handling purposes |
---|
| 218 | """ |
---|
| 219 | self.current_dataset = None |
---|
| 220 | self.current_datainfo = None |
---|
| 221 | self.output = [] |
---|
| 222 | |
---|
[ae69c690] | 223 | def remove_empty_q_values(self, has_error_dx=False, has_error_dy=False, |
---|
| 224 | has_error_dxl=False, has_error_dxw=False): |
---|
[ad92c5a] | 225 | """ |
---|
| 226 | Remove any point where Q == 0 |
---|
| 227 | """ |
---|
| 228 | x = self.current_dataset.x |
---|
| 229 | self.current_dataset.x = self.current_dataset.x[x != 0] |
---|
| 230 | self.current_dataset.y = self.current_dataset.y[x != 0] |
---|
[ae69c690] | 231 | if has_error_dy: |
---|
| 232 | self.current_dataset.dy = self.current_dataset.dy[x != 0] |
---|
| 233 | if has_error_dx: |
---|
| 234 | self.current_dataset.dx = self.current_dataset.dx[x != 0] |
---|
| 235 | if has_error_dxl: |
---|
| 236 | self.current_dataset.dxl = self.current_dataset.dxl[x != 0] |
---|
| 237 | if has_error_dxw: |
---|
| 238 | self.current_dataset.dxw = self.current_dataset.dxw[x != 0] |
---|
[ad92c5a] | 239 | |
---|
| 240 | def reset_data_list(self, no_lines=0): |
---|
| 241 | """ |
---|
| 242 | Reset the plottable_1D object |
---|
| 243 | """ |
---|
| 244 | # Initialize data sets with arrays the maximum possible size |
---|
| 245 | x = np.zeros(no_lines) |
---|
| 246 | y = np.zeros(no_lines) |
---|
[4660990] | 247 | dx = np.zeros(no_lines) |
---|
| 248 | dy = np.zeros(no_lines) |
---|
| 249 | self.current_dataset = plottable_1D(x, y, dx, dy) |
---|
[ad92c5a] | 250 | |
---|
[b09095a] | 251 | @staticmethod |
---|
| 252 | def splitline(line): |
---|
| 253 | """ |
---|
| 254 | Splits a line into pieces based on common delimeters |
---|
| 255 | :param line: A single line of text |
---|
| 256 | :return: list of values |
---|
| 257 | """ |
---|
| 258 | # Initial try for CSV (split on ,) |
---|
| 259 | toks = line.split(',') |
---|
| 260 | # Now try SCSV (split on ;) |
---|
| 261 | if len(toks) < 2: |
---|
| 262 | toks = line.split(';') |
---|
| 263 | # Now go for whitespace |
---|
| 264 | if len(toks) < 2: |
---|
| 265 | toks = line.split() |
---|
| 266 | return toks |
---|
| 267 | |
---|
[beba407] | 268 | @abstractmethod |
---|
[b09095a] | 269 | def get_file_contents(self): |
---|
[beba407] | 270 | """ |
---|
[ad92c5a] | 271 | Reader specific class to access the contents of the file |
---|
[b09095a] | 272 | All reader classes that inherit from FileReader must implement |
---|
[beba407] | 273 | """ |
---|
| 274 | pass |
---|