-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdirected_hypergraph.py
More file actions
1524 lines (1240 loc) · 62.6 KB
/
Copy pathdirected_hypergraph.py
File metadata and controls
1524 lines (1240 loc) · 62.6 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
"""
.. module:: directed_hypergraph
:synopsis: Defines DirectedHypergraph class for the basic properties
of a directed hypergraph, along with the relevant structures
regarding nodes, hyperedges, adjacency, etc.
"""
import copy
class DirectedHypergraph(object):
"""
The DirectedHypergraph class provides a directed hypergraph object
and associated functions for basic properties of directed hypergraphs.
A directed hypergraph contains nodes and hyperedges. Each hyperedge
connects a tail set of nodes to a head set of nodes. The tail and head
cannot both be empty.
A node is simply any hashable type. See "add_node" or "add_nodes" for
more details.
A directed hyperedge is a tuple of the tail nodes and the head nodes.
This class assigns (upon adding) and refers to each hyperedge by an
internal ID. See "add_hyperedge" or "add_hyperedges" for more details.
Self-loops are allowed, but parallel (multi) hyperedges are not.
:note: This class uses several data structures to store a directed
hypergraph. Since these structures must stay in sync (see: __init__),
we highly recommend that only the public methods be used for accessing
and modifying the hypergraph.
Examples:
Create an empty directed hypergraph (no nodes or hyperedges):
>>> H = DirectedHypergraph()
Add nodes (with or without attributes) to the hypergraph
one at a time (see: add_node) or several at a time (see: add_nodes):
>>> H.add_nodes(["A", "B", "C", "D"], {color: "black"})
Add hyperedges (with or without attributes) to the hypergraph one
at a time (see: add_hyperedge) or several at a time (see: add_hyperedges):
>>> H.add_hyperedges((["A"], ["B"]), (["A", "B"], ["C", "D"]))
Update attributes of existing nodes and hyperedges by simulating adding the
node or hyperedge again, with the [potentially new] attribute appended:
>>> H.add_node("A", label="sink")
>>> H.add_hyperedge((["A", "B"], ["C", "D"]), weight=5)
"""
def __init__(self):
"""Constructor for the DirectedHypergraph class.
Initializes all internal data structures used for the rapid
execution of most of the fundamental hypergraph queries.
"""
# _node_attributes: a dictionary mapping a node (any hashable type)
# to a dictionary of attributes of that node.
#
# Provides O(1) time access to the attributes of a node.
#
# Used in the implementation of methods such as add_node and
# get_node_attributes.
#
self._node_attributes = {}
# _hyperedge_attributes: a dictionary mapping a hyperedge ID
# (initially created by the call to add_hyperedge or add_hyperedges)
# to a dictionary of attributes of that hyperedge.
# Given a hyperedge ID, _hyperedge_attributes[hyperedge_id] stores
# the tail of the hyperedge as specified by the user (as "tail"),
# the head of the hyperedge as specified by the user (as "head"),
# and the weight of the hyperedge (as "weight").
# For internal purposes, it also stores the frozenset versions of
# the tail and head (as "__frozen_tail" and "__frozen_head").
#
# Provides O(1) time access to the attributes of a hyperedge.
#
# Used in the implementation of methods such as add_hyperedge and
# get_hyperedge_attributes.
#
self._hyperedge_attributes = {}
# The forward star of a node is the set of hyperedges such that the
# node is in the tail of each hyperedge in that set.
#
# _forward_star: a dictionary mapping a node to the set of hyperedges
# that are in that node's forward star.
#
# Provides O(1) time access to a reference to the set of outgoing
# hyperedges from a node.
#
# Used in the implementation of methods such as add_node and
# remove_hyperedge.
#
self._forward_star = {}
# The backward star of a node is the set of hyperedges such that the
# node is in the head of each hyperedge in that set.
#
# _backward_star: a dictionary mapping a node to the set of hyperedges
# that are in that node's backward star.
#
# Provides O(1) time access to a reference to the set of incoming
# hyperedges from a node.
#
# Used in the implementation of methods such as add_node and
# remove_hyperedge.
#
self._backward_star = {}
# _successors: a 2-dimensional dictionary mapping (first) a tail set
# and (second) a head set of a hyperedge to the ID of the corresponding
# hyperedge. We represent each tail set and each head set by a
# frozenset, so that the structure is hashable.
#
# Provides O(1) time access to the ID of the of the hyperedge
# connecting a specific tail frozenset to a specific head frozenset.
# Given a tail frozenset, it also provides O(1) time access to a
# reference to the dictionary mapping head frozensets to hyperedge IDs;
# these hyperedges are precisely those in the forward star of this
# tail frozenset.
#
self._successors = {}
# _predecessors: a 2-dimensional dictionary mapping (first) a head set
# and (second) a tail set of a hyperedge to the ID of the corresponding
# hyperedge. We represent each tail set and each head set by a
# frozenset, so that the structure is hashable.
#
# Provides O(1) time access to the ID of the of the hyperedge
# connecting a specific head frozenset to a specific tail frozenset.
# Given a head frozenset, it also provides O(1) time access to a
# reference to the dictionary mapping tail frozensets to hyperedge IDs;
# these hyperedges are precisely those in the backward star of this
# head frozenset.
#
self._predecessors = {}
# _current_hyperedge_id: an int representing the hyperedge ID that
# was most recently assigned by the class (since users don't
# name/ID their own hyperedges); hyperedges being added are issued
# ID "e"+_current_hyperedge_id.
#
# Since the class takes responsibility for giving hyperedges
# their IDs (i.e. a unique identifier; could be alternatively viewed
# as a unique name, label, etc.), the issued IDs need to be kept
# track of. A consecutive issuing of integer IDs to the hyperedges is a
# simple strategy to ensure their uniqueness and allow for
# intuitive readability.
#
# e.g., _current_hyperedge_id = 4 implies that 4 hyperedges have
# been added to the hypergraph, and that "e4" was the most recently
# assigned hyperedge.
#
# Note: An hyperedge, once added, will receive a unique ID. If this
# hyperedge is removed and subsequently re-added, it will not receive
# the same ID as it was issued when it was originally added.
#
self._current_hyperedge_id = 0
def _combine_attribute_arguments(self, attr_dict, attr):
"""Combines attr_dict and attr dictionaries, by updating attr_dict
with attr.
:param attr_dict: dictionary of attributes of the node.
:param attr: keyword arguments of attributes of the node;
attr's values will override attr_dict's values
if both are provided.
:returns: dict -- single dictionary of [combined] attributes.
:raises: AttributeError -- attr_dict argument must be a dictionary.
"""
# If no attribute dict was passed, treat the keyword
# arguments as the dict
if attr_dict is None:
attr_dict = attr
# Otherwise, combine the passed attribute dict with
# the keyword arguments
else:
try:
attr_dict.update(attr)
except AttributeError:
raise AttributeError("attr_dict argument \
must be a dictionary.")
return attr_dict
def has_node(self, node):
"""Determines if a specific node is present in the hypergraph.
:param node: reference to the node whose presence is being checked.
:returns: bool -- true iff the node exists in the hypergraph.
"""
return node in self._node_attributes
def add_node(self, node, attr_dict=None, **attr):
"""Adds a node to the graph, along with any related attributes
of the node.
:param node: reference to the node being added.
:param attr_dict: dictionary of attributes of the node.
:param attr: keyword arguments of attributes of the node;
attr's values will override attr_dict's values
if both are provided.
Examples:
::
>>> H = DirectedHypergraph()
>>> attributes = {label: "positive"}
>>> H.add_node("A", attributes)
>>> H.add_node("B", label="negative")
>>> H.add_node("C", attributes, root=True)
"""
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
# If the node hasn't previously been added, add it along
# with its attributes
if not self.has_node(node):
self._node_attributes[node] = attr_dict
self._forward_star[node] = set()
self._backward_star[node] = set()
# Otherwise, just update the node's attributes
else:
self._node_attributes[node].update(attr_dict)
def add_nodes(self, nodes, attr_dict=None, **attr):
"""Adds multiple nodes to the graph, along with any related attributes
of the nodes.
:param nodes: iterable container to either references of the nodes
OR tuples of (node reference, attribute dictionary);
if an attribute dictionary is provided in the tuple,
its values will override both attr_dict's and attr's
values.
:param attr_dict: dictionary of attributes shared by all the nodes.
:param attr: keyword arguments of attributes of the node;
attr's values will override attr_dict's values
if both are provided.
See also:
add_node
Examples:
::
>>> H = DirectedHypergraph()
>>> attributes = {label: "positive"}
>>> node_list = ["A",
("B", {label="negative"}),
("C", {root=True})]
>>> H.add_nodes(node_list, attributes)
"""
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
for node in nodes:
# Note: This won't behave properly if the node is actually a tuple
if type(node) is tuple:
# See ("B", {label="negative"}) in the documentation example
new_node, node_attr_dict = node
# Create a new dictionary and load it with node_attr_dict and
# attr_dict, with the former (node_attr_dict) taking precedence
new_dict = attr_dict.copy()
new_dict.update(node_attr_dict)
self.add_node(new_node, new_dict)
else:
# See "A" in the documentation example
self.add_node(node, attr_dict.copy())
def remove_node(self, node):
"""Removes a node and its attributes from the hypergraph. Removes
every hyperedge that contains this node in either the head or the tail.
:param node: reference to the node being added.
:raises: ValueError -- No such node exists.
Examples:
::
>>> H = DirectedHypergraph()
>>> H.add_node("A", label="positive")
>>> H.remove_node("A")
"""
if not self.has_node(node):
raise ValueError("No such node exists.")
# Remove every hyperedge which is in the forward star of the node
forward_star = self.get_forward_star(node)
for hyperedge_id in forward_star:
self.remove_hyperedge(hyperedge_id)
# Remove every hyperedge which is in the backward star of the node
# but that is not also in the forward start of the node (to handle
# overlapping hyperedges)
backward_star = self.get_backward_star(node)
for hyperedge_id in backward_star - forward_star:
self.remove_hyperedge(hyperedge_id)
# Remove node's forward and backward star
del self._forward_star[node]
del self._backward_star[node]
# Remove node's attributes dictionary
del self._node_attributes[node]
def remove_nodes(self, nodes):
"""Removes multiple nodes and their attributes from the graph. If
the nodes are part of any hyperedges, those hyperedges are removed
as well.
:param nodes: iterable container to either references of the nodes
OR tuples of (node reference, attribute dictionary);
if an attribute dictionary is provided in the tuple,
its values will override both attr_dict's and attr's
values.
See also:
remove_node
Examples:
::
>>> H = DirectedHypergraph()
>>> attributes = {label: "positive"}
>>> node_list = ["A",
("B", {label="negative"}),
("C", {root=True})]
>>> H.add_nodes(node_list, attributes)
>>> H.remove_nodes(["A", "B", "C"])
"""
for node in nodes:
self.remove_node(node)
def get_node_set(self):
"""Returns the set of nodes that are currently in the hypergraph.
:returns: set -- all nodes currently in the hypergraph
"""
return set(self._node_attributes.keys())
def node_iterator(self):
"""Provides an iterator over the nodes.
"""
return iter(self._node_attributes)
def get_node_attribute(self, node, attribute_name):
"""Given a node and the name of an attribute, get a copy
of that node's attribute.
:param node: reference to the node to retrieve the attribute of.
:param attribute_name: name of the attribute to retrieve.
:returns: attribute value of the attribute_name key for the
specified node.
:raises: ValueError -- No such node exists.
:raises: ValueError -- No such attribute exists.
"""
if not self.has_node(node):
raise ValueError("No such node exists.")
elif attribute_name not in self._node_attributes[node]:
raise ValueError("No such attribute exists.")
else:
return copy.\
copy(self._node_attributes[node][attribute_name])
def get_node_attributes(self, node):
"""Given a node, get a dictionary with copies of that node's
attributes.
:param node: reference to the node to retrieve the attributes of.
:returns: dict -- copy of each attribute of the specified node.
:raises: ValueError -- No such node exists.
"""
if not self.has_node(node):
raise ValueError("No such node exists.")
attributes = {}
for attr_name, attr_value in self._node_attributes[node].items():
attributes[attr_name] = copy.copy(attr_value)
return attributes
def _assign_next_hyperedge_id(self):
"""Returns the next [consecutive] ID to be assigned
to a hyperedge.
:returns: str -- hyperedge ID to be assigned.
"""
self._current_hyperedge_id += 1
return "hyperedge" + str(self._current_hyperedge_id)
def add_hyperedge(self, tail, head, attr_dict=None, **attr):
"""Adds a hyperedge to the hypergraph, along with any related
attributes of the hyperedge.
This method will automatically add any node from the tail and
head that was not in the hypergraph.
A hyperedge without a "weight" attribute specified will be
assigned the default value of 1.
:param tail: iterable container of references to nodes in the
tail of the hyperedge to be added.
:param head: iterable container of references to nodes in the
head of the hyperedge to be added.
:param attr_dict: dictionary of attributes shared by all
the hyperedges.
:param attr: keyword arguments of attributes of the hyperedge;
attr's values will override attr_dict's values
if both are provided.
:returns: str -- the ID of the hyperedge that was added.
:raises: ValueError -- tail and head arguments cannot both be empty.
Examples:
::
>>> H = DirectedHypergraph()
>>> x = H.add_hyperedge(["A", "B"], ["C", "D"])
>>> y = H.add_hyperedge(("A", "C"), ("B"), 'weight'=2)
>>> z = H.add_hyperedge(set(["D"]),
set(["A", "C"]),
{color: "red"})
"""
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
# Don't allow both empty tail and head containers (invalid hyperedge)
if not tail and not head:
raise ValueError("tail and head arguments \
cannot both be empty.")
# Use frozensets for tail and head sets to allow for hashable keys
frozen_tail = frozenset(tail)
frozen_head = frozenset(head)
# Initialize a successor dictionary for the tail and head, respectively
if frozen_tail not in self._successors:
self._successors[frozen_tail] = {}
if frozen_head not in self._predecessors:
self._predecessors[frozen_head] = {}
is_new_hyperedge = not self.has_hyperedge(frozen_tail, frozen_head)
if is_new_hyperedge:
# Add tail and head nodes to graph (if not already present)
self.add_nodes(frozen_head)
self.add_nodes(frozen_tail)
# Create new hyperedge name to use as reference for that hyperedge
hyperedge_id = self._assign_next_hyperedge_id()
# Add hyperedge to the forward-star and to the backward-star
# for each node in the tail and head sets, respectively
for node in frozen_tail:
self._forward_star[node].add(hyperedge_id)
for node in frozen_head:
self._backward_star[node].add(hyperedge_id)
# Add the hyperedge as the successors and predecessors
# of the tail set and head set, respectively
self._successors[frozen_tail][frozen_head] = hyperedge_id
self._predecessors[frozen_head][frozen_tail] = hyperedge_id
# Assign some special attributes to this hyperedge. We assign
# a default weight of 1 to the hyperedge. We also store the
# original tail and head sets in order to return them exactly
# as the user passed them into add_hyperedge.
self._hyperedge_attributes[hyperedge_id] = \
{"tail": tail, "__frozen_tail": frozen_tail,
"head": head, "__frozen_head": frozen_head,
"weight": 1}
else:
# If its not a new hyperedge, just get its ID to update attributes
hyperedge_id = self._successors[frozen_tail][frozen_head]
# Set attributes and return hyperedge ID
self._hyperedge_attributes[hyperedge_id].update(attr_dict)
return hyperedge_id
def add_hyperedges(self, hyperedges, attr_dict=None, **attr):
"""Adds multiple hyperedges to the graph, along with any related
attributes of the hyperedges.
If any node in the tail or head of any hyperedge has not
previously been added to the hypergraph, it will automatically
be added here. Hyperedges without a "weight" attribute specified
will be assigned the default value of 1.
:param hyperedges: iterable container to either tuples of
(tail reference, head reference) OR tuples of
(tail reference, head reference, attribute dictionary);
if an attribute dictionary is provided in the tuple,
its values will override both attr_dict's and attr's
values.
:param attr_dict: dictionary of attributes shared by all
the hyperedges.
:param attr: keyword arguments of attributes of the hyperedges;
attr's values will override attr_dict's values
if both are provided.
:returns: list -- the IDs of the hyperedges added in the order
specified by the hyperedges container's iterator.
See also:
add_hyperedge
Examples:
::
>>> H = DirectedHypergraph()
>>> xyz = hyperedge_list = ((["A", "B"], ["C", "D"]),
(("A", "C"), ("B"), {'weight': 2}),
(set(["D"]), set(["A", "C"])))
>>> H.add_hyperedges(hyperedge_list)
"""
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
hyperedge_ids = []
for hyperedge in hyperedges:
if len(hyperedge) == 3:
# See ("A", "C"), ("B"), {weight: 2}) in the
# documentation example
tail, head, hyperedge_attr_dict = hyperedge
# Create a new dictionary and load it with node_attr_dict and
# attr_dict, with the former (node_attr_dict) taking precedence
new_dict = attr_dict.copy()
new_dict.update(hyperedge_attr_dict)
hyperedge_id = self.add_hyperedge(tail, head, new_dict)
else:
# See (["A", "B"], ["C", "D"]) in the documentation example
tail, head = hyperedge
hyperedge_id = \
self.add_hyperedge(tail, head, attr_dict.copy())
hyperedge_ids.append(hyperedge_id)
return hyperedge_ids
def remove_hyperedge(self, hyperedge_id):
"""Removes a hyperedge and its attributes from the hypergraph.
:param hyperedge_id: ID of the hyperedge to be removed.
:raises: ValueError -- No such hyperedge exists.
Examples:
::
>>> H = DirectedHypergraph()
>>> xyz = hyperedge_list = ((["A"], ["B", "C"]),
(("A", "B"), ("C"), {'weight': 2}),
(set(["B"]), set(["A", "C"])))
>>> H.add_hyperedges(hyperedge_list)
>>> H.remove_hyperedge(xyz[0])
"""
if not self.has_hyperedge_id(hyperedge_id):
raise ValueError("No such hyperedge exists.")
frozen_tail = \
self._hyperedge_attributes[hyperedge_id]["__frozen_tail"]
frozen_head = \
self._hyperedge_attributes[hyperedge_id]["__frozen_head"]
# Remove this hyperedge from the forward-star of every tail node
for node in frozen_tail:
self._forward_star[node].remove(hyperedge_id)
# Remove this hyperedge from the backward-star of every head node
for node in frozen_head:
self._backward_star[node].remove(hyperedge_id)
# Remove frozen_head as a successor of frozen_tail
del self._successors[frozen_tail][frozen_head]
# If that tail is no longer the tail of any hyperedge, remove it
# from the successors dictionary
if self._successors[frozen_tail] == {}:
del self._successors[frozen_tail]
# Remove frozen_tail as a predecessor of frozen_head
del self._predecessors[frozen_head][frozen_tail]
# If that head is no longer the head of any hyperedge, remove it
# from the predecessors dictionary
if self._predecessors[frozen_head] == {}:
del self._predecessors[frozen_head]
# Remove hyperedge's attributes dictionary
del self._hyperedge_attributes[hyperedge_id]
def remove_hyperedges(self, hyperedge_ids):
"""Removes a set of hyperedges and their attributes from
the hypergraph.
:param hyperedge_ids: iterable container of IDs of the hyperedges
to be removed.
:raises: ValueError -- No such hyperedge exists.
See also:
remove_hyperedge
Examples:
::
>>> H = DirectedHypergraph()
>>> hyperedge_list = ((["A"], ["B", "C"]),
(("A", "B"), ("C"), {'weight': 2}),
(set(["B"]), set(["A", "C"])))
>>> hyperedge_ids = H.add_hyperedges(hyperedge_list)
>>> H.remove_hyperedges(hyperedge_ids)
"""
for hyperedge_id in hyperedge_ids:
self.remove_hyperedge(hyperedge_id)
def has_hyperedge(self, tail, head):
"""Given a tail and head set of nodes, returns whether there
is a hyperedge in the hypergraph that connects the tail set
to the head set.
:param tail: iterable container of references to nodes in the
tail of the hyperedge being checked.
:param head: iterable container of references to nodes in the
head of the hyperedge being checked.
:returns: bool -- true iff a hyperedge exists connecting the
specified tail set to the specified head set.
"""
frozen_tail = frozenset(tail)
frozen_head = frozenset(head)
return frozen_tail in self._successors and \
frozen_head in self._successors[frozen_tail]
def has_hyperedge_id(self, hyperedge_id):
"""Determines if a hyperedge referenced by hyperedge_id
exists in the hypergraph.
:param hyperedge_id: ID of the hyperedge whose existence is
being checked.
:returns: bool -- true iff a hyperedge exists that has id hyperedge_id.
"""
return hyperedge_id in self._hyperedge_attributes
def get_hyperedge_id_set(self):
"""Returns the set of IDs of hyperedges that are currently
in the hypergraph.
:returns: set -- all IDs of hyperedges currently in the hypergraph
"""
return set(self._hyperedge_attributes.keys())
def hyperedge_id_iterator(self):
"""Provides an iterator over the list of hyperedge IDs.
"""
return iter(self._hyperedge_attributes)
def get_hyperedge_id(self, tail, head):
"""From a tail and head set of nodes, returns the ID of the hyperedge
that these sets comprise.
:param tail: iterable container of references to nodes in the
tail of the hyperedge to be added
:param head: iterable container of references to nodes in the
head of the hyperedge to be added
:returns: str -- ID of the hyperedge that has that the specified
tail and head sets comprise.
:raises: ValueError -- No such hyperedge exists.
Examples:
::
>>> H = DirectedHypergraph()
>>> hyperedge_list = (["A"], ["B", "C"]),
(("A", "B"), ("C"), {weight: 2}),
(set(["B"]), set(["A", "C"])))
>>> hyperedge_ids = H.add_hyperedges(hyperedge_list)
>>> x = H.get_hyperedge_id(["A"], ["B", "C"])
"""
frozen_tail = frozenset(tail)
frozen_head = frozenset(head)
if not self.has_hyperedge(frozen_tail, frozen_head):
raise ValueError("No such hyperedge exists.")
return self._successors[frozen_tail][frozen_head]
def get_hyperedge_attribute(self, hyperedge_id, attribute_name):
"""Given a hyperedge ID and the name of an attribute, get a copy
of that hyperedge's attribute.
:param hyperedge_id: ID of the hyperedge to retrieve the attribute of.
:param attribute_name: name of the attribute to retrieve.
:returns: attribute value of the attribute_name key for the
specified hyperedge.
:raises: ValueError -- No such hyperedge exists.
:raises: ValueError -- No such attribute exists.
Examples:
::
>>> H = DirectedHypergraph()
>>> hyperedge_list = (["A"], ["B", "C"]),
(("A", "B"), ("C"), {weight: 2}),
(set(["B"]), set(["A", "C"])))
>>> hyperedge_ids = H.add_hyperedges(hyperedge_list)
>>> attribute = H.get_hyperedge_attribute(hyperedge_ids[0])
"""
if not self.has_hyperedge_id(hyperedge_id):
raise ValueError("No such hyperedge exists.")
elif attribute_name not in self._hyperedge_attributes[hyperedge_id]:
raise ValueError("No such attribute exists.")
else:
return copy.\
copy(self._hyperedge_attributes[hyperedge_id][attribute_name])
def get_hyperedge_attributes(self, hyperedge_id):
"""Given a hyperedge ID, get a dictionary of copies of that hyperedge's
attributes.
:param hyperedge_id: ID of the hyperedge to retrieve the attributes of.
:returns: dict -- copy of each attribute of the specified hyperedge_id
(except the private __frozen_tail and __frozen_head entries).
:raises: ValueError -- No such hyperedge exists.
"""
if not self.has_hyperedge_id(hyperedge_id):
raise ValueError("No such hyperedge exists.")
dict_to_copy = self._hyperedge_attributes[hyperedge_id].items()
attributes = {}
for attr_name, attr_value in dict_to_copy:
if attr_name not in ("__frozen_tail", "__frozen_head"):
attributes[attr_name] = copy.copy(attr_value)
return attributes
def get_hyperedge_tail(self, hyperedge_id):
"""Given a hyperedge ID, get a copy of that hyperedge's tail.
:param hyperedge_id: ID of the hyperedge to retrieve the tail from.
:returns: a copy of the container of nodes that the user provided
as the tail to the hyperedge referenced as hyperedge_id.
"""
return self.get_hyperedge_attribute(hyperedge_id, "tail")
def get_hyperedge_head(self, hyperedge_id):
"""Given a hyperedge ID, get a copy of that hyperedge's head.
:param hyperedge: ID of the hyperedge to retrieve the head from.
:returns: a copy of the container of nodes that the user provided
as the head to the hyperedge referenced as hyperedge_id.
"""
return self.get_hyperedge_attribute(hyperedge_id, "head")
def get_hyperedge_weight(self, hyperedge_id):
"""Given a hyperedge ID, get that hyperedge's weight.
:param hyperedge: ID of the hyperedge to retrieve the weight from.
:returns: a the weight of the hyperedge referenced as hyperedge_id.
"""
return self.get_hyperedge_attribute(hyperedge_id, "weight")
def get_forward_star(self, node):
"""Given a node, get a copy of that node's forward star.
:param node: node to retrieve the forward-star of.
:returns: set -- set of hyperedge_ids for the hyperedges
in the node's forward star.
:raises: ValueError -- No such node exists.
"""
if node not in self._node_attributes:
raise ValueError("No such node exists.")
return self._forward_star[node].copy()
def get_backward_star(self, node):
"""Given a node, get a copy of that node's backward star.
:param node: node to retrieve the backward-star of.
:returns: set -- set of hyperedge_ids for the hyperedges
in the node's backward star.
:raises: ValueError -- No such node exists.
"""
if node not in self._node_attributes:
raise ValueError("No such node exists.")
return self._backward_star[node].copy()
def get_successors(self, tail):
"""Given a tail set of nodes, get a list of edges of which the node
set is the tail of each edge.
:param tail: set of nodes that correspond to the tails of some
(possibly empty) set of edges.
:returns: set -- hyperedge_ids of the hyperedges that have tail
in the tail.
"""
frozen_tail = frozenset(tail)
# If this node set isn't any tail in the hypergraph, then it has
# no successors; thus, return an empty list
if frozen_tail not in self._successors:
return set()
return set(self._successors[frozen_tail].values())
def get_predecessors(self, head):
"""Given a head set of nodes, get a list of edges of which the node set
is the head of each edge.
:param head: set of nodes that correspond to the heads of some
(possibly empty) set of edges.
:returns: set -- hyperedge_ids of the hyperedges that have head
in the head.
"""
frozen_head = frozenset(head)
# If this node set isn't any head in the hypergraph, then it has
# no predecessors; thus, return an empty list
if frozen_head not in self._predecessors:
return set()
return set(self._predecessors[frozen_head].values())
# TODO: Make this a property of the hypergraph that stays updated with
# the hypergraph, for constant-time calls.
def is_B_hypergraph(self):
"""Indicates whether the hypergraph is a B-hypergraph.
In a B-hypergraph, all hyperedges are B-hyperedges -- that is, every
hyperedge has exactly one node in the head.
:returns: bool -- True iff the hypergraph is a B-hypergraph.
"""
for hyperedge_id in self._hyperedge_attributes:
head = self.get_hyperedge_head(hyperedge_id)
if len(head) > 1:
return False
return True
# TODO: Make this a property of the hypergraph that stays updated with
# the hypergraph, for constant-time calls.
def is_F_hypergraph(self):
"""Indicates whether the hypergraph is an F-hypergraph.
In an F-hypergraph, all hyperedges are F-hyperedges -- that is, every
hyperedge has exactly one node in the tail.
:returns: bool -- True iff the hypergraph is an F-hypergraph.
"""
for hyperedge_id in self._hyperedge_attributes:
tail = self.get_hyperedge_tail(hyperedge_id)
if len(tail) > 1:
return False
return True
# TODO: Make this a property of the hypergraph that stays updated with
# the hypergraph, for constant-time calls.
def is_BF_hypergraph(self):
"""Indicates whether the hypergraph is a BF-hypergraph.
A BF-hypergraph consists of only B-hyperedges and F-hyperedges.
See "is_B_hypergraph" or "is_F_hypergraph" for more details.
:returns: bool -- True iff the hypergraph is an F-hypergraph.
"""
for hyperedge_id in self._hyperedge_attributes:
tail = self.get_hyperedge_tail(hyperedge_id)
head = self.get_hyperedge_head(hyperedge_id)
if len(tail) > 1 and len(head) > 1:
return False
return True
def copy(self):
"""Creates a new DirectedHypergraph object with the same node and
hyperedge structure.
Copies of the nodes' and hyperedges' attributes are stored
and used in the new hypergraph.
:returns: DirectedHypergraph -- a new hypergraph that is a copy of
the current hypergraph
"""
return self.__copy__()
def __copy__(self):
"""Creates a new DirectedHypergraph object with the same node and
hyperedge structure.
Copies of the nodes' and hyperedges' attributes are stored
and used in the new hypergraph.
:returns: DirectedHypergraph -- a new hypergraph that is a copy of
the current hypergraph
"""
new_H = DirectedHypergraph()
# Loop over every node and its corresponding attribute dict
# in the original hypergraph's _node_attributes dict
for node, attr_dict in self._node_attributes.items():
# Create a new dict for that node to store that node's attributes
new_H._node_attributes[node] = {}
# Loop over each attribute of that node in the original hypergraph
# and, for each key, copy the corresponding value into the new
# hypergraph's dictionary using the same key
for attr_name, attr_value in attr_dict.items():
new_H._node_attributes[node][attr_name] = \
copy.copy(attr_value)
# Loop over every hyperedge_id and its corresponding attribute dict
# in the original hypergraph's _hyperedge_attributes dict
for hyperedge_id, attr_dict in self._hyperedge_attributes.items():
# Create a new dict for that node to store that node's attributes
new_H._hyperedge_attributes[hyperedge_id] = {}
# Loop over each attribute of that hyperedge in the original
# hypergraph and, for each key, copy the corresponding value
# the new hypergraph's dictionary
for attr_name, attr_value in attr_dict.items():
new_H.\
_hyperedge_attributes[hyperedge_id][attr_name] = \
copy.copy(attr_value)
# Copy the original hypergraph's forward star and backward star
new_H._backward_star = self._backward_star.copy()
for node in self._node_attributes.keys():
new_H._backward_star[node] = \
self._backward_star[node].copy()
new_H._forward_star[node] = \
self._forward_star[node].copy()
# Copy the original hypergraph's successors
for frozen_tail, successor_dict in self._successors.items():
new_H._successors[frozen_tail] = successor_dict.copy()
# Copy the original hypergraph's predecessors
for frozen_head, predecessor_dict in self._predecessors.items():
new_H._predecessors[frozen_head] = predecessor_dict.copy()
# Start assigning edge labels at the same
new_H._current_hyperedge_id = self._current_hyperedge_id
return new_H
def get_symmetric_image(self):
"""Creates a new DirectedHypergraph object that is the symmetric
image of this hypergraph (i.e., identical hypergraph with all
edge directions reversed).
Copies of each of the nodes' and hyperedges' attributes are stored
and used in the new hypergraph.
:returns: DirectedHypergraph -- a new hypergraph that is the symmetric
image of the current hypergraph.
"""
new_H = self.copy()
# No change to _node_attributes necessary, as nodes remain the same
# Reverse the tail and head (and __frozen_tail and __frozen_head) for
# every hyperedge
for hyperedge_id in self.get_hyperedge_id_set():
attr_dict = new_H._hyperedge_attributes[hyperedge_id]
attr_dict["tail"], attr_dict["head"] = \
attr_dict["head"], attr_dict["tail"]
attr_dict["__frozen_tail"], attr_dict["__frozen_head"] = \
attr_dict["__frozen_head"], attr_dict["__frozen_tail"]
# Reverse the definition of forward star and backward star
new_H._forward_star, new_H._backward_star = \
new_H._backward_star, new_H._forward_star
# Reverse the definition of successor and predecessor
new_H._successors, new_H._predecessors = \
new_H._predecessors, new_H._successors
return new_H
def get_induced_subhypergraph(self, nodes):
"""Gives a new hypergraph that is the subhypergraph of the current
hypergraph induced by the provided set of nodes. That is, the induced
subhypergraph's node set corresponds precisely to the nodes provided,
and the coressponding hyperedges in the subhypergraph are only those
from the original graph consist of tail and head sets that are subsets
of the provided nodes.
:param nodes: the set of nodes to find the induced subhypergraph of.
:returns: DirectedHypergraph -- the subhypergraph induced on the
provided nodes.
"""
sub_H = self.copy()
sub_H.remove_nodes(sub_H.get_node_set() - set(nodes))