This repository was archived by the owner on Dec 6, 2023. It is now read-only.
forked from saad0105050/PoS-visualization
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfork.py
More file actions
1333 lines (1012 loc) · 38.1 KB
/
Copy pathfork.py
File metadata and controls
1333 lines (1012 loc) · 38.1 KB
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
import charstring as c
import tine as t
class Fork:
'''Fork'''
def __init__(self, char_str = "" , force_viable = False, maintain_heights = False):
# self._raw_char_str = char_str
self._w = c.CharString(char_str) # empty string
if not self.w.valid():
raise ValueError("'{}' is not a valid characteristic string.".format(self.w))
self._maintain_heights = maintain_heights
self._honest_depths = []
self._nodes_by_slot = []
for slot in range(0, self.w.len + 1): # the index zero is for indexing convenience
self._honest_depths.append(0) # initially
self._nodes_by_slot.append([]) # initially
self.node_counter = 0
# self.root = t.Tine(fork = self) # empty tine
self.root = t.Tine(self) # empty tine
self._longest_tine = self.root # initial value
self._longest_tines = [self.root] # initial value
self._critical_tines = [self.root] # initially
self.tines = {self.root.id : self.root} # initial list of all tines
# self.lca_table = {}
self._num_slots_seen = 0 # no slot seen so far
if isinstance(force_viable, bool):
self._force_viable = force_viable
else:
raise ValueError("force_viable must be boolean")
self._find_critical_tines()
if self._w == "":
self.adversarial_slots = []
self.num_adversarial_slots = 0
else:
self.adversarial_slots = self.w.all_adversarial_slots()
self.num_adversarial_slots = len(self.adversarial_slots)
# ============= Setter/getters ===============
def _get_num_slots_seen(self):
return self._num_slots_seen
num_slots_seen = property(_get_num_slots_seen)
def _get_longest_tines(self):
return self._longest_tines
longest_tines = property(_get_longest_tines)
def _get_longest_tine(self):
return self._longest_tine
longest_tine = property(_get_longest_tine)
def _get_critical_tines(self):
return self._critical_tines
critical_tines = property(_get_critical_tines)
def _get_w(self):
return self._w
w = property(_get_w)
def _get_nodes_by_slot(self):
return self._nodes_by_slot
nodes_by_slot = property(_get_nodes_by_slot)
# # ============ LCA table ===============
# def lca_key(self, tine1, tine2):
# return str(sorted([tine1.id, tine2.id]))
# def lca(self, tine1, tine2):
# key = self.lca_key(tine1, tine2)
# if key in self.lca_table:
# return self.lca_table[key]
# else:
# lca = tine1.lca(tine2)
# self.lca_table[key] = lca
# return lca
# ============ Methods executed after a node is created/deleted ==================
def on_new_node(self, node):
self._nodes_by_slot[node.label].append(node)
# attach id
node.id = self.node_counter
# increment the node counter
self.node_counter += 1
# print("node id: {}".format(node.id))
# update height
if self._maintain_heights:
node.update_height_upstream()
# update the list of tines
# special: root is always a tine
# if node.id == 0:
# self.tines[node.id] = node
# this method is SLOPPY
# it does not update self.tines or self.longest_tines
# nor is it recursive
def on_node_deleted(self, child, parent = None):
if child is self.root:
raise ValueError("Error: root node deleted")
if parent is None:
parent = child.parent
# update node_by_slot
self._nodes_by_slot[child.label].remove(child)
# update height
if self._maintain_heights:
parent.update_height_upstream(removal = True)
# update the list of tines
try:
# before = str(fork.tines.keys())
# recursive deletion
# if not child.isleaf:
# # remove all children as well
# arr = list(child.children)
# [child.remove_child(child = c, fork = self) for c in arr]
# the child is no longer a tine
del self.tines[child.id]
# make parent the new tine if it is now a leaf
if parent.isleaf:
self.tines[parent.id] = parent
# after = str(fork.tines.keys())
# print("Removing tine ({}--{}) id: {} from {} new {}"
# .format(self.label, child.label, child.id, before, after))
except KeyError:
pass
# ============ Methods for fork-building =================
def advance_charstring(self, suffix):
# breakpoint()
if len(suffix) == 1 and suffix in ['0', '1']:
# advance by only one bit
new_w = c.CharString(prev = self.w, new_bit = suffix)
assert new_w.len == 1 + self.w.len
if suffix == '1':
self.adversarial_slots.append(new_w.len)
self.num_adversarial_slots += 1
else:
s = self.w.str() + suffix
new_w = c.CharString(s = s)
self.adversarial_slots = self.w.all_adversarial_slots()
self.num_adversarial_slots = len(self.adversarial_slots)
hd = self._honest_depths[self.w.len] # last value
# self._honest_depths.append(hd)
for i in range(len(suffix)):
# update honest depths for new slots
# the new values will be the last value
self._honest_depths.append(hd)
# make room for new slots
self._nodes_by_slot.append([])
# update w
self._w = new_w
# reserves will change; update critical tines
self._find_critical_tines()
# ============== Tine viability ==================
# answers whether a tine of a certain length is viable at the onset of a given slot
# the input should either be a tine,
# in which case length and slot is resolved from the tine,
# or the tuple (slot, length),
# in which case a tine is not required
def is_viable_tine(self, tine, onset_slot = None):
return self.is_viable_length(tine.len, onset_slot)
def is_viable_length(self, length, onset_slot = None):
if onset_slot is None:
if self.w.len == 0:
onset_slot = 1
else:
onset_slot = self.w.len
if onset_slot <= 0:
raise ValueError("is_viable_length(): 'Onset of slot: {}' is meaningless for w: {}".format(onset_slot, self.w.str()))
completed_slot = onset_slot - 1
if completed_slot < 0 or completed_slot > self.w.len:
raise IndexError("onset_slot: {} is incorrect for w.len: {}".format(self.w, self.w.len))
# finally, viability test
# the length must be no shorter than slot's honest depth
try:
return length >= self._honest_depths[completed_slot]
except IndexError:
print("IndexError: completed_slot: {} while len(self._honest_depths) = {} w = {}"
.format(completed_slot, len(self._honest_depths), self.w))
# by this rule, the root is viable before any honest block is added
#============ Extend a tine =======================
def extend_tine(self, tine, labels):
labels = self.check_extension_labels(tine, labels)
# now build the tine by adding a sequence of blocks
orig_tine = tine
old_tine = tine
for label in labels:
new_tine = None
if self.w.is_adversarial(label):
new_tine = t.Tine(fork = self, label = label, parent = old_tine)
elif self.okay_to_extend(old_tine, label):
new_tine = t.Tine(fork = self, label = label, parent = old_tine)
# update honest depths if an honest tine
self._on_new_honest_tine(new_tine)
else:
raise ValueError("Not okay to extend")
# get ready to add the next block
old_tine = new_tine
# the final tine is here
self.on_newly_extended_tine(new_tine = new_tine, old_tine = orig_tine)
return new_tine
def check_extension_labels(self, tine, labels):
if isinstance(labels, int):
labels = [labels]
# no duplicate labels
if len(labels) != len(set(labels)):
raise ValueError("Repeated labels: {}".format(labels))
# labels must be an increasing list of integers
# sorted_labels = self._bubblesort(labels)
n = len(labels)
for i in range(n - 1):
if labels[i + 1] <= labels[i]:
raise ValueError("Labels not sorted: {}".format(labels))
# all labels must be later than tine's label
if tine.label >= labels[0]:
raise ValueError("Bad label: new block at {} must be later than parent's label {}".format(label, parent.label))
# finally
return labels
def okay_to_extend(self, parent, label):
# viability of honest tines
# parent cannot be shorter than child's honest depth
honest_block = self.w.is_honest(label)
parent_viable = self.is_viable_tine(tine = parent, onset_slot = label)
# extend if
# (i.) not forcing viability; or
# (ii.) forcing viability, but adversarial block; or
# (iii.)forcing viability, honest block, and viable
if self._force_viable and honest_block and not parent_viable:
raise ValueError("Viability error: cannot extend a non-viable tine: {} reach: {} with an honest slot: {} in w: {}"
.format(parent.path, parent.reach, label, self.w.str()))
else:
return True
def _on_new_honest_tine(self, tine):
# update current and future honest depths
if tine.honest:
for slot in range(tine.label, self.w.len + 1):
self._honest_depths[slot] = tine.len
else:
raise ValueError("Not an honest tine")
def on_newly_extended_tine(self, new_tine, old_tine = None):
# add to the list of tines
# before = str(self.tines.keys())
self.tines[new_tine.id] = new_tine
# remove the orig tine from this list unless it is the root
if not old_tine:
old_tine = new_tine.parent
if old_tine is not None and old_tine is not self.root:
# not a tine (i.e., leaf node) anymore
try:
del self.tines[old_tine.id]
except KeyError:
# key does not exist
pass
# after = str(self.tines.keys())
# print("Adding tine ({}--{}) id: {} to {} new {}"
# .format(new_tine.parent.label, new_tine.label, new_tine.id, before, after))
# update the longest_tine if necessary
# keep track of only viable tines
new_viable_longest_tine = False
new_tine_is_viable = self.is_viable_length(length = new_tine.len, onset_slot = self.w.len + 1)
if new_tine_is_viable:
if new_tine.len > self.longest_tine.len:
# new longest tine
new_viable_longest_tine = True
# update the longest tine
self._longest_tine = new_tine
self._longest_tines = [new_tine]
elif new_tine.len == self.longest_tine.len:
self._longest_tines.append(new_tine)
# update critical tines if necessary
self._find_critical_tines()
# ==================== Tine reach and critical tines ====================
# return viable tines with maximal reach
def honest_tines_with_largest_reach(self):
# import priorityqueue
# pq = priorityqueue.MaxPriorityQueue()
# # recall: self.tines includes the root
# for t in self.tines.values():
# if t.reach >= 0:
# if not viable_only or t.is_viable():
# pq.insert(t, t.reach )
pq = self.pq_nodes_by_reach_decreasing(honest_only = True)
# first tine
tine = pq.pop()
best_tines = [tine]
# print("\nfirst best tine: {} reach: {}, length: {}, label: {}".format(tine, tine.reach, tine.len, tine.label))
# are there other tines with the same reach?
done = False
# while (len(tines) >= 1) and not done:
while (not pq.isempty()) and not done:
tine = pq.pop()
if tine.reach == best_tines[0].reach:
# print("\nother best tine: {} reach: {}, length: {}, label: {}".format(tine, tine.reach, tine.len, tine.label))
best_tines.append(tine)
else:
done = True
return best_tines
# critical tines does not have to be viable
def _find_critical_tines(self, node = None):
# self._critical_tines = [t for t in self.tines.values() if t.reach == 0 and self.is_viable_tine(t)]
self._critical_tines = [t for t in self.tines.values() if t.reach == 0]
def _find_critical_tines_old(self, node = None):
if node is None:
node = self.root
self._critical_tines.clear()
# now consider only leaves
if node.isleaf:
# leaf
if node.reach == 0:
self._critical_tines.append(node)
else:
# has children
for child in node.children:
self._find_critical_tines_old(child)
# finally
# special: the root is always extensible
if (node == self.root) and node.reach == 0 and (not node in self._critical_tines):
self._critical_tines.append(node)
# keep only nodes with a non-negative reach
def pq_nodes_by_reach_decreasing(self, honest_only = False):
# insert this node at the priority queue keyed by reach (smallest first)
import priorityqueue as q
# This is a max-pririty queue
# key = reach
# Remember: negative reach = negative priority
priority_negative = lambda item, priority: priority < 0
pq = q.MaxPriorityQueue(exclude_item_if = priority_negative)
# insert to pq only nodes with non-negative reach
if not honest_only:
[pq.insert(node, node.reach) for arr in self.nodes_by_slot for node in arr]
else:
[pq.insert(node, node.reach) for arr in self.nodes_by_slot for node in arr if node.honest]
return pq
# keep only nodes with a non-negative reach
def pq_nodes_by_reach_increasing(self, honest_only = False):
# insert this node at the priority queue keyed by reach (smallest first)
import priorityqueue as q
# This is a max-pririty queue
# key = -reach
# Remember: negative reach = positive priority
priority_positive = lambda item, priority: priority > 0
pq = q.MaxPriorityQueue(exclude_item_if = priority_positive)
# insert to pq only nodes with non-negative reach
if honest_only:
[pq.insert(node, -node.reach) for arr in self._nodes_by_slot for node in arr if node.honest]
else:
[pq.insert(node, -node.reach) for arr in self._nodes_by_slot for node in arr]
return pq
#===================== Methods for display ====================
def add_row_on_top(self, arr, row):
new_matrix = [row]
for line in arr:
new_matrix.append(line)
return new_matrix
def _sort_rows_by_splitting_point(self, matrix, tine_paths, tines):
import priorityqueue as q
pq = q.MaxPriorityQueue()
star_symbol = '*'
for i in range(len(matrix)):
row = matrix[i]
path = tine_paths[i]
tine = tines[i]
if star_symbol in row:
# earlier splits get higher priority
priority = -row.index(star_symbol)
else:
# the reference tine; highest priority
priority = -len(row)
pq.insert((row, path, tine), priority)
# now pop and add
matrix, tine_paths, tines = self._alternately_add_rows_to_matrix(pq)
return matrix, tine_paths, tines
def encode_nodes(self):
# reset all encodings
[node.reset_encoding() for node in self.get_nodes()]
# First, decorate all nodes on the longest tines
# Then decorate all other nodes
tines_and_types = [(self.longest_tines, True), (self.tines.values(), False)]
for tines, on_longest_tine in tines_and_types:
for tine in tines:
node = tine
while node and not node.is_encoding_on_longest_tine():
# pre-calculate the block encodings along the longest tines
node.calculate_and_set_encoding(on_longest_tine = on_longest_tine)
# deal with the parent node
node = node.parent
# long tines in the middle, short tines on the fringe
# assumes that node encodings are already computed
def _tines_to_rows(self,
nodes = None,
show_paths = False,
block_encoding = False, prune_slot_at = None,
long_tine_in_the_middle = True,
include_root = False):
import priorityqueue
pq = priorityqueue.MaxPriorityQueue()
n = self.w.len
# if block_encoding:
# # need to tell blocks if they are on the longest tine
if nodes is None:
# all tines
nodes = self.tines.values()
for tine in nodes:
if not include_root and tine == self.root:
pass
else:
if not show_paths:
path = ""
else:
if not prune_slot_at:
path = tine.path
else:
path = tine.partial_path(prune_slot_at)
longest_tine = (tine == self.longest_tine)
row = tine.to_row(
w_len = n,
block_encoding = block_encoding,
longest_tine = longest_tine,
prune_slot_at = prune_slot_at
)
pq.insert((row, path, tine), tine.len)
if long_tine_in_the_middle:
# long tines in the middle, short tines on the fringe
matrix, tine_paths, tines = self._alternately_add_rows_to_matrix(pq)
else:
matrix = []
tine_paths = []
tines = []
while not pq.isempty():
item = pq.pop()
# row = item[0]
# tine_path = item[1]
row, tine_path, tine = item
matrix.append(row)
tine_paths.append(tine_path)
tines.append(tine)
return matrix, tine_paths, tines
# expect: priority queue entries are (row, tine_path)
def _alternately_add_rows_to_matrix(self, pq):
matrix = []
tine_paths = []
tines = []
top = True
while not pq.isempty():
# item = pq.pop()
# row = item[0]
# tine_path = item[1]
row, tine_path, tine = pq.pop()
if top:
matrix = self.add_row_on_top(matrix, row)
tine_paths = self.add_row_on_top(tine_paths, tine_path)
tines = self.add_row_on_top(tines, tine)
else:
matrix.append(row)
tine_paths.append(tine_path)
tines.append(tine)
# change side
# print('Not changing side in tines to rows')
top = (not top)
return matrix, tine_paths, tines
def to_matrix(self, nodes = None, sort_by_splitting_point = False, show_tines = False,
block_encoding = False, deepest_node = None, prune_slot_at = None):
long_tine_in_the_middle = not sort_by_splitting_point
if block_encoding:
# pre-calculate the block encodings along the longest tine
self.encode_nodes()
rows, tine_paths, tines = self._tines_to_rows(
nodes = nodes,
show_paths = show_tines,
block_encoding = block_encoding, prune_slot_at = prune_slot_at,
long_tine_in_the_middle = long_tine_in_the_middle)
# [print(r) for r in rows]
matrix = self._compact_matrix(rows, block_encoding = block_encoding)
if sort_by_splitting_point:
# need to sort rows by splitting point
# need the matrix be compacted already
# the longest tine need to be at the top
matrix, tine_paths, tines = self._sort_rows_by_splitting_point(matrix, tine_paths, tines)
return matrix, tine_paths, tines
def _matrix_to_string(self, matrix, delim = ","):
str = "\n".join([delim.join(row) for row in matrix] )
return str
# comma-separated entries; lines separated by new-line
def __str__(self,
nodes = None, delim = ",", show_matrix = True, show_tines = False,
block_encoding = False, prune_slot_at = None,
sort_by_splitting_point = False, verbose = False):
matrix, tine_paths, tines = self.to_matrix(
nodes = nodes,
show_tines = show_tines,
block_encoding = block_encoding, prune_slot_at = prune_slot_at,
sort_by_splitting_point = sort_by_splitting_point)
str = ""
if show_tines:
lines = []
for r in range(0, len(matrix)):
row = ""
if show_matrix:
row = matrix[r]
tine_path = tine_paths[r]
lines.append(delim.join(row) + " tine: " + tine_path)
str = "\n".join(lines)
else:
# str = "\n".join([ delim.join(row) for row in matrix] )
str = self._matrix_to_string(matrix)
return str
def to_string(self,
nodes = None, delim = ",", show_matrix = True, show_tines = False,
sort_by_splitting_point = False, block_encoding = False,
prune_slot_at = None
):
return self.__str__(
nodes = nodes, delim = delim, show_tines = show_tines,
block_encoding = block_encoding, prune_slot_at = prune_slot_at,
show_matrix = show_matrix, sort_by_splitting_point = sort_by_splitting_point)
def _add_star(self, row, col):
# replace current block with *
row[col] = "*"
# delete all blocks to its left except the root column
for c in range(0, col):
if row[c] != "0":
row[c] = "0"
return row
def _compact_matrix(self, matrix, block_encoding = False):
num_rows = len(matrix)
num_cols = self.w.len + 1 # one column extra for the root node
honest_cells = ["3", "7"]
adv_cells = ["1", "5"]
# scan columns from right to left
for col in range(num_cols - 1, -1, -1):
slot = col
is_slot_honest = self.w.is_honest(slot)
if col == 0 or is_slot_honest:
# the root column is treated as honest
# are there multiple entries in this honest column?
preivous_honest_block = False
num_honest_cells = 0
first_honest_cell_row_index = None
some_honest_cell_on_the_longest_tine = False
num_honest_cells_on_the_longest_tine = 0 # for the genesis slot
# with this column at hand, scan rows from top to bottom
row_index = -1
for row in matrix:
row_index += 1
cell_value = row[col]
this_honest_cell_on_the_longest_tine = False
# is it an honest cell?
if not block_encoding:
is_honest_cell = (cell_value == "1")
else:
is_honest_cell = (cell_value in honest_cells)
if is_honest_cell:
if num_honest_cells == 0:
first_honest_cell_row_index = row_index
num_honest_cells += 1
if block_encoding and cell_value == "7":
# this honest cell is on the longest tine
# in a given slot, multiple honest cells on the longest chain
# happens only for the root node
multiple_honest_cells_on_the_longest_tine = \
(num_honest_cells_on_the_longest_tine is not None) and \
(num_honest_cells_on_the_longest_tine >= 1)
# assert (col == 0 or multiple_honest_cells_on_the_longest_tine is False)
this_honest_cell_on_the_longest_tine = True
num_honest_cells_on_the_longest_tine += 1
# we don't do anything on the first honest cell in this column
if num_honest_cells >= 2:
if not block_encoding:
# always substitue non-leading honest cells
row = self._add_star(row, col)
else:
if this_honest_cell_on_the_longest_tine and num_honest_cells_on_the_longest_tine == 1:
# this honest cell is the first on the longest tine
# we've already encountered an off-the-longest-chain honest cell
# modify that row and keep the current row intact
other_row = matrix[first_honest_cell_row_index] # this is the unchanged row
matrix[first_honest_cell_row_index] = self._add_star(other_row, col)
else:
# substitue non-leading honest cells
row = self._add_star(row, col)
# # at least two honest blocks
# # replace current block with *
# row[col] = "*"
# # delete all blocks to its left except the root column
# for c in range(0, col):
# if row[c] != "0":
# row[c] = "0"
return matrix
def diagnostics(self,
tines = True,
nodes = False,
matrix = False,
critical_tines = False,
verbose = False,
matrix_delim = ",",
tines_with_matrix = False,
block_encoding = False,
include_root = False):
# compact display if possible
if matrix and tines:
tines_with_matrix = True
# tines = False
# print the reach of every node
print("\n===== Fork on w = {} ({} bits) =====".format(self.w.str(), self.w._get_len()))
# diagnostics of every node
if nodes:
tines = False
print("----Node diagnostics----")
[n.diagnostics(verbose) for arr in self.nodes_by_slot for n in arr]
if tines:
num_tines = len(self.tines)
if not include_root:
num_tines -= 1
print("----Tines ({})----".format(num_tines))
for t in self.tines.values():
if t is not self.root or include_root:
t.diagnostics(verbose)
# touch_tine = lambda tine: tine.diagnostics(verbose)
# self.root.visit_leaves(touch_tine)
# if include_root:
# self.root.diagnostics(verbose)
if critical_tines:
print("----Critical tines----")
for tine in self._critical_tines:
tine.diagnostics()
if matrix:
print("----Matrix----")
num_chars = self.w.len + 1
num_delims = num_chars - 1
matrix_line = "-" * ( num_chars + num_delims) # one extra for the root
w_line = "w=" + ",".join(self.w.str())
print(w_line)
print(matrix_line)
print(self.__str__(delim = matrix_delim, show_tines = tines_with_matrix, block_encoding = block_encoding))
print(matrix_line)
#==================== Methods for a trimmed fork ==================
def trim_tine_tips_old(self):
remove_leaf = lambda leaf: leaf.parent.children.remove(leaf)
if len(self.root.children) >= 1:
self.root.visit_leaves(remove_leaf)
def trim_tine_tips(self, tines = None):
if not tines:
tines = list(self.tines.values()).copy()
new_tines = []
for t in tines:
if t is not self.root:
t.parent.remove_child(child = t, fork = self)
# did the parent become a new tine?
if t.parent.isleaf:
new_tines.append(t.parent)
return new_tines
# input: a list of tines {t}
# output: a list of nodes {p} where
# t is the only child of p
def parents_at_height(self, nodes, height, verbose = False):
new_nodes = {}
for t in nodes:
# print("Examining node: {}".format(t.id))
if hasattr(t, 'no_trim'):
# it stays in the next level
new_nodes[t.id] = t
elif t is not self.root:
# all tines have the same height
p = t.parent
if hasattr(p, 'no_trim'):
# p.no_trim = True but t.no_trim is None
# p does not go into the next level
continue
# print("Examining parent node: {} at height: {} with {} children".format(p.id, p.height, p.num_children()))
# this is crucial: check the height
elif p.height == height:
if p.id not in new_nodes:
# yes: the parent is in the next level set
# and it's not been seen yet
# print("Adding node {} at height {}".format(p.id, p.height))
new_nodes[p.id] = p
# return (new_nodes.values(), deepest_node)
return new_nodes.values()
# returns an array of size max_delete_blocks + 1
# index k = 0, 1, ..., max_delete_blocks
# value at index k is
# the matrix representation after trimming the last k blocks
# from every tine
def trim_tines_and_get_matrix(self,
max_delete_blocks = 0,
show_matrix = True,
show_tines = False,
sort_by_splitting_point = False,
block_encoding = True,
prune_slot_at = None,
verbose = False ):
hard_trim = False
# print("Begin trim_tines_and_get_matrix")
# self.diagnostics(matrix = False, tines = True)
result = []
# self.update_tines()
no_more_cut = False
if verbose:
for lt in self.longest_tines:
print("\tlongest tine: {}".format(lt.path))
valid_prune = \
prune_slot_at is not None and \
prune_slot_at >= 1 and \
prune_slot_at <= self.w.len
# the longest-tine must not be cut
# mark all nodes on the longest tine(s) as non-trimmable
for lt in self.longest_tines:
node = lt
while node:
setattr(node, 'no_trim', True)
if verbose:
print("node slot: {} no_trim: {}".format(node.label, node.no_trim))
node = node.parent
nodes = self.tines.values()
# check no_trim
# [print("no_trim: {}".format(n.label)) for arr in self._nodes_by_slot for n in arr if hasattr(n, 'no_trim')]
if verbose:
print("Valid prune: {} prune_slot_at: {}".format(valid_prune, prune_slot_at))
if block_encoding:
# pre-calculate the block encodings along the longest tine
for lt in self._longest_tines:
lt.to_row(self.w.len, block_encoding = True, longest_tine = True)
if not hard_trim:
self.update_heights()
height = 0
for k in range(0, max_delete_blocks + 1):
# print("\n---- k = {} ----".format(k))
# self.diagnostics(matrix = False, tines = True)
if k >= 1 and not no_more_cut:
# if len(self.root.children) >= 1:
# self.root.visit_leaves(remove_leaf)
# self.trim_tine_tips_old()
if hard_trim:
self.trim_tine_tips()
if self.root.num_children() == 0:
no_more_cut = True
else:
if verbose:
print("Level set at height: {} nodes: {} ".format(height, [n.label for n in nodes]))
height = height + 1
nodes = self.parents_at_height(nodes = nodes, height = height, verbose = verbose)
if not nodes:
no_more_cut = True
snapshot = self.to_string(
nodes = nodes,
show_tines = show_tines,
show_matrix = show_matrix,
sort_by_splitting_point = sort_by_splitting_point,
block_encoding = block_encoding,
prune_slot_at = prune_slot_at
)
result.append(snapshot)
# finally
# unmark all nodes that were marked as non-trimmable
to_do = [self.root]
while to_do:
node = to_do.pop(0)
del node.no_trim
[to_do.append(c) for c in node.children if hasattr(c, 'no_trim')]
return result
def delete_rightmost_nonempty(self, row, last_scanned = None, EMPTY = '0', SPLIT = '*'):
if not last_scanned:
last_scanned = len(row)
right_end = last_scanned - 1
# skip trailing EMPTY cells
while right_end >= 0 and right_end <= len(row) and row[right_end] == EMPTY:
right_end -= 1
# now either right_end == 0 or row[right_end] is non-empty
# if this cell is non-empty, delete it
# but don't delete blocks on the longest tines (i.e., value >= 5)
if right_end >= 0 and right_end < len(row) and row[right_end] != EMPTY:
# delete this block
row[right_end] = EMPTY
# finally
return row, right_end
def trim_tines_and_get_matrix_stable(self,
max_delete_blocks = 0,
show_matrix = True,
show_tines = False,
sort_by_splitting_point = False,
verbose = False ):
# a snapshot is a matrix of string symbols
snapshots = []
n = self.w.len
# all leaf nodes
nodes = self.tines.values()
# take the first snapshot