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)
40 self.add('load("%s")' % val)
43 with open(self.scriptout, 'w') as f :
47 class chdtxt(PrintRScript) :
51 class Alceste2(PrintRScript) :
53 self.sources(['chdfunct'])
55 lvars = [['clnb', `self.analyse.clnb`],
56 ['Contout', '"%s"' % self.pathout['Contout']],
57 ['ContSupOut', '"%s"' % self.pathout['ContSupOut']],
58 ['ContEtOut', '"%s"' % self.pathout['ContEtOut']],
59 ['profileout', '"%s"' % self.pathout['profils.csv']],
60 ['antiout', '"%s"' % self.pathout['antiprofils.csv']],
61 ['chisqtable', '"%s"' % self.pathout['chisqtable.csv']],
62 ['ptable', '"%s"' % self.pathout['ptable.csv']]]
68 # txt = "clnb<-%i\n" % clnb
72 #""" % (RscriptsPath['chdfunct'], DictChdTxtOut['RData'])
74 #dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
75 #datasup<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
76 #dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
77 #""" % (DictChdTxtOut['Contout'], DictChdTxtOut['ContSupOut'], DictChdTxtOut['ContEtOut'])
79 #tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
80 #tablesqrpsup<-BuildProf(as.matrix(datasup),n1,clnb)
81 #tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
84 #PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s",tablesqrpsup[4],tablesqrpsup[5])
85 #""" % (DictChdTxtOut['PROFILE_OUT'], DictChdTxtOut['ANTIPRO_OUT'])
87 #colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
88 #colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
89 #colnames(tablesqrpsup[[2]])<-paste('classe',1:clnb,sep=' ')
90 #colnames(tablesqrpsup[[1]])<-paste('classe',1:clnb,sep=' ')
91 #colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
92 #colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
93 #chistabletot<-rbind(tablesqrpact[2][[1]],tablesqrpsup[2][[1]])
94 #chistabletot<-rbind(chistabletot,tablesqrpet[2][[1]])
95 #ptabletot<-rbind(tablesqrpact[1][[1]],tablesqrpet[1][[1]])
98 #write.csv2(chistabletot,file="%s")
99 #write.csv2(ptabletot,file="%s")
101 #write.csv2(gbcluster,file="%s")
102 #""" % (DictChdTxtOut['chisqtable'], DictChdTxtOut['ptable'], DictChdTxtOut['SbyClasseOut'])
106 def RchdTxt(DicoPath, RscriptPath, mincl, classif_mode, nbt = 9, libsvdc = False, libsvdc_path = None, R_max_mem = False):
112 """ % (RscriptPath['CHD'], RscriptPath['chdtxt'], RscriptPath['anacor'], RscriptPath['Rgraph'])
125 """ % ffr(libsvdc_path)
134 data1 <- readMM("%s")
135 data1 <- as(data1, "dgCMatrix")
136 row.names(data1) <- 1:nrow(data1)
137 """ % DicoPath['TableUc1']
139 if classif_mode == 0:
141 data2 <- readMM("%s")
142 data2 <- as(data2, "dgCMatrix")
143 row.names(data2) <- 1:nrow(data2)
144 """ % DicoPath['TableUc2']
146 chd1<-CHD(data1, x = nbt, libsvdc = libsvdc, libsvdc.path = libsvdc.path)
149 if classif_mode == 0:
151 chd2<-CHD(data2, x = nbt, libsvdc = libsvdc, libsvdc.path = libsvdc.path)
160 listuce1<-read.csv2("%s")
161 """ % DicoPath['listeuce1']
163 if classif_mode == 0:
165 listuce2<-read.csv2("%s")
166 """ % DicoPath['listeuce2']
172 if classif_mode == 0:
177 chd.result <- Rchdtxt("%s",mincl=%i,classif_mode=%i, nbt = nbt)
179 classeuce1 <- chd.result$cuce1
180 classeuce2 <- chd.result$cuce2
181 """ % (DicoPath['uce'], mincl, classif_mode)
184 tree.tot1 <- make_tree_tot(chd1)
185 # open_file_graph("%s", widt = 600, height=400)
186 # plot(tree.tot1$tree.cl)
188 """%DicoPath['arbre1']
190 if classif_mode == 0:
192 tree.tot2 <- make_tree_tot(chd2)
193 # open_file_graph("%s", width = 600, height=400)
194 # plot(tree.tot2$tree.cl)
196 """ % DicoPath['arbre2']
199 tree.cut1 <- make_dendro_cut_tuple(tree.tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
200 save(tree.cut1, file="%s")
201 classes<-n1[,ncol(n1)]
202 open_file_graph("%s", width = 600, height=400)
203 plot.dendropr(tree.cut1$tree.cl,classes)
204 open_file_graph("%s", width = 600, height=400)
205 plot(tree.cut1$dendro_tot_cl)
207 """ % (DicoPath['Rdendro'], DicoPath['dendro1'], DicoPath['arbre1'])
209 if classif_mode == 0:
211 tree.cut2 <- make_dendro_cut_tuple(tree.tot2$dendro_tuple, chd.result$coord_ok, classeuce2, 2, nbt)
212 open_file_graph("%s", width = 600, height=400)
213 plot(tree.cut2$tree.cl)
215 open_file_graph("%s", width = 600, height=400)
216 plot(tree.cut1$dendro_tot_cl)
218 """ % (DicoPath['dendro2'], DicoPath['arbre2'])
221 save.image(file="%s")
222 """ % DicoPath['RData']
223 fileout = open(DicoPath['Rchdtxt'], 'w')
227 def RPamTxt(corpus, RscriptPath):
228 DicoPath = corpus.dictpathout
229 param = corpus.parametre
233 """ % (RscriptPath['pamtxt'])
236 """ % (RscriptPath['Rgraph'])
238 result <- pamtxt("%s", "%s", "%s", method = "%s", clust_type = "%s", clnb = %i)
240 """ % (DicoPath['TableUc1'], DicoPath['listeuce1'], DicoPath['uce'], param['method'], param['cluster_type'], param['nbcl'] )
242 open_file_graph("%s", width=400, height=400)
245 """ % (DicoPath['arbre1'])
247 save.image(file="%s")
248 """ % DicoPath['RData']
249 fileout = open(DicoPath['Rchdtxt'], 'w')
254 def RchdQuest(DicoPath, RscriptPath, nbcl = 10, mincl = 10):
260 """ % (RscriptPath['CHD'], RscriptPath['chdquest'], RscriptPath['anacor'],RscriptPath['Rgraph'])
268 chd.result<-Rchdquest("%s","%s","%s", nbt = nbt, mincl = mincl)
270 classeuce1 <- chd.result$cuce1
271 """ % (DicoPath['Act01'], DicoPath['listeuce1'], DicoPath['uce'])
274 tree_tot1 <- make_tree_tot(chd.result$chd)
275 open_file_graph("%s", width = 600, height=400)
276 plot(tree_tot1$tree.cl)
278 """%DicoPath['arbre1']
281 tree_cut1 <- make_dendro_cut_tuple(tree_tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
282 tree.cut1 <- tree_cut1
283 save(tree.cut1, file="%s")
284 open_file_graph("%s", width = 600, height=400)
285 classes<-n1[,ncol(n1)]
286 plot.dendropr(tree_cut1$tree.cl,classes)
287 """ % (DicoPath['Rdendro'],DicoPath['dendro1'])
290 save.image(file="%s")
291 """ % DicoPath['RData']
292 fileout = open(DicoPath['Rchdquest'], 'w')
296 def AlcesteTxtProf(DictChdTxtOut, RscriptsPath, clnb, taillecar):
297 txt = "clnb<-%i\n" % clnb
301 """ % (RscriptsPath['chdfunct'], DictChdTxtOut['RData'])
303 dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
304 datasup<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
305 dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
306 """ % (DictChdTxtOut['Contout'], DictChdTxtOut['ContSupOut'], DictChdTxtOut['ContEtOut'])
308 tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
309 tablesqrpsup<-BuildProf(as.matrix(datasup),n1,clnb)
310 tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
313 PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s",tablesqrpsup[4],tablesqrpsup[5])
314 """ % (DictChdTxtOut['PROFILE_OUT'], DictChdTxtOut['ANTIPRO_OUT'])
316 colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
317 colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
318 colnames(tablesqrpsup[[2]])<-paste('classe',1:clnb,sep=' ')
319 colnames(tablesqrpsup[[1]])<-paste('classe',1:clnb,sep=' ')
320 colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
321 colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
322 chistabletot<-rbind(tablesqrpact[2][[1]],tablesqrpsup[2][[1]])
323 chistabletot<-rbind(chistabletot,tablesqrpet[2][[1]])
324 ptabletot<-rbind(tablesqrpact[1][[1]],tablesqrpet[1][[1]])
327 write.csv2(chistabletot,file="%s")
328 write.csv2(ptabletot,file="%s")
330 write.csv2(gbcluster,file="%s")
331 """ % (DictChdTxtOut['chisqtable'], DictChdTxtOut['ptable'], DictChdTxtOut['SbyClasseOut'])
335 colnames(dataact)<-paste('classe',1:clnb,sep=' ')
336 colnames(datasup)<-paste('classe',1:clnb,sep=' ')
337 colnames(dataet)<-paste('classe',1:clnb,sep=' ')
338 rowtot<-nrow(dataact)+nrow(dataet)+nrow(datasup)
339 afctable<-rbind(as.matrix(dataact),as.matrix(datasup))
340 afctable<-rbind(afctable,as.matrix(dataet))
341 colnames(afctable)<-paste('classe',1:clnb,sep=' ')
342 afc<-ca(afctable,suprow=((nrow(dataact)+1):rowtot),nd=(ncol(afctable)-1))
343 debsup<-nrow(dataact)+1
344 debet<-nrow(dataact)+nrow(datasup)+1
346 afc<-AddCorrelationOk(afc)
348 #FIXME : split this!!!
351 """ % RscriptsPath['Rgraph']
354 afc <- summary.ca.dm(afc)
355 afc_table <- create_afc_table(afc)
356 write.csv2(afc_table$facteur, file = "%s")
357 write.csv2(afc_table$colonne, file = "%s")
358 write.csv2(afc_table$ligne, file = "%s")
359 """ % (DictChdTxtOut['afc_facteur'], DictChdTxtOut['afc_col'], DictChdTxtOut['afc_row'])
362 xlab <- paste('facteur 1 - ', round(afc$facteur[1,2],2), sep = '')
363 ylab <- paste('facteur 2 - ', round(afc$facteur[2,2],2), sep = '')
364 xlab <- paste(xlab, ' %', sep = '')
365 ylab <- paste(ylab, ' %', sep = '')
372 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
373 """ % (DictChdTxtOut['AFC2DL_OUT'])
375 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=debsup, fin=(debet-1), xlab = xlab, ylab = ylab)
376 """ % (DictChdTxtOut['AFC2DSL_OUT'])
378 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=debet, fin=fin, xlab = xlab, ylab = ylab)
379 """ % (DictChdTxtOut['AFC2DEL_OUT'])
381 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col=TRUE, what='coord', xlab = xlab, ylab = ylab)
382 """ % (DictChdTxtOut['AFC2DCL_OUT'])
384 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
385 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debsup, fin=(debet-1), xlab = xlab, ylab = ylab)
386 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debet, fin=fin, xlab = xlab, ylab = ylab)
387 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col=TRUE, what='crl', xlab = xlab, ylab = ylab)
388 """ % (DictChdTxtOut['AFC2DCoul'], DictChdTxtOut['AFC2DCoulSup'], DictChdTxtOut['AFC2DCoulEt'], DictChdTxtOut['AFC2DCoulCl'])
397 save.image(file="%s")
398 """ % DictChdTxtOut['RData']
399 file = open(DictChdTxtOut['RTxtProfGraph'], 'w')
404 def write_afc_graph(self):
405 if self.param['over'] : over = 'TRUE'
406 else : over = 'FALSE'
408 if self.param['do_select_nb'] : do_select_nb = 'TRUE'
409 else : do_select_nb = 'FALSE'
411 if self.param['do_select_chi'] : do_select_chi = 'TRUE'
412 else : do_select_chi = 'FALSE'
414 if self.param['cex_txt'] : cex_txt = 'TRUE'
415 else : cex_txt = 'FALSE'
417 if self.param['tchi'] : tchi = 'TRUE'
418 else : tchi = 'FALSE'
420 with open(self.RscriptsPath['afc_graph'], 'r') as f:
423 # self.DictPathOut['RData'], \
424 scripts = txt % (self.RscriptsPath['Rgraph'],\
425 self.param['typegraph'], \
426 self.param['what'], \
427 self.param['facteur'][0],\
428 self.param['facteur'][1], \
429 self.param['facteur'][2], \
431 over, do_select_nb, \
432 self.param['select_nb'], \
434 self.param['select_chi'], \
436 self.param['txt_min'], \
437 self.param['txt_max'], \
439 self.param['width'], \
440 self.param['height'],\
441 self.param['taillecar'], \
442 self.param['alpha'], \
443 self.param['film'], \
445 self.param['tchi_min'],\
446 self.param['tchi_max'],\
447 ffr(os.path.dirname(self.fileout)))
450 def print_simi3d(self):
451 simi3d = self.parent.simi3dpanel
452 txt = '#Fichier genere par Iramuteq'
453 if simi3d.movie.GetValue() :
454 movie = "'" + ffr(os.path.dirname(self.DictPathOut['RData'])) + "'"
457 if self.section == 'chd_dist_quest' :
462 dm<-read.csv2("%s",row.names=1,header = %s)
464 """ % (self.DictPathOut['Contout'], header, self.DictPathOut['RData'])
468 """ % self.parent.RscriptsPath['Rgraph']
472 make.simi.afc(dm,chistabletot, lim=%i, alpha = %.2f, movie = %s)
473 """ % (simi3d.spin_1.GetValue(), float(simi3d.slider_1.GetValue())/100, movie)
474 tmpfile = tempfile.mktemp(dir=self.parent.TEMPDIR)
475 tmp = open(tmpfile,'w')
480 def dendroandbarplot(table, rownames, colnames, rgraph, tmpgraph, intxt = False, dendro=False) :
482 txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
483 rownb = len(rownames)
484 rownames = 'c("' + '","'.join(rownames) + '")'
485 colnames = 'c("' + '","'.join(colnames) + '")'
489 di <- matrix(data=%s, nrow=%i, byrow = TRUE)
492 """ % (txttable, rownb, rownames, colnames)
499 height <- (30*ncol(di)) + (15*nrow(di))
500 height <- ifelse(height <= 400, 400, height)
502 open_file_graph("%s", width=width, height=height)
503 plot.dendro.lex(tree.cut1$tree.cl, di)
504 """ % (ffr(dendro),ffr(rgraph), ffr(tmpgraph))
507 def barplot(table, rownames, colnames, rgraph, tmpgraph, intxt = False) :
509 txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
510 #width = 100 + (15 * len(rownames)) + (100 * len(colnames))
511 #height = len(rownames) * 15
512 rownb = len(rownames)
515 rownames = 'c("' + '","'.join(rownames) + '")'
516 colnames = 'c("' + '","'.join(colnames) + '")'
521 di <- matrix(data=%s, nrow=%i, byrow = TRUE)
522 di[is.na(di)] <- max(di, na.rm=TRUE) + 2
525 """ % (txttable, rownb, rownames, colnames)
530 color = rainbow(nrow(di))
531 width <- 100 + (20*length(rownames(di))) + (100 * length(colnames(di)))
532 height <- nrow(di) * 15
533 if (height < 400) { height <- 400}
534 open_file_graph("%s",width = width, height = height)
536 layout(matrix(c(1,2),1,2, byrow=TRUE),widths=c(3,lcm(7)))
538 coord <- barplot(as.matrix(di), beside = TRUE, col = color, space = c(0.1,0.6))
543 lcoord <- apply(cc, 1, mean)
546 amp <- abs(max(di) - min(di))
553 d <- signif(amp%%/%%10,1)
558 if ((i/d) == (i%%/%%d)) {
563 plot(0, axes = FALSE, pch = '')
564 legend(x = 'center' , rownames(di), fill = color)
566 """ % (rgraph, ffr(tmpgraph))
569 #def RAfcUci(DictAfcUciOut, nd=2, RscriptsPath='', PARCEX='0.8'):
575 # dataact<-read.csv2("%s")
576 # """ % (DictAfcUciOut['TableCont'])#, encoding)
578 # datasup<-read.csv2("%s")
579 # """ % (DictAfcUciOut['TableSup'])#, encoding)
581 # dataet<-read.csv2("%s")
582 # """ % (DictAfcUciOut['TableEt'])#, encoding)
584 # datatotsup<-cbind(dataact,datasup)
585 # datatotet<-cbind(dataact,dataet)
586 # afcact<-ca(dataact,nd=nd)
587 # afcsup<-ca(datatotsup,supcol=((ncol(dataact)+1):ncol(datatotsup)),nd=nd)
588 # afcet<-ca(datatotet,supcol=((ncol(dataact)+1):ncol(datatotet)),nd=nd)
589 # afctot<-afcsup$colcoord
590 # rownames(afctot)<-afcsup$colnames
591 # colnames(afctot)<-paste('coord. facteur',1:nd,sep=' ')
592 # afctot<-cbind(afctot,mass=afcsup$colmass)
593 # afctot<-cbind(afctot,distance=afcsup$coldist)
594 # afctot<-cbind(afctot,intertie=afcsup$colinertia)
595 # rcolet<-afcet$colsup
596 # afctmp<-afcet$colcoord[rcolet,]
597 # rownames(afctmp)<-afcet$colnames[rcolet]
598 # afctmp<-cbind(afctmp,afcet$colmass[rcolet])
599 # afctmp<-cbind(afctmp,afcet$coldist[rcolet])
600 # afctmp<-cbind(afctmp,afcet$colinertia[rcolet])
601 # afctot<-rbind(afctot,afctmp)
602 # write.csv2(afctot,file = "%s")
604 # """ % (DictAfcUciOut['afc_row'], RscriptsPath['Rgraph'])
610 # PlotAfc(afcet,filename="%s",toplot=c%s, PARCEX=PARCEX)
611 # """ % (DictAfcUciOut['AfcColAct'], "('none','active')")
613 # PlotAfc(afcsup,filename="%s",toplot=c%s, PARCEX=PARCEX)
614 # """ % (DictAfcUciOut['AfcColSup'], "('none','passive')")
615 # txt += """PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
616 # """ % (DictAfcUciOut['AfcColEt'], "('none','passive')")
618 # PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
619 # """ % (DictAfcUciOut['AfcRow'], "('all','none')")
620 # f = open(DictAfcUciOut['Rafcuci'], 'w')