spatial_graph_algorithms.denoise
Score, filter, and evaluate likely false edges in SpatialGraph objects.
Usage
from spatial_graph_algorithms.denoise import EdgeFilterer, score_edges
from spatial_graph_algorithms.metrics import evaluate_denoising
scores = score_edges(sg, method="jaccard")
sg_clean = EdgeFilterer().by_fraction(
sg, scores, fraction=0.10, method="jaccard"
)
report = evaluate_denoising(sg_clean, scores=scores, method="jaccard")
API Reference
spatial_graph_algorithms.denoise.SCORE_POLARITY = {'betweenness': 'positive', 'jaccard': 'negative', 'square_bipartite': 'negative', 'community': 'negative', 'random_walk': 'negative', 'degree': 'positive'}
module-attribute
spatial_graph_algorithms.denoise.EdgeScorer
Compute edge suspicion scores from graph topology.
Each method accepts a CSR adjacency matrix and returns a dict mapping
canonical edge tuples (min(u, v), max(u, v)) to float scores.
Score polarity (high = suspect vs low = suspect) is method-specific —
see :data:SCORE_POLARITY and each method's docstring.
Methods:
| Name | Description |
|---|---|
betweenness |
Edge betweenness centrality. High = suspect. |
jaccard |
Jaccard neighbourhood overlap. Low = suspect. Unipartite only. |
square_bipartite |
4-cycle count. Low = suspect. Bipartite only. |
community |
Louvain intra-community consistency. Low = suspect. |
random_walk |
Stochastic walk visitation frequency. Low = suspect. |
degree |
Max endpoint degree. High = suspect. O(n), no graph construction. |
Source code in src/spatial_graph_algorithms/denoise/__init__.py
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 | |
Functions
betweenness(adj)
Score edges by edge betweenness centrality.
High centrality signals a critical bridge — a characteristic of long-range false connections that span otherwise distinct communities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adj
|
csr_matrix
|
Symmetric unweighted adjacency matrix. |
required |
Returns:
| Type | Description |
|---|---|
dict[tuple[int, int], float]
|
Edge → normalised betweenness in |
Notes
Uses networkx.edge_betweenness_centrality, runtime O(VE).
Slow on graphs with more than a few thousand nodes.
Examples:
>>> from spatial_graph_algorithms.simulate import generate
>>> from spatial_graph_algorithms.denoise import EdgeScorer
>>> sg = generate(n=100, seed=0)
>>> scores = EdgeScorer().betweenness(sg.adjacency_matrix)
>>> all(0.0 <= v <= 1.0 for v in scores.values())
True
Source code in src/spatial_graph_algorithms/denoise/__init__.py
jaccard(adj)
Score edges by Jaccard neighbourhood overlap.
Edges connecting nodes with few shared neighbours are more likely to be false connections bridging unrelated graph regions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adj
|
csr_matrix
|
Symmetric unweighted adjacency matrix for a unipartite graph. |
required |
Returns:
| Type | Description |
|---|---|
dict[tuple[int, int], float]
|
Edge → Jaccard score in |
Raises:
| Type | Description |
|---|---|
ValueError
|
If adj represents a bipartite graph. |
Examples:
>>> from spatial_graph_algorithms.simulate import generate
>>> from spatial_graph_algorithms.denoise import EdgeScorer
>>> sg = generate(n=100, seed=0)
>>> scores = EdgeScorer().jaccard(sg.adjacency_matrix)
>>> all(0.0 <= v <= 1.0 for v in scores.values())
True
Source code in src/spatial_graph_algorithms/denoise/__init__.py
square_bipartite(adj)
Score edges by 4-cycle participation in a bipartite graph.
True edges in a spatial bipartite graph typically close many 4-cycles (shared neighbours in the opposite partition). False edges span unrelated partitions and form fewer squares.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adj
|
csr_matrix
|
Symmetric unweighted adjacency matrix for a bipartite graph. |
required |
Returns:
| Type | Description |
|---|---|
dict[tuple[int, int], float]
|
Edge → 4-cycle count (as float). Low = suspect. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If adj does not represent a bipartite graph. |
Examples:
>>> from spatial_graph_algorithms.simulate import generate
>>> from spatial_graph_algorithms.denoise import EdgeScorer
>>> sg = generate(n=80, mode="knn_bipartite", seed=0)
>>> scores = EdgeScorer().square_bipartite(sg.adjacency_matrix)
>>> all(v >= 0 for v in scores.values())
True
Source code in src/spatial_graph_algorithms/denoise/__init__.py
square_bipartite_linalg(adj)
Alternative square_bipartite implementation using sparse matrix multiplication.
Source code in src/spatial_graph_algorithms/denoise/__init__.py
community(adj, *, n_runs=5)
Score edges by Louvain community membership consistency.
Runs the Louvain algorithm (via igraph) n_runs times. Each edge is scored by the fraction of runs it was classified as intra-community. Edges that persistently bridge communities are likely false connections.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adj
|
csr_matrix
|
Symmetric unweighted adjacency matrix. |
required |
n_runs
|
int
|
Independent Louvain repetitions. Higher = more stable scores. Default 5. |
5
|
Returns:
| Type | Description |
|---|---|
dict[tuple[int, int], float]
|
Edge → intra-community fraction in |
Examples:
>>> from spatial_graph_algorithms.simulate import generate
>>> from spatial_graph_algorithms.denoise import EdgeScorer
>>> sg = generate(n=100, seed=0)
>>> scores = EdgeScorer().community(sg.adjacency_matrix, n_runs=3)
>>> all(0.0 <= v <= 1.0 for v in scores.values())
True
Source code in src/spatial_graph_algorithms/denoise/__init__.py
random_walk(adj, *, walks_per_node=32, return_chance=0.3, expansions=1, seed=None)
Score edges by stochastic walk visitation frequency.
Performs walks_per_node random walks from every node. At each step there is a return_chance of attempting to return home. A walk only counts when the current position has two edge-disjoint paths back to the origin in the locally discovered subgraph — edges that act as bridges (typical of false connections) will have their walks discarded more often, yielding lower scores.
After normalisation, the visitation matrix is raised to the power
2 ** expansions via repeated matrix squaring (expansions = 1
computes Y @ Y), amplifying score separation between true and
false edges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adj
|
csr_matrix
|
Symmetric unweighted adjacency matrix. |
required |
walks_per_node
|
int
|
Walks launched per origin node. Default 32. |
32
|
return_chance
|
float
|
Per-step probability of attempting a return. Default 0.3. |
0.3
|
expansions
|
int
|
Number of matrix-squaring steps applied after normalisation.
Default 1 (computes |
1
|
seed
|
int
|
Random seed for reproducibility. |
None
|
Returns:
| Type | Description |
|---|---|
dict[tuple[int, int], float]
|
Edge → normalised visitation frequency. Low = suspect. |
Warns:
| Type | Description |
|---|---|
ResourceWarning
|
When adj has more than 2 000 nodes (O(n²) memory footprint). |
Examples:
>>> from spatial_graph_algorithms.simulate import generate
>>> from spatial_graph_algorithms.denoise import EdgeScorer
>>> sg = generate(n=60, seed=0)
>>> scores = EdgeScorer().random_walk(sg.adjacency_matrix, walks_per_node=4, seed=0)
>>> len(scores) == sg.n_edges
True
Source code in src/spatial_graph_algorithms/denoise/__init__.py
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 | |
degree(adj)
Score edges by the maximum degree of their two endpoints.
False edges inflate the degree of their endpoints above the baseline
set by true local connections. Scoring each edge by
max(deg_u, deg_v) highlights edges that touch anomalously
high-degree nodes.
Degree is read directly from the CSR indptr array via
np.diff(adj.indptr) — O(n), no graph construction required.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adj
|
csr_matrix
|
Symmetric unweighted adjacency matrix. |
required |
Returns:
| Type | Description |
|---|---|
dict[tuple[int, int], float]
|
Edge → |
Examples:
>>> from spatial_graph_algorithms.simulate import generate
>>> from spatial_graph_algorithms.denoise import EdgeScorer
>>> sg = generate(n=100, seed=0)
>>> scores = EdgeScorer().degree(sg.adjacency_matrix)
>>> len(scores) == sg.n_edges
True
Source code in src/spatial_graph_algorithms/denoise/__init__.py
spatial_graph_algorithms.denoise.EdgeFilterer
Remove edges from a SpatialGraph using scored edge rankings.
All methods accept a :class:SpatialGraph and a scores dict (from
:class:EdgeScorer) and return a new SpatialGraph with:
- Fewer edges in the adjacency matrix.
edge_metadata["is_removed"]boolean column (created fresh ifedge_metadatawasNone).- The largest connected component extracted — nodes that lose all edges after filtering are removed so the returned graph is always connected.
Methods:
| Name | Description |
|---|---|
by_fraction |
Remove the worst fraction of scored edges. |
by_threshold |
Remove edges above or below an explicit score value. |
by_percentile |
Remove edges outside a percentile band. |
by_optimal_f1 |
Oracle: sweep thresholds, pick the one maximising F1 vs ground truth. |
Source code in src/spatial_graph_algorithms/denoise/__init__.py
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 | |
Functions
by_fraction(sg, scores, *, fraction, method)
Remove the worst fraction of scored edges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sg
|
SpatialGraph
|
Input graph. |
required |
scores
|
dict
|
Edge scores from :class: |
required |
fraction
|
float
|
Fraction of edges to remove, in |
required |
method
|
str
|
Scoring method that produced scores. Score polarity is looked
up in :data: |
required |
Returns:
| Type | Description |
|---|---|
SpatialGraph
|
New graph with edges removed and |
Raises:
| Type | Description |
|---|---|
ValueError
|
If fraction is not in |
Examples:
>>> from spatial_graph_algorithms.simulate import generate
>>> from spatial_graph_algorithms.denoise import EdgeScorer, EdgeFilterer
>>> sg = generate(n=100, false_edges_fraction=0.1, seed=0)
>>> scores = EdgeScorer().jaccard(sg.adjacency_matrix)
>>> sg_clean = EdgeFilterer().by_fraction(
... sg, scores, fraction=0.05, method="jaccard"
... )
>>> sg_clean.n_edges < sg.n_edges
True
Source code in src/spatial_graph_algorithms/denoise/__init__.py
by_threshold(sg, scores, *, threshold, method)
Remove edges whose score crosses threshold.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sg
|
SpatialGraph
|
Input graph. |
required |
scores
|
dict
|
Edge scores from :class: |
required |
threshold
|
float
|
Score cut-off value. |
required |
method
|
str
|
Scoring method that produced scores. Score polarity is looked
up in :data: |
required |
Returns:
| Type | Description |
|---|---|
SpatialGraph
|
New graph with edges removed and |
Examples:
>>> sg_clean = EdgeFilterer().by_threshold(
... sg, scores, threshold=0.5, method="betweenness"
... )
Source code in src/spatial_graph_algorithms/denoise/__init__.py
by_percentile(sg, scores, *, percentile, method)
Remove edges outside a percentile band.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sg
|
SpatialGraph
|
Input graph. |
required |
scores
|
dict
|
Edge scores from :class: |
required |
percentile
|
float
|
Percentage of edges to remove from the worst end, in |
required |
method
|
str
|
Scoring method that produced scores. Score polarity is looked
up in :data: |
required |
Returns:
| Type | Description |
|---|---|
SpatialGraph
|
New graph with edges removed and |
Raises:
| Type | Description |
|---|---|
ValueError
|
If percentile is not in |
Examples:
Source code in src/spatial_graph_algorithms/denoise/__init__.py
by_optimal_f1(sg, scores)
Oracle filter: remove edges at the threshold that maximises F1.
Sweeps every candidate threshold and selects the one that maximises
the F1 score between removed edges and the ground-truth is_false
labels. Both score polarities are tried; the globally best threshold
wins regardless of direction.
This is an oracle method — it requires ground-truth labels and therefore only applies to simulated graphs. Use it to establish the theoretical upper bound for a given scorer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sg
|
SpatialGraph
|
Input graph. Must have |
required |
scores
|
dict
|
Edge scores from :class: |
required |
Returns:
| Type | Description |
|---|---|
SpatialGraph
|
Graph filtered at the optimal F1 threshold, with |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> from spatial_graph_algorithms.simulate import generate
>>> from spatial_graph_algorithms.denoise import EdgeScorer, EdgeFilterer
>>> from spatial_graph_algorithms.metrics import evaluate_denoising
>>> sg = generate(n=200, false_edges_fraction=0.10, seed=42)
>>> scores = EdgeScorer().jaccard(sg.adjacency_matrix)
>>> sg_opt = EdgeFilterer().by_optimal_f1(sg, scores)
>>> report = evaluate_denoising(sg_opt)
>>> report["f1"] >= 0.0
True
Source code in src/spatial_graph_algorithms/denoise/__init__.py
spatial_graph_algorithms.denoise.score_edges(sg, *, method, **kwargs)
Score all edges in sg using the specified method.
Convenience wrapper around :class:EdgeScorer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sg
|
SpatialGraph
|
Input graph. |
required |
method
|
str
|
One of |
required |
**kwargs
|
object
|
Forwarded to the scorer method (e.g. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[tuple[int, int], float]
|
Canonical edge tuples |
Raises:
| Type | Description |
|---|---|
ValueError
|
If method is not recognised. |
Examples:
>>> from spatial_graph_algorithms.simulate import generate
>>> from spatial_graph_algorithms.denoise import score_edges
>>> sg = generate(n=100, seed=0)
>>> scores = score_edges(sg, method="jaccard")
>>> len(scores) == sg.n_edges
True
Source code in src/spatial_graph_algorithms/denoise/__init__.py
spatial_graph_algorithms.denoise.denoise(sg, *, method, fraction_to_remove=0.05, **kwargs)
Score edges and remove the worst-scored fraction in one call.
Convenience wrapper combining :class:EdgeScorer with
:meth:EdgeFilterer.by_fraction. Score polarity is looked up
automatically from :data:SCORE_POLARITY.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sg
|
SpatialGraph
|
Input graph. |
required |
method
|
str
|
One of |
required |
fraction_to_remove
|
float
|
Fraction of edges to remove, in |
0.05
|
**kwargs
|
object
|
Forwarded to the scorer method. |
{}
|
Returns:
| Type | Description |
|---|---|
SpatialGraph
|
New graph with the worst-scored edges removed and |
Examples:
>>> from spatial_graph_algorithms.simulate import generate
>>> from spatial_graph_algorithms.denoise import denoise
>>> sg = generate(n=200, false_edges_fraction=0.10, seed=42)
>>> sg_clean = denoise(sg, method="jaccard", fraction_to_remove=0.05)
>>> sg_clean.n_edges < sg.n_edges
True