forked from nortikin/sverchok
-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_structure.py
executable file
·1503 lines (1250 loc) · 48.1 KB
/
data_structure.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
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
from contextlib import contextmanager
from collections import defaultdict
from functools import wraps
from math import radians, ceil
import itertools
import copy
from itertools import zip_longest, chain, cycle, islice
import bpy
from mathutils import Vector, Matrix
from numpy import (
array as np_array,
newaxis as np_newaxis,
ndarray,
ones as np_ones,
arange as np_arange,
repeat as np_repeat,
concatenate as np_concatenate,
tile as np_tile,
float64,
int32, int64)
from sverchok.utils.logging import debug
import numpy as np
DEBUG_MODE = False
RELOAD_EVENT = False
# this is set correctly later.
SVERCHOK_NAME = "sverchok"
cache_viewer_baker = {}
sentinel = object()
#####################################################
################### cache magic #####################
#####################################################
#handle for object in node and neuro node
temp_handle = {}
def handle_delete(handle):
if handle in temp_handle:
del temp_handle[handle]
def handle_read(handle):
if not (handle in temp_handle):
return (False, [])
return (True, temp_handle[handle]['prop'])
def handle_write(handle, prop):
handle_delete(handle)
temp_handle[handle] = {"prop" : prop}
def handle_check(handle, prop):
if handle in handle_check and \
prop == handle_check[handle]['prop']:
return True
return False
#####################################################
################ list matching magic ################
#####################################################
def repeat_last(lst):
"""
creates an infinite iterator the first each element in lst
and then keep repeating the last element,
use with terminating input
"""
last = [lst[-1]] if len(lst) else [] # len(lst) in case of numpy arrays
yield from chain(lst, cycle(last))
def fixed_iter(data, iter_number, fill_value=0):
"""
Creates iterator for given data which will be yielded iter_number times
If data is shorter then iter_number last element will be cycled
If data is empty [fill_value] list will be used instead
"""
last_index = -1
for i, item in zip(range(iter_number), data):
yield item
last_index = i
fill_value = item
if last_index + 1 < iter_number:
for i, item in zip(range(iter_number - (last_index + 1)), cycle([fill_value])):
yield item
def flat_iter(data):
"""[1, [2, 3, [4]], 5] -> 1, 2, 3, 4, 5 """
if isinstance(data, str):
yield data
return
try:
for v in data:
yield from flat_iter(v)
except TypeError:
yield data
def match_long_repeat(lsts):
"""return matched list, using the last value to fill lists as needed
longest list matching [[1,2,3,4,5], [10,11]] -> [[1,2,3,4,5], [10,11,11,11,11]]
lists passed into this function are not modified, it produces non-deep copies and extends those.
"""
max_l = 0
tmp = []
for l in lsts:
if not hasattr(l, '__len__'):
raise TypeError(f"Cannot perform data matching: input of type {type(l)} is not a list or tuple, but an atomic object")
max_l = max(max_l, len(l))
for l in lsts:
if len(l) == max_l:
tmp.append(l)
else:
tmp.append(repeat_last(l))
return list(map(list, zip(*zip(*tmp))))
def zip_long_repeat(*lists):
objects = match_long_repeat(lists)
return zip(*objects)
def match_long_cycle(lsts):
"""return matched list, cycling the shorter lists
longest list matching, cycle [[1,2,3,4,5] ,[10,11]] -> [[1,2,3,4,5] ,[10,11,10,11,10]]
"""
max_l = 0
tmp = []
for l in lsts:
max_l = max(max_l, len(l))
for l in lsts:
if len(l) == max_l:
tmp.append(l)
else:
tmp.append(itertools.cycle(l))
return list(map(list, zip(*zip(*tmp))))
# when you intent to use length of first list to control WHILE loop duration
# and you do not want to change the length of the first list, but you want the second list
# length to by not less than the length of the first
def second_as_first_cycle(F, S):
if len(F) > len(S):
return list(map(list, zip(*zip(*[F, itertools.cycle(S)]))))[1]
else:
return S
def match_cross(lsts):
""" return cross matched lists
[[1,2], [5,6,7]] -> [[1,1,1,2,2,2], [5,6,7,5,6,7]]
"""
return list(map(list, zip(*itertools.product(*lsts))))
def match_cross2(lsts):
""" return cross matched lists
[[1,2], [5,6,7]] ->[[1, 2, 1, 2, 1, 2], [5, 5, 6, 6, 7, 7]]
"""
return list(reversed(list(map(list, zip(*itertools.product(*reversed(lsts)))))))
# Shortest list decides output length [[1,2,3,4,5], [10,11]] -> [[1,2], [10, 11]]
def match_short(lsts):
"""return lists of equal length using the Shortest list to decides length
Shortest list decides output length [[1,2,3,4,5], [10,11]] -> [[1,2], [10, 11]]
"""
return list(map(list, zip(*zip(*lsts))))
def fullList(l, count):
"""extends list l so len is at least count if needed with the
last element of l"""
n = len(l)
if n == count:
return
d = count - n
if d > 0:
l.extend([l[-1] for a in range(d)])
return
def fullList_np(l, count):
"""extends list l so len is at least count if needed with the
last element of l"""
n = len(l)
if n == count:
return
d = count - n
if d > 0:
try:
l.extend([l[-1] for a in range(d)])
except:
l = numpy_full_list(l, n)
else:
l = l[:count]
def fullList_deep_copy(l, count):
"""the same that full list function but
it have correct work with objects such as lists."""
d = count - len(l)
if d > 0:
l.extend([copy.deepcopy(l[-1]) for _ in range(d)])
return
def cycle_for_length(lst, count):
result = []
n = len(lst)
for i in range(count):
result.append(lst[i % n])
return result
def repeat_last_for_length(lst, count, deepcopy=False):
"""
Repeat last item of the list enough times
for result's length to be equal to `count`.
repeat_last_for_length(None, n) = None
repeat_last_for_length([], n) = []
repeat_last_for_length([1,2], 4) = [1, 2, 2, 2]
"""
if not lst:
return lst
if len(lst) >= count:
return lst[:count]
n = len(lst)
x = lst[-1]
result = lst[:]
if deepcopy:
for i in range(count - n):
result.append(copy.deepcopy(x))
else:
for i in range(count - n):
result.append(x)
return result
def cycle_for_length(lst, count):
return list(islice(cycle(lst), count))
def sv_zip(*iterables):
"""zip('ABCD', 'xy') --> Ax By
like standard zip but list instead of tuple
"""
iterators = [iter(it) for it in iterables]
sentinel = object() # use internal sentinel
while iterators:
result = []
for it in iterators:
elem = next(it, sentinel)
if elem is sentinel:
return
result.append(elem)
yield result
list_match_modes = [
("SHORT", "Short", "Match shortest List", 1),
("CYCLE", "Cycle", "Match longest List by cycling", 2),
("REPEAT", "Repeat Last", "Match longest List by repeating last item", 3),
("XREF", "X-Ref", "Cross reference (fast cycle of long)", 4),
("XREF2", "X-Ref 2", "Cross reference (fast cycle of short)", 5),
]
list_match_func = {
"SHORT": match_short,
"CYCLE": match_long_cycle,
"REPEAT": match_long_repeat,
"XREF": match_cross,
"XREF2": match_cross2
}
numpy_list_match_modes = list_match_modes[:3]
# numpy_list_match_modes = [
# ("SHORT", "Match Short", "Match shortest List", 1),
# ("CYCLE", "Cycle", "Match longest List by cycling", 2),
# ("REPEAT", "Repeat Last", "Match longest List by repeating last item", 3),
# ]
def numpy_full_list(array, desired_length):
'''retuns array with desired length by repeating last item'''
if not isinstance(array, ndarray):
array = np_array(array)
length_diff = desired_length - array.shape[0]
if length_diff > 0:
new_part = np_repeat(array[np_newaxis, -1], length_diff, axis=0)
return np_concatenate((array, new_part))[:desired_length]
return array[:desired_length]
def numpy_full_list_cycle(array, desired_length):
'''retuns array with desired length by cycling'''
length_diff = desired_length - array.shape[0]
if length_diff > 0:
if length_diff < array.shape[0]:
return np_concatenate((array, array[:length_diff]))
new_part = np_repeat(array, ceil(length_diff / array.shape[0]), axis=0)
if len(array.shape) > 1:
shape = (ceil(length_diff / array.shape[0]), 1)
else:
shape = ceil(length_diff / array.shape[0])
new_part = np_tile(array, shape)
return np_concatenate((array, new_part[:length_diff]))
return array[:desired_length]
numpy_full_list_func = {
"SHORT": lambda x,l: x[:l],
"CYCLE": numpy_full_list_cycle,
"REPEAT": numpy_full_list,
}
def numpy_match_long_repeat(list_of_arrays):
'''match numpy arrays length by repeating last one'''
out = []
maxl = 0
for array in list_of_arrays:
maxl = max(maxl, array.shape[0])
for array in list_of_arrays:
length_diff = maxl - array.shape[0]
if length_diff > 0:
new_part = np_repeat(array[np_newaxis, -1], length_diff, axis=0)
array = np_concatenate((array, new_part))
out.append(array)
return out
def numpy_match_long_cycle(list_of_arrays):
'''match numpy arrays length by cycling over the array'''
out = []
maxl = 0
for array in list_of_arrays:
maxl = max(maxl, array.shape[0])
for array in list_of_arrays:
length_diff = maxl - array.shape[0]
if length_diff > 0:
if length_diff < array.shape[0]:
array = np_concatenate((array, array[:length_diff]))
else:
new_part = np_repeat(array, ceil(length_diff / array.shape[0]), axis=0)
if len(array.shape) > 1:
shape = (ceil(length_diff / array.shape[0]), 1)
else:
shape = ceil(length_diff / array.shape[0])
new_part = np_tile(array, shape)
array = np_concatenate((array, new_part[:length_diff]))
out.append(array)
return out
def numpy_match_short(list_of_arrays):
'''match numpy arrays length by cutting the longer arrays'''
out = []
minl = list_of_arrays[0].shape[0]
for array in list_of_arrays:
minl = min(minl, array.shape[0])
for array in list_of_arrays:
length_diff = array.shape[0] - minl
if length_diff > 0:
array = array[:minl]
out.append(array)
return out
numpy_list_match_func = {
"SHORT": numpy_match_short,
"CYCLE": numpy_match_long_cycle,
"REPEAT": numpy_match_long_repeat,
}
def make_repeaters(lists):
chain = itertools.chain
repeat = itertools.repeat
out =[]
for l in lists:
out.append(chain(l, repeat(l[-1])))
return out
def make_cyclers(lists):
cycle = itertools.cycle
out =[]
for l in lists:
out.append(cycle(l))
return out
iter_list_match_func = {
"SHORT": lambda x: x,
"CYCLE": make_cyclers,
"REPEAT": make_repeaters,
}
#####################################################
################# list levels magic #################
#####################################################
# working with nesting levels
# define data floor
# NOTE, these function cannot possibly work in all scenarios, use with care
def dataCorrect(data, nominal_dept=2):
"""data from nesting to standard: TO container( objects( lists( floats, ), ), )
"""
dept = levelsOflist(data)
output = []
if not dept: # for empty lists
return []
if dept < 2:
return data #[dept, data]
else:
output = data_standard(data, dept, nominal_dept)
return output
def dataCorrect_np(data, nominal_dept=2):
"""data from nesting to standard: TO container( objects( lists( floats, ), ), )
"""
dept = levels_of_list_or_np(data)
output = []
if not dept: # for empty lists
return []
if dept < 2:
return data #[dept, data]
else:
output = data_standard(data, dept, nominal_dept)
return output
def dataSpoil(data, dept):
"""from standard data to initial levels: to nested lists
container( objects( lists( nested_lists( floats, ), ), ), ) это невозможно!
"""
__doc__ = 'preparing and making spoil'
def Spoil(dat, dep):
__doc__ = 'making spoil'
out = []
if dep:
for d in dat:
out.append([Spoil(d, dep-1)])
else:
out = dat
return out
lol = levelsOflist(data)
if dept > lol:
out = Spoil(data, dept-lol)
else:
out = data
return out
def data_standard(data, dept, nominal_dept):
"""data from nesting to standard: TO container( objects( lists( floats, ), ), )"""
deptl = dept - 1
output = []
for object in data:
if deptl >= nominal_dept:
output.extend(data_standard(object, deptl, nominal_dept))
else:
output.append(data)
return output
return output
def levelsOflist(lst):
"""calc list nesting only in countainment level integer"""
level = 1
for n in lst:
if n and isinstance(n, (list, tuple)):
level += levelsOflist(n)
return level
return 0
def levels_of_list_or_np(lst):
"""calc list nesting only in countainment level integer"""
level = 1
for n in lst:
if isinstance(n, (list, tuple)):
level += levels_of_list_or_np(n)
elif isinstance(n, (ndarray)):
level += len(n.shape)
return level
return 0
SIMPLE_DATA_TYPES = (float, int, float64, int32, int64, str, Matrix)
def get_data_nesting_level(data, data_types=SIMPLE_DATA_TYPES):
"""
data: number, or list of numbers, or list of lists, etc.
data_types: list or tuple of types.
Detect nesting level of actual data.
"Actual" data is detected by belonging to one of data_types.
This method searches only for first instance of "actual data",
so it does not support cases when different elements of source
list have different nesting.
Returns integer.
Raises an exception if at some point it encounters element
which is not a tuple, list, or one of data_types.
get_data_nesting_level(1) == 0
get_data_nesting_level([]) == 1
get_data_nesting_level([1]) == 1
get_data_nesting_level([[(1,2,3)]]) == 3
"""
def helper(data, recursion_depth):
""" Needed only for better error reporting. """
if isinstance(data, data_types):
return 0
elif isinstance(data, (list, tuple, ndarray)):
if len(data) == 0:
return 1
else:
return helper(data[0], recursion_depth+1) + 1
elif data is None:
raise TypeError("get_data_nesting_level: encountered None at nesting level {}".format(recursion_depth))
else:
#unknown class. Return 0 level
return 0
return helper(data, 0)
def ensure_nesting_level(data, target_level, data_types=SIMPLE_DATA_TYPES, input_name=None):
"""
data: number, or list of numbers, or list of lists, etc.
target_level: data nesting level required for further processing.
data_types: list or tuple of types.
input_name: name of input socket data was taken from. Optional. If specified,
used for error reporting.
Wraps data in so many [] as required to achieve target nesting level.
Raises an exception, if data already has too high nesting level.
ensure_nesting_level(17, 0) == 17
ensure_nesting_level(17, 1) == [17]
ensure_nesting_level([17], 1) == [17]
ensure_nesting_level([17], 2) == [[17]]
ensure_nesting_level([(1,2,3)], 3) == [[(1,2,3)]]
ensure_nesting_level([[[17]]], 1) => exception
"""
current_level = get_data_nesting_level(data, data_types)
if current_level > target_level:
if input_name is None:
raise TypeError("ensure_nesting_level: input data already has nesting level of {}. Required level was {}.".format(current_level, target_level))
else:
raise TypeError("Input data in socket {} already has nesting level of {}. Required level was {}.".format(input_name, current_level, target_level))
result = data
for i in range(target_level - current_level):
result = [result]
return result
def ensure_min_nesting(data, target_level, data_types=SIMPLE_DATA_TYPES, input_name=None):
"""
data: number, or list of numbers, or list of lists, etc.
target_level: minimum data nesting level required for further processing.
data_types: list or tuple of types.
input_name: name of input socket data was taken from. Optional. If specified,
used for error reporting.
Wraps data in so many [] as required to achieve target nesting level.
If data already has too high nesting level the same data will be returned
ensure_min_nesting(17, 0) == 17
ensure_min_nesting(17, 1) == [17]
ensure_min_nesting([17], 1) == [17]
ensure_min_nesting([17], 2) == [[17]]
ensure_min_nesting([(1,2,3)], 3) == [[(1,2,3)]]
ensure_min_nesting([[[17]]], 1) => [[[17]]]
"""
current_level = get_data_nesting_level(data, data_types)
if current_level >= target_level:
return data
result = data
for i in range(target_level - current_level):
result = [result]
return result
def flatten_data(data, target_level=1, data_types=SIMPLE_DATA_TYPES):
"""
Reduce nesting level of `data` to `target_level`, by concatenating nested sub-lists.
Raises an exception if nesting level is already less than `target_level`.
Refer to data_structure_tests.py for examples.
"""
current_level = get_data_nesting_level(data, data_types)
if current_level < target_level:
raise TypeError(f"Can't flatten data to level {target_level}: data already have level {current_level}")
elif current_level == target_level:
return data
else:
result = []
for item in data:
result.extend(flatten_data(item, target_level=target_level, data_types=data_types))
return result
def graft_data(data, item_level=1, wrap_level=1, data_types=SIMPLE_DATA_TYPES):
"""
For each nested item of the list, which has it's own nesting level of `target_level`,
wrap that item into a pair of [].
For example, with item_level==0, this means wrap each number in the nested list
(however deep this number is nested) into pair of [].
Refer to data_structure_tests.py for examples.
"""
def wrap(item):
for i in range(wrap_level):
item = [item]
return item
def helper(data):
current_level = get_data_nesting_level(data, data_types)
if current_level == item_level:
return wrap(data)
else:
result = [helper(item) for item in data]
return result
return helper(data)
def wrap_data(data, wrap_level=1):
for i in range(wrap_level):
data = [data]
return data
def unwrap_data(data, unwrap_level=1, socket=None):
socket_msg = "" if socket is None else f" in socket {socket.label or socket.name}"
def unwrap(lst, level):
if not isinstance(lst, (list, tuple, ndarray)):
raise Exception(f"Cannot unwrap data: Data at level {level} is an atomic object, not a list {socket_msg}")
n = len(lst)
if n == 0:
raise Exception(f"Cannot unwrap data: Data at level {level} is an empty list {socket_msg}")
elif n > 1:
raise Exception(f"Cannot unwrap data: Data at level {level} contains {n} objects instead of one {socket_msg}")
else:
return lst[0]
for level in range(unwrap_level):
data = unwrap(data, level)
return data
class SvListLevelAdjustment(object):
def __init__(self, flatten=False, wrap=False):
self.flatten = flatten
self.wrap = wrap
def __repr__(self):
return f"<Flatten={self.flatten}, Wrap={self.wrap}>"
def list_levels_adjust(data, instructions, data_types=SIMPLE_DATA_TYPES):
data_level = get_data_nesting_level(data, data_types + (ndarray,))
if len(instructions) < data_level+1:
raise Exception(f"Number of instructions ({len(instructions)}) is less than data nesting level {data_level} + 1")
def process(data, instruction, level):
result = data
if level + 1 < data_level and instruction.flatten:
result = sum(result, [])
if instruction.wrap:
result = [result]
#print(f"II: {level}/{data_level}, {instruction}, {data} => {result}")
return result
def helper(data, instructions, level):
if level == data_level:
items = process(data, instructions[0], level)
else:
sub_items = [helper(item, instructions[1:], level+1) for item in data]
items = process(sub_items, instructions[0], level)
#print(f"?? {level}/{data_level}, {data} => {sub_items} => {items}")
return items
return helper(data, instructions, 0)
def map_at_level(function, data, item_level=0, data_types=SIMPLE_DATA_TYPES):
"""
Given a nested list of object, apply `function` to each sub-list of items.
Nesting structure of the result will be simpler than such of the input:
most nested levels (`item_level` of them) will be eliminated.
Refer to data_structure_tests.py for examples.
"""
current_level = get_data_nesting_level(data, data_types)
if current_level == item_level:
return function(data)
else:
return [map_at_level(function, item, item_level, data_types) for item in data]
def transpose_list(lst):
"""
Transpose a list of lists.
transpose_list([[1,2], [3,4]]) == [[1,3], [2, 4]]
"""
return list(map(list, zip(*lst)))
# from python 3.5 docs https://docs.python.org/3.5/library/itertools.html recipes
def split_by_count(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return list(map(list, zip_longest(*args, fillvalue=fillvalue)))
def describe_data_shape_by_level(data, include_numpy_nesting=True):
"""
Describe shape of data in human-readable form.
Returns tuple:
* data nesting level
* list of descriptions of data shapes at each nesting level
"""
def helper(data):
if not isinstance(data, (list, tuple)):
if isinstance(data, ndarray):
if include_numpy_nesting:
nesting = len(data.shape)
else:
nesting = 0
return nesting, [type(data).__name__ + " of " + str(data.dtype) + " with shape " + str(data.shape)]
return 0, [type(data).__name__]
else:
result = [f"{type(data).__name__} [{len(data)}]"]
if len(data) > 0:
child = data[0]
child_nesting, child_result = helper(child)
result = result + child_result
else:
child_nesting = 0
return (child_nesting + 1), result
nesting, result = helper(data)
return nesting, result
def describe_data_shape(data):
"""
Describe shape of data in human-readable form.
Returns string.
Can be used for debugging or for displaying information to user.
Note: this method inspects only first element of each list/tuple,
expecting they are all homogeneous (that is usually true in Sverchok).
describe_data_shape(None) == 'Level 0: NoneType'
describe_data_shape(1) == 'Level 0: int'
describe_data_shape([]) == 'Level 1: list [0]'
describe_data_shape([1]) == 'Level 1: list [1] of int'
describe_data_shape([[(1,2,3)]]) == 'Level 3: list [1] of list [1] of tuple [3] of int'
"""
nesting, descriptions = describe_data_shape_by_level(data)
result = " of ".join(descriptions)
return "Level {}: {}".format(nesting, result)
def describe_data_structure(data, data_types=SIMPLE_DATA_TYPES):
if isinstance(data, data_types):
return "*"
elif isinstance(data, (list, tuple)):
if isinstance(data[0], data_types):
return str(len(data)) + "*"
else:
rs = []
for item in data:
r = describe_data_structure(item, data_types)
rs.append(str(r))
rs = str(len(data)) + "[" + ", ".join(rs) + "]"
return rs
else:
raise TypeError(f"Unexpected data type: {type(data)}")
def calc_mask(subset_data, set_data, level=0, negate=False, ignore_order=True):
"""
Calculate mask: for each item in set_data, return True if it is present in subset_data.
The function can work at any specified level.
subset_data: subset, for example [1]
set_data: set, for example [1, 2, 3]
level: 0 to check immediate members of set and subset; 1 to work with lists of lists and so on.
negate: if True, then result will be negated (True if item of set is not present in subset).
ignore_order: when comparing lists, ignore items order.
Raises an exception if nesting level of input sets is less than specified level parameter.
calc_mask([1], [1,2,3]) == [True, False, False])
calc_mask([1], [1,2,3], negate=True) == [False, True, True]
"""
if level == 0:
if not isinstance(subset_data, (tuple, list)):
raise Exception("Specified level is too high for given Subset")
if not isinstance(set_data, (tuple, list)):
raise Exception("Specified level is too high for given Set")
if ignore_order and get_data_nesting_level(subset_data) > 1:
if negate:
return [set(item) not in map(set, subset_data) for item in set_data]
else:
return [set(item) in map(set, subset_data) for item in set_data]
else:
if negate:
return [item not in subset_data for item in set_data]
else:
return [item in subset_data for item in set_data]
else:
sub_objects = match_long_repeat([subset_data, set_data])
return [calc_mask(subset_item, set_item, level - 1, negate, ignore_order) for subset_item, set_item in zip(*sub_objects)]
def apply_mask(mask, lst):
good, bad = [], []
for m, item in zip(mask, lst):
if m:
good.append(item)
else:
bad.append(item)
return good, bad
def invert_index_list(indexes, length):
'''
Inverts indexes list
indexes: List[Int] of Ndarray flat numpy array
length: Int. Length of the base list
'''
mask = np_ones(length, dtype='bool')
mask[indexes] = False
inverted_indexes = np_arange(length)[mask]
return inverted_indexes
def rotate_list(l, y=1):
"""
"Rotate" list by shifting it's items towards the end and putting last items to the beginning.
For example,
rotate_list([1, 2, 3]) = [2, 3, 1]
rotate_list([1, 2, 3], y=2) = [3, 1, 2]
"""
if len(l) == 0:
return l
if y == 0:
return l
y = y % len(l)
return list(l[y:]) + list(l[:y])
def partition(p, lst):
good, bad = [], []
for item in lst:
if p(item):
good.append(item)
else:
bad.append(item)
return good, bad
def map_recursive(fn, data, data_types=SIMPLE_DATA_TYPES):
"""
Given a nested list of items, apply `fn` to each of these items.
Nesting structure of the result will be the same as in the input.
"""
def helper(data, level):
if isinstance(data, data_types):
return fn(data)
elif isinstance(data, (list, tuple)):
return [helper(item, level+1) for item in data]
else:
raise TypeError(f"Encountered unknown data of type {type(data)} at nesting level #{level}")
return helper(data, 0)
def map_unzip_recursirve(fn, data, data_types=SIMPLE_DATA_TYPES):
"""
Given a nested list of items, apply `fn` to each of these items.
This method expects that `fn` will return a tuple (or list) of results.
After applying `fn` to each of items of data, "unzip" the result, so that
each item of result of `fn` would be in a separate nested list.
Nesting structure of each of items of the result of this method will be
the same as nesting structure of input data.
Refer to data_structure_tests.py for examples.
"""
def helper(data, level):
if isinstance(data, data_types):
return fn(data)
elif isinstance(data, (list, tuple)):
results = [helper(item, level+1) for item in data]
return transpose_list(results)
else:
raise TypeError(f"Encountered unknown data of type {type(data)} at nesting level #{level}")
return helper(data, 0)
def unzip_dict_recursive(data, item_type=dict, to_dict=None):
"""
Given a nested list of dictionaries, return a dictionary of nested lists.
Nesting structure of each of values of resulting dictionary will be similar to
nesting structure of input data, only at the deepest level, instead of dictionaries
you will have their values.
inputs:
* data: nested list of dictionaries.
* item_type: allows to use arbitrary class instead of standard python's dict.
* to_dict: a function which translates data item into python's dict (or
another class with the same interface). Identity by default.
output: dictionary of nested lists.
Refer to data_structure_tests.py for examples.
"""
if to_dict is None:
to_dict = lambda d: d
def helper(data):
current_level = get_data_nesting_level(data, data_types=(item_type,))
if current_level == 0:
return to_dict(data)
elif current_level == 1:
result = defaultdict(list)
for dct in data:
dct = to_dict(dct)
for key, value in dct.items():
result[key].append(value)
return result
else:
result = defaultdict(list)
for item in data:
sub_result = helper(item)
for key, value in sub_result.items():
result[key].append(value)
return result
return helper(data)
def is_ultimately(data, data_types):
"""
Check if data is a nested list / tuple / array
which ultimately consists of items of data_types.
"""
if isinstance(data, (list, tuple, ndarray)):
return is_ultimately(data[0], data_types)
return isinstance(data, data_types)
#####################################################
################### matrix magic ####################
#####################################################
# tools that makes easier to convert data
# from string to matrixes, vertices,
# lists, other and vice versa
def Matrix_listing(prop):
"""Convert Matrix() into Sverchok data"""
mat_out = []
for matrix in prop:
unit = []
for m in matrix:
# [Matrix0, Matrix1, ... ]
unit.append(m[:])
mat_out.append((unit))
return mat_out
def Matrix_generate(prop):
"""Generate Matrix() data from Sverchok data"""
mat_out = []
for matrix in prop:
unit = Matrix()
for k, m in enumerate(matrix):
# [Matrix0, Matrix1, ... ]
unit[k] = Vector(m)
mat_out.append(unit)
return mat_out
def Matrix_location(prop, to_list=False):
"""return a list of locations representing the translation of the matrices"""
Vectors = []
for p in prop:
if to_list:
Vectors.append(p.translation[:])
else:
Vectors.append(p.translation)