Merge branch 'master' of http://www.netdig.org/git/iramuteq
[iramuteq] / Rscripts / simi.R
1 #from proxy package
2 #############################################################
3 #a, b, c, and d are the counts of all (TRUE, TRUE), (TRUE, FALSE), (FALSE, TRUE), and (FALSE, FALSE) 
4 # n <- a + b + c + d = nrow(x)
5
6 make.a <- function(x) {
7     a  <- t(x) %*% (x)
8     a
9 }
10
11 make.b <- function(x) {
12     b <- t(x) %*% (1 - x)
13     b
14 }
15
16 make.c <- function(x) {
17     c <- (1-t(x)) %*% x
18     c
19 }
20
21 make.d <- function(x, a, b, c) {
22 #??????????? ncol ?
23     d <- ncol(x) - a - b - c
24     d
25 }
26
27 ###########################################
28 #x, a
29 ###########################################
30 my.jaccard <- function(x) {
31     a <- make.a(x)
32     b <- make.b(x)
33     c <- make.c(x)
34     d <- make.d(x, a, b, c)
35     jac <- a / (a + b + c)
36     jac
37 }
38
39
40 prcooc <- function(x, a) {
41     prc <- (a / nrow(x)) 
42     prc
43 }
44
45 make.bin <- function(cs, a, i, j, nb) {
46     if (a[i, j] >= 1) {
47         ab <- a[i, j] - 1 
48         res <- binom.test(ab, nb, (cs[i]/nb) * (cs[j]/nb), "less")
49     } else {
50         res <- NULL
51         res$p.value <- 0
52     }
53     #res <- binom.test(ab, nb, (cs[i]/nb) * (cs[j]/nb), "less")
54     res$p.value
55     }
56
57 binom.sim <- function(x) {
58     a <- make.a(x)
59     n <- nrow(x)
60     cs <- colSums(x)
61     mat <- matrix(0,ncol(x),ncol(x))
62     colnames(mat)<-colnames(a)
63     rownames(mat)<-rownames(a)
64     for (i in 1:(ncol(x)-1)) {
65         for (j in (i+1):ncol(x)) {
66             mat[j,i] <- make.bin(cs, a, i, j , n)
67         }
68     }
69 #    print(mat)
70     mat
71 }
72
73
74 ############################################
75 # a, b, c
76 ############################################
77 # jaccard a, b, c   a / (a + b + c)
78 # Kulczynski1 a, b, c   a / (b + c)
79 # Kulczynski2 a, b, c   [a / (a + b) + a / (a + c)] / 2
80 # Mountford a, b, c    2a / (ab + ac + 2bc)
81 # Fager, McGowan a, b, c   a / sqrt((a + b)(a + c)) - 1 / 2 sqrt(a + c)
82 # Russel, Rao a (a/n)
83 # Dice, Czekanowski, Sorensen a, b, c   2a / (2a + b + c)
84 # Mozley, Margalef a, b, c  an / (a + b)(a + c)
85 # Ochiai a, b, c  a / sqrt[(a + b)(a + c)]
86 # Simpson a, b, c   a / min{(a + b), (a + c)}
87 # Braun-Blanquet a, b, c  a / max{(a + b), (a + c)}
88
89 #simple matching, Sokal/Michener a, b, c, d, ((a + d) /n)
90 # Hamman, a, b, c, d, ([a + d] - [b + c]) / n
91 # Faith , a, b, c, d, (a + d/2) / n
92 # Tanimoto, Rogers a, b, c, d, (a + d) / (a + 2b + 2c + d)
93 # Phi  a, b, c, d   (ad - bc) / sqrt[(a + b)(c + d)(a + c)(b + d)]
94 # Stiles a, b, c, d  log(n(|ad-bc| - 0.5n)^2 / [(a + b)(c + d)(a + c)(b + d)])
95 # Michael   a, b, c, d   4(ad - bc) / [(a + d)^2 + (b + c)^2]
96 # Yule a, b, c, d  (ad - bc) / (ad + bc)
97 # Yule2  a, b, c, d  (sqrt(ad) - sqrt(bc)) / (sqrt(ad) + sqrt(bc))
98
99 BuildProf01<-function(x,classes) {
100         #x : donnees en 0/1
101         #classes : classes de chaque lignes de x
102         dm<-cbind(x,cl=classes)
103         clnb=length(summary(as.data.frame(as.character(classes)),max=100))
104         print(clnb)
105         print(summary(as.data.frame(as.character(classes)),max=100))
106         mat<-matrix(0,ncol(x),clnb)
107         rownames(mat)<-colnames(x)
108         for (i in 1:clnb) {
109                 dtmp<-dm[which(dm$cl==i),]
110                 for (j in 1:(ncol(dtmp)-1)) {
111                         mat[j,i]<-sum(dtmp[,j])
112                 }
113         }
114         mat
115 }
116
117 do.simi <- function(x, method = 'cooc',seuil = NULL, p.type = 'tkplot',layout.type = 'frutch', max.tree = TRUE, coeff.vertex=NULL, coeff.edge = NULL, minmaxeff=c(NULL,NULL), vcexminmax= c(NULL,NULL), cex = 1, coords = NULL, communities = NULL, halo = FALSE) {
118         mat.simi <- x$mat
119     mat.eff <- x$eff
120     v.label <- colnames(mat.simi)
121         g1<-graph.adjacency(mat.simi,mode="lower",weighted=TRUE)
122         g.toplot<-g1
123         weori<-get.edge.attribute(g1,'weight')
124         if (max.tree) {
125         if (method == 'cooc') {
126                     invw <- 1 / weori
127         } else {
128             invw <- 1 - weori
129         }
130                 E(g1)$weight<-invw
131                 g.max<-minimum.spanning.tree(g1)
132         if (method == 'cooc') {
133                     E(g.max)$weight<-1 / E(g.max)$weight
134         } else {
135             E(g.max)$weight<-1 - E(g.max)$weight
136         }
137                 g.toplot<-g.max
138         }
139
140     if (!is.null(seuil)) {
141         print(seuil)
142         if (seuil >= max(mat.simi)) seuil <- 0
143         vec<-vector()
144         w<-E(g.toplot)$weight
145         tovire <- which(w<=seuil)
146         g.toplot <- delete.edges(g.toplot,(tovire))
147         for (i in 0:(length(V(g.toplot)))) {
148             if (length(neighbors(g.toplot,i))==0) {
149                 vec<-append(vec,i)
150             }
151         }
152         g.toplot <- delete.vertices(g.toplot,vec)
153         v.label <- V(g.toplot)$name
154         if (!is.logical(vec)) mat.eff <- mat.eff[-(vec)]
155     }
156
157         if (!is.null(minmaxeff[1])) {
158         eff<-norm.vec(mat.eff,minmaxeff[1],minmaxeff[2])
159     } else {
160         eff<-coeff.vertex
161     }
162     if (!is.null(vcexminmax[1])) {
163         label.cex = norm.vec(mat.eff, vcexminmax[1], vcexminmax[2])
164     } else {
165         label.cex = cex
166     }
167     if (!is.null(coeff.edge)) {
168         we.width <- norm.vec(abs(E(g.toplot)$weight), coeff.edge[1], coeff.edge[2]) 
169             #we.width <- abs((E(g.toplot)$weight/max(abs(E(g.toplot)$weight)))*coeff.edge)
170     } else {
171         we.width <- NULL
172     }
173     if (method != 'binom') {
174         we.label <- round(E(g.toplot)$weight,1)
175     } else {
176         we.label <- round(E(g.toplot)$weight,3)
177     }
178         if (p.type=='rgl') {
179         nd<-3
180     } else {
181         nd<-2
182     }
183     if (is.null(coords)) {
184         if (layout.type == 'frutch')
185                 lo <- layout.fruchterman.reingold(g.toplot,dim=nd)#, weightsA=E(g.toplot)$weight)
186         if (layout.type == 'kawa')
187                 lo <- layout.kamada.kawai(g.toplot,dim=nd)
188         if (layout.type == 'random')
189                 lo <- layout.random(g.toplot,dim=nd)
190         if (layout.type == 'circle' & p.type != 'rgl')
191                 lo <- layout.circle(g.toplot)
192         if (layout.type == 'circle' & p.type == 'rgl')
193                 lo <- layout.sphere(g.toplot)
194         if (layout.type == 'graphopt')
195             lo <- layout.graphopt(g.toplot)
196     } else {
197         lo <- coords
198     }
199     if (!is.null(communities)) {
200         if (communities == 0 ){ #'edge.betweenness.community') {
201             com <- edge.betweenness.community(g.toplot)
202         } else if (communities == 1) {
203             com <- fastgreedy.community(g.toplot)
204         } else if (communities == 2) {
205             com <- label.propagation.community(g.toplot)
206         } else if (communities == 3) {
207             com <- leading.eigenvector.community(g.toplot)
208         } else if (communities == 4) {
209             com <- multilevel.community(g.toplot)
210         } else if (communities == 5) {
211             com <- optimal.community(g.toplot)
212         } else if (communities == 6) {
213             com <- spinglass.community(g.toplot)
214         } else if (communities == 7) {
215             com <- walktrap.community(g.toplot)
216         } 
217     } else {
218         com <- NULL
219     }
220     
221         out <- list(graph = g.toplot, mat.eff = mat.eff, eff = eff, mat = mat.simi, v.label = v.label, we.width = we.width, we.label=we.label, label.cex = label.cex, layout = lo, communities = com, halo = halo)
222 }
223         
224 plot.simi <- function(graph.simi, p.type = 'tkplot',filename=NULL, communities = NULL, vertex.col = 'red', edge.col = 'black', edge.label = TRUE, vertex.label=TRUE, vertex.label.color = 'black', vertex.label.cex= NULL, vertex.size=NULL, leg=NULL, width = 800, height = 800, alpha = 0.1, cexalpha = FALSE, movie = NULL, svg = FALSE) {
225         mat.simi <- graph.simi$mat
226         g.toplot <- graph.simi$graph
227     if (is.null(vertex.size)) {
228         vertex.size <- graph.simi$eff
229     } else {
230         vertex.size <- vertex.size
231     }
232         we.width <- graph.simi$we.width
233     if (vertex.label) {
234         #v.label <- vire.nonascii(graph.simi$v.label)
235         v.label <- graph.simi$v.label
236     } else {
237         v.label <- NA
238     }
239     if (edge.label) {
240         we.label <- graph.simi$we.label
241     } else {
242         we.label <- NA
243     }
244         lo <- graph.simi$layout
245     if (!is.null(vertex.label.cex)) {
246         label.cex<-vertex.label.cex
247     } else {
248         label.cex = graph.simi$label.cex
249     }
250     if (cexalpha) {
251         alphas <- norm.vec(label.cex, 0.5,1)
252         nvlc <- NULL
253         if (length(vertex.label.color) == 1) {
254             for (i in 1:length(alphas)) {
255              nvlc <- append(nvlc, adjustcolor(vertex.label.color, alpha=alphas[i]))
256             }
257         } else {
258             for (i in 1:length(alphas)) {
259                 nvlc <- append(nvlc, adjustcolor(vertex.label.color[i], alpha=alphas[i]))
260             }
261         }
262         vertex.label.color <- nvlc  
263     }
264     if (p.type=='nplot') {
265         #print('ATTENTION - PAS OPEN FILE')
266         open_file_graph(filename, width = width, height = height, svg = svg)
267         par(mar=c(2,2,2,2))
268         if (!is.null(leg)) {
269             layout(matrix(c(1,2),1,2, byrow=TRUE),widths=c(3,lcm(7)))
270             par(mar=c(2,2,1,0))
271         }
272         par(pch=' ')
273         if (is.null(graph.simi$com)) {
274             plot(g.toplot,vertex.label='', edge.width=we.width, vertex.size=vertex.size, vertex.color=vertex.col, vertex.label.color='white', edge.label=we.label, edge.label.cex=cex, edge.color=edge.col, vertex.label.cex = 0, layout=lo)#, rescale = FALSE)
275         } else {
276             if (graph.simi$halo) {
277                 mark.groups <- communities(graph.simi$com)
278             } else {
279                 mark.groups <- NULL
280             }
281             plot(com, g.toplot,vertex.label='', edge.width=we.width, vertex.size=vertex.size, vertex.color=vertex.col, vertex.label.color='white', edge.label=we.label, edge.label.cex=cex, edge.color=edge.col, vertex.label.cex = 0, layout=lo, mark.groups = mark.groups)
282         }
283         #txt.layout <- lo
284         txt.layout <- layout.norm(lo, -1, 1, -1, 1, -1, 1)
285         #txt.layout <- txt.layout[order(label.cex),]
286         #vertex.label.color <- vertex.label.color[order(label.cex)]
287         #v.label <- v.label[order(label.cex)]
288         #label.cex <- label.cex[order(label.cex)]
289         text(txt.layout[,1], txt.layout[,2], v.label, cex=label.cex, col=vertex.label.color)
290         if (!is.null(leg)) {
291             par(mar=c(0,0,0,0))
292             plot(0, axes = FALSE, pch = '')
293             legend(x = 'center' , leg$unetoile, fill = leg$gcol)
294         }
295         dev.off()
296         return(lo)
297     }
298         if (p.type=='tkplot') {
299                 id <- tkplot(g.toplot,vertex.label=v.label, edge.width=we.width, vertex.size=vertex.size, vertex.color=vertex.col, vertex.label.color=vertex.label.color, edge.label=we.label, edge.color=edge.col, layout=lo)
300         coords = tkplot.getcoords(id)
301         ok <- try(coords <- tkplot.getcoords(id), TRUE)
302                 while (is.matrix(ok)) {
303             ok <- try(coords <- tkplot.getcoords(id), TRUE)
304                         Sys.sleep(0.5)
305         }
306         tkplot.off()
307     return(coords)
308         }
309         
310         if (p.type == 'rgl') {
311                 library('rgl')
312         #rgl.open()
313         #par3d(cex=0.8)
314         lo <- layout.norm(lo, -10, 10, -10, 10, -10, 10)
315                 rglplot(g.toplot,vertex.label='', edge.width=we.width/10, vertex.size=0.01, vertex.color=vertex.col, vertex.label.color="black", edge.color = edge.col, layout=lo, rescale = FALSE)
316         #los <- layout.norm(lo, -1, 1, -1, 1, -1, 1)
317                 text3d(lo[,1], lo[,2], lo[,3], vire.nonascii(v.label), col = vertex.label.color, alpha = 1, cex = vertex.label.cex)
318         rgl.spheres(lo, col = vertex.col, radius = vertex.size/100, alpha = alpha)
319         rgl.bg(color = c('white','black'))
320         if (!is.null(movie)) {
321             require(tcltk)
322             ReturnVal <- tkmessageBox(title="RGL 3 D",message="Cliquez pour commencer le film",icon="info",type="ok")
323
324             movie3d(spin3d(axis=c(0,1,0),rpm=6), movie = 'film_graph', frames = "tmpfilm", duration=10, clean=TRUE, top = TRUE, dir = movie)
325             ReturnVal <- tkmessageBox(title="RGL 3 D",message="Film fini !",icon="info",type="ok")
326         }
327         #play3d(spin3d(axis=c(0,1,0),rpm=6))
328         require(tcltk)
329         ReturnVal <- tkmessageBox(title="RGL 3 D",message="Cliquez pour fermer",icon="info",type="ok")
330         rgl.close()
331         #       while (rgl.cur() != 0)
332         #               Sys.sleep(0.5)
333         }
334 }
335
336
337 graph.word <- function(mat.simi, index) {
338     nm <- matrix(0, ncol = ncol(mat.simi), nrow=nrow(mat.simi), dimnames=list(row.names(mat.simi), colnames(mat.simi)))
339     nm[,index] <- mat.simi[,index]
340     nm[index,] <- mat.simi[index,]
341     nm
342 #    cs <- colSums(nm)
343 #    if (cs) nm <- nm[,-which(cs==0)]
344 #    rs <- rowSums(nm)
345 #    if (rs) nm <- nm[-which(rs==0),]
346 #    nm
347 }