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