-
Notifications
You must be signed in to change notification settings - Fork 1
/
_core.py
508 lines (405 loc) · 14.2 KB
/
_core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
from collections import OrderedDict
from decimal import Decimal
import hashlib
import multiprocessing
import re
import warnings
import six
import typepy
import dataproperty as dp
from six.moves import zip
from ._constant import PatternMatch
from ._logger import logger
from .error import InvalidDataError
class TableData(object):
"""
Class to represent a table data structure.
:param str table_name: Name of the table.
:param list header_list: Table header names.
:param list record_list: Table data records.
"""
@property
def table_name(self):
"""
:return: Name of the table.
:rtype: str
"""
return self.__table_name
@property
def header_list(self):
"""
:return: Table header names.
:rtype: list
"""
return self.__dp_extractor.header_list
@property
def value_matrix(self):
"""
:return: Table data records.
:rtype: list
"""
if self.__value_matrix:
return self.__value_matrix
self.__value_matrix = [
[value_dp.data for value_dp in value_dp_list]
for value_dp_list in self.__value_dp_matrix
]
return self.__value_matrix
@property
def value_dp_matrix(self):
"""
:return: DataProperty for table data.
:rtype: list
"""
return self.__value_dp_matrix
@property
def to_header_dp_list(self):
return self.__dp_extractor.to_header_dp_list()
@property
def record_list(self):
# alias property of value_matrix. this method will be deleted in the
# future
return self.value_matrix
def __init__(
self, table_name, header_list, record_list, is_strip_quote=False,
quoting_flags=None, max_workers=None):
self.__dp_extractor = dp.DataPropertyExtractor()
if quoting_flags:
self.__dp_extractor.quoting_flags = quoting_flags
self.__dp_extractor.strip_str_header = '"'
if is_strip_quote:
self.__dp_extractor.strip_str_value = '"'
if max_workers:
self.max_workers = max_workers
else:
if six.PY2:
# avoid unit test execution hang up at Python 2 environment
self.max_workers = 1
self.__dp_extractor.max_workers = 1
else:
self.max_workers = multiprocessing.cpu_count()
self.__table_name = table_name
self.__dp_extractor.header_list = header_list
self.__value_matrix = None
self.__value_dp_matrix = self.__dp_extractor.to_dp_matrix(
self.__preprocess_value_matrix(record_list))
def __repr__(self):
element_list = [
"table_name={}".format(self.table_name),
]
try:
element_list.append("header_list=[{}]".format(
", ".join(self.header_list)))
except TypeError:
element_list.append("header_list=None")
element_list.append("rows={}".format(len(self.value_dp_matrix)))
return ", ".join(element_list)
def __eq__(self, other):
return all([
self.table_name == other.table_name,
self.header_list == other.header_list,
all([
all([
lhs == rhs
for lhs, rhs in zip(lhs_list, rhs_list)
])
for lhs_list, rhs_list
in zip(self.value_dp_matrix, other.value_dp_matrix)
]),
])
def __ne__(self, other):
return any([
self.table_name != other.table_name,
self.header_list != other.header_list,
any([
any([
lhs != rhs
for lhs, rhs in zip(lhs_list, rhs_list)
])
for lhs_list, rhs_list
in zip(self.value_dp_matrix, other.value_dp_matrix)
]),
])
def __hash__(self):
body = (
self.table_name +
six.text_type(self.header_list) +
six.text_type(self.value_dp_matrix)
)
return hashlib.sha1(body.encode("utf-8")).hexdigest()
def is_empty_header(self):
"""
:return: |True| if the data :py:attr:`.header_list` is empty.
:rtype: bool
"""
return typepy.is_empty_sequence(self.header_list)
def is_empty_record(self):
"""
:return: |True| if the tabular data is not an empty nested list.
:rtype: bool
"""
try:
return not typepy.is_not_empty_sequence(self.value_dp_matrix[0])
except (TypeError, IndexError):
return True
def is_empty(self):
"""
:return:
|True| if the data :py:attr:`.header_list` or
:py:attr:`.value_matrix` is empty.
:rtype: bool
"""
return any([self.is_empty_header(), self.is_empty_record()])
def as_dict(self):
"""
:return: Table data as a |dict| instance.
:rtype: dict
:Sample Code:
.. code:: python
from tabledata import TableData
TableData(
table_name="sample",
header_list=["a", "b"],
record_list=[[1, 2], [3.3, 4.4]]
).as_dict()
:Output:
.. code:: json
{'sample': [OrderedDict([('a', 1), ('b', 2)]),
OrderedDict([('a', 3.3), ('b', 4.4)])]}
"""
from typepy import Typecode
self.__dp_extractor.float_type = float
dict_body = []
for value_dp_list in self.value_dp_matrix:
if typepy.is_empty_sequence(value_dp_list):
continue
dict_record = [
(header, value_dp.data)
for header, value_dp in zip(self.header_list, value_dp_list)
if value_dp.typecode != Typecode.NONE
]
if typepy.is_empty_sequence(dict_record):
continue
dict_body.append(OrderedDict(dict_record))
return {self.table_name: dict_body}
def asdict(self):
warnings.warn(
"asdict() will be deleted in the future, use as_dict instead.",
DeprecationWarning)
return self.as_dict()
def as_dataframe(self):
"""
:return: Table data as a ``pandas.DataFrame`` instance.
:rtype: pandas.DataFrame
:Sample Code:
.. code-block:: python
from tabledata import TableData
TableData(
table_name="sample",
header_list=["a", "b"],
record_list=[[1, 2], [3.3, 4.4]]
).as_dict()
:Output:
.. code-block:: none
a b
0 1 2
1 3.3 4.4
:Dependency Packages:
- `pandas <http://pandas.pydata.org/>`__
"""
import pandas
dataframe = pandas.DataFrame(self.value_matrix)
if not self.is_empty_header():
dataframe.columns = self.header_list
return dataframe
def filter_column(
self, pattern_list=None, is_invert_match=False,
is_re_match=False, pattern_match=PatternMatch.OR):
logger.debug(
"filter_column: pattern_list={}, is_invert_match={}, "
"is_re_match={}, pattern_match={}".format(
pattern_list, is_invert_match, is_re_match, pattern_match))
if not pattern_list:
return TableData(
table_name=self.table_name, header_list=self.header_list,
record_list=self.value_dp_matrix)
match_header_list = []
match_column_matrix = []
if pattern_match == PatternMatch.OR:
match_method = any
elif pattern_match == PatternMatch.AND:
match_method = all
else:
raise ValueError("unknown matching: {}".format(pattern_match))
for header, column_value_dp_list in zip(
self.header_list, zip(*self.value_dp_matrix)):
is_match_list = []
for pattern in pattern_list:
is_match = self.__is_match(header, pattern, is_re_match)
is_match_list.append(any([
is_match and not is_invert_match,
not is_match and is_invert_match,
]))
if match_method(is_match_list):
match_header_list.append(header)
match_column_matrix.append(column_value_dp_list)
logger.debug(
"filter_column: table={}, match_header_list={}".format(
self.table_name, match_header_list))
return TableData(
table_name=self.table_name, header_list=match_header_list,
record_list=list(zip(*match_column_matrix)))
@staticmethod
def from_dataframe(dataframe, table_name=""):
"""
Initialize TableData instance from a pandas.DataFrame instance.
:param pandas.DataFrame dataframe:
:param str table_name: Table name to create.
"""
return TableData(
table_name=table_name,
header_list=list(dataframe.columns.values),
record_list=dataframe.values.tolist())
@staticmethod
def __is_match(header, pattern, is_re_match):
if is_re_match:
return re.search(pattern, header) is not None
return header == pattern
def __to_record(self, values):
"""
Convert values to a record.
:param values: Value to be converted.
:type values: |dict|/|namedtuple|/|list|/|tuple|
:raises ValueError: If the ``value`` is invalid.
"""
try:
# dictionary to list
return [
dp.data
for dp in self.__dp_extractor.to_dp_list([
values.get(header) for header in self.header_list])
]
except AttributeError:
pass
try:
# namedtuple to list
dict_value = values._asdict()
return [
dp.data
for dp in self.__dp_extractor.to_dp_list([
dict_value.get(header) for header in self.header_list])
]
except AttributeError:
pass
try:
return [
dp.data
for dp in self.__dp_extractor.to_dp_list(values)
]
except TypeError:
raise InvalidDataError(
"record must be a list or tuple: actual={}".format(values))
def __preprocess_value_matrix(self, value_matrix):
return [
_preprocess_value_list(
self.header_list, value_list, record_idx)[1]
for record_idx, value_list in enumerate(value_matrix)
]
def __to_value_matrix(self, value_matrix):
"""
Convert matrix to records
"""
self.__dp_extractor.float_type = Decimal
if typepy.is_empty_sequence(self.header_list):
return value_matrix
if self.max_workers <= 1:
return self.__to_value_matrix_st(value_matrix)
return self.__to_value_matrix_mt(value_matrix)
def __to_value_matrix_st(self, value_matrix):
return [
_to_record_helper(
self.__dp_extractor, self.header_list, value_list,
record_idx)[1]
for record_idx, value_list in enumerate(value_matrix)
]
def __to_value_matrix_mt(self, value_matrix):
from concurrent import futures
record_mapping = {}
try:
with futures.ProcessPoolExecutor(self.max_workers) as executor:
future_list = [
executor.submit(
_to_record_helper, self.__dp_extractor,
self.header_list, value_list, record_idx)
for record_idx, value_list in enumerate(value_matrix)
]
for future in futures.as_completed(future_list):
record_idx, record = future.result()
record_mapping[record_idx] = record
finally:
logger.debug("shutdown ProcessPoolExecutor")
executor.shutdown()
return [
record_mapping[record_idx] for record_idx in sorted(record_mapping)
]
def _preprocess_value_list(header_list, values, record_idx):
if header_list:
try:
# dictionary to list
return (
record_idx,
[values.get(header) for header in header_list])
except (TypeError, AttributeError):
pass
try:
# namedtuple to list
dict_value = values._asdict()
return (
record_idx,
[dict_value.get(header) for header in header_list])
except (TypeError, AttributeError):
pass
if not isinstance(values, (tuple, list)):
raise InvalidDataError(
"record must be a list or tuple: actual={}".format(values))
return (record_idx, values)
def _to_record_helper(extractor, header_list, values, record_idx):
try:
# dictionary to list
return (
record_idx,
[
dp.data
for dp in extractor.to_dp_list([
values.get(header) for header in header_list])
])
except AttributeError:
pass
try:
# namedtuple to list
dict_value = values._asdict()
return (
record_idx,
[
dp.data
for dp in extractor.to_dp_list([
dict_value.get(header) for header in header_list])
])
except AttributeError:
pass
try:
return (
record_idx,
[
dp.data
for dp in extractor.to_dp_list(values)
])
except TypeError:
raise InvalidDataError(
"record must be a list or tuple: actual={}".format(values))