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, svdmethod = 'svdR', libsvdc = False, libsvdc_path = None, R_max_mem = False, mode_patate = False):
118 """ % (RscriptPath['CHD'], RscriptPath['chdtxt'], RscriptPath['anacor'], RscriptPath['Rgraph'])
127 if svdmethod == 'svdlibc' and libsvdc :
129 svd.method <- 'svdlibc'
131 """ % ffr(libsvdc_path)
132 elif svdmethod == 'irlba' :
135 svd.method <- 'irlba'
153 data1 <- readMM("%s")
154 data1 <- as(data1, "dgCMatrix")
155 row.names(data1) <- 1:nrow(data1)
156 """ % DicoPath['TableUc1']
158 if classif_mode == 0:
160 data2 <- readMM("%s")
161 data2 <- as(data2, "dgCMatrix")
162 row.names(data2) <- 1:nrow(data2)
163 """ % DicoPath['TableUc2']
165 chd1<-CHD(data1, x = nbt, mode.patate = mode.patate, svd.method = svd.method, libsvdc.path = libsvdc.path)
168 if classif_mode == 0:
170 chd2<-CHD(data2, x = nbt, mode.patate = mode.patate, svd.method = svd.method, libsvdc.path = libsvdc.path)
179 listuce1<-read.csv2("%s")
180 """ % DicoPath['listeuce1']
182 if classif_mode == 0:
184 listuce2<-read.csv2("%s")
185 """ % DicoPath['listeuce2']
191 if classif_mode == 0:
196 chd.result <- Rchdtxt("%s",mincl=%i,classif_mode=%i, nbt = nbt)
198 classeuce1 <- chd.result$cuce1
199 classeuce2 <- chd.result$cuce2
200 """ % (DicoPath['uce'], mincl, classif_mode)
203 tree.tot1 <- make_tree_tot(chd1)
204 # open_file_graph("%s", widt = 600, height=400)
205 # plot(tree.tot1$tree.cl)
207 """%DicoPath['arbre1']
209 if classif_mode == 0:
211 tree.tot2 <- make_tree_tot(chd2)
212 # open_file_graph("%s", width = 600, height=400)
213 # plot(tree.tot2$tree.cl)
215 """ % DicoPath['arbre2']
218 tree.cut1 <- make_dendro_cut_tuple(tree.tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
219 save(tree.cut1, file="%s")
220 classes<-n1[,ncol(n1)]
221 open_file_graph("%s", width = 600, height=400)
222 plot.dendropr(tree.cut1$tree.cl,classes, histo=TRUE)
223 open_file_graph("%s", width = 600, height=400)
224 plot(tree.cut1$dendro_tot_cl)
226 """ % (DicoPath['Rdendro'], DicoPath['dendro1'], DicoPath['arbre1'])
228 if classif_mode == 0:
230 tree.cut2 <- make_dendro_cut_tuple(tree.tot2$dendro_tuple, chd.result$coord_ok, classeuce2, 2, nbt)
231 open_file_graph("%s", width = 600, height=400)
232 plot(tree.cut2$tree.cl)
234 open_file_graph("%s", width = 600, height=400)
235 plot(tree.cut1$dendro_tot_cl)
237 """ % (DicoPath['dendro2'], DicoPath['arbre2'])
240 save.image(file="%s")
241 """ % DicoPath['RData']
242 fileout = open(DicoPath['Rchdtxt'], 'w')
246 def RPamTxt(corpus, RscriptPath):
247 DicoPath = corpus.dictpathout
248 param = corpus.parametre
252 """ % (RscriptPath['pamtxt'])
255 """ % (RscriptPath['Rgraph'])
257 result <- pamtxt("%s", "%s", "%s", method = "%s", clust_type = "%s", clnb = %i)
259 """ % (DicoPath['TableUc1'], DicoPath['listeuce1'], DicoPath['uce'], param['method'], param['cluster_type'], param['nbcl'] )
261 open_file_graph("%s", width=400, height=400)
264 """ % (DicoPath['arbre1'])
266 save.image(file="%s")
267 """ % DicoPath['RData']
268 fileout = open(DicoPath['Rchdtxt'], 'w')
273 def RchdQuest(DicoPath, RscriptPath, nbcl = 10, mincl = 10):
279 """ % (RscriptPath['CHD'], RscriptPath['chdquest'], RscriptPath['anacor'],RscriptPath['Rgraph'])
287 chd.result<-Rchdquest("%s","%s","%s", nbt = nbt, mincl = mincl)
289 classeuce1 <- chd.result$cuce1
290 """ % (DicoPath['mat01'], DicoPath['listeuce1'], DicoPath['uce'])
293 tree_tot1 <- make_tree_tot(chd.result$chd)
294 open_file_graph("%s", width = 600, height=400)
295 plot(tree_tot1$tree.cl)
297 """%DicoPath['arbre1']
300 tree_cut1 <- make_dendro_cut_tuple(tree_tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
301 tree.cut1 <- tree_cut1
302 save(tree.cut1, file="%s")
303 open_file_graph("%s", width = 600, height=400)
304 classes<-n1[,ncol(n1)]
305 plot.dendropr(tree_cut1$tree.cl,classes)
306 """ % (DicoPath['Rdendro'],DicoPath['dendro1'])
309 save.image(file="%s")
310 """ % DicoPath['RData']
311 fileout = open(DicoPath['Rchdquest'], 'w')
315 def AlcesteTxtProf(DictChdTxtOut, RscriptsPath, clnb, taillecar):
316 txt = "clnb<-%i\n" % clnb
320 """ % (RscriptsPath['chdfunct'], DictChdTxtOut['RData'])
322 dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
323 datasup<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
324 dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
325 """ % (DictChdTxtOut['Contout'], DictChdTxtOut['ContSupOut'], DictChdTxtOut['ContEtOut'])
327 tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
328 tablesqrpsup<-BuildProf(as.matrix(datasup),n1,clnb)
329 tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
332 PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s",tablesqrpsup[4],tablesqrpsup[5])
333 """ % (DictChdTxtOut['PROFILE_OUT'], DictChdTxtOut['ANTIPRO_OUT'])
335 colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
336 colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
337 colnames(tablesqrpsup[[2]])<-paste('classe',1:clnb,sep=' ')
338 colnames(tablesqrpsup[[1]])<-paste('classe',1:clnb,sep=' ')
339 colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
340 colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
341 chistabletot<-rbind(tablesqrpact[2][[1]],tablesqrpsup[2][[1]])
342 chistabletot<-rbind(chistabletot,tablesqrpet[2][[1]])
343 ptabletot<-rbind(tablesqrpact[1][[1]],tablesqrpet[1][[1]])
346 write.csv2(chistabletot,file="%s")
347 write.csv2(ptabletot,file="%s")
349 write.csv2(gbcluster,file="%s")
350 """ % (DictChdTxtOut['chisqtable'], DictChdTxtOut['ptable'], DictChdTxtOut['SbyClasseOut'])
354 colnames(dataact)<-paste('classe',1:clnb,sep=' ')
355 colnames(datasup)<-paste('classe',1:clnb,sep=' ')
356 colnames(dataet)<-paste('classe',1:clnb,sep=' ')
357 rowtot<-nrow(dataact)+nrow(dataet)+nrow(datasup)
358 afctable<-rbind(as.matrix(dataact),as.matrix(datasup))
359 afctable<-rbind(afctable,as.matrix(dataet))
360 colnames(afctable)<-paste('classe',1:clnb,sep=' ')
361 afc<-ca(afctable,suprow=((nrow(dataact)+1):rowtot),nd=(ncol(afctable)-1))
362 debsup<-nrow(dataact)+1
363 debet<-nrow(dataact)+nrow(datasup)+1
365 afc<-AddCorrelationOk(afc)
367 #FIXME : split this!!!
370 """ % RscriptsPath['Rgraph']
373 afc <- summary.ca.dm(afc)
374 afc_table <- create_afc_table(afc)
375 write.csv2(afc_table$facteur, file = "%s")
376 write.csv2(afc_table$colonne, file = "%s")
377 write.csv2(afc_table$ligne, file = "%s")
378 """ % (DictChdTxtOut['afc_facteur'], DictChdTxtOut['afc_col'], DictChdTxtOut['afc_row'])
381 #xlab <- paste('facteur 1 - ', round(afc$facteur[1,2],2), sep = '')
382 #ylab <- paste('facteur 2 - ', round(afc$facteur[2,2],2), sep = '')
383 #xlab <- paste(xlab, ' %', sep = '')
384 #ylab <- paste(ylab, ' %', sep = '')
389 xmin <- min(afc$rowcoord[,1], na.rm = TRUE) + (0.1 * min(afc$rowcoord[,1], na.rm = TRUE))
390 xmax <- max(afc$rowcoord[,1], na.rm = TRUE) + (0.1 * max(afc$rowcoord[,1], na.rm = TRUE))
391 ymin <- min(afc$rowcoord[,2], na.rm = TRUE) + (0.1 * min(afc$rowcoord[,2], na.rm = TRUE))
392 ymax <- max(afc$rowcoord[,2], na.rm = TRUE) + (0.1 * max(afc$rowcoord[,2], na.rm = TRUE))
399 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)
400 """ % (DictChdTxtOut['AFC2DL_OUT'])
402 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)
403 """ % (DictChdTxtOut['AFC2DSL_OUT'])
405 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)
406 """ % (DictChdTxtOut['AFC2DEL_OUT'])
408 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col=TRUE, what='coord', xlab = xlab, ylab = ylab, xmin=xmin, xmax=xmax, ymin = ymin, ymax=ymax)
409 """ % (DictChdTxtOut['AFC2DCL_OUT'])
411 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
412 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debsup, fin=(debet-1), xlab = xlab, ylab = ylab)
413 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debet, fin=fin, xlab = xlab, ylab = ylab)
414 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col=TRUE, what='crl', xlab = xlab, ylab = ylab)
415 # """ % (DictChdTxtOut['AFC2DCoul'], DictChdTxtOut['AFC2DCoulSup'], DictChdTxtOut['AFC2DCoulEt'], DictChdTxtOut['AFC2DCoulCl'])
424 save.image(file="%s")
425 """ % DictChdTxtOut['RData']
426 file = open(DictChdTxtOut['RTxtProfGraph'], 'w')
431 def write_afc_graph(self):
432 if self.param['over'] : over = 'TRUE'
433 else : over = 'FALSE'
435 if self.param['do_select_nb'] : do_select_nb = 'TRUE'
436 else : do_select_nb = 'FALSE'
438 if self.param['do_select_chi'] : do_select_chi = 'TRUE'
439 else : do_select_chi = 'FALSE'
441 if self.param['do_select_chi_classe'] : do_select_chi_classe = 'TRUE'
442 else : do_select_chi_classe = 'FALSE'
444 if self.param['cex_txt'] : cex_txt = 'TRUE'
445 else : cex_txt = 'FALSE'
447 if self.param['tchi'] : tchi = 'TRUE'
448 else : tchi = 'FALSE'
450 if self.param['svg'] : svg = 'TRUE'
453 with open(self.RscriptsPath['afc_graph'], 'r') as f:
456 # self.DictPathOut['RData'], \
457 scripts = txt % (self.RscriptsPath['Rgraph'],\
458 self.param['typegraph'], \
459 self.param['what'], \
460 self.param['facteur'][0],\
461 self.param['facteur'][1], \
462 self.param['facteur'][2], \
464 over, do_select_nb, \
465 self.param['select_nb'], \
467 self.param['select_chi'], \
468 do_select_chi_classe, \
469 self.param['nbchic'], \
471 self.param['txt_min'], \
472 self.param['txt_max'], \
474 self.param['width'], \
475 self.param['height'],\
476 self.param['taillecar'], \
477 self.param['alpha'], \
478 self.param['film'], \
480 self.param['tchi_min'],\
481 self.param['tchi_max'],\
482 ffr(os.path.dirname(self.fileout)),\
486 def print_simi3d(self):
487 simi3d = self.parent.simi3dpanel
488 txt = '#Fichier genere par Iramuteq'
489 if simi3d.movie.GetValue() :
490 movie = "'" + ffr(os.path.dirname(self.DictPathOut['RData'])) + "'"
494 #if self.corpus.parametres['type'] == 'corpus' :
500 dm<-read.csv2("%s",row.names=1,header = %s)
502 """ % (self.DictPathOut['Contout'], header, self.DictPathOut['RData'])
506 """ % self.parent.RscriptsPath['Rgraph']
510 make.simi.afc(dm,chistabletot, lim=%i, alpha = %.2f, movie = %s)
511 """ % (simi3d.spin_1.GetValue(), float(simi3d.slider_1.GetValue())/100, movie)
512 tmpfile = tempfile.mktemp(dir=self.parent.TEMPDIR)
513 tmp = open(tmpfile,'w')
518 def dendroandbarplot(table, rownames, colnames, rgraph, tmpgraph, intxt = False, dendro=False) :
520 txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
521 rownb = len(rownames)
522 rownames = 'c("' + '","'.join(rownames) + '")'
523 colnames = 'c("' + '","'.join(colnames) + '")'
527 di <- matrix(data=%s, nrow=%i, byrow = TRUE)
530 """ % (txttable, rownb, rownames, colnames)
537 height <- (30*ncol(di)) + (15*nrow(di))
538 height <- ifelse(height <= 400, 400, height)
540 open_file_graph("%s", width=width, height=height)
541 plot.dendro.lex(tree.cut1$tree.cl, di)
542 """ % (ffr(dendro),ffr(rgraph), ffr(tmpgraph))
545 def barplot(table, rownames, colnames, rgraph, tmpgraph, intxt = False) :
547 txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
548 #width = 100 + (15 * len(rownames)) + (100 * len(colnames))
549 #height = len(rownames) * 15
550 rownb = len(rownames)
553 rownames = 'c("' + '","'.join(rownames) + '")'
554 colnames = 'c("' + '","'.join(colnames) + '")'
558 di <- matrix(data=%s, nrow=%i, byrow = TRUE)
559 toinf <- which(di == Inf)
560 tominf <- which(di == -Inf)
563 valmax <- max(di, na.rm = TRUE)
571 if (length(tominf)) {
573 valmin <- min(di, na.rm = TRUE)
583 """ % (txttable, rownb, rownames, colnames)
588 color = rainbow(nrow(di))
589 width <- 100 + (20*length(rownames(di))) + (100 * length(colnames(di)))
590 height <- nrow(di) * 15
591 if (height < 400) { height <- 400}
592 open_file_graph("%s",width = width, height = height)
594 layout(matrix(c(1,2),1,2, byrow=TRUE),widths=c(3,lcm(7)))
596 yp = ifelse(length(toinf), 0.2, 0)
597 ym = ifelse(length(tominf), 0.2, 0)
598 ymin <- ifelse(!length(which(di < 0)), 0, min(di) - ym)
599 coord <- barplot(as.matrix(di), beside = TRUE, col = color, space = c(0.1,0.6), ylim=c(ymin, max(di) + yp))
601 coordinf <- coord[toinf]
603 text(x=coordinf, y=valinf + 0.1, 'i')
605 if (length(tominf)) {
606 coordinf <- coord[toinf]
608 text(x=coordinf, y=valinf - 0.1, 'i')
614 lcoord <- apply(cc, 1, mean)
617 amp <- abs(max(di) - min(di))
624 d <- signif(amp%%/%%10,1)
629 if ((i/d) == (i%%/%%d)) {
634 plot(0, axes = FALSE, pch = '')
635 legend(x = 'center' , rownames(di), fill = color)
637 """ % (rgraph, ffr(tmpgraph))
640 #def RAfcUci(DictAfcUciOut, nd=2, RscriptsPath='', PARCEX='0.8'):
646 # dataact<-read.csv2("%s")
647 # """ % (DictAfcUciOut['TableCont'])#, encoding)
649 # datasup<-read.csv2("%s")
650 # """ % (DictAfcUciOut['TableSup'])#, encoding)
652 # dataet<-read.csv2("%s")
653 # """ % (DictAfcUciOut['TableEt'])#, encoding)
655 # datatotsup<-cbind(dataact,datasup)
656 # datatotet<-cbind(dataact,dataet)
657 # afcact<-ca(dataact,nd=nd)
658 # afcsup<-ca(datatotsup,supcol=((ncol(dataact)+1):ncol(datatotsup)),nd=nd)
659 # afcet<-ca(datatotet,supcol=((ncol(dataact)+1):ncol(datatotet)),nd=nd)
660 # afctot<-afcsup$colcoord
661 # rownames(afctot)<-afcsup$colnames
662 # colnames(afctot)<-paste('coord. facteur',1:nd,sep=' ')
663 # afctot<-cbind(afctot,mass=afcsup$colmass)
664 # afctot<-cbind(afctot,distance=afcsup$coldist)
665 # afctot<-cbind(afctot,intertie=afcsup$colinertia)
666 # rcolet<-afcet$colsup
667 # afctmp<-afcet$colcoord[rcolet,]
668 # rownames(afctmp)<-afcet$colnames[rcolet]
669 # afctmp<-cbind(afctmp,afcet$colmass[rcolet])
670 # afctmp<-cbind(afctmp,afcet$coldist[rcolet])
671 # afctmp<-cbind(afctmp,afcet$colinertia[rcolet])
672 # afctot<-rbind(afctot,afctmp)
673 # write.csv2(afctot,file = "%s")
675 # """ % (DictAfcUciOut['afc_row'], RscriptsPath['Rgraph'])
681 # PlotAfc(afcet,filename="%s",toplot=c%s, PARCEX=PARCEX)
682 # """ % (DictAfcUciOut['AfcColAct'], "('none','active')")
684 # PlotAfc(afcsup,filename="%s",toplot=c%s, PARCEX=PARCEX)
685 # """ % (DictAfcUciOut['AfcColSup'], "('none','passive')")
686 # txt += """PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
687 # """ % (DictAfcUciOut['AfcColEt'], "('none','passive')")
689 # PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
690 # """ % (DictAfcUciOut['AfcRow'], "('all','none')")
691 # f = open(DictAfcUciOut['Rafcuci'], 'w')
695 class PrintSimiScript(PrintRScript) :
696 def make_script(self) :
698 self.packages(['igraph', 'proxy', 'Matrix'])
699 self.sources([self.analyse.parent.RscriptsPath['simi'], self.analyse.parent.RscriptsPath['Rgraph']])
701 if not self.parametres['keep_coord'] :
706 """ % (self.pathout['mat01.csv'], self.pathout['actives.csv'], self.pathout['selected.csv'])
709 cn <- read.table(cn.path, sep='\t', quote='"')
710 colnames(dm) <- cn[,1]
711 sel.col <- read.csv2(selected.col)
712 dm <- dm[, sel.col[,1] + 1]
717 """ % self.pathout['RData.RData']
719 if self.parametres['coeff'] == 0 :
721 if not self.parametres['keep_coord'] :
727 if not self.parametres['keep_coord'] :
731 if self.parametres['coeff'] == 1 :
735 mat <- simil(dm, method = 'Russel', diag = TRUE, upper = TRUE, by_rows = FALSE)
737 elif self.analyse.indices[self.parametres['coeff']] == 'binomial' :
739 if not self.parametres['keep_coord'] :
744 elif self.parametres['coeff'] != 0 :
745 method = self.analyse.indices[self.parametres['coeff']]
746 if not self.parametres['keep_coord'] :
749 mat <- simil(dm, method = method, diag = TRUE, upper = TRUE, by_rows = FALSE)
750 """ % self.analyse.indices[self.parametres['coeff']]
751 if not self.parametres['keep_coord'] :
753 mat <- as.matrix(stats::as.dist(mat,diag=TRUE,upper=TRUE))
755 mat[is.infinite(mat)] <- 0
757 if self.parametres['layout'] == 0 : layout = 'random'
758 if self.parametres['layout'] == 1 : layout = 'circle'
759 if self.parametres['layout'] == 2 : layout = 'frutch'
760 if self.parametres['layout'] == 3 : layout = 'kawa'
761 if self.parametres['layout'] == 4 : layout = 'graphopt'
765 if self.parametres['type_graph'] == 0 : type = 'tkplot'
766 if self.parametres['type_graph'] == 1 :
769 dirout = os.path.dirname(self.pathout['mat01'])
770 while os.path.exists(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png')):
772 self.filename = ffr(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png'))
773 if self.parametres['type_graph'] == 2 : type = 'rgl'
775 if self.parametres['arbremax'] :
777 self.txtgraph += ' - arbre maximum'
778 else : arbremax = 'FALSE'
780 if self.parametres['coeff_tv'] :
781 coeff_tv = self.parametres['coeff_tv_nb']
782 tvminmax = 'c(NULL,NULL)'
783 elif not self.parametres['coeff_tv'] or self.parametres.get('sformchi', False) :
785 tvminmax = 'c(%i, %i)' %(self.parametres['tvmin'], self.parametres['tvmax'])
786 if self.parametres['coeff_te'] : coeff_te = 'c(%i,%i)' % (self.parametres['coeff_temin'], self.parametres['coeff_temax'])
787 else : coeff_te = 'NULL'
789 if self.parametres['vcex'] or self.parametres.get('cexfromchi', False) :
790 vcexminmax = 'c(%i/10,%i/10)' % (self.parametres['vcexmin'],self.parametres['vcexmax'])
792 vcexminmax = 'c(NULL,NULL)'
793 if not self.parametres['label_v'] : label_v = 'FALSE'
794 else : label_v = 'TRUE'
796 if not self.parametres['label_e'] : label_e = 'FALSE'
797 else : label_e = 'TRUE'
799 if self.parametres['seuil_ok'] : seuil = str(self.parametres['seuil'])
800 else : seuil = 'NULL'
802 cols = str(self.parametres['cols']).replace(')',', max=255)')
803 cola = str(self.parametres['cola']).replace(')',',max=255)')
813 """ % self.parametres['cex']
815 if self.parametres['film'] :
818 """ % self.pathout['film']
830 """ % (label_v, label_e)
838 """ % (self.parametres['width'], self.parametres['height'])
839 if self.parametres['keep_coord'] :
841 coords <- try(coords, TRUE)
842 if (!is.matrix(coords)) {
852 """ % self.parametres['alpha']
855 """ % self.parametres['alpha']
856 #############################################
857 if self.parametres.get('bystar',False) :
861 for i, line in enumerate(self.parametres['listet']) :
864 """ % (i+1, ','.join([`val + 1` for val in line]))
867 """ % ("','".join([val for val in self.parametres['selectedstars']]))
871 for (i in 1:length(unetoile)) {
874 if (length(tosum) > 1) {
875 fsum <- cbind(fsum, colSums(dm[tosum,]))
877 fsum <- cbind(fsum, dm[tosum,])
881 lex <- AsLexico2(fsum, chip=TRUE)
882 dcol <- apply(lex[[4]],1,which.max)
883 toblack <- apply(lex[[4]],1,max)
884 gcol <- rainbow(length(unetoile))
886 vertex.label.color <- gcol[dcol]
887 vertex.label.color[which(toblack <= 3.84)] <- 'black'
888 leg <- list(unetoile=unetoile, gcol=gcol)
889 cols <- vertex.label.color
890 chivertex.size <- norm.vec(toblack, vcexminmax[1], vcexminmax[2])
892 """ % (self.analyse.parent.RscriptsPath['chdfunct'])
895 vertex.label.color <- 'black'
899 #############################################
903 # g.ori <- graph.adjacency(mat, mode='lower', weighted = TRUE)
904 # w.ori <- E(g.ori)$weight
906 # if (method == 'cooc') {
907 # E(g.ori)$weight <- 1 / w.ori
909 # E(g.ori)$weigth <- 1 - w.ori
911 # g.max <- minimum.spanning.tree(g.ori)
912 # if (method == 'cooc') {
913 # E(g.max)$weight <- 1 / E(g.max)$weight
915 # E(g.max)$weight <- 1 - E(g.max)$weight
924 x <- list(mat = mat, eff = eff)
925 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)
926 """ % (method, type, layout, arbremax, coeff_tv, coeff_te)
928 if self.parametres.get('bystar',False) :
929 if self.parametres.get('cexfromchi', False) :
931 label.cex<-chivertex.size
937 if self.parametres.get('sfromchi', False) :
939 vertex.size <- norm.vec(toblack, minmaxeff[1], minmaxeff[2])
950 lchi <- read.table("%s")
953 if 'selected_col' in dir(self.tableau) :
957 if tmpchi and self.parametres.get('cexfromchi', False) :
959 label.cex <- norm.vec(lchi, vcexminmax[1], vcexminmax[2])
963 if (is.null(vcexminmax[1])) {
966 label.cex <- graph.simi$label.cex
969 if tmpchi and self.parametres.get('sfromchi', False) :
971 vertex.size <- norm.vec(lchi, minmaxeff[1], minmaxeff[2])
975 if (is.null(minmaxeff[1])) {
978 vertex.size <- graph.simi$eff
981 txt += """ vertex.size <- NULL """
983 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)
984 save.image(file="%s")
985 """ % (type, self.filename, self.pathout['RData'])
990 class WordCloudRScript(PrintRScript) :
991 def make_script(self) :
992 self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
993 self.packages(['wordcloud'])
994 bg_col = Rcolor(self.parametres['col_bg'])
995 txt_col = Rcolor(self.parametres['col_text'])
997 act <- read.csv2("%s", header = FALSE, row.names=1, sep='\t')
998 selected.col <- read.table("%s")
999 toprint <- as.matrix(act[selected.col[,1] + 1,])
1000 rownames(toprint) <- rownames(act)[selected.col[,1] + 1]
1002 if (nrow(toprint) > maxword) {
1003 toprint <- as.matrix(toprint[order(toprint[,1], decreasing=TRUE),])
1004 toprint <- as.matrix(toprint[1:maxword,])
1006 open_file_graph("%s", width = %i, height = %i)
1008 wordcloud(row.names(toprint), toprint[,1], scale=c(%f,%f), random.order=FALSE, colors=rgb%s)
1010 """ % (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)