Skip to content

Commit

Permalink
Added recipe for average path lenght, related to #511
Browse files Browse the repository at this point in the history
  • Loading branch information
thomasrobiglio committed Feb 29, 2024
1 parent 3edd444 commit bdef46d
Showing 1 changed file with 47 additions and 2 deletions.
49 changes: 47 additions & 2 deletions docs/source/api/recipes/recipes.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -542,8 +542,8 @@
"data": {
"text/plain": [
"(<Axes3D: >,\n",
" (<mpl_toolkits.mplot3d.art3d.Path3DCollection at 0x7faad10a17f0>,\n",
" <mpl_toolkits.mplot3d.art3d.Poly3DCollection at 0x7faaf0fbf7f0>))"
" (<mpl_toolkits.mplot3d.art3d.Path3DCollection at 0x7f8ee06cf0a0>,\n",
" <mpl_toolkits.mplot3d.art3d.Poly3DCollection at 0x7f8f10c1fb50>))"
]
},
"execution_count": 20,
Expand Down Expand Up @@ -744,6 +744,51 @@
"pos = {inv_mapping[k]: v for k, v in pos.items()}\n",
"xgi.draw(S, pos=pos);"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## 14. Compute the average path length in a hypergraph\n",
"This recipe shows how to compute the average path lenght in a hypergraph.\n",
"You can compute all shortest path lenghts with [`xgi.shortest_path_length()`](https://xgi.readthedocs.io/en/stable/api/algorithms/xgi.algorithms.shortest_path.html#xgi.algorithms.shortest_path.shortest_path_length). \n",
"This gives and infinite length for disconnected nodes, to allow the computation in any case we replace `np.inf` by 0 for disconnected nodes and remove lengths 0 for self-loops."
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The average shortest path length is 4.48\n"
]
}
],
"source": [
"import xgi\n",
"import numpy as np\n",
"\n",
"H = xgi.random_hypergraph(N=100, ps=[0.2, 0.02], seed=1)\n",
"spl = xgi.shortest_path_length(H)\n",
"\n",
"lens = []\n",
"for tup in spl:\n",
" lens += tup[1].values()\n",
"\n",
"# remove lengths 0 for self-loops\n",
"lens = [i for i in lens if i!=0] \n",
"\n",
"# replace inf by 0 for disconnected nodes\n",
"lens = [0 if i==np.inf else i for i in lens] \n",
"\n",
"avg_shortest_path = np.sum(lens) / (N * (N-1))\n",
"print(\"The average shortest path length is\", avg_shortest_path)"
]
}
],
"metadata": {
Expand Down

0 comments on commit bdef46d

Please sign in to comment.