-
Notifications
You must be signed in to change notification settings - Fork 0
/
common_util.py
2572 lines (2144 loc) · 82.1 KB
/
common_util.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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# __
# ____________ ______ _____/ /_
# / ___/ ___/ / / / __ \/ ___/ __ \
# / /__/ / / /_/ / / / / /__/ / / /
# \___/_/ \__,_/_/ /_/\___/_/ /_/
# global project common utilities.
import sys
from os import sep, path, makedirs, walk, listdir, rmdir
from os.path import dirname, basename, realpath, normpath, exists, isfile, getsize, splitext, join as path_join
import socket
import json
import yaml
import re
import math
import numbers
import operator
import getopt
import inspect
import collections.abc
from copy import deepcopy
from collections import Mapping
import subprocess
from multiprocessing.pool import ThreadPool
from contextlib import suppress
from difflib import SequenceMatcher
from collections import defaultdict, MutableMapping, OrderedDict, ChainMap
from itertools import product, chain, tee, islice, zip_longest
from functools import reduce, partial, wraps
import time
from datetime import datetime, date, timedelta
from timeit import default_timer
import logging
import numpy as np
import pandas as pd
from graphviz import Digraph
from pandas.tseries.offsets import CustomBusinessDay, CustomBusinessHour
from pandas.testing import assert_series_equal, assert_frame_equal
from pandas.api.types import is_numeric_dtype
import torch
import dask
from dask import delayed, compute
import humanize
""" ********** SYSTEM SETTINGS ********** """
"""Project Root and Subpackage paths"""
CRUNCH_DIR = dirname(dirname(realpath(sys.argv[0]))) +sep # FIXME
RAW_DIR = CRUNCH_DIR +'raw' +sep
DATA_DIR = CRUNCH_DIR +'data' +sep
MUTATE_DIR = CRUNCH_DIR +'mutate' +sep
RECON_DIR = CRUNCH_DIR +'recon' +sep
MODEL_DIR = CRUNCH_DIR +'model' +sep
REPORT_DIR = CRUNCH_DIR +'report' +sep
logging.critical('script location: {}'.format(str(realpath(sys.argv[0]))))
logging.critical('using project dir: {}'.format(CRUNCH_DIR))
"""Supported Pandas DF IO Formats"""
FMT_EXTS = {
'csv': ('.csv',),
'arrow': ('.arrow',),
'feather': ('.feather',),
'hdf_fixed': ('.h5', '.hdf', '.he5', '.hdf5'),
'hdf_table': ('.h5', '.hdf', '.he5', '.hdf5'),
'parquet': ('.parquet',),
'pickle': ('.pickle',)
}
"""Default Pandas DF IO format"""
DF_DATA_FMT = 'arrow'
"""Dask Global Settings"""
#dask.config.set(scheduler='threads')
#dask.config.set(pool=ThreadPool(32))
""" ********** SYSTEM UTILS ********** """
get_pardir_from_path = lambda path: basename(normpath(path))
add_sep_if_none = lambda path: path if (path[-1] == sep) else path+sep
""" ********** GENERAL UTILS ********** """
"""Constants"""
BYTES_PER_MEGABYTE = 10**6
EMPTY_STR = ''
JSON_SFX = '.json'
JSON_SFX_LEN = len(JSON_SFX)
YAML_SFX = '.yaml'
DT_DAILY_FREQ = 'D'
DT_HOURLY_FREQ = 'H'
DT_CAL_DAILY_FREQ = DT_DAILY_FREQ
DT_BIZ_DAILY_FREQ = 'B'
DT_BIZ_HOURLY_FREQ = 'BH'
DT_FMT_YMD = '%Y-%m-%d'
DT_FMT_YMD_HM = '%Y-%m-%d %H:%M'
DT_FMT_YMD_HMS = '%Y-%m-%d %H:%M:%S'
DT_FMT_YMD_HMSF = '%Y-%m-%d %H:%M:%S:%f'
"""Type"""
def is_type(obj, *types):
return isinstance(obj, types)
def is_valid(obj):
return obj is not None
def isnt(obj):
return is_type(obj, type(None))
def is_real_num(obj):
return is_type(obj, numbers.Real)
def is_seq(obj):
return is_type(obj, collections.abc.Sequence)
def is_df(obj):
return is_type(obj, pd.DataFrame)
def is_ser(obj):
return is_type(obj, pd.Series)
def get_class_name(obj):
"""
Returns the class name of an object.
"""
return obj.__class__.__name__
"""Attributes"""
def has_all_attr(obj, *attrs):
"""
Return True if obj has all attributes.
"""
attr_list = dir(obj)
return all([attr in attr_list for attr in attrs])
def assert_has_all_attr(obj, *attrs):
"""
Pass assertion if obj has all attributes.
"""
assert has_all_attr(obj, *attrs), "object must have all of the following attributes: {}".format(str(list(attrs)))
"""Equality"""
def all_eq(first, *others):
for oth in others:
if (oth != first):
return False
return True
"""String"""
"""
Return string with escaped quotes enclosed around it.
Useful for programs, commands, and engines with text interfaces that use
enclosing quotes to recognize strings (like numexpr and sql).
"""
quote_it = lambda string: '\'' +string +'\'' # XXX - Deprecated in favor of 'wrap_quotes'
wrap_quotes = lambda string: '\'' +string +'\''
wrap_parens = lambda string: '(' +string +')'
strip_parens_content = lambda string: re.sub(r'\([^)]*\)', '', string) if (all([c in string for c in ('(', ')')])) else string
def str_to_list(string, delimiter=',', cast_to=str):
return list(map(cast_to, map(str.strip, string.split(delimiter))))
def find_numbers(string, ints=True):
"""
Return numbers found in a string
Written by Marc Maxmeister
Source: https://stackoverflow.com/questions/4289331/how-to-extract-numbers-from-a-string-in-python
"""
numexp = re.compile(r'[-]?\d[\d,]*[\.]?[\d{2}]*') #optional - in front
numbers = numexp.findall(string)
numbers = [x.replace(',','') for x in numbers]
if (ints):
return [int(x.replace(',','').split('.')[0]) for x in numbers]
else:
return numbers
def common_prefix(*strings):
"""
Return the largest common prefix among the sequence passed strings.
"""
pfx = []
if (len(strings)==1):
return strings[0]
while (all(len(pfx)<len(s) for s in strings)):
idx = len(pfx)
char = strings[0][idx]
if (all(s[idx]==char for s in strings[1:])):
pfx.append(char)
else:
break
return ''.join(pfx)
"""Datetime"""
dt_now = lambda: datetime.now()
str_now = lambda fmt=DT_FMT_YMD_HMS: dt_now().strftime(fmt)
dt_delta = lambda start, end: datetime.combine(date.min, end) - datetime.combine(date.min, start)
now_tz = lambda fmt='%z': dt_now().astimezone().strftime(fmt)
str_now_dtz = lambda fmt=DT_FMT_YMD_HMS: str_now(fmt=fmt) +' ' +now_tz()
def dti_tz_convert(dti, tz='US/Eastern'):
"""
Return pd.DatetimeIndex converted to destination timezone.
"""
return dti.tz_convert(tz)
def timestamp_on(timestamp):
"""
Return a constructor for a timestamp at a particular timestamped date.
"""
return partial(pd.Timestamp,
freq=timestamp.freq if (hasattr(timestamp, 'freq')) else None,
tz=timestamp.tz if (hasattr(timestamp, 'tz')) else None,
year=timestamp.year,
month=timestamp.month,
day=timestamp.day)
def pd_before_cutoff(pd_obj, cutoff_time=timestamp_on(dt_now())(hour=9, tz='US/Eastern')):
"""
Pandas filter helper function to remove days that don't start at or before the cutoff time.
Args:
pd_obj (pd.Series|pd.DataFrame): dti-indexed intraday series/dataframe
cutoff_time (pd.Timestamp): pandas timestamp for the cutoff time, the date component is not used; default is 9AM US/Eastern
Returns:
True if the pandas object index starts at or before the cutoff time, else False
"""
unique_dates = list(set(pd_obj.index.date))
assert(len(unique_dates)==1)
date = unique_dates[0]
local_times = dti_tz_convert(pd_obj.dropna(how='all').index, tz=cutoff_time.tz)
valid_local_times = local_times[local_times.date==date]
if (not all(pd.isnull(valid_local_times))):
min_time = valid_local_times.min()
cutoff_time = timestamp_on(min_time)(hour=cutoff_time.hour, minute=cutoff_time.minute, second=cutoff_time.second)
return min_time <= cutoff_time
return False
"""List"""
def list_wrap(obj):
return obj if (is_type(obj, list)) else [obj]
def remove_dups_list(lst):
return list(OrderedDict.fromkeys(lst))
def flatten2D(list2D):
return list(chain(*list2D))
def list_all_eq(first, *others):
for oth in others:
if (any(oth != first)):
return False
return True
def all_equal(lst): # Legacy
return all_eq(lst[0], *lst[1:])
first_element = lambda lst: lst[0]
def get0(obj):
"""
If an object is a list or tuple of length 1 return the singleton element, otherwise return the object.
"""
if (is_type(obj, list, tuple) and len(obj)==1):
return obj[0]
else:
return obj
def getcon(lst, string):
"""
Return sublist of items containing string, if only one match return it as a singleton.
"""
return get0(list(filter(lambda el: string in el, lst)))
def list_compare(master, other):
"""
Return describing relationship master and other.
Args:
master (list):
other (list):
Returns:
String describing relationship of lists
"""
master_set = set(master)
other_set = set(other)
if (master_set == other_set):
return 'equal'
elif (master_set > other_set):
return 'proper_superset'
elif (master_set < other_set):
return 'proper_subset'
elif (master_set & other_set == other_set):
return 'has_all'
elif (master_set & other_set < other_set):
return 'has_some'
elif (master_set.isdisjoint(other_set)):
return 'disjoint'
def get_range_cuts(start, end, ratios_list):
"""
Return a list of segment indices for cuts based on ratios over the range provided by the passed [start, end).
If the ratios result in fractional boundaries, they will be rounded to the closest integer.
The range cuts will traverse the whole [start, end) range provided.
"""
cuts = [start]
size = end - start
seg_start = start
for seg_ratio in ratios_list[:-1]:
seg_end = seg_start + int(round(seg_ratio*size))
cuts.append(seg_end)
seg_start = seg_end
cuts.append(end)
return cuts
def pairwise(iterable):
"""
Pairwise iterator (ie, size 2 sliding window).
Taken from itertools recipes (official docs): https://docs.python.org/3/library/itertools.html
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
"""
a, b = tee(iterable)
next(b, None)
return zip(a, b)
def best_match(original_key, candidates, alt_maps=None):
"""
Return string from candidates that is the best match to the original key
"""
if (original_key in candidates): # exact match
return original_key
elif(len(candidates) == 1): # unchanging
return candidates[0]
elif (alt_maps is not None): # mapped match
alt_keys = [original_key.replace(old, new) for old, new in alt_maps.items() if (old in original_key)]
for alt_key in alt_keys:
if (alt_key in candidates):
return alt_key
else: # inexact longest subseq match
match_len = [SequenceMatcher(None, original_key, can).find_longest_match(0, len(original_key), 0, len(can)).size for can in candidates]
match_key = candidates[match_len.index(max(match_len))]
logging.warn('using inexact match: ' +str(wrap_quotes(original_key)) +' mapped to ' +str(wrap_quotes(match_key)))
return match_key
"""Dict"""
class NestedDefaultDict(MutableMapping):
"""
Nested Default Dictionary class.
Defines a nested dictionary where arbitrary key lists are accomodated by instantiating default_dicts if that key list does not exist.
Implements a dict-like interface.
Will not hold a NestedDefaultDict as a value, if this is attempted the other NestedDefaultDict will be grafted to this one.
Empty NestedDefaultDict objects cannot be grafted on to this one.
"""
KEY_END = '.'
def __init__(self, keychains=None, tree=None, *args, **kwargs):
"""
NDD constructor.
Args:
keychains (list): paths to all leaves in tree
tree (defaultdict): value tree, recursive defaultdict of defaultdicts
"""
recursive_dict = lambda: defaultdict(recursive_dict)
self.keychains = [] if (keychains is None) else keychains
self.tree = recursive_dict() if (keychains is None) else tree
def empty(self):
"""
Return whether or not NDD is empty.
"""
return len(self.keychains) == 0
def keys(self):
"""
Yield from sorted iterator of keychains.
"""
yield from sorted(self.keychains)
def values(self):
"""
Yield from values in order of keychains.
"""
for key in self.keys():
yield self.__getitem__(key)
def items(self):
"""
Yield from key value pairs in order of keychains.
"""
for key in self.keys():
yield key, self.__getitem__(key)
def childkeys(self, parent):
"""
Yield all child keychains of a list of parent keys.
This will yield the original key if it exists in the set of keychains.
"""
yield from filter(lambda k: k[:len(parent)]==parent, self.keys())
def __setitem__(self, key, value):
"""
Set an item in the object.
If the value to set is a NestedDefaultDict, then it will be grafted on at the specified location,
overwriting the old branch.
Args:
key (list): list of keys
value (any): value to set
Returns:
None
Raises:
ValueError if the proposed key contains a reserved string
"""
if (NestedDefaultDict.KEY_END in key):
raise KeyError("Cannot use \'{}\' in a valid keychain, this string is reserved".format(NestedDefaultDict.KEY_END))
if (isinstance(value, NestedDefaultDict) or isinstance(value, defaultdict)):
for childkey in self.childkeys(key): # Remove old branch
self.__delitem__(childkey)
reduce(operator.getitem, key[:-1], self.tree)[key[-1]] = value.tree # Graft other NDD
for k, v in value.items():
self.__setitem__(key+k, v)
else:
reduce(operator.getitem, key, self.tree)[NestedDefaultDict.KEY_END] = value
if (not key in self.keychains):
self.keychains.append(key)
def __getitem__(self, key):
"""
Get an item.
Args:
key (list): list of keys
Returns:
item
Raises:
ValueError if the key doesn't exist
"""
if (key not in self.keychains):
raise KeyError("Attempted key doesn\'t exist")
return reduce(operator.getitem, key, self.tree)[NestedDefaultDict.KEY_END]
def __delitem__(self, key):
"""
Delete an item.
Only deletes that exact key and item: if ['a', 'b', 'c'] and ['a', 'b', 'c', 'd'] exists and the key ['a', 'b', 'c'] is deleted,
then ['a', 'b', 'c', 'd'] will continue to exist.
Args:
key (list): list of keys
Returns:
None
Raises:
ValueError if the key doesn't exist
"""
if (key not in self.keychains):
raise KeyError("Attempted key doesn\'t exist")
del reduce(operator.getitem, key, self.tree)[NestedDefaultDict.KEY_END]
self.keychains.remove(key)
def __add__(self, other):
"""
TODO - finish
Add two disjoint NDDs together and return the result as a new NDD.
Args:
other (NestedDefaultDict): other NDD to add to self
Returns:
new NDD with elements combined
Raises:
ValueError if the other item is not a NDD
ValueError if the two NDDs have any common keychains
"""
if (not isinstance(other, NestedDefaultDict)):
raise ValueError("Both objects must be NestedDefaultDicts to add them")
elif (any(kc in self.keychains for kc in other.keychains)):
raise KeyError("Cannot add NestedDefaultDicts with common keychains")
pass
# out = deepcopy(self)
# for k, v in other.items():
# other[k] = v
# return out
# return NestedDefaultDict(keychains=self.keychains+other.keychains, tree=self.tree.update(other.tree))
def __iter__(self):
"""
Return iterator over the keys (similar to standard dictionary).
"""
return self.keys()
def __len__(self):
"""
Return number of valid keychains.
"""
return len(self.keychains)
def __str__(self):
"""
Returns string representation
"""
return str(json.dumps(self.tree, indent=4, sort_keys=True))
def __repr__(self):
"""
Echoes class, id, & reproducible representation in the REPL
XXX - probably wrong
"""
return "{}, {}".format(self.keychains, self.tree)
def dict_flatten(d, parent_key='', sep='_'):
"""
Flatten a dictionary.
Source: https://stackoverflow.com/questions/6027558/flatten-nested-dictionaries-compressing-keys
"""
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if (is_type(v, MutableMapping)):
items.extend(dict_flatten(v, new_key, sep=sep).items())
else:
items.append((new_key, v))
return dict(items)
def deep_update(source, overrides):
"""
Update a nested dictionary or similar mapping.
Modify ``source`` in place.
https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth
"""
for key, value in overrides.items():
if isinstance(value, collections.Mapping) and value:
returned = deep_update(source.get(key, {}), value)
source[key] = returned
else:
source[key] = overrides[key]
return source
def dict_combine(a, b):
"""
Combine / merge two dicts into one.
"""
return {**a, **b}
def nice_print_dict(dictionary):
print(json.dumps(dictionary, indent=4, sort_keys=True))
def remove_keys(dictionary, list_keys):
for key in list_keys:
with suppress(KeyError):
del dictionary[key]
return dictionary
def recursive_dict():
"""
XXX - Deprecated in favor of NestedDefaultDict
Creates a recursive nestable defaultdict.
In other words, it will automatically create intermediate keys if
they don't exist!
"""
return defaultdict(recursive_dict)
def list_get_dict(dictionary, key_list):
return reduce(operator.getitem, key_list, dictionary)
def list_set_dict(dictionary, key_list, value):
list_get_dict(dictionary, key_list[:-1])[key_list[-1]] = value
def dict_path(dictionary, path=None, stop_cond=lambda v: not isinstance(v, dict)):
"""
Convenience function to give explicit paths from root keys until stop_cond is met.
By default stop_cond is set such that the path to all leaves (non-dict values) are found.
"""
if (path is None):
path = []
for key, val in dictionary.items():
newpath = path + [key]
if (stop_cond(val)):
yield newpath, val
else:
for unfinished in dict_path(val, newpath, stop_cond=stop_cond):
yield unfinished
def get_grid_variants(grid):
"""
Return possible combos of key-value maps of a structure of arrays.
Args:
grid (dict): an SOA-like dictionary
Returns:
list of dictionaries representing all combinations of key-values
Example:
{
a: [1, 2, 3],
b: [4, 5, 6]
}
maps to:
[
{a: 1, b: 4}, {a: 1, b: 5}, {a: 1, b: 6},
{a: 2, b: 4}, {a: 2, b: 5}, {a: 2, b: 6},
{a: 3, b: 4}, {a: 3, b: 5}, {a: 3, b: 6}
]
"""
names, combos = list(grid.keys()), list(product(*grid.values()))
variants = [{names[idx]: value for idx, value in enumerate(combo)} for combo in combos]
return variants
def get_list_variants(grid_groups):
"""
Return possible combos of key-value maps of a list of multiple structure of arrays.
Args:
grid_groups (list): a list of SOA-like dictionaries
Returns:
A list of tuples of all dictionary combinations
Example:
[
{
a: [1, 2],
b: [3, 4]
},
{
a: [1, 2],
c: [5, 6]
}
]
maps to:
[
({'a': 1, 'b': 3}, {'a': 1, 'c': 5}), ({'a': 1, 'b': 3}, {'a': 1, 'c': 6}), ({'a': 1, 'b': 3}, {'a': 2, 'c': 5}), ({'a': 1, 'b': 3}, {'a': 2, 'c': 6}),
({'a': 1, 'b': 4}, {'a': 1, 'c': 5}), ({'a': 1, 'b': 4}, {'a': 1, 'c': 6}), ({'a': 1, 'b': 4}, {'a': 2, 'c': 5}), ({'a': 1, 'b': 4}, {'a': 2, 'c': 6}),
({'a': 2, 'b': 3}, {'a': 1, 'c': 5}), ({'a': 2, 'b': 3}, {'a': 1, 'c': 6}), ({'a': 2, 'b': 3}, {'a': 2, 'c': 5}), ({'a': 2, 'b': 3}, {'a': 2, 'c': 6}),
({'a': 2, 'b': 4}, {'a': 1, 'c': 5}), ({'a': 2, 'b': 4}, {'a': 1, 'c': 6}), ({'a': 2, 'b': 4}, {'a': 2, 'c': 5}), ({'a': 2, 'b': 4}, {'a': 2, 'c': 6})
]
"""
grid_variants = [get_grid_variants(grid) for grid in grid_groups]
variants = [combo for combo in product(*grid_variants)]
return variants
def get_variants(mappings, fmt='grid'):
"""
Return all possible combinations of key-value maps as a list of dictionaries.
There are two modes, named after the input format of the data: grid and list.
Args:
mappings (dict|list): mapping to get combos of
fmt ('grid'|'list'): mode
Returns:
List of variants
"""
return {
'grid': partial(get_grid_variants),
'list': partial(get_list_variants)
}.get(fmt)(mappings)
"""Function"""
def get_fn_params(fn, params):
return {k: v for k, v in params.items() if (k in inspect.getfullargspec(fn).args)}
def compose(*fns):
"""
Perform function composition of passed functions, performed on input in the order they are passed.
"""
def composed(*args, **kwargs):
val = fns[0](*args, **kwargs)
for fn in fns[1:]:
val = fn(val)
return val
return composed
def dcompose(*fns):
"""
Perform delayed function composition of passed functions, performed on input in the order they are passed.
"""
def dcomposed(*args, **kwargs):
val = delayed(fns[0])(*args, **kwargs)
for fn in fns[1:]:
val = delayed(fn)(val)
return val
return dcomposed
def fn_default_args(fn):
"""
Return the default argument values of a function.
Source: https://stackoverflow.com/questions/12627118/get-a-function-arguments-default-value
Args:
fn (function): function to get default arguments of
Returns:
dict of default arguments and values
"""
signature = inspect.signature(fn)
return {
k: v.default for k, v in signature.parameters.items()
if (v.default is not inspect.Parameter.empty)
}
"""Iterator"""
def group_iter(iterable, n=2, fill_value=None):
"""
Iterates over fixed length, non-overlapping windows
"""
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
yield from zip_longest(*args, fillvalue=fill_value)
def window_iter(iterable, n=2):
"""
Returns a sliding window (of width n) over data from the iterable
s -> (s[0],s[1],...s[n-1]), (s[1],s[2],...,s[n]), ...
"""
it = iter(iterable)
result = tuple(islice(it, n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + (elem,)
yield result
def trunc_step_window_iter(iterable, n=2, step=1):
"""
Returns a truncated sliding window over data from the iterable
s -> (s[0],s[1],...s[n-1]), (s[step],s[step+1],...,s[step+n-1]), ...
"""
n_steps = ((len(iterable)-n)//step)+1
for i in range(n_steps):
start = i*step
yield iterable[start:start+n]
def col_iter(two_d_list):
"""
Iterates over columns of a two dimensional list
"""
yield from group_iter(chain.from_iterable(zip(*two_d_list)), n=len(two_d_list))
"""String Mappers"""
"""
The following are functions that return string mapping functions based on rule and handling parameters.
String mapping functions map a sequence of strings to a single string. Useful for naming new data columns.
"""
def concat_map(delimiter='_', **kwargs):
return lambda *strings: delimiter.join(strings)
first_letter_concat = lambda lst: "".join((string[0] for string in lst))
def substr_ad_map(check_fn=all_equal, accord_fn=first_element, discord_fn=first_letter_concat, delim='_', **kwargs):
"""
Map a sequence of strings to one string by handling accordances or discordances in substrings.
Assumes all strings in the sequence have an equal number of delimited substrings.
"""
def mapper(*strings):
output = []
str_row_vectors = [string.split(delim) for string in strings]
for col in col_iter(str_row_vectors):
substr = accord_fn(col) if (check_fn(col)) else discord_fn(col)
output.append(substr)
return delim.join(output)
return mapper
def fl_map(strs, delim='_'):
"""
Maps a list of strings to a single string based on common prefix of strings suffixed by first letters of each unique substring.
Args:
strs (list): list of strings to append suffixes to
delim (str): delimiter between original string and suffix
Returns:
common_prefix(strings) + delimiter + ''.join([first letter of each string])
"""
pfx = common_prefix(*strs)
pfx = pfx if (pfx[-1]==delim) else pfx+delim
fls = [str(s[len(pfx):][0] if (len(s)>len(pfx)) else '') for s in strs]
return pfx+''.join(fls)
def window_map(strs, mapper_fn=fl_map, n=2, delim='_'):
"""
Maps a list of strings to another list of strings by through a slided window function.
Args:
strs (list): list of strings to append suffixes to
mapper_fn (function): function slided across list that maps window of strings to a single string
n (int): sliding window size
delim (str): delimiter between original string and suffix
Returns:
list of strings
"""
return [mapper_fn(win, delim=delim) for win in window_iter(strs, n=n)]
def suffix_map(strs, suffixes, modify_unique=False, delim='_'):
"""
Append list of suffixes to list of strings and return result.
Args:
strs (list): list of strings to append suffixes to
suffixes (list): list of strings, if it is smaller than strs it will wrap around
modify_unique (bool): if True, append suffixes even if strs is already a list of unambiguous strings
delim (str): delimiter between original string and suffix
Returns:
list of strings
"""
if (modify_unique or len(set(strs))<len(strs)):
res = [delim.join([s, suffixes[i%len(suffixes)]]) for i, s in enumerate(strs)]
else:
res = strs
return res
"""Math"""
def zdiv(top, bottom, zdiv_ret=0):
return top/bottom if (bottom != 0) else zdiv_ret
def apply_nz_nn(fn):
"""
Return modified function where fn is only applied if the value is non zero and non null.
"""
def func(val):
if (val is None or val == 0):
return val
else:
return fn(val)
return func
one_minus = lambda val: 1 - val
odd_only = lambda val: val if (val % 2 in (1, -1)) else val-1
identity_fn = lambda val, *args, **kwargs: val
null_fn = lambda *args, **kwargs: None
""" ********** FS AND GENERAL IO UTILS ********** """
get_script_dir = lambda: dirname(realpath(sys.argv[0])) +sep
get_parent_dir = lambda: dirname(dirname(realpath(sys.argv[0]))) +sep
makedir_if_not_exists = lambda dir_path: makedirs(dir_path) if (not exists(dir_path)) else None
def load_json(fname, dir_path=None):
fpath = str(add_sep_if_none(dir_path) + fname) if dir_path else fname
if (not fname.endswith(JSON_SFX)):
fpath += JSON_SFX
if (isfile(fpath)):
with open(fpath) as json_data:
try:
return json.load(json_data)
except Exception as e:
logging.error(f'error in file {fname}: {e}')
raise e
else:
raise FileNotFoundError(f'{basename(fpath)} must be in: {dirname(fpath)}')
def rectify_json(json_dict):
"""
Convert types in dictionary to json serializable types
"""
for k, v in filter(lambda i: is_type(i[1], torch.Tensor, np.ndarray), \
json_dict.items()):
json_dict[k] = v.tolist()
return json_dict
def dump_json(json_dict, fname, dir_path=None, ind="\t", seps=None, **kwargs):
fpath = str(add_sep_if_none(dir_path) + fname) if dir_path else fname
if (not fname.endswith(JSON_SFX)):
fpath += JSON_SFX
if (isfile(fpath)):
logging.debug(f'json file exists at {fpath}, syncing...')
else:
logging.debug(f'json file does not exist at {fpath}, writing...')
with open(fpath, 'w', **kwargs) as json_fp:
try:
return json.dump(json_dict, json_fp, indent=ind, separators=seps, **kwargs)
except Exception as e:
logging.error(f'error in file {fname}: {e}')
raise e
def dump_yaml(yaml_dict, fname, dir_path=None, **kwargs):
fpath = str(add_sep_if_none(dir_path) + fname) if dir_path else fname
if (not fname.endswith(YAML_SFX)):
fpath += YAML_SFX
if (isfile(fpath)):
logging.debug(f'yaml file exists at {fpath}, syncing...')
else:
logging.debug(f'yaml file does not exist at {fpath}, writing...')
with open(fpath, 'w', **kwargs) as yaml_fp:
try:
return yaml.dump(yaml_dict, yaml_fp, **kwargs)
except Exception as e:
logging.error(f'error in file {fname}: {e}')
raise e
def get_cmd_args(argv, arg_list, script_name='', script_pkg='', set_logging=True):
"""
Parse commandline arguments from argv and return them as a dict.
Args:
argv (sys.argv): system argument input vector
arg_list (list): list of non-static commandline arguments,
end with '=' for non-flag arguments
no options can start with 'h' or 'l', these are reserved
script_name (str): name of calling script for use in the help dialog
set_logging (bool): whether or not to include a logging level commandline argument and initialize logging
Returns:
Dict of commandline argument to value mappings, a value maps to None if arg was not set or flag argument was not raised
"""
static_args = ['help', 'loglevel='] if (set_logging) else ['help']
arg_list = static_args + arg_list
arg_list_short = [str(arg_name[0] + ':' if arg_name[-1]=='=' else arg_name[0]) for arg_name in arg_list]
arg_str = ''.join(arg_list_short)
res = {arg_name: None for arg_name in arg_list}
arg_list_short_no_sym = [arg_short[0] for arg_short in arg_list_short]
assert(len({}.fromkeys(arg_list_short_no_sym)) == len(arg_list_short_no_sym)) # assert first letters of arg names are unique
help_arg_strs = ['-{s} {p}, --{l}{p}'.format(s=arg_list_short_no_sym[i], l=arg_list[i], \
p='<{}> '.format(arg_list[i][:-1].upper()) if (arg_list[i][-1]=='=') else '') for i in range(len(arg_list))]
help_fn = lambda: print('Usage: python3 -m {}{} [OPTION]...\nOptions:\n\t{}'.format(script_pkg+'.', splitext(script_name)[0], '\n\t'.join(help_arg_strs)))
try:
opts, args = getopt.getopt(argv, str('h' +arg_str), list(['help']+arg_list))
except getopt.GetoptError:
help_fn()
sys.exit(2)
for opt, arg in opts:
if opt in ('-h', '--help'):
help_fn()
sys.exit()
else:
for idx, arg_name in enumerate(arg_list):
arg_char = arg_list_short[idx][0]
if (arg_name[-1] == '='):
if opt in (str('-'+arg_char), str('--'+arg_name[:-1])):
res[arg_name] = arg
else:
if opt in (str('-'+arg_char), str('--'+arg_name)):
res[arg_name] = True
if (set_logging):
set_loglevel(res['loglevel='])
return res
def remove_empty_dirs(root_dir_path):
for path, subdirs, files in walk(root_dir_path, topdown=False):
for subdir in subdirs:
dir_path = path_join(path, subdir)
if not listdir(dir_path): # An empty list is False
rmdir(path_join(path, subdir))
def get_free_port(host="localhost"):
"""
Get a free port on the machine.
From the MongoBox project: https://github.com/theorm/mongobox
"""
temp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
temp_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
temp_sock.bind((host, 0))
port = temp_sock.getsockname()[1]
temp_sock.close()
del temp_sock
return port
""" ********** NUMPY GENERAL UTILS ********** """
def np_is_ndim(arr, dim=1):