1 | """ |
---|
2 | This is the base file reader class most file readers should inherit from. |
---|
3 | All generic functionality required for a file loader/reader is built into this |
---|
4 | class |
---|
5 | """ |
---|
6 | |
---|
7 | import os |
---|
8 | import logging |
---|
9 | import numpy as np |
---|
10 | from abc import abstractmethod |
---|
11 | from loader_exceptions import NoKnownLoaderException, FileContentsException,\ |
---|
12 | DataReaderException, DefaultReaderException |
---|
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 = [] |
---|
22 | # Current plottable_(1D/2D) object being loaded in |
---|
23 | current_dataset = None |
---|
24 | # Current DataInfo object being loaded in |
---|
25 | current_datainfo = None |
---|
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)"] |
---|
30 | # List of allowed extensions |
---|
31 | ext = ['.txt'] |
---|
32 | # Bypass extension check and try to load anyway |
---|
33 | allow_all = False |
---|
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 |
---|
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)) |
---|
49 | self.extension = extension.lower() |
---|
50 | # If the file type is not allowed, return nothing |
---|
51 | if self.extension in self.ext or self.allow_all: |
---|
52 | # Try to load the file, but raise an error if unable to. |
---|
53 | try: |
---|
54 | self.f_open = open(filepath, 'rb') |
---|
55 | self.get_file_contents() |
---|
56 | self.sort_one_d_data() |
---|
57 | except FileContentsException as e: |
---|
58 | self.handle_error_message(e.message) |
---|
59 | except OSError as e: |
---|
60 | # If the file cannot be opened |
---|
61 | msg = "Unable to open file: {}\n".format(filepath) |
---|
62 | msg += e.message |
---|
63 | self.handle_error_message(msg) |
---|
64 | finally: |
---|
65 | # Close the file handle if it is open |
---|
66 | if not self.f_open.closed: |
---|
67 | self.f_open.close() |
---|
68 | else: |
---|
69 | msg = "Unable to find file at: {}\n".format(filepath) |
---|
70 | msg += "Please check your file path and try again." |
---|
71 | self.handle_error_message(msg) |
---|
72 | # Return a list of parsed entries that data_loader can manage |
---|
73 | return self.output |
---|
74 | |
---|
75 | def handle_error_message(self, msg): |
---|
76 | """ |
---|
77 | Generic error handler to add an error to the current datainfo to |
---|
78 | propogate the error up the error chain. |
---|
79 | :param msg: Error message |
---|
80 | """ |
---|
81 | if isinstance(self.current_datainfo, DataInfo): |
---|
82 | self.current_datainfo.errors.append(msg) |
---|
83 | else: |
---|
84 | logger.warning(msg) |
---|
85 | |
---|
86 | def send_to_output(self): |
---|
87 | """ |
---|
88 | Helper that automatically combines the info and set and then appends it |
---|
89 | to output |
---|
90 | """ |
---|
91 | data_obj = combine_data_info_with_plottable(self.current_dataset, |
---|
92 | self.current_datainfo) |
---|
93 | self.output.append(data_obj) |
---|
94 | |
---|
95 | def sort_one_d_data(self): |
---|
96 | """ |
---|
97 | Sort 1D data along the X axis for consistency |
---|
98 | """ |
---|
99 | final_list = [] |
---|
100 | for data in self.output: |
---|
101 | if isinstance(data, Data1D): |
---|
102 | ind = np.lexsort((data.y, data.x)) |
---|
103 | data.x = np.asarray([data.x[i] for i in ind]) |
---|
104 | data.y = np.asarray([data.y[i] for i in ind]) |
---|
105 | if data.dx is not None: |
---|
106 | data.dx = np.asarray([data.dx[i] for i in ind]) |
---|
107 | if data.dxl is not None: |
---|
108 | data.dxl = np.asarray([data.dxl[i] for i in ind]) |
---|
109 | if data.dxw is not None: |
---|
110 | data.dxw = np.asarray([data.dxw[i] for i in ind]) |
---|
111 | if data.dy is not None: |
---|
112 | data.dy = np.asarray([data.dy[i] for i in ind]) |
---|
113 | if data.lam is not None: |
---|
114 | data.lam = np.asarray([data.lam[i] for i in ind]) |
---|
115 | if data.dlam is not None: |
---|
116 | data.dlam = np.asarray([data.dlam[i] for i in ind]) |
---|
117 | final_list.append(data) |
---|
118 | self.output = final_list |
---|
119 | |
---|
120 | def set_all_to_none(self): |
---|
121 | """ |
---|
122 | Set all mutable values to None for error handling purposes |
---|
123 | """ |
---|
124 | self.current_dataset = None |
---|
125 | self.current_datainfo = None |
---|
126 | self.output = [] |
---|
127 | |
---|
128 | def remove_empty_q_values(self, has_error_dx=False, has_error_dy=False): |
---|
129 | """ |
---|
130 | Remove any point where Q == 0 |
---|
131 | """ |
---|
132 | x = self.current_dataset.x |
---|
133 | self.current_dataset.x = self.current_dataset.x[x != 0] |
---|
134 | self.current_dataset.y = self.current_dataset.y[x != 0] |
---|
135 | self.current_dataset.dy = self.current_dataset.dy[x != 0] if \ |
---|
136 | has_error_dy else np.zeros(len(self.current_dataset.y)) |
---|
137 | self.current_dataset.dx = self.current_dataset.dx[x != 0] if \ |
---|
138 | has_error_dx else np.zeros(len(self.current_dataset.x)) |
---|
139 | |
---|
140 | def reset_data_list(self, no_lines=0): |
---|
141 | """ |
---|
142 | Reset the plottable_1D object |
---|
143 | """ |
---|
144 | # Initialize data sets with arrays the maximum possible size |
---|
145 | x = np.zeros(no_lines) |
---|
146 | y = np.zeros(no_lines) |
---|
147 | dy = np.zeros(no_lines) |
---|
148 | dx = np.zeros(no_lines) |
---|
149 | self.current_dataset = plottable_1D(x, y, dx, dy) |
---|
150 | |
---|
151 | @staticmethod |
---|
152 | def splitline(line): |
---|
153 | """ |
---|
154 | Splits a line into pieces based on common delimeters |
---|
155 | :param line: A single line of text |
---|
156 | :return: list of values |
---|
157 | """ |
---|
158 | # Initial try for CSV (split on ,) |
---|
159 | toks = line.split(',') |
---|
160 | # Now try SCSV (split on ;) |
---|
161 | if len(toks) < 2: |
---|
162 | toks = line.split(';') |
---|
163 | # Now go for whitespace |
---|
164 | if len(toks) < 2: |
---|
165 | toks = line.split() |
---|
166 | return toks |
---|
167 | |
---|
168 | @abstractmethod |
---|
169 | def get_file_contents(self): |
---|
170 | """ |
---|
171 | Reader specific class to access the contents of the file |
---|
172 | All reader classes that inherit from FileReader must implement |
---|
173 | """ |
---|
174 | pass |
---|