1 # -*- coding: utf-8 -*-
2 #Author: Pierre Ratinaud
3 #Copyright (c) 2008-2011 Pierre Ratinaud
6 #------------------------------------
7 # import des modules python
8 #------------------------------------
12 from datetime import datetime
15 #------------------------------------
16 # import des fichiers du projet
17 #------------------------------------
18 from chemins import ffr, PathOut
21 log = logging.getLogger('iramuteq.printRscript')
26 def __init__ (self, analyse, parametres = None):
28 self.pathout = analyse.pathout
29 self.analyse = analyse
30 if parametres is None:
31 self.parametres = analyse.parametres
33 self.parametres = parametres
34 #self.scriptout = ffr(self.pathout['lastRscript.R'])
35 self.scriptout = self.pathout['temp']
36 self.script = "#Script genere par IRaMuTeQ - %s\n" % datetime.now().ctime()
39 self.script = '\n'.join([self.script, txt])
41 def defvar(self, name, value):
42 self.add(' <- '.join([name, value]))
44 def defvars(self, lvars):
46 self.defvar(val[0],val[1])
48 def sources(self, lsources):
49 for source in lsources:
50 self.add('source("%s", encoding = \'utf8\')' % ffr(source))
52 def packages(self, lpks):
54 self.add('library(%s)' % pk)
58 self.add('load("%s")' % ffr(val))
61 with open(self.scriptout, 'w', encoding='utf8') as f:
66 class chdtxt(PrintRScript):
71 return str(color).replace(')', ', max=255)')
74 class Alceste2(PrintRScript):
77 self.sources(['chdfunct'])
79 lvars = [['clnb', repr(self.analyse.clnb)],
80 ['Contout', '"%s"' % self.pathout['Contout']],
81 ['ContSupOut', '"%s"' % self.pathout['ContSupOut']],
82 ['ContEtOut', '"%s"' % self.pathout['ContEtOut']],
83 ['profileout', '"%s"' % self.pathout['profils.csv']],
84 ['antiout', '"%s"' % self.pathout['antiprofils.csv']],
85 ['chisqtable', '"%s"' % self.pathout['chisqtable.csv']],
86 ['ptable', '"%s"' % self.pathout['ptable.csv']]]
90 # txt = "clnb<-%i\n" % clnb
94 #""" % (RscriptsPath['chdfunct'], DictChdTxtOut['RData'])
96 #dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
97 #datasup<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
98 #dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
99 #""" % (DictChdTxtOut['Contout'], DictChdTxtOut['ContSupOut'], DictChdTxtOut['ContEtOut'])
101 #tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
102 #tablesqrpsup<-BuildProf(as.matrix(datasup),n1,clnb)
103 #tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
106 #PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s",tablesqrpsup[4],tablesqrpsup[5])
107 #""" % (DictChdTxtOut['PROFILE_OUT'], DictChdTxtOut['ANTIPRO_OUT'])
109 #colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
110 #colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
111 #colnames(tablesqrpsup[[2]])<-paste('classe',1:clnb,sep=' ')
112 #colnames(tablesqrpsup[[1]])<-paste('classe',1:clnb,sep=' ')
113 #colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
114 #colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
115 #chistabletot<-rbind(tablesqrpact[2][[1]],tablesqrpsup[2][[1]])
116 #chistabletot<-rbind(chistabletot,tablesqrpet[2][[1]])
117 #ptabletot<-rbind(tablesqrpact[1][[1]],tablesqrpet[1][[1]])
120 #write.csv2(chistabletot,file="%s")
121 #write.csv2(ptabletot,file="%s")
123 #write.csv2(gbcluster,file="%s")
124 #""" % (DictChdTxtOut['chisqtable'], DictChdTxtOut['ptable'], DictChdTxtOut['SbyClasseOut'])
128 def RchdTxt(DicoPath, RscriptPath, mincl, classif_mode, nbt = 9, svdmethod = 'svdR', libsvdc = False, libsvdc_path = None, R_max_mem = False, mode_patate = False, nbproc=10):
134 """ % (ffr(RscriptPath['CHD']), ffr(RscriptPath['chdtxt']), ffr(RscriptPath['anacor']), ffr(RscriptPath['Rgraph']))
142 if svdmethod == 'svdlibc' and libsvdc:
144 svd.method <- 'svdlibc'
146 """ % ffr(libsvdc_path)
147 elif svdmethod == 'irlba':
150 svd.method <- 'irlba'
168 data1 <- readMM("%s")
169 data1 <- as(data1, "dgCMatrix")
170 row.names(data1) <- 1:nrow(data1)
171 """ % ffr(DicoPath['TableUc1'])
172 if classif_mode == 0:
174 data2 <- readMM("%s")
175 data2 <- as(data2, "dgCMatrix")
176 row.names(data2) <- 1:nrow(data2)
177 """ % ffr(DicoPath['TableUc2'])
180 #print('FIXME : source newCHD')
181 #source('/home/pierre/workspace/iramuteq/Rscripts/newCHD.R')
183 #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)
184 chd1<-CHD(data1, x = nbt, mode.patate = mode.patate, svd.method = svd.method, libsvdc.path = libsvdc.path)#, log.file = log1)
185 """ % (ffr(DicoPath['log-chd1.txt']), nbproc)
186 if classif_mode == 0:
189 chd2<-CHD(data2, x = nbt, mode.patate = mode.patate, svd.method =
190 svd.method, libsvdc.path = libsvdc.path)#, log.file = log2)
191 """ % ffr(DicoPath['log-chd2.txt'])
194 listuce1<-read.csv2("%s")
195 """ % ffr(DicoPath['listeuce1'])
196 if classif_mode == 0:
198 listuce2<-read.csv2("%s")
199 """ % ffr(DicoPath['listeuce2'])
203 if classif_mode == 0:
210 if (mincl == 0) {mincl <- round(nrow(chd1$n1)/(nbt+1))}
212 write.csv2(chd1$n1, file="%s")
213 if (classif_mode == 0) {
214 chd.result <- Rchdtxt(uceout, chd1, chd2 = chd2, mincl = mincl,classif_mode = classif_mode, nbt = nbt)
215 classeuce1 <- chd.result$cuce1
216 tree.tot1 <- make_tree_tot(chd1)
217 tree.cut1 <- make_dendro_cut_tuple(tree.tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
219 #chd.result <- Rchdtxt(uceout, chd1, chd2 = chd1, mincl = mincl,classif_mode = classif_mode, nbt = nbt)
220 tree.tot1 <- make_tree_tot(chd1)
221 terminales <- find.terminales(chd1$n1, chd1$list_mere, chd1$list_fille, mincl)
222 tree.cut1 <- make.classes(terminales, chd1$n1, tree.tot1$tree.cl, chd1$list_fille)
223 write.csv2(tree.cut1$n1, uceout)
224 chd.result <- tree.cut1
226 classes<-chd.result$n1[,ncol(chd.result$n1)]
227 write.csv2(chd.result$n1, file="%s")
228 """ % (classif_mode, mincl, ffr(DicoPath['uce']), ffr(DicoPath['n1-1.csv']), ffr(DicoPath['n1.csv']))
230 # tree.tot1 <- make_tree_tot(chd1)
231 # open_file_graph("%s", widt = 600, height=400)
232 # plot(tree.tot1$tree.cl)
234 """ % ffr(DicoPath['arbre1'])
235 if classif_mode == 0:
237 classeuce2 <- chd.result$cuce2
238 tree.tot2 <- make_tree_tot(chd2)
239 # open_file_graph("%s", width = 600, height=400)
240 # plot(tree.tot2$tree.cl)
242 """ % ffr(DicoPath['arbre2'] )
244 save(tree.cut1, file="%s")
246 open_file_graph("%s", width = 600, height=400)
247 plot.dendropr(tree.cut1$tree.cl,classes, histo=TRUE)
248 open_file_graph("%s", width = 600, height=400)
249 plot(tree.cut1$dendro_tot_cl)
251 """ % (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']))
263 #save.image(file="%s")
264 """ % (ffr(DicoPath['RData']))
265 fileout = open(DicoPath['Rchdtxt'], 'w', encoding='utf8')
269 def RPamTxt(corpus, RscriptPath):
270 DicoPath = corpus.pathout
271 param = corpus.parametres
274 """ % (RscriptPath['pamtxt'])
277 """ % (RscriptPath['Rgraph'])
279 result <- pamtxt("%s", "%s", "%s", method = "%s", clust_type = "%s", clnb = %i)
281 """ % (DicoPath['TableUc1'], DicoPath['listeuce1'], DicoPath['uce'], param['method'], param['cluster_type'], param['nbcl'] )
283 open_file_graph("%s", width=400, height=400)
286 """ % (DicoPath['arbre1'])
288 save.image(file="%s")
289 """ % DicoPath['RData']
290 fileout = open(DicoPath['Rchdtxt'], 'w', encoding='utf8')
294 def RchdQuest(DicoPath, RscriptPath, nbcl = 10, mincl = 10):
300 """ % (ffr(RscriptPath['CHD']), ffr(RscriptPath['chdquest']), ffr(RscriptPath['anacor']),ffr(RscriptPath['Rgraph']))
306 chd.result<-Rchdquest("%s","%s","%s", nbt = nbt, mincl = mincl)
308 classeuce1 <- chd.result$cuce1
309 """ % (ffr(DicoPath['mat01.csv']), ffr(DicoPath['listeuce1']), ffr(DicoPath['uce']))
311 tree_tot1 <- make_tree_tot(chd.result$chd)
312 open_file_graph("%s", width = 600, height=400)
313 plot(tree_tot1$tree.cl)
315 """ % ffr(DicoPath['arbre1'])
317 tree_cut1 <- make_dendro_cut_tuple(tree_tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
318 tree.cut1 <- tree_cut1
319 save(tree.cut1, file="%s")
320 open_file_graph("%s", width = 600, height=400)
321 classes<-n1[,ncol(n1)]
322 plot.dendropr(tree_cut1$tree.cl,classes, histo = TRUE)
323 """ % (ffr(DicoPath['Rdendro']), ffr(DicoPath['dendro1']))
325 save.image(file="%s")
326 """ % ffr(DicoPath['RData'])
327 fileout = open(DicoPath['Rchdquest'], 'w', encoding='utf8')
331 def ReinertTxtProf(DictChdTxtOut, RscriptsPath, clnb, taillecar):
332 txt = "clnb<-%i\n" % clnb
336 n1 <- read.csv2("%s")
337 """ % (ffr(RscriptsPath['chdfunct']), ffr(DictChdTxtOut['RData']), ffr(DictChdTxtOut['n1.csv']))
339 dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
340 datasup<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
341 dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
342 """ % (ffr(DictChdTxtOut['Contout']), ffr(DictChdTxtOut['ContSupOut']), ffr(DictChdTxtOut['ContEtOut']))
344 print('ATTENTION NEW BUILD PROF')
345 #tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
346 #tablesqrpsup<-BuildProf(as.matrix(datasup),n1,clnb)
347 #tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
348 tablesqrpact<-new.build.prof(as.matrix(dataact),n1,clnb)
349 tablesqrpsup<-new.build.prof(as.matrix(datasup),n1,clnb)
350 tablesqrpet<-new.build.prof(as.matrix(dataet),n1,clnb)
353 PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s",tablesqrpsup[4],tablesqrpsup[5])
354 """ % (ffr(DictChdTxtOut['PROFILE_OUT']), ffr(DictChdTxtOut['ANTIPRO_OUT']))
356 colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
357 colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
358 colnames(tablesqrpsup[[2]])<-paste('classe',1:clnb,sep=' ')
359 colnames(tablesqrpsup[[1]])<-paste('classe',1:clnb,sep=' ')
360 colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
361 colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
362 chistabletot<-rbind(tablesqrpact[2][[1]],tablesqrpsup[2][[1]])
363 chistabletot<-rbind(chistabletot,tablesqrpet[2][[1]])
364 ptabletot<-rbind(tablesqrpact[1][[1]],tablesqrpet[1][[1]])
367 write.csv2(chistabletot,file="%s")
368 write.csv2(ptabletot,file="%s")
370 write.csv2(gbcluster,file="%s")
371 """ % (ffr(DictChdTxtOut['chisqtable']), ffr(DictChdTxtOut['ptable']), ffr(DictChdTxtOut['SbyClasseOut']))
375 colnames(dataact)<-paste('classe',1:clnb,sep=' ')
376 colnames(datasup)<-paste('classe',1:clnb,sep=' ')
377 colnames(dataet)<-paste('classe',1:clnb,sep=' ')
378 rowtot<-nrow(dataact)+nrow(dataet)+nrow(datasup)
379 afctable<-rbind(as.matrix(dataact),as.matrix(datasup))
380 afctable<-rbind(afctable,as.matrix(dataet))
381 colnames(afctable)<-paste('classe',1:clnb,sep=' ')
382 afc<-ca(afctable,suprow=((nrow(dataact)+1):rowtot),nd=(ncol(afctable)-1))
383 debsup<-nrow(dataact)+1
384 debet<-nrow(dataact)+nrow(datasup)+1
386 afc<-AddCorrelationOk(afc)
388 #FIXME : split this!!!
391 """ % ffr(RscriptsPath['Rgraph'])
393 afc <- summary.ca.dm(afc)
394 afc_table <- create_afc_table(afc)
395 write.csv2(afc_table$facteur, file = "%s")
396 write.csv2(afc_table$colonne, file = "%s")
397 write.csv2(afc_table$ligne, file = "%s")
398 """ % (ffr(DictChdTxtOut['afc_facteur']), ffr(DictChdTxtOut['afc_col']), ffr(DictChdTxtOut['afc_row']))
403 xyminmax <- PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
404 """ % (ffr(DictChdTxtOut['AFC2DL_OUT']))
406 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)
407 """ % (ffr(DictChdTxtOut['AFC2DSL_OUT']))
409 if ((fin - debet) > 2) {
410 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)
412 """ % (ffr(DictChdTxtOut['AFC2DEL_OUT']))
414 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)
415 """ % (ffr(DictChdTxtOut['AFC2DCL_OUT']))
417 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
418 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debsup, fin=(debet-1), xlab = xlab, ylab = ylab)
419 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debet, fin=fin, xlab = xlab, ylab = ylab)
420 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col=TRUE, what='crl', xlab = xlab, ylab = ylab)
421 # """ % (DictChdTxtOut['AFC2DCoul'], DictChdTxtOut['AFC2DCoulSup'], DictChdTxtOut['AFC2DCoulEt'], DictChdTxtOut['AFC2DCoulCl'])
429 save.image(file="%s")
430 """ % ffr(DictChdTxtOut['RData'])
431 file = open(DictChdTxtOut['RTxtProfGraph'], 'w', encoding='utf8')
435 def write_afc_graph(self):
436 if self.param['over']:
440 if self.param['do_select_nb']:
441 do_select_nb = 'TRUE'
443 do_select_nb = 'FALSE'
444 if self.param['do_select_chi']:
445 do_select_chi = 'TRUE'
447 do_select_chi = 'FALSE'
448 if self.param['do_select_chi_classe']:
449 do_select_chi_classe = 'TRUE'
451 do_select_chi_classe = 'FALSE'
452 if self.param['cex_txt']:
456 if self.param['tchi']:
460 if self.param['svg']:
464 if self.param['typegraph'] == 4:
465 nodesfile = os.path.join(os.path.dirname(self.fileout),'nodes.csv')
466 edgesfile = os.path.join(os.path.dirname(self.fileout),'edges.csv')
470 with open(self.RscriptsPath['afc_graph'], 'r', encoding='utf8') as f:
472 # self.DictPathOut['RData'], \
473 scripts = txt % (ffr(self.RscriptsPath['Rgraph']),\
474 self.param['typegraph'], \
475 edgesfile, nodesfile, \
476 self.param['what'], \
477 self.param['facteur'][0],\
478 self.param['facteur'][1], \
479 self.param['facteur'][2], \
481 over, do_select_nb, \
482 self.param['select_nb'], \
484 self.param['select_chi'], \
485 do_select_chi_classe, \
486 self.param['nbchic'], \
488 self.param['txt_min'], \
489 self.param['txt_max'], \
491 self.param['width'], \
492 self.param['height'],\
493 self.param['taillecar'], \
494 self.param['alpha'], \
495 self.param['film'], \
497 self.param['tchi_min'],\
498 self.param['tchi_max'],\
499 ffr(os.path.dirname(self.fileout)),\
503 def print_simi3d(self):
504 simi3d = self.parent.simi3dpanel
505 txt = '#Fichier genere par Iramuteq'
506 if simi3d.movie.GetValue():
507 movie = "'" + ffr(os.path.dirname(self.DictPathOut['RData'])) + "'"
510 #if self.corpus.parametres['type'] == 'corpus':
516 dm<-read.csv2("%s",row.names=1,header = %s)
518 """ % (self.DictPathOut['Contout'], header, self.DictPathOut['RData'])
521 """ % self.parent.RscriptsPath['Rgraph']
523 make.simi.afc(dm,chistabletot, lim=%i, alpha = %.2f, movie = %s)
524 """ % (simi3d.spin_1.GetValue(), float(simi3d.slider_1.GetValue())/100, movie)
525 tmpfile = tempfile.mktemp(dir=self.parent.TEMPDIR)
526 tmp = open(tmpfile,'w', encoding='utf8')
531 def dendroandbarplot(table, rownames, colnames, rgraph, tmpgraph, intxt = False, dendro=False):
533 txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
534 rownb = len(rownames)
535 rownames = 'c("' + '","'.join(rownames) + '")'
536 colnames = 'c("' + '","'.join(colnames) + '")'
540 di <- matrix(data=%s, nrow=%i, byrow = TRUE)
543 """ % (txttable, rownb, rownames, colnames)
550 height <- (30*ncol(di)) + (15*nrow(di))
551 height <- ifelse(height <= 400, 400, height)
553 open_file_graph("%s", width=width, height=height)
554 plot.dendro.lex(tree.cut1$tree.cl, di)
555 """ % (ffr(dendro),ffr(rgraph), ffr(tmpgraph))
558 def barplot(table, parametres, intxt = False):
560 txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
561 #width = 100 + (15 * len(rownames)) + (100 * len(colnames))
562 #height = len(rownames) * 15
563 rownb = len(parametres['rownames'])
566 rownames = 'c("' + '","'.join(parametres['rownames']) + '")'
567 colnames = 'c("' + '","'.join(parametres['colnames']) + '")'
571 di <- matrix(data=%s, nrow=%i, byrow = TRUE)
572 toinf <- which(di == Inf)
573 tominf <- which(di == -Inf)
576 valmax <- max(di, na.rm = TRUE)
584 if (length(tominf)) {
586 valmin <- min(di, na.rm = TRUE)
596 """ % (txttable, rownb, rownames, colnames)
599 if not 'tree' in parametres:
602 color = rainbow(nrow(di))
605 open_file_graph("%s",width = width, height = height, svg = %s)
607 layout(matrix(c(1,2),1,2, byrow=TRUE),widths=c(3,lcm(12)))
609 yp = ifelse(length(toinf), 0.2, 0)
610 ym = ifelse(length(tominf), 0.2, 0)
611 ymin <- ifelse(!length(which(di < 0)), 0, min(di) - ym)
612 coord <- barplot(as.matrix(di), beside = TRUE, col = color, space = c(0.1,0.6), ylim=c(ymin, max(di) + yp), las = 2)
614 coordinf <- coord[toinf]
616 text(x=coordinf, y=valinf + 0.1, 'i')
618 if (length(tominf)) {
619 coordinf <- coord[toinf]
621 text(x=coordinf, y=valinf - 0.1, 'i')
627 lcoord <- apply(cc, 1, mean)
630 amp <- abs(max(di) - min(di))
637 d <- signif(amp%%/%%10,1)
642 if ((i/d) == (i%%/%%d)) {
647 plot(0, axes = FALSE, pch = '')
648 legend(x = 'center' , rownames(di), fill = color)
650 """ % (ffr(parametres['rgraph']), parametres['width'], parametres['height'], ffr(parametres['tmpgraph']), parametres['svg'])
658 open_file_graph("%s", width=width, height=height, svg = %s)
659 plot.dendro.lex(tree.cut1$tree.cl, di)
660 """ % (ffr(parametres['tree']), ffr(parametres['rgraph']), parametres['width'], parametres['height'], ffr(parametres['tmpgraph']), parametres['svg'])
663 #def RAfcUci(DictAfcUciOut, nd=2, RscriptsPath='', PARCEX='0.8'):
669 # dataact<-read.csv2("%s")
670 # """ % (DictAfcUciOut['TableCont'])#, encoding)
672 # datasup<-read.csv2("%s")
673 # """ % (DictAfcUciOut['TableSup'])#, encoding)
675 # dataet<-read.csv2("%s")
676 # """ % (DictAfcUciOut['TableEt'])#, encoding)
678 # datatotsup<-cbind(dataact,datasup)
679 # datatotet<-cbind(dataact,dataet)
680 # afcact<-ca(dataact,nd=nd)
681 # afcsup<-ca(datatotsup,supcol=((ncol(dataact)+1):ncol(datatotsup)),nd=nd)
682 # afcet<-ca(datatotet,supcol=((ncol(dataact)+1):ncol(datatotet)),nd=nd)
683 # afctot<-afcsup$colcoord
684 # rownames(afctot)<-afcsup$colnames
685 # colnames(afctot)<-paste('coord. facteur',1:nd,sep=' ')
686 # afctot<-cbind(afctot,mass=afcsup$colmass)
687 # afctot<-cbind(afctot,distance=afcsup$coldist)
688 # afctot<-cbind(afctot,intertie=afcsup$colinertia)
689 # rcolet<-afcet$colsup
690 # afctmp<-afcet$colcoord[rcolet,]
691 # rownames(afctmp)<-afcet$colnames[rcolet]
692 # afctmp<-cbind(afctmp,afcet$colmass[rcolet])
693 # afctmp<-cbind(afctmp,afcet$coldist[rcolet])
694 # afctmp<-cbind(afctmp,afcet$colinertia[rcolet])
695 # afctot<-rbind(afctot,afctmp)
696 # write.csv2(afctot,file = "%s")
698 # """ % (DictAfcUciOut['afc_row'], RscriptsPath['Rgraph'])
704 # PlotAfc(afcet,filename="%s",toplot=c%s, PARCEX=PARCEX)
705 # """ % (DictAfcUciOut['AfcColAct'], "('none','active')")
707 # PlotAfc(afcsup,filename="%s",toplot=c%s, PARCEX=PARCEX)
708 # """ % (DictAfcUciOut['AfcColSup'], "('none','passive')")
709 # txt += """PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
710 # """ % (DictAfcUciOut['AfcColEt'], "('none','passive')")
712 # PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
713 # """ % (DictAfcUciOut['AfcRow'], "('all','none')")
714 # f = open(DictAfcUciOut['Rafcuci'], 'w')
719 class PrintSimiScript(PrintRScript):
721 def make_script(self):
723 self.packages(['igraph', 'proxy', 'Matrix'])
724 self.sources([self.analyse.parent.RscriptsPath['simi'], self.analyse.parent.RscriptsPath['Rgraph']])
726 if not self.parametres['keep_coord'] and not (self.parametres['type'] == 'simimatrix' or self.parametres['type'] == 'simiclustermatrix'):
731 """ % (ffr(self.pathout['mat01.csv']), ffr(self.pathout['actives.csv']), ffr(self.pathout['selected.csv']))
732 if 'word' in self.parametres:
736 """ % self.parametres['word']
744 cn <- read.table(cn.path, sep="\t", quote='"', comment.char="")
745 colnames(dm) <- cn[,1]
746 if (file.exists(selected.col)) {
747 sel.col <- read.csv2(selected.col, header = FALSE)
748 sel.col <- sel.col[,1] + 1
750 sel.col <- 1:ncol(dm)
755 forme <- colnames(dm)[index]
756 if (!index %in% sel.col) {
757 sel.col <- append(sel.col, index)
760 index <- which(colnames(dm) == forme)
763 elif not self.parametres['keep_coord'] and (self.parametres['type'] == 'simimatrix' or self.parametres['type'] == 'simiclustermatrix'):
767 """ % (ffr(self.pathout['mat01.csv']), ffr(self.pathout['selected.csv']))
768 if 'word' in self.parametres:
772 """ % self.parametres['word']
778 dm <-read.csv2(dm.path)
780 if (file.exists(selected.col)) {
781 sel.col <- read.csv2(selected.col, header = FALSE)
782 sel.col <- sel.col[,1] + 1
784 sel.col <- 1:ncol(dm)
789 forme <- colnames(dm)[index]
790 if (!index %in% sel.col) {
791 sel.col <- append(sel.col, index)
794 index <- which(colnames(dm) == forme)
800 """ % ffr(self.pathout['RData.RData'])
801 if self.parametres['coeff'] == 0:
803 if not self.parametres['keep_coord']:
808 elif self.analyse.indices[self.parametres['coeff']] == 'Jaccard':
810 if not self.parametres['keep_coord']:
813 mat <- sparse.jaccard(dm)
816 if not self.parametres['keep_coord']:
820 if self.parametres['coeff'] == 1:
824 mat <- simil(dm, method = 'Russel', diag = TRUE, upper = TRUE, by_rows = FALSE)
826 elif self.analyse.indices[self.parametres['coeff']] == 'binomial':
828 if not self.parametres['keep_coord']:
833 elif self.parametres['coeff'] != 0 and self.analyse.indices[self.parametres['coeff']] != 'Jaccard':
834 method = self.analyse.indices[self.parametres['coeff']]
835 if not self.parametres['keep_coord']:
838 mat <- simil(dm, method = method, diag = TRUE, upper = TRUE, by_rows = FALSE)
839 """ % self.analyse.indices[self.parametres['coeff']]
840 if not self.parametres['keep_coord']:
842 mat <- as.matrix(stats::as.dist(mat,diag=TRUE,upper=TRUE))
844 if (length(which(mat == Inf))) {
845 infp <- which(mat == Inf)
847 maxmat <- max(mat, na.rm = TRUE)
855 if (length(which(mat == -Inf))) {
856 infm <- which(mat == -Inf)
858 minmat <- min(mat, na.rm = TRUE)
867 if 'word' in self.parametres and not self.parametres['keep_coord']:
869 mat <- graph.word(mat, index)
871 if (length(which(cs==0))) mat <- mat[,-which(cs==0)]
873 if (length(which(rs==0))) mat <- mat[-which(rs==0),]
874 if (length(which(cs==0))) dm <- dm[,-which(cs==0)]
876 index <- which(colnames(mat)==forme)
879 if self.parametres['layout'] == 0:
881 if self.parametres['layout'] == 1:
883 if self.parametres['layout'] == 2:
885 if self.parametres['layout'] == 3:
887 if self.parametres['layout'] == 4:
889 if self.parametres['layout'] == 5:
891 if self.parametres['layout'] == 6:
894 if self.parametres['type_graph'] == 0:
896 if self.parametres['type_graph'] == 1:
899 dirout = os.path.dirname(self.pathout['mat01.csv'])
900 while os.path.exists(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png')):
902 self.filename = ffr(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png'))
903 if self.parametres['type_graph'] == 2:
905 if self.parametres['type_graph'] == 3:
908 dirout = os.path.dirname(self.pathout['mat01.csv'])
909 while os.path.exists(os.path.join(dirout,'web_'+str(graphnb))):
911 self.filename = ffr(os.path.join(dirout,'web_'+str(graphnb)))
912 os.mkdir(self.filename)
913 self.filename = os.path.join(self.filename, 'gexf.gexf')
914 if self.parametres['type_graph'] == 4:
917 dirout = os.path.dirname(self.pathout['mat01.csv'])
918 while os.path.exists(os.path.join(dirout,'webrgl_'+str(graphnb))):
920 self.filename = ffr(os.path.join(dirout,'webrgl_'+str(graphnb)))
921 os.mkdir(self.filename)
922 if self.parametres['arbremax']:
924 self.txtgraph += ' - arbre maximum'
928 if self.parametres['coeff_tv']:
929 coeff_tv = self.parametres['coeff_tv_nb']
930 tvminmax = 'c(NULL,NULL)'
931 elif not self.parametres['coeff_tv'] or self.parametres.get('sformchi', False):
933 tvminmax = 'c(%i, %i)' %(self.parametres['tvmin'], self.parametres['tvmax'])
934 if self.parametres['coeff_te']:
935 coeff_te = 'c(%i,%i)' % (self.parametres['coeff_temin'], self.parametres['coeff_temax'])
938 if self.parametres['vcex'] or self.parametres.get('cexfromchi', False):
939 vcexminmax = 'c(%i/10,%i/10)' % (self.parametres['vcexmin'],self.parametres['vcexmax'])
941 vcexminmax = 'c(NULL,NULL)'
942 if not self.parametres['label_v']:
946 if not self.parametres['label_e']:
950 if self.parametres['seuil_ok']:
951 seuil = str(self.parametres['seuil'])
954 if not self.parametres.get('edgecurved', False):
961 cols = str(self.parametres['cols']).replace(')',', max=255)')
962 cola = str(self.parametres['cola']).replace(')',',max=255)')
971 """ % self.parametres['cex']
972 if self.parametres['film']:
975 """ % ffr(self.pathout['film'])
982 if (!is.null(seuil)) {
983 if (method!='cooc') {
991 """ % (label_v, label_e)
999 """ % (self.parametres['width'], self.parametres['height'])
1000 if self.parametres['keep_coord']:
1002 coords <- try(coords, TRUE)
1003 if (!is.matrix(coords)) {
1013 """ % self.parametres['alpha']
1016 """ % self.parametres['alpha']
1017 ######### ??? ##########
1018 if self.parametres.get('bystar',False):
1022 for i, line in enumerate(self.parametres['listet']):
1025 """ % (i+1, ','.join([repr(val + 1) for val in line]))
1028 """ % ("','".join([val for val in self.parametres['selectedstars']]))
1032 for (i in 1:length(unetoile)) {
1035 if (length(tosum) > 1) {
1036 fsum <- cbind(fsum, colSums(dm[tosum,]))
1038 fsum <- cbind(fsum, dm[tosum,])
1042 lex <- AsLexico2(fsum, chip=TRUE)
1043 dcol <- apply(lex[[4]],1,which.max)
1044 toblack <- apply(lex[[4]],1,max)
1045 gcol <- rainbow(length(unetoile))
1046 #gcol[2] <- 'orange'
1047 vertex.label.color <- gcol[dcol]
1048 vertex.label.color[which(toblack <= 3.84)] <- 'black'
1049 leg <- list(unetoile=unetoile, gcol=gcol)
1050 cols <- vertex.label.color
1051 chivertex.size <- norm.vec(toblack, vcexminmax[1], vcexminmax[2])
1053 """ % (ffr(self.analyse.parent.RscriptsPath['chdfunct']))
1056 vertex.label.color <- 'black'
1060 ######### ??? ##########
1062 # eff <- colSums(dm)
1063 # g.ori <- graph.adjacency(mat, mode='lower', weighted = TRUE)
1064 # w.ori <- E(g.ori)$weight
1066 # if (method == 'cooc') {
1067 # E(g.ori)$weight <- 1 / w.ori
1069 # E(g.ori)$weigth <- 1 - w.ori
1071 # g.max <- minimum.spanning.tree(g.ori)
1072 # if (method == 'cooc') {
1073 # E(g.max)$weight <- 1 / E(g.max)$weight
1075 # E(g.max)$weight <- 1 - E(g.max)$weight
1082 if self.parametres['com']:
1083 com = repr(self.parametres['communities'])
1086 if self.parametres['halo']:
1096 x <- list(mat = mat, eff = eff)
1097 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)
1098 """ % (method, type, layout, arbremax, coeff_tv, coeff_te)
1099 if self.parametres.get('bystar',False):
1100 if self.parametres.get('cexfromchi', False):
1102 label.cex<-chivertex.size
1108 if self.parametres.get('sfromchi', False):
1110 vertex.size <- norm.vec(toblack, minmaxeff[1], minmaxeff[2])
1117 #print self.parametres
1118 if (self.parametres['type'] == 'clustersimitxt' and self.parametres.get('tmpchi', False)) or (self.parametres['type'] in ['simimatrix','simiclustermatrix'] and 'tmpchi' in self.parametres):
1120 lchi <- read.table("%s")
1122 """ % ffr(self.parametres['tmpchi'])
1124 lchi <- lchi[sel.col]
1126 if self.parametres['type'] in ['clustersimitxt', 'simimatrix', 'simiclustermatrix'] and self.parametres.get('cexfromchi', False):
1128 label.cex <- norm.vec(lchi, vcexminmax[1], vcexminmax[2])
1132 if (is.null(vcexminmax[1])) {
1135 label.cex <- graph.simi$label.cex
1138 if (self.parametres['type'] in ['clustersimitxt', 'simimatrix', 'simiclustermatrix']) and self.parametres.get('sfromchi', False):
1140 vertex.size <- norm.vec(lchi, minmaxeff[1], minmaxeff[2])
1141 if (!length(vertex.size)) vertex.size <- 0
1145 if (is.null(minmaxeff[1])) {
1148 vertex.size <- graph.simi$eff
1151 #txt += """ vertex.size <- NULL """
1152 if self.parametres['svg']:
1162 if (col.from.proto) {
1163 proto.col <- read.table('/tmp/matcol.csv')
1164 v.proto.names <- make.names(proto.col[,1])
1165 v.proto.col <- as.character(proto.col[,2])
1166 v.proto.col[which(v.proto.col=='black')] <- 'yellow'
1167 v.names <- V(graph.simi$graph)$name
1168 num.color <- sapply(v.names, function(x) {if (x %%in%% v.proto.names) {v.proto.col[which(v.proto.names==x)]} else {'pink'}})
1169 vertex.col <- num.color
1170 V(graph.simi$graph)$proto.color <- vertex.col
1172 if (!is.null(graph.simi$com)) {
1173 com <- graph.simi$com
1174 colm <- rainbow(length(com))
1175 if (sum(vertex.size) != 0 || graph.simi$halo) {
1176 vertex.label.color <- 'black'
1177 vertex.col <- colm[membership(com)]
1179 vertex.label.color <- colm[membership(com)]
1182 if (!length(graph.simi$elim)==0) {
1183 vertex.label.color <- vertex.label.color[-graph.simi$elim]
1184 if (length(label.cex > 1)) {
1185 label.cex <- label.cex[-graph.simi$elim]
1188 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)
1189 save.image(file="%s")
1190 """ % (type, self.filename, ffr(self.pathout['RData']))
1195 class WordCloudRScript(PrintRScript):
1197 def make_script(self):
1198 self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1199 self.packages(['wordcloud'])
1200 bg_col = Rcolor(self.parametres['col_bg'])
1201 txt_col = Rcolor(self.parametres['col_text'])
1202 if self.parametres['svg']:
1210 act <- read.csv2("%s", header = FALSE, row.names=1, sep='\t')
1211 selected.col <- read.table("%s")
1212 toprint <- as.matrix(act[selected.col[,1] + 1,])
1213 rownames(toprint) <- rownames(act)[selected.col[,1] + 1]
1215 if (nrow(toprint) > maxword) {
1216 toprint <- as.matrix(toprint[order(toprint[,1], decreasing=TRUE),])
1217 toprint <- as.matrix(toprint[1:maxword,])
1219 open_file_graph("%s", width = %i, height = %i , svg = svg)
1221 wordcloud(row.names(toprint), toprint[,1], scale=c(%f,%f), random.order=FALSE, colors=rgb%s)
1223 """ % (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)
1228 class ProtoScript(PrintRScript):
1230 def make_script(self):
1231 self.sources([self.analyse.parent.RscriptsPath['Rgraph'], self.analyse.parent.RscriptsPath['prototypical.R']])
1232 self.packages(['wordcloud'])
1233 if self.parametres.get('cloud', False):
1238 errorn <- function(x) {
1239 qnorm(0.975)*sd(x)/sqrt(lenght(n))
1241 errort <- function(x) {
1242 qt(0.975,df=lenght(x)-1)*sd(x)/sqrt(lenght(x))
1244 mat <- read.csv2("%s", header = FALSE, row.names=1, sep='\t', quote='"', dec='.')
1245 open_file_graph("%s",height=800, width=1000)
1246 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')
1248 """ % (ffr(self.analyse.pathout['table.csv']), ffr(self.analyse.pathout['proto.png']), self.parametres['limfreq'], self.parametres['limrang'], self.parametres['typegraph'])
1253 class ExportAfc(PrintRScript):
1255 def make_script(self):
1256 self.source([self.analyse.parent.RscriptsPath['Rgraph']])
1257 self.packages(['rgexf'])
1262 class MergeGraphes(PrintRScript):
1264 def __init__(self, analyse):
1265 self.script = "#Script genere par IRaMuTeQ - %s\n" % datetime.now().ctime()
1266 self.pathout = PathOut()
1267 self.parametres = analyse.parametres
1268 self.scriptout = self.pathout['temp']
1269 self.analyse = analyse
1271 def make_script(self):
1280 g <- graph.simi$graph
1281 V(g)$weight <- (graph.simi$mat.eff/nrow(dm))*100
1284 for i, graph in enumerate(self.parametres['graphs']):
1285 path = os.path.dirname(graph)
1286 gname = ''.join(['g', repr(i)])
1287 RData = os.path.join(path,'RData.RData')
1288 txt += load % (ffr(RData), gname)
1290 self.sources([self.analyse.parent.RscriptsPath['simi']])
1292 merge.type <- 'proto'
1293 if (merge.type == 'normal') {
1294 ng <- merge.graph(graphs)
1296 ng <- merge.graph.proto(graphs)
1298 ngraph <- list(graph=ng, layout=layout.fruchterman.reingold(ng, dim=3), labex.cex=V(ng)$weight)
1299 write.graph(ng, "%s", format = 'graphml')
1300 """ % ffr(self.parametres['grapheout'])
1304 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'])
1327 class TgenProfScript(PrintRScript):
1329 def make_script(self):
1330 self.sources([self.analyse.ira.RscriptsPath['chdfunct']])
1332 tgen <- read.csv2("%s", row.names = 1, sep = '\\t')
1333 """ % ffr(self.parametres['tgeneff'])
1335 tgenlem <- read.csv2("%s", row.names = 1, sep = '\\t')
1336 """ % ffr(self.parametres['tgenlemeff'])
1338 res <- build.prof.tgen(tgen)
1339 write.table(res$chi2, file = "%s", sep='\\t', col.names = NA)
1340 write.table(res$pchi2, file = "%s", sep='\\t', col.names = NA)
1341 """ % (ffr(self.pathout['tgenchi2.csv']), ffr(self.pathout['tgenpchi2.csv']))
1343 reslem <- build.prof.tgen(tgenlem)
1344 write.table(reslem$chi2, file = "%s", sep='\\t', col.names = NA)
1345 write.table(reslem$pchi2, file = "%s", sep='\\t', col.names = NA)
1346 """ % (ffr(self.pathout['tgenlemchi2.csv']), ffr(self.pathout['tgenlempchi2.csv']))
1350 class FreqMultiScript(PrintRScript):
1352 def make_script(self):
1353 self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1355 freq <- read.csv2("%s", row.names=1, sep='\\t', dec='.')
1356 """ % ffr(self.pathout['frequences.csv'])
1358 toplot <- freq[order(freq[,2]) ,2]
1359 toplot.names = rownames(freq)[order(freq[,2])]
1360 h <- 80 + (20 * nrow(freq))
1361 open_file_graph("%s",height=h, width=500)
1362 par(mar=c(3,20,3,3))
1363 barplot(toplot, names = toplot.names, horiz=TRUE, las =1, col = rainbow(nrow(freq)))
1365 """ % ffr(self.pathout['barplotfreq.png'])
1367 toplot <- freq[order(freq[,4]) ,4]
1368 toplot.names = rownames(freq)[order(freq[,4])]
1369 open_file_graph("%s",height=h, width=500)
1370 par(mar=c(3,20,3,3))
1371 barplot(toplot, names = toplot.names, horiz=TRUE, las =1, col = rainbow(nrow(freq)))
1373 """ % ffr(self.pathout['barplotrow.png'])
1378 class LabbeScript(PrintRScript):
1380 def make_script(self):
1381 self.sources([self.analyse.parent.RscriptsPath['distance-labbe.R'],
1382 self.analyse.parent.RscriptsPath['Rgraph']])
1384 tab <- read.csv2("%s", header=TRUE, sep=';', row.names=1)
1385 """ % (ffr(self.pathout['tableafcm.csv']))
1389 print('empty columns !!')
1390 vide <- which(cs==0)
1394 #print('#### RcppIramuteq for C++ Labbe ####')
1395 #library(RcppIramuteq)
1396 #dist.mat <- labbe(as.matrix(tab))
1397 #rownames(dist.mat) <- colnames(tab)
1398 dist.mat <- dist.labbe(tab)
1399 dist.mat <- as.dist(dist.mat, upper=F, diag=F)
1400 write.table(as.matrix(dist.mat), "%s", sep='\t')
1403 chd <- hclust(dist.mat, method="ward.D2")
1404 open_file_graph("%s", width=1000, height=1000, svg=F)
1406 plot.phylo(as.phylo(chd), type='unrooted', lab4ut="axial")
1408 """ % (ffr(self.pathout['distmat.csv']), ffr(self.pathout['labbe-tree.png']))
1410 open_file_graph("%s", width=1000, height=1000, svg=F)
1411 par(mar=c(10,1,1,10))
1412 heatmap(as.matrix(dist.mat), symm = T, distfun=function(x) as.dist(x), margins=c(10,10))
1414 """ % ffr(self.pathout['labbe-heatmap.png'])
1416 #http://stackoverflow.com/questions/3081066/what-techniques-exists-in-r-to-visualize-a-distance-matrix
1417 dst <- data.matrix(dist.mat)
1419 rn <- row.names(as.matrix(dist.mat))
1420 open_file_graph("%s", width=1500, height=1000, svg=F)
1421 par(mar=c(10,10,3,3))
1422 image(1:dim, 1:dim, dst, axes = FALSE, xlab="", ylab="", col=heat.colors(99), breaks=seq(0.01,1,0.01))
1423 axis(1, 1:dim, rn, cex.axis = 0.9, las=3)
1424 axis(2, 1:dim, rn, cex.axis = 0.9, las=1)
1425 text(expand.grid(1:dim, 1:dim), sprintf("%%0.2f", dst), cex=0.6)
1427 """ % ffr(self.pathout['labbe-matrix.png'])
1430 g <- graph.adjacency(as.matrix(1-dist.mat), mode="lower", weighted=T)
1431 write.graph(g, file="%s", format='graphml')
1432 open_file_graph("%s", width=1000, height=1000, svg=F)
1435 E(g)$weight <- 1 - E(g)$weight
1436 g <- minimum.spanning.tree(g)
1437 E(g)$weight <- 1 - E(g)$weight
1438 write.graph(g, file="%s", format='graphml')
1439 open_file_graph("%s", width=1000, height=1000, svg=F)
1442 """ % (ffr(self.pathout['graph_tot.graphml']), ffr(self.pathout['graph_tot.png']), ffr(self.pathout['graph_min.graphml']), ffr(self.pathout['graph_min.png']))
1447 class ChronoChi2Script(PrintRScript):
1449 def make_script(self):
1450 self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1451 print(self.parametres)
1457 """ % (ffr(self.pathout['RData.RData']), ffr(self.pathout['dendrogramme.RData']))
1460 """ % self.parametres['svg']
1462 tc <- which(grepl("%s",rownames(chistabletot)))
1463 rn <- rownames(chistabletot)[tc]
1465 dpt <- chistabletot[tc,]
1466 tot <- afctable[tc,]
1471 """ % self.parametres['var'].replace('*', "\\\\*")
1473 classes <- n1[,ncol(n1)]
1474 tcl <- table(classes)
1475 if ('0' %in% names(tcl)) {
1476 to.vire <- which(names(tcl) == '0')
1477 tcl <- tcl[-to.vire]
1479 tclp <- tcl/sum(tcl)
1486 lcol <- c(lcol, qchisq(1-k,1))
1490 lcol <- c(3.84, lcol)
1491 lcol <- c(-Inf,lcol)
1492 lcol <- c(lcol, Inf)
1495 alphas <- seq(0,1, length.out=length(breaks))
1496 clod <- rev(as.numeric(tree.cut1$tree.cl$tip.label))
1500 open_file_graph("%s", w=%i, h=%i, svg=svg)
1501 """ % (ffr(self.parametres['tmpgraph']), self.parametres['width'], self.parametres['height'])
1504 mat.graphic <- matrix(c(rep(1,nrow(dd)),c(2:(nrow(dd)+1))), ncol=2)
1505 mat.graphic <- rbind(mat.graphic, c(max(mat.graphic) + 1 , max(mat.graphic) + 2))
1506 hauteur <- tclp[clod] * 0.9
1507 heights.graphic <- append(hauteur, 0.1)
1508 layout(mat.graphic, heights=heights.graphic, widths=c(0.15,0.85))
1510 tree.toplot <- tree.cut1$tree.cl
1511 num.label <- as.numeric(tree.cut1$tree.cl$tip.label)
1512 col.tree <- rainbow(length(num.label))[num.label]
1513 #tree.toplot$tip.label <- paste('classe ', tree.toplot$tip.label)
1514 plot.phylo(tree.toplot,label.offset=0.1, cex=1.1, no.margin=T, tip.color = col.tree)
1518 lcol <- cut(dd[i,], breaks, include.lowest=TRUE)
1519 ulcol <- names(table(lcol))
1520 lcol <- as.character(lcol)
1521 for (j in 1:length(ulcol)) {
1522 lcol[which(lcol==ulcol[j])] <- j
1524 lcol <- as.numeric(lcol)
1525 mcol <- rainbow(nrow(dd))[i]
1528 last.col <- c(last.col, rgb(r=col2rgb(mcol)[1]/255, g=col2rgb(mcol)[2]/255, b=col2rgb(mcol)[3]/255, a=k))
1531 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))
1533 plot(0,type='n',axes=FALSE,ann=FALSE)
1534 label.coords <- barplot(rep(1, ncol(dd)), width=ptc, names.arg = F, las=2, axes=F, ylim=c(0,1), plot=T, col='white')
1535 text(x=label.coords, y=0.5, labels=rn[order(rn)], srt=90)
1542 class ChronoPropScript(PrintRScript):
1544 def make_script(self):
1545 self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1546 print(self.parametres)
1552 """ % (ffr(self.pathout['RData.RData']), ffr(self.pathout['dendrogramme.RData']))
1555 """ % self.parametres['svg']
1557 tc <- which(grepl("%s",rownames(chistabletot)))
1558 rn <- rownames(chistabletot)[tc]
1560 dpt <- chistabletot[tc,]
1561 tot <- afctable[tc,]
1566 """ % self.parametres['var'].replace('*', "\\\\*")
1568 classes <- n1[,ncol(n1)]
1569 tcl <- table(classes)
1570 if ('0' %in% names(tcl)) {
1571 to.vire <- which(names(tcl) == '0')
1572 tcl <- tcl[-to.vire]
1574 tclp <- tcl/sum(tcl)
1577 open_file_graph("%s", w=%i, h=%i, svg=svg)
1578 """ % (ffr(self.parametres['tmpgraph']), self.parametres['width'], self.parametres['height'])
1580 ptt <- prop.table(as.matrix(tot), 1)
1581 par(mar=c(10,2,2,2))
1582 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)
1589 class ChronoggScript(PrintRScript):
1591 def make_script(self):
1592 self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1593 print(self.parametres)
1600 """ % (ffr(self.pathout['RData.RData']), ffr(self.pathout['dendrogramme.RData']))
1603 """ % self.parametres['svg']
1605 tc <- which(grepl("%s",rownames(chistabletot)))
1606 rn <- rownames(chistabletot)[tc]
1608 dpt <- chistabletot[tc,]
1609 tot <- afctable[tc,]
1614 """ % self.parametres['var'].replace('*', "\\\\*")
1616 classes <- n1[,ncol(n1)]
1617 tcl <- table(classes)
1618 if ('0' %in% names(tcl)) {
1619 to.vire <- which(names(tcl) == '0')
1620 tcl <- tcl[-to.vire]
1622 tclp <- tcl/sum(tcl)
1623 ptt <- prop.table(as.matrix(tot), 1)
1624 ptt <- ptt[,as.numeric(tree.cut1$tree.cl$tip.label)]
1625 rownames(ptt) <- cumsum(ptc)
1626 nptt<-as.data.frame(as.table(ptt))
1627 nptt[,1]<-as.numeric(as.character(nptt[,1]))
1628 col <- rainbow(ncol(ptt))[as.numeric(tree.cut1$tree.cl$tip.label)]
1631 open_file_graph("%s", w=%i, h=%i, svg=svg)
1632 """ % (ffr(self.parametres['tmpgraph']), self.parametres['width'], self.parametres['height'])
1634 par(mar=c(10,2,2,2))
1635 gg <- ggplot(data=nptt, aes(x=Var1,y=Freq,fill=Var2)) + geom_area(alpha=1 , size=0.5, colour="black")
1636 gg + scale_fill_manual(values=col)
1643 class DendroScript(PrintRScript):
1645 def make_script(self):
1646 if self.parametres['svg']:
1650 fileout = self.parametres['fileout']
1651 width = self.parametres['width']
1652 height = self.parametres['height']
1653 type_dendro = self.parametres['dendro_type']
1654 if self.parametres['taille_classe']:
1658 if self.parametres['color_nb'] == 0:
1662 if self.parametres['type_tclasse'] == 0:
1666 if self.parametres['svg']:
1670 dendro_path = self.pathout['Rdendro']
1671 classe_path = self.pathout['uce']
1676 classes <- read.csv2("%s", row.names=1)
1677 classes <- classes[,1]
1678 """ % (ffr(dendro_path), ffr(self.parametres['Rgraph']), ffr(classe_path))
1679 if self.parametres['dendro'] == 'simple':
1681 open_file_graph("%s", width=%i, height=%i, svg=%s)
1682 plot.dendropr(tree.cut1$tree.cl, classes, type.dendro="%s", histo=%s, bw=%s, lab=NULL, tclasse=%s)
1683 """ % (ffr(fileout), width, height, svg, type_dendro, histo, bw, tclasse)
1684 elif self.parametres['dendro'] == 'texte':
1688 if (is.null(debsup)) {
1691 chistable <- chistabletot[1:(debsup-1),]
1692 """ % (ffr(self.pathout['RData.RData']), ffr(self.parametres['Rgraph']))
1693 if self.parametres.get('translation', False):
1695 rn <- read.csv2("%s", header=FALSE, sep='\t')
1696 rnchis <- row.names(chistable)
1697 commun <- intersect(rnchis, unique(rn[,2]))
1698 idrnchis <- sapply(commun, function(x) {which(rnchis==x)})
1699 idrn <- sapply(commun, function(x) {which(as.vector(rn[,2])==x)[1]})
1700 rownames(chistable)[idrnchis] <- as.vector(rn[idrn,1])
1701 """ % ffr(self.parametres['translation'])
1703 open_file_graph("%s", width=%i, height=%i, svg = %s)
1704 plot.dendro.prof(tree.cut1$tree.cl, classes, chistable, nbbycl = 60, type.dendro="%s", bw=%s, lab=NULL)
1705 """ % (ffr(fileout), width, height, svg, type_dendro, bw)
1706 elif self.parametres['dendro'] == 'cloud':
1710 if (is.null(debsup)) {
1713 chistable <- chistabletot[1:(debsup-1),]
1714 open_file_graph("%s", width=%i, height=%i, svg=%s)
1715 plot.dendro.cloud(tree.cut1$tree.cl, classes, chistable, nbbycl = 300, type.dendro="%s", bw=%s, lab=NULL)
1716 """ % (ffr(self.pathout['RData.RData']), ffr(self.parametres['Rgraph']), ffr(fileout), width, height, svg, type_dendro, bw)
1721 class ReDoProfScript(PrintRScript):
1723 def make_script(self):
1724 self.sources([self.analyse.parent.RscriptsPath['chdfunct.R']])
1725 print(self.parametres)