[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 |
---|
| 8 | import logging |
---|
[b09095a] | 9 | import numpy as np |
---|
[beba407] | 10 | from abc import abstractmethod |
---|
| 11 | from loader_exceptions import NoKnownLoaderException, FileContentsException,\ |
---|
[da8bb53] | 12 | DataReaderException, DefaultReaderException |
---|
[beba407] | 13 | from data_info import Data1D, Data2D, DataInfo, plottable_1D, plottable_2D,\ |
---|
| 14 | combine_data_info_with_plottable |
---|
| 15 | |
---|
| 16 | logger = logging.getLogger(__name__) |
---|
| 17 | |
---|
| 18 | |
---|
| 19 | class FileReader(object): |
---|
| 20 | # List of Data1D and Data2D objects to be sent back to data_loader |
---|
| 21 | output = [] |
---|
[b09095a] | 22 | # Current plottable_(1D/2D) object being loaded in |
---|
[beba407] | 23 | current_dataset = None |
---|
[b09095a] | 24 | # Current DataInfo object being loaded in |
---|
[beba407] | 25 | current_datainfo = None |
---|
[b09095a] | 26 | # String to describe the type of data this reader can load |
---|
| 27 | type_name = "ASCII" |
---|
| 28 | # Wildcards to display |
---|
| 29 | type = ["Text files (*.txt|*.TXT)"] |
---|
[beba407] | 30 | # List of allowed extensions |
---|
| 31 | ext = ['.txt'] |
---|
| 32 | # Bypass extension check and try to load anyway |
---|
| 33 | allow_all = False |
---|
[b09095a] | 34 | # Able to import the unit converter |
---|
| 35 | has_converter = True |
---|
| 36 | # Open file handle |
---|
| 37 | f_open = None |
---|
| 38 | # Default value of zero |
---|
| 39 | _ZERO = 1e-16 |
---|
[beba407] | 40 | |
---|
| 41 | def read(self, filepath): |
---|
| 42 | """ |
---|
[bc570f4] | 43 | Basic file reader |
---|
| 44 | |
---|
[beba407] | 45 | :param filepath: The full or relative path to a file to be loaded |
---|
| 46 | """ |
---|
| 47 | if os.path.isfile(filepath): |
---|
| 48 | basename, extension = os.path.splitext(os.path.basename(filepath)) |
---|
[da8bb53] | 49 | self.extension = extension.lower() |
---|
[beba407] | 50 | # If the file type is not allowed, return nothing |
---|
[da8bb53] | 51 | if self.extension in self.ext or self.allow_all: |
---|
[beba407] | 52 | # Try to load the file, but raise an error if unable to. |
---|
| 53 | try: |
---|
[b09095a] | 54 | self.f_open = open(filepath, 'rb') |
---|
| 55 | self.get_file_contents() |
---|
[0b79323] | 56 | |
---|
[bc570f4] | 57 | except DataReaderException as e: |
---|
[da8bb53] | 58 | self.handle_error_message(e.message) |
---|
[beba407] | 59 | except OSError as e: |
---|
[b09095a] | 60 | # If the file cannot be opened |
---|
[beba407] | 61 | msg = "Unable to open file: {}\n".format(filepath) |
---|
| 62 | msg += e.message |
---|
| 63 | self.handle_error_message(msg) |
---|
[b09095a] | 64 | finally: |
---|
[da8bb53] | 65 | # Close the file handle if it is open |
---|
[b09095a] | 66 | if not self.f_open.closed: |
---|
| 67 | self.f_open.close() |
---|
[248ff73] | 68 | if len(self.output) > 0: |
---|
| 69 | # Sort the data that's been loaded |
---|
| 70 | self.sort_one_d_data() |
---|
| 71 | self.sort_two_d_data() |
---|
[beba407] | 72 | else: |
---|
| 73 | msg = "Unable to find file at: {}\n".format(filepath) |
---|
| 74 | msg += "Please check your file path and try again." |
---|
| 75 | self.handle_error_message(msg) |
---|
[a78433dd] | 76 | |
---|
[b09095a] | 77 | # Return a list of parsed entries that data_loader can manage |
---|
[beba407] | 78 | return self.output |
---|
| 79 | |
---|
| 80 | def handle_error_message(self, msg): |
---|
| 81 | """ |
---|
| 82 | Generic error handler to add an error to the current datainfo to |
---|
| 83 | propogate the error up the error chain. |
---|
| 84 | :param msg: Error message |
---|
| 85 | """ |
---|
[dcb91cf] | 86 | if len(self.output) > 0: |
---|
| 87 | self.output[-1].errors.append(msg) |
---|
| 88 | elif isinstance(self.current_datainfo, DataInfo): |
---|
[beba407] | 89 | self.current_datainfo.errors.append(msg) |
---|
| 90 | else: |
---|
| 91 | logger.warning(msg) |
---|
| 92 | |
---|
| 93 | def send_to_output(self): |
---|
| 94 | """ |
---|
| 95 | Helper that automatically combines the info and set and then appends it |
---|
| 96 | to output |
---|
| 97 | """ |
---|
| 98 | data_obj = combine_data_info_with_plottable(self.current_dataset, |
---|
| 99 | self.current_datainfo) |
---|
| 100 | self.output.append(data_obj) |
---|
| 101 | |
---|
[b09095a] | 102 | def sort_one_d_data(self): |
---|
| 103 | """ |
---|
| 104 | Sort 1D data along the X axis for consistency |
---|
| 105 | """ |
---|
| 106 | for data in self.output: |
---|
| 107 | if isinstance(data, Data1D): |
---|
[7477fb9] | 108 | # Sort data by increasing x and remove 1st point |
---|
[b09095a] | 109 | ind = np.lexsort((data.y, data.x)) |
---|
[9d786e5] | 110 | data.x = np.asarray([data.x[i] for i in ind]).astype(np.float64) |
---|
| 111 | data.y = np.asarray([data.y[i] for i in ind]).astype(np.float64) |
---|
[b09095a] | 112 | if data.dx is not None: |
---|
[9d786e5] | 113 | data.dx = np.asarray([data.dx[i] for i in ind]).astype(np.float64) |
---|
[b09095a] | 114 | if data.dxl is not None: |
---|
[9d786e5] | 115 | data.dxl = np.asarray([data.dxl[i] for i in ind]).astype(np.float64) |
---|
[b09095a] | 116 | if data.dxw is not None: |
---|
[9d786e5] | 117 | data.dxw = np.asarray([data.dxw[i] for i in ind]).astype(np.float64) |
---|
[b09095a] | 118 | if data.dy is not None: |
---|
[9d786e5] | 119 | data.dy = np.asarray([data.dy[i] for i in ind]).astype(np.float64) |
---|
[b09095a] | 120 | if data.lam is not None: |
---|
[9d786e5] | 121 | data.lam = np.asarray([data.lam[i] for i in ind]).astype(np.float64) |
---|
[b09095a] | 122 | if data.dlam is not None: |
---|
[9d786e5] | 123 | data.dlam = np.asarray([data.dlam[i] for i in ind]).astype(np.float64) |
---|
[dcb91cf] | 124 | if len(data.x) > 0: |
---|
[248ff73] | 125 | data.xmin = np.min(data.x) |
---|
| 126 | data.xmax = np.max(data.x) |
---|
| 127 | data.ymin = np.min(data.y) |
---|
| 128 | data.ymax = np.max(data.y) |
---|
[b09095a] | 129 | |
---|
[0b79323] | 130 | def sort_two_d_data(self): |
---|
| 131 | for dataset in self.output: |
---|
[9d786e5] | 132 | if isinstance(dataset, Data2D): |
---|
| 133 | dataset.data = dataset.data.astype(np.float64) |
---|
| 134 | dataset.qx_data = dataset.qx_data.astype(np.float64) |
---|
| 135 | dataset.xmin = np.min(dataset.qx_data) |
---|
| 136 | dataset.xmax = np.max(dataset.qx_data) |
---|
| 137 | dataset.qy_data = dataset.qy_data.astype(np.float64) |
---|
| 138 | dataset.ymin = np.min(dataset.qy_data) |
---|
| 139 | dataset.ymax = np.max(dataset.qy_data) |
---|
| 140 | dataset.q_data = np.sqrt(dataset.qx_data * dataset.qx_data |
---|
| 141 | + dataset.qy_data * dataset.qy_data) |
---|
| 142 | if dataset.err_data is not None: |
---|
| 143 | dataset.err_data = dataset.err_data.astype(np.float64) |
---|
| 144 | if dataset.dqx_data is not None: |
---|
| 145 | dataset.dqx_data = dataset.dqx_data.astype(np.float64) |
---|
| 146 | if dataset.dqy_data is not None: |
---|
| 147 | dataset.dqy_data = dataset.dqy_data.astype(np.float64) |
---|
| 148 | if dataset.mask is not None: |
---|
| 149 | dataset.mask = dataset.mask.astype(dtype=bool) |
---|
| 150 | |
---|
| 151 | if len(dataset.data.shape) == 2: |
---|
| 152 | n_rows, n_cols = dataset.data.shape |
---|
| 153 | dataset.y_bins = dataset.qy_data[0::int(n_cols)] |
---|
| 154 | dataset.x_bins = dataset.qx_data[:int(n_cols)] |
---|
[2f85af7] | 155 | dataset.data = dataset.data.flatten() |
---|
[0b79323] | 156 | |
---|
[da8bb53] | 157 | def set_all_to_none(self): |
---|
| 158 | """ |
---|
| 159 | Set all mutable values to None for error handling purposes |
---|
| 160 | """ |
---|
| 161 | self.current_dataset = None |
---|
| 162 | self.current_datainfo = None |
---|
| 163 | self.output = [] |
---|
| 164 | |
---|
[ad92c5a] | 165 | def remove_empty_q_values(self, has_error_dx=False, has_error_dy=False): |
---|
| 166 | """ |
---|
| 167 | Remove any point where Q == 0 |
---|
| 168 | """ |
---|
| 169 | x = self.current_dataset.x |
---|
| 170 | self.current_dataset.x = self.current_dataset.x[x != 0] |
---|
| 171 | self.current_dataset.y = self.current_dataset.y[x != 0] |
---|
| 172 | self.current_dataset.dy = self.current_dataset.dy[x != 0] if \ |
---|
| 173 | has_error_dy else np.zeros(len(self.current_dataset.y)) |
---|
| 174 | self.current_dataset.dx = self.current_dataset.dx[x != 0] if \ |
---|
| 175 | has_error_dx else np.zeros(len(self.current_dataset.x)) |
---|
| 176 | |
---|
| 177 | def reset_data_list(self, no_lines=0): |
---|
| 178 | """ |
---|
| 179 | Reset the plottable_1D object |
---|
| 180 | """ |
---|
| 181 | # Initialize data sets with arrays the maximum possible size |
---|
| 182 | x = np.zeros(no_lines) |
---|
| 183 | y = np.zeros(no_lines) |
---|
| 184 | dy = np.zeros(no_lines) |
---|
| 185 | dx = np.zeros(no_lines) |
---|
| 186 | self.current_dataset = plottable_1D(x, y, dx, dy) |
---|
| 187 | |
---|
[b09095a] | 188 | @staticmethod |
---|
| 189 | def splitline(line): |
---|
| 190 | """ |
---|
| 191 | Splits a line into pieces based on common delimeters |
---|
| 192 | :param line: A single line of text |
---|
| 193 | :return: list of values |
---|
| 194 | """ |
---|
| 195 | # Initial try for CSV (split on ,) |
---|
| 196 | toks = line.split(',') |
---|
| 197 | # Now try SCSV (split on ;) |
---|
| 198 | if len(toks) < 2: |
---|
| 199 | toks = line.split(';') |
---|
| 200 | # Now go for whitespace |
---|
| 201 | if len(toks) < 2: |
---|
| 202 | toks = line.split() |
---|
| 203 | return toks |
---|
| 204 | |
---|
[beba407] | 205 | @abstractmethod |
---|
[b09095a] | 206 | def get_file_contents(self): |
---|
[beba407] | 207 | """ |
---|
[ad92c5a] | 208 | Reader specific class to access the contents of the file |
---|
[b09095a] | 209 | All reader classes that inherit from FileReader must implement |
---|
[beba407] | 210 | """ |
---|
| 211 | pass |
---|