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.scriptout = self.pathout['temp']
21 self.script = u"#Script genere par IRaMuTeQ - %s" % datetime.now().ctime()
24 self.script = '\n'.join([self.script, txt])
26 def defvar(self, name, value) :
27 self.add(' <- '.join([name, value]))
29 def defvars(self, lvars) :
31 self.defvar(val[0],val[1])
33 def sources(self, lsources) :
34 for source in lsources :
35 self.add('source("%s")' % source)
39 self.add('load("%s")' % val)
42 with open(self.scriptout, 'w') as f :
46 class chdtxt(PrintRScript) :
50 class Alceste2(PrintRScript) :
52 self.sources(['chdfunct'])
54 lvars = [['clnb', `self.analyse.clnb`],
55 ['Contout', '"%s"' % self.pathout['Contout']],
56 ['ContSupOut', '"%s"' % self.pathout['ContSupOut']],
57 ['ContEtOut', '"%s"' % self.pathout['ContEtOut']],
58 ['profileout', '"%s"' % self.pathout['profils.csv']],
59 ['antiout', '"%s"' % self.pathout['antiprofils.csv']],
60 ['chisqtable', '"%s"' % self.pathout['chisqtable.csv']],
61 ['ptable', '"%s"' % self.pathout['ptable.csv']]]
67 # txt = "clnb<-%i\n" % clnb
71 #""" % (RscriptsPath['chdfunct'], DictChdTxtOut['RData'])
73 #dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
74 #datasup<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
75 #dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
76 #""" % (DictChdTxtOut['Contout'], DictChdTxtOut['ContSupOut'], DictChdTxtOut['ContEtOut'])
78 #tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
79 #tablesqrpsup<-BuildProf(as.matrix(datasup),n1,clnb)
80 #tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
83 #PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s",tablesqrpsup[4],tablesqrpsup[5])
84 #""" % (DictChdTxtOut['PROFILE_OUT'], DictChdTxtOut['ANTIPRO_OUT'])
86 #colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
87 #colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
88 #colnames(tablesqrpsup[[2]])<-paste('classe',1:clnb,sep=' ')
89 #colnames(tablesqrpsup[[1]])<-paste('classe',1:clnb,sep=' ')
90 #colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
91 #colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
92 #chistabletot<-rbind(tablesqrpact[2][[1]],tablesqrpsup[2][[1]])
93 #chistabletot<-rbind(chistabletot,tablesqrpet[2][[1]])
94 #ptabletot<-rbind(tablesqrpact[1][[1]],tablesqrpet[1][[1]])
97 #write.csv2(chistabletot,file="%s")
98 #write.csv2(ptabletot,file="%s")
100 #write.csv2(gbcluster,file="%s")
101 #""" % (DictChdTxtOut['chisqtable'], DictChdTxtOut['ptable'], DictChdTxtOut['SbyClasseOut'])
105 def RchdTxt(DicoPath, RscriptPath, mincl, classif_mode, nbt = 9, libsvdc = False, libsvdc_path = None, R_max_mem = False):
111 """ % (RscriptPath['CHD'], RscriptPath['chdtxt'], RscriptPath['anacor'], RscriptPath['Rgraph'])
124 """ % ffr(libsvdc_path)
133 data1 <- readMM("%s")
134 data1 <- as(data1, "dgCMatrix")
135 row.names(data1) <- 1:nrow(data1)
136 """ % DicoPath['TableUc1']
138 if classif_mode == 0:
140 data2 <- readMM("%s")
141 data2 <- as(data2, "dgCMatrix")
142 row.names(data2) <- 1:nrow(data2)
143 """ % DicoPath['TableUc2']
145 chd1<-CHD(data1, x = nbt, libsvdc = libsvdc, libsvdc.path = libsvdc.path)
148 if classif_mode == 0:
150 chd2<-CHD(data2, x = nbt, libsvdc = libsvdc, libsvdc.path = libsvdc.path)
159 listuce1<-read.csv2("%s")
160 """ % DicoPath['listeuce1']
162 if classif_mode == 0:
164 listuce2<-read.csv2("%s")
165 """ % DicoPath['listeuce2']
171 if classif_mode == 0:
176 chd.result <- Rchdtxt("%s",mincl=%i,classif_mode=%i, nbt = nbt)
178 classeuce1 <- chd.result$cuce1
179 classeuce2 <- chd.result$cuce2
180 """ % (DicoPath['uce'], mincl, classif_mode)
183 tree.tot1 <- make_tree_tot(chd1)
184 # open_file_graph("%s", widt = 600, height=400)
185 # plot(tree.tot1$tree.cl)
187 """%DicoPath['arbre1']
189 if classif_mode == 0:
191 tree.tot2 <- make_tree_tot(chd2)
192 # open_file_graph("%s", width = 600, height=400)
193 # plot(tree.tot2$tree.cl)
195 """ % DicoPath['arbre2']
198 tree.cut1 <- make_dendro_cut_tuple(tree.tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
199 save(tree.cut1, file="%s")
200 classes<-n1[,ncol(n1)]
201 open_file_graph("%s", width = 600, height=400)
202 plot.dendropr(tree.cut1$tree.cl,classes)
203 open_file_graph("%s", width = 600, height=400)
204 plot(tree.cut1$dendro_tot_cl)
206 """ % (DicoPath['Rdendro'], DicoPath['dendro1'], DicoPath['arbre1'])
208 if classif_mode == 0:
210 tree.cut2 <- make_dendro_cut_tuple(tree.tot2$dendro_tuple, chd.result$coord_ok, classeuce2, 2, nbt)
211 open_file_graph("%s", width = 600, height=400)
212 plot(tree.cut2$tree.cl)
214 open_file_graph("%s", width = 600, height=400)
215 plot(tree.cut1$dendro_tot_cl)
217 """ % (DicoPath['dendro2'], DicoPath['arbre2'])
220 save.image(file="%s")
221 """ % DicoPath['RData']
222 fileout = open(DicoPath['Rchdtxt'], 'w')
226 def RPamTxt(corpus, RscriptPath):
227 DicoPath = corpus.dictpathout
228 param = corpus.parametre
232 """ % (RscriptPath['pamtxt'])
235 """ % (RscriptPath['Rgraph'])
237 result <- pamtxt("%s", "%s", "%s", method = "%s", clust_type = "%s", clnb = %i)
239 """ % (DicoPath['TableUc1'], DicoPath['listeuce1'], DicoPath['uce'], param['method'], param['cluster_type'], param['nbcl'] )
241 open_file_graph("%s", width=400, height=400)
244 """ % (DicoPath['arbre1'])
246 save.image(file="%s")
247 """ % DicoPath['RData']
248 fileout = open(DicoPath['Rchdtxt'], 'w')
253 def RchdQuest(DicoPath, RscriptPath, nbcl = 10, mincl = 10):
259 """ % (RscriptPath['CHD'], RscriptPath['chdquest'], RscriptPath['anacor'],RscriptPath['Rgraph'])
267 chd.result<-Rchdquest("%s","%s","%s", nbt = nbt, mincl = mincl)
269 classeuce1 <- chd.result$cuce1
270 """ % (DicoPath['Act01'], DicoPath['listeuce1'], DicoPath['uce'])
273 tree_tot1 <- make_tree_tot(chd.result$chd)
274 open_file_graph("%s", width = 600, height=400)
275 plot(tree_tot1$tree.cl)
277 """%DicoPath['arbre1']
280 tree_cut1 <- make_dendro_cut_tuple(tree_tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
281 tree.cut1 <- tree_cut1
282 save(tree.cut1, file="%s")
283 open_file_graph("%s", width = 600, height=400)
284 classes<-n1[,ncol(n1)]
285 plot.dendropr(tree_cut1$tree.cl,classes)
286 """ % (DicoPath['Rdendro'],DicoPath['dendro1'])
289 save.image(file="%s")
290 """ % DicoPath['RData']
291 fileout = open(DicoPath['Rchdquest'], 'w')
295 def AlcesteTxtProf(DictChdTxtOut, RscriptsPath, clnb, taillecar):
296 txt = "clnb<-%i\n" % clnb
300 """ % (RscriptsPath['chdfunct'], DictChdTxtOut['RData'])
302 dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
303 datasup<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
304 dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
305 """ % (DictChdTxtOut['Contout'], DictChdTxtOut['ContSupOut'], DictChdTxtOut['ContEtOut'])
307 tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
308 tablesqrpsup<-BuildProf(as.matrix(datasup),n1,clnb)
309 tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
312 PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s",tablesqrpsup[4],tablesqrpsup[5])
313 """ % (DictChdTxtOut['PROFILE_OUT'], DictChdTxtOut['ANTIPRO_OUT'])
315 colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
316 colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
317 colnames(tablesqrpsup[[2]])<-paste('classe',1:clnb,sep=' ')
318 colnames(tablesqrpsup[[1]])<-paste('classe',1:clnb,sep=' ')
319 colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
320 colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
321 chistabletot<-rbind(tablesqrpact[2][[1]],tablesqrpsup[2][[1]])
322 chistabletot<-rbind(chistabletot,tablesqrpet[2][[1]])
323 ptabletot<-rbind(tablesqrpact[1][[1]],tablesqrpet[1][[1]])
326 write.csv2(chistabletot,file="%s")
327 write.csv2(ptabletot,file="%s")
329 write.csv2(gbcluster,file="%s")
330 """ % (DictChdTxtOut['chisqtable'], DictChdTxtOut['ptable'], DictChdTxtOut['SbyClasseOut'])
334 colnames(dataact)<-paste('classe',1:clnb,sep=' ')
335 colnames(datasup)<-paste('classe',1:clnb,sep=' ')
336 colnames(dataet)<-paste('classe',1:clnb,sep=' ')
337 rowtot<-nrow(dataact)+nrow(dataet)+nrow(datasup)
338 afctable<-rbind(as.matrix(dataact),as.matrix(datasup))
339 afctable<-rbind(afctable,as.matrix(dataet))
340 colnames(afctable)<-paste('classe',1:clnb,sep=' ')
341 afc<-ca(afctable,suprow=((nrow(dataact)+1):rowtot),nd=(ncol(afctable)-1))
342 debsup<-nrow(dataact)+1
343 debet<-nrow(dataact)+nrow(datasup)+1
345 afc<-AddCorrelationOk(afc)
347 #FIXME : split this!!!
350 """ % RscriptsPath['Rgraph']
353 afc <- summary.ca.dm(afc)
354 afc_table <- create_afc_table(afc)
355 write.csv2(afc_table$facteur, file = "%s")
356 write.csv2(afc_table$colonne, file = "%s")
357 write.csv2(afc_table$ligne, file = "%s")
358 """ % (DictChdTxtOut['afc_facteur'], DictChdTxtOut['afc_col'], DictChdTxtOut['afc_row'])
361 xlab <- paste('facteur 1 - ', round(afc$facteur[1,2],2), sep = '')
362 ylab <- paste('facteur 2 - ', round(afc$facteur[2,2],2), sep = '')
363 xlab <- paste(xlab, ' %', sep = '')
364 ylab <- paste(ylab, ' %', sep = '')
371 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
372 """ % (DictChdTxtOut['AFC2DL_OUT'])
374 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=debsup, fin=(debet-1), xlab = xlab, ylab = ylab)
375 """ % (DictChdTxtOut['AFC2DSL_OUT'])
377 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=debet, fin=fin, xlab = xlab, ylab = ylab)
378 """ % (DictChdTxtOut['AFC2DEL_OUT'])
380 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col=TRUE, what='coord', xlab = xlab, ylab = ylab)
381 """ % (DictChdTxtOut['AFC2DCL_OUT'])
383 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
384 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debsup, fin=(debet-1), xlab = xlab, ylab = ylab)
385 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debet, fin=fin, xlab = xlab, ylab = ylab)
386 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col=TRUE, what='crl', xlab = xlab, ylab = ylab)
387 """ % (DictChdTxtOut['AFC2DCoul'], DictChdTxtOut['AFC2DCoulSup'], DictChdTxtOut['AFC2DCoulEt'], DictChdTxtOut['AFC2DCoulCl'])
396 save.image(file="%s")
397 """ % DictChdTxtOut['RData']
398 file = open(DictChdTxtOut['RTxtProfGraph'], 'w')
403 def write_afc_graph(self):
404 if self.param['over'] : over = 'TRUE'
405 else : over = 'FALSE'
407 if self.param['do_select_nb'] : do_select_nb = 'TRUE'
408 else : do_select_nb = 'FALSE'
410 if self.param['do_select_chi'] : do_select_chi = 'TRUE'
411 else : do_select_chi = 'FALSE'
413 if self.param['cex_txt'] : cex_txt = 'TRUE'
414 else : cex_txt = 'FALSE'
416 if self.param['tchi'] : tchi = 'TRUE'
417 else : tchi = 'FALSE'
419 with open(self.RscriptsPath['afc_graph'], 'r') as f:
422 # self.DictPathOut['RData'], \
423 scripts = txt % (self.RscriptsPath['Rgraph'],\
424 self.param['typegraph'], \
425 self.param['what'], \
426 self.param['facteur'][0],\
427 self.param['facteur'][1], \
428 self.param['facteur'][2], \
430 over, do_select_nb, \
431 self.param['select_nb'], \
433 self.param['select_chi'], \
435 self.param['txt_min'], \
436 self.param['txt_max'], \
438 self.param['width'], \
439 self.param['height'],\
440 self.param['taillecar'], \
441 self.param['alpha'], \
442 self.param['film'], \
444 self.param['tchi_min'],\
445 self.param['tchi_max'],\
446 ffr(os.path.dirname(self.fileout)))
449 def print_simi3d(self):
450 simi3d = self.parent.simi3dpanel
451 txt = '#Fichier genere par Iramuteq'
452 if simi3d.movie.GetValue() :
453 movie = "'" + ffr(os.path.dirname(self.DictPathOut['RData'])) + "'"
456 if self.section == 'chd_dist_quest' :
461 dm<-read.csv2("%s",row.names=1,header = %s)
463 """ % (self.DictPathOut['Contout'], header, self.DictPathOut['RData'])
467 """ % self.parent.RscriptsPath['Rgraph']
471 make.simi.afc(dm,chistabletot, lim=%i, alpha = %.2f, movie = %s)
472 """ % (simi3d.spin_1.GetValue(), float(simi3d.slider_1.GetValue())/100, movie)
473 tmpfile = tempfile.mktemp(dir=self.parent.TEMPDIR)
474 tmp = open(tmpfile,'w')
479 def dendroandbarplot(table, rownames, colnames, rgraph, tmpgraph, intxt = False, dendro=False) :
481 txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
482 rownb = len(rownames)
483 rownames = 'c("' + '","'.join(rownames) + '")'
484 colnames = 'c("' + '","'.join(colnames) + '")'
488 di <- matrix(data=%s, nrow=%i, byrow = TRUE)
491 """ % (txttable, rownb, rownames, colnames)
498 height <- (30*ncol(di)) + (15*nrow(di))
499 height <- ifelse(height <= 400, 400, height)
501 open_file_graph("%s", width=width, height=height)
502 plot.dendro.lex(tree.cut1$tree.cl, di)
503 """ % (ffr(dendro),ffr(rgraph), ffr(tmpgraph))
506 def barplot(table, rownames, colnames, rgraph, tmpgraph, intxt = False) :
508 txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
509 #width = 100 + (15 * len(rownames)) + (100 * len(colnames))
510 #height = len(rownames) * 15
511 rownb = len(rownames)
514 rownames = 'c("' + '","'.join(rownames) + '")'
515 colnames = 'c("' + '","'.join(colnames) + '")'
520 di <- matrix(data=%s, nrow=%i, byrow = TRUE)
521 di[is.na(di)] <- max(di, na.rm=TRUE) + 2
524 """ % (txttable, rownb, rownames, colnames)
529 color = rainbow(nrow(di))
530 width <- 100 + (20*length(rownames(di))) + (100 * length(colnames(di)))
531 height <- nrow(di) * 15
532 if (height < 400) { height <- 400}
533 open_file_graph("%s",width = width, height = height)
535 layout(matrix(c(1,2),1,2, byrow=TRUE),widths=c(3,lcm(7)))
537 coord <- barplot(as.matrix(di), beside = TRUE, col = color, space = c(0.1,0.6))
542 lcoord <- apply(cc, 1, mean)
545 amp <- abs(max(di) - min(di))
552 d <- signif(amp%%/%%10,1)
557 if ((i/d) == (i%%/%%d)) {
562 plot(0, axes = FALSE, pch = '')
563 legend(x = 'center' , rownames(di), fill = color)
565 """ % (rgraph, ffr(tmpgraph))
568 #def RAfcUci(DictAfcUciOut, nd=2, RscriptsPath='', PARCEX='0.8'):
574 # dataact<-read.csv2("%s")
575 # """ % (DictAfcUciOut['TableCont'])#, encoding)
577 # datasup<-read.csv2("%s")
578 # """ % (DictAfcUciOut['TableSup'])#, encoding)
580 # dataet<-read.csv2("%s")
581 # """ % (DictAfcUciOut['TableEt'])#, encoding)
583 # datatotsup<-cbind(dataact,datasup)
584 # datatotet<-cbind(dataact,dataet)
585 # afcact<-ca(dataact,nd=nd)
586 # afcsup<-ca(datatotsup,supcol=((ncol(dataact)+1):ncol(datatotsup)),nd=nd)
587 # afcet<-ca(datatotet,supcol=((ncol(dataact)+1):ncol(datatotet)),nd=nd)
588 # afctot<-afcsup$colcoord
589 # rownames(afctot)<-afcsup$colnames
590 # colnames(afctot)<-paste('coord. facteur',1:nd,sep=' ')
591 # afctot<-cbind(afctot,mass=afcsup$colmass)
592 # afctot<-cbind(afctot,distance=afcsup$coldist)
593 # afctot<-cbind(afctot,intertie=afcsup$colinertia)
594 # rcolet<-afcet$colsup
595 # afctmp<-afcet$colcoord[rcolet,]
596 # rownames(afctmp)<-afcet$colnames[rcolet]
597 # afctmp<-cbind(afctmp,afcet$colmass[rcolet])
598 # afctmp<-cbind(afctmp,afcet$coldist[rcolet])
599 # afctmp<-cbind(afctmp,afcet$colinertia[rcolet])
600 # afctot<-rbind(afctot,afctmp)
601 # write.csv2(afctot,file = "%s")
603 # """ % (DictAfcUciOut['afc_row'], RscriptsPath['Rgraph'])
609 # PlotAfc(afcet,filename="%s",toplot=c%s, PARCEX=PARCEX)
610 # """ % (DictAfcUciOut['AfcColAct'], "('none','active')")
612 # PlotAfc(afcsup,filename="%s",toplot=c%s, PARCEX=PARCEX)
613 # """ % (DictAfcUciOut['AfcColSup'], "('none','passive')")
614 # txt += """PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
615 # """ % (DictAfcUciOut['AfcColEt'], "('none','passive')")
617 # PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
618 # """ % (DictAfcUciOut['AfcRow'], "('all','none')")
619 # f = open(DictAfcUciOut['Rafcuci'], 'w')