|
a |
|
b/Features/Variables.py |
|
|
1 |
#!/usr/bin/env python |
|
|
2 |
# -*- coding: UTF-8 -*- |
|
|
3 |
# |
|
|
4 |
# Copyright 2017 University of Westminster. All Rights Reserved. |
|
|
5 |
# |
|
|
6 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
|
|
7 |
# you may not use this file except in compliance with the License. |
|
|
8 |
# You may obtain a copy of the License at |
|
|
9 |
# |
|
|
10 |
# http://www.apache.org/licenses/LICENSE-2.0 |
|
|
11 |
# |
|
|
12 |
# Unless required by applicable law or agreed to in writing, software |
|
|
13 |
# distributed under the License is distributed on an "AS IS" BASIS, |
|
|
14 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|
|
15 |
# See the License for the specific language governing permissions and |
|
|
16 |
# limitations under the License. |
|
|
17 |
# ============================================================================== |
|
|
18 |
""" It reads and process variables. |
|
|
19 |
""" |
|
|
20 |
|
|
|
21 |
from typing import List, TypeVar, Dict, Callable |
|
|
22 |
import sys |
|
|
23 |
import logging |
|
|
24 |
import pandas as pd |
|
|
25 |
from ReadersWriters.ReadersWriters import ReadersWriters |
|
|
26 |
from Features.FeatureParser import FeatureParser |
|
|
27 |
from Configs.CONSTANTS import CONSTANTS |
|
|
28 |
|
|
|
29 |
PandasDataFrame = TypeVar('DataFrame') |
|
|
30 |
FeaturesFeatureParser = TypeVar('FeatureParser') |
|
|
31 |
|
|
|
32 |
__author__ = "Mohsen Mesgarpour" |
|
|
33 |
__copyright__ = "Copyright 2016, https://github.com/mesgarpour" |
|
|
34 |
__credits__ = ["Mohsen Mesgarpour"] |
|
|
35 |
__license__ = "GPL" |
|
|
36 |
__version__ = "1.1" |
|
|
37 |
__maintainer__ = "Mohsen Mesgarpour" |
|
|
38 |
__email__ = "mohsen.mesgarpour@gmail.com" |
|
|
39 |
__status__ = "Release" |
|
|
40 |
|
|
|
41 |
|
|
|
42 |
class Variables: |
|
|
43 |
def __init__(self, |
|
|
44 |
model_features_table: str, |
|
|
45 |
input_path: str, |
|
|
46 |
output_path: str, |
|
|
47 |
input_features_configs: str, |
|
|
48 |
output_table: str): |
|
|
49 |
"""Initialise the objects and constants. |
|
|
50 |
:param model_features_table: the feature table name. |
|
|
51 |
:param input_path: the input path. |
|
|
52 |
:param output_path: the output path. |
|
|
53 |
:param input_features_configs: the input features' configuration file. |
|
|
54 |
:param output_table: the output table name. |
|
|
55 |
""" |
|
|
56 |
self.__logger = logging.getLogger(CONSTANTS.app_name) |
|
|
57 |
self.__logger.debug(__name__) |
|
|
58 |
self.__model_features_table = model_features_table |
|
|
59 |
self.__output_path = output_path |
|
|
60 |
self.__output_table = output_table |
|
|
61 |
self.__readers_writers = ReadersWriters() |
|
|
62 |
# initialise settings |
|
|
63 |
self.__variables_settings = self.__init_settings(input_path, input_features_configs) |
|
|
64 |
self.__features_dic_names = self.__init_features_names() |
|
|
65 |
self.__features_dic_dtypes = self.__init_features_dtypes() |
|
|
66 |
self.__init_output(output_path, output_table) |
|
|
67 |
|
|
|
68 |
def set(self, |
|
|
69 |
input_schemas: List, |
|
|
70 |
input_tables: List, |
|
|
71 |
history_tables: List, |
|
|
72 |
column_index: str, |
|
|
73 |
query_batch_size: int): |
|
|
74 |
"""Set the variables by reading the selected features from MySQL database. |
|
|
75 |
:param input_schemas: the mysql database schemas. |
|
|
76 |
:param input_tables: the mysql table names. |
|
|
77 |
:param history_tables: the source tables' alias names (a.k.a. history table name) that features belong to |
|
|
78 |
(e.g. inpatient, or outpatient). |
|
|
79 |
:param column_index: the name of index column (unique integer value) in the database table, which is used |
|
|
80 |
for batch reading the input. |
|
|
81 |
:param query_batch_size: the number of rows to be read in each batch. |
|
|
82 |
:return: |
|
|
83 |
""" |
|
|
84 |
self.__logger.debug(__name__) |
|
|
85 |
query_batch_start, query_batch_max = self.__init_batch(input_schemas[0], input_tables[0]) |
|
|
86 |
features_names, features_dtypes = self.__set_features_names_types() |
|
|
87 |
self.__validate_mysql_names(input_schemas, input_tables) |
|
|
88 |
prevalence = self.__init_prevalence(input_schemas, input_tables, history_tables) |
|
|
89 |
self.__set_batch(features_names, features_dtypes, input_schemas, input_tables, history_tables, column_index, |
|
|
90 |
prevalence, query_batch_start, query_batch_max, query_batch_size) |
|
|
91 |
|
|
|
92 |
def __init_settings(self, |
|
|
93 |
input_path: str, |
|
|
94 |
input_features_configs: str) -> PandasDataFrame: |
|
|
95 |
"""Read and set the settings of input variables that are selected. |
|
|
96 |
:param input_path: the path of the input file. |
|
|
97 |
:param input_features_configs: the input features' configuration file. |
|
|
98 |
:return: the input variables settings. |
|
|
99 |
""" |
|
|
100 |
self.__logger.debug(__name__) |
|
|
101 |
variables_settings = self.__readers_writers.load_csv(input_path, input_features_configs, 0, True) |
|
|
102 |
variables_settings = variables_settings.loc[ |
|
|
103 |
(variables_settings["Selected"] == 1) & |
|
|
104 |
(variables_settings["Table_Reference_Name"] == self.__model_features_table)] |
|
|
105 |
variables_settings = variables_settings.reset_index() |
|
|
106 |
return variables_settings |
|
|
107 |
|
|
|
108 |
def __init_features_names(self) -> Dict: |
|
|
109 |
"""Generate the features names, based on variable name, source table alias name (a.k.a. history table |
|
|
110 |
name), and the aggregation function name. |
|
|
111 |
:return: the name of features. |
|
|
112 |
""" |
|
|
113 |
self.__logger.debug(__name__) |
|
|
114 |
table_history_names = set(self.__variables_settings["Table_History_Name"]) |
|
|
115 |
features_names = dict(zip(table_history_names, [[] for _ in range(len(table_history_names))])) |
|
|
116 |
for _, row in self.__variables_settings.iterrows(): |
|
|
117 |
if not pd.isnull(row["Variable_Aggregation"]): |
|
|
118 |
postfixes = row["Variable_Aggregation"].replace(' ', '').split(',') |
|
|
119 |
for postfix in postfixes: |
|
|
120 |
features_names[row["Table_History_Name"]].append(row["Variable_Name"] + "_" + postfix) |
|
|
121 |
else: |
|
|
122 |
features_names[row["Table_History_Name"]].append(row["Variable_Name"]) |
|
|
123 |
return features_names |
|
|
124 |
|
|
|
125 |
def __init_features_dtypes(self) -> Dict: |
|
|
126 |
"""Generate the features types, based on the input configuration file. |
|
|
127 |
:return: the dtypes of features. |
|
|
128 |
""" |
|
|
129 |
self.__logger.debug(__name__) |
|
|
130 |
table_history_names = set(self.__variables_settings["Table_History_Name"]) |
|
|
131 |
features_dtypes = dict(zip(table_history_names, [[] for _ in range(len(table_history_names))])) |
|
|
132 |
for _, row in self.__variables_settings.iterrows(): |
|
|
133 |
feature_types = row["Variable_dType"].replace(' ', '').split(',') |
|
|
134 |
for feature_type in feature_types: |
|
|
135 |
features_dtypes[row["Table_History_Name"]].append(feature_type) |
|
|
136 |
return features_dtypes |
|
|
137 |
|
|
|
138 |
def __init_output(self, |
|
|
139 |
output_path: str, |
|
|
140 |
output_table: str): |
|
|
141 |
"""Initialise the output file by writing the header row. |
|
|
142 |
:param output_path: the output path. |
|
|
143 |
:param output_table: the output table name. |
|
|
144 |
""" |
|
|
145 |
self.__logger.debug(__name__) |
|
|
146 |
keys = sorted(self.__features_dic_names.keys()) |
|
|
147 |
features_names = [f for k in keys for f in self.__features_dic_names[k]] |
|
|
148 |
self.__readers_writers.reset_csv(output_path, output_table) |
|
|
149 |
self.__readers_writers.save_csv(output_path, output_table, features_names, append=False) |
|
|
150 |
|
|
|
151 |
def __init_prevalence(self, |
|
|
152 |
input_schemas: List, |
|
|
153 |
input_tables: List, |
|
|
154 |
history_tables: List)-> Dict: |
|
|
155 |
"""Generate the prevalence dictionary of values for all the variables. |
|
|
156 |
:param input_schemas: the mysql database schemas. |
|
|
157 |
:param input_tables: the mysql table names. |
|
|
158 |
:param history_tables: the source tables' alias names (a.k.a. history table name) that features belong to |
|
|
159 |
(e.g. inpatient, or outpatient). |
|
|
160 |
:return: the prevalence dictionary of values for all the variables. |
|
|
161 |
""" |
|
|
162 |
self.__readers_writers.save_text( |
|
|
163 |
self.__output_path, self.__output_table, |
|
|
164 |
["Feature Name", "Top Prevalence Feature Name"], append=False, ext="ini") |
|
|
165 |
self.__readers_writers.save_text( |
|
|
166 |
self.__output_path, self.__output_table, |
|
|
167 |
["Feature Name", "Prevalence & Freq."], append=False, ext="txt") |
|
|
168 |
feature_parser = FeatureParser(self.__variables_settings, self.__output_path, self.__output_table) |
|
|
169 |
prevalence = dict() |
|
|
170 |
|
|
|
171 |
# for tables |
|
|
172 |
for table_i in range(len(input_schemas)): |
|
|
173 |
variables_settings = self.__variables_settings[ |
|
|
174 |
self.__variables_settings["Table_History_Name"] == history_tables[table_i]] |
|
|
175 |
prevalence[input_tables[table_i]] = dict() |
|
|
176 |
|
|
|
177 |
# for features |
|
|
178 |
for _, row in variables_settings.iterrows(): |
|
|
179 |
self.__logger.info("Prevalence: " + row["Variable_Name"] + " ...") |
|
|
180 |
if not pd.isnull(row["Variable_Aggregation"]): |
|
|
181 |
# read features |
|
|
182 |
variables = self.__init_prevalence_read( |
|
|
183 |
input_schemas[table_i], input_tables[table_i], row["Variable_Name"]) |
|
|
184 |
|
|
|
185 |
# validate |
|
|
186 |
if variables is None or len(variables) == 0: |
|
|
187 |
continue |
|
|
188 |
|
|
|
189 |
# prevalence |
|
|
190 |
prevalence[input_tables[table_i]][row["Variable_Name"]] = \ |
|
|
191 |
feature_parser.prevalence(variables[row["Variable_Name"]], row["Variable_Name"]) |
|
|
192 |
|
|
|
193 |
# for sub features |
|
|
194 |
postfixes = row["Variable_Aggregation"].replace(' ', '').split(',') |
|
|
195 |
for p in range(len(postfixes)): |
|
|
196 |
feature_name = row["Variable_Name"] + "_" + postfixes[p] |
|
|
197 |
if len(postfixes[p]) > 11 and postfixes[p][0:11] == "prevalence_": |
|
|
198 |
index = int(postfixes[p].split('_')[1]) - 1 |
|
|
199 |
feature_name_prevalence = "None" |
|
|
200 |
if index < len(prevalence[input_tables[table_i]][row["Variable_Name"]]): |
|
|
201 |
feature_name_prevalence = \ |
|
|
202 |
feature_name + "_" + \ |
|
|
203 |
str(prevalence[input_tables[table_i]][row["Variable_Name"]][index]) |
|
|
204 |
# save prevalence |
|
|
205 |
self.__readers_writers.save_text(self.__output_path, self.__output_table, |
|
|
206 |
[feature_name, feature_name_prevalence], |
|
|
207 |
append=True, ext="ini") |
|
|
208 |
return prevalence |
|
|
209 |
|
|
|
210 |
def __init_prevalence_read(self, |
|
|
211 |
input_schema: str, |
|
|
212 |
input_table: str, |
|
|
213 |
variable_name: str) -> PandasDataFrame: |
|
|
214 |
"""Read a variable from database, to calculate the prevalence of the values. |
|
|
215 |
:param input_schema: the mysql database schema. |
|
|
216 |
:param input_table: the mysql database table. |
|
|
217 |
:param variable_name: the variable name. |
|
|
218 |
:return: the selected variable. |
|
|
219 |
""" |
|
|
220 |
query = "SELECT `" + variable_name + "` FROM `" + input_table + "`;" |
|
|
221 |
return self.__readers_writers.load_mysql_query(query, input_schema, dataframing=True) |
|
|
222 |
|
|
|
223 |
def __init_batch(self, |
|
|
224 |
input_schema: str, |
|
|
225 |
input_table: str) -> [int, int]: |
|
|
226 |
"""Find the minimum and maximum value of the index column, to use when reading mysql tables in |
|
|
227 |
batches. |
|
|
228 |
:param input_schema: the mysql database schema. |
|
|
229 |
:param input_table: the mysql database table. |
|
|
230 |
:return: the minimum and maximum of the index column. |
|
|
231 |
""" |
|
|
232 |
self.__logger.debug(__name__) |
|
|
233 |
query = "select min(localID), max(localID) from `" + input_table + "`;" |
|
|
234 |
output = list(self.__readers_writers.load_mysql_query(query, input_schema, dataframing=False)) |
|
|
235 |
if [r[0] for r in output][0] is None: |
|
|
236 |
self.__logger.error(__name__ + " No data is found: " + query) |
|
|
237 |
sys.exit() |
|
|
238 |
|
|
|
239 |
query_batch_start = int([r[0] for r in output][0]) |
|
|
240 |
query_batch_max = int([r[1] for r in output][0]) |
|
|
241 |
return query_batch_start, query_batch_max |
|
|
242 |
|
|
|
243 |
def __set_features_names_types(self): |
|
|
244 |
"""Produce the sorted lists of features names and features dtypes. |
|
|
245 |
:return: the sorted lists of features names and features dtypes. |
|
|
246 |
""" |
|
|
247 |
self.__logger.debug(__name__) |
|
|
248 |
keys = sorted(self.__features_dic_names.keys()) |
|
|
249 |
features_names = [f for k in keys for f in self.__features_dic_names[k]] |
|
|
250 |
features_dtypes = [pd.Series(dtype=f) for k in keys for f in self.__features_dic_dtypes[k]] |
|
|
251 |
features_dtypes = pd.DataFrame(dict(zip(features_names, features_dtypes))).dtypes |
|
|
252 |
return features_names, features_dtypes |
|
|
253 |
|
|
|
254 |
def __set_batch(self, |
|
|
255 |
features_names: list, |
|
|
256 |
features_dtypes: Dict, |
|
|
257 |
input_schemas: List, |
|
|
258 |
input_tables: List, |
|
|
259 |
history_tables: List, |
|
|
260 |
column_index: str, |
|
|
261 |
prevalence: Dict, |
|
|
262 |
query_batch_start: int, |
|
|
263 |
query_batch_max: int, |
|
|
264 |
query_batch_size: int): |
|
|
265 |
"""Using batch processing first read variables, then generate features and write them into output. |
|
|
266 |
:param features_names: the name of features that are selected. |
|
|
267 |
:param features_dtypes: the dtypes of features that are selected. |
|
|
268 |
:param input_schemas: the mysql database schemas. |
|
|
269 |
:param input_tables: the mysql table names. |
|
|
270 |
:param history_tables: the source tables' alias names (a.k.a. history table name) that features belong to |
|
|
271 |
(e.g. inpatient, or outpatient). |
|
|
272 |
:param column_index: the name of index column (unique integer value) in the database table, which is used |
|
|
273 |
for batch reading the input. |
|
|
274 |
:param prevalence: the prevalence dictionary of values for all the variables. |
|
|
275 |
:param query_batch_start: the minimum value of the column index. |
|
|
276 |
:param query_batch_max: the maximum value of the column index. |
|
|
277 |
:param query_batch_size: the number of rows to be read in each batch. |
|
|
278 |
""" |
|
|
279 |
self.__logger.debug(__name__) |
|
|
280 |
feature_parser = FeatureParser(self.__variables_settings, self.__output_path, self.__output_table) |
|
|
281 |
step = -1 |
|
|
282 |
batch_break = False |
|
|
283 |
|
|
|
284 |
while not batch_break: |
|
|
285 |
step += 1 |
|
|
286 |
features = None |
|
|
287 |
for table_i in range(len(input_schemas)): |
|
|
288 |
self.__logger.info("Batch: " + str(step) + "; Table: " + input_tables[table_i]) |
|
|
289 |
|
|
|
290 |
# read job |
|
|
291 |
variables = self.__set_batch_read(input_schemas[table_i], input_tables[table_i], step, column_index, |
|
|
292 |
query_batch_start, query_batch_max, query_batch_size) |
|
|
293 |
|
|
|
294 |
# validate |
|
|
295 |
if variables is None: |
|
|
296 |
batch_break = True |
|
|
297 |
break |
|
|
298 |
elif len(variables) == 0: |
|
|
299 |
continue |
|
|
300 |
|
|
|
301 |
# process job |
|
|
302 |
if features is None: |
|
|
303 |
features = pd.DataFrame(0, index=range(len(variables)), columns=features_names) |
|
|
304 |
features = features.astype(dtype=features_dtypes) |
|
|
305 |
features = self.__set_batch_process( |
|
|
306 |
feature_parser, history_tables[table_i], features, variables, prevalence[input_tables[table_i]]) |
|
|
307 |
|
|
|
308 |
# write job |
|
|
309 |
if features is not None: |
|
|
310 |
features = features.astype(dtype=features_dtypes) |
|
|
311 |
self.__set_batch_write(features) |
|
|
312 |
|
|
|
313 |
def __set_batch_read(self, |
|
|
314 |
input_schema: str, |
|
|
315 |
input_table: str, |
|
|
316 |
step: int, |
|
|
317 |
column_index: str, |
|
|
318 |
query_batch_start: int, |
|
|
319 |
query_batch_max: int, |
|
|
320 |
query_batch_size: int) -> Callable[[PandasDataFrame, None], None]: |
|
|
321 |
"""Read the queried variables. |
|
|
322 |
:param input_schema: the mysql database schema. |
|
|
323 |
:param input_table: the mysql database table. |
|
|
324 |
:param step: the batch id. |
|
|
325 |
:param column_index: the name of index column (unique integer value) in the database table, which is used |
|
|
326 |
for batch reading the input. |
|
|
327 |
:param query_batch_start: the minimum value of the column index. |
|
|
328 |
:param query_batch_max: the maximum value of the column index. |
|
|
329 |
:param query_batch_size: the number of rows to be read in each batch. |
|
|
330 |
:return: the queried variables. |
|
|
331 |
""" |
|
|
332 |
step_start = query_batch_start + step * query_batch_size |
|
|
333 |
step_end = step_start + query_batch_size |
|
|
334 |
if step_start >= query_batch_max: |
|
|
335 |
return None |
|
|
336 |
# read |
|
|
337 |
query = "SELECT * FROM `" + input_table + \ |
|
|
338 |
"` WHERE `" + str(column_index) + "` >= " + str(step_start) + \ |
|
|
339 |
" AND `" + str(column_index) + "` < " + str(step_end) + ";" |
|
|
340 |
return self.__readers_writers.load_mysql_query(query, input_schema, dataframing=True) |
|
|
341 |
|
|
|
342 |
def __set_batch_process(self, |
|
|
343 |
feature_parser: FeaturesFeatureParser, |
|
|
344 |
history_table: str, |
|
|
345 |
features: PandasDataFrame, |
|
|
346 |
variables: PandasDataFrame, |
|
|
347 |
prevalence: List) -> PandasDataFrame: |
|
|
348 |
"""Process variables and generate features. |
|
|
349 |
:param feature_parser: |
|
|
350 |
:param history_table: the source table alias name (a.k.a. history table name) that features belong to |
|
|
351 |
(e.g. inpatient, or outpatient). |
|
|
352 |
:param features: the output features. |
|
|
353 |
:param variables: the input variables. |
|
|
354 |
:param prevalence: the prevalence dictionary of values for all the variables. |
|
|
355 |
:return: the generated features. |
|
|
356 |
""" |
|
|
357 |
return feature_parser.generate(history_table, features, variables, prevalence) |
|
|
358 |
|
|
|
359 |
def __set_batch_write(self, |
|
|
360 |
features: PandasDataFrame): |
|
|
361 |
"""Write the features into an output file. |
|
|
362 |
:param features: the output features. |
|
|
363 |
""" |
|
|
364 |
self.__readers_writers.save_csv(self.__output_path, self.__output_table, features, append=True) |
|
|
365 |
|
|
|
366 |
def __validate_mysql_names(self, |
|
|
367 |
input_schemas: List, |
|
|
368 |
history_tables: List): |
|
|
369 |
"""Validate mysql tables and their columns, and generate exception if table/column name is invalid. |
|
|
370 |
:param input_schemas: the mysql database schemas. |
|
|
371 |
:param history_tables: the source tables' alias names (a.k.a. history table name) that features belong to |
|
|
372 |
(e.g. inpatient, or outpatient). |
|
|
373 |
""" |
|
|
374 |
# for tables |
|
|
375 |
for table_i in range(len(input_schemas)): |
|
|
376 |
variables_settings = self.__variables_settings[ |
|
|
377 |
self.__variables_settings["Table_History_Name"] == history_tables[table_i]] |
|
|
378 |
# validate table name |
|
|
379 |
if not self.__readers_writers.exists_mysql( |
|
|
380 |
input_schemas[table_i], history_tables[table_i]): |
|
|
381 |
self.__logger.error(__name__ + " - Table does not exist: " + history_tables[table_i]) |
|
|
382 |
sys.exit() |
|
|
383 |
|
|
|
384 |
# for features |
|
|
385 |
for _, row in variables_settings.iterrows(): |
|
|
386 |
# validate column name |
|
|
387 |
if not self.__readers_writers.exists_mysql_column( |
|
|
388 |
input_schemas[table_i], history_tables[table_i], row["Variable_Name"]): |
|
|
389 |
self.__logger.error(__name__ + " - Column does not exist: " + row["Variable_Name"]) |
|
|
390 |
sys.exit() |