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", encoding = \'utf8\')' % ffr(source))
38 def packages(self, lpks) :
40 self.add('library(%s)' % pk)
44 self.add('load("%s")' % ffr(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 """ % (ffr(RscriptPath['CHD']), ffr(RscriptPath['chdtxt']), ffr(RscriptPath['anacor']), ffr(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 """ % ffr(DicoPath['TableUc1'])
158 if classif_mode == 0:
160 data2 <- readMM("%s")
161 data2 <- as(data2, "dgCMatrix")
162 row.names(data2) <- 1:nrow(data2)
163 """ % ffr(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)
175 listuce1<-read.csv2("%s")
176 """ % ffr(DicoPath['listeuce1'])
178 if classif_mode == 0:
180 listuce2<-read.csv2("%s")
181 """ % ffr(DicoPath['listeuce2'])
187 if classif_mode == 0:
195 if (classif_mode == 0) {
196 chd.result <- Rchdtxt(uceout, chd1, chd2 = chd2, mincl = mincl,classif_mode = classif_mode, nbt = nbt)
198 chd.result <- Rchdtxt(uceout, chd1, chd2 = chd1, mincl = mincl,classif_mode = classif_mode, nbt = nbt)
201 classeuce1 <- chd.result$cuce1
202 classes<-n1[,ncol(n1)]
203 write.csv2(n1, file="%s")
205 """ % (classif_mode, mincl, ffr(DicoPath['uce']), ffr(DicoPath['n1.csv']))
208 tree.tot1 <- make_tree_tot(chd1)
209 # open_file_graph("%s", widt = 600, height=400)
210 # plot(tree.tot1$tree.cl)
212 """ % ffr(DicoPath['arbre1'])
214 if classif_mode == 0:
216 classeuce2 <- chd.result$cuce2
217 tree.tot2 <- make_tree_tot(chd2)
218 # open_file_graph("%s", width = 600, height=400)
219 # plot(tree.tot2$tree.cl)
221 """ % ffr(DicoPath['arbre2'] )
224 tree.cut1 <- make_dendro_cut_tuple(tree.tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
225 save(tree.cut1, file="%s")
227 open_file_graph("%s", width = 600, height=400)
228 plot.dendropr(tree.cut1$tree.cl,classes, histo=TRUE)
229 open_file_graph("%s", width = 600, height=400)
230 plot(tree.cut1$dendro_tot_cl)
232 """ % (ffr(DicoPath['Rdendro']), ffr(DicoPath['dendro1']), ffr(DicoPath['arbre1']))
234 if classif_mode == 0:
236 tree.cut2 <- make_dendro_cut_tuple(tree.tot2$dendro_tuple, chd.result$coord_ok, classeuce2, 2, nbt)
237 open_file_graph("%s", width = 600, height=400)
238 plot(tree.cut2$tree.cl)
240 open_file_graph("%s", width = 600, height=400)
241 plot(tree.cut2$dendro_tot_cl)
243 """ % (ffr(DicoPath['dendro2']), ffr(DicoPath['arbre2']))
247 #save.image(file="%s")
248 """ % (ffr(DicoPath['RData']))
250 fileout = open(DicoPath['Rchdtxt'], 'w')
254 def RPamTxt(corpus, RscriptPath):
255 DicoPath = corpus.pathout
256 param = corpus.parametres
259 """ % (RscriptPath['pamtxt'])
262 """ % (RscriptPath['Rgraph'])
264 result <- pamtxt("%s", "%s", "%s", method = "%s", clust_type = "%s", clnb = %i)
266 """ % (DicoPath['TableUc1'], DicoPath['listeuce1'], DicoPath['uce'], param['method'], param['cluster_type'], param['nbcl'] )
268 open_file_graph("%s", width=400, height=400)
271 """ % (DicoPath['arbre1'])
273 save.image(file="%s")
274 """ % DicoPath['RData']
275 fileout = open(DicoPath['Rchdtxt'], 'w')
280 def RchdQuest(DicoPath, RscriptPath, nbcl = 10, mincl = 10):
286 """ % (ffr(RscriptPath['CHD']), ffr(RscriptPath['chdquest']), ffr(RscriptPath['anacor']),ffr(RscriptPath['Rgraph']))
294 chd.result<-Rchdquest("%s","%s","%s", nbt = nbt, mincl = mincl)
296 classeuce1 <- chd.result$cuce1
297 """ % (ffr(DicoPath['mat01.csv']), ffr(DicoPath['listeuce1']), ffr(DicoPath['uce']))
300 tree_tot1 <- make_tree_tot(chd.result$chd)
301 open_file_graph("%s", width = 600, height=400)
302 plot(tree_tot1$tree.cl)
304 """ % ffr(DicoPath['arbre1'])
307 tree_cut1 <- make_dendro_cut_tuple(tree_tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
308 tree.cut1 <- tree_cut1
309 save(tree.cut1, file="%s")
310 open_file_graph("%s", width = 600, height=400)
311 classes<-n1[,ncol(n1)]
312 plot.dendropr(tree_cut1$tree.cl,classes, histo = TRUE)
313 """ % (ffr(DicoPath['Rdendro']), ffr(DicoPath['dendro1']))
316 save.image(file="%s")
317 """ % ffr(DicoPath['RData'])
318 fileout = open(DicoPath['Rchdquest'], 'w')
322 def AlcesteTxtProf(DictChdTxtOut, RscriptsPath, clnb, taillecar):
323 txt = "clnb<-%i\n" % clnb
327 n1 <- read.csv2("%s")
328 """ % (ffr(RscriptsPath['chdfunct']), ffr(DictChdTxtOut['RData']), ffr(DictChdTxtOut['n1.csv']))
330 dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
331 datasup<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
332 dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
333 """ % (ffr(DictChdTxtOut['Contout']), ffr(DictChdTxtOut['ContSupOut']), ffr(DictChdTxtOut['ContEtOut']))
335 tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
336 tablesqrpsup<-BuildProf(as.matrix(datasup),n1,clnb)
337 tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
340 PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s",tablesqrpsup[4],tablesqrpsup[5])
341 """ % (ffr(DictChdTxtOut['PROFILE_OUT']), ffr(DictChdTxtOut['ANTIPRO_OUT']))
343 colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
344 colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
345 colnames(tablesqrpsup[[2]])<-paste('classe',1:clnb,sep=' ')
346 colnames(tablesqrpsup[[1]])<-paste('classe',1:clnb,sep=' ')
347 colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
348 colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
349 chistabletot<-rbind(tablesqrpact[2][[1]],tablesqrpsup[2][[1]])
350 chistabletot<-rbind(chistabletot,tablesqrpet[2][[1]])
351 ptabletot<-rbind(tablesqrpact[1][[1]],tablesqrpet[1][[1]])
354 write.csv2(chistabletot,file="%s")
355 write.csv2(ptabletot,file="%s")
357 write.csv2(gbcluster,file="%s")
358 """ % (ffr(DictChdTxtOut['chisqtable']), ffr(DictChdTxtOut['ptable']), ffr(DictChdTxtOut['SbyClasseOut']))
362 colnames(dataact)<-paste('classe',1:clnb,sep=' ')
363 colnames(datasup)<-paste('classe',1:clnb,sep=' ')
364 colnames(dataet)<-paste('classe',1:clnb,sep=' ')
365 rowtot<-nrow(dataact)+nrow(dataet)+nrow(datasup)
366 afctable<-rbind(as.matrix(dataact),as.matrix(datasup))
367 afctable<-rbind(afctable,as.matrix(dataet))
368 colnames(afctable)<-paste('classe',1:clnb,sep=' ')
369 afc<-ca(afctable,suprow=((nrow(dataact)+1):rowtot),nd=(ncol(afctable)-1))
370 debsup<-nrow(dataact)+1
371 debet<-nrow(dataact)+nrow(datasup)+1
373 afc<-AddCorrelationOk(afc)
375 #FIXME : split this!!!
378 """ % ffr(RscriptsPath['Rgraph'])
381 afc <- summary.ca.dm(afc)
382 afc_table <- create_afc_table(afc)
383 write.csv2(afc_table$facteur, file = "%s")
384 write.csv2(afc_table$colonne, file = "%s")
385 write.csv2(afc_table$ligne, file = "%s")
386 """ % (ffr(DictChdTxtOut['afc_facteur']), ffr(DictChdTxtOut['afc_col']), ffr(DictChdTxtOut['afc_row']))
392 xyminmax <- PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
393 """ % (ffr(DictChdTxtOut['AFC2DL_OUT']))
395 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)
396 """ % (ffr(DictChdTxtOut['AFC2DSL_OUT']))
398 if ((fin - debet) > 2) {
399 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)
401 """ % (ffr(DictChdTxtOut['AFC2DEL_OUT']))
403 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)
404 """ % (ffr(DictChdTxtOut['AFC2DCL_OUT']))
406 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
407 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debsup, fin=(debet-1), xlab = xlab, ylab = ylab)
408 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debet, fin=fin, xlab = xlab, ylab = ylab)
409 # PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col=TRUE, what='crl', xlab = xlab, ylab = ylab)
410 # """ % (DictChdTxtOut['AFC2DCoul'], DictChdTxtOut['AFC2DCoulSup'], DictChdTxtOut['AFC2DCoulEt'], DictChdTxtOut['AFC2DCoulCl'])
419 save.image(file="%s")
420 """ % ffr(DictChdTxtOut['RData'])
421 file = open(DictChdTxtOut['RTxtProfGraph'], 'w')
426 def write_afc_graph(self):
427 if self.param['over'] : over = 'TRUE'
428 else : over = 'FALSE'
430 if self.param['do_select_nb'] : do_select_nb = 'TRUE'
431 else : do_select_nb = 'FALSE'
433 if self.param['do_select_chi'] : do_select_chi = 'TRUE'
434 else : do_select_chi = 'FALSE'
436 if self.param['do_select_chi_classe'] : do_select_chi_classe = 'TRUE'
437 else : do_select_chi_classe = 'FALSE'
439 if self.param['cex_txt'] : cex_txt = 'TRUE'
440 else : cex_txt = 'FALSE'
442 if self.param['tchi'] : tchi = 'TRUE'
443 else : tchi = 'FALSE'
445 if self.param['svg'] : svg = 'TRUE'
448 with open(self.RscriptsPath['afc_graph'], 'r') as f:
451 # self.DictPathOut['RData'], \
452 scripts = txt % (ffr(self.RscriptsPath['Rgraph']),\
453 self.param['typegraph'], \
454 self.param['what'], \
455 self.param['facteur'][0],\
456 self.param['facteur'][1], \
457 self.param['facteur'][2], \
459 over, do_select_nb, \
460 self.param['select_nb'], \
462 self.param['select_chi'], \
463 do_select_chi_classe, \
464 self.param['nbchic'], \
466 self.param['txt_min'], \
467 self.param['txt_max'], \
469 self.param['width'], \
470 self.param['height'],\
471 self.param['taillecar'], \
472 self.param['alpha'], \
473 self.param['film'], \
475 self.param['tchi_min'],\
476 self.param['tchi_max'],\
477 ffr(os.path.dirname(self.fileout)),\
481 def print_simi3d(self):
482 simi3d = self.parent.simi3dpanel
483 txt = '#Fichier genere par Iramuteq'
484 if simi3d.movie.GetValue() :
485 movie = "'" + ffr(os.path.dirname(self.DictPathOut['RData'])) + "'"
489 #if self.corpus.parametres['type'] == 'corpus' :
495 dm<-read.csv2("%s",row.names=1,header = %s)
497 """ % (self.DictPathOut['Contout'], header, self.DictPathOut['RData'])
501 """ % self.parent.RscriptsPath['Rgraph']
505 make.simi.afc(dm,chistabletot, lim=%i, alpha = %.2f, movie = %s)
506 """ % (simi3d.spin_1.GetValue(), float(simi3d.slider_1.GetValue())/100, movie)
507 tmpfile = tempfile.mktemp(dir=self.parent.TEMPDIR)
508 tmp = open(tmpfile,'w')
513 def dendroandbarplot(table, rownames, colnames, rgraph, tmpgraph, intxt = False, dendro=False) :
515 txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
516 rownb = len(rownames)
517 rownames = 'c("' + '","'.join(rownames) + '")'
518 colnames = 'c("' + '","'.join(colnames) + '")'
522 di <- matrix(data=%s, nrow=%i, byrow = TRUE)
525 """ % (txttable, rownb, rownames, colnames)
532 height <- (30*ncol(di)) + (15*nrow(di))
533 height <- ifelse(height <= 400, 400, height)
535 open_file_graph("%s", width=width, height=height)
536 plot.dendro.lex(tree.cut1$tree.cl, di)
537 """ % (ffr(dendro),ffr(rgraph), ffr(tmpgraph))
540 def barplot(table, parametres, intxt = False) :
542 txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
543 #width = 100 + (15 * len(rownames)) + (100 * len(colnames))
544 #height = len(rownames) * 15
545 rownb = len(parametres['rownames'])
548 rownames = 'c("' + '","'.join(parametres['rownames']) + '")'
549 colnames = 'c("' + '","'.join(parametres['colnames']) + '")'
554 di <- matrix(data=%s, nrow=%i, byrow = TRUE)
555 toinf <- which(di == Inf)
556 tominf <- which(di == -Inf)
559 valmax <- max(di, na.rm = TRUE)
567 if (length(tominf)) {
569 valmin <- min(di, na.rm = TRUE)
579 """ % (txttable, rownb, rownames, colnames)
582 if not 'tree' in parametres :
585 color = rainbow(nrow(di))
588 open_file_graph("%s",width = width, height = height, svg = %s)
590 layout(matrix(c(1,2),1,2, byrow=TRUE),widths=c(3,lcm(7)))
592 yp = ifelse(length(toinf), 0.2, 0)
593 ym = ifelse(length(tominf), 0.2, 0)
594 ymin <- ifelse(!length(which(di < 0)), 0, min(di) - ym)
595 coord <- barplot(as.matrix(di), beside = TRUE, col = color, space = c(0.1,0.6), ylim=c(ymin, max(di) + yp), las = 2)
597 coordinf <- coord[toinf]
599 text(x=coordinf, y=valinf + 0.1, 'i')
601 if (length(tominf)) {
602 coordinf <- coord[toinf]
604 text(x=coordinf, y=valinf - 0.1, 'i')
610 lcoord <- apply(cc, 1, mean)
613 amp <- abs(max(di) - min(di))
620 d <- signif(amp%%/%%10,1)
625 if ((i/d) == (i%%/%%d)) {
630 plot(0, axes = FALSE, pch = '')
631 legend(x = 'center' , rownames(di), fill = color)
633 """ % (ffr(parametres['rgraph']), parametres['width'], parametres['height'], ffr(parametres['tmpgraph']), parametres['svg'])
641 open_file_graph("%s", width=width, height=height, svg = %s)
642 plot.dendro.lex(tree.cut1$tree.cl, di)
643 """ % (ffr(parametres['tree']), ffr(parametres['rgraph']), parametres['width'], parametres['height'], ffr(parametres['tmpgraph']), parametres['svg'])
646 #def RAfcUci(DictAfcUciOut, nd=2, RscriptsPath='', PARCEX='0.8'):
652 # dataact<-read.csv2("%s")
653 # """ % (DictAfcUciOut['TableCont'])#, encoding)
655 # datasup<-read.csv2("%s")
656 # """ % (DictAfcUciOut['TableSup'])#, encoding)
658 # dataet<-read.csv2("%s")
659 # """ % (DictAfcUciOut['TableEt'])#, encoding)
661 # datatotsup<-cbind(dataact,datasup)
662 # datatotet<-cbind(dataact,dataet)
663 # afcact<-ca(dataact,nd=nd)
664 # afcsup<-ca(datatotsup,supcol=((ncol(dataact)+1):ncol(datatotsup)),nd=nd)
665 # afcet<-ca(datatotet,supcol=((ncol(dataact)+1):ncol(datatotet)),nd=nd)
666 # afctot<-afcsup$colcoord
667 # rownames(afctot)<-afcsup$colnames
668 # colnames(afctot)<-paste('coord. facteur',1:nd,sep=' ')
669 # afctot<-cbind(afctot,mass=afcsup$colmass)
670 # afctot<-cbind(afctot,distance=afcsup$coldist)
671 # afctot<-cbind(afctot,intertie=afcsup$colinertia)
672 # rcolet<-afcet$colsup
673 # afctmp<-afcet$colcoord[rcolet,]
674 # rownames(afctmp)<-afcet$colnames[rcolet]
675 # afctmp<-cbind(afctmp,afcet$colmass[rcolet])
676 # afctmp<-cbind(afctmp,afcet$coldist[rcolet])
677 # afctmp<-cbind(afctmp,afcet$colinertia[rcolet])
678 # afctot<-rbind(afctot,afctmp)
679 # write.csv2(afctot,file = "%s")
681 # """ % (DictAfcUciOut['afc_row'], RscriptsPath['Rgraph'])
687 # PlotAfc(afcet,filename="%s",toplot=c%s, PARCEX=PARCEX)
688 # """ % (DictAfcUciOut['AfcColAct'], "('none','active')")
690 # PlotAfc(afcsup,filename="%s",toplot=c%s, PARCEX=PARCEX)
691 # """ % (DictAfcUciOut['AfcColSup'], "('none','passive')")
692 # txt += """PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
693 # """ % (DictAfcUciOut['AfcColEt'], "('none','passive')")
695 # PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
696 # """ % (DictAfcUciOut['AfcRow'], "('all','none')")
697 # f = open(DictAfcUciOut['Rafcuci'], 'w')
701 class PrintSimiScript(PrintRScript) :
702 def make_script(self) :
704 self.packages(['igraph', 'proxy', 'Matrix'])
705 self.sources([self.analyse.parent.RscriptsPath['simi'], self.analyse.parent.RscriptsPath['Rgraph']])
707 if not self.parametres['keep_coord'] and not self.parametres['type'] == 'simimatrix':
712 """ % (ffr(self.pathout['mat01.csv']), ffr(self.pathout['actives.csv']), ffr(self.pathout['selected.csv']))
713 if 'word' in self.parametres :
717 """ % self.parametres['word']
724 cn <- read.table(cn.path, sep='\t', quote='"')
725 colnames(dm) <- cn[,1]
726 if (file.exists(selected.col)) {
727 sel.col <- read.csv2(selected.col, header = FALSE)
728 sel.col <- sel.col[,1] + 1
730 sel.col <- 1:ncol(dm)
735 forme <- colnames(dm)[index]
736 if (!index %in% sel.col) {
737 sel.col <- append(sel.col, index)
740 index <- which(colnames(dm) == forme)
743 elif not self.parametres['keep_coord'] and self.parametres['type'] == 'simimatrix' :
747 """ % (ffr(self.pathout['mat01.csv']), ffr(self.pathout['selected.csv']))
748 if 'word' in self.parametres :
752 """ % self.parametres['word']
758 dm <-read.csv2(dm.path)
760 if (file.exists(selected.col)) {
761 sel.col <- read.csv2(selected.col, header = FALSE)
762 sel.col <- sel.col[,1] + 1
764 sel.col <- 1:ncol(dm)
769 forme <- colnames(dm)[index]
770 if (!index %in% sel.col) {
771 sel.col <- append(sel.col, index)
774 index <- which(colnames(dm) == forme)
780 """ % ffr(self.pathout['RData.RData'])
782 if self.parametres['coeff'] == 0 :
784 if not self.parametres['keep_coord'] :
790 if not self.parametres['keep_coord'] :
794 if self.parametres['coeff'] == 1 :
798 mat <- simil(dm, method = 'Russel', diag = TRUE, upper = TRUE, by_rows = FALSE)
800 elif self.analyse.indices[self.parametres['coeff']] == 'binomial' :
802 if not self.parametres['keep_coord'] :
807 elif self.parametres['coeff'] != 0 :
808 method = self.analyse.indices[self.parametres['coeff']]
809 if not self.parametres['keep_coord'] :
812 mat <- simil(dm, method = method, diag = TRUE, upper = TRUE, by_rows = FALSE)
813 """ % self.analyse.indices[self.parametres['coeff']]
814 if not self.parametres['keep_coord'] :
816 mat <- as.matrix(stats::as.dist(mat,diag=TRUE,upper=TRUE))
818 if (length(which(mat == Inf))) {
819 infp <- which(mat == Inf)
821 maxmat <- max(mat, na.rm = TRUE)
829 if (length(which(mat == -Inf))) {
830 infm <- which(mat == -Inf)
832 minmat <- min(mat, na.rm = TRUE)
841 if 'word' in self.parametres and not self.parametres['keep_coord'] :
843 mat <- graph.word(mat, index)
845 if (length(cs)) mat <- mat[,-which(cs==0)]
847 if (length(rs)) mat <- mat[-which(rs==0),]
848 if (length(cs)) dm <- dm[, -which(cs==0)]
851 if self.parametres['layout'] == 0 : layout = 'random'
852 if self.parametres['layout'] == 1 : layout = 'circle'
853 if self.parametres['layout'] == 2 : layout = 'frutch'
854 if self.parametres['layout'] == 3 : layout = 'kawa'
855 if self.parametres['layout'] == 4 : layout = 'graphopt'
859 if self.parametres['type_graph'] == 0 : type = 'tkplot'
860 if self.parametres['type_graph'] == 1 :
863 dirout = os.path.dirname(self.pathout['mat01.csv'])
864 while os.path.exists(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png')):
866 self.filename = ffr(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png'))
867 if self.parametres['type_graph'] == 2 : type = 'rgl'
868 if self.parametres['type_graph'] == 3 :
871 dirout = os.path.dirname(self.pathout['mat01.csv'])
872 while os.path.exists(os.path.join(dirout,'web_'+str(graphnb))):
874 self.filename = ffr(os.path.join(dirout,'web_'+str(graphnb)))
875 os.mkdir(self.filename)
876 self.filename = os.path.join(self.filename, 'gexf.gexf')
877 if self.parametres['type_graph'] == 4 :
880 dirout = os.path.dirname(self.pathout['mat01.csv'])
881 while os.path.exists(os.path.join(dirout,'webrgl_'+str(graphnb))):
883 self.filename = ffr(os.path.join(dirout,'webrgl_'+str(graphnb)))
884 os.mkdir(self.filename)
886 if self.parametres['arbremax'] :
888 self.txtgraph += ' - arbre maximum'
889 else : arbremax = 'FALSE'
891 if self.parametres['coeff_tv'] :
892 coeff_tv = self.parametres['coeff_tv_nb']
893 tvminmax = 'c(NULL,NULL)'
894 elif not self.parametres['coeff_tv'] or self.parametres.get('sformchi', False) :
896 tvminmax = 'c(%i, %i)' %(self.parametres['tvmin'], self.parametres['tvmax'])
897 if self.parametres['coeff_te'] : coeff_te = 'c(%i,%i)' % (self.parametres['coeff_temin'], self.parametres['coeff_temax'])
898 else : coeff_te = 'NULL'
900 if self.parametres['vcex'] or self.parametres.get('cexfromchi', False) :
901 vcexminmax = 'c(%i/10,%i/10)' % (self.parametres['vcexmin'],self.parametres['vcexmax'])
903 vcexminmax = 'c(NULL,NULL)'
904 if not self.parametres['label_v'] : label_v = 'FALSE'
905 else : label_v = 'TRUE'
907 if not self.parametres['label_e'] : label_e = 'FALSE'
908 else : label_e = 'TRUE'
910 if self.parametres['seuil_ok'] : seuil = str(self.parametres['seuil'])
911 else : seuil = 'NULL'
913 cols = str(self.parametres['cols']).replace(')',', max=255)')
914 cola = str(self.parametres['cola']).replace(')',',max=255)')
924 """ % self.parametres['cex']
926 if self.parametres['film'] :
929 """ % self.pathout['film']
936 if (!is.null(seuil)) {
937 if (method!='cooc') {
946 """ % (label_v, label_e)
954 """ % (self.parametres['width'], self.parametres['height'])
955 if self.parametres['keep_coord'] :
957 coords <- try(coords, TRUE)
958 if (!is.matrix(coords)) {
968 """ % self.parametres['alpha']
971 """ % self.parametres['alpha']
972 #############################################
973 if self.parametres.get('bystar',False) :
977 for i, line in enumerate(self.parametres['listet']) :
980 """ % (i+1, ','.join([`val + 1` for val in line]))
983 """ % ("','".join([val for val in self.parametres['selectedstars']]))
987 for (i in 1:length(unetoile)) {
990 if (length(tosum) > 1) {
991 fsum <- cbind(fsum, colSums(dm[tosum,]))
993 fsum <- cbind(fsum, dm[tosum,])
997 lex <- AsLexico2(fsum, chip=TRUE)
998 dcol <- apply(lex[[4]],1,which.max)
999 toblack <- apply(lex[[4]],1,max)
1000 gcol <- rainbow(length(unetoile))
1001 #gcol[2] <- 'orange'
1002 vertex.label.color <- gcol[dcol]
1003 vertex.label.color[which(toblack <= 3.84)] <- 'black'
1004 leg <- list(unetoile=unetoile, gcol=gcol)
1005 cols <- vertex.label.color
1006 chivertex.size <- norm.vec(toblack, vcexminmax[1], vcexminmax[2])
1008 """ % (ffr(self.analyse.parent.RscriptsPath['chdfunct']))
1011 vertex.label.color <- 'black'
1015 #############################################
1018 # eff <- colSums(dm)
1019 # g.ori <- graph.adjacency(mat, mode='lower', weighted = TRUE)
1020 # w.ori <- E(g.ori)$weight
1022 # if (method == 'cooc') {
1023 # E(g.ori)$weight <- 1 / w.ori
1025 # E(g.ori)$weigth <- 1 - w.ori
1027 # g.max <- minimum.spanning.tree(g.ori)
1028 # if (method == 'cooc') {
1029 # E(g.max)$weight <- 1 / E(g.max)$weight
1031 # E(g.max)$weight <- 1 - E(g.max)$weight
1038 if self.parametres['com'] :
1039 com = `self.parametres['communities']`
1042 if self.parametres['halo'] :
1052 x <- list(mat = mat, eff = eff)
1053 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)
1054 """ % (method, type, layout, arbremax, coeff_tv, coeff_te)
1056 if self.parametres.get('bystar',False) :
1057 if self.parametres.get('cexfromchi', False) :
1059 label.cex<-chivertex.size
1065 if self.parametres.get('sfromchi', False) :
1067 vertex.size <- norm.vec(toblack, minmaxeff[1], minmaxeff[2])
1074 #print self.parametres
1075 if (self.parametres['type'] == 'clustersimitxt' and self.parametres.get('tmpchi', False)) or (self.parametres['type'] == 'simimatrix' and 'tmpchi' in self.parametres):
1077 lchi <- read.table("%s")
1079 """ % ffr(self.parametres['tmpchi'])
1081 lchi <- lchi[sel.col]
1083 if self.parametres['type'] == 'clustersimitxt' and self.parametres.get('cexfromchi', False) :
1085 label.cex <- norm.vec(lchi, vcexminmax[1], vcexminmax[2])
1089 if (is.null(vcexminmax[1])) {
1092 label.cex <- graph.simi$label.cex
1095 if (self.parametres['type'] == 'clustersimitxt' or self.parametres['type'] == 'simimatrix') and self.parametres.get('sfromchi', False):
1097 vertex.size <- norm.vec(lchi, minmaxeff[1], minmaxeff[2])
1098 if (!length(vertex.size)) vertex.size <- 0
1102 if (is.null(minmaxeff[1])) {
1105 vertex.size <- graph.simi$eff
1108 #txt += """ vertex.size <- NULL """
1109 if self.parametres['svg'] : svg = 'TRUE'
1110 else : svg = 'FALSE'
1116 if (!is.null(graph.simi$com)) {
1117 com <- graph.simi$com
1118 colm <- rainbow(length(com))
1119 if (vertex.size != 0 || graph.simi$halo) {
1120 vertex.label.color <- 'black'
1121 vertex.col <- colm[membership(com)]
1123 vertex.label.color <- colm[membership(com)]
1126 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)
1127 save.image(file="%s")
1128 """ % (type, self.filename, ffr(self.pathout['RData']))
1133 class WordCloudRScript(PrintRScript) :
1134 def make_script(self) :
1135 self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1136 self.packages(['wordcloud'])
1137 bg_col = Rcolor(self.parametres['col_bg'])
1138 txt_col = Rcolor(self.parametres['col_text'])
1139 if self.parametres['svg'] :
1147 act <- read.csv2("%s", header = FALSE, row.names=1, sep='\t')
1148 selected.col <- read.table("%s")
1149 toprint <- as.matrix(act[selected.col[,1] + 1,])
1150 rownames(toprint) <- rownames(act)[selected.col[,1] + 1]
1152 if (nrow(toprint) > maxword) {
1153 toprint <- as.matrix(toprint[order(toprint[,1], decreasing=TRUE),])
1154 toprint <- as.matrix(toprint[1:maxword,])
1156 open_file_graph("%s", width = %i, height = %i , svg = svg)
1158 wordcloud(row.names(toprint), toprint[,1], scale=c(%f,%f), random.order=FALSE, colors=rgb%s)
1160 """ % (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)
1164 class ProtoScript(PrintRScript) :
1165 def make_script(self) :
1166 self.sources([self.analyse.parent.RscriptsPath['Rgraph'], self.analyse.parent.RscriptsPath['prototypical.R']])
1167 self.packages(['wordcloud'])
1168 if self.parametres.get('cloud', False) :
1173 errorn <- function(x) {
1174 qnorm(0.975)*sd(x)/sqrt(lenght(n))
1176 errort <- function(x) {
1177 qt(0.975,df=lenght(x)-1)*sd(x)/sqrt(lenght(x))
1179 mat <- read.csv2("%s", header = FALSE, row.names=1, sep='\t', quote='"', dec='.')
1180 open_file_graph("%s",height=800, width=1000)
1181 prototypical(mat, mfreq = %s, mrank = %s, cloud = FALSE, cexrange=c(1,2.4), cexalpha= c(0.4, 1), type = '%s')
1183 """ % (self.analyse.pathout['table.csv'], self.analyse.pathout['proto.png'], self.parametres['limfreq'], self.parametres['limrang'], self.parametres['typegraph'])
1188 class ExportAfc(PrintRScript) :
1189 def make_script(self) :
1190 self.source([self.analyse.parent.RscriptsPath['Rgraph']])
1191 self.packages(['rgexf'])
1195 class TgenSpecScript(PrintRScript):
1196 def make_script(self):
1197 self.packages(['textometry'])
1199 tgen <- read.csv2("%s", row.names = 1, sep = '\\t')
1200 """ % ffr(self.parametres['tgeneff'])
1202 tot <- tgen[nrow(tgen), ]
1204 tgen <- tgen[-nrow(tgen),]
1205 for (i in 1:nrow(tgen)) {
1206 mat <- rbind(tgen[i,], tot - tgen[i,])
1207 specmat <- specificities(mat)
1208 result <- rbind(result, specmat[1,])
1210 colnames(result) <- colnames(tgen)
1211 row.names(result) <- rownames(tgen)
1212 write.table(result, file = "%s", sep='\\t', col.names = NA)
1213 """ % ffr(self.pathout['tgenspec.csv'])