forked from PaddlePaddle/PaddleRec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.py
1216 lines (957 loc) · 39.7 KB
/
graph.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
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
This package implement Graph structure for handling graph data.
"""
import os
import json
import copy
import warnings
from collections import defaultdict
import numpy as np
import paddle
from pgl.utils import op
import pgl.graph_kernel as graph_kernel
from pgl.message import Message
from pgl.utils.edge_index import EdgeIndex
from pgl.utils.helper import check_is_tensor, scatter, maybe_num_nodes
from pgl.utils.helper import generate_segment_id_from_index, unique_segment
try:
from paddle.incubate import graph_send_recv
except:
from pgl.utils.helper import graph_send_recv
class Graph(object):
"""Implementation of graph interface in pgl.
This is a simple implementation of graph structure in pgl.
`pgl.Graph` is an alias for `pgl.graph.Graph`
Args:
edges: list of (u, v) tuples, 2D numpy.ndarray or 2D paddle.Tensor.
num_nodes (optional: int, numpy or paddle.Tensor): Number of nodes in a graph.
If not provided, the number of nodes will be infered from edges.
node_feat (optional): a dict of numpy array as node features.
edge_feat (optional): a dict of numpy array as edge features (should
have consistent order with edges).
Examples 1:
- Create a graph with numpy.
- Convert it into paddle.Tensor.
- Do send recv for graph neural network.
.. code-block:: python
import numpy as np
import pgl
num_nodes = 5
edges = [ (0, 1), (1, 2), (3, 4)]
feature = np.random.randn(5, 100).astype(np.float32)
edge_feature = np.random.randn(3, 100).astype(np.float32)
graph = pgl.Graph(num_nodes=num_nodes,
edges=edges,
node_feat={
"feature": feature
},
edge_feat={
"edge_feature": edge_feature
})
graph.tensor()
model = pgl.nn.GCNConv(100, 100)
out = model(graph, graph.node_feat["feature"])
Examples 2:
- Create a graph with paddle.Tensor.
- Do send recv for graph neural network.
.. code-block:: python
import paddle
import pgl
num_nodes = 5
edges = paddle.to_tensor([ (0, 1), (1, 2), (3, 4)])
feature = paddle.randn(shape=[5, 100])
edge_feature = paddle.randn(shape=[3, 100])
graph = pgl.Graph(num_nodes=num_nodes,
edges=edges,
node_feat={
"feature": feature
},
edge_feat={
"edge_feature": edge_feature
})
model = pgl.nn.GCNConv(100, 100)
out = model(graph, graph.node_feat["feature"])
"""
def __init__(self,
edges,
num_nodes=None,
node_feat=None,
edge_feat=None,
**kwargs):
if node_feat is not None:
self._node_feat = node_feat
else:
self._node_feat = {}
if edge_feat is not None:
self._edge_feat = edge_feat
else:
self._edge_feat = {}
if not check_is_tensor(edges):
if isinstance(edges, np.ndarray):
if edges.dtype != "int64":
edges = edges.astype("int64")
else:
edges = np.array(edges, dtype="int64")
self._edges = edges
if num_nodes is None:
self._num_nodes = maybe_num_nodes(self._edges)
else:
self._num_nodes = num_nodes
self._adj_src_index = kwargs.get("adj_src_index", None)
self._adj_dst_index = kwargs.get("adj_dst_index", None)
if check_is_tensor(self._num_nodes, self._edges,
*list(self._node_feat.values()),
*list(self._edge_feat.values())):
self._is_tensor = True
elif self._adj_src_index is not None and self._adj_src_index.is_tensor(
):
self._is_tensor = True
elif self._adj_dst_index is not None and self._adj_dst_index.is_tensor(
):
self._is_tensor = True
else:
self._is_tensor = False
if self._is_tensor:
# ensure all variable is tenosr
if not check_is_tensor(self._num_nodes):
self._num_nodes = paddle.to_tensor(self._num_nodes)
if not check_is_tensor(self._edges):
self._edges = paddle.to_tensor(self._edges)
for key in self._node_feat:
if not check_is_tensor(self._node_feat[key]):
self._node_feat[key] = paddle.to_tensor(self._node_feat[
key])
for key in self._edge_feat:
if not check_is_tensor(self._edge_feat[key]):
self._edge_feat[key] = paddle.to_tensor(self._edge_feat[
key])
if self._adj_src_index is not None:
if not self._adj_src_index.is_tensor():
self._adj_src_index.tensor(inplace=True)
if self._adj_dst_index is not None:
if not self._adj_dst_index.is_tensor():
self._adj_dst_index.tensor(inplace=True)
# preprocess graph level informations
self._process_graph_info(**kwargs)
self._nodes = None
def recv(self, reduce_func, msg, recv_mode="dst"):
"""Recv message and aggregate the message by reduce_func.
The UDF reduce_func function should has the following format.
.. code-block:: python
def reduce_func(msg):
'''
Args:
msg: An instance of Message class.
Return:
It should return a tensor with shape (batch_size, out_dims).
'''
pass
Args:
msg: A dictionary of tensor created by send function..
reduce_func: A callable UDF reduce function.
Return:
A tensor with shape (num_nodes, out_dims). The output for nodes with
no message will be zeros.
"""
if not self._is_tensor:
raise ValueError("You must call Graph.tensor()")
if not isinstance(msg, dict):
raise TypeError(
"The input of msg should be a dict, but receives a %s" %
(type(msg)))
if not callable(reduce_func):
raise TypeError("reduce_func should be callable")
src, dst, eid = self.sorted_edges(sort_by=recv_mode)
msg = op.RowReader(msg, eid)
if (recv_mode == "dst") and (not hasattr(self, "_dst_uniq_ind")):
self._dst_uniq_ind, self._dst_segment_ids = unique_segment(dst)
if (recv_mode == "src") and (not hasattr(self, "_src_uniq_ind")):
self._src_uniq_ind, self._src_segment_ids = unique_segment(src)
if recv_mode == "dst":
uniq_ind, segment_ids = self._dst_uniq_ind, self._dst_segment_ids
elif recv_mode == "src":
uniq_ind, segment_ids = self._src_uniq_ind, self._src_segment_ids
bucketed_msg = Message(msg, segment_ids)
output = reduce_func(bucketed_msg)
output_dim = output.shape[-1]
init_output = paddle.zeros(
shape=[self._num_nodes, output_dim], dtype=output.dtype)
final_output = scatter(init_output, uniq_ind, output)
return final_output
@classmethod
def load(cls, path, mmap_mode="r"):
"""Load Graph from path and return a Graph in numpy.
Args:
path: The directory path of the stored Graph.
mmap_mode: Default :code:`mmap_mode="r"`. If not None, memory-map the graph.
"""
num_nodes = np.load(
os.path.join(path, 'num_nodes.npy'), mmap_mode=mmap_mode)
edges = np.load(os.path.join(path, 'edges.npy'), mmap_mode=mmap_mode)
num_graph = np.load(
os.path.join(path, 'num_graph.npy'), mmap_mode=mmap_mode)
if os.path.exists(os.path.join(path, 'graph_node_index.npy')):
graph_node_index = np.load(
os.path.join(path, 'graph_node_index.npy'),
mmap_mode=mmap_mode)
else:
graph_node_index = None
if os.path.exists(os.path.join(path, 'graph_edge_index.npy')):
graph_edge_index = np.load(
os.path.join(path, 'graph_edge_index.npy'),
mmap_mode=mmap_mode)
else:
graph_edge_index = None
if os.path.isdir(os.path.join(path, 'adj_src')):
adj_src_index = EdgeIndex.load(
os.path.join(path, 'adj_src'), mmap_mode=mmap_mode)
else:
adj_src_index = None
if os.path.isdir(os.path.join(path, 'adj_dst')):
adj_dst_index = EdgeIndex.load(
os.path.join(path, 'adj_dst'), mmap_mode=mmap_mode)
else:
adj_dst_index = None
def _load_feat(feat_path):
"""Load features from .npy file.
"""
feat = {}
if os.path.isdir(feat_path):
for feat_name in os.listdir(feat_path):
feat[os.path.splitext(feat_name)[0]] = np.load(
os.path.join(feat_path, feat_name),
mmap_mode=mmap_mode)
return feat
node_feat = _load_feat(os.path.join(path, 'node_feat'))
edge_feat = _load_feat(os.path.join(path, 'edge_feat'))
return cls(edges=edges,
num_nodes=num_nodes,
node_feat=node_feat,
edge_feat=edge_feat,
adj_src_index=adj_src_index,
adj_dst_index=adj_dst_index,
_num_graph=num_graph,
_graph_node_index=graph_node_index,
_graph_edge_index=graph_edge_index)
def is_tensor(self):
"""Return whether the Graph is in paddle.Tensor or numpy format.
"""
return self._is_tensor
def _apply_to_tensor(self, key, value, inplace=True):
if value is None:
return value
if key == '_is_tensor':
# set is_tensor to True
return True
if isinstance(value, EdgeIndex):
value = value.tensor(inplace=inplace)
elif isinstance(value, dict):
if inplace:
for k, v in value.items():
value[k] = paddle.to_tensor(v)
else:
new_value = {}
for k, v in value.items():
new_value[k] = paddle.to_tensor(v)
value = new_value
else:
value = paddle.to_tensor(value)
return value
def tensor(self, inplace=True):
"""Convert the Graph into paddle.Tensor format.
In paddle.Tensor format, the graph edges and node features are in paddle.Tensor format.
You can use send and recv in paddle.Tensor graph.
Args:
inplace: (Default True) Whether to convert the graph into tensor inplace.
"""
if self._is_tensor:
return self
if inplace:
for key in self.__dict__:
self.__dict__[key] = self._apply_to_tensor(
key, self.__dict__[key], inplace)
return self
else:
new_dict = {}
for key in self.__dict__:
new_dict[key] = self._apply_to_tensor(key, self.__dict__[key],
inplace)
graph = self.__class__(
num_nodes=new_dict["_num_nodes"],
edges=new_dict["_edges"],
node_feat=new_dict["_node_feat"],
edge_feat=new_dict["_edge_feat"],
adj_src_index=new_dict["_adj_src_index"],
adj_dst_index=new_dict["_adj_dst_index"],
**new_dict)
return graph
def _apply_to_numpy(self, key, value, inplace=True):
if value is None:
return value
if key == '_is_tensor':
# set is_tensor to True
return False
if isinstance(value, EdgeIndex):
value = value.numpy(inplace=inplace)
elif isinstance(value, dict):
if inplace:
for k, v in value.items():
value[k] = v.numpy()
else:
new_value = {}
for k, v in value.items():
new_value[k] = v.numpy()
value = new_value
else:
value = value.numpy()
return value
def numpy(self, inplace=True):
"""Convert the Graph into numpy format.
In numpy format, the graph edges and node features are in numpy.ndarray format.
But you can't use send and recv in numpy graph.
Args:
inplace: (Default True) Whether to convert the graph into numpy inplace.
"""
if not self._is_tensor:
return self
if inplace:
for key in self.__dict__:
self.__dict__[key] = self._apply_to_numpy(
key, self.__dict__[key], inplace)
return self
else:
new_dict = {}
for key in self.__dict__:
new_dict[key] = self._apply_to_numpy(key, self.__dict__[key],
inplace)
graph = self.__class__(
num_nodes=new_dict["_num_nodes"],
edges=new_dict["_edges"],
node_feat=new_dict["_node_feat"],
edge_feat=new_dict["_edge_feat"],
adj_src_index=new_dict["_adj_src_index"],
adj_dst_index=new_dict["_adj_dst_index"],
**new_dict)
return graph
def dump(self, path):
"""Dump the graph into a directory.
This function will dump the graph information into the given directory path.
The graph can be read back with :code:`pgl.Graph.load`
Args:
path: The directory for the storage of the graph.
"""
if self._is_tensor:
# Convert back into numpy and dump.
graph = self.numpy(inplace=False)
graph.dump(path)
else:
if not os.path.exists(path):
os.makedirs(path)
np.save(os.path.join(path, 'num_nodes.npy'), self._num_nodes)
np.save(os.path.join(path, 'edges.npy'), self._edges)
np.save(os.path.join(path, 'num_graph.npy'), self._num_graph)
if self._adj_src_index is not None:
self._adj_src_index.dump(os.path.join(path, 'adj_src'))
if self._adj_dst_index is not None:
self._adj_dst_index.dump(os.path.join(path, 'adj_dst'))
if self._graph_node_index is not None:
np.save(
os.path.join(path, 'graph_node_index.npy'),
self._graph_node_index)
if self._graph_edge_index is not None:
np.save(
os.path.join(path, 'graph_edge_index.npy'),
self._graph_edge_index)
def _dump_feat(feat_path, feat):
"""Dump all features to .npy file.
"""
if len(feat) == 0:
return
if not os.path.exists(feat_path):
os.makedirs(feat_path)
for key in feat:
value = feat[key]
np.save(os.path.join(feat_path, key + ".npy"), value)
_dump_feat(os.path.join(path, "node_feat"), self.node_feat)
_dump_feat(os.path.join(path, "edge_feat"), self.edge_feat)
@property
def adj_src_index(self):
"""Return an EdgeIndex object for src.
"""
if self._adj_src_index is None:
u = self._edges[:, 0]
v = self._edges[:, 1]
self._adj_src_index = EdgeIndex.from_edges(
u=u, v=v, num_nodes=self._num_nodes)
return self._adj_src_index
@property
def adj_dst_index(self):
"""Return an EdgeIndex object for dst.
"""
if self._adj_dst_index is None:
v = self._edges[:, 0]
u = self._edges[:, 1]
self._adj_dst_index = EdgeIndex.from_edges(
u=u, v=v, num_nodes=self._num_nodes)
return self._adj_dst_index
@property
def edge_feat(self):
"""Return a dictionary of edge features.
"""
return self._edge_feat
@property
def node_feat(self):
"""Return a dictionary of node features.
"""
return self._node_feat
@property
def num_edges(self):
"""Return the number of edges.
"""
if self._is_tensor:
return paddle.shape(self._edges)[0]
else:
return self._edges.shape[0]
@property
def num_nodes(self):
"""Return the number of nodes.
"""
return self._num_nodes
@property
def edges(self):
"""Return all edges in numpy.ndarray or paddle.Tensor with shape (num_edges, 2).
"""
return self._edges
def sorted_edges(self, sort_by="src"):
"""Return sorted edges with different strategies.
This function will return sorted edges with different strategy.
If :code:`sort_by="src"`, then edges will be sorted by :code:`src`
nodes and otherwise :code:`dst`.
Args:
sort_by: The type for sorted edges. ("src" or "dst")
Return:
A tuple of (sorted_src, sorted_dst, sorted_eid).
"""
if sort_by not in ["src", "dst"]:
raise ValueError("sort_by should be in 'src' or 'dst'.")
if sort_by == 'src':
src, dst, eid = self.adj_src_index.triples()
else:
dst, src, eid = self.adj_dst_index.triples()
return src, dst, eid
@property
def nodes(self):
"""Return all nodes id from 0 to :code:`num_nodes - 1`
"""
if self._nodes is None:
if self.is_tensor():
self._nodes = paddle.arange(self.num_nodes)
else:
self._nodes = np.arange(self.num_nodes)
return self._nodes
def indegree(self, nodes=None):
"""Return the indegree of the given nodes
This function will return indegree of given nodes.
Args:
nodes: Return the indegree of given nodes,
if nodes is None, return indegree for all nodes
Return:
A numpy.ndarray or paddle.Tensor as the given nodes' indegree.
"""
if nodes is None:
return self.adj_dst_index.degree
else:
if self._is_tensor:
return paddle.gather(self.adj_dst_index.degree, nodes)
else:
return self.adj_dst_index.degree[nodes]
def outdegree(self, nodes=None):
"""Return the outdegree of the given nodes.
This function will return outdegree of given nodes.
Args:
nodes: Return the outdegree of given nodes,
if nodes is None, return outdegree for all nodes
Return:
A numpy.array or paddle.Tensor as the given nodes' outdegree.
"""
if nodes is None:
return self.adj_src_index.degree
else:
if self._is_tensor:
return paddle.gather(self.adj_src_index.degree, nodes)
else:
return self.adj_src_index.degree[nodes]
def successor(self, nodes=None, return_eids=False):
"""Find successor of given nodes.
This function will return the successor of given nodes.
Args:
nodes: Return the successor of given nodes,
if nodes is None, return successor for all nodes.
return_eids: If True return nodes together with corresponding eid
Return:
Return a list of numpy.ndarray and each numpy.ndarray represent a list
of successor ids for given nodes. If :code:`return_eids=True`, there will
be an additional list of numpy.ndarray and each numpy.ndarray represent
a list of eids that connected nodes to their successors.
Example:
.. code-block:: python
import numpy as np
import pgl
num_nodes = 5
edges = [ (0, 1), (1, 2), (3, 4)]
graph = pgl.Graph(num_nodes=num_nodes,
edges=edges)
succ, succ_eid = graph.successor(return_eids=True)
This will give output.
.. code-block:: python
succ:
[[1],
[2],
[],
[4],
[]]
succ_eid:
[[0],
[1],
[],
[2],
[]]
"""
if self.is_tensor():
raise ValueError(
"You must call Graph.numpy() first. Tensor object don't supprt successor now."
)
else:
if return_eids:
return self.adj_src_index.view_v(
nodes), self.adj_src_index.view_eid(nodes)
else:
return self.adj_src_index.view_v(nodes)
def sample_successor(self,
nodes,
max_degree,
return_eids=False,
shuffle=False):
"""Sample successors of given nodes.
Args:
nodes: Given nodes whose successors will be sampled.
max_degree: The max sampled successors for each nodes.
return_eids: Whether to return the corresponding eids.
Return:
Return a list of numpy.ndarray and each numpy.ndarray represent a list
of sampled successor ids for given nodes. If :code:`return_eids=True`, there will
be an additional list of numpy.ndarray and each numpy.ndarray represent
a list of eids that connected nodes to their successors.
"""
if self.is_tensor():
raise ValueError(
"You must call Graph.numpy() first. Tensor object don't supprt sample_successor now."
)
else:
node_succ = self.successor(nodes, return_eids=return_eids)
if return_eids:
node_succ, node_succ_eid = node_succ
if nodes is None:
nodes = self.nodes
node_succ = node_succ.tolist()
if return_eids:
node_succ_eid = node_succ_eid.tolist()
if return_eids:
return graph_kernel.sample_subset_with_eid(
node_succ, node_succ_eid, max_degree, shuffle)
else:
return graph_kernel.sample_subset(node_succ, max_degree,
shuffle)
def predecessor(self, nodes=None, return_eids=False):
"""Find predecessor of given nodes.
This function will return the predecessor of given nodes.
Args:
nodes: Return the predecessor of given nodes,
if nodes is None, return predecessor for all nodes.
return_eids: If True return nodes together with corresponding eid
Return:
Return a list of numpy.ndarray and each numpy.ndarray represent a list
of predecessor ids for given nodes. If :code:`return_eids=True`, there will
be an additional list of numpy.ndarray and each numpy.ndarray represent
a list of eids that connected nodes to their predecessors.
Example:
.. code-block:: python
import numpy as np
import pgl
num_nodes = 5
edges = [ (0, 1), (1, 2), (3, 4)]
graph = pgl.Graph(num_nodes=num_nodes,
edges=edges)
pred, pred_eid = graph.predecessor(return_eids=True)
This will give output.
.. code-block:: python
pred:
[[],
[0],
[1],
[],
[3]]
pred_eid:
[[],
[0],
[1],
[],
[2]]
"""
if self.is_tensor():
raise ValueError(
"You must call Graph.numpy() first. Tensor object don't supprt predecessor now."
)
else:
if return_eids:
return self.adj_dst_index.view_v(
nodes), self.adj_dst_index.view_eid(nodes)
else:
return self.adj_dst_index.view_v(nodes)
def sample_predecessor(self,
nodes,
max_degree,
return_eids=False,
shuffle=False):
"""Sample predecessor of given nodes.
Args:
nodes: Given nodes whose predecessor will be sampled.
max_degree: The max sampled predecessor for each nodes.
return_eids: Whether to return the corresponding eids.
Return:
Return a list of numpy.ndarray and each numpy.ndarray represent a list
of sampled predecessor ids for given nodes. If :code:`return_eids=True`, there will
be an additional list of numpy.ndarray and each numpy.ndarray represent
a list of eids that connected nodes to their predecessors.
"""
if self.is_tensor():
raise ValueError(
"You must call Graph.numpy() first. Tensor object don't supprt sample_predecessor now."
)
else:
node_pred = self.predecessor(nodes, return_eids=return_eids)
if return_eids:
node_pred, node_pred_eid = node_pred
if nodes is None:
nodes = self.nodes
node_pred = node_pred.tolist()
if return_eids:
node_pred_eid = node_pred_eid.tolist()
if return_eids:
return graph_kernel.sample_subset_with_eid(
node_pred, node_pred_eid, max_degree, shuffle)
else:
return graph_kernel.sample_subset(node_pred, max_degree,
shuffle)
@property
def num_graph(self):
""" Return Number of Graphs"""
return self._num_graph
@property
def graph_node_id(self):
""" Return a numpy.ndarray or paddle.Tensor with shape [num_nodes]
that indicates which graph the nodes belongs to.
Examples:
.. code-block:: python
import numpy as np
import pgl
num_nodes = 5
edges = [ (0, 1), (1, 2), (3, 4)]
graph = pgl.Graph(num_nodes=num_nodes,
edges=edges)
joint_graph = pgl.Graph.batch([graph, graph])
print(joint_graph.graph_node_id)
>>> [0, 0, 0, 0, 0, 1, 1, 1, 1 ,1]
"""
return generate_segment_id_from_index(self._graph_node_index)
@property
def graph_edge_id(self):
""" Return a numpy.ndarray or paddle.Tensor with shape [num_edges]
that indicates which graph the edges belongs to.
Examples:
.. code-block:: python
import numpy as np
import pgl
num_nodes = 5
edges = [ (0, 1), (1, 2), (3, 4)]
graph = pgl.Graph(num_nodes=num_nodes,
edges=edges)
joint_graph = pgl.Graph.batch([graph, graph])
print(joint_graph.graph_edge_id)
>>> [0, 0, 0, 1, 1, 1]
"""
return generate_segment_id_from_index(self._graph_edge_index)
def send_recv(self, feature, reduce_func="sum"):
"""This method combines the send and recv function using graph_send_recv API.
Now, this method only supports default copy send function, and built-in receive
function ('sum', 'mean', 'max', 'min').
Args:
feature (Tensor): The node feature of a graph.
reduce_func (str): Difference reduce function, including 'sum', 'mean', 'max', 'min'.
"""
assert isinstance(feature, paddle.Tensor) or isinstance(feature, paddle.static.framework.Variable), \
"The input of send_recv method should be Tensor."
assert reduce_func in ['sum', 'mean', 'max', 'min'], \
"Only support 'sum', 'mean', 'max', 'min' built-in reduce functions."
src, dst = self.edges[:, 0], self.edges[:, 1]
return graph_send_recv(feature, src, dst, pool_type=reduce_func)
def send(
self,
message_func,
src_feat=None,
dst_feat=None,
edge_feat=None, ):
"""Send message from all src nodes to dst nodes.
The UDF message function should has the following format.
.. code-block:: python
def message_func(src_feat, dst_feat, edge_feat):
'''
Args:
src_feat: the node feat dict attached to the src nodes.
dst_feat: the node feat dict attached to the dst nodes.
edge_feat: the edge feat dict attached to the
corresponding (src, dst) edges.
Return:
It should return a tensor or a dictionary of tensor. And each tensor
should have a shape of (num_edges, dims).
'''
return {'msg': src_feat['h']}
Args:
message_func: UDF function.
src_feat: a dict {name: tensor,} to build src node feat
dst_feat: a dict {name: tensor,} to build dst node feat
node_feat: a dict {name: tensor,} to build both src and dst node feat
edge_feat: a dict {name: tensor,} to build edge feat
Return:
A dictionary of tensor representing the message. Each of the values
in the dictionary has a shape (num_edges, dim) which should be collected
by :code:`recv` function.
"""
msg = {}
if self._is_tensor:
src_feat_temp = {}
dst_feat_temp = {}
if src_feat is not None:
assert isinstance(src_feat,
dict), "The input src_feat must be a dict"
src_feat_temp.update(src_feat)
if dst_feat is not None:
assert isinstance(dst_feat,
dict), "The input dst_feat must be a dict"
dst_feat_temp.update(dst_feat)
edge_feat_temp = {}
if edge_feat is not None:
assert isinstance(edge_feat,
dict), "The input edge_feat must be a dict"
edge_feat_temp.update(edge_feat)
src = self.edges[:, 0]
dst = self.edges[:, 1]
src_feat = op.RowReader(src_feat_temp, src)
dst_feat = op.RowReader(dst_feat_temp, dst)
msg = message_func(src_feat, dst_feat, edge_feat_temp)
if not isinstance(msg, dict):
raise TypeError(
"The outputs of the %s function is expected to be a dict, but got %s" \
% (message_func.__name__, type(msg)))
return msg
else:
raise ValueError("You must call Graph.tensor() first")
return msg