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\n" % 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:
199 if (classif_mode == 0) {
200 chd.result <- Rchdtxt(uceout, chd1, chd2 = chd2, mincl = mincl,classif_mode = classif_mode, nbt = nbt)
202 chd.result <- Rchdtxt(uceout, chd1, chd2 = chd1, mincl = mincl,classif_mode = classif_mode, nbt = nbt)
205 classeuce1 <- chd.result$cuce1
206 classeuce2 <- chd.result$cuce2
207 """ % (classif_mode, mincl, DicoPath['uce'])
210 tree.tot1 <- make_tree_tot(chd1)
211 # open_file_graph("%s", widt = 600, height=400)
212 # plot(tree.tot1$tree.cl)
214 """%DicoPath['arbre1']
216 if classif_mode == 0:
218 tree.tot2 <- make_tree_tot(chd2)
219 # open_file_graph("%s", width = 600, height=400)
220 # plot(tree.tot2$tree.cl)
222 """ % DicoPath['arbre2']
225 tree.cut1 <- make_dendro_cut_tuple(tree.tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
226 save(tree.cut1, file="%s")
227 classes<-n1[,ncol(n1)]
228 open_file_graph("%s", width = 600, height=400)
229 plot.dendropr(tree.cut1$tree.cl,classes, histo=TRUE)
230 open_file_graph("%s", width = 600, height=400)
231 plot(tree.cut1$dendro_tot_cl)
233 """ % (DicoPath['Rdendro'], DicoPath['dendro1'], DicoPath['arbre1'])
235 if classif_mode == 0:
237 tree.cut2 <- make_dendro_cut_tuple(tree.tot2$dendro_tuple, chd.result$coord_ok, classeuce2, 2, nbt)
238 open_file_graph("%s", width = 600, height=400)
239 plot(tree.cut2$tree.cl)
241 open_file_graph("%s", width = 600, height=400)
242 plot(tree.cut1$dendro_tot_cl)
244 """ % (DicoPath['dendro2'], DicoPath['arbre2'])
247 save.image(file="%s")
248 """ % DicoPath['RData']
249 fileout = open(DicoPath['Rchdtxt'], 'w')
253 def RPamTxt(corpus, RscriptPath):
254 DicoPath = corpus.pathout
255 param = corpus.parametres
258 """ % (RscriptPath['pamtxt'])
261 """ % (RscriptPath['Rgraph'])
263 result <- pamtxt("%s", "%s", "%s", method = "%s", clust_type = "%s", clnb = %i)
265 """ % (DicoPath['TableUc1'], DicoPath['listeuce1'], DicoPath['uce'], param['method'], param['cluster_type'], param['nbcl'] )
267 open_file_graph("%s", width=400, height=400)
270 """ % (DicoPath['arbre1'])
272 save.image(file="%s")
273 """ % DicoPath['RData']
274 fileout = open(DicoPath['Rchdtxt'], 'w')
279 def RchdQuest(DicoPath, RscriptPath, nbcl = 10, mincl = 10):
285 """ % (RscriptPath['CHD'], RscriptPath['chdquest'], RscriptPath['anacor'],RscriptPath['Rgraph'])
293 chd.result<-Rchdquest("%s","%s","%s", nbt = nbt, mincl = mincl)
295 classeuce1 <- chd.result$cuce1
296 """ % (DicoPath['mat01'], DicoPath['listeuce1'], DicoPath['uce'])
299 tree_tot1 <- make_tree_tot(chd.result$chd)
300 open_file_graph("%s", width = 600, height=400)
301 plot(tree_tot1$tree.cl)
303 """%DicoPath['arbre1']
306 tree_cut1 <- make_dendro_cut_tuple(tree_tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
307 tree.cut1 <- tree_cut1
308 save(tree.cut1, file="%s")
309 open_file_graph("%s", width = 600, height=400)
310 classes<-n1[,ncol(n1)]
311 plot.dendropr(tree_cut1$tree.cl,classes, histo = TRUE)
312 """ % (DicoPath['Rdendro'],DicoPath['dendro1'])
315 save.image(file="%s")
316 """ % DicoPath['RData']
317 fileout = open(DicoPath['Rchdquest'], 'w')
321 def AlcesteTxtProf(DictChdTxtOut, RscriptsPath, clnb, taillecar):
322 txt = "clnb<-%i\n" % clnb
326 """ % (RscriptsPath['chdfunct'], DictChdTxtOut['RData'])
328 dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
329 datasup<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
330 dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
331 """ % (DictChdTxtOut['Contout'], DictChdTxtOut['ContSupOut'], DictChdTxtOut['ContEtOut'])
333 tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
334 tablesqrpsup<-BuildProf(as.matrix(datasup),n1,clnb)
335 tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
338 PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s",tablesqrpsup[4],tablesqrpsup[5])
339 """ % (DictChdTxtOut['PROFILE_OUT'], DictChdTxtOut['ANTIPRO_OUT'])
341 colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
342 colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
343 colnames(tablesqrpsup[[2]])<-paste('classe',1:clnb,sep=' ')
344 colnames(tablesqrpsup[[1]])<-paste('classe',1:clnb,sep=' ')
345 colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
346 colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
347 chistabletot<-rbind(tablesqrpact[2][[1]],tablesqrpsup[2][[1]])
348 chistabletot<-rbind(chistabletot,tablesqrpet[2][[1]])
349 ptabletot<-rbind(tablesqrpact[1][[1]],tablesqrpet[1][[1]])
352 write.csv2(chistabletot,file="%s")
353 write.csv2(ptabletot,file="%s")
355 write.csv2(gbcluster,file="%s")
356 """ % (DictChdTxtOut['chisqtable'], DictChdTxtOut['ptable'], DictChdTxtOut['SbyClasseOut'])
360 colnames(dataact)<-paste('classe',1:clnb,sep=' ')
361 colnames(datasup)<-paste('classe',1:clnb,sep=' ')
362 colnames(dataet)<-paste('classe',1:clnb,sep=' ')
363 rowtot<-nrow(dataact)+nrow(dataet)+nrow(datasup)
364 afctable<-rbind(as.matrix(dataact),as.matrix(datasup))
365 afctable<-rbind(afctable,as.matrix(dataet))
366 colnames(afctable)<-paste('classe',1:clnb,sep=' ')
367 afc<-ca(afctable,suprow=((nrow(dataact)+1):rowtot),nd=(ncol(afctable)-1))
368 debsup<-nrow(dataact)+1
369 debet<-nrow(dataact)+nrow(datasup)+1
371 afc<-AddCorrelationOk(afc)
373 #FIXME : split this!!!
376 """ % RscriptsPath['Rgraph']
379 afc <- summary.ca.dm(afc)
380 afc_table <- create_afc_table(afc)
381 write.csv2(afc_table$facteur, file = "%s")
382 write.csv2(afc_table$colonne, file = "%s")
383 write.csv2(afc_table$ligne, file = "%s")
384 """ % (DictChdTxtOut['afc_facteur'], DictChdTxtOut['afc_col'], DictChdTxtOut['afc_row'])
390 xyminmax <- PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
391 """ % (DictChdTxtOut['AFC2DL_OUT'])
393 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])
394 """ % (DictChdTxtOut['AFC2DSL_OUT'])
396 if ((fin - debet) > 2) {
397 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])
399 """ % (DictChdTxtOut['AFC2DEL_OUT'])
401 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])
402 """ % (DictChdTxtOut['AFC2DCL_OUT'])
404 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
405 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debsup, fin=(debet-1), xlab = xlab, ylab = ylab)
406 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debet, fin=fin, xlab = xlab, ylab = ylab)
407 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col=TRUE, what='crl', xlab = xlab, ylab = ylab)
408 # """ % (DictChdTxtOut['AFC2DCoul'], DictChdTxtOut['AFC2DCoulSup'], DictChdTxtOut['AFC2DCoulEt'], DictChdTxtOut['AFC2DCoulCl'])
417 save.image(file="%s")
418 """ % DictChdTxtOut['RData']
419 file = open(DictChdTxtOut['RTxtProfGraph'], 'w')
424 def write_afc_graph(self):
425 if self.param['over'] : over = 'TRUE'
426 else : over = 'FALSE'
428 if self.param['do_select_nb'] : do_select_nb = 'TRUE'
429 else : do_select_nb = 'FALSE'
431 if self.param['do_select_chi'] : do_select_chi = 'TRUE'
432 else : do_select_chi = 'FALSE'
434 if self.param['do_select_chi_classe'] : do_select_chi_classe = 'TRUE'
435 else : do_select_chi_classe = 'FALSE'
437 if self.param['cex_txt'] : cex_txt = 'TRUE'
438 else : cex_txt = 'FALSE'
440 if self.param['tchi'] : tchi = 'TRUE'
441 else : tchi = 'FALSE'
443 if self.param['svg'] : svg = 'TRUE'
446 with open(self.RscriptsPath['afc_graph'], 'r') as f:
449 # self.DictPathOut['RData'], \
450 scripts = txt % (self.RscriptsPath['Rgraph'],\
451 self.param['typegraph'], \
452 self.param['what'], \
453 self.param['facteur'][0],\
454 self.param['facteur'][1], \
455 self.param['facteur'][2], \
457 over, do_select_nb, \
458 self.param['select_nb'], \
460 self.param['select_chi'], \
461 do_select_chi_classe, \
462 self.param['nbchic'], \
464 self.param['txt_min'], \
465 self.param['txt_max'], \
467 self.param['width'], \
468 self.param['height'],\
469 self.param['taillecar'], \
470 self.param['alpha'], \
471 self.param['film'], \
473 self.param['tchi_min'],\
474 self.param['tchi_max'],\
475 ffr(os.path.dirname(self.fileout)),\
479 def print_simi3d(self):
480 simi3d = self.parent.simi3dpanel
481 txt = '#Fichier genere par Iramuteq'
482 if simi3d.movie.GetValue() :
483 movie = "'" + ffr(os.path.dirname(self.DictPathOut['RData'])) + "'"
487 #if self.corpus.parametres['type'] == 'corpus' :
493 dm<-read.csv2("%s",row.names=1,header = %s)
495 """ % (self.DictPathOut['Contout'], header, self.DictPathOut['RData'])
499 """ % self.parent.RscriptsPath['Rgraph']
503 make.simi.afc(dm,chistabletot, lim=%i, alpha = %.2f, movie = %s)
504 """ % (simi3d.spin_1.GetValue(), float(simi3d.slider_1.GetValue())/100, movie)
505 tmpfile = tempfile.mktemp(dir=self.parent.TEMPDIR)
506 tmp = open(tmpfile,'w')
511 def dendroandbarplot(table, rownames, colnames, rgraph, tmpgraph, intxt = False, dendro=False) :
513 txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
514 rownb = len(rownames)
515 rownames = 'c("' + '","'.join(rownames) + '")'
516 colnames = 'c("' + '","'.join(colnames) + '")'
520 di <- matrix(data=%s, nrow=%i, byrow = TRUE)
523 """ % (txttable, rownb, rownames, colnames)
530 height <- (30*ncol(di)) + (15*nrow(di))
531 height <- ifelse(height <= 400, 400, height)
533 open_file_graph("%s", width=width, height=height)
534 plot.dendro.lex(tree.cut1$tree.cl, di)
535 """ % (ffr(dendro),ffr(rgraph), ffr(tmpgraph))
538 def barplot(table, rownames, colnames, rgraph, tmpgraph, intxt = False) :
540 txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
541 #width = 100 + (15 * len(rownames)) + (100 * len(colnames))
542 #height = len(rownames) * 15
543 rownb = len(rownames)
546 rownames = 'c("' + '","'.join(rownames) + '")'
547 colnames = 'c("' + '","'.join(colnames) + '")'
551 di <- matrix(data=%s, nrow=%i, byrow = TRUE)
552 toinf <- which(di == Inf)
553 tominf <- which(di == -Inf)
556 valmax <- max(di, na.rm = TRUE)
564 if (length(tominf)) {
566 valmin <- min(di, na.rm = TRUE)
576 """ % (txttable, rownb, rownames, colnames)
581 color = rainbow(nrow(di))
582 width <- 100 + (20*length(rownames(di))) + (100 * length(colnames(di)))
583 height <- nrow(di) * 15
584 if (height < 400) { height <- 400}
585 open_file_graph("%s",width = width, height = height)
587 layout(matrix(c(1,2),1,2, byrow=TRUE),widths=c(3,lcm(7)))
589 yp = ifelse(length(toinf), 0.2, 0)
590 ym = ifelse(length(tominf), 0.2, 0)
591 ymin <- ifelse(!length(which(di < 0)), 0, min(di) - ym)
592 coord <- barplot(as.matrix(di), beside = TRUE, col = color, space = c(0.1,0.6), ylim=c(ymin, max(di) + yp))
594 coordinf <- coord[toinf]
596 text(x=coordinf, y=valinf + 0.1, 'i')
598 if (length(tominf)) {
599 coordinf <- coord[toinf]
601 text(x=coordinf, y=valinf - 0.1, 'i')
607 lcoord <- apply(cc, 1, mean)
610 amp <- abs(max(di) - min(di))
617 d <- signif(amp%%/%%10,1)
622 if ((i/d) == (i%%/%%d)) {
627 plot(0, axes = FALSE, pch = '')
628 legend(x = 'center' , rownames(di), fill = color)
630 """ % (rgraph, ffr(tmpgraph))
633 #def RAfcUci(DictAfcUciOut, nd=2, RscriptsPath='', PARCEX='0.8'):
639 # dataact<-read.csv2("%s")
640 # """ % (DictAfcUciOut['TableCont'])#, encoding)
642 # datasup<-read.csv2("%s")
643 # """ % (DictAfcUciOut['TableSup'])#, encoding)
645 # dataet<-read.csv2("%s")
646 # """ % (DictAfcUciOut['TableEt'])#, encoding)
648 # datatotsup<-cbind(dataact,datasup)
649 # datatotet<-cbind(dataact,dataet)
650 # afcact<-ca(dataact,nd=nd)
651 # afcsup<-ca(datatotsup,supcol=((ncol(dataact)+1):ncol(datatotsup)),nd=nd)
652 # afcet<-ca(datatotet,supcol=((ncol(dataact)+1):ncol(datatotet)),nd=nd)
653 # afctot<-afcsup$colcoord
654 # rownames(afctot)<-afcsup$colnames
655 # colnames(afctot)<-paste('coord. facteur',1:nd,sep=' ')
656 # afctot<-cbind(afctot,mass=afcsup$colmass)
657 # afctot<-cbind(afctot,distance=afcsup$coldist)
658 # afctot<-cbind(afctot,intertie=afcsup$colinertia)
659 # rcolet<-afcet$colsup
660 # afctmp<-afcet$colcoord[rcolet,]
661 # rownames(afctmp)<-afcet$colnames[rcolet]
662 # afctmp<-cbind(afctmp,afcet$colmass[rcolet])
663 # afctmp<-cbind(afctmp,afcet$coldist[rcolet])
664 # afctmp<-cbind(afctmp,afcet$colinertia[rcolet])
665 # afctot<-rbind(afctot,afctmp)
666 # write.csv2(afctot,file = "%s")
668 # """ % (DictAfcUciOut['afc_row'], RscriptsPath['Rgraph'])
674 # PlotAfc(afcet,filename="%s",toplot=c%s, PARCEX=PARCEX)
675 # """ % (DictAfcUciOut['AfcColAct'], "('none','active')")
677 # PlotAfc(afcsup,filename="%s",toplot=c%s, PARCEX=PARCEX)
678 # """ % (DictAfcUciOut['AfcColSup'], "('none','passive')")
679 # txt += """PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
680 # """ % (DictAfcUciOut['AfcColEt'], "('none','passive')")
682 # PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
683 # """ % (DictAfcUciOut['AfcRow'], "('all','none')")
684 # f = open(DictAfcUciOut['Rafcuci'], 'w')
688 class PrintSimiScript(PrintRScript) :
689 def make_script(self) :
691 self.packages(['igraph', 'proxy', 'Matrix'])
692 self.sources([self.analyse.parent.RscriptsPath['simi'], self.analyse.parent.RscriptsPath['Rgraph']])
694 if not self.parametres['keep_coord'] and not self.parametres['type'] == 'simimatrix':
699 """ % (self.pathout['mat01.csv'], self.pathout['actives.csv'], self.pathout['selected.csv'])
700 if 'word' in self.parametres :
704 """ % self.parametres['word']
711 cn <- read.table(cn.path, sep='\t', quote='"')
712 colnames(dm) <- cn[,1]
713 sel.col <- read.csv2(selected.col, header = FALSE)
714 sel.col <- sel.col[,1] + 1
718 forme <- colnames(dm)[index]
719 if (!index %in% sel.col) {
720 sel.col <- append(sel.col, index)
723 index <- which(colnames(dm) == forme)
726 elif not self.parametres['keep_coord'] and self.parametres['type'] == 'simimatrix' :
730 """ % (self.pathout['mat01.csv'], self.pathout['selected.csv'])
731 if 'word' in self.parametres :
735 """ % self.parametres['word']
741 dm <-read.csv2(dm.path)
743 sel.col <- read.csv2(selected.col, header = FALSE)
744 sel.col <- sel.col[,1] + 1
748 forme <- colnames(dm)[index]
749 if (!index %in% sel.col) {
750 sel.col <- append(sel.col, index)
753 index <- which(colnames(dm) == forme)
759 """ % self.pathout['RData.RData']
761 if self.parametres['coeff'] == 0 :
763 if not self.parametres['keep_coord'] :
769 if not self.parametres['keep_coord'] :
773 if self.parametres['coeff'] == 1 :
777 mat <- simil(dm, method = 'Russel', diag = TRUE, upper = TRUE, by_rows = FALSE)
779 elif self.analyse.indices[self.parametres['coeff']] == 'binomial' :
781 if not self.parametres['keep_coord'] :
786 elif self.parametres['coeff'] != 0 :
787 method = self.analyse.indices[self.parametres['coeff']]
788 if not self.parametres['keep_coord'] :
791 mat <- simil(dm, method = method, diag = TRUE, upper = TRUE, by_rows = FALSE)
792 """ % self.analyse.indices[self.parametres['coeff']]
793 if not self.parametres['keep_coord'] :
795 mat <- as.matrix(stats::as.dist(mat,diag=TRUE,upper=TRUE))
797 if (length(which(mat == Inf))) {
798 infp <- which(mat == Inf)
800 maxmat <- max(mat, na.rm = TRUE)
808 if (length(which(mat == -Inf))) {
809 infm <- which(mat == -Inf)
811 minmat <- min(mat, na.rm = TRUE)
820 if 'word' in self.parametres and not self.parametres['keep_coord'] :
822 mat <- graph.word(mat, index)
824 if (length(cs)) mat <- mat[,-which(cs==0)]
826 if (length(rs)) mat <- mat[-which(rs==0),]
827 if (length(cs)) dm <- dm[, -which(cs==0)]
830 if self.parametres['layout'] == 0 : layout = 'random'
831 if self.parametres['layout'] == 1 : layout = 'circle'
832 if self.parametres['layout'] == 2 : layout = 'frutch'
833 if self.parametres['layout'] == 3 : layout = 'kawa'
834 if self.parametres['layout'] == 4 : layout = 'graphopt'
838 if self.parametres['type_graph'] == 0 : type = 'tkplot'
839 if self.parametres['type_graph'] == 1 :
842 dirout = os.path.dirname(self.pathout['mat01'])
843 while os.path.exists(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png')):
845 self.filename = ffr(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png'))
846 if self.parametres['type_graph'] == 2 : type = 'rgl'
848 if self.parametres['arbremax'] :
850 self.txtgraph += ' - arbre maximum'
851 else : arbremax = 'FALSE'
853 if self.parametres['coeff_tv'] :
854 coeff_tv = self.parametres['coeff_tv_nb']
855 tvminmax = 'c(NULL,NULL)'
856 elif not self.parametres['coeff_tv'] or self.parametres.get('sformchi', False) :
858 tvminmax = 'c(%i, %i)' %(self.parametres['tvmin'], self.parametres['tvmax'])
859 if self.parametres['coeff_te'] : coeff_te = 'c(%i,%i)' % (self.parametres['coeff_temin'], self.parametres['coeff_temax'])
860 else : coeff_te = 'NULL'
862 if self.parametres['vcex'] or self.parametres.get('cexfromchi', False) :
863 vcexminmax = 'c(%i/10,%i/10)' % (self.parametres['vcexmin'],self.parametres['vcexmax'])
865 vcexminmax = 'c(NULL,NULL)'
866 if not self.parametres['label_v'] : label_v = 'FALSE'
867 else : label_v = 'TRUE'
869 if not self.parametres['label_e'] : label_e = 'FALSE'
870 else : label_e = 'TRUE'
872 if self.parametres['seuil_ok'] : seuil = str(self.parametres['seuil'])
873 else : seuil = 'NULL'
875 cols = str(self.parametres['cols']).replace(')',', max=255)')
876 cola = str(self.parametres['cola']).replace(')',',max=255)')
886 """ % self.parametres['cex']
888 if self.parametres['film'] :
891 """ % self.pathout['film']
903 """ % (label_v, label_e)
911 """ % (self.parametres['width'], self.parametres['height'])
912 if self.parametres['keep_coord'] :
914 coords <- try(coords, TRUE)
915 if (!is.matrix(coords)) {
925 """ % self.parametres['alpha']
928 """ % self.parametres['alpha']
929 #############################################
930 if self.parametres.get('bystar',False) :
934 for i, line in enumerate(self.parametres['listet']) :
937 """ % (i+1, ','.join([`val + 1` for val in line]))
940 """ % ("','".join([val for val in self.parametres['selectedstars']]))
944 for (i in 1:length(unetoile)) {
947 if (length(tosum) > 1) {
948 fsum <- cbind(fsum, colSums(dm[tosum,]))
950 fsum <- cbind(fsum, dm[tosum,])
954 lex <- AsLexico2(fsum, chip=TRUE)
955 dcol <- apply(lex[[4]],1,which.max)
956 toblack <- apply(lex[[4]],1,max)
957 gcol <- rainbow(length(unetoile))
959 vertex.label.color <- gcol[dcol]
960 vertex.label.color[which(toblack <= 3.84)] <- 'black'
961 leg <- list(unetoile=unetoile, gcol=gcol)
962 cols <- vertex.label.color
963 chivertex.size <- norm.vec(toblack, vcexminmax[1], vcexminmax[2])
965 """ % (self.analyse.parent.RscriptsPath['chdfunct'])
968 vertex.label.color <- 'black'
972 #############################################
976 # g.ori <- graph.adjacency(mat, mode='lower', weighted = TRUE)
977 # w.ori <- E(g.ori)$weight
979 # if (method == 'cooc') {
980 # E(g.ori)$weight <- 1 / w.ori
982 # E(g.ori)$weigth <- 1 - w.ori
984 # g.max <- minimum.spanning.tree(g.ori)
985 # if (method == 'cooc') {
986 # E(g.max)$weight <- 1 / E(g.max)$weight
988 # E(g.max)$weight <- 1 - E(g.max)$weight
995 if self.parametres['com'] :
996 com = `self.parametres['communities']`
999 if self.parametres['halo'] :
1009 x <- list(mat = mat, eff = eff)
1010 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)
1011 """ % (method, type, layout, arbremax, coeff_tv, coeff_te)
1013 if self.parametres.get('bystar',False) :
1014 if self.parametres.get('cexfromchi', False) :
1016 label.cex<-chivertex.size
1022 if self.parametres.get('sfromchi', False) :
1024 vertex.size <- norm.vec(toblack, minmaxeff[1], minmaxeff[2])
1031 if self.parametres['type'] == 'clustersimitxt' :
1033 lchi <- read.table("%s")
1035 """ % ffr(self.parametres['tmpchi'])
1037 lchi <- lchi[sel.col]
1039 if self.parametres['type'] == 'clustersimitxt' and self.parametres.get('cexfromchi', False) :
1041 label.cex <- norm.vec(lchi, vcexminmax[1], vcexminmax[2])
1045 if (is.null(vcexminmax[1])) {
1048 label.cex <- graph.simi$label.cex
1051 if self.parametres['type'] == 'clustersimitxt' and self.parametres.get('sfromchi', False) :
1053 vertex.size <- norm.vec(lchi, minmaxeff[1], minmaxeff[2])
1054 if (!length(vertex.size)) vertex.size <- 0
1058 if (is.null(minmaxeff[1])) {
1061 vertex.size <- graph.simi$eff
1064 #txt += """ vertex.size <- NULL """
1065 if self.parametres['svg'] : svg = 'TRUE'
1066 else : svg = 'FALSE'
1072 if (!is.null(graph.simi$com)) {
1073 com <- graph.simi$com
1074 colm <- rainbow(length(com))
1075 if (vertex.size != 0 || graph.simi$halo) {
1076 vertex.label.color <- 'black'
1077 vertex.col <- colm[membership(com)]
1079 vertex.label.color <- colm[membership(com)]
1082 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, svg = svg)
1083 save.image(file="%s")
1084 """ % (type, self.filename, self.pathout['RData'])
1089 class WordCloudRScript(PrintRScript) :
1090 def make_script(self) :
1091 self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1092 self.packages(['wordcloud'])
1093 bg_col = Rcolor(self.parametres['col_bg'])
1094 txt_col = Rcolor(self.parametres['col_text'])
1095 if self.parametres['svg'] :
1103 act <- read.csv2("%s", header = FALSE, row.names=1, sep='\t')
1104 selected.col <- read.table("%s")
1105 toprint <- as.matrix(act[selected.col[,1] + 1,])
1106 rownames(toprint) <- rownames(act)[selected.col[,1] + 1]
1108 if (nrow(toprint) > maxword) {
1109 toprint <- as.matrix(toprint[order(toprint[,1], decreasing=TRUE),])
1110 toprint <- as.matrix(toprint[1:maxword,])
1112 open_file_graph("%s", width = %i, height = %i , svg = svg)
1114 wordcloud(row.names(toprint), toprint[,1], scale=c(%f,%f), random.order=FALSE, colors=rgb%s)
1116 """ % (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)