[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 | """ |
---|
| 43 | Basic file reader |
---|
| 44 | |
---|
| 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: |
---|
[da8bb53] | 54 | self.load_unit_converter() |
---|
[b09095a] | 55 | self.f_open = open(filepath, 'rb') |
---|
| 56 | self.get_file_contents() |
---|
| 57 | self.sort_one_d_data() |
---|
[da8bb53] | 58 | except FileContentsException as e: |
---|
| 59 | self.handle_error_message(e.message) |
---|
[beba407] | 60 | except OSError as e: |
---|
[b09095a] | 61 | # If the file cannot be opened |
---|
[beba407] | 62 | msg = "Unable to open file: {}\n".format(filepath) |
---|
| 63 | msg += e.message |
---|
| 64 | self.handle_error_message(msg) |
---|
[b09095a] | 65 | finally: |
---|
[da8bb53] | 66 | # Close the file handle if it is open |
---|
[b09095a] | 67 | if not self.f_open.closed: |
---|
| 68 | self.f_open.close() |
---|
[beba407] | 69 | else: |
---|
| 70 | msg = "Unable to find file at: {}\n".format(filepath) |
---|
| 71 | msg += "Please check your file path and try again." |
---|
| 72 | self.handle_error_message(msg) |
---|
[b09095a] | 73 | # Return a list of parsed entries that data_loader can manage |
---|
[beba407] | 74 | return self.output |
---|
| 75 | |
---|
| 76 | def handle_error_message(self, msg): |
---|
| 77 | """ |
---|
| 78 | Generic error handler to add an error to the current datainfo to |
---|
| 79 | propogate the error up the error chain. |
---|
| 80 | :param msg: Error message |
---|
| 81 | """ |
---|
| 82 | if isinstance(self.current_datainfo, DataInfo): |
---|
| 83 | self.current_datainfo.errors.append(msg) |
---|
| 84 | else: |
---|
| 85 | logger.warning(msg) |
---|
| 86 | |
---|
| 87 | def send_to_output(self): |
---|
| 88 | """ |
---|
| 89 | Helper that automatically combines the info and set and then appends it |
---|
| 90 | to output |
---|
| 91 | """ |
---|
| 92 | data_obj = combine_data_info_with_plottable(self.current_dataset, |
---|
| 93 | self.current_datainfo) |
---|
| 94 | self.output.append(data_obj) |
---|
| 95 | |
---|
[da8bb53] | 96 | def load_unit_converter(self): |
---|
[b09095a] | 97 | """ |
---|
| 98 | Generic unit conversion import |
---|
| 99 | """ |
---|
| 100 | # Check whether we have a converter available |
---|
| 101 | self.has_converter = True |
---|
| 102 | try: |
---|
| 103 | from sas.sascalc.data_util.nxsunit import Converter |
---|
| 104 | except: |
---|
| 105 | self.has_converter = False |
---|
| 106 | |
---|
| 107 | def sort_one_d_data(self): |
---|
| 108 | """ |
---|
| 109 | Sort 1D data along the X axis for consistency |
---|
| 110 | """ |
---|
| 111 | final_list = [] |
---|
| 112 | for data in self.output: |
---|
| 113 | if isinstance(data, Data1D): |
---|
| 114 | ind = np.lexsort((data.y, data.x)) |
---|
| 115 | data.x = np.asarray([data.x[i] for i in ind]) |
---|
| 116 | data.y = np.asarray([data.y[i] for i in ind]) |
---|
| 117 | if data.dx is not None: |
---|
| 118 | data.dx = np.asarray([data.dx[i] for i in ind]) |
---|
| 119 | if data.dxl is not None: |
---|
| 120 | data.dxl = np.asarray([data.dxl[i] for i in ind]) |
---|
| 121 | if data.dxw is not None: |
---|
| 122 | data.dxw = np.asarray([data.dxw[i] for i in ind]) |
---|
| 123 | if data.dy is not None: |
---|
| 124 | data.dy = np.asarray([data.dy[i] for i in ind]) |
---|
| 125 | if data.lam is not None: |
---|
| 126 | data.lam = np.asarray([data.lam[i] for i in ind]) |
---|
| 127 | if data.dlam is not None: |
---|
| 128 | data.dlam = np.asarray([data.dlam[i] for i in ind]) |
---|
| 129 | final_list.append(data) |
---|
| 130 | self.output = final_list |
---|
| 131 | |
---|
[da8bb53] | 132 | def set_all_to_none(self): |
---|
| 133 | """ |
---|
| 134 | Set all mutable values to None for error handling purposes |
---|
| 135 | """ |
---|
| 136 | self.current_dataset = None |
---|
| 137 | self.current_datainfo = None |
---|
| 138 | self.output = [] |
---|
| 139 | |
---|
[b09095a] | 140 | @staticmethod |
---|
| 141 | def splitline(line): |
---|
| 142 | """ |
---|
| 143 | Splits a line into pieces based on common delimeters |
---|
| 144 | :param line: A single line of text |
---|
| 145 | :return: list of values |
---|
| 146 | """ |
---|
| 147 | # Initial try for CSV (split on ,) |
---|
| 148 | toks = line.split(',') |
---|
| 149 | # Now try SCSV (split on ;) |
---|
| 150 | if len(toks) < 2: |
---|
| 151 | toks = line.split(';') |
---|
| 152 | # Now go for whitespace |
---|
| 153 | if len(toks) < 2: |
---|
| 154 | toks = line.split() |
---|
| 155 | return toks |
---|
| 156 | |
---|
[beba407] | 157 | @abstractmethod |
---|
[b09095a] | 158 | def get_file_contents(self): |
---|
[beba407] | 159 | """ |
---|
[b09095a] | 160 | All reader classes that inherit from FileReader must implement |
---|
[beba407] | 161 | """ |
---|
| 162 | pass |
---|