-
Notifications
You must be signed in to change notification settings - Fork 1
/
ActiveGraph.py
2102 lines (1876 loc) · 75.7 KB
/
ActiveGraph.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
# ActiveGraph.py -- The Graph class needed for defining FARG models, and
# supporting classes
from abc import ABC, abstractmethod
from typing import Union, List, Tuple, Dict, Set, FrozenSet, Iterable, Any, \
NewType, Type, ClassVar, Callable, Sequence
from dataclasses import dataclass, field
from inspect import isclass
from copy import copy, deepcopy
from operator import attrgetter, itemgetter
from random import choice, choices
from itertools import product, chain
from collections import defaultdict
from Primitives import Hop, Hops, PortGraphPrimitives, ActiveGraphPrimitives, \
ActivationPrimitives, ActivationPolicy, SupportPrimitives, SupportPolicy, \
SlipnetPolicy
from Node import Node, NodeId, MaybeNodeId, PortLabel, PortLabels, is_nodeid, \
NRef, NRefs, CRef, CRefs, MaybeNRef, MaybeCRef, \
as_nodeid, as_node, as_nodeids, as_nodes, is_abstract_cref
from PortMates import PortMates
from Action import Action, Actions, FindBasis
from ActiveNode import ActiveNode, ActionNode, Sleeping
from Propagator import Propagator
from util import as_iter, as_list, as_set, is_iter, repr_str, first, reseed, \
intersection, empty_set, sample_without_replacement, PushAttr, \
always_true, filter_none, clip, reweight
from exc import NodeLacksMethod, NoSuchNode, NoSuchNodeclass, NeedArg, \
FargDone, FizzleWithTag, Fizzle
from log import *
from criteria import Criterion, OfClass, NodeEq, NoMate
#TODO rm
class Support(ActiveGraphPrimitives):
def support_for(self, node: NRef) -> float:
#TODO
return 1.0
class Touches:
pass
class Members(ActiveGraphPrimitives):
pass
class ActiveGraph(
Touches, Members, ActivationPolicy, SupportPolicy, SlipnetPolicy,
ActivationPrimitives, SupportPrimitives, ActiveGraphPrimitives
):
std_port_mates = PortMates([
('members', 'member_of'), ('tags', 'taggees'), ('built_by', 'built'),
('next', 'prev'), ('copy_of', 'copies'), ('problem', 'problem_solver'),
('activation_from', 'activation_to'), ('support_from', 'support_to'),
('completion', 'completion_of'), ('basis', 'basis_of'),
('need_basis_like', 'archetypal_basis_of'),
('source_chain', 'live_chain')
])
def __init__(
self,
seed: Union[int, None]=None,
t: Union[int, None]=None,
num_timesteps: Union[int, None]=None,
port_mates: Union[PortMates, None]=None,
*args,
**kwargs
):
if t is None:
t = 0
self.t = t
self.seed = reseed(seed)
super().__init__(*args, **kwargs)
self.num_timesteps = num_timesteps
self.final_result: Union[FargDone, None] = None
self.port_mates: PortMates = deepcopy(self.std_port_mates)
if port_mates:
self.port_mates += port_mates
self.nodeclasses: Dict[str, Type[Node]] = {}
# Automatically link activation from new nodes of given type to
# given node(s).
self.activation_autolinks: List[Tuple[Type[Node], NRefs]] = []
self.max_active_nodes: Union[int, None] = None
self.max_actions: int = 1
self.builder: MaybeNRef = None # Node that is currently "building"
# other nodes
self.new_nodes: Set[NodeId] = set() # Nodes built this timestep
self.prev_new_nodes: Set[NodeId] = set() # Nodes built last timestep
self.touched_nodes: Set[NodeId] = set()
self.prev_touched_nodes: Set[NodeId] = set()
self.after_touch_nodes: Set[NodeId] = set()
# Nodes that need their .after_touch_update method called at the
# end of each timestep.
self.during_touch = False
self.prev_actions: List[Action] = []
self.ws: MaybeNRef = None
self.slipnet: MaybeNRef = None
def add_nodeclasses(self, *clss: Type[Node]):
self.nodeclasses.update((cls.__name__, cls) for cls in clss)
def add_activation_autolinks(self, *pairs: Tuple[Type[Node], NRefs]):
self.activation_autolinks += pairs
self.make_activation_links(self.members_recursive(self.ws), pairs)
# Overrides for ActiveGraphPrimitives
def add_node(
self,
node: Union[Type[Node], Node, str, Type[Action]],
*args,
**kwargs
) -> Node:
'''Creates a new node and returns its Node object. The Node object's
NodeParams are filled in from 'args' and 'kwargs', producing
FilledParams and attributes within the node and/or links to neighbors.
The filling in of NodeParams happens whether a new Node object is
created or if an existing Node is supplied, as explained below.
If 'node' is a Node class, a new Node object of that class is created.
If 'node' is a string, it must be the name of a NodeClass registered
with the graph. The new Node is created as if 'node' were that
NodeClass.
If 'node' is itself a Node object, the new node is given that object
for its datum and its .id field is filled in.
If 'node' is an Action object, the new node is an ActionNode with
.action set to that Action object.
If 'node' is a nodeid (an int), it must refer to an existing node in
the graph. A new Node is created as if 'node' were the class of the
referenced node.
#TODO Explain touches, implicit membership, builder, Workspace and
Slipnet, and .on_build().
'''
#print('ADD_NODE', repr(node), args, kwargs)
if isclass(node) and issubclass(node, Action):
action = node(*args)
kwargs['action'] = action
return self.add_node(ActionNode, **kwargs)
elif isinstance(node, Action):
return self.add_node(ActionNode, action=node, **kwargs)
builder = kwargs.pop('builder', self.builder)
activation = kwargs.pop('activation', None)
if isinstance(node, Node): # We were given a Node object
kwargs = {**node.regen_kwargs(), **kwargs}
already = self.already_built(node, *args, **kwargs)
if already:
# TODO boost its activation
return already
self._add_node(node)
if ShowPrimitives:
print('built', self.long_nodestr(node))
# TODO Apply link FilledParams? DONE?
filled_params = node.make_filled_params(self, *args, **kwargs)
filled_params.apply_to_node(self, node.id)
else: # We were given some indication of the new node's class
if isinstance(node, str) or is_nodeid(node):
node = self.as_nodeclass(node)
# TODO Catch/throw exception if it doesn't exist?
already = self.already_built(node, *args, **kwargs)
if already:
# TODO boost its activation
return already # TODO Don't return yet; updates later
assert issubclass(node, Node), f'{node} is not a subclass of Node'
filled_params = node.make_filled_params(self, *args, **kwargs)
node: Node = node() # Create the Node object
self._add_node(node, activation)
if ShowPrimitives:
print('built', self.long_nodestr(node))
filled_params.apply_to_node(self, node.id)
self.add_implicit_membership(node)
self.mark_builder(node, builder)
classname = node.__class__.__name__
if not self.ws and classname == 'Workspace':
self.ws = node
if not self.slipnet and classname == 'Slipnet':
self.slipnet = node
if classname not in self.nodeclasses:
self.nodeclasses[classname] = node.__class__
node.on_build()
self.new_nodes.add(self.as_nodeid(node))
if self.callable(node, 'after_touch_update'):
self.after_touch_nodes.add(node.id)
return node
def _add_node(
self,
node: Node,
activation: Union[float, None]=None
) -> NodeId:
'''Makes the node, sets its .id and .g members, its .tob ("time of
birth"), its initial activation, and returns its id.'''
id = super()._add_node(node)
node.tob = self.t
if activation is None:
activation = node.initial_activation
self.set_activation(node, activation)
self.set_support_for(node, node.initial_support_for)
return id
#TODO UT
def remove_node(self, node: NRefs):
'''Touches all of node's neighbors and all the tags of node's
neighbors, and then removes node.'''
self.touch(self.neighbors(node))
self.touch(self.tags_of(self.neighbors(node)))
for n in as_iter(node):
if self.has_node(n):
if ShowPrimitives:
print('removed node', self.long_nodestr(n))
self._remove_node(self.as_nodeid(n))
# TODO Allow either port_label1 or port_label2 to be None; fill in
# default from port_mates.
def add_edge(
self,
nodes1: NRefs,
port_label1: PortLabels,
nodes2: NRefs,
port_label2: PortLabels,
**attr
):
for fromid in as_nodeids(nodes1):
for fromlabel in as_iter(port_label1):
for toid in as_nodeids(nodes2):
for tolabel in as_iter(port_label2):
tl = self.best_fitting_port_label(toid, tolabel)
self._add_edge(fromid, fromlabel, toid, tl, **attr)
self.touch(fromid)
self.touch(toid)
if ShowPrimitives:
print(
'added edge ',
self.hopstr(fromid, fromlabel, toid, tl),
attr
)
def move_edge(
self,
nodes1: NRefs,
port_label1: PortLabels,
nodes2: NRefs,
port_label2: PortLabels,
**attr
):
self.remove_hops_from_port(nodes1, port_label1)
self.add_edge(nodes1, port_label1, nodes2, port_label2, **attr)
def edge_weight(
self,
node1: NRef,
port_label1: PortLabel,
node2: NRef,
port_label2: PortLabel,
):
return self._edge_weight(
self.as_nodeid(node1), port_label1,
self.as_nodeid(node2), port_label2
)
def has_edge(
self,
nodes1: NRefs,
port_label1: PortLabels,
nodes2: NRefs,
port_label2: PortLabels
) -> bool:
'''Returns True iff all the nodes specified have edges between all
the port labels specified.'''
# for fromid in as_nodeids(nodes1):
# for fromlabel in as_iter(port_label1):
# for toid in as_nodeids(nodes2):
# for tolabel in as_iter(port_label2):
# if not self.find_hop(fromid, fromlabel, toid, tolabel):
# return False
fromlabel = self.port_mates.expand_port_label(port_label1)
tolabel = self.port_mates.expand_port_label(port_label2)
for fromid in as_nodeids(nodes1):
for toid in as_nodeids(nodes2):
if not self.find_hop(fromid, fromlabel, toid, tolabel):
return False
return True
def has_hop(
self,
from_node: NRefs,
from_port_label: PortLabels,
to_node: NRefs,
to_port_label: PortLabels
):
'''Returns True iff all the specified hops exist. Unlike .has_edge(),
.has_hop() does not expand port labels. The port labels much match
exactly; port inheritance does not make a match.'''
return all(
self.find_hop(fromid, fromlabel, toid, tolabel)
for fromid in as_nodeids(from_node)
for fromlabel in as_iter(from_port_label)
for toid in as_nodeids(to_node)
for tolabel in as_iter(to_port_label)
)
def remove_edge(
self,
node1: NRefs,
port_label1: PortLabels,
node2: NRefs,
port_label2: PortLabels,
):
'''It is not an error to remove an edge that does not exist. Regardless,
we "touch" both nodes.'''
for fromid in as_nodeids(node1):
for fromlabel in as_iter(port_label1):
for toid in as_nodeids(node2):
for tolabel in as_iter(port_label2):
self._remove_edge(fromid, fromlabel, toid, tolabel)
self.touch(fromid)
self.touch(toid)
if ShowPrimitives:
print('removed edge', self.nodestr(fromid), fromlabel, self.nodestr(toid), tolabel)
# TODO UT
def neighbors(
self,
nodes: NRefs,
port_label: PortLabels = None,
neighbor_class: Union[Type[Node], NRef] = None,
neighbor_label: PortLabels = None,
exclude_port_label: PortLabels = frozenset(['copy_of', 'copies'])
) -> Set[NodeId]:
hops = set()
port_label = self.expand_port_label(port_label)
exclude_port_label = self.expand_port_label(exclude_port_label)
neighbor_label = self.expand_port_label(neighbor_label)
for node in as_iter(nodes):
if not port_label:
hops |= self.hops_from_node(node)
else:
for pl in as_iter(port_label):
hops |= self.hops_from_port(node, pl)
if exclude_port_label:
exclude_port_label = as_set(exclude_port_label)
for hop in list(hops):
if hop.from_port_label in exclude_port_label:
hops.discard(hop)
if neighbor_class is not None:
for hop in list(hops):
if not self.is_of_class(hop.to_node, neighbor_class):
hops.discard(hop)
if neighbor_label is None:
result = set(hop.to_node for hop in hops)
else:
pls = as_set(neighbor_label)
result = set(
hop.to_node
for hop in hops
if hop.to_port_label in pls
)
return result
#TODO UT
def neighbor(
self,
node: NRef,
port_label: PortLabels = None,
neighbor_class: Union[Type[Node], NRef] = None,
neighbor_label: PortLabels = None
) -> MaybeNRef:
'''Returns the 'first' neighbor. TODO Define 'first' better.'''
return first(self.neighbors(
node, port_label, neighbor_class, neighbor_label
))
# TODO UT
def incidence_outgoing(self, node: MaybeNRef, port_label: PortLabels) \
-> Dict[PortLabel, NRefs]:
# node = self.as_node(node)
# if not node:
# return {}
result: Dict[PortLabel, Set[NodeId]] = defaultdict(set)
for hop in self.hops_from_node(node):
for port_label in as_iter(port_label):
if self.port_mates.isa(hop.from_port_label, port_label):
result[hop.from_port_label].add(hop.to_node)
return result
# TODO UT
@staticmethod
def prepend_port_label_prefix(prefix: str, d: Dict[PortLabel, Any]) \
-> Dict[PortLabel, Any]:
'''Returns d after prepending prefix to each key. Does not change d,
and does not prepend the prefix if it's already there.'''
return dict(
(k if k.startswith(prefix) else prefix + k, v)
for k, v in d.items()
)
def walk(
self,
nodes: NRefs,
port_label: PortLabels = None,
neighbor_class: Union[Type[Node], NRef] = None,
neighbor_label: PortLabels = None,
include_start = True,
max_hops: Union[int, None] = None
) -> Iterable[NodeId]:
seen: Set[NodeId] = set()
to_visit: List[Tuple(NodeId, int)] = [] # int is # of hops
for node in as_iter(nodes):
nodeid = as_nodeid(node)
if nodeid not in seen:
if include_start:
yield nodeid
seen.add(nodeid)
to_visit.append((nodeid, 0))
while to_visit:
nodeid, num_hops = to_visit.pop(0)
for n in self.neighbors(
nodeid, port_label, neighbor_class, neighbor_label
):
if n not in seen:
yield n
seen.add(n)
if max_hops is None or num_hops + 1 < max_hops:
to_visit.append((n, num_hops + 1))
def walkd(
self,
nodes: NRefs,
port_label: PortLabels = None,
neighbor_class: Union[Type[Node], NRef] = None,
neighbor_label: PortLabels = None,
include_start = True,
max_hops: Union[int, None] = None
) -> Iterable[Tuple[NodeId, int]]:
'''Same as .walk() but generates tuples of
(nodeid, distance-from-start-node[s]).'''
seen: Set[NodeId] = set()
to_visit: List[Tuple(NodeId, int)] = [] # int is # of hops
for node in as_iter(nodes):
nodeid = as_nodeid(node)
if nodeid not in seen:
if include_start:
yield (nodeid, 0)
seen.add(nodeid)
to_visit.append((nodeid, 0))
while to_visit:
nodeid, num_hops = to_visit.pop(0)
for n in self.neighbors(
nodeid, port_label, neighbor_class, neighbor_label
):
if n not in seen:
yield (n, num_hops + 1)
seen.add(n)
if max_hops is None or num_hops + 1 < max_hops:
to_visit.append((n, num_hops + 1))
# TODO UT
# TODO rename chain_together
def link_sequence(
self,
nodes: Iterable[NRef],
prev_label: PortLabel='prev',
next_label: PortLabel='next'
):
nodes = list(nodes)
for prev_node, next_node in zip(nodes[:-1], nodes[1:]):
self.add_edge(prev_node, next_label, next_node, prev_label)
def inhibit_all_next(self, node: NRefs):
for n in as_iter(node):
self.as_node(n).inhibit_all_next()
# as_ functions
def as_nodeid(self, nref: NRef) -> Union[NodeId, None]:
return as_nodeid(nref)
def as_nodeids(self, nrefs: NRefs) -> Set[NodeId]:
return as_nodeids(nrefs)
def as_node(self, nref: NRef) -> Union[Node, None]:
return as_node(self, nref)
def as_nodes(self, nrefs: NRefs) -> Iterable[Node]:
return as_nodes(self, nrefs)
def as_nodeclasses(self, crefs: Union[CRefs, None]) -> List[Type[Node]]:
return [self.as_nodeclass(cref) for cref in as_iter(crefs)]
def as_nodeclass(self, cref: CRef) -> Type[Node]:
if isclass(cref):
assert issubclass(cref, Node)
return cref
elif is_nodeid(cref):
node = self.as_node(cref)
if not node:
raise NoSuchNode(node)
return node.__class__
elif isinstance(cref, str):
try:
return self.nodeclasses[cref]
except KeyError:
raise NoSuchNodeclass(cref)
elif isinstance(cref, Node):
return cref.__class__
raise ValueError(
f'{cref} is not a CRef (i.e. does not specify a nodeclass)'
)
def is_nref(self, x: Any) -> bool:
'''Is x a reference to a Node, i.e. a nodeid or a Node object? Returns
True even if x is not a node in the graph (e.g. if x is a deleted node
or a Node that hasn't yet been given an id).'''
return is_nodeid(x) or isinstance(x, Node)
def is_nrefs(self, x: Any) -> bool:
'''Is x a reference to zero or more Nodes, as defined by .is_nref()?
Returns True if x is itself a Node reference or if x is an iterable
containing only Node references. Hence returns True if x is an empty
list or tuple.'''
if self.is_nref(x):
return True
if is_iter(x):
return all(self.is_nref(elem) for elem in x)
return False
# Node-building
def already_built(
self,
nodeclas: Union[Type[Node], MaybeNRef],
*args, # ignored if nodeclas is a Node
**kwargs # ignored if nodeclas is a Node
) -> Union[Node, None]:
'''Returns None if the specified node is not already built, or the Node
if it is. If kwargs provides a non-false value for 'copy_of', we
automatically return None. A nodeclass with .is_duplicable == True is
never deemed already built. If nodeclas is a Node object, we look for
existing nodes with the same class and parameters, getting the Node
object's parameters by calling its .regen_kwargs() method.'''
if kwargs.get('copy_of', None):
return None
if not nodeclas:
return None
if is_nodeid(nodeclas):
nodeclas = self.as_node(nodeclas)
if isinstance(nodeclas, Node):
args = ()
kwargs = nodeclas.regen_kwargs()
nodeclas = nodeclas.__class__
if nodeclas.is_duplicable:
return None
filled_params = nodeclas.make_filled_params(self, *args, **kwargs)
filled_params.remove_ignored_for_dupcheck(nodeclas)
if filled_params.specifies_mates():
candidates = self.neighbors(filled_params.potential_neighbors())
else:
candidates = self.nodes()
# TODO Refactor so that the (possible) generator in 'candidates'
# never gets assigned to a named variable. (Good practice?)
result = self.as_node(first(
candidate
for candidate in candidates
if (
self.class_of(candidate) is nodeclas
and
filled_params.is_match(self, nodeclas, candidate)
)
))
#print('ALREADY', nodeclas, result)
return result
def auto_link(self, from_node: NRef, port_label: PortLabel, to_node: NRef):
'''Links from_node.port_label to to_node at appropriate port_label
for to_node, or throws an exception.'''
self.port_mates.auto_link(self, from_node, port_label, to_node)
def add_implicit_membership(self, node: Node):
'''If nodeid has no member_of link, add link to the "lowest common
denominator" member_of all its neighbors.'''
if self.has_neighbor_at(node, 'member_of'):
return
container_sets: Set[Set[NRef]] = set()
for n1 in self.neighbors(node):
n1_containers = self.containers_of_recursive(n1)
if n1_containers:
container_sets.add(frozenset(n1_containers))
containers = intersection(*container_sets)
containers.discard(as_nodeid(node))
for c in containers:
self.put_in_container(node, c)
def containers_of_recursive(self, node: NRef) -> Set[NodeId]:
result = set()
for container in self.containers_of(node):
result.add(container)
result |= self.containers_of_recursive(container)
return result
def containers_of(self, node: NRef) -> Set[NodeId]:
return self.neighbors(node, 'member_of')
# TODO Specify tag_port_label and/or infer it
def add_tag(self, tag: MaybeCRef, node: NRefs) \
-> MaybeNRef:
if isclass(tag) or isinstance(tag, str):
#assert tag.is_tag
return self.add_node(tag, taggees=node)
elif tag is None:
return
else:
assert is_nodeid(tag) or isinstance(tag, Node)
#TODO UT
if not self.has_node(tag):
return self.add_node(tag, taggees=node)
else:
self.add_edge(tag, 'taggees', node, 'tags')
return tag
def copy_node(self, old_node: NRef, **kwargs):
# HACK Should be deepcopy, but getting an error: NoneType is not
# callable.
old_node = self.as_node(old_node)
datum = copy(old_node)
return self.add_node(datum, copy_of=old_node.id, **kwargs)
def copy_group(
self,
original_group_node: NRef,
destination_group_node: NRef
) -> Union[NodeId, None]:
# TODO Handle case where nothing gets copied, or disallow it.
'''Returns nodeid of new group node.'''
d = {} # Maps source nodes to new nodes
original_group_node = self.as_nodeid(original_group_node)
destination_group_node = self.as_nodeid(destination_group_node)
# Copy the nodes
old_nodeids = (
self.members_recursive(original_group_node)
|
{original_group_node}
)
for old_nodeid in old_nodeids:
d[old_nodeid] = self.copy_node(old_nodeid)
# Link to destination_group_node
self.add_edge(
d[original_group_node], 'member_of',
destination_group_node, 'members'
)
# Copy the edges
for old_nodeid, new_node in d.items():
for hop in self.hops_from_node(old_nodeid):
try:
new_mate = d[hop.to_node]
except KeyError:
continue
self.add_edge(
new_node, hop.from_port_label, new_mate, hop.to_port_label,
weight=self._hop_weight(hop)
)
return d[original_group_node]
def add_next_member(
self,
group: NRef,
nspec: Union[Type[Node], Node, str],
*args,
**kwargs
) -> Node:
lm = self.last_member(group)
node = self.add_node(nspec, *args, **kwargs, member_of=group)
self.add_edge(lm, 'next', node, 'prev')
return node
# TODO UT
def last_member(self, group: MaybeNRef) -> MaybeNRef:
return self.look_for(NoMate('next'), subset=self.members_of(group))
def mark_builder(self, built_node: MaybeNRef, builder: MaybeNRef):
self.add_edge(built_node, 'built_by', builder, 'built')
# Interrogating nodes
def class_of(self, node: NRef) -> Union[Type[Node], None]:
'''Returns None if node does not exist.'''
datum = self.datum(node)
if datum is None:
return None
else:
return datum.__class__
#TODO UT
def is_of_class(self, nrefs: NRefs, nodeclasses: CRefs) -> bool:
'''Returns True iff all nodes referenced are instances of any the
nodeclasses referenced. Returns False if there are no node references
or no nodeclasses.'''
nodes = as_list(self.as_nodes(nrefs))
if not nodes:
return False
try:
nodeclasses = self.as_nodeclasses(nodeclasses)
except NoSuchNodeclass:
return False
if not nodeclasses:
return False
return all(
any(isinstance(node, cl) for cl in nodeclasses)
for node in nodes
)
# TODO UT
def node_isa(
self,
nrefs: NRefs,
specs: Union[CRefs, Node]
) -> bool:
'''Does every node in 'nrefs' match 'specs'? False if nrefs is
empty or contains a non-existent node.
If specs is a Node object without an id, we match against class,
allowing inheritance, and against attributes; we ignore mates.
Otherwise we match against *any* nodeclass indicated by 'specs'.
'''
nodes = as_list(self.as_nodes(nrefs))
if not nodes:
return False
nodeclasses = self.as_nodeclasses(specs)
if not nodeclasses:
return False
for node in as_iter(nodes):
if not any(isinstance(node, cl) for cl in nodeclasses):
return False
if isinstance(node, Node) and node.id is None:
raise NotImplementedError
return True
def is_member(self, node: NRefs, container_node: NRefs):
return self.has_hop(container_node, 'members', node, 'member_of')
def value_of(self, nref: NRef, attr_name: str='value') -> Any:
try:
return getattr(self.as_node(nref), attr_name)
except AttributeError:
return None
def has_tag(
self,
nodes: NRefs,
tagclass: Union[Type[Node], NodeId, Node, str]='Tag',
#taggee_port_label: PortLabel='tags'
**kwargs
) -> bool:
'''Returns True iff all the nodes have the given tag.'''
# TODO Document kwargs
return all(
self._has_tag(node, tagclass, **kwargs)
for node in as_iter(nodes)
)
# OLD
# if isinstance(tagclass, str):
# try:
# tagclass = self.as_nodeclass(tagclass)
# except NoSuchNodeclass:
# if tagclass == 'Failed' or tagclass == 'Blocked':
# return False
# else:
# raise
#
# if isclass(tagclass):
# return all(
# self.has_neighbor_at(
# n, port_label=taggee_port_label, neighbor_class=tagclass
# )
# for n in as_iter(node)
# )
# else: #tagclass is actually a node, not a class
# if isinstance(tagclass, Node) and tagclass.id is None:
# # tagclass is just a Node object to compare against, not
# # an actual node in the graph.
# return all(
# self.at_least_one_eq_node(
# tagclass,
# self.neighbors(n, port_label=taggee_port_label)
# ) for n in as_iter(node)
# )
# else:
# tagid = self.as_nodeid(tagclass)
# return all(
# tagid in self.neighbors(n, port_label=taggee_port_label)
# for n in as_iter(node)
# )
def _has_tag(
self,
node: MaybeNRef,
tagclass: Union[Type[Node], NodeId, Node, str]='Tag',
**kwargs
) -> bool:
'''Like .has_tag() but looks only at a single node.'''
if not kwargs:
kwargs = {'taggees': self.as_nodeid(node)}
return any(self.nb_match(tag, **kwargs)
for tag in self.tags_of(node, tagclass)
)
def nb_match(self, node: MaybeNRef, **kwargs) -> bool:
'''Neighborhood match.''' #TODO Document better.
node = self.as_node(node)
if not node:
return False
for port_label, neighbor in kwargs.items():
if neighbor:
if not as_nodeids(neighbor).intersection(
self.neighbors(node, port_label=port_label)
):
return False
else: # if neighbor is unspecified, match any neighbor
if not self.neighbor(node, port_label=port_label):
return False
return True
def at_least_one_eq_node(self, nobject: Node, candidates: NRefs) -> bool:
'''Returns True if at least one member of candidates == nobject.
It's OK if nobject does not exist in the graph or does not have an id.
We are only comparing against a Node object, not necessarily an
actual node in the graph.'''
for c in as_iter(candidates):
#print('ATL', nobject, c, self.as_node(c), nobject == self.as_node(c))
if nobject == self.as_node(c):
return True
else:
return False
def is_tag(self, node: NRefs) -> bool:
return all(n and n.is_tag for n in self.as_nodes(node))
def builder_of(self, node: MaybeNRef):
return self.neighbor(node, port_label='built_by')
def is_built_by(self, node: NRefs, builder_node: MaybeNRef) -> bool:
'''Was node built by builder_node, as shown in the graph?'''
return all(
self.has_edge(n, 'built_by', builder_node, 'built')
for n in self.as_nodes(node)
)
#TODO UT
def has_neighbor_at(
self,
node: NRefs,
port_label: PortLabels = None,
neighbor_class: Union[Type[Node], NRef] = None,
neighbor_label: PortLabels = None
) -> bool:
'''Returns True if at least one node given has a neighbor with the
specified characteristics.'''
# INEFFICIENT Instead of calling .neighbors(), should stop searching
# at first match.
return bool(self.neighbors(
node, port_label, neighbor_class, neighbor_label
))
def add_override_node(
self,
node: NRef,
port_label: PortLabel,
overriding_node: NRef
):
'''Adds an edge from node.port_label to overriding_node.overriding.
This signifies that overriding_node should be the value of the
argument named port_label when running any Action inside node.'''
self.add_edge(node, port_label, overriding_node, 'overriding')
def get_overrides(
self,
node: NRef,
names: Union[str, Iterable[str], None]
) -> Dict[str, Any]:
result = {}
for name in as_iter(names):
if self.is_plural_port_label(name):
result[name] = self.neighbors(node, port_label=name)
else:
n = self.neighbor(node, port_label=name)
if n:
if name == 'value': # HACK
result[name] = self.value_of(n)
else:
result[name] = n
return result
def is_plural_port_label(self, port_label: PortLabel) -> bool:
# Numbo-specific HACK
return port_label == 'consume_operands'
# Querying the graph
# TODO Better: Pass OfClass to .nodes()
def nodes_of_class(
self,
cls: Iterable[Union[Type[Node], Type[Action]]],
nodes: NRefs=None
) -> List[NRef]:
result = []
if nodes is None:
nodes = self.nodes()
for node in nodes:
for cl in as_iter(cls):
if issubclass(cl, Node):
if isinstance(self.as_node(node), cl):
result.append(node)
else:
assert issubclass(cl, Action)
if (
isinstance(self.as_node(node), ActionNode)
and
isinstance(self.getattr(node, 'action'), cl)
):
result.append(node)
return result
def node_of_class(self, cl: Type[Node], nodes=None) -> MaybeNRef:
# TODO Choose in a more principled way. And maybe call look_for()
# to do the search.
if nodes is None:
nodes = self.nodes()
for node in as_iter(nodes):
if self.is_of_class(node, cl):
return node
return None
def choose_by_activation(
self,
nodes_or_tups: Union[List[NodeId], List[Tuple[NodeId]]]
) -> MaybeNRef:
# if not nodes_or_tups:
# return None
# return choices(nodes_or_tups, self.activations_of(nodes_or_tups))[0]
d = dict(
(nodeid, self.activation(nodeid))
for nodeid in self._uniq_in_tups(nodes_or_tups)
)
return self.choose_by_dict_weight(nodes_or_tups, d)
def _uniq_in_tups(
self,
nodes_or_tups: Union[List[NodeId], List[Tuple[NodeId]]]
) -> Iterable[NodeId]:
if isinstance(nodes_or_tups[0], tuple):
return set(
x
for tup in nodes_or_tups
for x in tup
)
else:
return nodes_or_tups
def choose_by_dict_weight(
self,
nodes_or_tups: Union[List[NodeId], List[Tuple[NodeId]]],
d: Dict[NodeId, float]
) -> MaybeNRef:
if not nodes_or_tups:
return None
weights = list(reweight(self._weighted(nodes_or_tups, d), s=0.78))
# print('CBDW', nodes_or_tups, weights)
# for nt, w in zip(nodes_or_tups, weights):
# print(f' {nt} {w:.3f}')
return choices(nodes_or_tups, weights)[0]
def _weighted(
self,
nodes_or_tups: Union[List[NodeId], List[Tuple[NodeId]]],
d: Dict[NodeId, float]
) -> List[float]:
if not nodes_or_tups:
return []