1 # -*- coding: utf-8 -*-
2 #Author: Pierre Ratinaud
3 #Copyright (c) 2008-2011 Pierre Ratinaud
7 from chemins import ffr, PathOut
10 from datetime import datetime
13 log = logging.getLogger('iramuteq.printRscript')
16 def __init__ (self, analyse, parametres = None):
18 self.pathout = analyse.pathout
19 self.analyse = analyse
20 if parametres is None :
21 self.parametres = analyse.parametres
23 self.parametres = parametres
24 #self.scriptout = ffr(self.pathout['lastRscript.R'])
25 self.scriptout = self.pathout['temp']
26 self.script = u"#Script genere par IRaMuTeQ - %s\n" % datetime.now().ctime()
29 self.script = '\n'.join([self.script, txt])
31 def defvar(self, name, value) :
32 self.add(' <- '.join([name, value]))
34 def defvars(self, lvars) :
36 self.defvar(val[0],val[1])
38 def sources(self, lsources) :
39 for source in lsources :
40 self.add('source("%s", encoding = \'utf8\')' % ffr(source))
42 def packages(self, lpks) :
44 self.add('library(%s)' % pk)
48 self.add('load("%s")' % ffr(val))
51 with open(self.scriptout, 'w') as f :
55 class chdtxt(PrintRScript) :
59 return str(color).replace(')', ', max=255)')
61 class Alceste2(PrintRScript) :
63 self.sources(['chdfunct'])
65 lvars = [['clnb', `self.analyse.clnb`],
66 ['Contout', '"%s"' % self.pathout['Contout']],
67 ['ContSupOut', '"%s"' % self.pathout['ContSupOut']],
68 ['ContEtOut', '"%s"' % self.pathout['ContEtOut']],
69 ['profileout', '"%s"' % self.pathout['profils.csv']],
70 ['antiout', '"%s"' % self.pathout['antiprofils.csv']],
71 ['chisqtable', '"%s"' % self.pathout['chisqtable.csv']],
72 ['ptable', '"%s"' % self.pathout['ptable.csv']]]
78 # txt = "clnb<-%i\n" % clnb
82 #""" % (RscriptsPath['chdfunct'], DictChdTxtOut['RData'])
84 #dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
85 #datasup<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
86 #dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
87 #""" % (DictChdTxtOut['Contout'], DictChdTxtOut['ContSupOut'], DictChdTxtOut['ContEtOut'])
89 #tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
90 #tablesqrpsup<-BuildProf(as.matrix(datasup),n1,clnb)
91 #tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
94 #PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s",tablesqrpsup[4],tablesqrpsup[5])
95 #""" % (DictChdTxtOut['PROFILE_OUT'], DictChdTxtOut['ANTIPRO_OUT'])
97 #colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
98 #colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
99 #colnames(tablesqrpsup[[2]])<-paste('classe',1:clnb,sep=' ')
100 #colnames(tablesqrpsup[[1]])<-paste('classe',1:clnb,sep=' ')
101 #colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
102 #colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
103 #chistabletot<-rbind(tablesqrpact[2][[1]],tablesqrpsup[2][[1]])
104 #chistabletot<-rbind(chistabletot,tablesqrpet[2][[1]])
105 #ptabletot<-rbind(tablesqrpact[1][[1]],tablesqrpet[1][[1]])
108 #write.csv2(chistabletot,file="%s")
109 #write.csv2(ptabletot,file="%s")
111 #write.csv2(gbcluster,file="%s")
112 #""" % (DictChdTxtOut['chisqtable'], DictChdTxtOut['ptable'], DictChdTxtOut['SbyClasseOut'])
116 def RchdTxt(DicoPath, RscriptPath, mincl, classif_mode, nbt = 9, svdmethod = 'svdR', libsvdc = False, libsvdc_path = None, R_max_mem = False, mode_patate = False, nbproc=1):
122 """ % (ffr(RscriptPath['CHD']), ffr(RscriptPath['chdtxt']), ffr(RscriptPath['anacor']), ffr(RscriptPath['Rgraph']))
131 if svdmethod == 'svdlibc' and libsvdc :
133 svd.method <- 'svdlibc'
135 """ % ffr(libsvdc_path)
136 elif svdmethod == 'irlba' :
139 svd.method <- 'irlba'
157 data1 <- readMM("%s")
158 data1 <- as(data1, "dgCMatrix")
159 row.names(data1) <- 1:nrow(data1)
160 """ % ffr(DicoPath['TableUc1'])
162 if classif_mode == 0:
164 data2 <- readMM("%s")
165 data2 <- as(data2, "dgCMatrix")
166 row.names(data2) <- 1:nrow(data2)
167 """ % ffr(DicoPath['TableUc2'])
170 #print('FIXME : source newCHD')
171 #source('/home/pierre/workspace/iramuteq/Rscripts/newCHD.R')
173 #chd1<-CHD(data1, x = nbt, mode.patate = mode.patate, svd.method = svd.method, libsvdc.path = libsvdc.path, find='matrix', select.next='size', sample=20, amp=500, proc.nb=nbproc)
174 chd1<-CHD(data1, x = nbt, mode.patate = mode.patate, svd.method = svd.method, libsvdc.path = libsvdc.path)#, log.file = log1)
175 """ % (ffr(DicoPath['log-chd1.txt']), nbproc)
177 if classif_mode == 0:
180 chd2<-CHD(data2, x = nbt, mode.patate = mode.patate, svd.method =
181 svd.method, libsvdc.path = libsvdc.path)#, log.file = log2)
182 """ % ffr(DicoPath['log-chd2.txt'])
186 listuce1<-read.csv2("%s")
187 """ % ffr(DicoPath['listeuce1'])
189 if classif_mode == 0:
191 listuce2<-read.csv2("%s")
192 """ % ffr(DicoPath['listeuce2'])
198 if classif_mode == 0:
205 if (mincl == 0) {mincl <- round(nrow(chd1$n1)/(nbt+1))}
207 write.csv2(chd1$n1, file="%s")
208 if (classif_mode == 0) {
209 chd.result <- Rchdtxt(uceout, chd1, chd2 = chd2, mincl = mincl,classif_mode = classif_mode, nbt = nbt)
210 classeuce1 <- chd.result$cuce1
211 tree.tot1 <- make_tree_tot(chd1)
212 tree.cut1 <- make_dendro_cut_tuple(tree.tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
215 #chd.result <- Rchdtxt(uceout, chd1, chd2 = chd1, mincl = mincl,classif_mode = classif_mode, nbt = nbt)
216 tree.tot1 <- make_tree_tot(chd1)
217 terminales <- find.terminales(chd1$n1, chd1$list_mere, chd1$list_fille, mincl)
218 tree.cut1 <- make.classes(terminales, chd1$n1, tree.tot1$tree.cl, chd1$list_fille)
219 write.csv2(tree.cut1$n1, uceout)
220 chd.result <- tree.cut1
222 classes<-chd.result$n1[,ncol(chd.result$n1)]
223 write.csv2(chd.result$n1, file="%s")
224 """ % (classif_mode, mincl, ffr(DicoPath['uce']), ffr(DicoPath['n1-1.csv']), ffr(DicoPath['n1.csv']))
227 # tree.tot1 <- make_tree_tot(chd1)
228 # open_file_graph("%s", widt = 600, height=400)
229 # plot(tree.tot1$tree.cl)
231 """ % ffr(DicoPath['arbre1'])
233 if classif_mode == 0:
235 classeuce2 <- chd.result$cuce2
236 tree.tot2 <- make_tree_tot(chd2)
237 # open_file_graph("%s", width = 600, height=400)
238 # plot(tree.tot2$tree.cl)
240 """ % ffr(DicoPath['arbre2'] )
243 save(tree.cut1, file="%s")
245 open_file_graph("%s", width = 600, height=400)
246 plot.dendropr(tree.cut1$tree.cl,classes, histo=TRUE)
247 open_file_graph("%s", width = 600, height=400)
248 plot(tree.cut1$dendro_tot_cl)
250 """ % (ffr(DicoPath['Rdendro']), ffr(DicoPath['dendro1']), ffr(DicoPath['arbre1']))
252 if classif_mode == 0:
254 tree.cut2 <- make_dendro_cut_tuple(tree.tot2$dendro_tuple, chd.result$coord_ok, classeuce2, 2, nbt)
255 open_file_graph("%s", width = 600, height=400)
256 plot(tree.cut2$tree.cl)
258 open_file_graph("%s", width = 600, height=400)
259 plot(tree.cut2$dendro_tot_cl)
261 """ % (ffr(DicoPath['dendro2']), ffr(DicoPath['arbre2']))
265 #save.image(file="%s")
266 """ % (ffr(DicoPath['RData']))
268 fileout = open(DicoPath['Rchdtxt'], 'w')
272 def RPamTxt(corpus, RscriptPath):
273 DicoPath = corpus.pathout
274 param = corpus.parametres
277 """ % (RscriptPath['pamtxt'])
280 """ % (RscriptPath['Rgraph'])
282 result <- pamtxt("%s", "%s", "%s", method = "%s", clust_type = "%s", clnb = %i)
284 """ % (DicoPath['TableUc1'], DicoPath['listeuce1'], DicoPath['uce'], param['method'], param['cluster_type'], param['nbcl'] )
286 open_file_graph("%s", width=400, height=400)
289 """ % (DicoPath['arbre1'])
291 save.image(file="%s")
292 """ % DicoPath['RData']
293 fileout = open(DicoPath['Rchdtxt'], 'w')
298 def RchdQuest(DicoPath, RscriptPath, nbcl = 10, mincl = 10):
304 """ % (ffr(RscriptPath['CHD']), ffr(RscriptPath['chdquest']), ffr(RscriptPath['anacor']),ffr(RscriptPath['Rgraph']))
312 chd.result<-Rchdquest("%s","%s","%s", nbt = nbt, mincl = mincl)
314 classeuce1 <- chd.result$cuce1
315 """ % (ffr(DicoPath['mat01.csv']), ffr(DicoPath['listeuce1']), ffr(DicoPath['uce']))
318 tree_tot1 <- make_tree_tot(chd.result$chd)
319 open_file_graph("%s", width = 600, height=400)
320 plot(tree_tot1$tree.cl)
322 """ % ffr(DicoPath['arbre1'])
325 tree_cut1 <- make_dendro_cut_tuple(tree_tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
326 tree.cut1 <- tree_cut1
327 save(tree.cut1, file="%s")
328 open_file_graph("%s", width = 600, height=400)
329 classes<-n1[,ncol(n1)]
330 plot.dendropr(tree_cut1$tree.cl,classes, histo = TRUE)
331 """ % (ffr(DicoPath['Rdendro']), ffr(DicoPath['dendro1']))
334 save.image(file="%s")
335 """ % ffr(DicoPath['RData'])
336 fileout = open(DicoPath['Rchdquest'], 'w')
340 def ReinertTxtProf(DictChdTxtOut, RscriptsPath, clnb, taillecar):
341 txt = "clnb<-%i\n" % clnb
345 n1 <- read.csv2("%s")
346 """ % (ffr(RscriptsPath['chdfunct']), ffr(DictChdTxtOut['RData']), ffr(DictChdTxtOut['n1.csv']))
348 dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
349 datasup<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
350 dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
351 """ % (ffr(DictChdTxtOut['Contout']), ffr(DictChdTxtOut['ContSupOut']), ffr(DictChdTxtOut['ContEtOut']))
353 print('ATTENTION NEW BUILD PROF')
354 #tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
355 #tablesqrpsup<-BuildProf(as.matrix(datasup),n1,clnb)
356 #tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
357 tablesqrpact<-new.build.prof(as.matrix(dataact),n1,clnb)
358 tablesqrpsup<-new.build.prof(as.matrix(datasup),n1,clnb)
359 tablesqrpet<-new.build.prof(as.matrix(dataet),n1,clnb)
363 PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s",tablesqrpsup[4],tablesqrpsup[5])
364 """ % (ffr(DictChdTxtOut['PROFILE_OUT']), ffr(DictChdTxtOut['ANTIPRO_OUT']))
366 colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
367 colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
368 colnames(tablesqrpsup[[2]])<-paste('classe',1:clnb,sep=' ')
369 colnames(tablesqrpsup[[1]])<-paste('classe',1:clnb,sep=' ')
370 colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
371 colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
372 chistabletot<-rbind(tablesqrpact[2][[1]],tablesqrpsup[2][[1]])
373 chistabletot<-rbind(chistabletot,tablesqrpet[2][[1]])
374 ptabletot<-rbind(tablesqrpact[1][[1]],tablesqrpet[1][[1]])
377 write.csv2(chistabletot,file="%s")
378 write.csv2(ptabletot,file="%s")
380 write.csv2(gbcluster,file="%s")
381 """ % (ffr(DictChdTxtOut['chisqtable']), ffr(DictChdTxtOut['ptable']), ffr(DictChdTxtOut['SbyClasseOut']))
385 colnames(dataact)<-paste('classe',1:clnb,sep=' ')
386 colnames(datasup)<-paste('classe',1:clnb,sep=' ')
387 colnames(dataet)<-paste('classe',1:clnb,sep=' ')
388 rowtot<-nrow(dataact)+nrow(dataet)+nrow(datasup)
389 afctable<-rbind(as.matrix(dataact),as.matrix(datasup))
390 afctable<-rbind(afctable,as.matrix(dataet))
391 colnames(afctable)<-paste('classe',1:clnb,sep=' ')
392 afc<-ca(afctable,suprow=((nrow(dataact)+1):rowtot),nd=(ncol(afctable)-1))
393 debsup<-nrow(dataact)+1
394 debet<-nrow(dataact)+nrow(datasup)+1
396 afc<-AddCorrelationOk(afc)
398 #FIXME : split this!!!
401 """ % ffr(RscriptsPath['Rgraph'])
404 afc <- summary.ca.dm(afc)
405 afc_table <- create_afc_table(afc)
406 write.csv2(afc_table$facteur, file = "%s")
407 write.csv2(afc_table$colonne, file = "%s")
408 write.csv2(afc_table$ligne, file = "%s")
409 """ % (ffr(DictChdTxtOut['afc_facteur']), ffr(DictChdTxtOut['afc_col']), ffr(DictChdTxtOut['afc_row']))
415 xyminmax <- PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
416 """ % (ffr(DictChdTxtOut['AFC2DL_OUT']))
418 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=debsup, fin=(debet-1), xlab = xlab, ylab = ylab, xmin = xyminmax$xminmax[1], xmax = xyminmax$xminmax[2], ymin = xyminmax$yminmax[1], ymax = xyminmax$yminmax[2], active=FALSE)
419 """ % (ffr(DictChdTxtOut['AFC2DSL_OUT']))
421 if ((fin - debet) > 2) {
422 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=debet, fin=fin, xlab = xlab, ylab = ylab, xmin = xyminmax$xminmax[1], xmax = xyminmax$xminmax[2], ymin = xyminmax$yminmax[1], ymax = xyminmax$yminmax[2], active = FALSE)
424 """ % (ffr(DictChdTxtOut['AFC2DEL_OUT']))
426 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col=TRUE, what='coord', xlab = xlab, ylab = ylab, xmin = xyminmax$xminmax[1], xmax = xyminmax$xminmax[2], ymin = xyminmax$yminmax[1], ymax = xyminmax$yminmax[2], active=FALSE)
427 """ % (ffr(DictChdTxtOut['AFC2DCL_OUT']))
429 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
430 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debsup, fin=(debet-1), xlab = xlab, ylab = ylab)
431 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debet, fin=fin, xlab = xlab, ylab = ylab)
432 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col=TRUE, what='crl', xlab = xlab, ylab = ylab)
433 # """ % (DictChdTxtOut['AFC2DCoul'], DictChdTxtOut['AFC2DCoulSup'], DictChdTxtOut['AFC2DCoulEt'], DictChdTxtOut['AFC2DCoulCl'])
442 save.image(file="%s")
443 """ % ffr(DictChdTxtOut['RData'])
444 file = open(DictChdTxtOut['RTxtProfGraph'], 'w')
449 def write_afc_graph(self):
450 if self.param['over'] : over = 'TRUE'
451 else : over = 'FALSE'
453 if self.param['do_select_nb'] : do_select_nb = 'TRUE'
454 else : do_select_nb = 'FALSE'
456 if self.param['do_select_chi'] : do_select_chi = 'TRUE'
457 else : do_select_chi = 'FALSE'
459 if self.param['do_select_chi_classe'] : do_select_chi_classe = 'TRUE'
460 else : do_select_chi_classe = 'FALSE'
462 if self.param['cex_txt'] : cex_txt = 'TRUE'
463 else : cex_txt = 'FALSE'
465 if self.param['tchi'] : tchi = 'TRUE'
466 else : tchi = 'FALSE'
468 if self.param['svg'] : svg = 'TRUE'
471 if self.param['typegraph'] == 4 :
472 nodesfile = os.path.join(os.path.dirname(self.fileout),'nodes.csv')
473 edgesfile = os.path.join(os.path.dirname(self.fileout),'edges.csv')
478 with open(self.RscriptsPath['afc_graph'], 'r') as f:
481 # self.DictPathOut['RData'], \
482 scripts = txt % (ffr(self.RscriptsPath['Rgraph']),\
483 self.param['typegraph'], \
484 edgesfile, nodesfile, \
485 self.param['what'], \
486 self.param['facteur'][0],\
487 self.param['facteur'][1], \
488 self.param['facteur'][2], \
490 over, do_select_nb, \
491 self.param['select_nb'], \
493 self.param['select_chi'], \
494 do_select_chi_classe, \
495 self.param['nbchic'], \
497 self.param['txt_min'], \
498 self.param['txt_max'], \
500 self.param['width'], \
501 self.param['height'],\
502 self.param['taillecar'], \
503 self.param['alpha'], \
504 self.param['film'], \
506 self.param['tchi_min'],\
507 self.param['tchi_max'],\
508 ffr(os.path.dirname(self.fileout)),\
512 def print_simi3d(self):
513 simi3d = self.parent.simi3dpanel
514 txt = '#Fichier genere par Iramuteq'
515 if simi3d.movie.GetValue() :
516 movie = "'" + ffr(os.path.dirname(self.DictPathOut['RData'])) + "'"
520 #if self.corpus.parametres['type'] == 'corpus' :
526 dm<-read.csv2("%s",row.names=1,header = %s)
528 """ % (self.DictPathOut['Contout'], header, self.DictPathOut['RData'])
532 """ % self.parent.RscriptsPath['Rgraph']
536 make.simi.afc(dm,chistabletot, lim=%i, alpha = %.2f, movie = %s)
537 """ % (simi3d.spin_1.GetValue(), float(simi3d.slider_1.GetValue())/100, movie)
538 tmpfile = tempfile.mktemp(dir=self.parent.TEMPDIR)
539 tmp = open(tmpfile,'w')
544 def dendroandbarplot(table, rownames, colnames, rgraph, tmpgraph, intxt = False, dendro=False) :
546 txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
547 rownb = len(rownames)
548 rownames = 'c("' + '","'.join(rownames) + '")'
549 colnames = 'c("' + '","'.join(colnames) + '")'
553 di <- matrix(data=%s, nrow=%i, byrow = TRUE)
556 """ % (txttable, rownb, rownames, colnames)
563 height <- (30*ncol(di)) + (15*nrow(di))
564 height <- ifelse(height <= 400, 400, height)
566 open_file_graph("%s", width=width, height=height)
567 plot.dendro.lex(tree.cut1$tree.cl, di)
568 """ % (ffr(dendro),ffr(rgraph), ffr(tmpgraph))
571 def barplot(table, parametres, intxt = False) :
573 txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
574 #width = 100 + (15 * len(rownames)) + (100 * len(colnames))
575 #height = len(rownames) * 15
576 rownb = len(parametres['rownames'])
579 rownames = 'c("' + '","'.join(parametres['rownames']) + '")'
580 colnames = 'c("' + '","'.join(parametres['colnames']) + '")'
585 di <- matrix(data=%s, nrow=%i, byrow = TRUE)
586 toinf <- which(di == Inf)
587 tominf <- which(di == -Inf)
590 valmax <- max(di, na.rm = TRUE)
598 if (length(tominf)) {
600 valmin <- min(di, na.rm = TRUE)
610 """ % (txttable, rownb, rownames, colnames)
613 if not 'tree' in parametres :
616 color = rainbow(nrow(di))
619 open_file_graph("%s",width = width, height = height, svg = %s)
621 layout(matrix(c(1,2),1,2, byrow=TRUE),widths=c(3,lcm(12)))
623 yp = ifelse(length(toinf), 0.2, 0)
624 ym = ifelse(length(tominf), 0.2, 0)
625 ymin <- ifelse(!length(which(di < 0)), 0, min(di) - ym)
626 coord <- barplot(as.matrix(di), beside = TRUE, col = color, space = c(0.1,0.6), ylim=c(ymin, max(di) + yp), las = 2)
628 coordinf <- coord[toinf]
630 text(x=coordinf, y=valinf + 0.1, 'i')
632 if (length(tominf)) {
633 coordinf <- coord[toinf]
635 text(x=coordinf, y=valinf - 0.1, 'i')
641 lcoord <- apply(cc, 1, mean)
644 amp <- abs(max(di) - min(di))
651 d <- signif(amp%%/%%10,1)
656 if ((i/d) == (i%%/%%d)) {
661 plot(0, axes = FALSE, pch = '')
662 legend(x = 'center' , rownames(di), fill = color)
664 """ % (ffr(parametres['rgraph']), parametres['width'], parametres['height'], ffr(parametres['tmpgraph']), parametres['svg'])
672 open_file_graph("%s", width=width, height=height, svg = %s)
673 plot.dendro.lex(tree.cut1$tree.cl, di)
674 """ % (ffr(parametres['tree']), ffr(parametres['rgraph']), parametres['width'], parametres['height'], ffr(parametres['tmpgraph']), parametres['svg'])
677 #def RAfcUci(DictAfcUciOut, nd=2, RscriptsPath='', PARCEX='0.8'):
683 # dataact<-read.csv2("%s")
684 # """ % (DictAfcUciOut['TableCont'])#, encoding)
686 # datasup<-read.csv2("%s")
687 # """ % (DictAfcUciOut['TableSup'])#, encoding)
689 # dataet<-read.csv2("%s")
690 # """ % (DictAfcUciOut['TableEt'])#, encoding)
692 # datatotsup<-cbind(dataact,datasup)
693 # datatotet<-cbind(dataact,dataet)
694 # afcact<-ca(dataact,nd=nd)
695 # afcsup<-ca(datatotsup,supcol=((ncol(dataact)+1):ncol(datatotsup)),nd=nd)
696 # afcet<-ca(datatotet,supcol=((ncol(dataact)+1):ncol(datatotet)),nd=nd)
697 # afctot<-afcsup$colcoord
698 # rownames(afctot)<-afcsup$colnames
699 # colnames(afctot)<-paste('coord. facteur',1:nd,sep=' ')
700 # afctot<-cbind(afctot,mass=afcsup$colmass)
701 # afctot<-cbind(afctot,distance=afcsup$coldist)
702 # afctot<-cbind(afctot,intertie=afcsup$colinertia)
703 # rcolet<-afcet$colsup
704 # afctmp<-afcet$colcoord[rcolet,]
705 # rownames(afctmp)<-afcet$colnames[rcolet]
706 # afctmp<-cbind(afctmp,afcet$colmass[rcolet])
707 # afctmp<-cbind(afctmp,afcet$coldist[rcolet])
708 # afctmp<-cbind(afctmp,afcet$colinertia[rcolet])
709 # afctot<-rbind(afctot,afctmp)
710 # write.csv2(afctot,file = "%s")
712 # """ % (DictAfcUciOut['afc_row'], RscriptsPath['Rgraph'])
718 # PlotAfc(afcet,filename="%s",toplot=c%s, PARCEX=PARCEX)
719 # """ % (DictAfcUciOut['AfcColAct'], "('none','active')")
721 # PlotAfc(afcsup,filename="%s",toplot=c%s, PARCEX=PARCEX)
722 # """ % (DictAfcUciOut['AfcColSup'], "('none','passive')")
723 # txt += """PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
724 # """ % (DictAfcUciOut['AfcColEt'], "('none','passive')")
726 # PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
727 # """ % (DictAfcUciOut['AfcRow'], "('all','none')")
728 # f = open(DictAfcUciOut['Rafcuci'], 'w')
732 class PrintSimiScript(PrintRScript) :
733 def make_script(self) :
735 self.packages(['igraph', 'proxy', 'Matrix'])
736 self.sources([self.analyse.parent.RscriptsPath['simi'], self.analyse.parent.RscriptsPath['Rgraph']])
738 if not self.parametres['keep_coord'] and not (self.parametres['type'] == 'simimatrix' or self.parametres['type'] == 'simiclustermatrix') :
743 """ % (ffr(self.pathout['mat01.csv']), ffr(self.pathout['actives.csv']), ffr(self.pathout['selected.csv']))
744 if 'word' in self.parametres :
748 """ % self.parametres['word']
756 cn <- read.table(cn.path, sep="\t", quote='"')
757 colnames(dm) <- cn[,1]
758 if (file.exists(selected.col)) {
759 sel.col <- read.csv2(selected.col, header = FALSE)
760 sel.col <- sel.col[,1] + 1
762 sel.col <- 1:ncol(dm)
767 forme <- colnames(dm)[index]
768 if (!index %in% sel.col) {
769 sel.col <- append(sel.col, index)
772 index <- which(colnames(dm) == forme)
775 elif not self.parametres['keep_coord'] and (self.parametres['type'] == 'simimatrix' or self.parametres['type'] == 'simiclustermatrix'):
779 """ % (ffr(self.pathout['mat01.csv']), ffr(self.pathout['selected.csv']))
780 if 'word' in self.parametres :
784 """ % self.parametres['word']
790 dm <-read.csv2(dm.path)
792 if (file.exists(selected.col)) {
793 sel.col <- read.csv2(selected.col, header = FALSE)
794 sel.col <- sel.col[,1] + 1
796 sel.col <- 1:ncol(dm)
801 forme <- colnames(dm)[index]
802 if (!index %in% sel.col) {
803 sel.col <- append(sel.col, index)
806 index <- which(colnames(dm) == forme)
812 """ % ffr(self.pathout['RData.RData'])
814 if self.parametres['coeff'] == 0 :
816 if not self.parametres['keep_coord'] :
821 elif self.analyse.indices[self.parametres['coeff']] == 'Jaccard' :
823 if not self.parametres['keep_coord'] :
826 mat <- sparse.jaccard(dm)
829 if not self.parametres['keep_coord'] :
833 if self.parametres['coeff'] == 1 :
837 mat <- simil(dm, method = 'Russel', diag = TRUE, upper = TRUE, by_rows = FALSE)
839 elif self.analyse.indices[self.parametres['coeff']] == 'binomial' :
841 if not self.parametres['keep_coord'] :
846 elif self.parametres['coeff'] != 0 and self.analyse.indices[self.parametres['coeff']] != 'Jaccard':
847 method = self.analyse.indices[self.parametres['coeff']]
848 if not self.parametres['keep_coord'] :
851 mat <- simil(dm, method = method, diag = TRUE, upper = TRUE, by_rows = FALSE)
852 """ % self.analyse.indices[self.parametres['coeff']]
853 if not self.parametres['keep_coord'] :
855 mat <- as.matrix(stats::as.dist(mat,diag=TRUE,upper=TRUE))
857 if (length(which(mat == Inf))) {
858 infp <- which(mat == Inf)
860 maxmat <- max(mat, na.rm = TRUE)
868 if (length(which(mat == -Inf))) {
869 infm <- which(mat == -Inf)
871 minmat <- min(mat, na.rm = TRUE)
880 if 'word' in self.parametres and not self.parametres['keep_coord'] :
882 mat <- graph.word(mat, index)
884 if (length(which(cs==0))) mat <- mat[,-which(cs==0)]
886 if (length(which(rs==0))) mat <- mat[-which(rs==0),]
887 if (length(which(cs==0))) dm <- dm[,-which(cs==0)]
889 index <- which(colnames(mat)==forme)
893 if self.parametres['layout'] == 0 : layout = 'random'
894 if self.parametres['layout'] == 1 : layout = 'circle'
895 if self.parametres['layout'] == 2 : layout = 'frutch'
896 if self.parametres['layout'] == 3 : layout = 'kawa'
897 if self.parametres['layout'] == 4 : layout = 'graphopt'
898 if self.parametres['layout'] == 5 : layout = 'spirale'
899 if self.parametres['layout'] == 6 : layout = 'spirale3D'
903 if self.parametres['type_graph'] == 0 : type = 'tkplot'
904 if self.parametres['type_graph'] == 1 :
907 dirout = os.path.dirname(self.pathout['mat01.csv'])
908 while os.path.exists(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png')):
910 self.filename = ffr(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png'))
911 if self.parametres['type_graph'] == 2 : type = 'rgl'
912 if self.parametres['type_graph'] == 3 :
915 dirout = os.path.dirname(self.pathout['mat01.csv'])
916 while os.path.exists(os.path.join(dirout,'web_'+str(graphnb))):
918 self.filename = ffr(os.path.join(dirout,'web_'+str(graphnb)))
919 os.mkdir(self.filename)
920 self.filename = os.path.join(self.filename, 'gexf.gexf')
921 if self.parametres['type_graph'] == 4 :
924 dirout = os.path.dirname(self.pathout['mat01.csv'])
925 while os.path.exists(os.path.join(dirout,'webrgl_'+str(graphnb))):
927 self.filename = ffr(os.path.join(dirout,'webrgl_'+str(graphnb)))
928 os.mkdir(self.filename)
930 if self.parametres['arbremax'] :
932 self.txtgraph += ' - arbre maximum'
933 else : arbremax = 'FALSE'
935 if self.parametres['coeff_tv'] :
936 coeff_tv = self.parametres['coeff_tv_nb']
937 tvminmax = 'c(NULL,NULL)'
938 elif not self.parametres['coeff_tv'] or self.parametres.get('sformchi', False) :
940 tvminmax = 'c(%i, %i)' %(self.parametres['tvmin'], self.parametres['tvmax'])
941 if self.parametres['coeff_te'] : coeff_te = 'c(%i,%i)' % (self.parametres['coeff_temin'], self.parametres['coeff_temax'])
942 else : coeff_te = 'NULL'
944 if self.parametres['vcex'] or self.parametres.get('cexfromchi', False) :
945 vcexminmax = 'c(%i/10,%i/10)' % (self.parametres['vcexmin'],self.parametres['vcexmax'])
947 vcexminmax = 'c(NULL,NULL)'
948 if not self.parametres['label_v'] : label_v = 'FALSE'
949 else : label_v = 'TRUE'
951 if not self.parametres['label_e'] : label_e = 'FALSE'
952 else : label_e = 'TRUE'
954 if self.parametres['seuil_ok'] : seuil = str(self.parametres['seuil'])
955 else : seuil = 'NULL'
957 if not self.parametres.get('edgecurved', False) :
966 cols = str(self.parametres['cols']).replace(')',', max=255)')
967 cola = str(self.parametres['cola']).replace(')',',max=255)')
977 """ % self.parametres['cex']
979 if self.parametres['film'] :
982 """ % ffr(self.pathout['film'])
989 if (!is.null(seuil)) {
990 if (method!='cooc') {
999 """ % (label_v, label_e)
1007 """ % (self.parametres['width'], self.parametres['height'])
1008 if self.parametres['keep_coord'] :
1010 coords <- try(coords, TRUE)
1011 if (!is.matrix(coords)) {
1021 """ % self.parametres['alpha']
1024 """ % self.parametres['alpha']
1025 #############################################
1026 if self.parametres.get('bystar',False) :
1030 for i, line in enumerate(self.parametres['listet']) :
1033 """ % (i+1, ','.join([`val + 1` for val in line]))
1036 """ % ("','".join([val for val in self.parametres['selectedstars']]))
1040 for (i in 1:length(unetoile)) {
1043 if (length(tosum) > 1) {
1044 fsum <- cbind(fsum, colSums(dm[tosum,]))
1046 fsum <- cbind(fsum, dm[tosum,])
1050 lex <- AsLexico2(fsum, chip=TRUE)
1051 dcol <- apply(lex[[4]],1,which.max)
1052 toblack <- apply(lex[[4]],1,max)
1053 gcol <- rainbow(length(unetoile))
1054 #gcol[2] <- 'orange'
1055 vertex.label.color <- gcol[dcol]
1056 vertex.label.color[which(toblack <= 3.84)] <- 'black'
1057 leg <- list(unetoile=unetoile, gcol=gcol)
1058 cols <- vertex.label.color
1059 chivertex.size <- norm.vec(toblack, vcexminmax[1], vcexminmax[2])
1061 """ % (ffr(self.analyse.parent.RscriptsPath['chdfunct']))
1064 vertex.label.color <- 'black'
1068 #############################################
1071 # eff <- colSums(dm)
1072 # g.ori <- graph.adjacency(mat, mode='lower', weighted = TRUE)
1073 # w.ori <- E(g.ori)$weight
1075 # if (method == 'cooc') {
1076 # E(g.ori)$weight <- 1 / w.ori
1078 # E(g.ori)$weigth <- 1 - w.ori
1080 # g.max <- minimum.spanning.tree(g.ori)
1081 # if (method == 'cooc') {
1082 # E(g.max)$weight <- 1 / E(g.max)$weight
1084 # E(g.max)$weight <- 1 - E(g.max)$weight
1091 if self.parametres['com'] :
1092 com = `self.parametres['communities']`
1095 if self.parametres['halo'] :
1105 x <- list(mat = mat, eff = eff)
1106 graph.simi <- do.simi(x, method='%s', seuil = seuil, p.type = '%s', layout.type = '%s', max.tree = %s, coeff.vertex=%s, coeff.edge = %s, minmaxeff = minmaxeff, vcexminmax = vcexminmax, cex = cex, coords = coords, communities = communities, halo = halo, index.word=index)
1107 """ % (method, type, layout, arbremax, coeff_tv, coeff_te)
1109 if self.parametres.get('bystar',False) :
1110 if self.parametres.get('cexfromchi', False) :
1112 label.cex<-chivertex.size
1118 if self.parametres.get('sfromchi', False) :
1120 vertex.size <- norm.vec(toblack, minmaxeff[1], minmaxeff[2])
1127 #print self.parametres
1128 if (self.parametres['type'] == 'clustersimitxt' and self.parametres.get('tmpchi', False)) or (self.parametres['type'] in ['simimatrix','simiclustermatrix'] and 'tmpchi' in self.parametres):
1130 lchi <- read.table("%s")
1132 """ % ffr(self.parametres['tmpchi'])
1134 lchi <- lchi[sel.col]
1136 if self.parametres['type'] in ['clustersimitxt', 'simimatrix', 'simiclustermatrix'] and self.parametres.get('cexfromchi', False) :
1138 label.cex <- norm.vec(lchi, vcexminmax[1], vcexminmax[2])
1142 if (is.null(vcexminmax[1])) {
1145 label.cex <- graph.simi$label.cex
1148 if (self.parametres['type'] in ['clustersimitxt', 'simimatrix', 'simiclustermatrix']) and self.parametres.get('sfromchi', False):
1150 vertex.size <- norm.vec(lchi, minmaxeff[1], minmaxeff[2])
1151 if (!length(vertex.size)) vertex.size <- 0
1155 if (is.null(minmaxeff[1])) {
1158 vertex.size <- graph.simi$eff
1161 #txt += """ vertex.size <- NULL """
1162 if self.parametres['svg'] : svg = 'TRUE'
1163 else : svg = 'FALSE'
1170 if (col.from.proto) {
1171 proto.col <- read.table('/tmp/matcol.csv')
1172 v.proto.names <- make.names(proto.col[,1])
1173 v.proto.col <- as.character(proto.col[,2])
1174 v.proto.col[which(v.proto.col=='black')] <- 'yellow'
1175 v.names <- V(graph.simi$graph)$name
1176 num.color <- sapply(v.names, function(x) {if (x %%in%% v.proto.names) {v.proto.col[which(v.proto.names==x)]} else {'pink'}})
1177 vertex.col <- num.color
1178 V(graph.simi$graph)$proto.color <- vertex.col
1180 if (!is.null(graph.simi$com)) {
1181 com <- graph.simi$com
1182 colm <- rainbow(length(com))
1183 if (vertex.size != 0 || graph.simi$halo) {
1184 vertex.label.color <- 'black'
1185 vertex.col <- colm[membership(com)]
1187 vertex.label.color <- colm[membership(com)]
1190 if (!length(graph.simi$elim)==0) {
1191 vertex.label.color <- vertex.label.color[-graph.simi$elim]
1192 if (length(label.cex > 1)) {
1193 label.cex <- label.cex[-graph.simi$elim]
1196 coords <- plot.simi(graph.simi, p.type='%s',filename="%s", vertex.label = label.v, edge.label = label.e, vertex.col = vertex.col, vertex.label.color = vertex.label.color, vertex.label.cex=label.cex, vertex.size = vertex.size, edge.col = cola, leg=leg, width = width, height = height, alpha = alpha, movie = film, edge.curved = edge.curved, svg = svg)
1197 save.image(file="%s")
1198 """ % (type, self.filename, ffr(self.pathout['RData']))
1203 class WordCloudRScript(PrintRScript) :
1204 def make_script(self) :
1205 self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1206 self.packages(['wordcloud'])
1207 bg_col = Rcolor(self.parametres['col_bg'])
1208 txt_col = Rcolor(self.parametres['col_text'])
1209 if self.parametres['svg'] :
1217 act <- read.csv2("%s", header = FALSE, row.names=1, sep='\t')
1218 selected.col <- read.table("%s")
1219 toprint <- as.matrix(act[selected.col[,1] + 1,])
1220 rownames(toprint) <- rownames(act)[selected.col[,1] + 1]
1222 if (nrow(toprint) > maxword) {
1223 toprint <- as.matrix(toprint[order(toprint[,1], decreasing=TRUE),])
1224 toprint <- as.matrix(toprint[1:maxword,])
1226 open_file_graph("%s", width = %i, height = %i , svg = svg)
1228 wordcloud(row.names(toprint), toprint[,1], scale=c(%f,%f), random.order=FALSE, colors=rgb%s)
1230 """ % (ffr(self.analyse.pathout['actives_eff.csv']), ffr(self.analyse.pathout['selected.csv']), self.parametres['maxword'], ffr(self.parametres['graphout']), self.parametres['width'], self.parametres['height'], bg_col, self.parametres['maxcex'], self.parametres['mincex'], txt_col)
1234 class ProtoScript(PrintRScript) :
1235 def make_script(self) :
1236 self.sources([self.analyse.parent.RscriptsPath['Rgraph'], self.analyse.parent.RscriptsPath['prototypical.R']])
1237 self.packages(['wordcloud'])
1238 if self.parametres.get('cloud', False) :
1243 errorn <- function(x) {
1244 qnorm(0.975)*sd(x)/sqrt(lenght(n))
1246 errort <- function(x) {
1247 qt(0.975,df=lenght(x)-1)*sd(x)/sqrt(lenght(x))
1249 mat <- read.csv2("%s", header = FALSE, row.names=1, sep='\t', quote='"', dec='.')
1250 open_file_graph("%s",height=800, width=1000)
1251 prototypical(mat, mfreq = %s, mrank = %s, cloud = FALSE, cexrange=c(1,2.4), cexalpha= c(0.4, 1), type = '%s', mat.col.path='/tmp/matcol.csv')
1253 """ % (ffr(self.analyse.pathout['table.csv']), ffr(self.analyse.pathout['proto.png']), self.parametres['limfreq'], self.parametres['limrang'], self.parametres['typegraph'])
1258 class ExportAfc(PrintRScript) :
1259 def make_script(self) :
1260 self.source([self.analyse.parent.RscriptsPath['Rgraph']])
1261 self.packages(['rgexf'])
1265 class MergeGraphes(PrintRScript) :
1266 def __init__(self, analyse):
1267 self.script = u"#Script genere par IRaMuTeQ - %s\n" % datetime.now().ctime()
1268 self.pathout = PathOut()
1269 self.parametres = analyse.parametres
1270 self.scriptout = self.pathout['temp']
1271 self.analyse = analyse
1273 def make_script(self) :
1283 g <- graph.simi$graph
1284 V(g)$weight <- (graph.simi$mat.eff/nrow(dm))*100
1287 for i, graph in enumerate(self.parametres['graphs']) :
1288 path = os.path.dirname(graph)
1289 gname = ''.join(['g', `i`])
1290 RData = os.path.join(path,'RData.RData')
1291 txt += load % (ffr(RData), gname)
1293 self.sources([self.analyse.parent.RscriptsPath['simi']])
1295 merge.type <- 'proto'
1296 if (merge.type == 'normal') {
1297 ng <- merge.graph(graphs)
1299 ng <- merge.graph.proto(graphs)
1301 ngraph <- list(graph=ng, layout=layout.fruchterman.reingold(ng, dim=3), labex.cex=V(ng)$weight)
1302 write.graph(ng, "%s", format = 'graphml')
1303 """ % ffr(self.parametres['grapheout'])
1306 class TgenSpecScript(PrintRScript):
1307 def make_script(self):
1308 self.packages(['textometry'])
1310 tgen <- read.csv2("%s", row.names = 1, sep = '\\t')
1311 """ % ffr(self.parametres['tgeneff'])
1313 tot <- tgen[nrow(tgen), ]
1315 tgen <- tgen[-nrow(tgen),]
1316 for (i in 1:nrow(tgen)) {
1317 mat <- rbind(tgen[i,], tot - tgen[i,])
1318 specmat <- specificities(mat)
1319 result <- rbind(result, specmat[1,])
1321 colnames(result) <- colnames(tgen)
1322 row.names(result) <- rownames(tgen)
1323 write.table(result, file = "%s", sep='\\t', col.names = NA)
1324 """ % ffr(self.pathout['tgenspec.csv'])
1327 class TgenProfScript(PrintRScript):
1328 def make_script(self):
1329 self.sources([self.analyse.ira.RscriptsPath['chdfunct']])
1331 tgen <- read.csv2("%s", row.names = 1, sep = '\\t')
1332 """ % ffr(self.parametres['tgeneff'])
1334 tgenlem <- read.csv2("%s", row.names = 1, sep = '\\t')
1335 """ % ffr(self.parametres['tgenlemeff'])
1337 res <- build.prof.tgen(tgen)
1338 write.table(res$chi2, file = "%s", sep='\\t', col.names = NA)
1339 write.table(res$pchi2, file = "%s", sep='\\t', col.names = NA)
1340 """ % (ffr(self.pathout['tgenchi2.csv']), ffr(self.pathout['tgenpchi2.csv']))
1342 reslem <- build.prof.tgen(tgenlem)
1343 write.table(reslem$chi2, file = "%s", sep='\\t', col.names = NA)
1344 write.table(reslem$pchi2, file = "%s", sep='\\t', col.names = NA)
1345 """ % (ffr(self.pathout['tgenlemchi2.csv']), ffr(self.pathout['tgenlempchi2.csv']))
1348 class FreqMultiScript(PrintRScript):
1349 def make_script(self):
1350 self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1352 freq <- read.csv2("%s", row.names=1, sep='\\t', dec='.')
1353 """ % ffr(self.pathout['frequences.csv'])
1355 toplot <- freq[order(freq[,2]) ,2]
1356 toplot.names = rownames(freq)[order(freq[,2])]
1357 h <- 80 + (20 * nrow(freq))
1358 open_file_graph("%s",height=h, width=500)
1359 par(mar=c(3,20,3,3))
1360 barplot(toplot, names = toplot.names, horiz=TRUE, las =1, col = rainbow(nrow(freq)))
1362 """ % ffr(self.pathout['barplotfreq.png'])
1364 toplot <- freq[order(freq[,4]) ,4]
1365 toplot.names = rownames(freq)[order(freq[,4])]
1366 open_file_graph("%s",height=h, width=500)
1367 par(mar=c(3,20,3,3))
1368 barplot(toplot, names = toplot.names, horiz=TRUE, las =1, col = rainbow(nrow(freq)))
1370 """ % ffr(self.pathout['barplotrow.png'])
1374 class LabbeScript(PrintRScript) :
1375 def make_script(self) :
1376 self.sources([self.analyse.parent.RscriptsPath['distance-labbe.R'],
1377 self.analyse.parent.RscriptsPath['Rgraph']])
1379 tab <- read.csv2("%s", header=TRUE, sep=';', row.names=1)
1380 """ % (ffr(self.pathout['tableafcm.csv']))
1382 dist.mat <- dist.labbe(tab)
1383 dist.mat <- as.dist(dist.mat, upper=F, diag=F)
1384 write.table(as.matrix(dist.mat), "%s", sep='\t')
1387 chd <- hclust(dist.mat, method="ward.D2")
1388 open_file_graph("%s", width=1000, height=1000, svg=F)
1390 plot.phylo(as.phylo(chd), type='unrooted', lab4ut="axial")
1392 """ % (ffr(self.pathout['distmat.csv']), ffr(self.pathout['labbe-tree.png']))
1394 open_file_graph("%s", width=1000, height=1000, svg=F)
1395 par(mar=c(10,1,1,10))
1396 heatmap(as.matrix(dist.mat), symm = T, distfun=function(x) as.dist(x), margins=c(10,10))
1398 """ % ffr(self.pathout['labbe-heatmap.png'])
1400 #http://stackoverflow.com/questions/3081066/what-techniques-exists-in-r-to-visualize-a-distance-matrix
1401 dst <- data.matrix(dist.mat)
1403 rn <- row.names(as.matrix(dist.mat))
1404 open_file_graph("%s", width=1500, height=1000, svg=F)
1405 par(mar=c(10,10,3,3))
1406 image(1:dim, 1:dim, dst, axes = FALSE, xlab="", ylab="", col=heat.colors(99), breaks=seq(0.01,1,0.01))
1407 axis(1, 1:dim, rn, cex.axis = 0.9, las=3)
1408 axis(2, 1:dim, rn, cex.axis = 0.9, las=1)
1409 text(expand.grid(1:dim, 1:dim), sprintf("%%0.2f", dst), cex=0.6)
1411 """ % ffr(self.pathout['labbe-matrix.png'])
1414 g <- graph.adjacency(as.matrix(1-dist.mat), mode="lower", weighted=T)
1415 write.graph(g, file="%s", format='graphml')
1416 open_file_graph("%s", width=1000, height=1000, svg=F)
1419 E(g)$weight <- 1 - E(g)$weight
1420 g <- minimum.spanning.tree(g)
1421 E(g)$weight <- 1 - E(g)$weight
1422 write.graph(g, file="%s", format='graphml')
1423 open_file_graph("%s", width=1000, height=1000, svg=F)
1426 """ % (ffr(self.pathout['graph_tot.graphml']), ffr(self.pathout['graph_tot.png']), ffr(self.pathout['graph_min.graphml']), ffr(self.pathout['graph_min.png']))
1430 class ChronoChi2Script(PrintRScript) :
1431 def make_script(self) :
1432 self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1433 print self.parametres
1439 """ % (ffr(self.pathout['RData.RData']), ffr(self.pathout['dendrogramme.RData']))
1442 """ % self.parametres['svg']
1444 tc <- which(grepl("%s",rownames(chistabletot)))
1445 rn <- rownames(chistabletot)[tc]
1447 dpt <- chistabletot[tc,]
1448 tot <- afctable[tc,]
1453 """ % self.parametres['var'].replace(u'*', u"\\\\*")
1455 classes <- n1[,ncol(n1)]
1456 tcl <- table(classes)
1457 if ('0' %in% names(tcl)) {
1458 to.vire <- which(names(tcl) == '0')
1459 tcl <- tcl[-to.vire]
1461 tclp <- tcl/sum(tcl)
1469 lcol <- c(lcol, qchisq(1-k,1))
1473 lcol <- c(3.84, lcol)
1474 lcol <- c(-Inf,lcol)
1475 lcol <- c(lcol, Inf)
1478 alphas <- seq(0,1, length.out=length(breaks))
1479 clod <- rev(as.numeric(tree.cut1$tree.cl$tip.label))
1483 open_file_graph("%s", w=%i, h=%i, svg=svg)
1484 """ % (ffr(self.parametres['tmpgraph']), self.parametres['width'], self.parametres['height'])
1487 mat.graphic <- matrix(c(rep(1,nrow(dd)),c(2:(nrow(dd)+1))), ncol=2)
1488 mat.graphic <- rbind(mat.graphic, c(max(mat.graphic) + 1 , max(mat.graphic) + 2))
1489 hauteur <- tclp[clod] * 0.9
1490 heights.graphic <- append(hauteur, 0.1)
1491 layout(mat.graphic, heights=heights.graphic, widths=c(0.15,0.85))
1493 tree.toplot <- tree.cut1$tree.cl
1494 num.label <- as.numeric(tree.cut1$tree.cl$tip.label)
1495 col.tree <- rainbow(length(num.label))[num.label]
1496 #tree.toplot$tip.label <- paste('classe ', tree.toplot$tip.label)
1497 plot.phylo(tree.toplot,label.offset=0.1, cex=1.1, no.margin=T, tip.color = col.tree)
1501 lcol <- cut(dd[i,], breaks, include.lowest=TRUE)
1502 ulcol <- names(table(lcol))
1503 lcol <- as.character(lcol)
1504 for (j in 1:length(ulcol)) {
1505 lcol[which(lcol==ulcol[j])] <- j
1507 lcol <- as.numeric(lcol)
1508 mcol <- rainbow(nrow(dd))[i]
1511 last.col <- c(last.col, rgb(r=col2rgb(mcol)[1]/255, g=col2rgb(mcol)[2]/255, b=col2rgb(mcol)[3]/255, a=k))
1515 barplot(rep(1,ncol(dd)), width=ptc, names.arg=FALSE, axes=FALSE, col=last.col[lcol], border=rgb(r=0, g=0, b=0, a=0.3))
1517 plot(0,type='n',axes=FALSE,ann=FALSE)
1518 label.coords <- barplot(rep(1, ncol(dd)), width=ptc, names.arg = F, las=2, axes=F, ylim=c(0,1), plot=T, col='white')
1519 text(x=label.coords, y=0.5, labels=rn[order(rn)], srt=90)
1525 class ChronoPropScript(PrintRScript) :
1526 def make_script(self) :
1527 self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1528 print self.parametres
1534 """ % (ffr(self.pathout['RData.RData']), ffr(self.pathout['dendrogramme.RData']))
1537 """ % self.parametres['svg']
1539 tc <- which(grepl("%s",rownames(chistabletot)))
1540 rn <- rownames(chistabletot)[tc]
1542 dpt <- chistabletot[tc,]
1543 tot <- afctable[tc,]
1548 """ % self.parametres['var'].replace(u'*', u"\\\\*")
1550 classes <- n1[,ncol(n1)]
1551 tcl <- table(classes)
1552 if ('0' %in% names(tcl)) {
1553 to.vire <- which(names(tcl) == '0')
1554 tcl <- tcl[-to.vire]
1556 tclp <- tcl/sum(tcl)
1559 open_file_graph("%s", w=%i, h=%i, svg=svg)
1560 """ % (ffr(self.parametres['tmpgraph']), self.parametres['width'], self.parametres['height'])
1562 ptt <- prop.table(as.matrix(tot), 1)
1563 par(mar=c(10,2,2,2))
1564 barplot(t(ptt)[as.numeric(tree.cut1$tree.cl$tip.label),], col=rainbow(ncol(ptt))[as.numeric(tree.cut1$tree.cl$tip.label)], width=ptc, las=3, space=0.05, cex.axis=0.7, border=NA)
1570 class ChronoggScript(PrintRScript) :
1571 def make_script(self) :
1572 self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1573 print self.parametres
1580 """ % (ffr(self.pathout['RData.RData']), ffr(self.pathout['dendrogramme.RData']))
1583 """ % self.parametres['svg']
1585 tc <- which(grepl("%s",rownames(chistabletot)))
1586 rn <- rownames(chistabletot)[tc]
1588 dpt <- chistabletot[tc,]
1589 tot <- afctable[tc,]
1594 """ % self.parametres['var'].replace(u'*', u"\\\\*")
1596 classes <- n1[,ncol(n1)]
1597 tcl <- table(classes)
1598 if ('0' %in% names(tcl)) {
1599 to.vire <- which(names(tcl) == '0')
1600 tcl <- tcl[-to.vire]
1602 tclp <- tcl/sum(tcl)
1603 ptt <- prop.table(as.matrix(tot), 1)
1604 ptt <- ptt[,as.numeric(tree.cut1$tree.cl$tip.label)]
1605 rownames(ptt) <- cumsum(ptc)
1606 nptt<-as.data.frame(as.table(ptt))
1607 nptt[,1]<-as.numeric(as.character(nptt[,1]))
1608 col <- rainbow(ncol(ptt))[as.numeric(tree.cut1$tree.cl$tip.label)]
1611 open_file_graph("%s", w=%i, h=%i, svg=svg)
1612 """ % (ffr(self.parametres['tmpgraph']), self.parametres['width'], self.parametres['height'])
1614 par(mar=c(10,2,2,2))
1615 gg <- ggplot(data=nptt, aes(x=Var1,y=Freq,fill=Var2)) + geom_area(alpha=1 , size=0.5, colour="black")
1616 gg + scale_fill_manual(values=col)
1622 class DendroScript(PrintRScript) :
1623 def make_script(self) :
1624 if self.parametres['svg'] :
1628 fileout = self.parametres['fileout']
1629 width = self.parametres['width']
1630 height = self.parametres['height']
1631 type_dendro = self.parametres['dendro_type']
1632 if self.parametres['taille_classe'] :
1636 if self.parametres['color_nb'] == 0 :
1640 if self.parametres['type_tclasse'] == 0 :
1644 if self.parametres['svg'] :
1648 dendro_path = self.pathout['Rdendro']
1649 classe_path = self.pathout['uce']
1654 classes <- read.csv2("%s", row.names=1)
1655 classes <- classes[,1]
1656 """ % (ffr(dendro_path), ffr(self.parametres['Rgraph']), ffr(classe_path))
1657 if self.parametres['dendro'] == 'simple' :
1659 open_file_graph("%s", width=%i, height=%i, svg=%s)
1660 plot.dendropr(tree.cut1$tree.cl, classes, type.dendro="%s", histo=%s, bw=%s, lab=NULL, tclasse=%s)
1661 """ % (ffr(fileout), width, height, svg, type_dendro, histo, bw, tclasse)
1662 elif self.parametres['dendro'] == 'texte' :
1666 if (is.null(debsup)) {
1669 chistable <- chistabletot[1:(debsup-1),]
1670 """ % (ffr(self.pathout['RData.RData']), ffr(self.parametres['Rgraph']))
1671 if self.parametres.get('translation', False) :
1673 rn <- read.csv2("%s", header=FALSE, sep='\t')
1674 rnchis <- row.names(chistable)
1675 commun <- intersect(rnchis, unique(rn[,2]))
1676 idrnchis <- sapply(commun, function(x) {which(rnchis==x)})
1677 idrn <- sapply(commun, function(x) {which(as.vector(rn[,2])==x)[1]})
1678 rownames(chistable)[idrnchis] <- as.vector(rn[idrn,1])
1679 """ % ffr(self.parametres['translation'])
1681 open_file_graph("%s", width=%i, height=%i, svg = %s)
1682 plot.dendro.prof(tree.cut1$tree.cl, classes, chistable, nbbycl = 60, type.dendro="%s", bw=%s, lab=NULL)
1683 """ % (ffr(fileout), width, height, svg, type_dendro, bw)
1684 elif self.parametres['dendro'] == 'cloud' :
1688 if (is.null(debsup)) {
1691 chistable <- chistabletot[1:(debsup-1),]
1692 open_file_graph("%s", width=%i, height=%i, svg=%s)
1693 plot.dendro.cloud(tree.cut1$tree.cl, classes, chistable, nbbycl = 300, type.dendro="%s", bw=%s, lab=NULL)
1694 """ % (ffr(self.pathout['RData.RData']), ffr(self.parametres['Rgraph']), ffr(fileout), width, height, svg, type_dendro, bw)
1699 class ReDoProfScript(PrintRScript) :
1700 def make_script(self) :
1701 self.sources([self.analyse.parent.RscriptsPath['chdfunct.R']])
1702 print self.parametres