/
r_python.Rmd
246 lines (196 loc) · 7.21 KB
/
r_python.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
73
74
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
140
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
---
title: "Représentation et inférence de réseaux avec R et Python"
author: "State of the R"
date: "24-28/08/2020"
output: html_document
---
## Utilisation de Python dans rmarkdown
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE)
```
Pour pouvoir utiliser `Python` dans `Rmarkdown` il faut utiliser le package `reticulate`.
On peut lui préciser le chemin de la version que l'on veut utiliser une certaine version plutôt que celle par défaut. Si une version de `Python` est déjà chargée, il faut relancer la session `R` pour que la modification soit appliqué.
```{r}
library(reticulate)
use_virtualenv("r-reticulate")
reticulate::py_config()
```
Il suffit alors de créer un chunk avec `python` comme langage. Tous les objets `R` de l'environnement sont accessible via la commande `r.`.
```{python}
x = 2
print(x)
r.x = x
```
Dans un chunk `R`, les objets `python` sont accessible avec la commande `py$`.
```{r}
x <- py$x
y <- x**2
print(y)
typeof(y)
```
Il faut faire attention à la transformation automatique des types de `R` vers `python`, ce dernier étant plus pointilleux que `R` la dessus.
```{python}
z = [i**2 for i in range(int(r.y))]
print(z)
```
## Utilisation de la librarie graph_tool
`graph_tool` est une librairie `python` pour analyser des réseaux développer par T. Peixoto.
Elle permet entre autre de faire des visualisations interactive de graphes et est également très réputée pour ces implémentations du SBM et du degree corrected SBM.
```{r}
library(sbm)
library(igraph)
library(tidyverse)
```
```{python}
import graph_tool.all as gt
import matplotlib.pyplot as plt
import numpy as np
import math
import time
```
```{python}
g = gt.collection.data["football"]
print(g)
```
```{python}
state = gt.minimize_blockmodel_dl(g)
m = state.get_matrix()
```
Les plots `matplotlib` sortent très bien dans le notebook, mais ce n'est pas le cas des plots interactifs. Ceux-ci ouvrent une fenêtre `python` interactive et bloquent la compilation du document.
```{python, eval = FALSE}
plt.matshow(m.todense())
```
Si l'on décide de sortir un plot *inline*, la fenêtre virtuelle ne s'ouvre pas et l'on récupère juste l'adresse mémoire du graph stocker. Il faut sauver dans un fichier et insérer "à la main"
```{python graph_fig}
pv = None
for i in range(1000):
ret = state.mcmc_sweep(niter=10)
pv = state.collect_vertex_marginals(pv)
gt.mf_entropy(g, pv)
p = gt.graph_draw(g, pos=g.vp["pos"], vertex_shape="pie",
vertex_pie_fractions=pv, inline= True, output = "img/hier.png")
```
![plot hierarchique](img/hier.png)
On obtient des représentations graphiques sur des graph assez gros (1500 noeuds) rapidement.
```{python}
g = gt.price_network(1500)
deg = g.degree_property_map("in")
deg.a = 4 * (np.sqrt(deg.a) * 0.5 + 0.4)
```
```{python}
ebet = gt.betweenness(g)[1]
ebet.a /= ebet.a.max() / 10.
eorder = ebet.copy()
eorder.a *= -1
pos = gt.sfdp_layout(g)
control = g.new_edge_property("vector<double>")
for e in g.edges():
d = np.sqrt(sum((pos[e.source()].a - pos[e.target()].a) ** 2)) / 5
control[e] = [0.3, d, 0.7, d]
gt.graph_draw(g, pos=pos, vertex_size=deg, vertex_fill_color=deg, vorder=deg,
edge_color=ebet, eorder=eorder, edge_pen_width=ebet,
edge_control_points=control, # some curvy edges
output="img/graph-draw.png")
```
![graph1500](img/graph-draw.png)
Et l'on peut également sortir des plots interactifs avec graphviz.
```{python, eval = FALSE}
g = gt.price_network(1500)
deg = g.degree_property_map("in")
deg.a = 2 * (np.sqrt(deg.a) * 0.5 + 0.4)
ebet = gt.betweenness(g)[1]
#gt.graphviz_draw(g, vcolor=deg, vorder=deg, elen=10,
# ecolor=ebet, eorder=ebet, )#, output="graphviz-draw.pdf")
```
```{python, eval = FALSE}
g = gt.price_network(3000)
pos = gt.sfdp_layout(g)
gt.graph_draw(g, pos=pos)#, output="graph-draw-sfdp.pdf")
```
```{python, eval =FALSE}
g = gt.collection.data["netscience"]
g = gt.GraphView(g, vfilt=gt.label_largest_component(g))
g.purge_vertices()
state = gt.minimize_nested_blockmodel_dl(g, deg_corr=True)
t = gt.get_hierarchy_tree(state)[0]
tpos = pos = gt.radial_tree_layout(t, t.vertex(t.num_vertices() - 1), weighted=True)
cts = gt.get_hierarchy_control_points(g, t, tpos)
pos = g.own_property(tpos)
b = state.levels[0].b
shape = b.copy()
shape.a %= 14
gt.graph_draw(g, pos=pos, vertex_fill_color=b, vertex_shape=shape,
edge_control_points=cts,
edge_color=[0, 0, 0, 0.3], vertex_anchor=0)#, output="netscience_nested_mdl.pdf")
```
Un essaie de plot hiérarchique:
```{python celegans_hier}
g = gt.collection.data["celegansneural"]
state = gt.minimize_nested_blockmodel_dl(g, deg_corr=True)
gt.draw_hierarchy(state, output="img/celegansneural_hier.png")
```
![plot hierarchique](img/celegansneural_hier.png)
Si l'on fit un sbm sur un graph, l'autoplot sur l'état des blocks du graphe se fait automatiquement.
```{python}
t0 = time.time()
g = gt.collection.data["polbooks"]
state = gt.minimize_blockmodel_dl(g , deg_corr=False)
for i in range(10):
s = gt.minimize_blockmodel_dl(g , deg_corr=False)
if s.entropy() < state.entropy():
state = s
t = t0 - time.time()
print(t)
state.entropy()
```
```{python}
state.draw(pos=g.vp["pos"], vertex_shape=state.get_blocks(), output="img/polbooks_blocks_mdl.svg")
```
![Image graph tools](img/polbooks_blocks_mdl.svg)
## Passe de `python` à `R`
On peut passer le réseau via la matrice d'adjacence de `python` à `R`, mais on aimerait mieux sortir un objet `graphml` qui est bien lu par `igraph`.
Malheureusement, cela ne fonctionne pas. Toutes les méthodes de `graph_tool` sur les noeuds et les arêtes renvoient des itérateurs. Il est nécessaire de les transformer en vecteur avec de les utiliser en `R`.
```{python}
blocks = [b for b in state.get_blocks()]
A = gt.adjacency(g)
## g.save(file_name= "/home/stc/Documents/StateOfTheR/FinistR2020/graph_gt.graphml", fmt="graphml")
```
<!-- ```{r, eval = FALSE} -->
<!-- g <- igraph::read.graph("/home/stc/Documents/StateOfTheR/FinistR2020/graph_gt.graphml", format = "graphml") -->
<!-- ``` -->
```{r}
py$blocks + 1
```
```{r}
A <- as.matrix(py$A)
isSymmetric(A)
```
```{r}
my_sbm <- blockmodels::BM_bernoulli("SBM_sym", A, verbosity = 0, plotting = "")
```
```{r}
t0 <- Sys.time()
my_sbm$estimate()
t <- t0 - Sys.time()
t
```
```{r}
aricode::ARI(c1 = py$blocks +1, c2 = my_sbm$memberships[[5]]$map()$C)
my_sbm$memberships[[5]]$map()$C
py$blocks +1
```
Les clustering obtenus par `graph-tool` et sbm (`blockmodels`) sont très proche pour le sbm simple.
```{r, eval = FALSE}
igraph::graph_from_adjacency_matrix(
A, mode = "directed") %>% igraph::write_graph(file = "graph_test.graphml", format = "graphml")
```
```{python, eval = FALSE}
gr = gt.load_graph(file_name="~/Documents/StateOfTheR/FinistR2020/graph_test.graphml", fmt="graphml")
```
```{python, eval = FALSE}
gr.set_directed = False
gt.minimize_blockmodel_dl(gr, deg_corr=False)
```
## Reste à faire
* Trouver une meilleur méthode pour passer un objet de type graph de `python` vers `R`. Une solution serait peut-être d'utiliser le module `igraph` de `python`.
* Est-il possible de capturer une fenêtre interactive `python` pour la mettre dans la sortie html du `rmarkdown` ?