-
Notifications
You must be signed in to change notification settings - Fork 268
Expand file tree
/
Copy pathgraphframe.py
More file actions
1487 lines (1262 loc) · 65.6 KB
/
Copy pathgraphframe.py
File metadata and controls
1487 lines (1262 loc) · 65.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
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#
from __future__ import annotations
import warnings
from typing import TYPE_CHECKING, Any, final
from pyspark.sql import functions as F
from pyspark.storagelevel import StorageLevel
from pyspark.version import __version__
try:
from typing import override
except ImportError:
from typing_extensions import override
class AggregateNeighbors:
"""Helper class for referencing attributes in AggregateNeighbors expressions.
Use these static methods in accumulator update expressions, stopping conditions,
and target conditions to reference vertex and edge attributes.
**Example:**
>>> result = g.aggregate_neighbors(
... starting_vertices=F.col("id") == 1,
... max_hops=5,
... accumulator_names=["sum_values"],
... accumulator_inits=[F.lit(0)],
... accumulator_updates=[
... F.col("sum_values") + AggregateNeighbors.dst_attr("value")
... ],
... target_condition=AggregateNeighbors.dst_attr("id") == 10
... )
"""
@staticmethod
def src_attr(colName: str) -> Column:
"""Reference a source vertex attribute.
:param colName: Name of the source vertex attribute
:return: Column expression referencing the attribute
"""
return F.col("src_attributes").getField(colName)
@staticmethod
def dst_attr(colName: str) -> Column:
"""Reference a destination vertex attribute.
:param colName: Name of the destination vertex attribute
:return: Column expression referencing the attribute
"""
return F.col("dst_attributes").getField(colName)
@staticmethod
def edge_attr(colName: str) -> Column:
"""Reference an edge attribute.
:param colName: Name of the edge attribute
:return: Column expression referencing the attribute
"""
return F.col("edge_attributes").getField(colName)
if __version__[:3] >= "3.4":
from pyspark.sql.utils import is_remote
else:
# All the Connect-related utilities are accessible starting from 3.4.x
def is_remote() -> bool:
return False
from graphframes.internal.utils import (
_HASH2VEC_DECAY_FUNCTIONS,
_RandomWalksEmbeddingsParameters,
)
if TYPE_CHECKING:
from pyspark.sql import Column, DataFrame
from graphframes.classic.graphframe import GraphFrame as GraphFrameClassic
from graphframes.connect.graphframes_client import GraphFrameConnect
from graphframes.lib import Pregel
"""Constant for the vertices ID column name."""
ID = "id"
"""Constant for the edge src column name."""
SRC = "src"
"""Constant for the edge dst column name."""
DST = "dst"
"""Constant for the edge column name."""
EDGE = "edge"
"""Constant for the weight column name."""
WEIGHT = "weight"
class GraphFrame:
"""
Represents a graph with vertices and edges stored as DataFrames.
:param v: :class:`DataFrame` holding vertex information.
Must contain a column named "id" that stores unique
vertex IDs.
:param e: :class:`DataFrame` holding edge information.
Must contain two columns "src" and "dst" storing source
vertex IDs and destination vertex IDs of edges, respectively.
>>> localVertices = [(1,"A"), (2,"B"), (3, "C")]
>>> localEdges = [(1,2,"love"), (2,1,"hate"), (2,3,"follow")]
>>> v = spark.createDataFrame(localVertices, ["id", "name"])
>>> e = spark.createDataFrame(localEdges, ["src", "dst", "action"])
>>> g = GraphFrame(v, e)
"""
ID: str = ID
SRC: str = SRC
DST: str = DST
EDGE: str = EDGE
WEIGHT: str = WEIGHT
@staticmethod
def _from_impl(impl: "GraphFrameClassic | GraphFrameConnect") -> "GraphFrame":
return GraphFrame(impl._vertices, impl._edges)
def __init__(self, v: DataFrame, e: DataFrame) -> None:
"""
Initialize a GraphFrame from vertex DataFrame and edges DataFrame.
:param v: :class:`DataFrame` holding vertex information.
Must contain a column named "id" that stores unique
vertex IDs.
:param e: :class:`DataFrame` holding edge information.
Must contain two columns "src" and "dst" storing source
vertex IDs and destination vertex IDs of edges, respectively.
"""
self._impl: "GraphFrameClassic | GraphFrameConnect"
if self.ID not in v.columns:
raise ValueError(
"Vertex ID column {} missing from vertex DataFrame, which has columns: {}".format(
self.ID, ",".join(v.columns)
)
)
if self.SRC not in e.columns:
raise ValueError(
"Source vertex ID column {} missing from edge DataFrame, which has columns: {}".format( # noqa: E501
self.SRC, ",".join(e.columns)
)
)
if self.DST not in e.columns:
raise ValueError(
"Destination vertex ID column {} missing from edge DataFrame, which has columns: {}".format( # noqa: E501
self.DST, ",".join(e.columns)
)
)
if is_remote():
from graphframes.connect.graphframes_client import GraphFrameConnect
self._impl = GraphFrameConnect(v, e) # ty: ignore[invalid-argument-type]
else:
from graphframes.classic.graphframe import GraphFrame as GraphFrameClassic
self._impl = GraphFrameClassic(v, e) # ty: ignore[invalid-argument-type]
@property
def vertices(self) -> DataFrame:
"""
:class:`DataFrame` holding vertex information, with unique column "id"
for vertex IDs.
"""
return self._impl._vertices
@property
def edges(self) -> DataFrame:
"""
:class:`DataFrame` holding edge information, with unique columns "src" and
"dst" storing source vertex IDs and destination vertex IDs of edges,
respectively.
"""
return self._impl._edges
@property
def nodes(self) -> DataFrame:
"""Alias to vertices."""
return self.vertices
@override
def __repr__(self) -> str:
# Exactly like in the scala core
v_cols = [self.ID] + [col for col in self._impl._vertices.columns if col != self.ID]
e_cols = [self.SRC, self.DST] + [
col for col in self._impl._edges.columns if col not in {self.SRC, self.DST}
]
v = self._impl._vertices.select(*v_cols).__repr__()
e = self._impl._edges.select(*e_cols).__repr__()
return f"GraphFrame(v:{v}, e:{e})"
def cache(self) -> "GraphFrame":
"""Persist the dataframe representation of vertices and edges of the graph with the default
storage level.
"""
new_vertices = self._impl._vertices.cache()
new_edges = self._impl._edges.cache()
return GraphFrame(new_vertices, new_edges)
def persist(self, storageLevel: StorageLevel = StorageLevel.MEMORY_ONLY) -> "GraphFrame":
"""Persist the dataframe representation of vertices and edges of the graph with the given
storage level.
"""
new_vertices = self._impl._vertices.persist(storageLevel=storageLevel)
new_edges = self._impl._edges.persist(storageLevel=storageLevel)
return GraphFrame(new_vertices, new_edges)
def unpersist(self, blocking: bool = False) -> "GraphFrame":
"""Mark the dataframe representation of vertices and edges of the graph as non-persistent,
and remove all blocks for it from memory and disk.
"""
new_vertices = self._impl._vertices.unpersist(blocking=blocking)
new_edges = self._impl._edges.unpersist(blocking=blocking)
return GraphFrame(new_vertices, new_edges)
@property
def outDegrees(self) -> DataFrame:
"""
The out-degree of each vertex in the graph, returned as a DataFrame with two columns:
- "id": the ID of the vertex
- "outDegree" (integer) storing the out-degree of the vertex
Note that vertices with 0 out-edges are not returned in the result.
:return: DataFrame with new vertices column "outDegree"
"""
return self._impl._edges.groupBy(F.col(self.SRC).alias(self.ID)).agg(
F.count("*").alias("outDegree")
)
@property
def inDegrees(self) -> DataFrame:
"""
The in-degree of each vertex in the graph, returned as a DataFame with two columns:
- "id": the ID of the vertex
- "inDegree" (int) storing the in-degree of the vertex
Note that vertices with 0 in-edges are not returned in the result.
:return: DataFrame with new vertices column "inDegree"
"""
return self._impl._edges.groupBy(F.col(self.DST).alias(self.ID)).agg(
F.count("*").alias("inDegree")
)
@property
def degrees(self) -> DataFrame:
"""
The degree of each vertex in the graph, returned as a DataFrame with two columns:
- "id": the ID of the vertex
- 'degree' (integer) the degree of the vertex
Note that vertices with 0 edges are not returned in the result.
:return: DataFrame with new vertices column "degree"
"""
return (
self._impl._edges.select(
F.explode(F.array(F.col(self.SRC), F.col(self.DST))).alias(self.ID)
)
.groupBy(self.ID)
.agg(F.count("*").alias("degree"))
)
def type_out_degree(self, edge_type_col: str, edge_types: list[Any] | None = None) -> DataFrame:
"""
The out-degree of each vertex per edge type, returned as a DataFrame with two columns:
- "id": the ID of the vertex
- "outDegrees": a struct with a field for each edge type, storing the out-degree count
:param edge_type_col: Name of the column in edges DataFrame that contains edge types
:param edge_types: Optional list of edge type values. If None, edge types will be discovered automatically.
:return: DataFrame with columns "id" and "outDegrees" (struct type)
""" # noqa: E501
if edge_types is not None:
pivot_df = self._impl._edges.groupBy(F.col(self.SRC).alias(self.ID)).pivot(
edge_type_col, edge_types
)
else:
pivot_df = self._impl._edges.groupBy(F.col(self.SRC).alias(self.ID)).pivot(
edge_type_col
)
count_df = pivot_df.agg(F.count(F.lit(1))).na.fill(0)
struct_cols = [
F.col(col_name).cast("int").alias(col_name)
for col_name in count_df.columns
if col_name != self.ID
]
return count_df.select(F.col(self.ID), F.struct(*struct_cols).alias("outDegrees"))
def type_in_degree(self, edge_type_col: str, edge_types: list[Any] | None = None) -> DataFrame:
"""
The in-degree of each vertex per edge type, returned as a DataFrame with two columns:
- "id": the ID of the vertex
- "inDegrees": a struct with a field for each edge type, storing the in-degree count
:param edge_type_col: Name of the column in edges DataFrame that contains edge types
:param edge_types: Optional list of edge type values. If None, edge types will be discovered automatically.
:return: DataFrame with columns "id" and "inDegrees" (struct type)
""" # noqa: E501
if edge_types is not None:
pivot_df = self._impl._edges.groupBy(F.col(self.DST).alias(self.ID)).pivot(
edge_type_col, edge_types
)
else:
pivot_df = self._impl._edges.groupBy(F.col(self.DST).alias(self.ID)).pivot(
edge_type_col
)
count_df = pivot_df.agg(F.count(F.lit(1))).na.fill(0)
struct_cols = [
F.col(col_name).cast("int").alias(col_name)
for col_name in count_df.columns
if col_name != self.ID
]
return count_df.select(F.col(self.ID), F.struct(*struct_cols).alias("inDegrees"))
def type_degree(self, edge_type_col: str, edge_types: list[Any] | None = None) -> DataFrame:
"""
The total degree of each vertex per edge type (both in and out), returned as a DataFrame
with two columns:
- "id": the ID of the vertex
- "degrees": a struct with a field for each edge type, storing the total degree count
:param edge_type_col: Name of the column in edges DataFrame that contains edge types
:param edge_types: Optional list of edge type values. If None, edge types will be discovered automatically.
:return: DataFrame with columns "id" and "degrees" (struct type)
""" # noqa: E501
exploded_edges = self._impl._edges.select(
F.explode(F.array(F.col(self.SRC), F.col(self.DST))).alias(self.ID),
F.col(edge_type_col),
)
if edge_types is not None:
pivot_df = exploded_edges.groupBy(self.ID).pivot(edge_type_col, edge_types)
else:
pivot_df = exploded_edges.groupBy(self.ID).pivot(edge_type_col)
count_df = pivot_df.agg(F.count(F.lit(1))).na.fill(0)
struct_cols = [
F.col(col_name).cast("int").alias(col_name)
for col_name in count_df.columns
if col_name != self.ID
]
return count_df.select(F.col(self.ID), F.struct(*struct_cols).alias("degrees"))
@property
def triplets(self) -> DataFrame:
"""
The triplets (source vertex)-[edge]->(destination vertex) for all edges in the graph.
Returned as a :class:`DataFrame` with three columns:
- "src": source vertex with schema matching 'vertices'
- "edge": edge with schema matching 'edges'
- 'dst': destination vertex with schema matching 'vertices'
:return: DataFrame with columns 'src', 'edge', and 'dst'
"""
return self._impl.triplets
@property
def pregel(self) -> Pregel:
"""
Get the :class:`graphframes.classic.pregel.Pregel`
or :class`graphframes.connect.graphframes_client.Pregel`
object for running pregel.
See :class:`graphframes.lib.Pregel` for more details.
"""
return self._impl.pregel
def find(self, pattern: str) -> DataFrame:
"""
Motif finding: searching the graph for structural patterns.
Motif finding uses a simple Domain-Specific Language (DSL) for expressing structural
queries. For example, ``graph.find("(a)-[e1]->(b); (b)-[e2]->(a)")`` will search for
pairs of vertices ``a``, ``b`` connected by edges in both directions. It returns a
:class:`DataFrame` of all such structures, with columns for each named element (vertex
or edge) in the motif.
**Performance tip:** Motif finding translates patterns into a series of joins. Enabling
Spark's Cost-Based Optimizer (CBO) and join reordering can significantly improve
performance::
spark.conf.set("spark.sql.cbo.enabled", "true")
spark.conf.set("spark.sql.cbo.joinReorder.enabled", "true")
The join reorder algorithm is bounded by ``spark.sql.cbo.joinReorder.dp.threshold``
(default: ``12``). If the estimated number of joins in your motif exceeds this threshold,
increase it accordingly::
spark.conf.set("spark.sql.cbo.joinReorder.dp.threshold", "20")
CBO relies on table statistics, so run ``ANALYZE TABLE <tableName> COMPUTE STATISTICS`` on
the vertices and edges tables (or temp views) to ensure accurate statistics are available.
:param pattern: String describing the motif to search for.
:return: DataFrame with one Row for each instance of the motif found.
"""
return self._impl.find(pattern=pattern)
def filterVertices(self, condition: str | Column) -> "GraphFrame":
"""
Filters the vertices based on expression, remove edges containing any dropped vertices.
:param condition: String or Column describing the condition expression for filtering.
:return: GraphFrame with filtered vertices and edges.
"""
return GraphFrame._from_impl(self._impl.filterVertices(condition=condition))
def filterEdges(self, condition: str | Column) -> "GraphFrame":
"""
Filters the edges based on expression, keep all vertices.
:param condition: String or Column describing the condition expression for filtering.
:return: GraphFrame with filtered edges.
"""
return GraphFrame._from_impl(self._impl.filterEdges(condition=condition))
def dropIsolatedVertices(self) -> "GraphFrame":
"""
Drops isolated vertices, vertices are not contained in any edges.
:return: GraphFrame with filtered vertices.
"""
return GraphFrame._from_impl(self._impl.dropIsolatedVertices())
def detectingCycles(
self,
checkpoint_interval: int = 2,
use_local_checkpoints: bool = False,
storage_level: StorageLevel = StorageLevel.MEMORY_AND_DISK_DESER,
) -> DataFrame:
"""Find all cycles in the graph.
An implementation of the Rocha–Thatte cycle detection algorithm.
Rocha, Rodrigo Caetano, and Bhalchandra D. Thatte. "Distributed cycle detection in
large-scale sparse graphs." Proceedings of Simpósio Brasileiro de Pesquisa Operacional
(SBPO'15) (2015): 1-11.
Returns a DataFrame with unique cycles.
:param checkpoint_interval: Pregel checkpoint interval, default is 2
:param use_local_checkpoints: should local checkpoints be used instead of checkpointDir
:storage_level: the level of storage for both intermediate results and an output DataFrame
:return: Persisted DataFrame with all the cycles
"""
return self._impl.detectingCycles(checkpoint_interval, use_local_checkpoints, storage_level)
def bfs(
self,
fromExpr: str,
toExpr: str,
edgeFilter: str | None = None,
maxPathLength: int = 10,
) -> DataFrame:
"""
Breadth-first search (BFS).
See Scala documentation for more details.
:return: DataFrame with one Row for each shortest path between matching vertices.
"""
return self._impl.bfs(
fromExpr=fromExpr,
toExpr=toExpr,
edgeFilter=edgeFilter,
maxPathLength=maxPathLength,
)
def all_paths(
self,
from_expr: Column | str,
to_expr: Column | str,
edge_filter: Column | str | None = None,
max_path_length: int = 5,
is_directed: bool = True,
checkpoint_interval: int = 2,
use_local_checkpoints: bool = False,
storage_level: StorageLevel = StorageLevel.MEMORY_AND_DISK_DESER,
) -> DataFrame:
"""
Computes all simple paths between source and destination vertices.
This algorithm enumerates paths up to ``max_path_length`` hops. It supports directed
and undirected traversal as well as optional edge filtering. It returns all simple
paths between source and destination vertices. Here the term "simple" means no
repeated vertices. For example, if there are paths A-B-C, A-D-C and the edge B-A,
and the user asked to find all the paths between "A" and "C", only A-B-C and A-D-C
will be returned, but not A-B-A-D-C.
The default value of ``max_path_length`` is 5. Keep in mind that requesting
``max_path_length`` on the scale of the graph diameter may cause the algorithm to
try to return (almost) all simple paths in the graph, which can create huge
performance degradation or even OOM-like errors.
**Returned DataFrame schema:**
- ``path``: array of vertex ids in traversal order
- ``len``: number of edges in the path (Long)
.. note::
In the case of an undirected graph, the algorithm runs on an internal graph
made by union of edges and reversed edges. It is assumed that the graph does
not have multi-edges. Results may be unstable and unpredictable for graphs
with multi-edges.
**Example:**
>>> paths = g.all_paths(
... from_expr="name = 'A'",
... to_expr="name = 'C'",
... max_path_length=3,
... )
>>> paths.show()
:param from_expr: Column expression or SQL expression string identifying the
source (starting) vertices.
:param to_expr: Column expression or SQL expression string identifying the
destination (target) vertices.
:param edge_filter: Optional Column expression or SQL expression string applied
to edges during traversal. Only edges satisfying this condition are considered.
If not provided, all edges are considered.
:param max_path_length: Maximum number of edges in a path; must be greater than 0.
Default is 5. Setting a large value (e.g., on the scale of the graph diameter)
may cause severe performance degradation or out-of-memory errors.
:param is_directed: Whether to use directed traversal. If False, the graph is
treated as undirected by internally unioning edges with reversed edges.
Default is True.
:param checkpoint_interval: Checkpoint every N iterations, 0 = disabled (default: 0)
:param use_local_checkpoints: Use local checkpoints (faster but less reliable)
:param storage_level: Storage level for intermediate results
:return: DataFrame with columns ``path`` (array of vertex ids) and ``len``
(number of edges in the path).
"""
return self._impl.all_paths(
from_expr=from_expr,
to_expr=to_expr,
edge_filter=edge_filter,
max_path_length=max_path_length,
is_directed=is_directed,
checkpoint_interval=checkpoint_interval,
use_local_checkpoints=use_local_checkpoints,
storage_level=storage_level,
)
def aggregateMessages(
self,
aggCol: list[Column | str] | Column,
sendToSrc: list[Column | str] | Column | str | None = None,
sendToDst: list[Column | str] | Column | str | None = None,
intermediate_storage_level: StorageLevel = StorageLevel.MEMORY_AND_DISK_DESER,
) -> DataFrame:
"""
Aggregates messages from the neighbours.
When specifying the messages and aggregation function, the user may reference columns using
the static methods in :class:`graphframes.lib.AggregateMessages`.
See Scala documentation for more details.
Warning! The result of this method is persisted DataFrame object! Users should handle unpersist
to avoid possible memory leaks!
:param aggCol: the requested aggregation output either as a collection of
:class:`pyspark.sql.Column` or SQL expression string
:param sendToSrc: message sent to the source vertex of each triplet either as
a collection of :class:`pyspark.sql.Column` or SQL expression string (default: None)
:param sendToDst: message sent to the destination vertex of each triplet either as
collection of :class:`pyspark.sql.Column` or SQL expression string (default: None)
:param intermediate_storage_level: the level of intermediate storage that will be used
for both intermediate result and the output.
:return: Persisted DataFrame with columns for the vertex ID and the resulting aggregated message.
The name of the resulted message column is based on the alias of the provided aggCol!
""" # noqa: E501
if sendToDst is None:
sendToDst = []
if sendToSrc is None:
sendToSrc = []
# Back-compatibility workaround
if not isinstance(aggCol, list):
warnings.warn(
"Passing single column to aggCol is deprecated, use list",
DeprecationWarning,
)
return self.aggregateMessages(
[aggCol], sendToSrc, sendToDst, intermediate_storage_level
)
if not isinstance(sendToSrc, list):
warnings.warn(
"Passing single column to sendToSrc is deprecated, use list",
DeprecationWarning,
)
return self.aggregateMessages(
aggCol, [sendToSrc], sendToDst, intermediate_storage_level
)
if not isinstance(sendToDst, list):
warnings.warn(
"Passing single column to sendToDst is deprecated, use list",
DeprecationWarning,
)
return self.aggregateMessages(
aggCol, sendToSrc, [sendToDst], intermediate_storage_level
)
if len(aggCol) == 0:
raise TypeError("At least one aggregation column should be provided!")
if (len(sendToSrc) == 0) and (len(sendToDst) == 0):
raise ValueError("Either `sendToSrc`, `sendToDst`, or both have to be provided")
return self._impl.aggregateMessages(
aggCol=aggCol,
sendToSrc=sendToSrc,
sendToDst=sendToDst,
intermediate_storage_level=intermediate_storage_level,
)
# Standard algorithms
def connectedComponents(
self,
algorithm: str = "graphframes",
checkpointInterval: int = 2,
broadcastThreshold: int = 1000000,
useLabelsAsComponents: bool = False,
use_local_checkpoints: bool = False,
max_iter: int = 2 ^ 31 - 2,
storage_level: StorageLevel = StorageLevel.MEMORY_AND_DISK_DESER,
) -> DataFrame:
"""
Computes the connected components of the graph.
See Scala documentation for more details.
:param algorithm: connected components algorithm to use (default: "graphframes")
Supported algorithms are "two_phase", "randomized_contraction",
"graphframes" (deprecated alias for "two_phase") and "graphx".
:param checkpointInterval: checkpoint interval in terms of number of iterations (default: 2)
:param broadcastThreshold: broadcast threshold in propagating component assignments
(default: 1000000). Passing -1 disable manual broadcasting and
allows AQE to handle skewed joins. This mode is much faster
and is recommended to use. Default value may be changed to -1
in the future versions of GraphFrames.
:param useLabelsAsComponents: if True, uses the vertex labels as components, otherwise will
use longs
:param use_local_checkpoints: should local checkpoints be used, default false;
local checkpoints are faster and does not require to set
a persistent checkpointDir; from the other side, local
checkpoints are less reliable and require executors to have
big enough local disks.
:param storage_level: storage level for both intermediate and final dataframes.
:return: DataFrame with new vertices column "component"
"""
return self._impl.connectedComponents(
algorithm=algorithm,
checkpointInterval=checkpointInterval,
broadcastThreshold=broadcastThreshold,
useLabelsAsComponents=useLabelsAsComponents,
use_local_checkpoints=use_local_checkpoints,
max_iter=max_iter,
storage_level=storage_level,
)
def maximal_independent_set(
self,
seed: int = 42,
checkpoint_interval: int = 2,
use_local_checkpoints: bool = False,
storage_level: StorageLevel = StorageLevel.MEMORY_AND_DISK_DESER,
) -> DataFrame:
"""
This method implements a distributed algorithm for finding a Maximal Independent Set (MIS)
in a graph.
An MIS is a set of vertices such that no two vertices in the set are adjacent (i.e., there
is no edge between any two vertices in the set), and the set is maximal, meaning that adding
any other vertex to the set would violate the independence property. Note that this
implementation finds a maximal (but not necessarily maximum) independent set; that is, it
ensures no more vertices can be added to the set, but does not guarantee that the set has
the largest possible number of vertices among all possible independent sets in the graph.
The algorithm implemented here is based on the paper: Ghaffari, Mohsen. "An improved
distributed algorithm for maximal independent set." Proceedings of the twenty-seventh annual
ACM-SIAM symposium on Discrete algorithms. Society for Industrial and Applied Mathematics,
2016.
Note: This is a randomized, non-deterministic algorithm. The result may vary between runs
even if a fixed random seed is provided because of how Apache Spark works.
:param seed: random seed used for tie-breaking in the algorithm (default: 42)
:param checkpoint_interval: checkpoint interval in terms of number of iterations (default: 2)
:param use_local_checkpoints: whether to use local checkpoints (default: False);
local checkpoints are faster and do not require setting
a persistent checkpoint directory; however, they are less
reliable and require executors to have sufficient local disk space.
:param storage_level: storage level for both intermediate and final DataFrames
(default: MEMORY_AND_DISK_DESER)
:return: DataFrame with new vertex column "selected", where "true" indicates the vertex
is part of the Maximal Independent Set
""" # noqa: E501
return self._impl.maximal_independent_set(
checkpoint_interval, storage_level, use_local_checkpoints, seed
)
def k_core(
self,
checkpoint_interval: int = 2,
use_local_checkpoints: bool = False,
storage_level: StorageLevel = StorageLevel.MEMORY_AND_DISK_DESER,
) -> DataFrame:
"""
The k-core is the maximal subgraph such that every vertex has at least degree k.
The k-core metric is a measure of the centrality of a node in a network, based on its
degree and the degrees of its neighbors. Nodes with higher k-core values are considered
to be more central and influential within the network.
This implementation is based on the algorithm described in:
Mandal, Aritra, and Mohammad Al Hasan. "A distributed k-core decomposition algorithm
on spark." 2017 IEEE International Conference on Big Data (Big Data). IEEE, 2017.
:param checkpoint_interval: Pregel checkpoint interval, default is 2
:param use_local_checkpoints: should local checkpoints be used instead of checkpointDir
:param storage_level: the level of storage for both intermediate results and an output DataFrame
:return: Persisted DataFrame with ID and k-core values (column "kcore")
""" # noqa: E501
return self._impl.k_core(checkpoint_interval, use_local_checkpoints, storage_level)
def hyper_anf(
self,
n_hops: int = 3,
lg_nom_entries: int = 12,
edge_filter: Column | str | None = None,
checkpoint_interval: int = 2,
use_local_checkpoints: bool = False,
storage_level: StorageLevel = StorageLevel.MEMORY_AND_DISK_DESER,
) -> DataFrame:
"""HyperANF-style approximation of the neighbourhood function.
This implementation is inspired by
`HyperANF: Approximating the Neighbourhood Function of Very Large Graphs on a Budget
<https://arxiv.org/pdf/1011.5599>`_
(Vigna, Boldi, Rosa; 2010).
The input graph is treated as directed: for each vertex, reachability is computed by
following outgoing edges from ``src`` to ``dst``.
Compared with the cumulative neighbourhood-function presentation in the paper, this
implementation returns one column per hop: ``hop_0``, ``hop_1``, ``hop_2``, …, ``hop_N``.
The ``hop_0`` column contains a HyperLogLog sketch of the source vertex itself, and each
``hop_k`` column for ``k >= 1`` contains a HyperLogLog sketch of the set of vertices
reachable in exactly ``k`` hops. To derive the cumulative approximate neighbourhood
function for distances up to some hop ``k``, combine ``hop_0`` through ``hop_k`` with
``hll_union`` and then apply ``hll_sketch_estimate`` to the merged sketch.
The computation can also be restricted to a subgraph by supplying an edge filter
expression via ``edge_filter``. A common use case is to filter on ``src``, for example
``"src IN (1, 2, 3)"``, to obtain sketches only for a selected set of starting vertices.
**Example:**
>>> result = g.hyper_anf(n_hops=2)
>>> result.columns
['id', 'hop_0', 'hop_1', 'hop_2']
:param n_hops: Maximum hop distance to compute (positive integer). The result will
contain columns ``hop_0`` through ``hop_N`` where ``N = n_hops``.
:param lg_nom_entries: Log2 of nominal entries used by HLL sketch aggregations.
Must be between 4 and 21 (inclusive). Higher values increase accuracy at the
cost of memory. Default is 12.
:param edge_filter: Optional column expression or SQL expression string applied to
edges before computation. Only edges satisfying this predicate participate in
the directed reachability expansion.
:param checkpoint_interval: Checkpoint interval in terms of number of iterations
(default: 2). Use 0 to disable checkpointing.
:param use_local_checkpoints: Whether to use local checkpoints instead of a
persistent checkpoint directory. Local checkpoints are faster but less reliable.
:param storage_level: Storage level for intermediate and final DataFrames.
:return: Persisted DataFrame with vertex ``id`` and one sketch column per hop
(``hop_0``, ``hop_1``, …, ``hop_N``).
""" # noqa: E501
if n_hops <= 0:
raise ValueError("n_hops must be a positive integer")
if not (4 <= lg_nom_entries <= 21):
raise ValueError("lg_nom_entries must be between 4 and 21 (inclusive)")
return self._impl.hyper_anf(
n_hops=n_hops,
lg_nom_entries=lg_nom_entries,
edge_filter=edge_filter,
checkpoint_interval=checkpoint_interval,
use_local_checkpoints=use_local_checkpoints,
storage_level=storage_level,
)
def labelPropagation(
self,
maxIter: int,
algorithm: str = "graphx",
use_local_checkpoints: bool = False,
checkpoint_interval: int = 2,
storage_level: StorageLevel = StorageLevel.MEMORY_AND_DISK_DESER,
) -> DataFrame:
"""
Runs static label propagation for detecting communities in networks.
See Scala documentation for more details.
:param maxIter: the number of iterations to be performed
:param algorithm: implementation to use, possible values are "graphframes" and "graphx";
"graphx" is faster for small-medium sized graphs,
"graphframes" requires less amount of memory
:param use_local_checkpoints: should local checkpoints be used, default false;
local checkpoints are faster and does not require to set
a persistent checkpointDir; from the other side, local
checkpoints are less reliable and require executors to have
big enough local disks.
:checkpoint_interval: How often should the intermediate result be checkpointed;
Using big value here may tend to huge logical plan growth due
to the iterative nature of the algorithm.
:param storage_level: storage level for both intermediate and final dataframes.
:return: Persisted DataFrame with new vertices column "label"
"""
return self._impl.labelPropagation(
maxIter=maxIter,
algorithm=algorithm,
use_local_checkpoints=use_local_checkpoints,
checkpoint_interval=checkpoint_interval,
storage_level=storage_level,
)
def neighborhood_aware_cdlp(
self,
max_iter: int,
structural_similarity_multiplier: float = 0.5,
ignore_direct_links: bool = False,
initial_label_col: str | None = None,
is_directed: bool = True,
lg_nom_entries: int = 12,
use_local_checkpoints: bool = False,
checkpoint_interval: int = 2,
storage_level: StorageLevel = StorageLevel.MEMORY_AND_DISK_DESER,
) -> DataFrame:
"""
Neighborhood-aware community detection via weighted label propagation.
This algorithm is a Label Propagation variant where each incoming label vote is weighted
by a combination of:
- optional direct-link baseline strength (enabled unless
``ignore_direct_links = True``), and
- neighborhood-overlap strength
(``structural_similarity_multiplier * common_neighbors``).
Intuitively, labels from neighbors that are structurally similar to the destination
(many common neighbors) can be amplified instead of treating all edges equally.
At each iteration, every vertex aggregates weighted incoming votes by label and picks
the label with maximum total weight.
Edge-weight regimes:
- ``ignore_direct_links = False``:
``edge_weight = 1 + structural_similarity_multiplier * common_neighbors``
- ``ignore_direct_links = True``:
``edge_weight = structural_similarity_multiplier * common_neighbors``
:param max_iter: maximum number of propagation rounds.
:param structural_similarity_multiplier: scales neighborhood-overlap contribution.
Must be non-negative.
:param ignore_direct_links: whether to drop direct-link baseline vote mass.
:param initial_label_col: optional vertex column used to initialize labels.
:param is_directed: whether to treat edges as directed.
:param lg_nom_entries: log2 nominal entries used by Theta sketch aggregations.
:param use_local_checkpoints: whether to use local checkpoints.
:param checkpoint_interval: checkpoint interval in iterations.
:param storage_level: storage level for intermediate datasets.
:return: Persisted DataFrame with new vertex column ``label``.
"""
if structural_similarity_multiplier < 0.0:
raise ValueError("structural_similarity_multiplier must be >= 0")
if ignore_direct_links and structural_similarity_multiplier == 0.0:
raise ValueError(
"structural_similarity_multiplier must be > 0 when ignore_direct_links is True"
)
return self._impl.neighborhood_aware_cdlp(
max_iter=max_iter,
structural_similarity_multiplier=structural_similarity_multiplier,
ignore_direct_links=ignore_direct_links,
use_local_checkpoints=use_local_checkpoints,
checkpoint_interval=checkpoint_interval,
storage_level=storage_level,
is_directed=is_directed,
lg_nom_entries=lg_nom_entries,
initial_label_col=initial_label_col,
)
def pageRank(
self,
resetProbability: float = 0.15,
sourceId: Any | None = None,
maxIter: int | None = None,
tol: float | None = None,
) -> "GraphFrame":
"""
Runs the PageRank algorithm on the graph.
Note: Exactly one of fixed_num_iter or tolerance must be set.
See Scala documentation for more details.
:param resetProbability: Probability of resetting to a random vertex.
:param sourceId: (optional) the source vertex for a personalized PageRank.
:param maxIter: If set, the algorithm is run for a fixed number
of iterations. This may not be set if the `tol` parameter is set.
:param tol: If set, the algorithm is run until the given tolerance.
This may not be set if the `numIter` parameter is set.
:return: GraphFrame with new vertices column "pagerank" and new edges column "weight"
"""
return GraphFrame._from_impl(
self._impl.pageRank(
resetProbability=resetProbability,
sourceId=sourceId,
maxIter=maxIter,
tol=tol,
)
)
def parallelPersonalizedPageRank(
self,
resetProbability: float = 0.15,
sourceIds: list[Any] | None = None,
maxIter: int | None = None,
) -> "GraphFrame":
"""
Run the personalized PageRank algorithm on the graph,
from the provided list of sources in parallel for a fixed number of iterations.
See Scala documentation for more details.
:param resetProbability: Probability of resetting to a random vertex
:param sourceIds: the source vertices for a personalized PageRank
:param maxIter: the fixed number of iterations this algorithm runs
:return: GraphFrame with new vertices column "pageranks" and new edges column "weight"
"""
return GraphFrame._from_impl(
self._impl.parallelPersonalizedPageRank(
resetProbability=resetProbability, sourceIds=sourceIds, maxIter=maxIter
)
)
def shortestPaths(
self,
landmarks: list[str | int],
algorithm: str = "graphx",
use_local_checkpoints: bool = False,
checkpoint_interval: int = 2,
storage_level: StorageLevel = StorageLevel.MEMORY_AND_DISK_DESER,
is_directed: bool = True,