Skip to content

Commit 49f6b46

Browse files
Graph Centrality (#11897)
* Initial commit: Implement graph centrality algorithms for weighted graphs - Added core functionality to compute central and median nodes in a weighted graph using: - Floyd-Warshall algorithm for calculating all-pairs shortest paths - Eccentricity for determining the central node - Harmonic closeness centrality for determining the median node - Developed utility functions to handle graph data and validate positive edge weights - Included extensive doctests to verify functionality across various graph types: - Single-node, disconnected, fully connected, cyclic, and directed acyclic graphs (DAGs) - Improved code modularity and readability by refactoring functions - Enforced code style and consistency with `ruff` and `black` formatting - Documented the algorithmic approach, complexity, and example applications in the module docstring * Implement style changes suggested by bot. * updating DIRECTORY.md * Fix formatting and improve documentation clarity --------- Co-authored-by: Christian Clauss <cclauss@me.com> Co-authored-by: cclauss <cclauss@users.noreply.github.com>
1 parent d51160d commit 49f6b46

2 files changed

Lines changed: 387 additions & 0 deletions

File tree

‎DIRECTORY.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -640,6 +640,7 @@
640640
* [Gale Shapley Bigraph](graphs/gale_shapley_bigraph.py)
641641
* [Graph Adjacency List](graphs/graph_adjacency_list.py)
642642
* [Graph Adjacency Matrix](graphs/graph_adjacency_matrix.py)
643+
* [Graph Centrality](graphs/graph_centrality.py)
643644
* [Graph List](graphs/graph_list.py)
644645
* [Graphs Floyd Warshall](graphs/graphs_floyd_warshall.py)
645646
* [Greedy Best First](graphs/greedy_best_first.py)

‎graphs/graph_centrality.py‎

Lines changed: 386 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,386 @@
1+
"""
2+
Graph Centrality Algorithms for Determining Central and Median Nodes in a Graph.
3+
4+
This module provides functions to compute the central and median nodes in a weighted
5+
graph based on graph-theoretical centrality measures. The central node minimizes the
6+
maximum shortest-path distance to all other reachable nodes (eccentricity), while the
7+
median node maximizes the sum of the reciprocals of the shortest-path distances to all
8+
other reachable nodes (harmonic closeness centrality).
9+
10+
Problem Description:
11+
Given a weighted graph G = (V, E), where V is the set of vertices, and E is the set of
12+
edges with positive weights representing distances between nodes, determine:
13+
14+
- Central Node: The node with minimal eccentricity. The eccentricity of a node v is
15+
defined as the greatest distance between v and any other node reachable from v.
16+
17+
- Median Node: The node with maximal harmonic closeness centrality. The harmonic
18+
closeness centrality of a node v is the sum of the reciprocals of the shortest-path
19+
distances from v to all other reachable nodes.
20+
21+
Algorithms Implemented:
22+
- Floyd-Warshall Algorithm for All-Pairs Shortest Paths.
23+
- Calculation of Eccentricity and Harmonic Closeness Centrality.
24+
25+
Algorithm Descriptions:
26+
27+
Floyd-Warshall Algorithm (Pseudo-code):
28+
---------------------------------------
29+
for k from 1 to N:
30+
for i from 1 to N:
31+
for j from 1 to N:
32+
if distance[i][j] > distance[i][k] + distance[k][j]:
33+
distance[i][j] = distance[i][k] + distance[k][j]
34+
35+
Central and Median Node Calculation:
36+
------------------------------------
37+
For each node i:
38+
- Eccentricity[i] = maximum distance from node i to any other reachable node.
39+
- Closeness[i] = sum of reciprocals of distances from node i to all reachable nodes.
40+
41+
Select:
42+
- Central Node: node with minimal eccentricity.
43+
- Median Node: node with maximal closeness.
44+
45+
References:
46+
- https://en.wikipedia.org/wiki/Centrality
47+
- Floyd-Warshall Algorithm: https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm
48+
- Closeness Centrality: https://en.wikipedia.org/wiki/Closeness_centrality
49+
50+
Example Application:
51+
These algorithms can be applied to real-world problems, such as determining the optimal
52+
location for facilities (e.g., emergency response centers) to minimize response times
53+
within a network. By identifying the central or median nodes, organizations can make
54+
informed decisions on resource placement to improve efficiency and accessibility.
55+
"""
56+
57+
import numpy as np
58+
59+
60+
def initialize_distance_matrix(
61+
graph: dict[int, list[tuple[int, float]]], number_of_nodes: int
62+
) -> np.ndarray:
63+
"""Initialize the distance matrix and validate edge weights.
64+
65+
Args:
66+
graph: The graph represented as an adjacency list.
67+
number_of_nodes: The total number of nodes in the graph.
68+
69+
Returns:
70+
A numpy.ndarray representing the initialized distance matrix.
71+
72+
Raises:
73+
ValueError: If any edge has a non-positive weight.
74+
"""
75+
distance_matrix: np.ndarray = np.full((number_of_nodes, number_of_nodes), np.inf)
76+
np.fill_diagonal(distance_matrix, 0)
77+
78+
for node_index, edges in graph.items():
79+
for neighbor_index, edge_weight in edges:
80+
if edge_weight <= 0:
81+
error_message: str = (
82+
f"Edge weight must be positive. Found {edge_weight} between "
83+
f"nodes {node_index} and {neighbor_index}."
84+
)
85+
raise ValueError(error_message)
86+
distance_matrix[node_index, neighbor_index] = edge_weight
87+
88+
return distance_matrix
89+
90+
91+
def floyd_warshall_algorithm(graph: dict[int, list[tuple[int, float]]]) -> np.ndarray:
92+
"""Compute all-pairs shortest paths using the Floyd-Warshall algorithm.
93+
94+
Floyd-Warshall Complexity:
95+
--------------------------
96+
Time Complexity: O(N^3), where N is the number of nodes.
97+
Space Complexity: O(N^2), for storing the distance matrix.
98+
99+
Args:
100+
graph: The graph represented as an adjacency list.
101+
102+
Returns:
103+
The distance matrix with the shortest paths between all pairs of nodes.
104+
"""
105+
number_of_nodes: int = len(graph)
106+
distance_matrix: np.ndarray = initialize_distance_matrix(graph, number_of_nodes)
107+
108+
for k in range(number_of_nodes):
109+
# Use broadcasting to update the distance matrix in place
110+
distance_matrix[:] = np.minimum(
111+
distance_matrix,
112+
distance_matrix[:, k][:, np.newaxis] + distance_matrix[k, :],
113+
)
114+
115+
return distance_matrix
116+
117+
118+
def get_reachable_distances(distances: np.ndarray) -> np.ndarray:
119+
"""Filter reachable distances, excluding infinite values (unreachable nodes).
120+
121+
Args:
122+
distances: Array of shortest-path distances from a specific node.
123+
124+
Returns:
125+
An array of distances to reachable nodes only (finite values).
126+
"""
127+
return distances[np.isfinite(distances) & (distances != 0)]
128+
129+
130+
def find_central_node(
131+
eccentricities: list[tuple[int, float]],
132+
) -> tuple[int, float]:
133+
"""Identify the node with minimal eccentricity among reachable nodes.
134+
135+
Args:
136+
eccentricities: List of tuples (node index, eccentricity).
137+
138+
Returns:
139+
The node with minimal eccentricity and its value. Returns (-1, inf) if
140+
no valid nodes are found.
141+
"""
142+
valid_eccentricities = [e for e in eccentricities if e[1] != float("inf")]
143+
return min(
144+
valid_eccentricities,
145+
key=lambda node_eccentricity: (node_eccentricity[1], node_eccentricity[0]),
146+
default=(-1, float("inf")),
147+
)
148+
149+
150+
def find_median_node(closenesses: list[tuple[int, float]]) -> tuple[int, float]:
151+
"""Identify the node with maximal closeness among reachable nodes.
152+
153+
Args:
154+
closenesses: List of tuples (node index, closeness centrality).
155+
156+
Returns:
157+
The node with maximal closeness and its value. Returns (-1, inf) if
158+
no valid nodes are found.
159+
"""
160+
valid_closenesses = [c for c in closenesses if c[1] != float("inf")]
161+
return max(
162+
valid_closenesses,
163+
key=lambda node_closeness: (node_closeness[1], -node_closeness[0]),
164+
default=(-1, float("inf")),
165+
)
166+
167+
168+
def find_central_and_median_node(
169+
distance_matrix: np.ndarray,
170+
) -> tuple[tuple[int, float], tuple[int, float]]:
171+
"""Determine the central and median nodes based on shortest-path distances.
172+
173+
For each node, calculates its eccentricity and harmonic closeness centrality,
174+
considering only reachable nodes. Then, identifies the central node (minimal
175+
eccentricity) and median node (maximal closeness).
176+
177+
Args:
178+
distance_matrix: A numpy.ndarray representing shortest-path distances
179+
between all pairs of nodes.
180+
181+
Returns:
182+
A tuple containing:
183+
- central_node: A tuple (node index, eccentricity) for the node with
184+
minimal eccentricity.
185+
- median_node: A tuple (node index, closeness) for the node with maximal
186+
harmonic closeness centrality.
187+
"""
188+
num_nodes: int = len(distance_matrix)
189+
190+
# Single-node graph case
191+
if num_nodes == 1:
192+
return (0, 0.0), (0, 0.0)
193+
194+
eccentricities: list[tuple[int, float]] = []
195+
closenesses: list[tuple[int, float]] = []
196+
197+
for i in range(num_nodes):
198+
reachable_distances = get_reachable_distances(distance_matrix[i])
199+
200+
if reachable_distances.size == 0:
201+
# No reachable nodes, isolated component
202+
eccentricity = float("inf")
203+
closeness = float("inf")
204+
else:
205+
# Compute eccentricity and closeness for reachable nodes
206+
eccentricity = float(np.max(reachable_distances))
207+
closeness = float(np.sum(1 / reachable_distances))
208+
209+
eccentricities.append((i, eccentricity))
210+
closenesses.append((i, closeness))
211+
212+
central_node = find_central_node(eccentricities)
213+
median_node = find_median_node(closenesses)
214+
215+
return central_node, median_node
216+
217+
218+
# Test cases included as doctests
219+
def test_single_node() -> None:
220+
"""
221+
Test a graph with a single node.
222+
223+
>>> graph = {0: []}
224+
>>> distance_matrix = floyd_warshall_algorithm(graph)
225+
>>> central_node, median_node = find_central_and_median_node(distance_matrix)
226+
>>> central_node
227+
(0, 0.0)
228+
>>> median_node
229+
(0, 0.0)
230+
"""
231+
232+
233+
def test_two_nodes_positive_weight() -> None:
234+
"""
235+
Test a graph with two nodes connected by a positive weight.
236+
237+
>>> graph = {0: [(1, 5.0)], 1: [(0, 5.0)]}
238+
>>> distance_matrix = floyd_warshall_algorithm(graph)
239+
>>> central_node, median_node = find_central_and_median_node(distance_matrix)
240+
>>> central_node
241+
(0, 5.0)
242+
>>> median_node
243+
(0, 0.2)
244+
"""
245+
246+
247+
def test_fully_connected_graph() -> None:
248+
"""
249+
Test a fully connected graph.
250+
251+
>>> graph = {
252+
... 0: [(1, 1.0), (2, 1.0)],
253+
... 1: [(0, 1.0), (2, 1.0)],
254+
... 2: [(0, 1.0), (1, 1.0)],
255+
... }
256+
>>> distance_matrix = floyd_warshall_algorithm(graph)
257+
>>> central_node, median_node = find_central_and_median_node(distance_matrix)
258+
>>> central_node
259+
(0, 1.0)
260+
>>> median_node
261+
(0, 2.0)
262+
"""
263+
264+
265+
def test_directed_acyclic_graph() -> None:
266+
"""
267+
Test a directed acyclic graph (DAG).
268+
269+
>>> graph = {
270+
... 0: [(1, 1.0), (2, 2.0)],
271+
... 1: [(3, 3.0)],
272+
... 2: [(3, 1.0)],
273+
... 3: []
274+
... }
275+
>>> distance_matrix = floyd_warshall_algorithm(graph)
276+
>>> central_node, median_node = find_central_and_median_node(distance_matrix)
277+
>>> central_node
278+
(2, 1.0)
279+
>>> median_node
280+
(0, 1.8333333333333333)
281+
"""
282+
283+
284+
def test_disconnected_graph() -> None:
285+
"""
286+
Test a disconnected graph with nodes that cannot reach each other.
287+
288+
>>> graph = {
289+
... 0: [],
290+
... 1: [],
291+
... 2: []
292+
... }
293+
>>> distance_matrix = floyd_warshall_algorithm(graph)
294+
>>> central_node, median_node = find_central_and_median_node(distance_matrix)
295+
>>> central_node
296+
(-1, inf)
297+
>>> median_node
298+
(-1, inf)
299+
"""
300+
301+
302+
def test_graph_with_zero_weight() -> None:
303+
"""
304+
Test a graph with zero weight, which should raise a ValueError.
305+
306+
>>> graph = {0: [(1, 0.0)], 1: []}
307+
>>> floyd_warshall_algorithm(graph)
308+
Traceback (most recent call last):
309+
...
310+
ValueError: Edge weight must be positive. Found 0.0 between nodes 0 and 1.
311+
"""
312+
313+
314+
def test_graph_with_negative_weight() -> None:
315+
"""
316+
Test a graph with negative weight, which should raise a ValueError.
317+
318+
>>> graph = {0: [(1, -2.0)], 1: []}
319+
>>> floyd_warshall_algorithm(graph)
320+
Traceback (most recent call last):
321+
...
322+
ValueError: Edge weight must be positive. Found -2.0 between nodes 0 and 1.
323+
"""
324+
325+
326+
def test_cyclic_graph() -> None:
327+
"""
328+
Test a cyclic graph where there is a cycle between nodes.
329+
330+
>>> graph = {
331+
... 0: [(1, 1.0)],
332+
... 1: [(2, 1.0)],
333+
... 2: [(0, 1.0)]
334+
... }
335+
>>> distance_matrix = floyd_warshall_algorithm(graph)
336+
>>> central_node, median_node = find_central_and_median_node(distance_matrix)
337+
>>> central_node
338+
(0, 2.0)
339+
>>> median_node
340+
(0, 1.5)
341+
"""
342+
343+
344+
def test_sparse_graph() -> None:
345+
"""
346+
Test a larger sparse graph.
347+
348+
>>> graph = {
349+
... 0: [(1, 2.0)],
350+
... 1: [(2, 3.0)],
351+
... 2: [(3, 4.0)],
352+
... 3: [(4, 5.0)],
353+
... 4: []
354+
... }
355+
>>> distance_matrix = floyd_warshall_algorithm(graph)
356+
>>> central_node, median_node = find_central_and_median_node(distance_matrix)
357+
>>> central_node
358+
(3, 5.0)
359+
>>> median_node
360+
(0, 0.8825396825396825)
361+
"""
362+
363+
364+
def test_large_fully_connected_graph() -> None:
365+
"""
366+
Test a larger fully connected graph with random weights.
367+
368+
>>> import random
369+
>>> random.seed(42)
370+
>>> number_of_nodes = 10
371+
>>> graph = {i: [(j, random.uniform(1, 10)) for j in
372+
... range(number_of_nodes) if i != j]
373+
... for i in range(number_of_nodes)}
374+
>>> distance_matrix = floyd_warshall_algorithm(graph)
375+
>>> central_node, median_node = find_central_and_median_node(distance_matrix)
376+
>>> central_node[0] is not None # Ensure it found a central node
377+
True
378+
>>> median_node[0] is not None # Ensure it found a median node
379+
True
380+
"""
381+
382+
383+
if __name__ == "__main__":
384+
import doctest
385+
386+
doctest.testmod()

0 commit comments

Comments
 (0)