data_knowledge-networks_metrics-combined_clean.ipynb 12.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Calculating different network metrics\n",
    "\n",
    "\n",
    "Networkx:\n",
    "- [x] N, E: Number of nodes/edges in the network N\n",
    "- [x] r: Density \n",
    "- [x] k: avg degree\n",
    "- [x] C: Clustering coefficient\n",
MGerlach's avatar
MGerlach committed
15
16
    "- [x] geff: global efficiency\n",
    "- [x] L: Characteristic path length (largest connected component)\n",
17
18
19
20
21
22
23
24
25
26
27
28
    "- [ ] Phi: small-world propensity\n",
    "   - networkx contains code for a quantity called [sigma](https://networkx.org/documentation/networkx-2.2/reference/algorithms/generated/networkx.algorithms.smallworld.sigma.html)\n",
    "   - this is different than the small-world propensity described, e.g., in \n",
    "\n",
    "BCT\n",
    "- [x] cps: core-periphery structure\n",
    "\n",
    "Graph-tool\n",
    "- [x] mdl: Minimum Description Length\n",
    "- [x] modq: Modularity score of the partition on the lowest level in the hierarchy\n",
    "\n",
    "Risper:\n",
MGerlach's avatar
MGerlach committed
29
    "- [x] persistent homology :Number of 0,1,2-cycles\n",
30
    "- [?] compression: use description length?\n",
MGerlach's avatar
MGerlach committed
31
    "- [x] mechanical features: d, DoF_C\n",
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
    "\n",
    "\n",
    "General:\n",
    "- [ ] All observables for randomized versions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Load packages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os, sys\n",
    "import json\n",
    "import pickle\n",
    "from sqlitedict import SqliteDict\n",
    "import json\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "import networkx as nx\n",
    "import graph_tool.all as gt\n",
    "import bct\n",
    "from ripser import ripser\n",
    "\n",
    "\n",
    "import utils_network\n",
    "import utils_networkx\n",
    "import utils_gt\n",
73
74
    "# import utils_ripser\n",
    "import utils_filtration_metrics\n",
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
    "\n",
    "%load_ext autoreload\n",
    "%autoreload 2\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Load datasets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "snapshot = \"2022-03\"\n",
    "wiki_db = \"enwiki\"\n",
    "# mode = \"pickle\" # for bulk acccess\n",
    "mode = \"sqlite\" # for individual access"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## Load a links table of the form {page_id: pageids of outlinks }\n",
    "FNAME_read = \"/home/mgerlach/REPOS/curios-critical-readers/data/pages-links_%s_%s.{0}\"%(wiki_db,snapshot)\n",
    "if mode == \"pickle\":\n",
    "    with open(FNAME_read.format(\"pkl\"),\"rb\") as fin:\n",
    "        dict_links = pickle.load(fin)  \n",
    "elif mode == \"sqlite\":\n",
    "    dict_links = SqliteDict(FNAME_read.format(\"sqlite\"))\n",
    "else:\n",
    "    dict_links = {}\n",
    "print(len(dict_links))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# reading sessions subsample\n",
    "FNAME_read = \"/home/mgerlach/REPOS/curios-critical-readers/data/sessions-app_%s_%s_small.json\"%(wiki_db,snapshot)\n",
    "list_sessions = []\n",
    "with open(FNAME_read) as fin:\n",
    "    for line in fin:\n",
    "        json_in = json.loads(line)\n",
    "        session = json_in.get(\"session\",[])\n",
    "        list_sessions+=[session]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# select a single reading session\n",
