1 # -*- coding: utf-8 -*-
2 #Author: Pierre Ratinaud
3 #Copyright (c) 2008-2020 Pierre Ratinaud
4 #modification pour python 3 : Laurent Mérat, 6x7 - mai 2020
7 #------------------------------------
8 # import des modules python
9 #------------------------------------
13 from datetime import datetime
16 #------------------------------------
17 # import des fichiers du projet
18 #------------------------------------
19 from chemins import ffr, PathOut
22 log = logging.getLogger('iramuteq.printRscript')
27 def __init__ (self, analyse, parametres = None):
29 self.pathout = analyse.pathout
30 self.analyse = analyse
31 if parametres is None:
32 self.parametres = analyse.parametres
34 self.parametres = parametres
35 #self.scriptout = ffr(self.pathout['lastRscript.R'])
36 self.scriptout = self.pathout['temp']
37 self.script = "#Script genere par IRaMuTeQ - %s\n" % datetime.now().ctime()
40 self.script = '\n'.join([self.script, txt])
42 def defvar(self, name, value):
43 self.add(' <- '.join([name, value]))
45 def defvars(self, lvars):
47 self.defvar(val[0],val[1])
49 def sources(self, lsources):
50 for source in lsources:
51 self.add('source("%s", encoding = \'utf8\')' % ffr(source))
53 def packages(self, lpks):
55 self.add('library(%s)' % pk)
59 self.add('load("%s")' % ffr(val))
62 with open(self.scriptout, 'w') as f:
67 class chdtxt(PrintRScript):
72 return str(color).replace(')', ', max=255)')
75 class Alceste2(PrintRScript):
78 self.sources(['chdfunct'])
80 lvars = [['clnb', repr(self.analyse.clnb)],
81 ['Contout', '"%s"' % self.pathout['Contout']],
82 ['ContSupOut', '"%s"' % self.pathout['ContSupOut']],
83 ['ContEtOut', '"%s"' % self.pathout['ContEtOut']],
84 ['profileout', '"%s"' % self.pathout['profils.csv']],
85 ['antiout', '"%s"' % self.pathout['antiprofils.csv']],
86 ['chisqtable', '"%s"' % self.pathout['chisqtable.csv']],
87 ['ptable', '"%s"' % self.pathout['ptable.csv']]]
91 # txt = "clnb<-%i\n" % clnb
95 #""" % (RscriptsPath['chdfunct'], DictChdTxtOut['RData'])
97 #dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
98 #datasup<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
99 #dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
100 #""" % (DictChdTxtOut['Contout'], DictChdTxtOut['ContSupOut'], DictChdTxtOut['ContEtOut'])
102 #tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
103 #tablesqrpsup<-BuildProf(as.matrix(datasup),n1,clnb)
104 #tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
107 #PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s",tablesqrpsup[4],tablesqrpsup[5])
108 #""" % (DictChdTxtOut['PROFILE_OUT'], DictChdTxtOut['ANTIPRO_OUT'])
110 #colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
111 #colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
112 #colnames(tablesqrpsup[[2]])<-paste('classe',1:clnb,sep=' ')
113 #colnames(tablesqrpsup[[1]])<-paste('classe',1:clnb,sep=' ')
114 #colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
115 #colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
116 #chistabletot<-rbind(tablesqrpact[2][[1]],tablesqrpsup[2][[1]])
117 #chistabletot<-rbind(chistabletot,tablesqrpet[2][[1]])
118 #ptabletot<-rbind(tablesqrpact[1][[1]],tablesqrpet[1][[1]])
121 #write.csv2(chistabletot,file="%s")
122 #write.csv2(ptabletot,file="%s")
124 #write.csv2(gbcluster,file="%s")
125 #""" % (DictChdTxtOut['chisqtable'], DictChdTxtOut['ptable'], DictChdTxtOut['SbyClasseOut'])
129 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):
135 """ % (ffr(RscriptPath['CHD']), ffr(RscriptPath['chdtxt']), ffr(RscriptPath['anacor']), ffr(RscriptPath['Rgraph']))
143 if svdmethod == 'svdlibc' and libsvdc:
145 svd.method <- 'svdlibc'
147 """ % ffr(libsvdc_path)
148 elif svdmethod == 'irlba':
151 svd.method <- 'irlba'
169 data1 <- readMM("%s")
170 data1 <- as(data1, "dgCMatrix")
171 row.names(data1) <- 1:nrow(data1)
172 """ % ffr(DicoPath['TableUc1'])
173 if classif_mode == 0:
175 data2 <- readMM("%s")
176 data2 <- as(data2, "dgCMatrix")
177 row.names(data2) <- 1:nrow(data2)
178 """ % ffr(DicoPath['TableUc2'])
181 #print('FIXME : source newCHD')
182 #source('/home/pierre/workspace/iramuteq/Rscripts/newCHD.R')
184 #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)
185 chd1<-CHD(data1, x = nbt, mode.patate = mode.patate, svd.method = svd.method, libsvdc.path = libsvdc.path)#, log.file = log1)
186 """ % (ffr(DicoPath['log-chd1.txt']), nbproc)
187 if classif_mode == 0:
190 chd2<-CHD(data2, x = nbt, mode.patate = mode.patate, svd.method =
191 svd.method, libsvdc.path = libsvdc.path)#, log.file = log2)
192 """ % ffr(DicoPath['log-chd2.txt'])
195 listuce1<-read.csv2("%s")
196 """ % ffr(DicoPath['listeuce1'])
197 if classif_mode == 0:
199 listuce2<-read.csv2("%s")
200 """ % ffr(DicoPath['listeuce2'])
204 if classif_mode == 0:
211 if (mincl == 0) {mincl <- round(nrow(chd1$n1)/(nbt+1))}
213 write.csv2(chd1$n1, file="%s")
214 if (classif_mode == 0) {
215 chd.result <- Rchdtxt(uceout, chd1, chd2 = chd2, mincl = mincl,classif_mode = classif_mode, nbt = nbt)
216 classeuce1 <- chd.result$cuce1
217 tree.tot1 <- make_tree_tot(chd1)
218 tree.cut1 <- make_dendro_cut_tuple(tree.tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
220 #chd.result <- Rchdtxt(uceout, chd1, chd2 = chd1, mincl = mincl,classif_mode = classif_mode, nbt = nbt)
221 tree.tot1 <- make_tree_tot(chd1)
222 terminales <- find.terminales(chd1$n1, chd1$list_mere, chd1$list_fille, mincl)
223 tree.cut1 <- make.classes(terminales, chd1$n1, tree.tot1$tree.cl, chd1$list_fille)
224 write.csv2(tree.cut1$n1, uceout)
225 chd.result <- tree.cut1
227 classes<-chd.result$n1[,ncol(chd.result$n1)]
228 write.csv2(chd.result$n1, file="%s")
229 """ % (classif_mode, mincl, ffr(DicoPath['uce']), ffr(DicoPath['n1-1.csv']), ffr(DicoPath['n1.csv']))
231 # tree.tot1 <- make_tree_tot(chd1)
232 # open_file_graph("%s", widt = 600, height=400)
233 # plot(tree.tot1$tree.cl)
235 """ % ffr(DicoPath['arbre1'])
236 if classif_mode == 0:
238 classeuce2 <- chd.result$cuce2
239 tree.tot2 <- make_tree_tot(chd2)
240 # open_file_graph("%s", width = 600, height=400)
241 # plot(tree.tot2$tree.cl)
243 """ % ffr(DicoPath['arbre2'] )
245 save(tree.cut1, file="%s")
247 open_file_graph("%s", width = 600, height=400)
248 plot.dendropr(tree.cut1$tree.cl,classes, histo=TRUE)
249 open_file_graph("%s", width = 600, height=400)
250 plot(tree.cut1$dendro_tot_cl)
252 """ % (ffr(DicoPath['Rdendro']), ffr(DicoPath['dendro1']), ffr(DicoPath['arbre1']))
253 if classif_mode == 0:
255 tree.cut2 <- make_dendro_cut_tuple(tree.tot2$dendro_tuple, chd.result$coord_ok, classeuce2, 2, nbt)
256 open_file_graph("%s", width = 600, height=400)
257 plot(tree.cut2$tree.cl)
259 open_file_graph("%s", width = 600, height=400)
260 plot(tree.cut2$dendro_tot_cl)
262 """ % (ffr(DicoPath['dendro2']), ffr(DicoPath['arbre2']))
264 #save.image(file="%s")
265 """ % (ffr(DicoPath['RData']))
266 fileout = open(DicoPath['Rchdtxt'], 'w')
270 def RPamTxt(corpus, RscriptPath):
271 DicoPath = corpus.pathout
272 param = corpus.parametres
275 """ % (RscriptPath['pamtxt'])
278 """ % (RscriptPath['Rgraph'])
280 result <- pamtxt("%s", "%s", "%s", method = "%s", clust_type = "%s", clnb = %i)
282 """ % (DicoPath['TableUc1'], DicoPath['listeuce1'], DicoPath['uce'], param['method'], param['cluster_type'], param['nbcl'] )
284 open_file_graph("%s", width=400, height=400)
287 """ % (DicoPath['arbre1'])
289 save.image(file="%s")
290 """ % DicoPath['RData']
291 fileout = open(DicoPath['Rchdtxt'], 'w')
295 def RchdQuest(DicoPath, RscriptPath, nbcl = 10, mincl = 10):
301 """ % (ffr(RscriptPath['CHD']), ffr(RscriptPath['chdquest']), ffr(RscriptPath['anacor']),ffr(RscriptPath['Rgraph']))
307 chd.result<-Rchdquest("%s","%s","%s", nbt = nbt, mincl = mincl)
309 classeuce1 <- chd.result$cuce1
310 """ % (ffr(DicoPath['mat01.csv']), ffr(DicoPath['listeuce1']), ffr(DicoPath['uce']))
312 tree_tot1 <- make_tree_tot(chd.result$chd)
313 open_file_graph("%s", width = 600, height=400)
314 plot(tree_tot1$tree.cl)
316 """ % ffr(DicoPath['arbre1'])
318 tree_cut1 <- make_dendro_cut_tuple(tree_tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
319 tree.cut1 <- tree_cut1
320 save(tree.cut1, file="%s")
321 open_file_graph("%s", width = 600, height=400)
322 classes<-n1[,ncol(n1)]
323 plot.dendropr(tree_cut1$tree.cl,classes, histo = TRUE)
324 """ % (ffr(DicoPath['Rdendro']), ffr(DicoPath['dendro1']))
326 save.image(file="%s")
327 """ % ffr(DicoPath['RData'])
328 fileout = open(DicoPath['Rchdquest'], 'w')
332 def ReinertTxtProf(DictChdTxtOut, RscriptsPath, clnb, taillecar):
333 txt = "clnb<-%i\n" % clnb
337 n1 <- read.csv2("%s")
338 """ % (ffr(RscriptsPath['chdfunct']), ffr(DictChdTxtOut['RData']), ffr(DictChdTxtOut['n1.csv']))
340 dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
341 datasup<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
342 dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
343 """ % (ffr(DictChdTxtOut['Contout']), ffr(DictChdTxtOut['ContSupOut']), ffr(DictChdTxtOut['ContEtOut']))
345 print('ATTENTION NEW BUILD PROF')
346 #tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
347 #tablesqrpsup<-BuildProf(as.matrix(datasup),n1,clnb)
348 #tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
349 tablesqrpact<-new.build.prof(as.matrix(dataact),n1,clnb)
350 tablesqrpsup<-new.build.prof(as.matrix(datasup),n1,clnb)
351 tablesqrpet<-new.build.prof(as.matrix(dataet),n1,clnb)
354 PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s",tablesqrpsup[4],tablesqrpsup[5])
355 """ % (ffr(DictChdTxtOut['PROFILE_OUT']), ffr(DictChdTxtOut['ANTIPRO_OUT']))
357 colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
358 colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
359 colnames(tablesqrpsup[[2]])<-paste('classe',1:clnb,sep=' ')
360 colnames(tablesqrpsup[[1]])<-paste('classe',1:clnb,sep=' ')
361 colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
362 colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
363 chistabletot<-rbind(tablesqrpact[2][[1]],tablesqrpsup[2][[1]])
364 chistabletot<-rbind(chistabletot,tablesqrpet[2][[1]])
365 ptabletot<-rbind(tablesqrpact[1][[1]],tablesqrpet[1][[1]])
368 write.csv2(chistabletot,file="%s")
369 write.csv2(ptabletot,file="%s")
371 write.csv2(gbcluster,file="%s")
372 """ % (ffr(DictChdTxtOut['chisqtable']), ffr(DictChdTxtOut['ptable']), ffr(DictChdTxtOut['SbyClasseOut']))
376 colnames(dataact)<-paste('classe',1:clnb,sep=' ')
377 colnames(datasup)<-paste('classe',1:clnb,sep=' ')
378 colnames(dataet)<-paste('classe',1:clnb,sep=' ')
379 rowtot<-nrow(dataact)+nrow(dataet)+nrow(datasup)
380 afctable<-rbind(as.matrix(dataact),as.matrix(datasup))
381 afctable<-rbind(afctable,as.matrix(dataet))
382 colnames(afctable)<-paste('classe',1:clnb,sep=' ')
383 afc<-ca(afctable,suprow=((nrow(dataact)+1):rowtot),nd=(ncol(afctable)-1))
384 debsup<-nrow(dataact)+1
385 debet<-nrow(dataact)+nrow(datasup)+1
387 afc<-AddCorrelationOk(afc)
389 #FIXME : split this!!!
392 """ % ffr(RscriptsPath['Rgraph'])
394 afc <- summary.ca.dm(afc)
395 afc_table <- create_afc_table(afc)
396 write.csv2(afc_table$facteur, file = "%s")
397 write.csv2(afc_table$colonne, file = "%s")
398 write.csv2(afc_table$ligne, file = "%s")
399 """ % (ffr(DictChdTxtOut['afc_facteur']), ffr(DictChdTxtOut['afc_col']), ffr(DictChdTxtOut['afc_row']))
404 xyminmax <- PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
405 """ % (ffr(DictChdTxtOut['AFC2DL_OUT']))
407 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)
408 """ % (ffr(DictChdTxtOut['AFC2DSL_OUT']))
410 if ((fin - debet) > 2) {
411 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)
413 """ % (ffr(DictChdTxtOut['AFC2DEL_OUT']))
415 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)
416 """ % (ffr(DictChdTxtOut['AFC2DCL_OUT']))
418 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
419 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debsup, fin=(debet-1), xlab = xlab, ylab = ylab)
420 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debet, fin=fin, xlab = xlab, ylab = ylab)
421 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col=TRUE, what='crl', xlab = xlab, ylab = ylab)
422 # """ % (DictChdTxtOut['AFC2DCoul'], DictChdTxtOut['AFC2DCoulSup'], DictChdTxtOut['AFC2DCoulEt'], DictChdTxtOut['AFC2DCoulCl'])
430 save.image(file="%s")
431 """ % ffr(DictChdTxtOut['RData'])
432 file = open(DictChdTxtOut['RTxtProfGraph'], 'w')
436 def write_afc_graph(self):
437 if self.param['over']:
441 if self.param['do_select_nb']:
442 do_select_nb = 'TRUE'
444 do_select_nb = 'FALSE'
445 if self.param['do_select_chi']:
446 do_select_chi = 'TRUE'
448 do_select_chi = 'FALSE'
449 if self.param['do_select_chi_classe']:
450 do_select_chi_classe = 'TRUE'
452 do_select_chi_classe = 'FALSE'
453 if self.param['cex_txt']:
457 if self.param['tchi']:
461 if self.param['svg']:
465 if self.param['typegraph'] == 4:
466 nodesfile = os.path.join(os.path.dirname(self.fileout),'nodes.csv')
467 edgesfile = os.path.join(os.path.dirname(self.fileout),'edges.csv')
471 with open(self.RscriptsPath['afc_graph'], 'r') as f:
473 # self.DictPathOut['RData'], \
474 scripts = txt % (ffr(self.RscriptsPath['Rgraph']),\
475 self.param['typegraph'], \
476 edgesfile, nodesfile, \
477 self.param['what'], \
478 self.param['facteur'][0],\
479 self.param['facteur'][1], \
480 self.param['facteur'][2], \
482 over, do_select_nb, \
483 self.param['select_nb'], \
485 self.param['select_chi'], \
486 do_select_chi_classe, \
487 self.param['nbchic'], \
489 self.param['txt_min'], \
490 self.param['txt_max'], \
492 self.param['width'], \
493 self.param['height'],\
494 self.param['taillecar'], \
495 self.param['alpha'], \
496 self.param['film'], \
498 self.param['tchi_min'],\
499 self.param['tchi_max'],\
500 ffr(os.path.dirname(self.fileout)),\
504 def print_simi3d(self):
505 simi3d = self.parent.simi3dpanel
506 txt = '#Fichier genere par Iramuteq'
507 if simi3d.movie.GetValue():
508 movie = "'" + ffr(os.path.dirname(self.DictPathOut['RData'])) + "'"
511 #if self.corpus.parametres['type'] == 'corpus':
517 dm<-read.csv2("%s",row.names=1,header = %s)
519 """ % (self.DictPathOut['Contout'], header, self.DictPathOut['RData'])
522 """ % self.parent.RscriptsPath['Rgraph']
524 make.simi.afc(dm,chistabletot, lim=%i, alpha = %.2f, movie = %s)
525 """ % (simi3d.spin_1.GetValue(), float(simi3d.slider_1.GetValue())/100, movie)
526 tmpfile = tempfile.mktemp(dir=self.parent.TEMPDIR)
527 tmp = open(tmpfile,'w')
532 def dendroandbarplot(table, rownames, colnames, rgraph, tmpgraph, intxt = False, dendro=False):
534 txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
535 rownb = len(rownames)
536 rownames = 'c("' + '","'.join(rownames) + '")'
537 colnames = 'c("' + '","'.join(colnames) + '")'
541 di <- matrix(data=%s, nrow=%i, byrow = TRUE)
544 """ % (txttable, rownb, rownames, colnames)
551 height <- (30*ncol(di)) + (15*nrow(di))
552 height <- ifelse(height <= 400, 400, height)
554 open_file_graph("%s", width=width, height=height)
555 plot.dendro.lex(tree.cut1$tree.cl, di)
556 """ % (ffr(dendro),ffr(rgraph), ffr(tmpgraph))
559 def barplot(table, parametres, intxt = False):
561 txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
562 #width = 100 + (15 * len(rownames)) + (100 * len(colnames))
563 #height = len(rownames) * 15
564 rownb = len(parametres['rownames'])
567 rownames = 'c("' + '","'.join(parametres['rownames']) + '")'
568 colnames = 'c("' + '","'.join(parametres['colnames']) + '")'
572 di <- matrix(data=%s, nrow=%i, byrow = TRUE)
573 toinf <- which(di == Inf)
574 tominf <- which(di == -Inf)
577 valmax <- max(di, na.rm = TRUE)
585 if (length(tominf)) {
587 valmin <- min(di, na.rm = TRUE)
597 """ % (txttable, rownb, rownames, colnames)
600 if not 'tree' in parametres:
603 color = rainbow(nrow(di))
606 open_file_graph("%s",width = width, height = height, svg = %s)
608 layout(matrix(c(1,2),1,2, byrow=TRUE),widths=c(3,lcm(12)))
610 yp = ifelse(length(toinf), 0.2, 0)
611 ym = ifelse(length(tominf), 0.2, 0)
612 ymin <- ifelse(!length(which(di < 0)), 0, min(di) - ym)
613 coord <- barplot(as.matrix(di), beside = TRUE, col = color, space = c(0.1,0.6), ylim=c(ymin, max(di) + yp), las = 2)
615 coordinf <- coord[toinf]
617 text(x=coordinf, y=valinf + 0.1, 'i')
619 if (length(tominf)) {
620 coordinf <- coord[toinf]
622 text(x=coordinf, y=valinf - 0.1, 'i')
628 lcoord <- apply(cc, 1, mean)
631 amp <- abs(max(di) - min(di))
638 d <- signif(amp%%/%%10,1)
643 if ((i/d) == (i%%/%%d)) {
648 plot(0, axes = FALSE, pch = '')
649 legend(x = 'center' , rownames(di), fill = color)
651 """ % (ffr(parametres['rgraph']), parametres['width'], parametres['height'], ffr(parametres['tmpgraph']), parametres['svg'])
659 open_file_graph("%s", width=width, height=height, svg = %s)
660 plot.dendro.lex(tree.cut1$tree.cl, di)
661 """ % (ffr(parametres['tree']), ffr(parametres['rgraph']), parametres['width'], parametres['height'], ffr(parametres['tmpgraph']), parametres['svg'])
664 #def RAfcUci(DictAfcUciOut, nd=2, RscriptsPath='', PARCEX='0.8'):
670 # dataact<-read.csv2("%s")
671 # """ % (DictAfcUciOut['TableCont'])#, encoding)
673 # datasup<-read.csv2("%s")
674 # """ % (DictAfcUciOut['TableSup'])#, encoding)
676 # dataet<-read.csv2("%s")
677 # """ % (DictAfcUciOut['TableEt'])#, encoding)
679 # datatotsup<-cbind(dataact,datasup)
680 # datatotet<-cbind(dataact,dataet)
681 # afcact<-ca(dataact,nd=nd)
682 # afcsup<-ca(datatotsup,supcol=((ncol(dataact)+1):ncol(datatotsup)),nd=nd)
683 # afcet<-ca(datatotet,supcol=((ncol(dataact)+1):ncol(datatotet)),nd=nd)
684 # afctot<-afcsup$colcoord
685 # rownames(afctot)<-afcsup$colnames
686 # colnames(afctot)<-paste('coord. facteur',1:nd,sep=' ')
687 # afctot<-cbind(afctot,mass=afcsup$colmass)
688 # afctot<-cbind(afctot,distance=afcsup$coldist)
689 # afctot<-cbind(afctot,intertie=afcsup$colinertia)
690 # rcolet<-afcet$colsup
691 # afctmp<-afcet$colcoord[rcolet,]
692 # rownames(afctmp)<-afcet$colnames[rcolet]
693 # afctmp<-cbind(afctmp,afcet$colmass[rcolet])
694 # afctmp<-cbind(afctmp,afcet$coldist[rcolet])
695 # afctmp<-cbind(afctmp,afcet$colinertia[rcolet])
696 # afctot<-rbind(afctot,afctmp)
697 # write.csv2(afctot,file = "%s")
699 # """ % (DictAfcUciOut['afc_row'], RscriptsPath['Rgraph'])
705 # PlotAfc(afcet,filename="%s",toplot=c%s, PARCEX=PARCEX)
706 # """ % (DictAfcUciOut['AfcColAct'], "('none','active')")
708 # PlotAfc(afcsup,filename="%s",toplot=c%s, PARCEX=PARCEX)
709 # """ % (DictAfcUciOut['AfcColSup'], "('none','passive')")
710 # txt += """PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
711 # """ % (DictAfcUciOut['AfcColEt'], "('none','passive')")
713 # PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
714 # """ % (DictAfcUciOut['AfcRow'], "('all','none')")
715 # f = open(DictAfcUciOut['Rafcuci'], 'w')
720 class PrintSimiScript(PrintRScript):
722 def make_script(self):
724 self.packages(['igraph', 'proxy', 'Matrix'])
725 self.sources([self.analyse.parent.RscriptsPath['simi'], self.analyse.parent.RscriptsPath['Rgraph']])
727 if not self.parametres['keep_coord'] and not (self.parametres['type'] == 'simimatrix' or self.parametres['type'] == 'simiclustermatrix'):
732 """ % (ffr(self.pathout['mat01.csv']), ffr(self.pathout['actives.csv']), ffr(self.pathout['selected.csv']))
733 if 'word' in self.parametres:
737 """ % self.parametres['word']
745 cn <- read.table(cn.path, sep="\t", quote='"')
746 colnames(dm) <- cn[,1]
747 if (file.exists(selected.col)) {
748 sel.col <- read.csv2(selected.col, header = FALSE)
749 sel.col <- sel.col[,1] + 1
751 sel.col <- 1:ncol(dm)
756 forme <- colnames(dm)[index]
757 if (!index %in% sel.col) {
758 sel.col <- append(sel.col, index)
761 index <- which(colnames(dm) == forme)
764 elif not self.parametres['keep_coord'] and (self.parametres['type'] == 'simimatrix' or self.parametres['type'] == 'simiclustermatrix'):
768 """ % (ffr(self.pathout['mat01.csv']), ffr(self.pathout['selected.csv']))
769 if 'word' in self.parametres:
773 """ % self.parametres['word']
779 dm <-read.csv2(dm.path)
781 if (file.exists(selected.col)) {
782 sel.col <- read.csv2(selected.col, header = FALSE)
783 sel.col <- sel.col[,1] + 1
785 sel.col <- 1:ncol(dm)
790 forme <- colnames(dm)[index]
791 if (!index %in% sel.col) {
792 sel.col <- append(sel.col, index)
795 index <- which(colnames(dm) == forme)
801 """ % ffr(self.pathout['RData.RData'])
802 if self.parametres['coeff'] == 0:
804 if not self.parametres['keep_coord']:
809 elif self.analyse.indices[self.parametres['coeff']] == 'Jaccard':
811 if not self.parametres['keep_coord']:
814 mat <- sparse.jaccard(dm)
817 if not self.parametres['keep_coord']:
821 if self.parametres['coeff'] == 1:
825 mat <- simil(dm, method = 'Russel', diag = TRUE, upper = TRUE, by_rows = FALSE)
827 elif self.analyse.indices[self.parametres['coeff']] == 'binomial':
829 if not self.parametres['keep_coord']:
834 elif self.parametres['coeff'] != 0 and self.analyse.indices[self.parametres['coeff']] != 'Jaccard':
835 method = self.analyse.indices[self.parametres['coeff']]
836 if not self.parametres['keep_coord']:
839 mat <- simil(dm, method = method, diag = TRUE, upper = TRUE, by_rows = FALSE)
840 """ % self.analyse.indices[self.parametres['coeff']]
841 if not self.parametres['keep_coord']:
843 mat <- as.matrix(stats::as.dist(mat,diag=TRUE,upper=TRUE))
845 if (length(which(mat == Inf))) {
846 infp <- which(mat == Inf)
848 maxmat <- max(mat, na.rm = TRUE)
856 if (length(which(mat == -Inf))) {
857 infm <- which(mat == -Inf)
859 minmat <- min(mat, na.rm = TRUE)
868 if 'word' in self.parametres and not self.parametres['keep_coord']:
870 mat <- graph.word(mat, index)
872 if (length(which(cs==0))) mat <- mat[,-which(cs==0)]
874 if (length(which(rs==0))) mat <- mat[-which(rs==0),]
875 if (length(which(cs==0))) dm <- dm[,-which(cs==0)]
877 index <- which(colnames(mat)==forme)
880 if self.parametres['layout'] == 0:
882 if self.parametres['layout'] == 1:
884 if self.parametres['layout'] == 2:
886 if self.parametres['layout'] == 3:
888 if self.parametres['layout'] == 4:
890 if self.parametres['layout'] == 5:
892 if self.parametres['layout'] == 6:
895 if self.parametres['type_graph'] == 0:
897 if self.parametres['type_graph'] == 1:
900 dirout = os.path.dirname(self.pathout['mat01.csv'])
901 while os.path.exists(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png')):
903 self.filename = ffr(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png'))
904 if self.parametres['type_graph'] == 2:
906 if self.parametres['type_graph'] == 3:
909 dirout = os.path.dirname(self.pathout['mat01.csv'])
910 while os.path.exists(os.path.join(dirout,'web_'+str(graphnb))):
912 self.filename = ffr(os.path.join(dirout,'web_'+str(graphnb)))
913 os.mkdir(self.filename)
914 self.filename = os.path.join(self.filename, 'gexf.gexf')
915 if self.parametres['type_graph'] == 4:
918 dirout = os.path.dirname(self.pathout['mat01.csv'])
919 while os.path.exists(os.path.join(dirout,'webrgl_'+str(graphnb))):
921 self.filename = ffr(os.path.join(dirout,'webrgl_'+str(graphnb)))
922 os.mkdir(self.filename)
923 if self.parametres['arbremax']:
925 self.txtgraph += ' - arbre maximum'
929 if self.parametres['coeff_tv']:
930 coeff_tv = self.parametres['coeff_tv_nb']
931 tvminmax = 'c(NULL,NULL)'
932 elif not self.parametres['coeff_tv'] or self.parametres.get('sformchi', False):
934 tvminmax = 'c(%i, %i)' %(self.parametres['tvmin'], self.parametres['tvmax'])
935 if self.parametres['coeff_te']:
936 coeff_te = 'c(%i,%i)' % (self.parametres['coeff_temin'], self.parametres['coeff_temax'])
939 if self.parametres['vcex'] or self.parametres.get('cexfromchi', False):
940 vcexminmax = 'c(%i/10,%i/10)' % (self.parametres['vcexmin'],self.parametres['vcexmax'])
942 vcexminmax = 'c(NULL,NULL)'
943 if not self.parametres['label_v']:
947 if not self.parametres['label_e']:
951 if self.parametres['seuil_ok']:
952 seuil = str(self.parametres['seuil'])
955 if not self.parametres.get('edgecurved', False):
962 cols = str(self.parametres['cols']).replace(')',', max=255)')
963 cola = str(self.parametres['cola']).replace(')',',max=255)')
972 """ % self.parametres['cex']
973 if self.parametres['film']:
976 """ % ffr(self.pathout['film'])
983 if (!is.null(seuil)) {
984 if (method!='cooc') {
992 """ % (label_v, label_e)
1000 """ % (self.parametres['width'], self.parametres['height'])
1001 if self.parametres['keep_coord']:
1003 coords <- try(coords, TRUE)
1004 if (!is.matrix(coords)) {
1014 """ % self.parametres['alpha']
1017 """ % self.parametres['alpha']
1018 ######### ??? ##########
1019 if self.parametres.get('bystar',False):
1023 for i, line in enumerate(self.parametres['listet']):
1026 """ % (i+1, ','.join([repr(val + 1) for val in line]))
1029 """ % ("','".join([val for val in self.parametres['selectedstars']]))
1033 for (i in 1:length(unetoile)) {
1036 if (length(tosum) > 1) {
1037 fsum <- cbind(fsum, colSums(dm[tosum,]))
1039 fsum <- cbind(fsum, dm[tosum,])
1043 lex <- AsLexico2(fsum, chip=TRUE)
1044 dcol <- apply(lex[[4]],1,which.max)
1045 toblack <- apply(lex[[4]],1,max)
1046 gcol <- rainbow(length(unetoile))
1047 #gcol[2] <- 'orange'
1048 vertex.label.color <- gcol[dcol]
1049 vertex.label.color[which(toblack <= 3.84)] <- 'black'
1050 leg <- list(unetoile=unetoile, gcol=gcol)
1051 cols <- vertex.label.color
1052 chivertex.size <- norm.vec(toblack, vcexminmax[1], vcexminmax[2])
1054 """ % (ffr(self.analyse.parent.RscriptsPath['chdfunct']))
1057 vertex.label.color <- 'black'
1061 ######### ??? ##########
1063 # eff <- colSums(dm)
1064 # g.ori <- graph.adjacency(mat, mode='lower', weighted = TRUE)
1065 # w.ori <- E(g.ori)$weight
1067 # if (method == 'cooc') {
1068 # E(g.ori)$weight <- 1 / w.ori
1070 # E(g.ori)$weigth <- 1 - w.ori
1072 # g.max <- minimum.spanning.tree(g.ori)
1073 # if (method == 'cooc') {
1074 # E(g.max)$weight <- 1 / E(g.max)$weight
1076 # E(g.max)$weight <- 1 - E(g.max)$weight
1083 if self.parametres['com']:
1084 com = repr(self.parametres['communities'])
1087 if self.parametres['halo']:
1097 x <- list(mat = mat, eff = eff)
1098 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)
1099 """ % (method, type, layout, arbremax, coeff_tv, coeff_te)
1100 if self.parametres.get('bystar',False):
1101 if self.parametres.get('cexfromchi', False):
1103 label.cex<-chivertex.size
1109 if self.parametres.get('sfromchi', False):
1111 vertex.size <- norm.vec(toblack, minmaxeff[1], minmaxeff[2])
1118 #print self.parametres
1119 if (self.parametres['type'] == 'clustersimitxt' and self.parametres.get('tmpchi', False)) or (self.parametres['type'] in ['simimatrix','simiclustermatrix'] and 'tmpchi' in self.parametres):
1121 lchi <- read.table("%s")
1123 """ % ffr(self.parametres['tmpchi'])
1125 lchi <- lchi[sel.col]
1127 if self.parametres['type'] in ['clustersimitxt', 'simimatrix', 'simiclustermatrix'] and self.parametres.get('cexfromchi', False):
1129 label.cex <- norm.vec(lchi, vcexminmax[1], vcexminmax[2])
1133 if (is.null(vcexminmax[1])) {
1136 label.cex <- graph.simi$label.cex
1139 if (self.parametres['type'] in ['clustersimitxt', 'simimatrix', 'simiclustermatrix']) and self.parametres.get('sfromchi', False):
1141 vertex.size <- norm.vec(lchi, minmaxeff[1], minmaxeff[2])
1142 if (!length(vertex.size)) vertex.size <- 0
1146 if (is.null(minmaxeff[1])) {
1149 vertex.size <- graph.simi$eff
1152 #txt += """ vertex.size <- NULL """
1153 if self.parametres['svg']:
1163 if (col.from.proto) {
1164 proto.col <- read.table('/tmp/matcol.csv')
1165 v.proto.names <- make.names(proto.col[,1])
1166 v.proto.col <- as.character(proto.col[,2])
1167 v.proto.col[which(v.proto.col=='black')] <- 'yellow'
1168 v.names <- V(graph.simi$graph)$name
1169 num.color <- sapply(v.names, function(x) {if (x %%in%% v.proto.names) {v.proto.col[which(v.proto.names==x)]} else {'pink'}})
1170 vertex.col <- num.color
1171 V(graph.simi$graph)$proto.color <- vertex.col
1173 if (!is.null(graph.simi$com)) {
1174 com <- graph.simi$com
1175 colm <- rainbow(length(com))
1176 if (sum(vertex.size) != 0 || graph.simi$halo) {
1177 vertex.label.color <- 'black'
1178 vertex.col <- colm[membership(com)]
1180 vertex.label.color <- colm[membership(com)]
1183 if (!length(graph.simi$elim)==0) {
1184 vertex.label.color <- vertex.label.color[-graph.simi$elim]
1185 if (length(label.cex > 1)) {
1186 label.cex <- label.cex[-graph.simi$elim]
1189 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)
1190 save.image(file="%s")
1191 """ % (type, self.filename, ffr(self.pathout['RData']))
1196 class WordCloudRScript(PrintRScript):
1198 def make_script(self):
1199 self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1200 self.packages(['wordcloud'])
1201 bg_col = Rcolor(self.parametres['col_bg'])
1202 txt_col = Rcolor(self.parametres['col_text'])
1203 if self.parametres['svg']:
1211 act <- read.csv2("%s", header = FALSE, row.names=1, sep='\t')
1212 selected.col <- read.table("%s")
1213 toprint <- as.matrix(act[selected.col[,1] + 1,])
1214 rownames(toprint) <- rownames(act)[selected.col[,1] + 1]
1216 if (nrow(toprint) > maxword) {
1217 toprint <- as.matrix(toprint[order(toprint[,1], decreasing=TRUE),])
1218 toprint <- as.matrix(toprint[1:maxword,])
1220 open_file_graph("%s", width = %i, height = %i , svg = svg)
1222 wordcloud(row.names(toprint), toprint[,1], scale=c(%f,%f), random.order=FALSE, colors=rgb%s)
1224 """ % (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)
1229 class ProtoScript(PrintRScript):
1231 def make_script(self):
1232 self.sources([self.analyse.parent.RscriptsPath['Rgraph'], self.analyse.parent.RscriptsPath['prototypical.R']])
1233 self.packages(['wordcloud'])
1234 if self.parametres.get('cloud', False):
1239 errorn <- function(x) {
1240 qnorm(0.975)*sd(x)/sqrt(lenght(n))
1242 errort <- function(x) {
1243 qt(0.975,df=lenght(x)-1)*sd(x)/sqrt(lenght(x))
1245 mat <- read.csv2("%s", header = FALSE, row.names=1, sep='\t', quote='"', dec='.')
1246 open_file_graph("%s",height=800, width=1000)
1247 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')
1249 """ % (ffr(self.analyse.pathout['table.csv']), ffr(self.analyse.pathout['proto.png']), self.parametres['limfreq'], self.parametres['limrang'], self.parametres['typegraph'])
1254 class ExportAfc(PrintRScript):
1256 def make_script(self):
1257 self.source([self.analyse.parent.RscriptsPath['Rgraph']])
1258 self.packages(['rgexf'])
1263 class MergeGraphes(PrintRScript):
1265 def __init__(self, analyse):
1266 self.script = "#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):
1281 g <- graph.simi$graph
1282 V(g)$weight <- (graph.simi$mat.eff/nrow(dm))*100
1285 for i, graph in enumerate(self.parametres['graphs']):
1286 path = os.path.dirname(graph)
1287 gname = ''.join(['g', repr(i)])
1288 RData = os.path.join(path,'RData.RData')
1289 txt += load % (ffr(RData), gname)
1291 self.sources([self.analyse.parent.RscriptsPath['simi']])
1293 merge.type <- 'proto'
1294 if (merge.type == 'normal') {
1295 ng <- merge.graph(graphs)
1297 ng <- merge.graph.proto(graphs)
1299 ngraph <- list(graph=ng, layout=layout.fruchterman.reingold(ng, dim=3), labex.cex=V(ng)$weight)
1300 write.graph(ng, "%s", format = 'graphml')
1301 """ % ffr(self.parametres['grapheout'])
1305 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'])
1328 class TgenProfScript(PrintRScript):
1330 def make_script(self):
1331 self.sources([self.analyse.ira.RscriptsPath['chdfunct']])
1333 tgen <- read.csv2("%s", row.names = 1, sep = '\\t')
1334 """ % ffr(self.parametres['tgeneff'])
1336 tgenlem <- read.csv2("%s", row.names = 1, sep = '\\t')
1337 """ % ffr(self.parametres['tgenlemeff'])
1339 res <- build.prof.tgen(tgen)
1340 write.table(res$chi2, file = "%s", sep='\\t', col.names = NA)
1341 write.table(res$pchi2, file = "%s", sep='\\t', col.names = NA)
1342 """ % (ffr(self.pathout['tgenchi2.csv']), ffr(self.pathout['tgenpchi2.csv']))
1344 reslem <- build.prof.tgen(tgenlem)
1345 write.table(reslem$chi2, file = "%s", sep='\\t', col.names = NA)
1346 write.table(reslem$pchi2, file = "%s", sep='\\t', col.names = NA)
1347 """ % (ffr(self.pathout['tgenlemchi2.csv']), ffr(self.pathout['tgenlempchi2.csv']))
1351 class FreqMultiScript(PrintRScript):
1353 def make_script(self):
1354 self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1356 freq <- read.csv2("%s", row.names=1, sep='\\t', dec='.')
1357 """ % ffr(self.pathout['frequences.csv'])
1359 toplot <- freq[order(freq[,2]) ,2]
1360 toplot.names = rownames(freq)[order(freq[,2])]
1361 h <- 80 + (20 * nrow(freq))
1362 open_file_graph("%s",height=h, width=500)
1363 par(mar=c(3,20,3,3))
1364 barplot(toplot, names = toplot.names, horiz=TRUE, las =1, col = rainbow(nrow(freq)))
1366 """ % ffr(self.pathout['barplotfreq.png'])
1368 toplot <- freq[order(freq[,4]) ,4]
1369 toplot.names = rownames(freq)[order(freq[,4])]
1370 open_file_graph("%s",height=h, width=500)
1371 par(mar=c(3,20,3,3))
1372 barplot(toplot, names = toplot.names, horiz=TRUE, las =1, col = rainbow(nrow(freq)))
1374 """ % ffr(self.pathout['barplotrow.png'])
1379 class LabbeScript(PrintRScript):
1381 def make_script(self):
1382 self.sources([self.analyse.parent.RscriptsPath['distance-labbe.R'],
1383 self.analyse.parent.RscriptsPath['Rgraph']])
1385 tab <- read.csv2("%s", header=TRUE, sep=';', row.names=1)
1386 """ % (ffr(self.pathout['tableafcm.csv']))
1388 dist.mat <- dist.labbe(tab)
1389 dist.mat <- as.dist(dist.mat, upper=F, diag=F)
1390 write.table(as.matrix(dist.mat), "%s", sep='\t')
1393 chd <- hclust(dist.mat, method="ward.D2")
1394 open_file_graph("%s", width=1000, height=1000, svg=F)
1396 plot.phylo(as.phylo(chd), type='unrooted', lab4ut="axial")
1398 """ % (ffr(self.pathout['distmat.csv']), ffr(self.pathout['labbe-tree.png']))
1400 open_file_graph("%s", width=1000, height=1000, svg=F)
1401 par(mar=c(10,1,1,10))
1402 heatmap(as.matrix(dist.mat), symm = T, distfun=function(x) as.dist(x), margins=c(10,10))
1404 """ % ffr(self.pathout['labbe-heatmap.png'])
1406 #http://stackoverflow.com/questions/3081066/what-techniques-exists-in-r-to-visualize-a-distance-matrix
1407 dst <- data.matrix(dist.mat)
1409 rn <- row.names(as.matrix(dist.mat))
1410 open_file_graph("%s", width=1500, height=1000, svg=F)
1411 par(mar=c(10,10,3,3))
1412 image(1:dim, 1:dim, dst, axes = FALSE, xlab="", ylab="", col=heat.colors(99), breaks=seq(0.01,1,0.01))
1413 axis(1, 1:dim, rn, cex.axis = 0.9, las=3)
1414 axis(2, 1:dim, rn, cex.axis = 0.9, las=1)
1415 text(expand.grid(1:dim, 1:dim), sprintf("%%0.2f", dst), cex=0.6)
1417 """ % ffr(self.pathout['labbe-matrix.png'])
1420 g <- graph.adjacency(as.matrix(1-dist.mat), mode="lower", weighted=T)
1421 write.graph(g, file="%s", format='graphml')
1422 open_file_graph("%s", width=1000, height=1000, svg=F)
1425 E(g)$weight <- 1 - E(g)$weight
1426 g <- minimum.spanning.tree(g)
1427 E(g)$weight <- 1 - E(g)$weight
1428 write.graph(g, file="%s", format='graphml')
1429 open_file_graph("%s", width=1000, height=1000, svg=F)
1432 """ % (ffr(self.pathout['graph_tot.graphml']), ffr(self.pathout['graph_tot.png']), ffr(self.pathout['graph_min.graphml']), ffr(self.pathout['graph_min.png']))
1437 class ChronoChi2Script(PrintRScript):
1439 def make_script(self):
1440 self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1441 print(self.parametres)
1447 """ % (ffr(self.pathout['RData.RData']), ffr(self.pathout['dendrogramme.RData']))
1450 """ % self.parametres['svg']
1452 tc <- which(grepl("%s",rownames(chistabletot)))
1453 rn <- rownames(chistabletot)[tc]
1455 dpt <- chistabletot[tc,]
1456 tot <- afctable[tc,]
1461 """ % self.parametres['var'].replace('*', "\\\\*")
1463 classes <- n1[,ncol(n1)]
1464 tcl <- table(classes)
1465 if ('0' %in% names(tcl)) {
1466 to.vire <- which(names(tcl) == '0')
1467 tcl <- tcl[-to.vire]
1469 tclp <- tcl/sum(tcl)
1476 lcol <- c(lcol, qchisq(1-k,1))
1480 lcol <- c(3.84, lcol)
1481 lcol <- c(-Inf,lcol)
1482 lcol <- c(lcol, Inf)
1485 alphas <- seq(0,1, length.out=length(breaks))
1486 clod <- rev(as.numeric(tree.cut1$tree.cl$tip.label))
1490 open_file_graph("%s", w=%i, h=%i, svg=svg)
1491 """ % (ffr(self.parametres['tmpgraph']), self.parametres['width'], self.parametres['height'])
1494 mat.graphic <- matrix(c(rep(1,nrow(dd)),c(2:(nrow(dd)+1))), ncol=2)
1495 mat.graphic <- rbind(mat.graphic, c(max(mat.graphic) + 1 , max(mat.graphic) + 2))
1496 hauteur <- tclp[clod] * 0.9
1497 heights.graphic <- append(hauteur, 0.1)
1498 layout(mat.graphic, heights=heights.graphic, widths=c(0.15,0.85))
1500 tree.toplot <- tree.cut1$tree.cl
1501 num.label <- as.numeric(tree.cut1$tree.cl$tip.label)
1502 col.tree <- rainbow(length(num.label))[num.label]
1503 #tree.toplot$tip.label <- paste('classe ', tree.toplot$tip.label)
1504 plot.phylo(tree.toplot,label.offset=0.1, cex=1.1, no.margin=T, tip.color = col.tree)
1508 lcol <- cut(dd[i,], breaks, include.lowest=TRUE)
1509 ulcol <- names(table(lcol))
1510 lcol <- as.character(lcol)
1511 for (j in 1:length(ulcol)) {
1512 lcol[which(lcol==ulcol[j])] <- j
1514 lcol <- as.numeric(lcol)
1515 mcol <- rainbow(nrow(dd))[i]
1518 last.col <- c(last.col, rgb(r=col2rgb(mcol)[1]/255, g=col2rgb(mcol)[2]/255, b=col2rgb(mcol)[3]/255, a=k))
1521 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))
1523 plot(0,type='n',axes=FALSE,ann=FALSE)
1524 label.coords <- barplot(rep(1, ncol(dd)), width=ptc, names.arg = F, las=2, axes=F, ylim=c(0,1), plot=T, col='white')
1525 text(x=label.coords, y=0.5, labels=rn[order(rn)], srt=90)
1532 class ChronoPropScript(PrintRScript):
1534 def make_script(self):
1535 self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1536 print(self.parametres)
1542 """ % (ffr(self.pathout['RData.RData']), ffr(self.pathout['dendrogramme.RData']))
1545 """ % self.parametres['svg']
1547 tc <- which(grepl("%s",rownames(chistabletot)))
1548 rn <- rownames(chistabletot)[tc]
1550 dpt <- chistabletot[tc,]
1551 tot <- afctable[tc,]
1556 """ % self.parametres['var'].replace('*', "\\\\*")
1558 classes <- n1[,ncol(n1)]
1559 tcl <- table(classes)
1560 if ('0' %in% names(tcl)) {
1561 to.vire <- which(names(tcl) == '0')
1562 tcl <- tcl[-to.vire]
1564 tclp <- tcl/sum(tcl)
1567 open_file_graph("%s", w=%i, h=%i, svg=svg)
1568 """ % (ffr(self.parametres['tmpgraph']), self.parametres['width'], self.parametres['height'])
1570 ptt <- prop.table(as.matrix(tot), 1)
1571 par(mar=c(10,2,2,2))
1572 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)
1579 class ChronoggScript(PrintRScript):
1581 def make_script(self):
1582 self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1583 print(self.parametres)
1590 """ % (ffr(self.pathout['RData.RData']), ffr(self.pathout['dendrogramme.RData']))
1593 """ % self.parametres['svg']
1595 tc <- which(grepl("%s",rownames(chistabletot)))
1596 rn <- rownames(chistabletot)[tc]
1598 dpt <- chistabletot[tc,]
1599 tot <- afctable[tc,]
1604 """ % self.parametres['var'].replace('*', "\\\\*")
1606 classes <- n1[,ncol(n1)]
1607 tcl <- table(classes)
1608 if ('0' %in% names(tcl)) {
1609 to.vire <- which(names(tcl) == '0')
1610 tcl <- tcl[-to.vire]
1612 tclp <- tcl/sum(tcl)
1613 ptt <- prop.table(as.matrix(tot), 1)
1614 ptt <- ptt[,as.numeric(tree.cut1$tree.cl$tip.label)]
1615 rownames(ptt) <- cumsum(ptc)
1616 nptt<-as.data.frame(as.table(ptt))
1617 nptt[,1]<-as.numeric(as.character(nptt[,1]))
1618 col <- rainbow(ncol(ptt))[as.numeric(tree.cut1$tree.cl$tip.label)]
1621 open_file_graph("%s", w=%i, h=%i, svg=svg)
1622 """ % (ffr(self.parametres['tmpgraph']), self.parametres['width'], self.parametres['height'])
1624 par(mar=c(10,2,2,2))
1625 gg <- ggplot(data=nptt, aes(x=Var1,y=Freq,fill=Var2)) + geom_area(alpha=1 , size=0.5, colour="black")
1626 gg + scale_fill_manual(values=col)
1633 class DendroScript(PrintRScript):
1635 def make_script(self):
1636 if self.parametres['svg']:
1640 fileout = self.parametres['fileout']
1641 width = self.parametres['width']
1642 height = self.parametres['height']
1643 type_dendro = self.parametres['dendro_type']
1644 if self.parametres['taille_classe']:
1648 if self.parametres['color_nb'] == 0:
1652 if self.parametres['type_tclasse'] == 0:
1656 if self.parametres['svg']:
1660 dendro_path = self.pathout['Rdendro']
1661 classe_path = self.pathout['uce']
1666 classes <- read.csv2("%s", row.names=1)
1667 classes <- classes[,1]
1668 """ % (ffr(dendro_path), ffr(self.parametres['Rgraph']), ffr(classe_path))
1669 if self.parametres['dendro'] == 'simple':
1671 open_file_graph("%s", width=%i, height=%i, svg=%s)
1672 plot.dendropr(tree.cut1$tree.cl, classes, type.dendro="%s", histo=%s, bw=%s, lab=NULL, tclasse=%s)
1673 """ % (ffr(fileout), width, height, svg, type_dendro, histo, bw, tclasse)
1674 elif self.parametres['dendro'] == 'texte':
1678 if (is.null(debsup)) {
1681 chistable <- chistabletot[1:(debsup-1),]
1682 """ % (ffr(self.pathout['RData.RData']), ffr(self.parametres['Rgraph']))
1683 if self.parametres.get('translation', False):
1685 rn <- read.csv2("%s", header=FALSE, sep='\t')
1686 rnchis <- row.names(chistable)
1687 commun <- intersect(rnchis, unique(rn[,2]))
1688 idrnchis <- sapply(commun, function(x) {which(rnchis==x)})
1689 idrn <- sapply(commun, function(x) {which(as.vector(rn[,2])==x)[1]})
1690 rownames(chistable)[idrnchis] <- as.vector(rn[idrn,1])
1691 """ % ffr(self.parametres['translation'])
1693 open_file_graph("%s", width=%i, height=%i, svg = %s)
1694 plot.dendro.prof(tree.cut1$tree.cl, classes, chistable, nbbycl = 60, type.dendro="%s", bw=%s, lab=NULL)
1695 """ % (ffr(fileout), width, height, svg, type_dendro, bw)
1696 elif self.parametres['dendro'] == 'cloud':
1700 if (is.null(debsup)) {
1703 chistable <- chistabletot[1:(debsup-1),]
1704 open_file_graph("%s", width=%i, height=%i, svg=%s)
1705 plot.dendro.cloud(tree.cut1$tree.cl, classes, chistable, nbbycl = 300, type.dendro="%s", bw=%s, lab=NULL)
1706 """ % (ffr(self.pathout['RData.RData']), ffr(self.parametres['Rgraph']), ffr(fileout), width, height, svg, type_dendro, bw)
1711 class ReDoProfScript(PrintRScript):
1713 def make_script(self):
1714 self.sources([self.analyse.parent.RscriptsPath['chdfunct.R']])
1715 print(self.parametres)