1 # -*- coding: utf-8 -*-
2 #Author: Pierre Ratinaud
3 #Copyright (c) 2008-2011 Pierre Ratinaud
7 from chemins import ffr
10 from datetime import datetime
13 log = logging.getLogger('iramuteq.printRscript')
16 def __init__ (self, analyse):
18 self.pathout = analyse.pathout
19 self.analyse = analyse
20 self.parametres = analyse.parametres
21 self.scriptout = self.pathout['temp']
22 self.script = u"#Script genere par IRaMuTeQ - %s" % datetime.now().ctime()
25 self.script = '\n'.join([self.script, txt])
27 def defvar(self, name, value) :
28 self.add(' <- '.join([name, value]))
30 def defvars(self, lvars) :
32 self.defvar(val[0],val[1])
34 def sources(self, lsources) :
35 for source in lsources :
36 self.add('source("%s")' % source)
38 def packages(self, lpks) :
40 self.add('library(%s)' % pk)
44 self.add('load("%s")' % val)
47 with open(self.scriptout, 'w') as f :
51 class chdtxt(PrintRScript) :
55 return str(color).replace(')', ', max=255)')
57 class Alceste2(PrintRScript) :
59 self.sources(['chdfunct'])
61 lvars = [['clnb', `self.analyse.clnb`],
62 ['Contout', '"%s"' % self.pathout['Contout']],
63 ['ContSupOut', '"%s"' % self.pathout['ContSupOut']],
64 ['ContEtOut', '"%s"' % self.pathout['ContEtOut']],
65 ['profileout', '"%s"' % self.pathout['profils.csv']],
66 ['antiout', '"%s"' % self.pathout['antiprofils.csv']],
67 ['chisqtable', '"%s"' % self.pathout['chisqtable.csv']],
68 ['ptable', '"%s"' % self.pathout['ptable.csv']]]
74 # txt = "clnb<-%i\n" % clnb
78 #""" % (RscriptsPath['chdfunct'], DictChdTxtOut['RData'])
80 #dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
81 #datasup<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
82 #dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
83 #""" % (DictChdTxtOut['Contout'], DictChdTxtOut['ContSupOut'], DictChdTxtOut['ContEtOut'])
85 #tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
86 #tablesqrpsup<-BuildProf(as.matrix(datasup),n1,clnb)
87 #tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
90 #PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s",tablesqrpsup[4],tablesqrpsup[5])
91 #""" % (DictChdTxtOut['PROFILE_OUT'], DictChdTxtOut['ANTIPRO_OUT'])
93 #colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
94 #colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
95 #colnames(tablesqrpsup[[2]])<-paste('classe',1:clnb,sep=' ')
96 #colnames(tablesqrpsup[[1]])<-paste('classe',1:clnb,sep=' ')
97 #colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
98 #colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
99 #chistabletot<-rbind(tablesqrpact[2][[1]],tablesqrpsup[2][[1]])
100 #chistabletot<-rbind(chistabletot,tablesqrpet[2][[1]])
101 #ptabletot<-rbind(tablesqrpact[1][[1]],tablesqrpet[1][[1]])
104 #write.csv2(chistabletot,file="%s")
105 #write.csv2(ptabletot,file="%s")
107 #write.csv2(gbcluster,file="%s")
108 #""" % (DictChdTxtOut['chisqtable'], DictChdTxtOut['ptable'], DictChdTxtOut['SbyClasseOut'])
112 def RchdTxt(DicoPath, RscriptPath, mincl, classif_mode, nbt = 9, libsvdc = False, libsvdc_path = None, R_max_mem = False):
118 """ % (RscriptPath['CHD'], RscriptPath['chdtxt'], RscriptPath['anacor'], RscriptPath['Rgraph'])
131 """ % ffr(libsvdc_path)
140 data1 <- readMM("%s")
141 data1 <- as(data1, "dgCMatrix")
142 row.names(data1) <- 1:nrow(data1)
143 """ % DicoPath['TableUc1']
145 if classif_mode == 0:
147 data2 <- readMM("%s")
148 data2 <- as(data2, "dgCMatrix")
149 row.names(data2) <- 1:nrow(data2)
150 """ % DicoPath['TableUc2']
151 #log.info('ATTENTION ############# MODEPATATE ####################')
153 chd1<-CHD(data1, x = nbt, mode.patate = FALSE, libsvdc = libsvdc, libsvdc.path = libsvdc.path)
156 if classif_mode == 0:
158 chd2<-CHD(data2, x = nbt, libsvdc = libsvdc, libsvdc.path = libsvdc.path)
167 listuce1<-read.csv2("%s")
168 """ % DicoPath['listeuce1']
170 if classif_mode == 0:
172 listuce2<-read.csv2("%s")
173 """ % DicoPath['listeuce2']
179 if classif_mode == 0:
184 chd.result <- Rchdtxt("%s",mincl=%i,classif_mode=%i, nbt = nbt)
186 classeuce1 <- chd.result$cuce1
187 classeuce2 <- chd.result$cuce2
188 """ % (DicoPath['uce'], mincl, classif_mode)
191 tree.tot1 <- make_tree_tot(chd1)
192 # open_file_graph("%s", widt = 600, height=400)
193 # plot(tree.tot1$tree.cl)
195 """%DicoPath['arbre1']
197 if classif_mode == 0:
199 tree.tot2 <- make_tree_tot(chd2)
200 # open_file_graph("%s", width = 600, height=400)
201 # plot(tree.tot2$tree.cl)
203 """ % DicoPath['arbre2']
206 tree.cut1 <- make_dendro_cut_tuple(tree.tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
207 save(tree.cut1, file="%s")
208 classes<-n1[,ncol(n1)]
209 open_file_graph("%s", width = 600, height=400)
210 plot.dendropr(tree.cut1$tree.cl,classes, histo=TRUE)
211 open_file_graph("%s", width = 600, height=400)
212 plot(tree.cut1$dendro_tot_cl)
214 """ % (DicoPath['Rdendro'], DicoPath['dendro1'], DicoPath['arbre1'])
216 if classif_mode == 0:
218 tree.cut2 <- make_dendro_cut_tuple(tree.tot2$dendro_tuple, chd.result$coord_ok, classeuce2, 2, nbt)
219 open_file_graph("%s", width = 600, height=400)
220 plot(tree.cut2$tree.cl)
222 open_file_graph("%s", width = 600, height=400)
223 plot(tree.cut1$dendro_tot_cl)
225 """ % (DicoPath['dendro2'], DicoPath['arbre2'])
228 save.image(file="%s")
229 """ % DicoPath['RData']
230 fileout = open(DicoPath['Rchdtxt'], 'w')
234 def RPamTxt(corpus, RscriptPath):
235 DicoPath = corpus.dictpathout
236 param = corpus.parametre
240 """ % (RscriptPath['pamtxt'])
243 """ % (RscriptPath['Rgraph'])
245 result <- pamtxt("%s", "%s", "%s", method = "%s", clust_type = "%s", clnb = %i)
247 """ % (DicoPath['TableUc1'], DicoPath['listeuce1'], DicoPath['uce'], param['method'], param['cluster_type'], param['nbcl'] )
249 open_file_graph("%s", width=400, height=400)
252 """ % (DicoPath['arbre1'])
254 save.image(file="%s")
255 """ % DicoPath['RData']
256 fileout = open(DicoPath['Rchdtxt'], 'w')
261 def RchdQuest(DicoPath, RscriptPath, nbcl = 10, mincl = 10):
267 """ % (RscriptPath['CHD'], RscriptPath['chdquest'], RscriptPath['anacor'],RscriptPath['Rgraph'])
275 chd.result<-Rchdquest("%s","%s","%s", nbt = nbt, mincl = mincl)
277 classeuce1 <- chd.result$cuce1
278 """ % (DicoPath['Act01'], DicoPath['listeuce1'], DicoPath['uce'])
281 tree_tot1 <- make_tree_tot(chd.result$chd)
282 open_file_graph("%s", width = 600, height=400)
283 plot(tree_tot1$tree.cl)
285 """%DicoPath['arbre1']
288 tree_cut1 <- make_dendro_cut_tuple(tree_tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
289 tree.cut1 <- tree_cut1
290 save(tree.cut1, file="%s")
291 open_file_graph("%s", width = 600, height=400)
292 classes<-n1[,ncol(n1)]
293 plot.dendropr(tree_cut1$tree.cl,classes)
294 """ % (DicoPath['Rdendro'],DicoPath['dendro1'])
297 save.image(file="%s")
298 """ % DicoPath['RData']
299 fileout = open(DicoPath['Rchdquest'], 'w')
303 def AlcesteTxtProf(DictChdTxtOut, RscriptsPath, clnb, taillecar):
304 txt = "clnb<-%i\n" % clnb
308 """ % (RscriptsPath['chdfunct'], DictChdTxtOut['RData'])
310 dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
311 datasup<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
312 dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
313 """ % (DictChdTxtOut['Contout'], DictChdTxtOut['ContSupOut'], DictChdTxtOut['ContEtOut'])
315 tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
316 tablesqrpsup<-BuildProf(as.matrix(datasup),n1,clnb)
317 tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
320 PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s",tablesqrpsup[4],tablesqrpsup[5])
321 """ % (DictChdTxtOut['PROFILE_OUT'], DictChdTxtOut['ANTIPRO_OUT'])
323 colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
324 colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
325 colnames(tablesqrpsup[[2]])<-paste('classe',1:clnb,sep=' ')
326 colnames(tablesqrpsup[[1]])<-paste('classe',1:clnb,sep=' ')
327 colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
328 colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
329 chistabletot<-rbind(tablesqrpact[2][[1]],tablesqrpsup[2][[1]])
330 chistabletot<-rbind(chistabletot,tablesqrpet[2][[1]])
331 ptabletot<-rbind(tablesqrpact[1][[1]],tablesqrpet[1][[1]])
334 write.csv2(chistabletot,file="%s")
335 write.csv2(ptabletot,file="%s")
337 write.csv2(gbcluster,file="%s")
338 """ % (DictChdTxtOut['chisqtable'], DictChdTxtOut['ptable'], DictChdTxtOut['SbyClasseOut'])
342 colnames(dataact)<-paste('classe',1:clnb,sep=' ')
343 colnames(datasup)<-paste('classe',1:clnb,sep=' ')
344 colnames(dataet)<-paste('classe',1:clnb,sep=' ')
345 rowtot<-nrow(dataact)+nrow(dataet)+nrow(datasup)
346 afctable<-rbind(as.matrix(dataact),as.matrix(datasup))
347 afctable<-rbind(afctable,as.matrix(dataet))
348 colnames(afctable)<-paste('classe',1:clnb,sep=' ')
349 afc<-ca(afctable,suprow=((nrow(dataact)+1):rowtot),nd=(ncol(afctable)-1))
350 debsup<-nrow(dataact)+1
351 debet<-nrow(dataact)+nrow(datasup)+1
353 afc<-AddCorrelationOk(afc)
355 #FIXME : split this!!!
358 """ % RscriptsPath['Rgraph']
361 afc <- summary.ca.dm(afc)
362 afc_table <- create_afc_table(afc)
363 write.csv2(afc_table$facteur, file = "%s")
364 write.csv2(afc_table$colonne, file = "%s")
365 write.csv2(afc_table$ligne, file = "%s")
366 """ % (DictChdTxtOut['afc_facteur'], DictChdTxtOut['afc_col'], DictChdTxtOut['afc_row'])
369 #xlab <- paste('facteur 1 - ', round(afc$facteur[1,2],2), sep = '')
370 #ylab <- paste('facteur 2 - ', round(afc$facteur[2,2],2), sep = '')
371 #xlab <- paste(xlab, ' %', sep = '')
372 #ylab <- paste(ylab, ' %', sep = '')
377 xmin <- min(afc$rowcoord[,1], na.rm = TRUE) + (0.1 * min(afc$rowcoord[,1], na.rm = TRUE))
378 xmax <- max(afc$rowcoord[,1], na.rm = TRUE) + (0.1 * max(afc$rowcoord[,1], na.rm = TRUE))
379 ymin <- min(afc$rowcoord[,2], na.rm = TRUE) + (0.1 * min(afc$rowcoord[,2], na.rm = TRUE))
380 ymax <- max(afc$rowcoord[,2], na.rm = TRUE) + (0.1 * max(afc$rowcoord[,2], na.rm = TRUE))
387 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab, xmin=xmin, xmax=xmax, ymin = ymin, ymax=ymax)
388 """ % (DictChdTxtOut['AFC2DL_OUT'])
390 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=debsup, fin=(debet-1), xlab = xlab, ylab = ylab, xmin=xmin, xmax=xmax, ymin = ymin, ymax=ymax)
391 """ % (DictChdTxtOut['AFC2DSL_OUT'])
393 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=debet, fin=fin, xlab = xlab, ylab = ylab, xmin=xmin, xmax=xmax, ymin = ymin, ymax=ymax)
394 """ % (DictChdTxtOut['AFC2DEL_OUT'])
396 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col=TRUE, what='coord', xlab = xlab, ylab = ylab, xmin=xmin, xmax=xmax, ymin = ymin, ymax=ymax)
397 """ % (DictChdTxtOut['AFC2DCL_OUT'])
399 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
400 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debsup, fin=(debet-1), xlab = xlab, ylab = ylab)
401 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debet, fin=fin, xlab = xlab, ylab = ylab)
402 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col=TRUE, what='crl', xlab = xlab, ylab = ylab)
403 # """ % (DictChdTxtOut['AFC2DCoul'], DictChdTxtOut['AFC2DCoulSup'], DictChdTxtOut['AFC2DCoulEt'], DictChdTxtOut['AFC2DCoulCl'])
412 save.image(file="%s")
413 """ % DictChdTxtOut['RData']
414 file = open(DictChdTxtOut['RTxtProfGraph'], 'w')
419 def write_afc_graph(self):
420 if self.param['over'] : over = 'TRUE'
421 else : over = 'FALSE'
423 if self.param['do_select_nb'] : do_select_nb = 'TRUE'
424 else : do_select_nb = 'FALSE'
426 if self.param['do_select_chi'] : do_select_chi = 'TRUE'
427 else : do_select_chi = 'FALSE'
429 if self.param['do_select_chi_classe'] : do_select_chi_classe = 'TRUE'
430 else : do_select_chi_classe = 'FALSE'
432 if self.param['cex_txt'] : cex_txt = 'TRUE'
433 else : cex_txt = 'FALSE'
435 if self.param['tchi'] : tchi = 'TRUE'
436 else : tchi = 'FALSE'
438 with open(self.RscriptsPath['afc_graph'], 'r') as f:
441 # self.DictPathOut['RData'], \
442 scripts = txt % (self.RscriptsPath['Rgraph'],\
443 self.param['typegraph'], \
444 self.param['what'], \
445 self.param['facteur'][0],\
446 self.param['facteur'][1], \
447 self.param['facteur'][2], \
449 over, do_select_nb, \
450 self.param['select_nb'], \
452 self.param['select_chi'], \
453 do_select_chi_classe, \
454 self.param['nbchic'], \
456 self.param['txt_min'], \
457 self.param['txt_max'], \
459 self.param['width'], \
460 self.param['height'],\
461 self.param['taillecar'], \
462 self.param['alpha'], \
463 self.param['film'], \
465 self.param['tchi_min'],\
466 self.param['tchi_max'],\
467 ffr(os.path.dirname(self.fileout)))
470 def print_simi3d(self):
471 simi3d = self.parent.simi3dpanel
472 txt = '#Fichier genere par Iramuteq'
473 if simi3d.movie.GetValue() :
474 movie = "'" + ffr(os.path.dirname(self.DictPathOut['RData'])) + "'"
478 #if self.corpus.parametres['type'] == 'corpus' :
484 dm<-read.csv2("%s",row.names=1,header = %s)
486 """ % (self.DictPathOut['Contout'], header, self.DictPathOut['RData'])
490 """ % self.parent.RscriptsPath['Rgraph']
494 make.simi.afc(dm,chistabletot, lim=%i, alpha = %.2f, movie = %s)
495 """ % (simi3d.spin_1.GetValue(), float(simi3d.slider_1.GetValue())/100, movie)
496 tmpfile = tempfile.mktemp(dir=self.parent.TEMPDIR)
497 tmp = open(tmpfile,'w')
502 def dendroandbarplot(table, rownames, colnames, rgraph, tmpgraph, intxt = False, dendro=False) :
504 txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
505 rownb = len(rownames)
506 rownames = 'c("' + '","'.join(rownames) + '")'
507 colnames = 'c("' + '","'.join(colnames) + '")'
511 di <- matrix(data=%s, nrow=%i, byrow = TRUE)
514 """ % (txttable, rownb, rownames, colnames)
521 height <- (30*ncol(di)) + (15*nrow(di))
522 height <- ifelse(height <= 400, 400, height)
524 open_file_graph("%s", width=width, height=height)
525 plot.dendro.lex(tree.cut1$tree.cl, di)
526 """ % (ffr(dendro),ffr(rgraph), ffr(tmpgraph))
529 def barplot(table, rownames, colnames, rgraph, tmpgraph, intxt = False) :
531 txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
532 #width = 100 + (15 * len(rownames)) + (100 * len(colnames))
533 #height = len(rownames) * 15
534 rownb = len(rownames)
537 rownames = 'c("' + '","'.join(rownames) + '")'
538 colnames = 'c("' + '","'.join(colnames) + '")'
542 di <- matrix(data=%s, nrow=%i, byrow = TRUE)
543 toinf <- which(di == Inf)
544 tominf <- which(di == -Inf)
547 valmax <- max(di, na.rm = TRUE)
555 if (length(tominf)) {
557 valmin <- min(di, na.rm = TRUE)
567 """ % (txttable, rownb, rownames, colnames)
572 color = rainbow(nrow(di))
573 width <- 100 + (20*length(rownames(di))) + (100 * length(colnames(di)))
574 height <- nrow(di) * 15
575 if (height < 400) { height <- 400}
576 open_file_graph("%s",width = width, height = height)
578 layout(matrix(c(1,2),1,2, byrow=TRUE),widths=c(3,lcm(7)))
580 yp = ifelse(length(toinf), 0.2, 0)
581 ym = ifelse(length(tominf), 0.2, 0)
582 ymin <- ifelse(!length(which(di < 0)), 0, min(di) - ym)
583 coord <- barplot(as.matrix(di), beside = TRUE, col = color, space = c(0.1,0.6), ylim=c(ymin, max(di) + yp))
585 coordinf <- coord[toinf]
587 text(x=coordinf, y=valinf + 0.1, 'i')
589 if (length(tominf)) {
590 coordinf <- coord[toinf]
592 text(x=coordinf, y=valinf - 0.1, 'i')
598 lcoord <- apply(cc, 1, mean)
601 amp <- abs(max(di) - min(di))
608 d <- signif(amp%%/%%10,1)
613 if ((i/d) == (i%%/%%d)) {
618 plot(0, axes = FALSE, pch = '')
619 legend(x = 'center' , rownames(di), fill = color)
621 """ % (rgraph, ffr(tmpgraph))
624 #def RAfcUci(DictAfcUciOut, nd=2, RscriptsPath='', PARCEX='0.8'):
630 # dataact<-read.csv2("%s")
631 # """ % (DictAfcUciOut['TableCont'])#, encoding)
633 # datasup<-read.csv2("%s")
634 # """ % (DictAfcUciOut['TableSup'])#, encoding)
636 # dataet<-read.csv2("%s")
637 # """ % (DictAfcUciOut['TableEt'])#, encoding)
639 # datatotsup<-cbind(dataact,datasup)
640 # datatotet<-cbind(dataact,dataet)
641 # afcact<-ca(dataact,nd=nd)
642 # afcsup<-ca(datatotsup,supcol=((ncol(dataact)+1):ncol(datatotsup)),nd=nd)
643 # afcet<-ca(datatotet,supcol=((ncol(dataact)+1):ncol(datatotet)),nd=nd)
644 # afctot<-afcsup$colcoord
645 # rownames(afctot)<-afcsup$colnames
646 # colnames(afctot)<-paste('coord. facteur',1:nd,sep=' ')
647 # afctot<-cbind(afctot,mass=afcsup$colmass)
648 # afctot<-cbind(afctot,distance=afcsup$coldist)
649 # afctot<-cbind(afctot,intertie=afcsup$colinertia)
650 # rcolet<-afcet$colsup
651 # afctmp<-afcet$colcoord[rcolet,]
652 # rownames(afctmp)<-afcet$colnames[rcolet]
653 # afctmp<-cbind(afctmp,afcet$colmass[rcolet])
654 # afctmp<-cbind(afctmp,afcet$coldist[rcolet])
655 # afctmp<-cbind(afctmp,afcet$colinertia[rcolet])
656 # afctot<-rbind(afctot,afctmp)
657 # write.csv2(afctot,file = "%s")
659 # """ % (DictAfcUciOut['afc_row'], RscriptsPath['Rgraph'])
665 # PlotAfc(afcet,filename="%s",toplot=c%s, PARCEX=PARCEX)
666 # """ % (DictAfcUciOut['AfcColAct'], "('none','active')")
668 # PlotAfc(afcsup,filename="%s",toplot=c%s, PARCEX=PARCEX)
669 # """ % (DictAfcUciOut['AfcColSup'], "('none','passive')")
670 # txt += """PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
671 # """ % (DictAfcUciOut['AfcColEt'], "('none','passive')")
673 # PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
674 # """ % (DictAfcUciOut['AfcRow'], "('all','none')")
675 # f = open(DictAfcUciOut['Rafcuci'], 'w')
679 class PrintSimiScript(PrintRScript) :
680 def make_script(self) :
682 self.packages(['igraph', 'proxy', 'Matrix'])
683 self.sources([self.analyse.parent.RscriptsPath['simi'], self.analyse.parent.RscriptsPath['Rgraph']])
685 if not self.parametres['keep_coord'] :
690 """ % (self.pathout['mat01.csv'], self.pathout['actives.csv'], self.pathout['selected.csv'])
693 cn <- read.table(cn.path, sep=';', quote='"')
694 colnames(dm) <- cn[,1]
695 sel.col <- read.csv2(selected.col)
696 dm <- dm[, sel.col[,1] + 1]
701 """ % self.pathout['RData.RData']
703 if self.parametres['coeff'] == 0 :
705 if not self.parametres['keep_coord'] :
711 if not self.parametres['keep_coord'] :
715 if self.parametres['coeff'] == 1 :
719 mat <- simil(dm, method = 'Russel', diag = TRUE, upper = TRUE, by_rows = FALSE)
721 elif self.analyse.indices[self.parametres['coeff']] == 'binomial' :
723 if not self.parametres['keep_coord'] :
728 elif self.parametres['coeff'] != 0 :
729 method = self.analyse.indices[self.parametres['coeff']]
730 if not self.parametres['keep_coord'] :
733 mat <- simil(dm, method = method, diag = TRUE, upper = TRUE, by_rows = FALSE)
734 """ % self.analyse.indices[self.parametres['coeff']]
735 if not self.parametres['keep_coord'] :
737 mat <- as.matrix(stats::as.dist(mat,diag=TRUE,upper=TRUE))
739 mat[is.infinite(mat)] <- 0
741 if self.parametres['layout'] == 0 : layout = 'random'
742 if self.parametres['layout'] == 1 : layout = 'circle'
743 if self.parametres['layout'] == 2 : layout = 'frutch'
744 if self.parametres['layout'] == 3 : layout = 'kawa'
745 if self.parametres['layout'] == 4 : layout = 'graphopt'
749 if self.parametres['type_graph'] == 0 : type = 'tkplot'
750 if self.parametres['type_graph'] == 1 :
753 dirout = os.path.dirname(self.pathout['mat01'])
754 while os.path.exists(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png')):
756 self.filename = ffr(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png'))
757 if self.parametres['type_graph'] == 2 : type = 'rgl'
759 if self.parametres['arbremax'] :
761 self.txtgraph += ' - arbre maximum'
762 else : arbremax = 'FALSE'
764 if self.parametres['coeff_tv'] :
765 coeff_tv = self.parametres['coeff_tv_nb']
766 tvminmax = 'c(NULL,NULL)'
767 elif not self.parametres['coeff_tv'] or self.parametres.get('sformchi', False) :
769 tvminmax = 'c(%i, %i)' %(self.parametres['tvmin'], self.parametres['tvmax'])
770 if self.parametres['coeff_te'] : coeff_te = 'c(%i,%i)' % (self.parametres['coeff_temin'], self.parametres['coeff_temax'])
771 else : coeff_te = 'NULL'
773 if self.parametres['vcex'] or self.parametres.get('cexfromchi', False) :
774 vcexminmax = 'c(%i/10,%i/10)' % (self.parametres['vcexmin'],self.parametres['vcexmax'])
776 vcexminmax = 'c(NULL,NULL)'
777 if not self.parametres['label_v'] : label_v = 'FALSE'
778 else : label_v = 'TRUE'
780 if not self.parametres['label_e'] : label_e = 'FALSE'
781 else : label_e = 'TRUE'
783 if self.parametres['seuil_ok'] : seuil = str(self.parametres['seuil'])
784 else : seuil = 'NULL'
786 cols = str(self.parametres['cols']).replace(')',', max=255)')
787 cola = str(self.parametres['cola']).replace(')',',max=255)')
797 """ % self.parametres['cex']
799 if self.parametres['film'] :
802 """ % self.pathout['film']
814 """ % (label_v, label_e)
822 """ % (self.parametres['width'], self.parametres['height'])
823 if self.parametres['keep_coord'] :
825 coords <- try(coords, TRUE)
826 if (!is.matrix(coords)) {
836 """ % self.parametres['alpha']
839 """ % self.parametres['alpha']
840 #############################################
841 if self.parametres.get('bystar',False) :
845 for i, line in enumerate(self.parametres['listet']) :
848 """ % (i+1, ','.join([`val + 1` for val in line]))
851 """ % ("','".join([val for val in self.parametres['selectedstars']]))
855 for (i in 1:length(unetoile)) {
858 if (length(tosum) > 1) {
859 fsum <- cbind(fsum, colSums(dm[tosum,]))
861 fsum <- cbind(fsum, dm[tosum,])
865 lex <- AsLexico2(fsum, chip=TRUE)
866 dcol <- apply(lex[[4]],1,which.max)
867 toblack <- apply(lex[[4]],1,max)
868 gcol <- rainbow(length(unetoile))
870 vertex.label.color <- gcol[dcol]
871 vertex.label.color[which(toblack <= 3.84)] <- 'black'
872 leg <- list(unetoile=unetoile, gcol=gcol)
873 cols <- vertex.label.color
874 chivertex.size <- norm.vec(toblack, vcexminmax[1], vcexminmax[2])
876 """ % (self.analyse.parent.RscriptsPath['chdfunct'])
879 vertex.label.color <- 'black'
883 #############################################
887 # g.ori <- graph.adjacency(mat, mode='lower', weighted = TRUE)
888 # w.ori <- E(g.ori)$weight
890 # if (method == 'cooc') {
891 # E(g.ori)$weight <- 1 / w.ori
893 # E(g.ori)$weigth <- 1 - w.ori
895 # g.max <- minimum.spanning.tree(g.ori)
896 # if (method == 'cooc') {
897 # E(g.max)$weight <- 1 / E(g.max)$weight
899 # E(g.max)$weight <- 1 - E(g.max)$weight
908 x <- list(mat = mat, eff = eff)
909 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)
910 """ % (method, type, layout, arbremax, coeff_tv, coeff_te)
912 if self.parametres.get('bystar',False) :
913 if self.parametres.get('cexfromchi', False) :
915 label.cex<-chivertex.size
921 if self.parametres.get('sfromchi', False) :
923 vertex.size <- norm.vec(toblack, minmaxeff[1], minmaxeff[2])
934 lchi <- read.table("%s")
937 if 'selected_col' in dir(self.tableau) :
941 if tmpchi and self.parametres.get('cexfromchi', False) :
943 label.cex <- norm.vec(lchi, vcexminmax[1], vcexminmax[2])
947 if (is.null(vcexminmax[1])) {
950 label.cex <- graph.simi$label.cex
953 if tmpchi and self.parametres.get('sfromchi', False) :
955 vertex.size <- norm.vec(lchi, minmaxeff[1], minmaxeff[2])
959 if (is.null(minmaxeff[1])) {
962 vertex.size <- graph.simi$eff
965 txt += """ vertex.size <- NULL """
967 coords <- plot.simi(graph.simi, p.type='%s',filename="%s", vertex.label = label.v, edge.label = label.e, vertex.col = cols, 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)
968 save.image(file="%s")
969 """ % (type, self.filename, self.pathout['RData'])
974 class WordCloudRScript(PrintRScript) :
975 def make_script(self) :
976 self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
977 self.packages(['wordcloud'])
978 bg_col = Rcolor(self.parametres['col_bg'])
979 txt_col = Rcolor(self.parametres['col_text'])
981 act <- read.csv2("%s", header = FALSE, row.names=1, sep='\t')
982 selected.col <- read.table("%s")
983 toprint <- as.matrix(act[selected.col[,1] + 1,])
984 rownames(toprint) <- rownames(act)[selected.col[,1] + 1]
986 if (nrow(toprint) > maxword) {
987 toprint <- as.matrix(toprint[order(toprint[,1], decreasing=TRUE),])
988 toprint <- as.matrix(toprint[1:maxword,])
990 open_file_graph("%s", width = %i, height = %i)
992 wordcloud(row.names(toprint), toprint[,1], scale=c(%f,%f), random.order=FALSE, colors=rgb%s)
994 """ % (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)