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):
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')
172 #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)
173 chd1<-CHD(data1, x = nbt, mode.patate = mode.patate, svd.method = svd.method, libsvdc.path = libsvdc.path)#, log.file = log1)
174 """ % ffr(DicoPath['log-chd1.txt'])
176 if classif_mode == 0:
179 chd2<-CHD(data2, x = nbt, mode.patate = mode.patate, svd.method =
180 svd.method, libsvdc.path = libsvdc.path)#, log.file = log2)
181 """ % ffr(DicoPath['log-chd2.txt'])
185 listuce1<-read.csv2("%s")
186 """ % ffr(DicoPath['listeuce1'])
188 if classif_mode == 0:
190 listuce2<-read.csv2("%s")
191 """ % ffr(DicoPath['listeuce2'])
197 if classif_mode == 0:
204 if (mincl == 0) {mincl <- round(nrow(chd1$n1)/(nbt+1))}
206 write.csv2(chd1$n1, file="%s")
207 if (classif_mode == 0) {
208 chd.result <- Rchdtxt(uceout, chd1, chd2 = chd2, mincl = mincl,classif_mode = classif_mode, nbt = nbt)
209 classeuce1 <- chd.result$cuce1
210 tree.tot1 <- make_tree_tot(chd1)
211 tree.cut1 <- make_dendro_cut_tuple(tree.tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
214 #chd.result <- Rchdtxt(uceout, chd1, chd2 = chd1, mincl = mincl,classif_mode = classif_mode, nbt = nbt)
215 tree.tot1 <- make_tree_tot(chd1)
216 terminales <- find.terminales(chd1$n1, chd1$list_mere, chd1$list_fille, mincl)
217 tree.cut1 <- make.classes(terminales, chd1$n1, tree.tot1$tree.cl, chd1$list_fille)
218 write.csv2(tree.cut1$n1, uceout)
219 chd.result <- tree.cut1
221 classes<-chd.result$n1[,ncol(chd.result$n1)]
222 write.csv2(chd.result$n1, file="%s")
223 """ % (classif_mode, mincl, ffr(DicoPath['uce']), ffr(DicoPath['n1-1.csv']), ffr(DicoPath['n1.csv']))
226 # tree.tot1 <- make_tree_tot(chd1)
227 # open_file_graph("%s", widt = 600, height=400)
228 # plot(tree.tot1$tree.cl)
230 """ % ffr(DicoPath['arbre1'])
232 if classif_mode == 0:
234 classeuce2 <- chd.result$cuce2
235 tree.tot2 <- make_tree_tot(chd2)
236 # open_file_graph("%s", width = 600, height=400)
237 # plot(tree.tot2$tree.cl)
239 """ % ffr(DicoPath['arbre2'] )
242 save(tree.cut1, file="%s")
244 open_file_graph("%s", width = 600, height=400)
245 plot.dendropr(tree.cut1$tree.cl,classes, histo=TRUE)
246 open_file_graph("%s", width = 600, height=400)
247 plot(tree.cut1$dendro_tot_cl)
249 """ % (ffr(DicoPath['Rdendro']), ffr(DicoPath['dendro1']), ffr(DicoPath['arbre1']))
251 if classif_mode == 0:
253 tree.cut2 <- make_dendro_cut_tuple(tree.tot2$dendro_tuple, chd.result$coord_ok, classeuce2, 2, nbt)
254 open_file_graph("%s", width = 600, height=400)
255 plot(tree.cut2$tree.cl)
257 open_file_graph("%s", width = 600, height=400)
258 plot(tree.cut2$dendro_tot_cl)
260 """ % (ffr(DicoPath['dendro2']), ffr(DicoPath['arbre2']))
264 #save.image(file="%s")
265 """ % (ffr(DicoPath['RData']))
267 fileout = open(DicoPath['Rchdtxt'], 'w')
271 def RPamTxt(corpus, RscriptPath):
272 DicoPath = corpus.pathout
273 param = corpus.parametres
276 """ % (RscriptPath['pamtxt'])
279 """ % (RscriptPath['Rgraph'])
281 result <- pamtxt("%s", "%s", "%s", method = "%s", clust_type = "%s", clnb = %i)
283 """ % (DicoPath['TableUc1'], DicoPath['listeuce1'], DicoPath['uce'], param['method'], param['cluster_type'], param['nbcl'] )
285 open_file_graph("%s", width=400, height=400)
288 """ % (DicoPath['arbre1'])
290 save.image(file="%s")
291 """ % DicoPath['RData']
292 fileout = open(DicoPath['Rchdtxt'], 'w')
297 def RchdQuest(DicoPath, RscriptPath, nbcl = 10, mincl = 10):
303 """ % (ffr(RscriptPath['CHD']), ffr(RscriptPath['chdquest']), ffr(RscriptPath['anacor']),ffr(RscriptPath['Rgraph']))
311 chd.result<-Rchdquest("%s","%s","%s", nbt = nbt, mincl = mincl)
313 classeuce1 <- chd.result$cuce1
314 """ % (ffr(DicoPath['mat01.csv']), ffr(DicoPath['listeuce1']), ffr(DicoPath['uce']))
317 tree_tot1 <- make_tree_tot(chd.result$chd)
318 open_file_graph("%s", width = 600, height=400)
319 plot(tree_tot1$tree.cl)
321 """ % ffr(DicoPath['arbre1'])
324 tree_cut1 <- make_dendro_cut_tuple(tree_tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
325 tree.cut1 <- tree_cut1
326 save(tree.cut1, file="%s")
327 open_file_graph("%s", width = 600, height=400)
328 classes<-n1[,ncol(n1)]
329 plot.dendropr(tree_cut1$tree.cl,classes, histo = TRUE)
330 """ % (ffr(DicoPath['Rdendro']), ffr(DicoPath['dendro1']))
333 save.image(file="%s")
334 """ % ffr(DicoPath['RData'])
335 fileout = open(DicoPath['Rchdquest'], 'w')
339 def ReinertTxtProf(DictChdTxtOut, RscriptsPath, clnb, taillecar):
340 txt = "clnb<-%i\n" % clnb
344 n1 <- read.csv2("%s")
345 """ % (ffr(RscriptsPath['chdfunct']), ffr(DictChdTxtOut['RData']), ffr(DictChdTxtOut['n1.csv']))
347 dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
348 datasup<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
349 dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
350 """ % (ffr(DictChdTxtOut['Contout']), ffr(DictChdTxtOut['ContSupOut']), ffr(DictChdTxtOut['ContEtOut']))
352 print('ATTENTION NEW BUILD PROF')
353 #tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
354 #tablesqrpsup<-BuildProf(as.matrix(datasup),n1,clnb)
355 #tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
356 tablesqrpact<-new.build.prof(as.matrix(dataact),n1,clnb)
357 tablesqrpsup<-new.build.prof(as.matrix(datasup),n1,clnb)
358 tablesqrpet<-new.build.prof(as.matrix(dataet),n1,clnb)
362 PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s",tablesqrpsup[4],tablesqrpsup[5])
363 """ % (ffr(DictChdTxtOut['PROFILE_OUT']), ffr(DictChdTxtOut['ANTIPRO_OUT']))
365 colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
366 colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
367 colnames(tablesqrpsup[[2]])<-paste('classe',1:clnb,sep=' ')
368 colnames(tablesqrpsup[[1]])<-paste('classe',1:clnb,sep=' ')
369 colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
370 colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
371 chistabletot<-rbind(tablesqrpact[2][[1]],tablesqrpsup[2][[1]])
372 chistabletot<-rbind(chistabletot,tablesqrpet[2][[1]])
373 ptabletot<-rbind(tablesqrpact[1][[1]],tablesqrpet[1][[1]])
376 write.csv2(chistabletot,file="%s")
377 write.csv2(ptabletot,file="%s")
379 write.csv2(gbcluster,file="%s")
380 """ % (ffr(DictChdTxtOut['chisqtable']), ffr(DictChdTxtOut['ptable']), ffr(DictChdTxtOut['SbyClasseOut']))
384 colnames(dataact)<-paste('classe',1:clnb,sep=' ')
385 colnames(datasup)<-paste('classe',1:clnb,sep=' ')
386 colnames(dataet)<-paste('classe',1:clnb,sep=' ')
387 rowtot<-nrow(dataact)+nrow(dataet)+nrow(datasup)
388 afctable<-rbind(as.matrix(dataact),as.matrix(datasup))
389 afctable<-rbind(afctable,as.matrix(dataet))
390 colnames(afctable)<-paste('classe',1:clnb,sep=' ')
391 afc<-ca(afctable,suprow=((nrow(dataact)+1):rowtot),nd=(ncol(afctable)-1))
392 debsup<-nrow(dataact)+1
393 debet<-nrow(dataact)+nrow(datasup)+1
395 afc<-AddCorrelationOk(afc)
397 #FIXME : split this!!!
400 """ % ffr(RscriptsPath['Rgraph'])
403 afc <- summary.ca.dm(afc)
404 afc_table <- create_afc_table(afc)
405 write.csv2(afc_table$facteur, file = "%s")
406 write.csv2(afc_table$colonne, file = "%s")
407 write.csv2(afc_table$ligne, file = "%s")
408 """ % (ffr(DictChdTxtOut['afc_facteur']), ffr(DictChdTxtOut['afc_col']), ffr(DictChdTxtOut['afc_row']))
414 xyminmax <- PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
415 """ % (ffr(DictChdTxtOut['AFC2DL_OUT']))
417 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)
418 """ % (ffr(DictChdTxtOut['AFC2DSL_OUT']))
420 if ((fin - debet) > 2) {
421 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)
423 """ % (ffr(DictChdTxtOut['AFC2DEL_OUT']))
425 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)
426 """ % (ffr(DictChdTxtOut['AFC2DCL_OUT']))
428 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
429 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debsup, fin=(debet-1), xlab = xlab, ylab = ylab)
430 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debet, fin=fin, xlab = xlab, ylab = ylab)
431 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col=TRUE, what='crl', xlab = xlab, ylab = ylab)
432 # """ % (DictChdTxtOut['AFC2DCoul'], DictChdTxtOut['AFC2DCoulSup'], DictChdTxtOut['AFC2DCoulEt'], DictChdTxtOut['AFC2DCoulCl'])
441 save.image(file="%s")
442 """ % ffr(DictChdTxtOut['RData'])
443 file = open(DictChdTxtOut['RTxtProfGraph'], 'w')
448 def write_afc_graph(self):
449 if self.param['over'] : over = 'TRUE'
450 else : over = 'FALSE'
452 if self.param['do_select_nb'] : do_select_nb = 'TRUE'
453 else : do_select_nb = 'FALSE'
455 if self.param['do_select_chi'] : do_select_chi = 'TRUE'
456 else : do_select_chi = 'FALSE'
458 if self.param['do_select_chi_classe'] : do_select_chi_classe = 'TRUE'
459 else : do_select_chi_classe = 'FALSE'
461 if self.param['cex_txt'] : cex_txt = 'TRUE'
462 else : cex_txt = 'FALSE'
464 if self.param['tchi'] : tchi = 'TRUE'
465 else : tchi = 'FALSE'
467 if self.param['svg'] : svg = 'TRUE'
470 if self.param['typegraph'] == 4 :
471 nodesfile = os.path.join(os.path.dirname(self.fileout),'nodes.csv')
472 edgesfile = os.path.join(os.path.dirname(self.fileout),'edges.csv')
477 with open(self.RscriptsPath['afc_graph'], 'r') as f:
480 # self.DictPathOut['RData'], \
481 scripts = txt % (ffr(self.RscriptsPath['Rgraph']),\
482 self.param['typegraph'], \
483 edgesfile, nodesfile, \
484 self.param['what'], \
485 self.param['facteur'][0],\
486 self.param['facteur'][1], \
487 self.param['facteur'][2], \
489 over, do_select_nb, \
490 self.param['select_nb'], \
492 self.param['select_chi'], \
493 do_select_chi_classe, \
494 self.param['nbchic'], \
496 self.param['txt_min'], \
497 self.param['txt_max'], \
499 self.param['width'], \
500 self.param['height'],\
501 self.param['taillecar'], \
502 self.param['alpha'], \
503 self.param['film'], \
505 self.param['tchi_min'],\
506 self.param['tchi_max'],\
507 ffr(os.path.dirname(self.fileout)),\
511 def print_simi3d(self):
512 simi3d = self.parent.simi3dpanel
513 txt = '#Fichier genere par Iramuteq'
514 if simi3d.movie.GetValue() :
515 movie = "'" + ffr(os.path.dirname(self.DictPathOut['RData'])) + "'"
519 #if self.corpus.parametres['type'] == 'corpus' :
525 dm<-read.csv2("%s",row.names=1,header = %s)
527 """ % (self.DictPathOut['Contout'], header, self.DictPathOut['RData'])
531 """ % self.parent.RscriptsPath['Rgraph']
535 make.simi.afc(dm,chistabletot, lim=%i, alpha = %.2f, movie = %s)
536 """ % (simi3d.spin_1.GetValue(), float(simi3d.slider_1.GetValue())/100, movie)
537 tmpfile = tempfile.mktemp(dir=self.parent.TEMPDIR)
538 tmp = open(tmpfile,'w')
543 def dendroandbarplot(table, rownames, colnames, rgraph, tmpgraph, intxt = False, dendro=False) :
545 txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
546 rownb = len(rownames)
547 rownames = 'c("' + '","'.join(rownames) + '")'
548 colnames = 'c("' + '","'.join(colnames) + '")'
552 di <- matrix(data=%s, nrow=%i, byrow = TRUE)
555 """ % (txttable, rownb, rownames, colnames)
562 height <- (30*ncol(di)) + (15*nrow(di))
563 height <- ifelse(height <= 400, 400, height)
565 open_file_graph("%s", width=width, height=height)
566 plot.dendro.lex(tree.cut1$tree.cl, di)
567 """ % (ffr(dendro),ffr(rgraph), ffr(tmpgraph))
570 def barplot(table, parametres, intxt = False) :
572 txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
573 #width = 100 + (15 * len(rownames)) + (100 * len(colnames))
574 #height = len(rownames) * 15
575 rownb = len(parametres['rownames'])
578 rownames = 'c("' + '","'.join(parametres['rownames']) + '")'
579 colnames = 'c("' + '","'.join(parametres['colnames']) + '")'
584 di <- matrix(data=%s, nrow=%i, byrow = TRUE)
585 toinf <- which(di == Inf)
586 tominf <- which(di == -Inf)
589 valmax <- max(di, na.rm = TRUE)
597 if (length(tominf)) {
599 valmin <- min(di, na.rm = TRUE)
609 """ % (txttable, rownb, rownames, colnames)
612 if not 'tree' in parametres :
615 color = rainbow(nrow(di))
618 open_file_graph("%s",width = width, height = height, svg = %s)
620 layout(matrix(c(1,2),1,2, byrow=TRUE),widths=c(3,lcm(12)))
622 yp = ifelse(length(toinf), 0.2, 0)
623 ym = ifelse(length(tominf), 0.2, 0)
624 ymin <- ifelse(!length(which(di < 0)), 0, min(di) - ym)
625 coord <- barplot(as.matrix(di), beside = TRUE, col = color, space = c(0.1,0.6), ylim=c(ymin, max(di) + yp), las = 2)
627 coordinf <- coord[toinf]
629 text(x=coordinf, y=valinf + 0.1, 'i')
631 if (length(tominf)) {
632 coordinf <- coord[toinf]
634 text(x=coordinf, y=valinf - 0.1, 'i')
640 lcoord <- apply(cc, 1, mean)
643 amp <- abs(max(di) - min(di))
650 d <- signif(amp%%/%%10,1)
655 if ((i/d) == (i%%/%%d)) {
660 plot(0, axes = FALSE, pch = '')
661 legend(x = 'center' , rownames(di), fill = color)
663 """ % (ffr(parametres['rgraph']), parametres['width'], parametres['height'], ffr(parametres['tmpgraph']), parametres['svg'])
671 open_file_graph("%s", width=width, height=height, svg = %s)
672 plot.dendro.lex(tree.cut1$tree.cl, di)
673 """ % (ffr(parametres['tree']), ffr(parametres['rgraph']), parametres['width'], parametres['height'], ffr(parametres['tmpgraph']), parametres['svg'])
676 #def RAfcUci(DictAfcUciOut, nd=2, RscriptsPath='', PARCEX='0.8'):
682 # dataact<-read.csv2("%s")
683 # """ % (DictAfcUciOut['TableCont'])#, encoding)
685 # datasup<-read.csv2("%s")
686 # """ % (DictAfcUciOut['TableSup'])#, encoding)
688 # dataet<-read.csv2("%s")
689 # """ % (DictAfcUciOut['TableEt'])#, encoding)
691 # datatotsup<-cbind(dataact,datasup)
692 # datatotet<-cbind(dataact,dataet)
693 # afcact<-ca(dataact,nd=nd)
694 # afcsup<-ca(datatotsup,supcol=((ncol(dataact)+1):ncol(datatotsup)),nd=nd)
695 # afcet<-ca(datatotet,supcol=((ncol(dataact)+1):ncol(datatotet)),nd=nd)
696 # afctot<-afcsup$colcoord
697 # rownames(afctot)<-afcsup$colnames
698 # colnames(afctot)<-paste('coord. facteur',1:nd,sep=' ')
699 # afctot<-cbind(afctot,mass=afcsup$colmass)
700 # afctot<-cbind(afctot,distance=afcsup$coldist)
701 # afctot<-cbind(afctot,intertie=afcsup$colinertia)
702 # rcolet<-afcet$colsup
703 # afctmp<-afcet$colcoord[rcolet,]
704 # rownames(afctmp)<-afcet$colnames[rcolet]
705 # afctmp<-cbind(afctmp,afcet$colmass[rcolet])
706 # afctmp<-cbind(afctmp,afcet$coldist[rcolet])
707 # afctmp<-cbind(afctmp,afcet$colinertia[rcolet])
708 # afctot<-rbind(afctot,afctmp)
709 # write.csv2(afctot,file = "%s")
711 # """ % (DictAfcUciOut['afc_row'], RscriptsPath['Rgraph'])
717 # PlotAfc(afcet,filename="%s",toplot=c%s, PARCEX=PARCEX)
718 # """ % (DictAfcUciOut['AfcColAct'], "('none','active')")
720 # PlotAfc(afcsup,filename="%s",toplot=c%s, PARCEX=PARCEX)
721 # """ % (DictAfcUciOut['AfcColSup'], "('none','passive')")
722 # txt += """PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
723 # """ % (DictAfcUciOut['AfcColEt'], "('none','passive')")
725 # PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
726 # """ % (DictAfcUciOut['AfcRow'], "('all','none')")
727 # f = open(DictAfcUciOut['Rafcuci'], 'w')
731 class PrintSimiScript(PrintRScript) :
732 def make_script(self) :
734 self.packages(['igraph', 'proxy', 'Matrix'])
735 self.sources([self.analyse.parent.RscriptsPath['simi'], self.analyse.parent.RscriptsPath['Rgraph']])
737 if not self.parametres['keep_coord'] and not (self.parametres['type'] == 'simimatrix' or self.parametres['type'] == 'simiclustermatrix') :
742 """ % (ffr(self.pathout['mat01.csv']), ffr(self.pathout['actives.csv']), ffr(self.pathout['selected.csv']))
743 if 'word' in self.parametres :
747 """ % self.parametres['word']
755 cn <- read.table(cn.path, sep="\t", quote='"')
756 colnames(dm) <- cn[,1]
757 if (file.exists(selected.col)) {
758 sel.col <- read.csv2(selected.col, header = FALSE)
759 sel.col <- sel.col[,1] + 1
761 sel.col <- 1:ncol(dm)
766 forme <- colnames(dm)[index]
767 if (!index %in% sel.col) {
768 sel.col <- append(sel.col, index)
771 index <- which(colnames(dm) == forme)
774 elif not self.parametres['keep_coord'] and (self.parametres['type'] == 'simimatrix' or self.parametres['type'] == 'simiclustermatrix'):
778 """ % (ffr(self.pathout['mat01.csv']), ffr(self.pathout['selected.csv']))
779 if 'word' in self.parametres :
783 """ % self.parametres['word']
789 dm <-read.csv2(dm.path)
791 if (file.exists(selected.col)) {
792 sel.col <- read.csv2(selected.col, header = FALSE)
793 sel.col <- sel.col[,1] + 1
795 sel.col <- 1:ncol(dm)
800 forme <- colnames(dm)[index]
801 if (!index %in% sel.col) {
802 sel.col <- append(sel.col, index)
805 index <- which(colnames(dm) == forme)
811 """ % ffr(self.pathout['RData.RData'])
813 if self.parametres['coeff'] == 0 :
815 if not self.parametres['keep_coord'] :
820 elif self.analyse.indices[self.parametres['coeff']] == 'Jaccard' :
822 if not self.parametres['keep_coord'] :
825 mat <- sparse.jaccard(dm)
828 if not self.parametres['keep_coord'] :
832 if self.parametres['coeff'] == 1 :
836 mat <- simil(dm, method = 'Russel', diag = TRUE, upper = TRUE, by_rows = FALSE)
838 elif self.analyse.indices[self.parametres['coeff']] == 'binomial' :
840 if not self.parametres['keep_coord'] :
845 elif self.parametres['coeff'] != 0 and self.analyse.indices[self.parametres['coeff']] != 'Jaccard':
846 method = self.analyse.indices[self.parametres['coeff']]
847 if not self.parametres['keep_coord'] :
850 mat <- simil(dm, method = method, diag = TRUE, upper = TRUE, by_rows = FALSE)
851 """ % self.analyse.indices[self.parametres['coeff']]
852 if not self.parametres['keep_coord'] :
854 mat <- as.matrix(stats::as.dist(mat,diag=TRUE,upper=TRUE))
856 if (length(which(mat == Inf))) {
857 infp <- which(mat == Inf)
859 maxmat <- max(mat, na.rm = TRUE)
867 if (length(which(mat == -Inf))) {
868 infm <- which(mat == -Inf)
870 minmat <- min(mat, na.rm = TRUE)
879 if 'word' in self.parametres and not self.parametres['keep_coord'] :
881 mat <- graph.word(mat, index)
883 if (length(which(cs==0))) mat <- mat[,-which(cs==0)]
885 if (length(which(rs==0))) mat <- mat[-which(rs==0),]
886 if (length(which(cs==0))) dm <- dm[,-which(cs==0)]
888 index <- which(colnames(mat)==forme)
892 if self.parametres['layout'] == 0 : layout = 'random'
893 if self.parametres['layout'] == 1 : layout = 'circle'
894 if self.parametres['layout'] == 2 : layout = 'frutch'
895 if self.parametres['layout'] == 3 : layout = 'kawa'
896 if self.parametres['layout'] == 4 : layout = 'graphopt'
897 if self.parametres['layout'] == 5 : layout = 'spirale'
898 if self.parametres['layout'] == 6 : layout = 'spirale3D'
902 if self.parametres['type_graph'] == 0 : type = 'tkplot'
903 if self.parametres['type_graph'] == 1 :
906 dirout = os.path.dirname(self.pathout['mat01.csv'])
907 while os.path.exists(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png')):
909 self.filename = ffr(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png'))
910 if self.parametres['type_graph'] == 2 : type = 'rgl'
911 if self.parametres['type_graph'] == 3 :
914 dirout = os.path.dirname(self.pathout['mat01.csv'])
915 while os.path.exists(os.path.join(dirout,'web_'+str(graphnb))):
917 self.filename = ffr(os.path.join(dirout,'web_'+str(graphnb)))
918 os.mkdir(self.filename)
919 self.filename = os.path.join(self.filename, 'gexf.gexf')
920 if self.parametres['type_graph'] == 4 :
923 dirout = os.path.dirname(self.pathout['mat01.csv'])
924 while os.path.exists(os.path.join(dirout,'webrgl_'+str(graphnb))):
926 self.filename = ffr(os.path.join(dirout,'webrgl_'+str(graphnb)))
927 os.mkdir(self.filename)
929 if self.parametres['arbremax'] :
931 self.txtgraph += ' - arbre maximum'
932 else : arbremax = 'FALSE'
934 if self.parametres['coeff_tv'] :
935 coeff_tv = self.parametres['coeff_tv_nb']
936 tvminmax = 'c(NULL,NULL)'
937 elif not self.parametres['coeff_tv'] or self.parametres.get('sformchi', False) :
939 tvminmax = 'c(%i, %i)' %(self.parametres['tvmin'], self.parametres['tvmax'])
940 if self.parametres['coeff_te'] : coeff_te = 'c(%i,%i)' % (self.parametres['coeff_temin'], self.parametres['coeff_temax'])
941 else : coeff_te = 'NULL'
943 if self.parametres['vcex'] or self.parametres.get('cexfromchi', False) :
944 vcexminmax = 'c(%i/10,%i/10)' % (self.parametres['vcexmin'],self.parametres['vcexmax'])
946 vcexminmax = 'c(NULL,NULL)'
947 if not self.parametres['label_v'] : label_v = 'FALSE'
948 else : label_v = 'TRUE'
950 if not self.parametres['label_e'] : label_e = 'FALSE'
951 else : label_e = 'TRUE'
953 if self.parametres['seuil_ok'] : seuil = str(self.parametres['seuil'])
954 else : seuil = 'NULL'
956 if not self.parametres.get('edgecurved', False) :
965 cols = str(self.parametres['cols']).replace(')',', max=255)')
966 cola = str(self.parametres['cola']).replace(')',',max=255)')
976 """ % self.parametres['cex']
978 if self.parametres['film'] :
981 """ % ffr(self.pathout['film'])
988 if (!is.null(seuil)) {
989 if (method!='cooc') {
998 """ % (label_v, label_e)
1006 """ % (self.parametres['width'], self.parametres['height'])
1007 if self.parametres['keep_coord'] :
1009 coords <- try(coords, TRUE)
1010 if (!is.matrix(coords)) {
1020 """ % self.parametres['alpha']
1023 """ % self.parametres['alpha']
1024 #############################################
1025 if self.parametres.get('bystar',False) :
1029 for i, line in enumerate(self.parametres['listet']) :
1032 """ % (i+1, ','.join([`val + 1` for val in line]))
1035 """ % ("','".join([val for val in self.parametres['selectedstars']]))
1039 for (i in 1:length(unetoile)) {
1042 if (length(tosum) > 1) {
1043 fsum <- cbind(fsum, colSums(dm[tosum,]))
1045 fsum <- cbind(fsum, dm[tosum,])
1049 lex <- AsLexico2(fsum, chip=TRUE)
1050 dcol <- apply(lex[[4]],1,which.max)
1051 toblack <- apply(lex[[4]],1,max)
1052 gcol <- rainbow(length(unetoile))
1053 #gcol[2] <- 'orange'
1054 vertex.label.color <- gcol[dcol]
1055 vertex.label.color[which(toblack <= 3.84)] <- 'black'
1056 leg <- list(unetoile=unetoile, gcol=gcol)
1057 cols <- vertex.label.color
1058 chivertex.size <- norm.vec(toblack, vcexminmax[1], vcexminmax[2])
1060 """ % (ffr(self.analyse.parent.RscriptsPath['chdfunct']))
1063 vertex.label.color <- 'black'
1067 #############################################
1070 # eff <- colSums(dm)
1071 # g.ori <- graph.adjacency(mat, mode='lower', weighted = TRUE)
1072 # w.ori <- E(g.ori)$weight
1074 # if (method == 'cooc') {
1075 # E(g.ori)$weight <- 1 / w.ori
1077 # E(g.ori)$weigth <- 1 - w.ori
1079 # g.max <- minimum.spanning.tree(g.ori)
1080 # if (method == 'cooc') {
1081 # E(g.max)$weight <- 1 / E(g.max)$weight
1083 # E(g.max)$weight <- 1 - E(g.max)$weight
1090 if self.parametres['com'] :
1091 com = `self.parametres['communities']`
1094 if self.parametres['halo'] :
1104 x <- list(mat = mat, eff = eff)
1105 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)
1106 """ % (method, type, layout, arbremax, coeff_tv, coeff_te)
1108 if self.parametres.get('bystar',False) :
1109 if self.parametres.get('cexfromchi', False) :
1111 label.cex<-chivertex.size
1117 if self.parametres.get('sfromchi', False) :
1119 vertex.size <- norm.vec(toblack, minmaxeff[1], minmaxeff[2])
1126 #print self.parametres
1127 if (self.parametres['type'] == 'clustersimitxt' and self.parametres.get('tmpchi', False)) or (self.parametres['type'] in ['simimatrix','simiclustermatrix'] and 'tmpchi' in self.parametres):
1129 lchi <- read.table("%s")
1131 """ % ffr(self.parametres['tmpchi'])
1133 lchi <- lchi[sel.col]
1135 if self.parametres['type'] in ['clustersimitxt', 'simimatrix', 'simiclustermatrix'] and self.parametres.get('cexfromchi', False) :
1137 label.cex <- norm.vec(lchi, vcexminmax[1], vcexminmax[2])
1141 if (is.null(vcexminmax[1])) {
1144 label.cex <- graph.simi$label.cex
1147 if (self.parametres['type'] in ['clustersimitxt', 'simimatrix', 'simiclustermatrix']) and self.parametres.get('sfromchi', False):
1149 vertex.size <- norm.vec(lchi, minmaxeff[1], minmaxeff[2])
1150 if (!length(vertex.size)) vertex.size <- 0
1154 if (is.null(minmaxeff[1])) {
1157 vertex.size <- graph.simi$eff
1160 #txt += """ vertex.size <- NULL """
1161 if self.parametres['svg'] : svg = 'TRUE'
1162 else : svg = 'FALSE'
1169 if (col.from.proto) {
1170 proto.col <- read.table('/tmp/matcol.csv')
1171 v.proto.names <- make.names(proto.col[,1])
1172 v.proto.col <- as.character(proto.col[,2])
1173 v.proto.col[which(v.proto.col=='black')] <- 'yellow'
1174 v.names <- V(graph.simi$graph)$name
1175 num.color <- sapply(v.names, function(x) {if (x %%in%% v.proto.names) {v.proto.col[which(v.proto.names==x)]} else {'pink'}})
1176 vertex.col <- num.color
1177 V(graph.simi$graph)$proto.color <- vertex.col
1179 if (!is.null(graph.simi$com)) {
1180 com <- graph.simi$com
1181 colm <- rainbow(length(com))
1182 if (vertex.size != 0 || graph.simi$halo) {
1183 vertex.label.color <- 'black'
1184 vertex.col <- colm[membership(com)]
1186 vertex.label.color <- colm[membership(com)]
1189 if (!is.null(graph.simi$elim)) {
1190 vertex.label.color <- vertex.label.color[-graph.simi$elim]
1191 if (length(label.cex > 1)) {
1192 label.cex <- label.cex[-graph.simi$elim]
1195 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)
1196 save.image(file="%s")
1197 """ % (type, self.filename, ffr(self.pathout['RData']))
1202 class WordCloudRScript(PrintRScript) :
1203 def make_script(self) :
1204 self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1205 self.packages(['wordcloud'])
1206 bg_col = Rcolor(self.parametres['col_bg'])
1207 txt_col = Rcolor(self.parametres['col_text'])
1208 if self.parametres['svg'] :
1216 act <- read.csv2("%s", header = FALSE, row.names=1, sep='\t')
1217 selected.col <- read.table("%s")
1218 toprint <- as.matrix(act[selected.col[,1] + 1,])
1219 rownames(toprint) <- rownames(act)[selected.col[,1] + 1]
1221 if (nrow(toprint) > maxword) {
1222 toprint <- as.matrix(toprint[order(toprint[,1], decreasing=TRUE),])
1223 toprint <- as.matrix(toprint[1:maxword,])
1225 open_file_graph("%s", width = %i, height = %i , svg = svg)
1227 wordcloud(row.names(toprint), toprint[,1], scale=c(%f,%f), random.order=FALSE, colors=rgb%s)
1229 """ % (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)
1233 class ProtoScript(PrintRScript) :
1234 def make_script(self) :
1235 self.sources([self.analyse.parent.RscriptsPath['Rgraph'], self.analyse.parent.RscriptsPath['prototypical.R']])
1236 self.packages(['wordcloud'])
1237 if self.parametres.get('cloud', False) :
1242 errorn <- function(x) {
1243 qnorm(0.975)*sd(x)/sqrt(lenght(n))
1245 errort <- function(x) {
1246 qt(0.975,df=lenght(x)-1)*sd(x)/sqrt(lenght(x))
1248 mat <- read.csv2("%s", header = FALSE, row.names=1, sep='\t', quote='"', dec='.')
1249 open_file_graph("%s",height=800, width=1000)
1250 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')
1252 """ % (ffr(self.analyse.pathout['table.csv']), ffr(self.analyse.pathout['proto.png']), self.parametres['limfreq'], self.parametres['limrang'], self.parametres['typegraph'])
1257 class ExportAfc(PrintRScript) :
1258 def make_script(self) :
1259 self.source([self.analyse.parent.RscriptsPath['Rgraph']])
1260 self.packages(['rgexf'])
1264 class MergeGraphes(PrintRScript) :
1265 def __init__(self, analyse):
1266 self.script = u"#Script genere par IRaMuTeQ - %s\n" % datetime.now().ctime()
1267 self.pathout = PathOut()
1268 self.parametres = analyse.parametres
1269 self.scriptout = self.pathout['temp']
1270 self.analyse = analyse
1272 def make_script(self) :
1282 g <- graph.simi$graph
1283 V(g)$weight <- (graph.simi$mat.eff/nrow(dm))*100
1286 for i, graph in enumerate(self.parametres['graphs']) :
1287 path = os.path.dirname(graph)
1288 gname = ''.join(['g', `i`])
1289 RData = os.path.join(path,'RData.RData')
1290 txt += load % (ffr(RData), gname)
1292 self.sources([self.analyse.parent.RscriptsPath['simi']])
1294 merge.type <- 'proto'
1295 if (merge.type == 'normal') {
1296 ng <- merge.graph(graphs)
1298 ng <- merge.graph.proto(graphs)
1300 ngraph <- list(graph=ng, layout=layout.fruchterman.reingold(ng, dim=3), labex.cex=V(ng)$weight)
1301 write.graph(ng, "%s", format = 'graphml')
1302 """ % ffr(self.parametres['grapheout'])
1305 class TgenSpecScript(PrintRScript):
1306 def make_script(self):
1307 self.packages(['textometry'])
1309 tgen <- read.csv2("%s", row.names = 1, sep = '\\t')
1310 """ % ffr(self.parametres['tgeneff'])
1312 tot <- tgen[nrow(tgen), ]
1314 tgen <- tgen[-nrow(tgen),]
1315 for (i in 1:nrow(tgen)) {
1316 mat <- rbind(tgen[i,], tot - tgen[i,])
1317 specmat <- specificities(mat)
1318 result <- rbind(result, specmat[1,])
1320 colnames(result) <- colnames(tgen)
1321 row.names(result) <- rownames(tgen)
1322 write.table(result, file = "%s", sep='\\t', col.names = NA)
1323 """ % ffr(self.pathout['tgenspec.csv'])
1326 class TgenProfScript(PrintRScript):
1327 def make_script(self):
1328 self.sources([self.analyse.ira.RscriptsPath['chdfunct']])
1330 tgen <- read.csv2("%s", row.names = 1, sep = '\\t')
1331 """ % ffr(self.parametres['tgeneff'])
1333 tgenlem <- read.csv2("%s", row.names = 1, sep = '\\t')
1334 """ % ffr(self.parametres['tgenlemeff'])
1336 res <- build.prof.tgen(tgen)
1337 write.table(res$chi2, file = "%s", sep='\\t', col.names = NA)
1338 write.table(res$pchi2, file = "%s", sep='\\t', col.names = NA)
1339 """ % (ffr(self.pathout['tgenchi2.csv']), ffr(self.pathout['tgenpchi2.csv']))
1341 reslem <- build.prof.tgen(tgenlem)
1342 write.table(reslem$chi2, file = "%s", sep='\\t', col.names = NA)
1343 write.table(reslem$pchi2, file = "%s", sep='\\t', col.names = NA)
1344 """ % (ffr(self.pathout['tgenlemchi2.csv']), ffr(self.pathout['tgenlempchi2.csv']))
1347 class FreqMultiScript(PrintRScript):
1348 def make_script(self):
1349 self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1351 freq <- read.csv2("%s", row.names=1, sep='\\t', dec='.')
1352 """ % ffr(self.pathout['frequences.csv'])
1354 toplot <- freq[order(freq[,2]) ,2]
1355 toplot.names = rownames(freq)[order(freq[,2])]
1356 h <- 80 + (20 * nrow(freq))
1357 open_file_graph("%s",height=h, width=500)
1358 par(mar=c(3,20,3,3))
1359 barplot(toplot, names = toplot.names, horiz=TRUE, las =1, col = rainbow(nrow(freq)))
1361 """ % ffr(self.pathout['barplotfreq.png'])
1363 toplot <- freq[order(freq[,4]) ,4]
1364 toplot.names = rownames(freq)[order(freq[,4])]
1365 open_file_graph("%s",height=h, width=500)
1366 par(mar=c(3,20,3,3))
1367 barplot(toplot, names = toplot.names, horiz=TRUE, las =1, col = rainbow(nrow(freq)))
1369 """ % ffr(self.pathout['barplotrow.png'])
1373 class LabbeScript(PrintRScript) :
1374 def make_script(self) :
1375 self.sources([self.analyse.parent.RscriptsPath['distance-labbe.R'],
1376 self.analyse.parent.RscriptsPath['Rgraph']])
1378 tab <- read.csv2("%s", header=TRUE, sep=';', row.names=1)
1379 """ % (ffr(self.pathout['tableafcm.csv']))
1381 dist.mat <- dist.labbe(tab)
1382 dist.mat <- as.dist(dist.mat, upper=F, diag=F)
1383 write.table(as.matrix(dist.mat), "%s", sep='\t')
1386 chd <- hclust(dist.mat, method="ward.D2")
1387 open_file_graph("%s", width=1000, height=1000, svg=F)
1389 plot.phylo(as.phylo(chd), type='unrooted', lab4ut="axial")
1391 """ % (ffr(self.pathout['distmat.csv']), ffr(self.pathout['labbe-tree.png']))
1393 open_file_graph("%s", width=1000, height=1000, svg=F)
1394 par(mar=c(10,1,1,10))
1395 heatmap(as.matrix(dist.mat), symm = T, distfun=function(x) as.dist(x), margins=c(10,10))
1397 """ % ffr(self.pathout['labbe-heatmap.png'])
1399 #http://stackoverflow.com/questions/3081066/what-techniques-exists-in-r-to-visualize-a-distance-matrix
1400 dst <- data.matrix(dist.mat)
1402 rn <- row.names(as.matrix(dist.mat))
1403 open_file_graph("%s", width=1500, height=1000, svg=F)
1404 par(mar=c(10,10,3,3))
1405 image(1:dim, 1:dim, dst, axes = FALSE, xlab="", ylab="", col=heat.colors(99), breaks=seq(0.01,1,0.01))
1406 axis(1, 1:dim, rn, cex.axis = 0.9, las=3)
1407 axis(2, 1:dim, rn, cex.axis = 0.9, las=1)
1408 text(expand.grid(1:dim, 1:dim), sprintf("%%0.2f", dst), cex=0.6)
1410 """ % ffr(self.pathout['labbe-matrix.png'])
1413 g <- graph.adjacency(as.matrix(1-dist.mat), mode="lower", weighted=T)
1414 write.graph(g, file="%s", format='graphml')
1415 open_file_graph("%s", width=1000, height=1000, svg=F)
1418 E(g)$weight <- 1 - E(g)$weight
1419 g <- minimum.spanning.tree(g)
1420 E(g)$weight <- 1 - E(g)$weight
1421 write.graph(g, file="%s", format='graphml')
1422 open_file_graph("%s", width=1000, height=1000, svg=F)
1425 """ % (ffr(self.pathout['graph_tot.graphml']), ffr(self.pathout['graph_tot.png']), ffr(self.pathout['graph_min.graphml']), ffr(self.pathout['graph_min.png']))
1429 class ChronoChi2Script(PrintRScript) :
1430 def make_script(self) :
1431 self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1432 print self.parametres
1438 """ % (ffr(self.pathout['RData.RData']), ffr(self.pathout['dendrogramme.RData']))
1441 """ % self.parametres['svg']
1443 tc <- which(grepl("%s",rownames(chistabletot)))
1444 rn <- rownames(chistabletot)[tc]
1446 dpt <- chistabletot[tc,]
1447 tot <- afctable[tc,]
1452 """ % self.parametres['var'].replace(u'*', u"\\\\*")
1454 classes <- n1[,ncol(n1)]
1455 tcl <- table(classes)
1456 if ('0' %in% names(tcl)) {
1457 to.vire <- which(names(tcl) == '0')
1458 tcl <- tcl[-to.vire]
1460 tclp <- tcl/sum(tcl)
1468 lcol <- c(lcol, qchisq(1-k,1))
1472 lcol <- c(3.84, lcol)
1473 lcol <- c(-Inf,lcol)
1474 lcol <- c(lcol, Inf)
1477 alphas <- seq(0,1, length.out=length(breaks))
1478 clod <- rev(as.numeric(tree.cut1$tree.cl$tip.label))
1482 open_file_graph("%s", w=%i, h=%i, svg=svg)
1483 """ % (ffr(self.parametres['tmpgraph']), self.parametres['width'], self.parametres['height'])
1486 mat.graphic <- matrix(c(rep(1,nrow(dd)),c(2:(nrow(dd)+1))), ncol=2)
1487 mat.graphic <- rbind(mat.graphic, c(max(mat.graphic) + 1 , max(mat.graphic) + 2))
1488 hauteur <- tclp[clod] * 0.9
1489 heights.graphic <- append(hauteur, 0.1)
1490 layout(mat.graphic, heights=heights.graphic, widths=c(0.15,0.85))
1492 tree.toplot <- tree.cut1$tree.cl
1493 num.label <- as.numeric(tree.cut1$tree.cl$tip.label)
1494 col.tree <- rainbow(length(num.label))[num.label]
1495 #tree.toplot$tip.label <- paste('classe ', tree.toplot$tip.label)
1496 plot.phylo(tree.toplot,label.offset=0.1, cex=1.1, no.margin=T, tip.color = col.tree)
1500 lcol <- cut(dd[i,], breaks, include.lowest=TRUE)
1501 ulcol <- names(table(lcol))
1502 lcol <- as.character(lcol)
1503 for (j in 1:length(ulcol)) {
1504 lcol[which(lcol==ulcol[j])] <- j
1506 lcol <- as.numeric(lcol)
1507 mcol <- rainbow(nrow(dd))[i]
1510 last.col <- c(last.col, rgb(r=col2rgb(mcol)[1]/255, g=col2rgb(mcol)[2]/255, b=col2rgb(mcol)[3]/255, a=k))
1514 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))
1516 plot(0,type='n',axes=FALSE,ann=FALSE)
1517 label.coords <- barplot(rep(1, ncol(dd)), width=ptc, names.arg = F, las=2, axes=F, ylim=c(0,1), plot=T, col='white')
1518 text(x=label.coords, y=0.5, labels=rn[order(rn)], srt=90)
1524 class ChronoPropScript(PrintRScript) :
1525 def make_script(self) :
1526 self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1527 print self.parametres
1533 """ % (ffr(self.pathout['RData.RData']), ffr(self.pathout['dendrogramme.RData']))
1536 """ % self.parametres['svg']
1538 tc <- which(grepl("%s",rownames(chistabletot)))
1539 rn <- rownames(chistabletot)[tc]
1541 dpt <- chistabletot[tc,]
1542 tot <- afctable[tc,]
1547 """ % self.parametres['var'].replace(u'*', u"\\\\*")
1549 classes <- n1[,ncol(n1)]
1550 tcl <- table(classes)
1551 if ('0' %in% names(tcl)) {
1552 to.vire <- which(names(tcl) == '0')
1553 tcl <- tcl[-to.vire]
1555 tclp <- tcl/sum(tcl)
1558 open_file_graph("%s", w=%i, h=%i, svg=svg)
1559 """ % (ffr(self.parametres['tmpgraph']), self.parametres['width'], self.parametres['height'])
1561 ptt <- prop.table(as.matrix(tot), 1)
1562 par(mar=c(10,2,2,2))
1563 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)
1569 class DendroScript(PrintRScript) :
1570 def make_script(self) :
1571 if self.parametres['svg'] :
1575 fileout = self.parametres['fileout']
1576 width = self.parametres['width']
1577 height = self.parametres['height']
1578 type_dendro = self.parametres['dendro_type']
1579 if self.parametres['taille_classe'] :
1583 if self.parametres['color_nb'] == 0 :
1587 if self.parametres['type_tclasse'] == 0 :
1591 if self.parametres['svg'] :
1595 dendro_path = self.pathout['Rdendro']
1596 classe_path = self.pathout['uce']
1601 classes <- read.csv2("%s", row.names=1)
1602 classes <- classes[,1]
1603 """ % (ffr(dendro_path), ffr(self.parametres['Rgraph']), ffr(classe_path))
1604 if self.parametres['dendro'] == 'simple' :
1606 open_file_graph("%s", width=%i, height=%i, svg=%s)
1607 plot.dendropr(tree.cut1$tree.cl, classes, type.dendro="%s", histo=%s, bw=%s, lab=NULL, tclasse=%s)
1608 """ % (ffr(fileout), width, height, svg, type_dendro, histo, bw, tclasse)
1609 elif self.parametres['dendro'] == 'texte' :
1613 if (is.null(debsup)) {
1616 chistable <- chistabletot[1:(debsup-1),]
1617 """ % (ffr(self.pathout['RData.RData']), ffr(self.parametres['Rgraph']))
1618 if self.parametres.get('translation', False) :
1620 rn <- read.csv2("%s", header=FALSE, sep='\t')
1621 rnchis <- row.names(chistable)
1622 commun <- intersect(rnchis, unique(rn[,2]))
1623 idrnchis <- sapply(commun, function(x) {which(rnchis==x)})
1624 idrn <- sapply(commun, function(x) {which(as.vector(rn[,2])==x)[1]})
1625 rownames(chistable)[idrnchis] <- as.vector(rn[idrn,1])
1626 """ % ffr(self.parametres['translation'])
1628 open_file_graph("%s", width=%i, height=%i, svg = %s)
1629 plot.dendro.prof(tree.cut1$tree.cl, classes, chistable, nbbycl = 60, type.dendro="%s", bw=%s, lab=NULL)
1630 """ % (ffr(fileout), width, height, svg, type_dendro, bw)
1631 elif self.parametres['dendro'] == 'cloud' :
1635 if (is.null(debsup)) {
1638 chistable <- chistabletot[1:(debsup-1),]
1639 open_file_graph("%s", width=%i, height=%i, svg=%s)
1640 plot.dendro.cloud(tree.cut1$tree.cl, classes, chistable, nbbycl = 300, type.dendro="%s", bw=%s, lab=NULL)
1641 """ % (ffr(self.pathout['RData.RData']), ffr(self.parametres['Rgraph']), ffr(fileout), width, height, svg, type_dendro, bw)
1646 class ReDoProfScript(PrintRScript) :
1647 def make_script(self) :
1648 self.sources([self.analyse.parent.RscriptsPath['chdfunct.R']])
1649 print self.parametres