36fd860f37ca3c3beb73becb3300d0aba4a11d88
[iramuteq] / PrintRScript.py
1 # -*- coding: utf-8 -*-
2 #Author: Pierre Ratinaud
3 #Copyright (c) 2008-2011 Pierre Ratinaud
4 #Lisense: GNU/GPL
5
6 import tempfile
7 from chemins import ffr
8 import os
9 import locale
10 from datetime import datetime
11 import logging
12
13 log = logging.getLogger('iramuteq.printRscript')
14
15 class PrintRScript :
16     def __init__ (self, analyse):
17         log.info('Rscript')
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()
23     
24     def add(self, txt) :
25         self.script = '\n'.join([self.script, txt])
26     
27     def defvar(self, name, value) :
28         self.add(' <- '.join([name, value]))
29
30     def defvars(self, lvars) :
31         for val in lvars :
32             self.defvar(val[0],val[1])
33
34     def sources(self, lsources) :
35         for source in lsources :
36             self.add('source("%s")' % source)
37
38     def packages(self, lpks) :
39         for pk in lpks :
40             self.add('library(%s)' % pk)
41
42     def load(self, l) :
43         for val in l :
44             self.add('load("%s")' % val)
45
46     def write(self) :
47         with open(self.scriptout, 'w') as f :
48             f.write(self.script)
49
50
51 class chdtxt(PrintRScript) :
52     pass
53
54 def Rcolor(color) :
55     return str(color).replace(')', ', max=255)')
56
57 class Alceste2(PrintRScript) :
58     def doscript(self) :
59         self.sources(['chdfunct'])
60         self.load(['Rdata'])
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']]]
69        
70         self.defvars(lvars) 
71
72
73
74 #    txt = "clnb<-%i\n" % clnb
75 #    txt += """
76 #source("%s")
77 #load("%s")
78 #""" % (RscriptsPath['chdfunct'], DictChdTxtOut['RData'])
79 #    txt += """
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'])
84 #    txt += """
85 #tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
86 #tablesqrpsup<-BuildProf(as.matrix(datasup),n1,clnb)
87 #tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
88 #"""
89 #    txt += """
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'])
92 #    txt += """
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]])
102 #"""
103 #    txt += """
104 #write.csv2(chistabletot,file="%s")
105 #write.csv2(ptabletot,file="%s")
106 #gbcluster<-n1
107 #write.csv2(gbcluster,file="%s")
108 #""" % (DictChdTxtOut['chisqtable'], DictChdTxtOut['ptable'], DictChdTxtOut['SbyClasseOut'])
109 #
110
111
112 def RchdTxt(DicoPath, RscriptPath, mincl, classif_mode, nbt = 9, libsvdc = False, libsvdc_path = None, R_max_mem = False):
113     txt = """
114     source("%s")
115     source("%s")
116     source("%s")
117     source("%s")
118     """ % (RscriptPath['CHD'], RscriptPath['chdtxt'], RscriptPath['anacor'], RscriptPath['Rgraph'])
119     if R_max_mem :
120         txt += """
121     memory.limit(%i)
122         """ % R_max_mem
123
124     txt += """
125     nbt <- %i
126     """ % nbt
127     if libsvdc :
128         txt += """
129         libsvdc <- TRUE
130         libsvdc.path <- "%s"
131         """ % ffr(libsvdc_path)
132     else :
133         txt += """
134         libsvdc <- FALSE
135         libsvdc.path <- NULL
136         """
137
138     txt +="""
139     library(Matrix)
140     data1 <- readMM("%s")
141     data1 <- as(data1, "dgCMatrix")
142     row.names(data1) <- 1:nrow(data1)
143     """ % DicoPath['TableUc1']
144     
145     if classif_mode == 0:
146         txt += """
147         data2 <- readMM("%s")
148         data2 <- as(data2, "dgCMatrix")
149         row.names(data2) <- 1:nrow(data2)
150         """ % DicoPath['TableUc2']
151     log.info('ATTENTION ############# MODEPATATE ####################')
152     txt += """
153     chd1<-CHD(data1, x = nbt, mode.patate = TRUE, libsvdc = libsvdc, libsvdc.path = libsvdc.path)
154     """
155     
156     if classif_mode == 0:
157         txt += """
158     chd2<-CHD(data2, x = nbt, libsvdc = libsvdc, libsvdc.path = libsvdc.path)
159     """
160     else:
161         txt += """
162     chd2<-chd1
163     """    
164     
165     txt += """
166     #lecture des uce
167     listuce1<-read.csv2("%s")
168     """ % DicoPath['listeuce1']
169     
170     if classif_mode == 0:
171         txt += """
172         listuce2<-read.csv2("%s")
173         """ % DicoPath['listeuce2']
174         
175     txt += """
176 #    rm(data1)
177     """
178     
179     if classif_mode == 0:
180         txt += """
181 #        rm(data2)
182         """
183     txt += """
184     chd.result <- Rchdtxt("%s",mincl=%i,classif_mode=%i, nbt = nbt)
185     n1 <- chd.result$n1
186     classeuce1 <- chd.result$cuce1
187     classeuce2 <- chd.result$cuce2
188     """ % (DicoPath['uce'], mincl, classif_mode)
189     
190     txt += """
191     tree.tot1 <- make_tree_tot(chd1)
192 #    open_file_graph("%s", widt = 600, height=400)
193 #    plot(tree.tot1$tree.cl)
194 #    dev.off()
195     """%DicoPath['arbre1']
196     
197     if classif_mode == 0:
198         txt += """
199         tree.tot2 <- make_tree_tot(chd2)
200 #        open_file_graph("%s", width = 600, height=400)
201 #        plot(tree.tot2$tree.cl)
202 #        dev.off()
203         """ % DicoPath['arbre2']  
204               
205     txt += """
206     tree.cut1 <- make_dendro_cut_tuple(tree.tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
207     save(tree.cut1, file="%s")
208     classes<-n1[,ncol(n1)]
209     open_file_graph("%s", width = 600, height=400)
210     plot.dendropr(tree.cut1$tree.cl,classes)
211     open_file_graph("%s", width = 600, height=400)
212     plot(tree.cut1$dendro_tot_cl)
213     dev.off()
214     """ % (DicoPath['Rdendro'], DicoPath['dendro1'], DicoPath['arbre1'])
215     
216     if classif_mode == 0:
217         txt += """
218         tree.cut2 <- make_dendro_cut_tuple(tree.tot2$dendro_tuple, chd.result$coord_ok, classeuce2, 2, nbt)
219         open_file_graph("%s", width = 600, height=400)
220         plot(tree.cut2$tree.cl)
221         dev.off()
222         open_file_graph("%s", width = 600, height=400)
223         plot(tree.cut1$dendro_tot_cl)
224         dev.off()
225         """ % (DicoPath['dendro2'], DicoPath['arbre2'])
226         
227     txt += """
228     save.image(file="%s")
229     """ % DicoPath['RData']
230     fileout = open(DicoPath['Rchdtxt'], 'w')
231     fileout.write(txt)
232     fileout.close()
233
234 def RPamTxt(corpus, RscriptPath):
235     DicoPath = corpus.dictpathout
236     param = corpus.parametre
237     print param
238     txt = """
239     source("%s")
240     """ % (RscriptPath['pamtxt'])
241     txt += """
242     source("%s")
243     """ % (RscriptPath['Rgraph'])
244     txt += """
245     result <- pamtxt("%s", "%s", "%s", method = "%s", clust_type = "%s", clnb = %i)
246     n1 <- result$uce
247     """ % (DicoPath['TableUc1'], DicoPath['listeuce1'], DicoPath['uce'], param['method'], param['cluster_type'], param['nbcl'] )
248     txt += """
249     open_file_graph("%s", width=400, height=400)
250     plot(result$cl)
251     dev.off()
252     """ % (DicoPath['arbre1'])
253     txt += """
254     save.image(file="%s")
255     """ % DicoPath['RData']
256     fileout = open(DicoPath['Rchdtxt'], 'w')
257     fileout.write(txt)
258     fileout.close()
259     
260
261 def RchdQuest(DicoPath, RscriptPath, nbcl = 10, mincl = 10):
262     txt = """
263     source("%s")
264     source("%s")
265     source("%s")
266     source("%s")
267     """ % (RscriptPath['CHD'], RscriptPath['chdquest'], RscriptPath['anacor'],RscriptPath['Rgraph'])
268
269     txt += """
270     nbt <- %i - 1
271     mincl <- %i
272     """ % (nbcl, mincl)
273
274     txt += """
275     chd.result<-Rchdquest("%s","%s","%s", nbt = nbt, mincl = mincl)
276     n1 <- chd.result$n1
277     classeuce1 <- chd.result$cuce1
278     """ % (DicoPath['Act01'], DicoPath['listeuce1'], DicoPath['uce'])
279     
280     txt += """
281     tree_tot1 <- make_tree_tot(chd.result$chd)
282     open_file_graph("%s", width = 600, height=400)
283     plot(tree_tot1$tree.cl)
284     dev.off()
285     """%DicoPath['arbre1']
286     
287     txt += """
288     tree_cut1 <- make_dendro_cut_tuple(tree_tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
289     tree.cut1 <- tree_cut1
290     save(tree.cut1, file="%s")
291     open_file_graph("%s", width = 600, height=400)
292     classes<-n1[,ncol(n1)]
293     plot.dendropr(tree_cut1$tree.cl,classes)
294     """ % (DicoPath['Rdendro'],DicoPath['dendro1'])
295     
296     txt += """
297     save.image(file="%s")
298     """ % DicoPath['RData']
299     fileout = open(DicoPath['Rchdquest'], 'w')
300     fileout.write(txt)
301     fileout.close()
302     
303 def AlcesteTxtProf(DictChdTxtOut, RscriptsPath, clnb, taillecar):
304     txt = "clnb<-%i\n" % clnb
305     txt += """
306 source("%s")
307 load("%s")
308 """ % (RscriptsPath['chdfunct'], DictChdTxtOut['RData'])
309     txt += """
310 dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
311 datasup<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
312 dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
313 """ % (DictChdTxtOut['Contout'], DictChdTxtOut['ContSupOut'], DictChdTxtOut['ContEtOut'])
314     txt += """
315 tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
316 tablesqrpsup<-BuildProf(as.matrix(datasup),n1,clnb)
317 tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
318 """
319     txt += """
320 PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s",tablesqrpsup[4],tablesqrpsup[5])
321 """ % (DictChdTxtOut['PROFILE_OUT'], DictChdTxtOut['ANTIPRO_OUT'])
322     txt += """
323 colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
324 colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
325 colnames(tablesqrpsup[[2]])<-paste('classe',1:clnb,sep=' ')
326 colnames(tablesqrpsup[[1]])<-paste('classe',1:clnb,sep=' ')
327 colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
328 colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
329 chistabletot<-rbind(tablesqrpact[2][[1]],tablesqrpsup[2][[1]])
330 chistabletot<-rbind(chistabletot,tablesqrpet[2][[1]])
331 ptabletot<-rbind(tablesqrpact[1][[1]],tablesqrpet[1][[1]])
332 """
333     txt += """
334 write.csv2(chistabletot,file="%s")
335 write.csv2(ptabletot,file="%s")
336 gbcluster<-n1
337 write.csv2(gbcluster,file="%s")
338 """ % (DictChdTxtOut['chisqtable'], DictChdTxtOut['ptable'], DictChdTxtOut['SbyClasseOut'])
339     if clnb > 2 :
340         txt += """
341     library(ca)
342     colnames(dataact)<-paste('classe',1:clnb,sep=' ')
343     colnames(datasup)<-paste('classe',1:clnb,sep=' ')
344     colnames(dataet)<-paste('classe',1:clnb,sep=' ')
345     rowtot<-nrow(dataact)+nrow(dataet)+nrow(datasup)
346     afctable<-rbind(as.matrix(dataact),as.matrix(datasup))
347     afctable<-rbind(afctable,as.matrix(dataet))
348     colnames(afctable)<-paste('classe',1:clnb,sep=' ')
349     afc<-ca(afctable,suprow=((nrow(dataact)+1):rowtot),nd=(ncol(afctable)-1))
350     debsup<-nrow(dataact)+1
351     debet<-nrow(dataact)+nrow(datasup)+1
352     fin<-rowtot
353     afc<-AddCorrelationOk(afc)
354     """
355     #FIXME : split this!!!
356         txt += """
357     source("%s")
358     """ % RscriptsPath['Rgraph']
359     
360         txt += """
361         afc <- summary.ca.dm(afc)
362         afc_table <- create_afc_table(afc)
363         write.csv2(afc_table$facteur, file = "%s")
364         write.csv2(afc_table$colonne, file = "%s")
365         write.csv2(afc_table$ligne, file = "%s")
366         """ % (DictChdTxtOut['afc_facteur'], DictChdTxtOut['afc_col'], DictChdTxtOut['afc_row'])
367     
368         txt += """
369         xlab <- paste('facteur 1 - ', round(afc$facteur[1,2],2), sep = '')
370         ylab <- paste('facteur 2 - ', round(afc$facteur[2,2],2), sep = '')
371         xlab <- paste(xlab, ' %', sep = '')
372         ylab <- paste(ylab, ' %', sep = '')
373         """
374     
375         txt += """
376     PARCEX<-%s
377     """ % taillecar
378         txt += """
379     PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
380     """ % (DictChdTxtOut['AFC2DL_OUT'])
381         txt += """
382     PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=debsup, fin=(debet-1), xlab = xlab, ylab = ylab)
383     """ % (DictChdTxtOut['AFC2DSL_OUT'])
384         txt += """
385     PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=debet, fin=fin, xlab = xlab, ylab = ylab)
386     """ % (DictChdTxtOut['AFC2DEL_OUT'])
387         txt += """
388     PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col=TRUE, what='coord', xlab = xlab, ylab = ylab)
389     """ % (DictChdTxtOut['AFC2DCL_OUT'])
390         txt += """
391     PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
392     PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debsup, fin=(debet-1), xlab = xlab, ylab = ylab)
393     PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debet, fin=fin, xlab = xlab, ylab = ylab)
394     PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col=TRUE, what='crl', xlab = xlab, ylab = ylab)
395     """ % (DictChdTxtOut['AFC2DCoul'], DictChdTxtOut['AFC2DCoulSup'], DictChdTxtOut['AFC2DCoulEt'], DictChdTxtOut['AFC2DCoulCl'])
396        
397     txt += """
398 #rm(dataact)
399 #rm(datasup)
400 #rm(dataet)
401 rm(tablesqrpact)
402 rm(tablesqrpsup)
403 rm(tablesqrpet)
404 save.image(file="%s")
405 """ % DictChdTxtOut['RData']
406     file = open(DictChdTxtOut['RTxtProfGraph'], 'w')
407     file.write(txt)
408     file.close()
409
410
411 def write_afc_graph(self):
412     if self.param['over'] : over = 'TRUE'
413     else : over = 'FALSE'
414
415     if self.param['do_select_nb'] : do_select_nb = 'TRUE'
416     else : do_select_nb = 'FALSE'
417
418     if self.param['do_select_chi'] : do_select_chi = 'TRUE'
419     else : do_select_chi = 'FALSE'
420
421     if self.param['do_select_chi_classe'] : do_select_chi_classe = 'TRUE'
422     else : do_select_chi_classe = 'FALSE'
423
424     if self.param['cex_txt'] : cex_txt = 'TRUE'
425     else : cex_txt = 'FALSE'
426
427     if self.param['tchi'] : tchi = 'TRUE'
428     else : tchi = 'FALSE'
429
430     with open(self.RscriptsPath['afc_graph'], 'r') as f:
431         txt = f.read()
432
433 #    self.DictPathOut['RData'], \
434     scripts = txt % (self.RscriptsPath['Rgraph'],\
435     self.param['typegraph'], \
436     self.param['what'], \
437     self.param['facteur'][0],\
438     self.param['facteur'][1], \
439     self.param['facteur'][2], \
440     self.param['qui'], \
441     over,  do_select_nb, \
442     self.param['select_nb'],  \
443     do_select_chi, \
444     self.param['select_chi'], \
445     do_select_chi_classe, \
446     self.param['nbchic'], \
447     cex_txt, \
448     self.param['txt_min'], \
449     self.param['txt_max'], \
450     self.fileout, \
451     self.param['width'], \
452     self.param['height'],\
453     self.param['taillecar'], \
454     self.param['alpha'], \
455     self.param['film'], \
456     tchi,\
457     self.param['tchi_min'],\
458     self.param['tchi_max'],\
459     ffr(os.path.dirname(self.fileout)))
460     return scripts
461         
462 def print_simi3d(self):
463     simi3d = self.parent.simi3dpanel
464     txt = '#Fichier genere par Iramuteq'
465     if simi3d.movie.GetValue() :
466         movie = "'" + ffr(os.path.dirname(self.DictPathOut['RData'])) + "'"
467     else :
468         movie = 'NULL'
469     
470     #if self.corpus.parametres['type'] == 'corpus' :
471     #    header = 'TRUE'
472     #else :
473     #    header = 'FALSE'
474     header = 'FALSE'
475     txt += """
476     dm<-read.csv2("%s",row.names=1,header = %s)
477     load("%s")
478     """ % (self.DictPathOut['Contout'], header, self.DictPathOut['RData'])
479     
480     txt += """
481     source("%s")
482     """ % self.parent.RscriptsPath['Rgraph']
483
484
485     txt += """
486     make.simi.afc(dm,chistabletot, lim=%i, alpha = %.2f, movie = %s)
487     """ % (simi3d.spin_1.GetValue(), float(simi3d.slider_1.GetValue())/100, movie)
488     tmpfile = tempfile.mktemp(dir=self.parent.TEMPDIR)
489     tmp = open(tmpfile,'w')
490     tmp.write(txt)
491     tmp.close()
492     return tmpfile
493
494 def dendroandbarplot(table, rownames, colnames, rgraph, tmpgraph, intxt = False, dendro=False) :
495     if not intxt :
496         txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
497     rownb = len(rownames)
498     rownames = 'c("' + '","'.join(rownames) + '")'
499     colnames = 'c("' + '","'.join(colnames) + '")'
500     if not intxt :
501         #FIXME
502         txt = """
503             di <- matrix(data=%s, nrow=%i, byrow = TRUE)
504             rownames(di)<- %s
505             colnames(di) <- %s
506         """ % (txttable, rownb, rownames, colnames)
507     else :
508         txt = intxt
509     txt += """
510         load("%s")
511         library(ape)
512         source("%s")
513         height <- (30*ncol(di)) + (15*nrow(di))
514         height <- ifelse(height <= 400, 400, height)
515         width <- 500
516         open_file_graph("%s", width=width, height=height)
517         plot.dendro.lex(tree.cut1$tree.cl, di)
518         """ % (ffr(dendro),ffr(rgraph),  ffr(tmpgraph))
519     return txt
520
521 def barplot(table, rownames, colnames, rgraph, tmpgraph, intxt = False) :
522     if not intxt :
523         txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
524     #width = 100 + (15 * len(rownames)) + (100 * len(colnames))
525     #height =  len(rownames) * 15
526     rownb = len(rownames)
527     #if height < 400 :
528     #    height = 400
529     rownames = 'c("' + '","'.join(rownames) + '")'
530     colnames = 'c("' + '","'.join(colnames) + '")'
531     if not intxt :
532         #FIXME
533         txt = """
534             inf <- NA
535             di <- matrix(data=%s, nrow=%i, byrow = TRUE)
536             di[is.na(di)] <- max(di, na.rm=TRUE) + 2
537             rownames(di)<- %s
538             colnames(di) <- %s
539         """ % (txttable, rownb, rownames, colnames)
540     else :
541         txt = intxt
542     txt += """
543         source("%s")
544         color = rainbow(nrow(di))
545         width <- 100 + (20*length(rownames(di))) + (100 * length(colnames(di)))
546         height <- nrow(di) * 15
547         if (height < 400) { height <- 400}
548         open_file_graph("%s",width = width, height = height)
549         par(mar=c(0,0,0,0))
550             layout(matrix(c(1,2),1,2, byrow=TRUE),widths=c(3,lcm(7)))
551         par(mar=c(2,2,1,0))
552         coord <- barplot(as.matrix(di), beside = TRUE, col = color, space = c(0.1,0.6))
553         c <- colMeans(coord)
554         c1 <- c[-1]
555         c2 <- c[-length(c)]
556         cc <- cbind(c1,c2)
557         lcoord <- apply(cc, 1, mean)
558         abline(v=lcoord)
559         if (min(di) < 0) {
560             amp <- abs(max(di) - min(di))
561         } else {
562             amp <- max(di)
563         }
564         if (amp < 10) {
565             d <- 2
566         } else {
567             d <- signif(amp%%/%%10,1)
568         }
569         mn <- round(min(di))
570         mx <- round(max(di))
571         for (i in mn:mx) {
572             if ((i/d) == (i%%/%%d)) { 
573                 abline(h=i,lty=3)
574             }
575         }
576         par(mar=c(0,0,0,0))
577         plot(0, axes = FALSE, pch = '')
578         legend(x = 'center' , rownames(di), fill = color)
579         dev.off()
580         """ % (rgraph, ffr(tmpgraph))    
581     return txt
582
583 #def RAfcUci(DictAfcUciOut, nd=2, RscriptsPath='', PARCEX='0.8'):
584 #    txt = """
585 #    library(ca)
586 #    nd<-%i
587 #    """ % nd
588 #    txt += """
589 #    dataact<-read.csv2("%s")
590 #    """ % (DictAfcUciOut['TableCont'])#, encoding)
591 #    txt += """
592 #    datasup<-read.csv2("%s")
593 #    """ % (DictAfcUciOut['TableSup'])#, encoding)
594 #    txt += """
595 #    dataet<-read.csv2("%s")
596 #    """ % (DictAfcUciOut['TableEt'])#, encoding)
597 #    txt += """
598 #    datatotsup<-cbind(dataact,datasup)
599 #    datatotet<-cbind(dataact,dataet)
600 #    afcact<-ca(dataact,nd=nd)
601 #    afcsup<-ca(datatotsup,supcol=((ncol(dataact)+1):ncol(datatotsup)),nd=nd)
602 #    afcet<-ca(datatotet,supcol=((ncol(dataact)+1):ncol(datatotet)),nd=nd)
603 #    afctot<-afcsup$colcoord
604 #    rownames(afctot)<-afcsup$colnames
605 #    colnames(afctot)<-paste('coord. facteur',1:nd,sep=' ')
606 #    afctot<-cbind(afctot,mass=afcsup$colmass)
607 #    afctot<-cbind(afctot,distance=afcsup$coldist)
608 #    afctot<-cbind(afctot,intertie=afcsup$colinertia)
609 #    rcolet<-afcet$colsup
610 #    afctmp<-afcet$colcoord[rcolet,]
611 #    rownames(afctmp)<-afcet$colnames[rcolet]
612 #    afctmp<-cbind(afctmp,afcet$colmass[rcolet])
613 #    afctmp<-cbind(afctmp,afcet$coldist[rcolet])
614 #    afctmp<-cbind(afctmp,afcet$colinertia[rcolet])
615 #    afctot<-rbind(afctot,afctmp)
616 #    write.csv2(afctot,file = "%s")
617 #    source("%s")
618 #    """ % (DictAfcUciOut['afc_row'], RscriptsPath['Rgraph'])
619 #    txt += """
620 #    PARCEX=%s
621 #    """ % PARCEX
622 #    #FIXME
623 #    txt += """
624 #    PlotAfc(afcet,filename="%s",toplot=c%s, PARCEX=PARCEX)
625 #    """ % (DictAfcUciOut['AfcColAct'], "('none','active')")
626 #    txt += """
627 #    PlotAfc(afcsup,filename="%s",toplot=c%s, PARCEX=PARCEX)
628 #    """ % (DictAfcUciOut['AfcColSup'], "('none','passive')")
629 #    txt += """PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
630 #    """ % (DictAfcUciOut['AfcColEt'], "('none','passive')")
631 #    txt += """
632 #    PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
633 #    """ % (DictAfcUciOut['AfcRow'], "('all','none')")
634 #    f = open(DictAfcUciOut['Rafcuci'], 'w')
635 #    f.write(txt)
636 #    f.close()
637
638 class PrintSimiScript(PrintRScript) :
639     def make_script(self) :
640         self.txtgraph = ''
641         self.packages(['igraph', 'proxy', 'Matrix'])
642         self.sources([self.analyse.parent.RscriptsPath['simi'], self.analyse.parent.RscriptsPath['Rgraph']])
643         txt = """
644         dm.path <- "%s"
645         cn.path <- "%s"
646         selected.col <- "%s"
647         """ % (self.pathout['mat01.csv'], self.pathout['actives.csv'], self.pathout['selected.csv'])
648         txt += """
649         dm <-readMM(dm.path)
650         cn <- read.table(cn.path, sep=';', quote='"')
651         colnames(dm) <- cn[,1]
652         sel.col <- read.csv2(selected.col)
653         dm <- dm[, sel.col[,1] + 1]
654         """
655
656         if self.parametres['coeff'] == 0 :
657             method = 'cooc'
658             txt += """
659             method <- 'cooc'
660             mat <- make.a(dm)
661             """
662         else :
663             txt += """
664             dm <- as.matrix(dm)
665             """
666         if self.parametres['coeff'] == 1 :
667             method = 'prcooc'
668             txt += """
669             method <- 'Russel'
670             mat <- simil(dm, method = 'Russel', diag = TRUE, upper = TRUE, by_rows = FALSE)
671             """
672         elif self.analyse.indices[self.parametres['coeff']] == 'binomial' :
673             method = 'binomial'
674             txt += """
675             method <- 'binomial'
676             mat <- binom.sim(dm)
677             """
678         elif self.parametres['coeff'] != 0 :
679             method = self.analyse.indices[self.parametres['coeff']]
680             txt += """
681             method <-"%s"
682             mat <- simil(dm, method = method, diag = TRUE, upper = TRUE, by_rows = FALSE)
683             """ % self.analyse.indices[self.parametres['coeff']]
684         txt += """
685         mat <- as.matrix(stats::as.dist(mat,diag=TRUE,upper=TRUE))
686         mat[is.na(mat)] <- 0
687         mat[is.infinite(mat)] <- 0
688         """
689         if self.parametres['layout'] == 0 : layout = 'random'
690         if self.parametres['layout'] == 1 : layout = 'circle'
691         if self.parametres['layout'] == 2 : layout = 'frutch'
692         if self.parametres['layout'] == 3 : layout = 'kawa'
693         if self.parametres['layout'] == 4 : layout = 'graphopt'
694
695         self.filename=''
696         if self.parametres['type_graph'] == 0 : type = 'tkplot'
697         if self.parametres['type_graph'] == 1 : 
698             graphnb = 1
699             type = 'nplot'
700             dirout = os.path.dirname(self.pathout['mat01'])
701             while os.path.exists(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png')):
702                 graphnb +=1
703             self.filename = ffr(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png'))
704         if self.parametres['type_graph'] == 2 : type = 'rgl'
705
706         if self.parametres['arbremax'] : 
707             arbremax = 'TRUE'
708             self.txtgraph += ' - arbre maximum'
709         else : arbremax = 'FALSE'
710         
711         if self.parametres['coeff_tv'] : 
712             coeff_tv = self.parametres['coeff_tv_nb']
713             tvminmax = 'c(NULL,NULL)'
714         elif not self.parametres['coeff_tv'] or self.parametres.get('sformchi', False) :
715             coeff_tv = 'NULL'
716             tvminmax = 'c(%i, %i)' %(self.parametres['tvmin'], self.parametres['tvmax'])
717         if self.parametres['coeff_te'] : coeff_te = 'c(%i,%i)' % (self.parametres['coeff_temin'], self.parametres['coeff_temax'])
718         else : coeff_te = 'NULL'
719         
720         if self.parametres['vcex'] or self.parametres.get('cexfromchi', False) :
721             vcexminmax = 'c(%i/10,%i/10)' % (self.parametres['vcexmin'],self.parametres['vcexmax'])
722         else :
723             vcexminmax = 'c(NULL,NULL)'
724         if not self.parametres['label_v'] : label_v = 'FALSE'
725         else : label_v = 'TRUE'
726
727         if not self.parametres['label_e'] : label_e = 'FALSE'
728         else : label_e = 'TRUE'
729         
730         if self.parametres['seuil_ok'] : seuil = str(self.parametres['seuil'])
731         else : seuil = 'NULL'
732             
733         cols = str(self.parametres['cols']).replace(')',', max=255)')
734         cola = str(self.parametres['cola']).replace(')',',max=255)')
735
736         txt += """
737         minmaxeff <- %s
738         """ % tvminmax
739         txt += """
740         vcexminmax <- %s
741         """ % vcexminmax
742         txt += """
743         cex = %i/10
744         """ % self.parametres['cex']
745
746         if self.parametres['film'] : 
747             txt += """
748             film <- "%s"
749             """ % self.pathout['film']
750         else : 
751             txt += """
752             film <- NULL
753             """
754         txt += """
755         seuil <- %s
756         """ % seuil
757         
758         txt += """
759         label.v <- %s
760         label.e <- %s
761         """ % (label_v, label_e)
762         txt += """
763         cols <- rgb%s
764         cola <- rgb%s
765         """ % (cols, cola)
766         txt += """
767         width <- %i
768         height <- %i
769         """ % (self.parametres['width'], self.parametres['height'])
770         if self.parametres['keep_coord'] :
771             txt += """
772             coords <- try(coords, TRUE)
773             if (!is.matrix(coords)) {
774                 coords<-NULL
775             }
776             """
777         else :
778             txt += """
779             coords <- NULL
780             """
781         txt += """
782         alpha <- %i/100
783         """ % self.parametres['alpha']
784         txt += """
785         alpha <- %i/100
786         """ % self.parametres['alpha']
787 #############################################
788         if  self.parametres.get('bystar',False) :
789             txt += """
790             et <- list()
791             """
792             print self.parametres
793             for i,et in enumerate(self.parametres['stars']) :
794                 txt+= """
795                 et[[%i]] <- c(%s)
796                 """ % (i+1, ','.join(et[1:]))
797             txt+= """
798             unetoile <- c('%s')
799             """ % ("','".join([val[0] for val in self.tableau.etline]))
800             txt += """
801             fsum <- NULL
802             rs <- rowSums(dm)
803             for (i in 1:length(unetoile)) {
804                 print(unetoile[i])
805                 tosum <- et[[i]]
806                 if (length(tosum) > 1) {
807                     fsum <- cbind(fsum, colSums(dm[tosum,]))
808                 } else {
809                     fsum <- cbind(fsum, dm[tosum,])
810                 }
811             }
812             source("%s")
813             lex <- AsLexico2(fsum, chip=TRUE)
814             dcol <- apply(lex[[4]],1,which.max)
815             toblack <- apply(lex[[4]],1,max)
816             gcol <- rainbow(length(unetoile))
817             #gcol[2] <- 'orange'
818             vertex.label.color <- gcol[dcol]
819             vertex.label.color[which(toblack <= 3.84)] <- 'black'
820             leg <- list(unetoile=unetoile, gcol=gcol)  
821             cols <- vertex.label.color
822             chivertex.size <- norm.vec(toblack, vcexminmax[1],  vcexminmax[2])
823             
824             """ % (self.parent.RscriptsPath['chdfunct'])
825         else :
826             txt += """
827             vertex.label.color <- 'black' 
828             chivertex.size <- 1
829             leg<-NULL
830             """
831 #############################################        
832
833 #        txt += """
834 #        eff <- colSums(dm)
835 #        g.ori <- graph.adjacency(mat, mode='lower', weighted = TRUE)
836 #        w.ori <- E(g.ori)$weight
837 #        if (max.tree) {
838 #            if (method == 'cooc') {
839 #                E(g.ori)$weight <- 1 / w.ori
840 #            } else {
841 #                E(g.ori)$weigth <- 1 - w.ori
842 #            }
843 #            g.max <- minimum.spanning.tree(g.ori)
844 #            if (method == 'cooc') {
845 #                E(g.max)$weight <- 1 / E(g.max)$weight
846 #            } else {
847 #                E(g.max)$weight <- 1 - E(g.max)$weight
848 #            }
849 #            g.toplot <- g.max
850 #        } else {
851 #            g.toplot <- g.ori
852 #        }
853 #        """
854         txt += """
855         eff <- colSums(dm)
856         x <- list(mat = mat, eff = eff)
857         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)
858         """ % (method, type, layout, arbremax, coeff_tv, coeff_te)
859             
860         if self.parametres.get('bystar',False) :
861             if self.parametres.get('cexfromchi', False) :
862                 txt+="""
863                     label.cex<-chivertex.size
864                     """
865             else :
866                 txt+="""
867                 label.cex <- NULL
868                 """
869             if self.parametres.get('sfromchi', False) :
870                 txt += """
871                 vertex.size <- norm.vec(toblack, minmaxeff[1], minmaxeff[2])
872                 """
873             else :
874                 txt += """
875                 vertex.size <- NULL
876                 """
877         else :
878             #FIXME
879             tmpchi = False
880             if tmpchi :
881                 txt += """
882                 lchi <- read.table("%s")
883                 lchi <- lchi[,1]
884                 """ % ffr(tmpchi)
885                 if 'selected_col' in dir(self.tableau) :
886                     txt += """
887                     lchi <- lchi[c%s+1]
888                     """ % datas
889             if tmpchi and self.parametres.get('cexfromchi', False) :
890                 txt += """ 
891                 label.cex <- norm.vec(lchi, vcexminmax[1], vcexminmax[2])
892                 """
893             else :
894                 txt += """
895             if (is.null(vcexminmax[1])) {
896                 label.cex <- NULL
897             } else {
898                 label.cex <- graph.simi$label.cex
899             }
900             """
901             if tmpchi and self.parametres.get('sfromchi', False) :
902                 txt += """ 
903                 vertex.size <- norm.vec(lchi, minmaxeff[1], minmaxeff[2])
904                 """
905             else :
906                 txt += """
907             if (is.null(minmaxeff[1])) {
908                 vertex.size <- NULL
909             } else {
910                 vertex.size <- graph.simi$eff
911             }
912             """
913         txt += """ vertex.size <- NULL """
914         txt += """
915         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)
916         save.image(file="%s")
917         """ % (type, self.filename, self.pathout['RData'])
918         
919         self.add(txt)
920         self.write()
921
922 class WordCloudRScript(PrintRScript) :
923     def make_script(self) :
924         self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
925         self.packages(['wordcloud'])
926         bg_col = Rcolor(self.parametres['col_bg'])
927         txt_col = Rcolor(self.parametres['col_text'])
928         txt = """
929         act <- read.csv2("%s", header = FALSE, row.names=1, sep='\t')
930         selected.col <- read.table("%s")
931         toprint <- as.matrix(act[selected.col[,1] + 1,])
932         rownames(toprint) <- rownames(act)[selected.col[,1] + 1]
933         maxword <- %i
934         if (nrow(toprint) > maxword) {
935             toprint <- as.matrix(toprint[order(toprint[,1], decreasing=TRUE),])
936             toprint <- as.matrix(toprint[1:maxword,])
937         }
938         open_file_graph("%s", width = %i, height = %i)
939         par(bg=rgb%s)
940         wordcloud(row.names(toprint), toprint[,1], scale=c(%f,%f), random.order=FALSE, colors=rgb%s)
941         dev.off()
942         """ % (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)
943         self.add(txt)
944         self.write()