-
Notifications
You must be signed in to change notification settings - Fork 274
Expand file tree
/
Copy pathpregel.py
More file actions
574 lines (474 loc) · 21.4 KB
/
Copy pathpregel.py
File metadata and controls
574 lines (474 loc) · 21.4 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
"""Demonstrate GraphFrames Pregel API capabilities. Code from the Pregel Tutorial.
This script contains progressive examples showing how to use GraphFrames'
Pregel and AggregateMessages APIs for scalable graph algorithms, including
the Four-Question Framework worked example (average answer score per tag).
Spark 4.0+ (recommended):
Interactive: pyspark --packages io.graphframes:graphframes-spark4_2.13:0.12.1
Batch: spark-submit --packages io.graphframes:graphframes-spark4_2.13:0.12.1\\
python/graphframes/tutorials/pregel.py
Spark 3.5.x:
Interactive: pyspark --packages io.graphframes:graphframes-spark3_2.13:0.11.0
Batch: spark-submit --packages io.graphframes:graphframes-spark3_2.13:0.11.0 \\
python/graphframes/tutorials/pregel.py
"""
import math
from pathlib import Path
import click
import pyspark.sql.functions as F
from pyspark.sql import DataFrame, SparkSession, Window
from graphframes import GraphFrame
from graphframes.lib import AggregateMessages as AM
from graphframes.lib import Pregel
DEFAULT_DATA_DIR = str(Path(__file__).parent / "data")
def log_hist(df: DataFrame) -> None:
"""Print a text histogram of in-degrees, with bar length on a log scale"""
# Bucket the in-degrees into powers of two: 0, 1, 2-3, 4-7, 8-15, ...
histogram = (
df.withColumn(
"bucket",
F.when(F.col("in_degree") == 0, F.lit(-1)).otherwise(F.floor(F.log2("in_degree"))),
)
.groupBy("bucket")
.agg(F.count("*").alias("num_vertices"))
.orderBy("bucket")
.collect() # tiny result set - safe to bring to the driver
)
click.echo(f"{'in_degree':>9} {'vertices':>9}")
for row in histogram:
if row["bucket"] == -1:
label = "0"
else:
low = 2 ** row["bucket"]
high = 2 ** (row["bucket"] + 1) - 1
label = str(low) if low == high else f"{low}-{high}"
bar = "#" * max(1, round(10 * math.log10(max(row["num_vertices"], 1))))
click.echo(f"{label:>9} {row['num_vertices']:>9} {bar}")
@click.command()
@click.option(
"--data-dir",
default=DEFAULT_DATA_DIR,
help="Directory containing Stack Exchange Parquet data (default: package data directory)",
)
def main(data_dir: str) -> None:
# ──────────────────────────────────────────────────────────────────────
# SparkSession
# ──────────────────────────────────────────────────────────────────────
spark: SparkSession = (
SparkSession.builder.appName("Pregel Tutorial")
.config("spark.sql.caseSensitive", True)
.getOrCreate()
)
spark.sparkContext.setCheckpointDir("/tmp/graphframes-checkpoints/pregel")
spark.sparkContext.setLogLevel("WARN")
# ──────────────────────────────────────────────────────────────────────
# Load Stack Exchange Data
# ──────────────────────────────────────────────────────────────────────
STACKEXCHANGE_SITE = "stats.meta.stackexchange.com"
BASE_PATH = f"{data_dir}/{STACKEXCHANGE_SITE}"
NODES_PATH: str = f"{BASE_PATH}/Nodes.parquet"
EDGES_PATH: str = f"{BASE_PATH}/Edges.parquet"
click.echo("\n" + "=" * 70)
click.echo("Loading Stack Exchange data...")
click.echo("=" * 70)
nodes_df: DataFrame = spark.read.parquet(NODES_PATH)
nodes_df = nodes_df.repartition(50).checkpoint().cache()
edges_df: DataFrame = spark.read.parquet(EDGES_PATH)
edges_df = edges_df.repartition(50).checkpoint().cache()
g = GraphFrame(nodes_df, edges_df)
click.echo(f"Nodes: {nodes_df.count():,}")
click.echo(f"Edges: {edges_df.count():,}")
# ======================================================================
# Example 1: In-Degree with AggregateMessages
# ======================================================================
click.echo("\n" + "=" * 70)
click.echo("EXAMPLE 1: In-Degree with AggregateMessages")
click.echo("=" * 70)
# Each source node sends 1 to its destination
am_in_degrees = g.aggregateMessages(F.count(AM.msg).alias("in_degree"), sendToDst=F.lit(1))
# Left join to include zero-degree nodes
complete_in_deg = (
g.vertices.select("id", "Type")
.join(am_in_degrees, on="id", how="left")
.na.fill(0, ["in_degree"])
)
click.echo("\nIn-degree distribution (AggregateMessages):")
complete_in_deg.groupBy("in_degree").count().orderBy("in_degree").show(10)
click.echo("In-degree histogram (log scale):")
log_hist(complete_in_deg)
click.echo("\nTop 10 nodes by in-degree:")
complete_in_deg.orderBy(F.desc("in_degree")).show(10)
# ======================================================================
# Example 2: In-Degree with Pregel
# ======================================================================
click.echo("\n" + "=" * 70)
click.echo("EXAMPLE 2: In-Degree with Pregel")
click.echo("=" * 70)
pregel_in_degree = (
g.pregel.setMaxIter(1)
.withVertexColumn(
"in_degree",
F.lit(0), # Initial value: 0
F.coalesce(Pregel.msg(), F.lit(0)), # Update: use message or keep 0
)
.sendMsgToDst(F.lit(1)) # Send 1 to each destination
.aggMsgs(F.sum(Pregel.msg())) # Sum all received messages
.run()
)
click.echo("\nIn-degree distribution (Pregel):")
pregel_in_degree.select("in_degree").groupBy("in_degree").count().orderBy("in_degree").show(10)
click.echo("In-degree histogram (log scale):")
log_hist(pregel_in_degree)
click.echo("\nTop 10 nodes by in-degree (Pregel):")
pregel_in_degree.select("id", "Type", "in_degree").orderBy(F.desc("in_degree")).show(10)
# ======================================================================
# Example 3: PageRank with Pregel
# ======================================================================
click.echo("\n" + "=" * 70)
click.echo("EXAMPLE 3: PageRank with Pregel")
click.echo("=" * 70)
# Compute out-degrees
out_degrees = g.outDegrees.withColumnRenamed("outDegree", "out_degree")
pr_vertices = nodes_df.join(out_degrees, on="id", how="left").na.fill(1, ["out_degree"])
g_pr = GraphFrame(pr_vertices, edges_df)
# PageRank parameters
num_vertices = g_pr.vertices.count()
damping = 0.85
max_iter = 10
click.echo(
f"Running PageRank: {num_vertices:,} vertices, damping={damping}, max_iter={max_iter}"
)
pr_results = (
g_pr.pregel.setMaxIter(max_iter)
.withVertexColumn(
"pagerank",
F.lit(1.0 / num_vertices),
F.coalesce(Pregel.msg(), F.lit(0.0)) * F.lit(damping)
+ F.lit((1.0 - damping) / num_vertices),
)
.sendMsgToDst(Pregel.src("pagerank") / Pregel.src("out_degree"))
.aggMsgs(F.sum(Pregel.msg()))
.run()
)
click.echo("\nTop 20 nodes by PageRank:")
pr_results.select("id", "Type", "pagerank").orderBy(F.desc("pagerank")).show(20)
# Show by type
click.echo("Top 10 Questions by PageRank:")
(
pr_results.filter(F.col("Type") == "Question")
.select("id", "Title", "pagerank")
.orderBy(F.desc("pagerank"))
.show(10, truncate=50)
)
click.echo("Top 10 Users by PageRank:")
(
pr_results.filter(F.col("Type") == "User")
.select("id", "DisplayName", "Reputation", "pagerank")
.orderBy(F.desc("pagerank"))
.show(10, truncate=50)
)
# Compare rankings with built-in PageRank
# Note: the built-in PageRank may use different normalization so absolute values differ,
# but the relative rankings should be very similar.
click.echo("\nComparing rankings with built-in PageRank...")
builtin_pr = g.pageRank(resetProbability=1 - damping, maxIter=max_iter)
pregel_ranked = pr_results.select("id", F.col("pagerank").alias("pregel_pr")).withColumn(
"pregel_rank", F.dense_rank().over(Window.orderBy(F.desc("pregel_pr")))
)
builtin_ranked = builtin_pr.vertices.select(
"id", F.col("pagerank").alias("builtin_pr")
).withColumn("builtin_rank", F.dense_rank().over(Window.orderBy(F.desc("builtin_pr"))))
comparison = pregel_ranked.join(builtin_ranked, on="id")
click.echo("Top 10 comparison (Pregel rank vs Built-in rank):")
(
comparison.filter(F.col("pregel_rank") <= 10)
.select("id", "pregel_rank", "builtin_rank", "pregel_pr", "builtin_pr")
.orderBy("pregel_rank")
.show(10)
)
# Rank correlation
rank_corr = comparison.stat.corr("pregel_rank", "builtin_rank")
click.echo(f"Rank correlation (Spearman-like): {rank_corr:.4f}")
# Unpersist built-in PR result
builtin_pr.vertices.unpersist()
# ======================================================================
# Example 4: Connected Components with Pregel
# ======================================================================
click.echo("\n" + "=" * 70)
click.echo("EXAMPLE 4: Connected Components with Pregel")
click.echo("=" * 70)
# Use a simplified graph for connected components (just id and edges)
cc_vertices = g.vertices.select("id")
cc_graph = GraphFrame(cc_vertices, g.edges.select("src", "dst"))
cc_results = (
cc_graph.pregel.setMaxIter(20)
.setEarlyStopping(True)
.withVertexColumn(
"component",
F.col("id"), # Each vertex starts as its own component (label = own id)
F.least(F.col("component"), F.coalesce(Pregel.msg(), F.col("component"))),
)
.sendMsgToDst(Pregel.src("component")) # Send label to neighbors
.sendMsgToSrc(Pregel.dst("component")) # Bidirectional for undirected CC
.aggMsgs(F.min(Pregel.msg())) # Take the minimum label
.run()
)
num_components = cc_results.select("component").distinct().count()
click.echo(f"\nNumber of connected components: {num_components:,}")
click.echo("Component size distribution:")
(
cc_results.groupBy("component")
.count()
.orderBy(F.desc("count"))
.withColumn("count", F.format_number(F.col("count"), 0))
.show(10)
)
# Unpersist
cc_results.unpersist()
# ======================================================================
# Example 5: Single-Source Shortest Paths with Pregel
# ======================================================================
click.echo("\n" + "=" * 70)
click.echo("EXAMPLE 5: Shortest Paths with Pregel")
click.echo("=" * 70)
# Pick a popular question as the source
popular_question = (
nodes_df.filter(F.col("Type") == "Question")
.orderBy(F.desc("ViewCount"))
.select("id", "Title")
.first()
)
source_id = popular_question["id"]
click.echo(f"Source: {popular_question['Title']}")
click.echo(f"Source ID: {source_id}")
# Simplified graph for shortest paths
sp_vertices = g.vertices.select("id")
sp_graph = GraphFrame(sp_vertices, g.edges.select("src", "dst"))
# Use a large int as infinity
INF = 999999
sp_results = (
sp_graph.pregel.setMaxIter(10)
.setEarlyStopping(True)
.withVertexColumn(
"distance",
F.when(F.col("id") == source_id, F.lit(0)).otherwise(F.lit(INF)),
F.least(F.col("distance"), F.coalesce(Pregel.msg(), F.lit(INF))),
)
.sendMsgToDst(
F.when(Pregel.src("distance") < F.lit(INF), Pregel.src("distance") + F.lit(1))
)
.sendMsgToSrc(
F.when(Pregel.dst("distance") < F.lit(INF), Pregel.dst("distance") + F.lit(1))
)
.aggMsgs(F.min(Pregel.msg()))
.run()
)
click.echo("\nDistance distribution from source question:")
sp_results.filter(F.col("distance") < INF).groupBy("distance").count().orderBy("distance").show(
20
)
reachable = sp_results.filter(F.col("distance") < INF).count()
total = sp_results.count()
click.echo(f"Reachable vertices: {reachable:,} / {total:,} ({reachable / total:.1%})")
# Unpersist
sp_results.unpersist()
# ======================================================================
# Example 6: Reputation Propagation with Pregel
# ======================================================================
click.echo("\n" + "=" * 70)
click.echo("EXAMPLE 6: Reputation Propagation with Pregel")
click.echo("=" * 70)
# Build a subgraph: Users -> (Posts) -> Answers -> (Answers) -> Questions
# We want to propagate user reputation through the answer graph
# Get user nodes with Reputation
user_nodes = nodes_df.filter(F.col("Type") == "User").select(
"id", F.col("Reputation").cast("double").alias("reputation"), F.lit("User").alias("Type")
)
# Get answer nodes
answer_nodes = nodes_df.filter(F.col("Type") == "Answer").select(
"id", F.col("Score").cast("double").alias("score"), F.lit("Answer").alias("Type")
)
# Get question nodes
question_nodes = nodes_df.filter(F.col("Type") == "Question").select(
"id", F.col("ViewCount").cast("double").alias("views"), F.lit("Question").alias("Type")
)
# Build unified vertices for the reputation subgraph
rep_vertices = (
user_nodes.withColumn("score", F.lit(0.0))
.withColumn("views", F.lit(0.0))
.unionByName(
answer_nodes.withColumn("reputation", F.lit(0.0)).withColumn("views", F.lit(0.0))
)
.unionByName(
question_nodes.withColumn("reputation", F.lit(0.0)).withColumn("score", F.lit(0.0))
)
.na.fill(0.0)
)
# Get edges: User->Answer (Posts) and Answer->Question (Answers)
posts_edges = edges_df.filter(F.col("relationship") == "Posts").select("src", "dst")
answers_edges = edges_df.filter(F.col("relationship") == "Answers").select("src", "dst")
rep_edges = posts_edges.unionByName(answers_edges)
rep_graph = GraphFrame(rep_vertices, rep_edges)
click.echo(
f"Reputation subgraph: {rep_vertices.count():,} vertices, {rep_edges.count():,} edges"
)
# Propagate reputation: User rep flows through Answers to Questions
# Iteration 1: Users send reputation to their Answers
# Iteration 2: Answers (now carrying user rep) send to Questions
rep_results = (
rep_graph.pregel.setMaxIter(2)
.withVertexColumn(
"authority",
F.col("reputation"), # Users start with their reputation; others start at 0
F.coalesce(Pregel.msg(), F.lit(0.0)) + F.col("authority"),
)
.sendMsgToDst(
# Send authority to destination
F.when(Pregel.src("authority") > F.lit(0), Pregel.src("authority"))
)
.aggMsgs(F.sum(Pregel.msg()))
.run()
)
click.echo("\nTop 20 Questions by propagated authority (reputation from answerers):")
(
rep_results.filter(F.col("Type") == "Question")
.select("id", "authority")
.orderBy(F.desc("authority"))
.show(20)
)
# Join with original question data for interpretability
top_questions = (
rep_results.filter(F.col("Type") == "Question")
.select(F.col("id"), F.col("authority"))
.join(
nodes_df.filter(F.col("Type") == "Question").select("id", "Title", "ViewCount"), on="id"
)
.orderBy(F.desc("authority"))
)
click.echo("Top 10 Questions with titles and authority scores:")
top_questions.show(10, truncate=60)
# Unpersist
rep_results.unpersist()
# ======================================================================
# Four-Question Framework: average answer score per Tag
# ======================================================================
click.echo("\n" + "=" * 70)
click.echo("FOUR-QUESTION FRAMEWORK: Average Answer Score per Tag")
click.echo("=" * 70)
# Subgraph: Tags, Questions, and Answers (Answers carry Score)
tag_nodes = nodes_df.filter(F.col("Type") == "Tag").select(
"id", F.col("TagName").alias("name"), F.lit("Tag").alias("Type")
)
question_nodes = nodes_df.filter(F.col("Type") == "Question").select(
"id", F.lit(None).cast("string").alias("name"), F.lit("Question").alias("Type")
)
answer_nodes = nodes_df.filter(F.col("Type") == "Answer").select(
"id",
F.lit(None).cast("string").alias("name"),
F.col("Score").cast("double").alias("score"),
F.lit("Answer").alias("Type"),
)
avg_vertices = (
tag_nodes.withColumn("score", F.lit(0.0))
.unionByName(question_nodes.withColumn("score", F.lit(0.0)))
.unionByName(answer_nodes)
.na.fill({"score": 0.0})
)
# Answers → Questions (as-is); reverse Tags so Questions → Tags
answers_edges = edges_df.filter(F.col("relationship") == "Answers").select("src", "dst")
questions_to_tags = edges_df.filter(F.col("relationship") == "Tags").select(
F.col("dst").alias("src"), F.col("src").alias("dst")
)
avg_edges = answers_edges.unionByName(questions_to_tags)
avg_graph = GraphFrame(avg_vertices, avg_edges)
click.echo(
f"Tag-average subgraph: {avg_vertices.count():,} vertices, {avg_edges.count():,} edges"
)
# Two-hop: Answer → Question → Tag via struct messages (score, count)
avg_results = (
avg_graph.pregel.setMaxIter(2)
.withVertexColumn(
"total_score",
F.when(F.col("Type") == "Answer", F.col("score")).otherwise(F.lit(0.0)),
F.col("total_score") + F.coalesce(Pregel.msg().getField("score"), F.lit(0.0)),
)
.withVertexColumn(
"answer_count",
F.when(F.col("Type") == "Answer", F.lit(1.0)).otherwise(F.lit(0.0)),
F.col("answer_count") + F.coalesce(Pregel.msg().getField("count"), F.lit(0.0)),
)
.sendMsgToDst(
F.when(
Pregel.src("answer_count") > F.lit(0),
F.struct(
Pregel.src("total_score").alias("score"),
Pregel.src("answer_count").alias("count"),
),
)
)
.aggMsgs(
F.struct(
F.sum(Pregel.msg().getField("score")).alias("score"),
F.sum(Pregel.msg().getField("count")).alias("count"),
)
)
.run()
)
click.echo("\nTop tags by average answer score:")
(
avg_results.filter(F.col("Type") == "Tag")
.filter(F.col("answer_count") > 0)
.withColumn("avg_answer_score", F.col("total_score") / F.col("answer_count"))
.select("name", "total_score", "answer_count", "avg_answer_score")
.orderBy(F.desc("avg_answer_score"))
.show(10, truncate=40)
)
avg_results.unpersist()
# ======================================================================
# Example 7: Debug Trace - Message Path Tracking
# ======================================================================
click.echo("\n" + "=" * 70)
click.echo("EXAMPLE 7: Debug Trace - Message Path Tracking")
click.echo("=" * 70)
# Use a small test graph for clarity
test_vertices = spark.createDataFrame(
[("A", "Alice"), ("B", "Bob"), ("C", "Charlie"), ("D", "David")], ["id", "name"]
)
test_edges = spark.createDataFrame(
[("A", "B"), ("A", "C"), ("B", "C"), ("C", "D")], ["src", "dst"]
)
test_graph = GraphFrame(test_vertices, test_edges)
click.echo("Test graph: A->B, A->C, B->C, C->D")
click.echo("\nTracking message paths through 3 iterations of Pregel...")
# Track paths: each vertex accumulates the path of messages it receives
trace_results = (
test_graph.pregel.setMaxIter(3)
.withVertexColumn(
"trace",
F.col("id"), # Start with own id
F.concat_ws(" <- ", F.coalesce(Pregel.msg(), F.lit("")), F.col("id")),
)
.sendMsgToDst(Pregel.src("trace"))
.aggMsgs(
# Collect all incoming traces and join them
F.concat_ws(" | ", F.collect_list(Pregel.msg()))
)
.run()
)
click.echo("\nVertex traces after 3 iterations:")
trace_results.select("id", "name", "trace").orderBy("id").show(truncate=False)
click.echo(
"\nEach vertex shows who influenced it. Reading right-to-left:\n"
" 'X <- Y <- Z' means Z's state flowed through Y to reach X.\n"
" '|' separates independent paths arriving at the same vertex."
)
# Unpersist
trace_results.unpersist()
# ──────────────────────────────────────────────────────────────────────
# Cleanup
# ──────────────────────────────────────────────────────────────────────
click.echo("\n" + "=" * 70)
click.echo("All 7 examples complete!")
click.echo("=" * 70)
spark.stop()
if __name__ == "__main__":
main()