graph-dependence 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,26 @@
1
+ """Diagnostics that keep graph dependence and graph advantage separate."""
2
+
3
+ from .api import diagnose
4
+ from .metrics import binary_auc
5
+ from .nulls import DegreePreservingNull, degree_preserving
6
+ from .types import (
7
+ DependenceReport,
8
+ GraphFreeScorer,
9
+ GraphScorer,
10
+ Metric,
11
+ NullDraw,
12
+ NullModel,
13
+ )
14
+
15
+ __all__ = [
16
+ "DegreePreservingNull",
17
+ "DependenceReport",
18
+ "GraphFreeScorer",
19
+ "GraphScorer",
20
+ "Metric",
21
+ "NullDraw",
22
+ "NullModel",
23
+ "binary_auc",
24
+ "degree_preserving",
25
+ "diagnose",
26
+ ]
@@ -0,0 +1,143 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ import random
5
+ from collections.abc import Hashable, Sequence
6
+ from statistics import fmean
7
+ from typing import TypeVar
8
+
9
+ import networkx as nx
10
+
11
+ from .metrics import binary_auc
12
+ from .nulls import DegreePreservingNull
13
+ from .types import (
14
+ DependenceReport,
15
+ GraphFreeScorer,
16
+ GraphScorer,
17
+ Metric,
18
+ NullDraw,
19
+ NullModel,
20
+ frozen_metadata,
21
+ )
22
+
23
+ ExampleT = TypeVar("ExampleT")
24
+ NodeT = TypeVar("NodeT", bound=Hashable)
25
+
26
+
27
+ def _callable_name(value: object) -> str:
28
+ name = getattr(value, "__name__", None)
29
+ if isinstance(name, str):
30
+ return name
31
+ return type(value).__name__
32
+
33
+
34
+ def _metric_score(
35
+ predictions: Sequence[float],
36
+ targets: Sequence[float | int | bool],
37
+ metric: Metric,
38
+ ) -> float:
39
+ if len(predictions) != len(targets):
40
+ raise ValueError("a scorer must return one prediction per target")
41
+ value = float(metric(predictions, targets))
42
+ if not math.isfinite(value):
43
+ raise ValueError("metric must return a finite scalar")
44
+ return value
45
+
46
+
47
+ def _resolve_null(null_model: str | NullModel[NodeT]) -> NullModel[NodeT]:
48
+ if null_model == "degree_preserving":
49
+ return DegreePreservingNull[NodeT]()
50
+ if isinstance(null_model, str):
51
+ raise ValueError("the only built-in null model is 'degree_preserving'")
52
+ return null_model
53
+
54
+
55
+ def diagnose(
56
+ graph: nx.Graph[NodeT],
57
+ examples: Sequence[ExampleT],
58
+ targets: Sequence[float | int | bool],
59
+ graph_scorer: GraphScorer[NodeT, ExampleT],
60
+ *,
61
+ graph_free_scorer: GraphFreeScorer[ExampleT] | None = None,
62
+ null_model: str | NullModel[NodeT] = "degree_preserving",
63
+ metric: Metric = binary_auc,
64
+ null_draws: int = 1,
65
+ seed: int | None = 0,
66
+ ) -> DependenceReport:
67
+ """Measure graph dependence and comparator-relative graph advantage.
68
+
69
+ ``seed`` controls null generation only. Any randomness in scorer fitting or
70
+ evaluation remains part of the supplied scorer's procedure and should be
71
+ controlled by the caller.
72
+ """
73
+
74
+ if null_draws <= 0:
75
+ raise ValueError("null_draws must be positive")
76
+ if len(examples) != len(targets):
77
+ raise ValueError("examples and targets must have the same length")
78
+ if not examples:
79
+ raise ValueError("examples and targets must not be empty")
80
+
81
+ frozen_examples = tuple(examples)
82
+ frozen_targets = tuple(targets)
83
+ observed_predictions = graph_scorer(graph, frozen_examples)
84
+ observed_score = _metric_score(observed_predictions, frozen_targets, metric)
85
+
86
+ model = _resolve_null(null_model)
87
+ seed_stream = random.Random(seed)
88
+ draw_scores: list[float] = []
89
+ draw_metadata: list[object] = []
90
+ draw_seeds: list[int | None] = []
91
+ for _ in range(null_draws):
92
+ draw_seed = None if seed is None else seed_stream.randrange(2**63)
93
+ raw_draw = model(graph.copy(), seed=draw_seed)
94
+ if isinstance(raw_draw, NullDraw):
95
+ draw = raw_draw
96
+ elif isinstance(raw_draw, nx.Graph):
97
+ draw = NullDraw(graph=raw_draw, metadata=frozen_metadata({}))
98
+ else:
99
+ raise TypeError("a null model must return NullDraw or networkx.Graph")
100
+ if draw.graph is graph:
101
+ raise ValueError("a null model must return a fresh graph")
102
+ null_predictions = graph_scorer(draw.graph, frozen_examples)
103
+ draw_scores.append(_metric_score(null_predictions, frozen_targets, metric))
104
+ draw_seeds.append(draw_seed)
105
+ draw_metadata.append(draw.metadata)
106
+
107
+ null_score = fmean(draw_scores)
108
+ comparator_score: float | None = None
109
+ if graph_free_scorer is not None:
110
+ comparator_predictions = graph_free_scorer(frozen_examples)
111
+ comparator_score = _metric_score(comparator_predictions, frozen_targets, metric)
112
+
113
+ model_name = getattr(model, "name", _callable_name(model))
114
+ if not isinstance(model_name, str):
115
+ model_name = _callable_name(model)
116
+ metadata = frozen_metadata(
117
+ {
118
+ "evaluation_examples": len(frozen_examples),
119
+ "null_draws": null_draws,
120
+ "null_draw_seeds": tuple(draw_seeds),
121
+ "null_draw_metadata": tuple(draw_metadata),
122
+ "graph_scorer": _callable_name(graph_scorer),
123
+ "graph_free_scorer": (
124
+ _callable_name(graph_free_scorer)
125
+ if graph_free_scorer is not None
126
+ else None
127
+ ),
128
+ }
129
+ )
130
+ return DependenceReport(
131
+ dependence=observed_score - null_score,
132
+ advantage=(
133
+ observed_score - comparator_score if comparator_score is not None else None
134
+ ),
135
+ null_survival=(null_score / observed_score if observed_score > 0 else None),
136
+ observed_score=observed_score,
137
+ null_score=null_score,
138
+ comparator_score=comparator_score,
139
+ metric_name=_callable_name(metric),
140
+ null_model_name=model_name,
141
+ seed=seed,
142
+ metadata=metadata,
143
+ )
@@ -0,0 +1,49 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from collections.abc import Sequence
5
+
6
+
7
+ def binary_auc(
8
+ predictions: Sequence[float],
9
+ targets: Sequence[float | int | bool],
10
+ ) -> float:
11
+ """Return binary ROC AUC, assigning tied scores their average rank.
12
+
13
+ The implementation is the normalized Mann--Whitney statistic. Targets must
14
+ be exactly zero or one, and both classes must be present.
15
+ """
16
+
17
+ if len(predictions) != len(targets):
18
+ raise ValueError("predictions and targets must have the same length")
19
+ if not predictions:
20
+ raise ValueError("predictions and targets must not be empty")
21
+
22
+ pairs: list[tuple[float, int]] = []
23
+ for prediction, target in zip(predictions, targets, strict=True):
24
+ score = float(prediction)
25
+ label_value = float(target)
26
+ if not math.isfinite(score):
27
+ raise ValueError("predictions must be finite")
28
+ if label_value not in (0.0, 1.0):
29
+ raise ValueError("binary_auc targets must be zero or one")
30
+ pairs.append((score, int(label_value)))
31
+
32
+ pairs.sort(key=lambda item: item[0])
33
+ positive_count = sum(label for _, label in pairs)
34
+ negative_count = len(pairs) - positive_count
35
+ if positive_count == 0 or negative_count == 0:
36
+ raise ValueError("binary_auc requires both positive and negative targets")
37
+
38
+ positive_rank_sum = 0.0
39
+ start = 0
40
+ while start < len(pairs):
41
+ stop = start + 1
42
+ while stop < len(pairs) and pairs[stop][0] == pairs[start][0]:
43
+ stop += 1
44
+ average_rank = ((start + 1) + stop) / 2.0
45
+ positive_rank_sum += average_rank * sum(label for _, label in pairs[start:stop])
46
+ start = stop
47
+
48
+ mann_whitney = positive_rank_sum - positive_count * (positive_count + 1) / 2
49
+ return mann_whitney / (positive_count * negative_count)
@@ -0,0 +1,150 @@
1
+ from __future__ import annotations
2
+
3
+ import random
4
+ from collections.abc import Hashable
5
+ from dataclasses import dataclass, field
6
+ from typing import Generic, TypeVar
7
+
8
+ import networkx as nx
9
+
10
+ from .types import NullDraw, frozen_metadata
11
+
12
+ NodeT = TypeVar("NodeT", bound=Hashable)
13
+ Edge = tuple[NodeT, NodeT]
14
+ EdgeKey = frozenset[NodeT]
15
+
16
+
17
+ def _edge_key(edge: Edge[NodeT]) -> EdgeKey[NodeT]:
18
+ return frozenset(edge)
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class DegreePreservingNull(Generic[NodeT]):
23
+ """A fixed-budget double-edge-swap null for simple, unweighted graphs.
24
+
25
+ ``forbidden_edges`` are pairs that a draw may not introduce. A forbidden
26
+ pair already present in the intact graph may be retained, but once removed
27
+ it is not reintroduced.
28
+ """
29
+
30
+ attempts_per_edge: int = 10
31
+ forbidden_edges: tuple[Edge[NodeT], ...] = ()
32
+ name: str = field(default="degree_preserving", init=False)
33
+
34
+ def __post_init__(self) -> None:
35
+ if self.attempts_per_edge <= 0:
36
+ raise ValueError("attempts_per_edge must be positive")
37
+
38
+ def __call__(self, graph: nx.Graph[NodeT], *, seed: int | None) -> NullDraw[NodeT]:
39
+ if graph.is_directed():
40
+ raise TypeError("DegreePreservingNull requires an undirected graph")
41
+ if graph.is_multigraph():
42
+ raise TypeError("DegreePreservingNull requires a simple graph")
43
+ if any(left == right for left, right in graph.edges()):
44
+ raise ValueError("DegreePreservingNull does not admit self-loops")
45
+ if any(attributes for _, _, attributes in graph.edges(data=True)):
46
+ raise ValueError(
47
+ "edge attributes are not supported because swaps would require "
48
+ "an explicit attribute-assignment rule"
49
+ )
50
+
51
+ work = graph.copy()
52
+ edges: list[Edge[NodeT]] = list(work.edges())
53
+ intact_keys = {_edge_key(edge) for edge in edges}
54
+ forbidden = {_edge_key(edge) for edge in self.forbidden_edges} - intact_keys
55
+ live = set(intact_keys)
56
+ intact_degrees = dict(graph.degree())
57
+ edge_count = len(edges)
58
+ attempts = self.attempts_per_edge * edge_count
59
+ accepted = 0
60
+ rejections = {
61
+ "self_loop": 0,
62
+ "duplicate": 0,
63
+ "forbidden": 0,
64
+ "degenerate": 0,
65
+ }
66
+ rng = random.Random(seed)
67
+
68
+ if edge_count >= 2:
69
+ for _ in range(attempts):
70
+ left_index, right_index = rng.sample(range(edge_count), 2)
71
+ left = edges[left_index]
72
+ right = edges[right_index]
73
+ a, b = left if rng.getrandbits(1) else (left[1], left[0])
74
+ c, d = right if rng.getrandbits(1) else (right[1], right[0])
75
+ proposed_left = (a, d)
76
+ proposed_right = (c, b)
77
+
78
+ if a == d or c == b:
79
+ rejections["self_loop"] += 1
80
+ continue
81
+
82
+ old_keys = {_edge_key(left), _edge_key(right)}
83
+ new_keys = {_edge_key(proposed_left), _edge_key(proposed_right)}
84
+ if len(new_keys) != 2:
85
+ rejections["duplicate"] += 1
86
+ continue
87
+ if new_keys == old_keys:
88
+ rejections["degenerate"] += 1
89
+ continue
90
+ remaining = live - old_keys
91
+ if new_keys & remaining:
92
+ rejections["duplicate"] += 1
93
+ continue
94
+ if new_keys & forbidden:
95
+ rejections["forbidden"] += 1
96
+ continue
97
+
98
+ work.remove_edge(*left)
99
+ work.remove_edge(*right)
100
+ work.add_edge(*proposed_left)
101
+ work.add_edge(*proposed_right)
102
+ live.difference_update(old_keys)
103
+ live.update(new_keys)
104
+ edges[left_index] = proposed_left
105
+ edges[right_index] = proposed_right
106
+ accepted += 1
107
+
108
+ output_keys = {_edge_key(edge) for edge in work.edges()}
109
+ degree_preserved = dict(work.degree()) == intact_degrees
110
+ edge_count_preserved = work.number_of_edges() == graph.number_of_edges()
111
+ forbidden_violations = len(output_keys & forbidden)
112
+ if not degree_preserved or not edge_count_preserved or forbidden_violations:
113
+ raise RuntimeError("degree-preserving sampler violated an invariant")
114
+
115
+ retained = len(output_keys & intact_keys)
116
+ metadata = frozen_metadata(
117
+ {
118
+ "sampler": "fixed_budget_double_edge_swap",
119
+ "seed": seed,
120
+ "attempts_per_edge": self.attempts_per_edge,
121
+ "attempted_swaps": attempts,
122
+ "accepted_swaps": accepted,
123
+ "rejections": frozen_metadata(rejections),
124
+ "edge_count": edge_count,
125
+ "edge_count_preserved": edge_count_preserved,
126
+ "labeled_degree_preserved": degree_preserved,
127
+ "forbidden_edge_violations": forbidden_violations,
128
+ "edge_retention_fraction": (
129
+ retained / edge_count if edge_count else 1.0
130
+ ),
131
+ "components_observed": nx.number_connected_components(graph),
132
+ "components_null": nx.number_connected_components(work),
133
+ }
134
+ )
135
+ return NullDraw(graph=work, metadata=metadata)
136
+
137
+
138
+ def degree_preserving(
139
+ graph: nx.Graph[NodeT],
140
+ *,
141
+ seed: int | None = None,
142
+ attempts_per_edge: int = 10,
143
+ forbidden_edges: tuple[Edge[NodeT], ...] = (),
144
+ ) -> NullDraw[NodeT]:
145
+ """Functional interface to :class:`DegreePreservingNull`."""
146
+
147
+ return DegreePreservingNull[NodeT](
148
+ attempts_per_edge=attempts_per_edge,
149
+ forbidden_edges=forbidden_edges,
150
+ )(graph, seed=seed)
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,107 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Hashable, Mapping, Sequence
4
+ from dataclasses import dataclass
5
+ from types import MappingProxyType
6
+ from typing import Generic, Protocol, TypeVar
7
+
8
+ import networkx as nx
9
+
10
+ ExampleT_contra = TypeVar("ExampleT_contra", contravariant=True)
11
+ NodeT = TypeVar("NodeT", bound=Hashable)
12
+ NodeT_scorer = TypeVar("NodeT_scorer", bound=Hashable)
13
+
14
+
15
+ class GraphScorer(Protocol[NodeT_scorer, ExampleT_contra]):
16
+ """Score evaluation examples using a graph condition."""
17
+
18
+ def __call__(
19
+ self,
20
+ graph: nx.Graph[NodeT_scorer],
21
+ examples: Sequence[ExampleT_contra],
22
+ /,
23
+ ) -> Sequence[float]: ...
24
+
25
+
26
+ class GraphFreeScorer(Protocol[ExampleT_contra]):
27
+ """Score the same evaluation examples without access to a graph."""
28
+
29
+ def __call__(self, examples: Sequence[ExampleT_contra], /) -> Sequence[float]: ...
30
+
31
+
32
+ class Metric(Protocol):
33
+ """Reduce predictions and targets to a scalar where larger is better."""
34
+
35
+ def __call__(
36
+ self,
37
+ predictions: Sequence[float],
38
+ targets: Sequence[float | int | bool],
39
+ /,
40
+ ) -> float: ...
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class NullDraw(Generic[NodeT]):
45
+ """One graph sampled from a declared null model."""
46
+
47
+ graph: nx.Graph[NodeT]
48
+ metadata: Mapping[str, object]
49
+
50
+
51
+ class NullModel(Protocol[NodeT]):
52
+ """Generate a fresh null graph and describe the implemented draw."""
53
+
54
+ @property
55
+ def name(self) -> str:
56
+ """Stable, human-readable null-model name."""
57
+ ...
58
+
59
+ def __call__(
60
+ self, graph: nx.Graph[NodeT], /, *, seed: int | None
61
+ ) -> NullDraw[NodeT] | nx.Graph[NodeT]: ...
62
+
63
+
64
+ def frozen_metadata(values: Mapping[str, object]) -> Mapping[str, object]:
65
+ """Return a shallow immutable copy suitable for a frozen result object."""
66
+
67
+ return MappingProxyType(dict(values))
68
+
69
+
70
+ def _plain(value: object) -> object:
71
+ if isinstance(value, Mapping):
72
+ return {str(key): _plain(item) for key, item in value.items()}
73
+ if isinstance(value, tuple):
74
+ return [_plain(item) for item in value]
75
+ return value
76
+
77
+
78
+ @dataclass(frozen=True)
79
+ class DependenceReport:
80
+ """The two contrasts, their three reference scores, and null diagnostics."""
81
+
82
+ dependence: float
83
+ advantage: float | None
84
+ null_survival: float | None
85
+ observed_score: float
86
+ null_score: float
87
+ comparator_score: float | None
88
+ metric_name: str
89
+ null_model_name: str
90
+ seed: int | None
91
+ metadata: Mapping[str, object]
92
+
93
+ def to_dict(self) -> dict[str, object]:
94
+ """Return a JSON-compatible representation."""
95
+
96
+ return {
97
+ "dependence": self.dependence,
98
+ "advantage": self.advantage,
99
+ "null_survival": self.null_survival,
100
+ "observed_score": self.observed_score,
101
+ "null_score": self.null_score,
102
+ "comparator_score": self.comparator_score,
103
+ "metric_name": self.metric_name,
104
+ "null_model_name": self.null_model_name,
105
+ "seed": self.seed,
106
+ "metadata": _plain(self.metadata),
107
+ }
@@ -0,0 +1,211 @@
1
+ Metadata-Version: 2.4
2
+ Name: graph-dependence
3
+ Version: 0.1.0
4
+ Summary: Minimal diagnostics that separate graph dependence from graph advantage.
5
+ Project-URL: Homepage, https://third-wheel.github.io/dependence-is-not-advantage/
6
+ Project-URL: Documentation, https://github.com/Third-Wheel/dependence-is-not-advantage#readme
7
+ Project-URL: Paper, https://www.alphaxiv.org/abs/2608.dependence-is-not-advantage
8
+ Project-URL: Repository, https://github.com/Third-Wheel/dependence-is-not-advantage
9
+ Project-URL: Issues, https://github.com/Third-Wheel/dependence-is-not-advantage/issues
10
+ Author-email: Prahas Duggireddy <prahasduggireddy@thirdwheel.ai>
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE
13
+ Keywords: evaluation,graph ablation,graph learning,link prediction,null model
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: License :: OSI Approved :: Apache Software License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
24
+ Requires-Python: >=3.11
25
+ Requires-Dist: networkx<4,>=3.2
26
+ Provides-Extra: dev
27
+ Requires-Dist: mypy>=1.17; extra == 'dev'
28
+ Requires-Dist: pytest-cov>=6.2; extra == 'dev'
29
+ Requires-Dist: pytest>=8.4; extra == 'dev'
30
+ Requires-Dist: ruff>=0.12; extra == 'dev'
31
+ Requires-Dist: types-networkx>=3.2; extra == 'dev'
32
+ Provides-Extra: release
33
+ Requires-Dist: build>=1.2; extra == 'release'
34
+ Requires-Dist: twine>=6.1; extra == 'release'
35
+ Description-Content-Type: text/markdown
36
+
37
+ # Graph Dependence
38
+
39
+ This repository contains the reference implementation for [_Dependence Is Not
40
+ Advantage: What Randomizing the Graph Does Not
41
+ Measure_](https://www.alphaxiv.org/abs/2608.dependence-is-not-advantage). The
42
+ paper is by Prahas Duggireddy and the package is maintained by Third Wheel.
43
+
44
+ The package reports two comparisons that are easy to mix up in graph-ablation
45
+ studies:
46
+
47
+ - **Dependence:** how a graph procedure changes when the observed graph is
48
+ replaced by a stated graph null.
49
+ - **Advantage:** how that procedure compares with a named scorer that does not
50
+ receive the graph.
51
+
52
+ Randomization answers the first question. It does not answer the second one by
53
+ itself. The implementation is intentionally small, typed, and close to these
54
+ definitions. Version 0.1.0 is an early reference implementation, not a general
55
+ graph-learning framework or a full reproduction of the paper.
56
+
57
+ Paper and project links:
58
+
59
+ - [Preprint](https://www.alphaxiv.org/abs/2608.dependence-is-not-advantage)
60
+ - [Project page](https://third-wheel.github.io/dependence-is-not-advantage/)
61
+ - [Source on GitHub](https://github.com/Third-Wheel/dependence-is-not-advantage)
62
+ - [Citation metadata](CITATION.cff)
63
+
64
+ ## Quick start
65
+
66
+ The smallest complete example needs no network access. From a checkout:
67
+
68
+ ```bash
69
+ python -m pip install .
70
+ python examples/minimal.py
71
+ ```
72
+
73
+ It uses a fixed graph, fixed node-content features, a degree-preserving null,
74
+ and seed 7. The command prints a JSON-compatible report that is small enough
75
+ to read alongside the source.
76
+
77
+ For an evaluation of your own, the central call looks like this:
78
+
79
+ ```python
80
+ from graph_dependence import DegreePreservingNull, binary_auc, diagnose
81
+
82
+ # Provide these objects from your evaluation protocol.
83
+ report = diagnose(
84
+ graph=graph,
85
+ examples=examples,
86
+ targets=targets,
87
+ graph_scorer=score_with_graph,
88
+ graph_free_scorer=score_without_graph,
89
+ null_model=DegreePreservingNull(attempts_per_edge=10),
90
+ metric=binary_auc,
91
+ null_draws=10,
92
+ seed=7,
93
+ )
94
+ print(report.to_dict())
95
+ ```
96
+
97
+ The call keeps the intact, null, and graph-free comparator scores together.
98
+ The resulting report can be serialized with `to_dict()` without a custom
99
+ encoder.
100
+
101
+ ## What the report means
102
+
103
+ | Field | Comparison | Interpretation |
104
+ | --------------- | ----------------------------------- | ---------------------------------------------------------------- |
105
+ | `dependence` | `observed_score - null_score` | Change under the declared graph intervention. |
106
+ | `advantage` | `observed_score - comparator_score` | Difference from the named graph-free scorer. |
107
+ | `null_survival` | `null_score / observed_score` | Fraction of the observed score that remains after randomization. |
108
+
109
+ `advantage` is `None` when no graph-free scorer is supplied. `null_survival` is
110
+ `None` when the observed score is not positive, because the ratio is undefined
111
+ there. The report also records the three reference scores, the seed, the null
112
+ model name, and sampler diagnostics.
113
+
114
+ ## The public API
115
+
116
+ | Symbol | Use |
117
+ | ------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
118
+ | `diagnose` | Evaluate the intact, null, and optional graph-free arms and return one report. |
119
+ | `DegreePreservingNull` | Generate fixed-budget double-edge-swap null graphs and record the checks performed. |
120
+ | `DependenceReport` | Store scores, contrasts, seed, and metadata; `to_dict()` returns JSON-compatible values. |
121
+ | `binary_auc` | Provide a small dependency-free binary ranking metric for examples and tests. |
122
+ | `GraphScorer`, `GraphFreeScorer`, `Metric`, `NullModel` | Define the typed callable boundaries supplied by the caller. |
123
+
124
+ The formal definitions, empirical results, and claim boundaries remain in the
125
+ paper. The package implements the diagnostic around them; it does not recreate
126
+ the paper's training runs or manuscript tables.
127
+
128
+ ## Supplying scorers and metrics
129
+
130
+ A graph scorer receives a NetworkX graph and the evaluation examples. A
131
+ graph-free scorer receives the same examples without the graph. Both return one
132
+ score per example. A metric receives those scores and the targets and returns a
133
+ scalar, with larger values meaning better performance.
134
+
135
+ ```python
136
+ def score_with_graph(graph, examples):
137
+ return [len(list(nx.common_neighbors(graph, u, v))) for u, v in examples]
138
+
139
+
140
+ def score_without_graph(examples):
141
+ return [content_similarity[u, v] for u, v in examples]
142
+ ```
143
+
144
+ Custom scorers and metrics are ordinary callables. If a scorer trains a model
145
+ or uses randomness, condition-specific fitting and seed control are the
146
+ caller's responsibility. The `seed` argument controls null generation only.
147
+
148
+ ## The degree-preserving null
149
+
150
+ `DegreePreservingNull` applies a fixed budget of double-edge-swap attempts to
151
+ an undirected, simple, unweighted graph. It rejects self-loops, duplicate
152
+ edges, and new edges listed in `forbidden_edges`. Each draw records accepted
153
+ swaps, edge retention, component counts, and explicit degree and edge-count
154
+ checks.
155
+
156
+ Degree preservation describes a constraint, not a unique probability
157
+ distribution. The implementation records its sampler and budget and does not
158
+ claim uniform sampling over all graphs with the same degree sequence. Edge
159
+ attributes are rejected because assigning them to newly formed edges would
160
+ silently define a different intervention.
161
+
162
+ ## Public-data example
163
+
164
+ [`examples/cora.py`](examples/cora.py) downloads the public Cora citation graph,
165
+ constructs a deterministic link-prediction split, and compares
166
+ common-neighbor scores with a graph-free bag-of-words Jaccard scorer:
167
+
168
+ ```bash
169
+ python examples/cora.py
170
+ ```
171
+
172
+ This is an API example, not a reproduction of the paper's Cora row. The paper
173
+ uses the published HeaRT split, its hard negatives, and Hits@20. The example
174
+ uses a small deterministic split and AUC so that it can remain independent of
175
+ a training framework.
176
+
177
+ ## Repository layout
178
+
179
+ ```text
180
+ src/graph_dependence/ package implementation and py.typed marker
181
+ examples/minimal.py deterministic, network-free example
182
+ examples/cora.py optional public-data example
183
+ tests/ package and scientific-boundary tests
184
+ site/ paper page, searchable PDF, figure, and citations
185
+ ```
186
+
187
+ The paper and visible landing page are authoritative for scholarly claims.
188
+ `pyproject.toml` is authoritative for package version and support metadata;
189
+ `CITATION.cff` is authoritative for software citation metadata.
190
+
191
+ ## Scope
192
+
193
+ This repository does not train GraphSAGE, recreate manuscript tables, prescribe
194
+ a universally valid null model, or turn predictive improvement into evidence of
195
+ downstream recommendation benefit. It is a reference implementation for
196
+ separating dependence from advantage in an evaluation protocol.
197
+
198
+ For the formal definitions and empirical study, see the [paper](https://www.alphaxiv.org/abs/2608.dependence-is-not-advantage). For software reuse,
199
+ cite the version used and see [`CITATION.cff`](CITATION.cff).
200
+
201
+ ## Development
202
+
203
+ The package supports Python 3.11 and newer. To run the local checks after an
204
+ editable install:
205
+
206
+ ```bash
207
+ python -m pip install -e '.[dev]'
208
+ ruff check .
209
+ mypy --strict .
210
+ pytest --cov=graph_dependence --cov-branch
211
+ ```
@@ -0,0 +1,10 @@
1
+ graph_dependence/__init__.py,sha256=BvDsINCneYu4KEQzpINJMZN4TDfxOnLiuMw21Xa6ZME,532
2
+ graph_dependence/api.py,sha256=y3Uu8pvAL-BhbfCvcrgzlDnCil-zkcF7z0CaaFvTndc,4949
3
+ graph_dependence/metrics.py,sha256=JJFvLfefX5GQ6WSVkuN8-q_ZH_OuBSljUAtx5cU1RJg,1838
4
+ graph_dependence/nulls.py,sha256=hw3faGenHEOIKCiEtvsZNgcXuRO00fx1P2SYgGG79V0,5814
5
+ graph_dependence/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
6
+ graph_dependence/types.py,sha256=PC_U2iq3sqNoaeaKhqur6ipHU0cRkDPYQBcoAKU5bzk,3086
7
+ graph_dependence-0.1.0.dist-info/METADATA,sha256=GFeIOYpczEGlJ0PpmzeOZ2qfHuV2h50-rr017NGWQNw,9469
8
+ graph_dependence-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
9
+ graph_dependence-0.1.0.dist-info/licenses/LICENSE,sha256=Hq7LHlYyCrLQl1rGbv32wsekHtNuXaWVbi7xxhvmoNE,11329
10
+ graph_dependence-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,204 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work
42
+ and for which the editorial revisions, annotations, elaborations,
43
+ or other modifications represent, as a whole, an original work of
44
+ authorship. For the purposes of this License, Derivative Works
45
+ shall not include works that remain separable from, or merely link
46
+ (or bind by name) to the interfaces of, the Work and Derivative
47
+ Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright
53
+ owner or by an individual or Legal Entity authorized to submit on
54
+ behalf of the copyright owner. For the purposes of this definition,
55
+ "submitted" means any form of electronic, verbal, or written
56
+ communication sent to the Licensor or its representatives, including
57
+ but not limited to communication on electronic mailing lists, source
58
+ code control systems, and issue tracking systems that are managed by,
59
+ or on behalf of, the Licensor for the purpose of discussing and
60
+ improving the Work, but excluding communication that is conspicuously
61
+ marked or otherwise designated in writing by the copyright owner as
62
+ "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute
110
+ must include a readable copy of the attribution notices
111
+ contained within such NOTICE file, excluding those notices
112
+ that do not pertain to any part of the Derivative Works, in
113
+ at least one of the following places: within a NOTICE text
114
+ file distributed as part of the Derivative Works; within the
115
+ Source form or documentation, if provided along with the
116
+ Derivative Works; or, within a display generated by the
117
+ Derivative Works, if and wherever such third-party notices
118
+ normally appear. The contents of the NOTICE file are for
119
+ informational purposes only and do not modify the License.
120
+ You may add Your own attribution notices within Derivative
121
+ Works that You distribute, alongside or as an addendum to
122
+ the NOTICE text from the Work, provided that such additional
123
+ attribution notices cannot be construed as modifying the
124
+ License.
125
+
126
+ You may add Your own copyright statement to Your modifications and
127
+ may provide additional or different license terms and conditions
128
+ for use, reproduction, or distribution of Your modifications, or
129
+ for any such Derivative Works as a whole, provided Your use,
130
+ reproduction, and distribution of the Work otherwise complies with
131
+ the conditions stated in this License.
132
+
133
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
134
+ any Contribution intentionally submitted for inclusion in the Work
135
+ by You to the Licensor shall be under the terms and conditions of
136
+ this License, without any additional terms or conditions.
137
+ Notwithstanding the above, nothing herein shall supersede or modify
138
+ the terms of any separate license agreement you may have executed
139
+ with Licensor regarding such Contributions.
140
+
141
+ 6. Trademarks. This License does not grant permission to use the trade
142
+ names, trademarks, service marks, or product names of the Licensor,
143
+ except as required for reasonable and customary use in describing
144
+ the origin of the Work and reproducing the content of the NOTICE file.
145
+
146
+ 7. Disclaimer of Warranty. Unless required by applicable law or
147
+ agreed to in writing, Licensor provides the Work (and each
148
+ Contributor provides its Contributions) on an "AS IS" BASIS,
149
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
150
+ implied, including, without limitation, any warranties or conditions
151
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
152
+ PARTICULAR PURPOSE. You are solely responsible for determining the
153
+ appropriateness of using or redistributing the Work and assume any
154
+ risks associated with Your exercise of permissions under this License.
155
+
156
+ 8. Limitation of Liability. In no event and under no legal theory,
157
+ whether in tort (including negligence), contract, or otherwise,
158
+ unless required by applicable law (such as deliberate and grossly
159
+ negligent acts) or agreed to in writing, shall any Contributor be
160
+ liable to You for damages, including any direct, indirect, special,
161
+ incidental, or consequential damages of any character arising as
162
+ a result of this License or out of the use or inability to use the
163
+ Work (including but not limited to damages for loss of goodwill,
164
+ work stoppage, computer failure or malfunction, or any and all
165
+ other commercial damages or losses), even if such Contributor has
166
+ been advised of the possibility of such damages.
167
+
168
+ 9. Accepting Warranty or Additional Liability. While redistributing
169
+ the Work or Derivative Works thereof, You may choose to offer,
170
+ and charge a fee for, acceptance of support, warranty, indemnity,
171
+ or other liability obligations and/or rights consistent with this
172
+ License. However, in accepting such obligations, You may act only
173
+ on Your own behalf and on Your sole responsibility, not on behalf
174
+ of any other Contributor, and only if You agree to indemnify,
175
+ defend, and hold each Contributor harmless for any liability
176
+ incurred by, or claims asserted against, such Contributor by reason
177
+ of your accepting any such warranty or additional liability.
178
+
179
+ END OF TERMS AND CONDITIONS
180
+
181
+ APPENDIX: How to apply the Apache License to your work.
182
+
183
+ To apply the Apache License to your work, attach the following
184
+ boilerplate notice, with the fields enclosed by brackets "[]"
185
+ replaced with your own identifying information. (Don't include
186
+ the brackets!) The text should be enclosed in the appropriate
187
+ comment syntax for the file format. We also recommend that a
188
+ file or class name and description of purpose be included on the
189
+ same "printed page" as the copyright notice for easier
190
+ identification within third-party archives.
191
+
192
+ Copyright 2026 Third Wheel
193
+
194
+ Licensed under the Apache License, Version 2.0 (the "License");
195
+ you may not use this file except in compliance with the License.
196
+ You may obtain a copy of the License at
197
+
198
+ http://www.apache.org/licenses/LICENSE-2.0
199
+
200
+ Unless required by applicable law or agreed to in writing, software
201
+ distributed under the License is distributed on an "AS IS" BASIS,
202
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
203
+ See the License for the specific language governing permissions and
204
+ limitations under the License.