MGerlach's avatar
MGerlach committed
140
    "session = list_sessions[22]\n",
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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
    "print(\"Length of session: \",len(session))\n",
    "for page in session:\n",
    "    print(page)\n",
    "    if page[\"pos\"] == 5:\n",
    "        break"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Preparing the networks"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# we want an undirected network\n",
    "directed = False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# list of nodes/edges from hyperlinks between articles\n",
    "list_nodes, list_edges = utils_network.session2edgelist_links(session,dict_links, directed = directed)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# graph-object networkx\n",
    "g_nx = utils_networkx.make_graph_links(list_nodes, list_edges, directed=directed)\n",
    "print(g_nx)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# graph-object graph-tool\n",
    "g_gt = utils_gt.make_graph_links(list_nodes, list_edges, directed = directed)\n",
    "print(g_gt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Adjacency matrix\n",
    "A = nx.convert_matrix.to_numpy_array(g_nx)\n",
    "print(A)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# rewired edgelist (degree-preserving) in case we want to compare with a null model\n",
    "list_edges_rewired = utils_network.rewire_edges(list_edges, directed = directed)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Networkx"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# nodes and edges\n",
    "N = nx.number_of_nodes(g_nx)\n",
    "E = nx.number_of_edges(g_nx)\n",
    "print(\"Nodes: \", N)\n",
    "print(\"Edges: \", E)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# average degree\n",
    "k = np.mean([v for k,v in nx.degree(g_nx)])\n",
    "print(\"Average degree: \", k)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# density\n",
    "r = nx.density(g_nx)\n",
    "print(\"Density: \", r)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# clustering\n",
    "C = nx.average_clustering(g_nx)\n",
    "print(\"Clustering coefficient: \", C)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# global efficiency\n",
    "geff = nx.global_efficiency(g_nx)\n",
    "print(\"Global efficiency: \", geff)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Characteristic path length\n",
    "g_nx_conmax = g_nx.subgraph(max(nx.connected_components(g_nx), key=len))\n",
    "cpl = nx.average_shortest_path_length(g_nx_conmax)\n",
    "print(\"Characteristic Path Length (largest connected component): \", cpl)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# small-world property\n",
    "# sigma = nx.sigma(g_nx_conmax)\n",
    "# print(\"Small-world property: \", sigma)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# small-world propensity\n",
    "\n",
    "# TODO\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# BCT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# core-periphery structure\n",
    "cps_result = bct.core_periphery_dir(A)\n",
    "cps = cps_result[1]\n",
    "print(\"Core-periphery structure: \", cps)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Graph-tool"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# fit a hierarchical blockmodel\n",
    "state = gt.minimize_nested_blockmodel_dl(g_gt)\n",
    "# do a few swaps to find minimum\n",
    "for i in range(100):\n",
MGerlach's avatar
MGerlach committed
359
360
    "    ret = state.multiflip_mcmc_sweep(niter=10, beta=np.inf)\n",
    "state.draw()"
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
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# description length\n",
    "mdl = state.entropy()\n",
    "print(\"Minimum Description Length :\", mdl)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# modularity of partition on the lowest level\n",
    "l = 0\n",
    "blocks = state.project_level(l).get_blocks()\n",
    "modq = gt.modularity(g_gt,blocks)\n",
    "print(\"Modularity score (partition on the lowest level): \", modq)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
398
399
400
401
402
403
404
405
    "# Filtration metrics"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Persistent homology"
406
407
408
409
410
411
412
413
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
414
415
416
417
    "G = nx.adjacency_matrix(g_nx).todense()\n",
    "G = np.array(G)\n",
    "G = G + np.transpose(G) # make symmetric\n",
    "G[G > 0] = 1 # binarize\n",
418
    "# make a filtration matrix from adjacency matrix\n",
419
    "weighted_G = utils_filtration_metrics.make_filtration_matrix(G)"
420
421
422
423
424
425
426
427
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
428
429
430
    "# Compute persistent homology\n",
    "bars_orig = utils_filtration_metrics.get_barcode(weighted_G)\n",
    "bettis_orig = utils_filtration_metrics.betti_curves(bars_orig, weighted_G.shape[0])"
431
432
433
   ]
  },
  {
434
435
   "cell_type": "code",
   "execution_count": null,
436
   "metadata": {},
437
   "outputs": [],
438
   "source": [
439
    "utils_filtration_metrics.plot_barcode(bars_orig, weighted_G.shape[0])"
440
441
442
443
444
445
446
447
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
448
449
450
    "plt.plot(np.arange(G.shape[0]), bettis_orig[0])\n",
    "plt.xlabel('Nodes')\n",
    "plt.ylabel('Number of 0-Cycles')"
451
452
453
454
455
456
457
458
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
459
460
461
    "plt.plot(np.arange(G.shape[0]), bettis_orig[1])\n",
    "plt.xlabel('Nodes')\n",
    "plt.ylabel('Number of 1-Cycles')"
462
463
464
465
466
467
468
469
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
470
    "plt.plot(np.arange(G.shape[0]), bettis_orig[2])\n",
471
    "plt.xlabel('Nodes')\n",
472
473
474
475
476
477
478
479
    "plt.ylabel('Number of 2-Cycles')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Mechanical features"
480
481
482
483
484
485
486
487
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
488
489
490
491
492
493
494
495
496
497
    "[d, conform] = utils_filtration_metrics.compute_mechanical_features(G)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot(np.arange(G.shape[0]), d)\n",
498
    "plt.xlabel('Nodes')\n",
499
    "plt.ylabel('d')"
500
501
502
503
504
505
506
507
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
508
    "plt.plot(np.arange(G.shape[0]), conform)\n",
509
    "plt.xlabel('Nodes')\n",
MGerlach's avatar
MGerlach committed
510
    "plt.ylabel('DoF_C')\n"
511
   ]
MGerlach's avatar
MGerlach committed
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
533
534
535
536
  }
 ],
 "metadata": {
  "kernelspec": {
537
   "display_name": "conda_curiosity",
538
   "language": "python",
539
   "name": "conda_curiosity"
540
541
542
543
544
545
546
547
548
549
550
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
551
   "version": "3.7.12"
552
553
554
555
556
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}