Skip to content

Commit 91cae24

Browse files
authored
Merge pull request #1 from MKaczkow/add-bellman-ford-example
Bellman-Ford example notebook
2 parents 2751138 + c5f4f4e commit 91cae24

1 file changed

Lines changed: 137 additions & 0 deletions

File tree

bellman_ford/DEMO.ipynb

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "code",
5+
"execution_count": null,
6+
"id": "7f235e2e",
7+
"metadata": {},
8+
"outputs": [],
9+
"source": [
10+
"import networkx as nx\n",
11+
"from scipy.sparse.csgraph import bellman_ford"
12+
]
13+
},
14+
{
15+
"cell_type": "code",
16+
"execution_count": 4,
17+
"id": "7d256792",
18+
"metadata": {},
19+
"outputs": [
20+
{
21+
"name": "stdout",
22+
"output_type": "stream",
23+
"text": [
24+
"Shortest distances from vertex A (0): [0, 2, 1, 3, 4]\n"
25+
]
26+
}
27+
],
28+
"source": [
29+
"# edge (u, v, w) means an edge from u to v with weight w\n",
30+
"edges = [\n",
31+
" (0, 1, 3),\n",
32+
" (0, 2, 1),\n",
33+
" (1, 2, 7),\n",
34+
" (1, 3, 5),\n",
35+
" (2, 3, 2),\n",
36+
" (3, 2, -1),\n",
37+
" (3, 4, 1),\n",
38+
" (4, 1, -2),\n",
39+
"]\n",
40+
"\n",
41+
"# assuming A-E are indexed as 0-4\n",
42+
"distances = [float('inf')] * 5\n",
43+
"distances[0] = 0\n",
44+
"\n",
45+
"for _ in range(4): # v-1 iterations\n",
46+
" for u, v, w in edges: # 'w' is the 'new' weight\n",
47+
" if distances[u] < float('inf'):\n",
48+
" distances[v] = min(distances[v], distances[u] + w)\n",
49+
"\n",
50+
"print(\"Shortest distances from vertex A (0):\", distances)\n"
51+
]
52+
},
53+
{
54+
"cell_type": "code",
55+
"execution_count": null,
56+
"id": "9afe182f",
57+
"metadata": {},
58+
"outputs": [
59+
{
60+
"name": "stdout",
61+
"output_type": "stream",
62+
"text": [
63+
"nodes: ['A', 'B', 'C', 'D', 'E']\n",
64+
"distances from source (A): [0. 2. 1. 3. 4.]\n",
65+
"predecessors: [-9999 4 0 2 3]\n",
66+
" A: distance=0.0, predecessor=None\n",
67+
" B: distance=2.0, predecessor=E\n",
68+
" C: distance=1.0, predecessor=A\n",
69+
" D: distance=3.0, predecessor=C\n",
70+
" E: distance=4.0, predecessor=D\n"
71+
]
72+
}
73+
],
74+
"source": [
75+
"# build a small directed graph with weights (same as in example)\n",
76+
"G = nx.DiGraph()\n",
77+
"G.add_weighted_edges_from([\n",
78+
" ('A', 'B', 3),\n",
79+
" ('A', 'C', 1),\n",
80+
" ('B', 'C', 7),\n",
81+
" ('B', 'D', 5),\n",
82+
" ('C', 'D', 2),\n",
83+
" ('D', 'C', -1),\n",
84+
" ('D', 'E', 1),\n",
85+
" ('E', 'B', -2),\n",
86+
"])\n",
87+
"\n",
88+
"# convert to an adjacency/weight matrix\n",
89+
"W = nx.to_numpy_array(G, weight='weight')\n",
90+
"\n",
91+
"# run scipy's bellman_ford on the weight matrix from source index 0\n",
92+
"distances, predecessors = bellman_ford(W, indices=0, return_predecessors=True)\n",
93+
"\n",
94+
"nodes = list(G.nodes())\n",
95+
"print(\"nodes:\", nodes)\n",
96+
"print(\"distances from source (A):\", distances)\n",
97+
"print(\"predecessors:\", predecessors)\n",
98+
"\n",
99+
"# interpret results in terms of node names\n",
100+
"for i, d in enumerate(distances):\n",
101+
" pred = predecessors[i]\n",
102+
" pred_name = nodes[pred] if pred != -9999 else None\n",
103+
" print(f\" {nodes[i]}: distance={d}, predecessor={pred_name}\")"
104+
]
105+
},
106+
{
107+
"cell_type": "markdown",
108+
"id": "358750df",
109+
"metadata": {},
110+
"source": [
111+
"### References\n",
112+
"* [algorithms for cp](https://cp-algorithms.com/graph/bellman_ford.html)"
113+
]
114+
}
115+
],
116+
"metadata": {
117+
"kernelspec": {
118+
"display_name": "venv (3.11.0)",
119+
"language": "python",
120+
"name": "python3"
121+
},
122+
"language_info": {
123+
"codemirror_mode": {
124+
"name": "ipython",
125+
"version": 3
126+
},
127+
"file_extension": ".py",
128+
"mimetype": "text/x-python",
129+
"name": "python",
130+
"nbconvert_exporter": "python",
131+
"pygments_lexer": "ipython3",
132+
"version": "3.11.0"
133+
}
134+
},
135+
"nbformat": 4,
136+
"nbformat_minor": 5
137+
}

0 commit comments

Comments
 (0)