Merge branch 'master' of http://www.iramuteq.org/git/iramuteq
[iramuteq] / PrintRScript.py
1 # -*- coding: utf-8 -*-
2 #Author: Pierre Ratinaud
3 #Copyright (c) 2008-2011 Pierre Ratinaud
4 #License: 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\n" % 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", encoding = \'utf8\')' % ffr(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")' % ffr(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, svdmethod = 'svdR', libsvdc = False, libsvdc_path = None, R_max_mem = False, mode_patate = False):
113     txt = """
114     source("%s")
115     source("%s")
116     source("%s")
117     source("%s")
118     """ % (ffr(RscriptPath['CHD']), ffr(RscriptPath['chdtxt']), ffr(RscriptPath['anacor']), ffr(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 svdmethod == 'svdlibc' and libsvdc :
128         txt += """
129         svd.method <- 'svdlibc'
130         libsvdc.path <- "%s"
131         """ % ffr(libsvdc_path)
132     elif svdmethod == 'irlba' :
133         txt += """
134         library(irlba)
135         svd.method <- 'irlba'
136         libsvdc.path <- NULL
137         """
138     else :
139         txt += """
140         svd.method = 'svdR'
141         libsvdc.path <- NULL
142         """
143     if mode_patate :
144         txt += """
145         mode.patate = TRUE
146         """
147     else :
148         txt += """
149         mode.patate = FALSE
150         """
151     txt +="""
152     library(Matrix)
153     data1 <- readMM("%s")
154     data1 <- as(data1, "dgCMatrix")
155     row.names(data1) <- 1:nrow(data1)
156     """ % ffr(DicoPath['TableUc1'])
157     
158     if classif_mode == 0:
159         txt += """
160         data2 <- readMM("%s")
161         data2 <- as(data2, "dgCMatrix")
162         row.names(data2) <- 1:nrow(data2)
163         """ % ffr(DicoPath['TableUc2'])
164     txt += """
165     chd1<-CHD(data1, x = nbt, mode.patate = mode.patate, svd.method = svd.method, libsvdc.path = libsvdc.path)
166     """
167     
168     if classif_mode == 0:
169         txt += """
170     chd2<-CHD(data2, x = nbt, mode.patate = mode.patate, svd.method = svd.method, libsvdc.path = libsvdc.path)
171     """
172     
173     txt += """
174     #lecture des uce
175     listuce1<-read.csv2("%s")
176     """ % ffr(DicoPath['listeuce1'])
177     
178     if classif_mode == 0:
179         txt += """
180         listuce2<-read.csv2("%s")
181         """ % ffr(DicoPath['listeuce2'])
182         
183     txt += """
184     rm(data1)
185     """
186     
187     if classif_mode == 0:
188         txt += """
189         rm(data2)
190         """
191     txt += """
192     classif_mode <- %i
193     mincl <- %i
194     uceout <- "%s"
195     if (classif_mode == 0) {
196         chd.result <- Rchdtxt(uceout, chd1, chd2 = chd2, mincl = mincl,classif_mode = classif_mode, nbt = nbt)
197     } else {
198         chd.result <- Rchdtxt(uceout, chd1, chd2 = chd1, mincl = mincl,classif_mode = classif_mode, nbt = nbt)
199     }
200     n1 <- chd.result$n1
201     classeuce1 <- chd.result$cuce1
202     classes<-n1[,ncol(n1)]
203     write.csv2(n1, file="%s")
204     rm(n1)
205     """ % (classif_mode, mincl, ffr(DicoPath['uce']), ffr(DicoPath['n1.csv']))
206     
207     txt += """
208     tree.tot1 <- make_tree_tot(chd1)
209 #    open_file_graph("%s", widt = 600, height=400)
210 #    plot(tree.tot1$tree.cl)
211 #    dev.off()
212     """ % ffr(DicoPath['arbre1'])
213     
214     if classif_mode == 0:
215         txt += """
216         classeuce2 <- chd.result$cuce2
217         tree.tot2 <- make_tree_tot(chd2)
218 #        open_file_graph("%s", width = 600, height=400)
219 #        plot(tree.tot2$tree.cl)
220 #        dev.off()
221         """ % ffr(DicoPath['arbre2'] ) 
222               
223     txt += """
224     tree.cut1 <- make_dendro_cut_tuple(tree.tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
225     save(tree.cut1, file="%s")
226     
227     open_file_graph("%s", width = 600, height=400)
228     plot.dendropr(tree.cut1$tree.cl,classes, histo=TRUE)
229     open_file_graph("%s", width = 600, height=400)
230     plot(tree.cut1$dendro_tot_cl)
231     dev.off()
232     """ % (ffr(DicoPath['Rdendro']), ffr(DicoPath['dendro1']), ffr(DicoPath['arbre1']))
233     
234     if classif_mode == 0:
235         txt += """
236         tree.cut2 <- make_dendro_cut_tuple(tree.tot2$dendro_tuple, chd.result$coord_ok, classeuce2, 2, nbt)
237         open_file_graph("%s", width = 600, height=400)
238         plot(tree.cut2$tree.cl)
239         dev.off()
240         open_file_graph("%s", width = 600, height=400)
241         plot(tree.cut1$dendro_tot_cl)
242         dev.off()
243         """ % (ffr(DicoPath['dendro2']), ffr(DicoPath['arbre2']))
244         
245     txt += """
246     
247     #save.image(file="%s")
248     """ % (ffr(DicoPath['RData']))
249     
250     fileout = open(DicoPath['Rchdtxt'], 'w')
251     fileout.write(txt)
252     fileout.close()
253
254 def RPamTxt(corpus, RscriptPath):
255     DicoPath = corpus.pathout
256     param = corpus.parametres
257     txt = """
258     source("%s")
259     """ % (RscriptPath['pamtxt'])
260     txt += """
261     source("%s")
262     """ % (RscriptPath['Rgraph'])
263     txt += """
264     result <- pamtxt("%s", "%s", "%s", method = "%s", clust_type = "%s", clnb = %i)
265     n1 <- result$uce
266     """ % (DicoPath['TableUc1'], DicoPath['listeuce1'], DicoPath['uce'], param['method'], param['cluster_type'], param['nbcl'] )
267     txt += """
268     open_file_graph("%s", width=400, height=400)
269     plot(result$cl)
270     dev.off()
271     """ % (DicoPath['arbre1'])
272     txt += """
273     save.image(file="%s")
274     """ % DicoPath['RData']
275     fileout = open(DicoPath['Rchdtxt'], 'w')
276     fileout.write(txt)
277     fileout.close()
278     
279
280 def RchdQuest(DicoPath, RscriptPath, nbcl = 10, mincl = 10):
281     txt = """
282     source("%s")
283     source("%s")
284     source("%s")
285     source("%s")
286     """ % (ffr(RscriptPath['CHD']), ffr(RscriptPath['chdquest']), ffr(RscriptPath['anacor']),ffr(RscriptPath['Rgraph']))
287
288     txt += """
289     nbt <- %i - 1
290     mincl <- %i
291     """ % (nbcl, mincl)
292
293     txt += """
294     chd.result<-Rchdquest("%s","%s","%s", nbt = nbt, mincl = mincl)
295     n1 <- chd.result$n1
296     classeuce1 <- chd.result$cuce1
297     """ % (ffr(DicoPath['mat01.csv']), ffr(DicoPath['listeuce1']), ffr(DicoPath['uce']))
298     
299     txt += """
300     tree_tot1 <- make_tree_tot(chd.result$chd)
301     open_file_graph("%s", width = 600, height=400)
302     plot(tree_tot1$tree.cl)
303     dev.off()
304     """ % ffr(DicoPath['arbre1'])
305     
306     txt += """
307     tree_cut1 <- make_dendro_cut_tuple(tree_tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
308     tree.cut1 <- tree_cut1
309     save(tree.cut1, file="%s")
310     open_file_graph("%s", width = 600, height=400)
311     classes<-n1[,ncol(n1)]
312     plot.dendropr(tree_cut1$tree.cl,classes, histo = TRUE)
313     """ % (ffr(DicoPath['Rdendro']), ffr(DicoPath['dendro1']))
314     
315     txt += """
316     save.image(file="%s")
317     """ % ffr(DicoPath['RData'])
318     fileout = open(DicoPath['Rchdquest'], 'w')
319     fileout.write(txt)
320     fileout.close()
321     
322 def AlcesteTxtProf(DictChdTxtOut, RscriptsPath, clnb, taillecar):
323     txt = "clnb<-%i\n" % clnb
324     txt += """
325 source("%s")
326 #load("%s")
327 n1 <- read.csv2("%s")
328 """ % (ffr(RscriptsPath['chdfunct']), ffr(DictChdTxtOut['RData']), ffr(DictChdTxtOut['n1.csv']))
329     txt += """
330 dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
331 datasup<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
332 dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
333 """ % (ffr(DictChdTxtOut['Contout']), ffr(DictChdTxtOut['ContSupOut']), ffr(DictChdTxtOut['ContEtOut']))
334     txt += """
335 tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
336 tablesqrpsup<-BuildProf(as.matrix(datasup),n1,clnb)
337 tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
338 """
339     txt += """
340 PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s",tablesqrpsup[4],tablesqrpsup[5])
341 """ % (ffr(DictChdTxtOut['PROFILE_OUT']), ffr(DictChdTxtOut['ANTIPRO_OUT']))
342     txt += """
343 colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
344 colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
345 colnames(tablesqrpsup[[2]])<-paste('classe',1:clnb,sep=' ')
346 colnames(tablesqrpsup[[1]])<-paste('classe',1:clnb,sep=' ')
347 colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
348 colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
349 chistabletot<-rbind(tablesqrpact[2][[1]],tablesqrpsup[2][[1]])
350 chistabletot<-rbind(chistabletot,tablesqrpet[2][[1]])
351 ptabletot<-rbind(tablesqrpact[1][[1]],tablesqrpet[1][[1]])
352 """
353     txt += """
354 write.csv2(chistabletot,file="%s")
355 write.csv2(ptabletot,file="%s")
356 gbcluster<-n1
357 write.csv2(gbcluster,file="%s")
358 """ % (ffr(DictChdTxtOut['chisqtable']), ffr(DictChdTxtOut['ptable']), ffr(DictChdTxtOut['SbyClasseOut']))
359     if clnb > 2 :
360         txt += """
361     library(ca)
362     colnames(dataact)<-paste('classe',1:clnb,sep=' ')
363     colnames(datasup)<-paste('classe',1:clnb,sep=' ')
364     colnames(dataet)<-paste('classe',1:clnb,sep=' ')
365     rowtot<-nrow(dataact)+nrow(dataet)+nrow(datasup)
366     afctable<-rbind(as.matrix(dataact),as.matrix(datasup))
367     afctable<-rbind(afctable,as.matrix(dataet))
368     colnames(afctable)<-paste('classe',1:clnb,sep=' ')
369     afc<-ca(afctable,suprow=((nrow(dataact)+1):rowtot),nd=(ncol(afctable)-1))
370     debsup<-nrow(dataact)+1
371     debet<-nrow(dataact)+nrow(datasup)+1
372     fin<-rowtot
373     afc<-AddCorrelationOk(afc)
374     """
375     #FIXME : split this!!!
376         txt += """
377     source("%s")
378     """ % ffr(RscriptsPath['Rgraph'])
379     
380         txt += """
381         afc <- summary.ca.dm(afc)
382         afc_table <- create_afc_table(afc)
383         write.csv2(afc_table$facteur, file = "%s")
384         write.csv2(afc_table$colonne, file = "%s")
385         write.csv2(afc_table$ligne, file = "%s")
386         """ % (ffr(DictChdTxtOut['afc_facteur']), ffr(DictChdTxtOut['afc_col']), ffr(DictChdTxtOut['afc_row']))
387     
388         txt += """
389     PARCEX<-%s
390     """ % taillecar
391         txt += """
392     xyminmax <- PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
393     """ % (ffr(DictChdTxtOut['AFC2DL_OUT']))
394         txt += """
395     PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=debsup, fin=(debet-1), xlab = xlab, ylab = ylab, xmin = xyminmax$xminmax[1], xmax = xyminmax$xminmax[2], ymin = xyminmax$yminmax[1], ymax = xyminmax$yminmax[2], active=FALSE)
396     """ % (ffr(DictChdTxtOut['AFC2DSL_OUT']))
397         txt += """
398         if ((fin - debet) > 2) {
399     PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=debet, fin=fin, xlab = xlab, ylab = ylab, xmin = xyminmax$xminmax[1], xmax = xyminmax$xminmax[2], ymin = xyminmax$yminmax[1], ymax = xyminmax$yminmax[2], active = FALSE)
400         }
401     """ % (ffr(DictChdTxtOut['AFC2DEL_OUT']))
402         txt += """
403     PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col=TRUE, what='coord', xlab = xlab, ylab = ylab, xmin = xyminmax$xminmax[1], xmax = xyminmax$xminmax[2], ymin = xyminmax$yminmax[1], ymax = xyminmax$yminmax[2], active=FALSE)
404     """ % (ffr(DictChdTxtOut['AFC2DCL_OUT']))
405 #        txt += """
406  #   PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
407  #   PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debsup, fin=(debet-1), xlab = xlab, ylab = ylab)
408   #  PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debet, fin=fin, xlab = xlab, ylab = ylab)
409  #   PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col=TRUE, what='crl', xlab = xlab, ylab = ylab)
410  #   """ % (DictChdTxtOut['AFC2DCoul'], DictChdTxtOut['AFC2DCoulSup'], DictChdTxtOut['AFC2DCoulEt'], DictChdTxtOut['AFC2DCoulCl'])
411        
412     txt += """
413 #rm(dataact)
414 #rm(datasup)
415 #rm(dataet)
416 rm(tablesqrpact)
417 rm(tablesqrpsup)
418 rm(tablesqrpet)
419 save.image(file="%s")
420 """ % ffr(DictChdTxtOut['RData'])
421     file = open(DictChdTxtOut['RTxtProfGraph'], 'w')
422     file.write(txt)
423     file.close()
424
425
426 def write_afc_graph(self):
427     if self.param['over'] : over = 'TRUE'
428     else : over = 'FALSE'
429
430     if self.param['do_select_nb'] : do_select_nb = 'TRUE'
431     else : do_select_nb = 'FALSE'
432
433     if self.param['do_select_chi'] : do_select_chi = 'TRUE'
434     else : do_select_chi = 'FALSE'
435
436     if self.param['do_select_chi_classe'] : do_select_chi_classe = 'TRUE'
437     else : do_select_chi_classe = 'FALSE'
438
439     if self.param['cex_txt'] : cex_txt = 'TRUE'
440     else : cex_txt = 'FALSE'
441
442     if self.param['tchi'] : tchi = 'TRUE'
443     else : tchi = 'FALSE'
444
445     if self.param['svg'] : svg = 'TRUE'
446     else : svg = 'FALSE'
447
448     with open(self.RscriptsPath['afc_graph'], 'r') as f:
449         txt = f.read()
450
451 #    self.DictPathOut['RData'], \
452     scripts = txt % (ffr(self.RscriptsPath['Rgraph']),\
453     self.param['typegraph'], \
454     self.param['what'], \
455     self.param['facteur'][0],\
456     self.param['facteur'][1], \
457     self.param['facteur'][2], \
458     self.param['qui'], \
459     over,  do_select_nb, \
460     self.param['select_nb'],  \
461     do_select_chi, \
462     self.param['select_chi'], \
463     do_select_chi_classe, \
464     self.param['nbchic'], \
465     cex_txt, \
466     self.param['txt_min'], \
467     self.param['txt_max'], \
468     self.fileout, \
469     self.param['width'], \
470     self.param['height'],\
471     self.param['taillecar'], \
472     self.param['alpha'], \
473     self.param['film'], \
474     tchi,\
475     self.param['tchi_min'],\
476     self.param['tchi_max'],\
477     ffr(os.path.dirname(self.fileout)),\
478     svg)
479     return scripts
480         
481 def print_simi3d(self):
482     simi3d = self.parent.simi3dpanel
483     txt = '#Fichier genere par Iramuteq'
484     if simi3d.movie.GetValue() :
485         movie = "'" + ffr(os.path.dirname(self.DictPathOut['RData'])) + "'"
486     else :
487         movie = 'NULL'
488     
489     #if self.corpus.parametres['type'] == 'corpus' :
490     #    header = 'TRUE'
491     #else :
492     #    header = 'FALSE'
493     header = 'FALSE'
494     txt += """
495     dm<-read.csv2("%s",row.names=1,header = %s)
496     load("%s")
497     """ % (self.DictPathOut['Contout'], header, self.DictPathOut['RData'])
498     
499     txt += """
500     source("%s")
501     """ % self.parent.RscriptsPath['Rgraph']
502
503
504     txt += """
505     make.simi.afc(dm,chistabletot, lim=%i, alpha = %.2f, movie = %s)
506     """ % (simi3d.spin_1.GetValue(), float(simi3d.slider_1.GetValue())/100, movie)
507     tmpfile = tempfile.mktemp(dir=self.parent.TEMPDIR)
508     tmp = open(tmpfile,'w')
509     tmp.write(txt)
510     tmp.close()
511     return tmpfile
512
513 def dendroandbarplot(table, rownames, colnames, rgraph, tmpgraph, intxt = False, dendro=False) :
514     if not intxt :
515         txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
516     rownb = len(rownames)
517     rownames = 'c("' + '","'.join(rownames) + '")'
518     colnames = 'c("' + '","'.join(colnames) + '")'
519     if not intxt :
520         #FIXME
521         txt = """
522             di <- matrix(data=%s, nrow=%i, byrow = TRUE)
523             rownames(di)<- %s
524             colnames(di) <- %s
525         """ % (txttable, rownb, rownames, colnames)
526     else :
527         txt = intxt
528     txt += """
529         load("%s")
530         library(ape)
531         source("%s")
532         height <- (30*ncol(di)) + (15*nrow(di))
533         height <- ifelse(height <= 400, 400, height)
534         width <- 500
535         open_file_graph("%s", width=width, height=height)
536         plot.dendro.lex(tree.cut1$tree.cl, di)
537         """ % (ffr(dendro),ffr(rgraph),  ffr(tmpgraph))
538     return txt
539
540 def barplot(table, parametres, intxt = False) :
541     if not intxt :
542         txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
543     #width = 100 + (15 * len(rownames)) + (100 * len(colnames))
544     #height =  len(rownames) * 15
545     rownb = len(parametres['rownames'])
546     #if height < 400 :
547     #    height = 400
548     rownames = 'c("' + '","'.join(parametres['rownames']) + '")'
549     colnames = 'c("' + '","'.join(parametres['colnames']) + '")'
550
551     if not intxt :
552         #FIXME
553         txt = """
554             di <- matrix(data=%s, nrow=%i, byrow = TRUE)
555             toinf <- which(di == Inf)
556             tominf <- which(di == -Inf)
557             if (length(toinf)) {
558                 di[toinf] <- NA
559                 valmax <- max(di, na.rm = TRUE)
560                 if (valmax <= 0) {
561                     valmax <- 2
562                 } else {
563                     valmax <- valmax + 2
564                 }
565                 di[toinf] <- valmax
566             }
567             if (length(tominf)) {
568                 di[tominf] <- NA
569                 valmin <- min(di, na.rm = TRUE)
570                 if (valmin >=0) {
571                     valmin <- -2
572                 } else {
573                     valmin <- valmin - 2
574                 }
575                 di[tominf] <- valmin
576             }
577             rownames(di)<- %s
578             colnames(di) <- %s
579         """ % (txttable, rownb, rownames, colnames)
580     else :
581         txt = intxt
582     if not 'tree' in parametres :
583         txt += """
584             source("%s")
585             color = rainbow(nrow(di))
586             width <- %i
587             height <- %i
588             open_file_graph("%s",width = width, height = height, svg = %s)
589                 par(mar=c(0,0,0,0))
590             layout(matrix(c(1,2),1,2, byrow=TRUE),widths=c(3,lcm(7)))
591             par(mar=c(8,4,1,0))
592             yp = ifelse(length(toinf), 0.2, 0)
593             ym = ifelse(length(tominf), 0.2, 0)
594             ymin <- ifelse(!length(which(di < 0)), 0, min(di) - ym)
595             coord <- barplot(as.matrix(di), beside = TRUE, col = color, space = c(0.1,0.6), ylim=c(ymin, max(di) + yp), las = 2)
596             if (length(toinf)) {
597                 coordinf <- coord[toinf]
598                 valinf <- di[toinf]
599                 text(x=coordinf, y=valinf + 0.1, 'i')
600             }
601             if (length(tominf)) {
602                 coordinf <- coord[toinf]
603                 valinf <- di[toinf]
604                 text(x=coordinf, y=valinf - 0.1, 'i')
605             }            
606             c <- colMeans(coord)
607             c1 <- c[-1]
608             c2 <- c[-length(c)]
609             cc <- cbind(c1,c2)
610             lcoord <- apply(cc, 1, mean)
611             abline(v=lcoord)
612             if (min(di) < 0) {
613                 amp <- abs(max(di) - min(di))
614             } else {
615                 amp <- max(di)
616             }
617             if (amp < 10) {
618                 d <- 2
619             } else {
620                 d <- signif(amp%%/%%10,1)
621             }
622             mn <- round(min(di))
623             mx <- round(max(di))
624             for (i in mn:mx) {
625                 if ((i/d) == (i%%/%%d)) { 
626                     abline(h=i,lty=3)
627                 }
628             }
629             par(mar=c(0,0,0,0))
630             plot(0, axes = FALSE, pch = '')
631             legend(x = 'center' , rownames(di), fill = color)
632             dev.off()
633             """ % (ffr(parametres['rgraph']), parametres['width'], parametres['height'], ffr(parametres['tmpgraph']), parametres['svg'])    
634     else :
635         txt += """
636         load("%s")
637         library(ape)
638         source("%s")
639         width = %i
640         height = %i
641         open_file_graph("%s", width=width, height=height, svg = %s)
642         plot.dendro.lex(tree.cut1$tree.cl, di)
643         """ % (ffr(parametres['tree']), ffr(parametres['rgraph']), parametres['width'], parametres['height'], ffr(parametres['tmpgraph']), parametres['svg'])
644     return txt
645
646 #def RAfcUci(DictAfcUciOut, nd=2, RscriptsPath='', PARCEX='0.8'):
647 #    txt = """
648 #    library(ca)
649 #    nd<-%i
650 #    """ % nd
651 #    txt += """
652 #    dataact<-read.csv2("%s")
653 #    """ % (DictAfcUciOut['TableCont'])#, encoding)
654 #    txt += """
655 #    datasup<-read.csv2("%s")
656 #    """ % (DictAfcUciOut['TableSup'])#, encoding)
657 #    txt += """
658 #    dataet<-read.csv2("%s")
659 #    """ % (DictAfcUciOut['TableEt'])#, encoding)
660 #    txt += """
661 #    datatotsup<-cbind(dataact,datasup)
662 #    datatotet<-cbind(dataact,dataet)
663 #    afcact<-ca(dataact,nd=nd)
664 #    afcsup<-ca(datatotsup,supcol=((ncol(dataact)+1):ncol(datatotsup)),nd=nd)
665 #    afcet<-ca(datatotet,supcol=((ncol(dataact)+1):ncol(datatotet)),nd=nd)
666 #    afctot<-afcsup$colcoord
667 #    rownames(afctot)<-afcsup$colnames
668 #    colnames(afctot)<-paste('coord. facteur',1:nd,sep=' ')
669 #    afctot<-cbind(afctot,mass=afcsup$colmass)
670 #    afctot<-cbind(afctot,distance=afcsup$coldist)
671 #    afctot<-cbind(afctot,intertie=afcsup$colinertia)
672 #    rcolet<-afcet$colsup
673 #    afctmp<-afcet$colcoord[rcolet,]
674 #    rownames(afctmp)<-afcet$colnames[rcolet]
675 #    afctmp<-cbind(afctmp,afcet$colmass[rcolet])
676 #    afctmp<-cbind(afctmp,afcet$coldist[rcolet])
677 #    afctmp<-cbind(afctmp,afcet$colinertia[rcolet])
678 #    afctot<-rbind(afctot,afctmp)
679 #    write.csv2(afctot,file = "%s")
680 #    source("%s")
681 #    """ % (DictAfcUciOut['afc_row'], RscriptsPath['Rgraph'])
682 #    txt += """
683 #    PARCEX=%s
684 #    """ % PARCEX
685 #    #FIXME
686 #    txt += """
687 #    PlotAfc(afcet,filename="%s",toplot=c%s, PARCEX=PARCEX)
688 #    """ % (DictAfcUciOut['AfcColAct'], "('none','active')")
689 #    txt += """
690 #    PlotAfc(afcsup,filename="%s",toplot=c%s, PARCEX=PARCEX)
691 #    """ % (DictAfcUciOut['AfcColSup'], "('none','passive')")
692 #    txt += """PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
693 #    """ % (DictAfcUciOut['AfcColEt'], "('none','passive')")
694 #    txt += """
695 #    PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
696 #    """ % (DictAfcUciOut['AfcRow'], "('all','none')")
697 #    f = open(DictAfcUciOut['Rafcuci'], 'w')
698 #    f.write(txt)
699 #    f.close()
700
701 class PrintSimiScript(PrintRScript) :
702     def make_script(self) :
703         self.txtgraph = ''
704         self.packages(['igraph', 'proxy', 'Matrix'])
705         self.sources([self.analyse.parent.RscriptsPath['simi'], self.analyse.parent.RscriptsPath['Rgraph']])
706         txt = ''
707         if not self.parametres['keep_coord'] and not self.parametres['type'] == 'simimatrix':
708             txt += """
709             dm.path <- "%s"
710             cn.path <- "%s"
711             selected.col <- "%s"
712             """ % (ffr(self.pathout['mat01.csv']), ffr(self.pathout['actives.csv']), ffr(self.pathout['selected.csv']))
713             if 'word' in self.parametres :
714                 txt += """
715                 word <- TRUE
716                 index <- %i + 1
717                 """ % self.parametres['word']
718             else :
719                 txt += """
720                 word <- FALSE
721                 """
722             txt += """
723             dm <-readMM(dm.path)
724             cn <- read.table(cn.path, sep='\t', quote='"')
725             colnames(dm) <- cn[,1]
726             if (file.exists(selected.col)) {
727                 sel.col <- read.csv2(selected.col, header = FALSE)
728                 sel.col <- sel.col[,1] + 1
729             } else {
730                 sel.col <- 1:ncol(dm)
731             }
732             if (!word) {
733                 dm <- dm[, sel.col]
734             } else {
735                 forme <- colnames(dm)[index]
736                 if (!index %in% sel.col) {
737                     sel.col <- append(sel.col, index)
738                 }
739                 dm <- dm[, sel.col]
740                 index <- which(colnames(dm) == forme)
741             }
742             """
743         elif not self.parametres['keep_coord'] and self.parametres['type'] == 'simimatrix' :
744             txt += """
745             dm.path <- "%s"
746             selected.col <- "%s"
747             """ % (ffr(self.pathout['mat01.csv']), ffr(self.pathout['selected.csv']))
748             if 'word' in self.parametres :
749                 txt += """
750                 word <- TRUE
751                 index <- %i + 1
752                 """ % self.parametres['word']
753             else :
754                 txt += """
755                 word <- FALSE
756                 """
757             txt += """
758             dm <-read.csv2(dm.path)
759             dm <- as.matrix(dm)
760             if (file.exists(selected.col)) {
761                 sel.col <- read.csv2(selected.col, header = FALSE)
762                 sel.col <- sel.col[,1] + 1
763             } else {
764                 sel.col <- 1:ncol(dm)
765             }
766             if (!word) {
767                 dm <- dm[, sel.col]
768             } else {
769                 forme <- colnames(dm)[index]
770                 if (!index %in% sel.col) {
771                     sel.col <- append(sel.col, index)
772                 }
773                 dm <- dm[, sel.col]
774                 index <- which(colnames(dm) == forme)
775             }
776             """
777         else :
778             txt += """
779             load("%s")
780             """ % ffr(self.pathout['RData.RData'])
781         
782         if self.parametres['coeff'] == 0 :
783             method = 'cooc'
784             if not self.parametres['keep_coord'] :
785                 txt += """
786                 method <- 'cooc'
787                 mat <- make.a(dm)
788                 """
789         else :
790             if not self.parametres['keep_coord'] :
791                 txt += """
792                 dm <- as.matrix(dm)
793                 """
794         if self.parametres['coeff'] == 1 :
795             method = 'prcooc'
796             txt += """
797             method <- 'Russel'
798             mat <- simil(dm, method = 'Russel', diag = TRUE, upper = TRUE, by_rows = FALSE)
799             """
800         elif self.analyse.indices[self.parametres['coeff']] == 'binomial' :
801             method = 'binomial'
802             if not self.parametres['keep_coord'] :
803                 txt += """
804                 method <- 'binomial'
805                 mat <- binom.sim(dm)
806                 """
807         elif self.parametres['coeff'] != 0 :
808             method = self.analyse.indices[self.parametres['coeff']]
809             if not self.parametres['keep_coord'] :
810                 txt += """
811                 method <-"%s"
812                 mat <- simil(dm, method = method, diag = TRUE, upper = TRUE, by_rows = FALSE)
813                 """ % self.analyse.indices[self.parametres['coeff']]
814         if not self.parametres['keep_coord'] :
815             txt += """
816             mat <- as.matrix(stats::as.dist(mat,diag=TRUE,upper=TRUE))
817             mat[is.na(mat)] <- 0
818             if (length(which(mat == Inf))) {
819                 infp <- which(mat == Inf)
820                 mat[infp] <- NA
821                 maxmat <- max(mat, na.rm = TRUE)
822                 if (maxmat > 0) {
823                 maxmat <- maxmat + 1
824                 } else {
825                     maxmat <- 0
826                 }
827                 mat[infp] <- maxmat
828             }
829             if (length(which(mat == -Inf))) {
830                 infm <- which(mat == -Inf)
831                 mat[infm] <- NA
832                 minmat <- min(mat, na.rm = TRUE)
833                 if (maxmat < 0) {
834                 minmat <- minmat - 1
835                 } else {
836                     minmat <- 0
837                 }
838                 mat[infm] <- minmat
839             }
840             """
841         if 'word' in self.parametres and not self.parametres['keep_coord'] :
842             txt += """
843             mat <- graph.word(mat, index)
844             cs <- colSums(mat)
845             if (length(cs)) mat <- mat[,-which(cs==0)]
846             rs <- rowSums(mat)
847             if (length(rs)) mat <- mat[-which(rs==0),]
848             if (length(cs)) dm <- dm[, -which(cs==0)]
849             """
850
851         if self.parametres['layout'] == 0 : layout = 'random'
852         if self.parametres['layout'] == 1 : layout = 'circle'
853         if self.parametres['layout'] == 2 : layout = 'frutch'
854         if self.parametres['layout'] == 3 : layout = 'kawa'
855         if self.parametres['layout'] == 4 : layout = 'graphopt'
856
857
858         self.filename=''
859         if self.parametres['type_graph'] == 0 : type = 'tkplot'
860         if self.parametres['type_graph'] == 1 : 
861             graphnb = 1
862             type = 'nplot'
863             dirout = os.path.dirname(self.pathout['mat01.csv'])
864             while os.path.exists(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png')):
865                 graphnb +=1
866             self.filename = ffr(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png'))
867         if self.parametres['type_graph'] == 2 : type = 'rgl'
868         if self.parametres['type_graph'] == 3 : 
869             graphnb = 1
870             type = 'web'
871             dirout = os.path.dirname(self.pathout['mat01.csv'])
872             while os.path.exists(os.path.join(dirout,'web_'+str(graphnb))):
873                 graphnb +=1
874             self.filename = ffr(os.path.join(dirout,'web_'+str(graphnb)))
875             os.mkdir(self.filename)        
876             self.filename = os.path.join(self.filename, 'gexf.gexf')
877         if self.parametres['type_graph'] == 4 : 
878             graphnb = 1
879             type = 'rglweb'
880             dirout = os.path.dirname(self.pathout['mat01.csv'])
881             while os.path.exists(os.path.join(dirout,'webrgl_'+str(graphnb))):
882                 graphnb +=1
883             self.filename = ffr(os.path.join(dirout,'webrgl_'+str(graphnb)))
884             os.mkdir(self.filename)
885
886         if self.parametres['arbremax'] : 
887             arbremax = 'TRUE'
888             self.txtgraph += ' - arbre maximum'
889         else : arbremax = 'FALSE'
890         
891         if self.parametres['coeff_tv'] : 
892             coeff_tv = self.parametres['coeff_tv_nb']
893             tvminmax = 'c(NULL,NULL)'
894         elif not self.parametres['coeff_tv'] or self.parametres.get('sformchi', False) :
895             coeff_tv = 'NULL'
896             tvminmax = 'c(%i, %i)' %(self.parametres['tvmin'], self.parametres['tvmax'])
897         if self.parametres['coeff_te'] : coeff_te = 'c(%i,%i)' % (self.parametres['coeff_temin'], self.parametres['coeff_temax'])
898         else : coeff_te = 'NULL'
899         
900         if self.parametres['vcex'] or self.parametres.get('cexfromchi', False) :
901             vcexminmax = 'c(%i/10,%i/10)' % (self.parametres['vcexmin'],self.parametres['vcexmax'])
902         else :
903             vcexminmax = 'c(NULL,NULL)'
904         if not self.parametres['label_v'] : label_v = 'FALSE'
905         else : label_v = 'TRUE'
906
907         if not self.parametres['label_e'] : label_e = 'FALSE'
908         else : label_e = 'TRUE'
909         
910         if self.parametres['seuil_ok'] : seuil = str(self.parametres['seuil'])
911         else : seuil = 'NULL'
912             
913         cols = str(self.parametres['cols']).replace(')',', max=255)')
914         cola = str(self.parametres['cola']).replace(')',',max=255)')
915
916         txt += """
917         minmaxeff <- %s
918         """ % tvminmax
919         txt += """
920         vcexminmax <- %s
921         """ % vcexminmax
922         txt += """
923         cex = %i/10
924         """ % self.parametres['cex']
925
926         if self.parametres['film'] : 
927             txt += """
928             film <- "%s"
929             """ % self.pathout['film']
930         else : 
931             txt += """
932             film <- NULL
933             """
934         txt += """
935         seuil <- %s
936         if (!is.null(seuil)) {
937             if (method!='cooc') {
938                 seuil <- seuil/100
939             } 
940         }
941         """ % seuil
942         
943         txt += """
944         label.v <- %s
945         label.e <- %s
946         """ % (label_v, label_e)
947         txt += """
948         cols <- rgb%s
949         cola <- rgb%s
950         """ % (cols, cola)
951         txt += """
952         width <- %i
953         height <- %i
954         """ % (self.parametres['width'], self.parametres['height'])
955         if self.parametres['keep_coord'] :
956             txt += """
957             coords <- try(coords, TRUE)
958             if (!is.matrix(coords)) {
959                 coords<-NULL
960             }
961             """
962         else :
963             txt += """
964             coords <- NULL
965             """
966         txt += """
967         alpha <- %i/100
968         """ % self.parametres['alpha']
969         txt += """
970         alpha <- %i/100
971         """ % self.parametres['alpha']
972 #############################################
973         if  self.parametres.get('bystar',False) :
974             txt += """
975             et <- list()
976             """
977             for i, line in enumerate(self.parametres['listet']) :
978                 txt+= """
979                 et[[%i]] <- c(%s)
980                 """ % (i+1, ','.join([`val + 1` for val in line]))
981             txt+= """
982             unetoile <- c('%s')
983             """ % ("','".join([val for val in self.parametres['selectedstars']]))
984             txt += """
985             fsum <- NULL
986             rs <- rowSums(dm)
987             for (i in 1:length(unetoile)) {
988                 print(unetoile[i])
989                 tosum <- et[[i]]
990                 if (length(tosum) > 1) {
991                     fsum <- cbind(fsum, colSums(dm[tosum,]))
992                 } else {
993                     fsum <- cbind(fsum, dm[tosum,])
994                 }
995             }
996             source("%s")
997             lex <- AsLexico2(fsum, chip=TRUE)
998             dcol <- apply(lex[[4]],1,which.max)
999             toblack <- apply(lex[[4]],1,max)
1000             gcol <- rainbow(length(unetoile))
1001             #gcol[2] <- 'orange'
1002             vertex.label.color <- gcol[dcol]
1003             vertex.label.color[which(toblack <= 3.84)] <- 'black'
1004             leg <- list(unetoile=unetoile, gcol=gcol)  
1005             cols <- vertex.label.color
1006             chivertex.size <- norm.vec(toblack, vcexminmax[1],  vcexminmax[2])
1007             
1008             """ % (ffr(self.analyse.parent.RscriptsPath['chdfunct']))
1009         else :
1010             txt += """
1011             vertex.label.color <- 'black' 
1012             chivertex.size <- 1
1013             leg<-NULL
1014             """
1015 #############################################        
1016
1017 #        txt += """
1018 #        eff <- colSums(dm)
1019 #        g.ori <- graph.adjacency(mat, mode='lower', weighted = TRUE)
1020 #        w.ori <- E(g.ori)$weight
1021 #        if (max.tree) {
1022 #            if (method == 'cooc') {
1023 #                E(g.ori)$weight <- 1 / w.ori
1024 #            } else {
1025 #                E(g.ori)$weigth <- 1 - w.ori
1026 #            }
1027 #            g.max <- minimum.spanning.tree(g.ori)
1028 #            if (method == 'cooc') {
1029 #                E(g.max)$weight <- 1 / E(g.max)$weight
1030 #            } else {
1031 #                E(g.max)$weight <- 1 - E(g.max)$weight
1032 #            }
1033 #            g.toplot <- g.max
1034 #        } else {
1035 #            g.toplot <- g.ori
1036 #        }
1037 #        """
1038         if self.parametres['com'] :
1039             com = `self.parametres['communities']`
1040         else :
1041             com = 'NULL'
1042         if self.parametres['halo'] :
1043             halo = 'TRUE'
1044         else :
1045             halo = 'FALSE'
1046         txt += """
1047         communities <- %s
1048         halo <- %s
1049         """ % (com, halo)
1050         txt += """
1051         eff <- colSums(dm)
1052         x <- list(mat = mat, eff = eff)
1053         graph.simi <- do.simi(x, method='%s', seuil = seuil, p.type = '%s', layout.type = '%s', max.tree = %s, coeff.vertex=%s, coeff.edge = %s, minmaxeff = minmaxeff, vcexminmax = vcexminmax, cex = cex, coords = coords, communities = communities, halo = halo)
1054         """ % (method, type, layout, arbremax, coeff_tv, coeff_te)
1055             
1056         if self.parametres.get('bystar',False) :
1057             if self.parametres.get('cexfromchi', False) :
1058                 txt+="""
1059                     label.cex<-chivertex.size
1060                     """
1061             else :
1062                 txt+="""
1063                 label.cex <- cex
1064                 """
1065             if self.parametres.get('sfromchi', False) :
1066                 txt += """
1067                 vertex.size <- norm.vec(toblack, minmaxeff[1], minmaxeff[2])
1068                 """
1069             else :
1070                 txt += """
1071                 vertex.size <- NULL
1072                 """
1073         else :
1074             #print self.parametres
1075             if (self.parametres['type'] == 'clustersimitxt' and self.parametres.get('tmpchi', False)) or (self.parametres['type'] == 'simimatrix' and 'tmpchi' in self.parametres): 
1076                 txt += """
1077                 lchi <- read.table("%s")
1078                 lchi <- lchi[,1]
1079                 """ % ffr(self.parametres['tmpchi'])
1080                 txt += """
1081                     lchi <- lchi[sel.col]
1082                     """
1083             if self.parametres['type'] == 'clustersimitxt' and self.parametres.get('cexfromchi', False) :
1084                 txt += """ 
1085                 label.cex <- norm.vec(lchi, vcexminmax[1], vcexminmax[2])
1086                 """
1087             else :
1088                 txt += """
1089             if (is.null(vcexminmax[1])) {
1090                 label.cex <- cex
1091             } else {
1092                 label.cex <- graph.simi$label.cex
1093             }
1094             """
1095             if (self.parametres['type'] == 'clustersimitxt' or self.parametres['type'] == 'simimatrix') and self.parametres.get('sfromchi', False):
1096                 txt += """ 
1097                 vertex.size <- norm.vec(lchi, minmaxeff[1], minmaxeff[2])
1098                 if (!length(vertex.size)) vertex.size <- 0
1099                 """
1100             else :
1101                 txt += """
1102             if (is.null(minmaxeff[1])) {
1103                 vertex.size <- 0
1104             } else {
1105                 vertex.size <- graph.simi$eff
1106             }
1107             """
1108         #txt += """ vertex.size <- NULL """
1109         if self.parametres['svg'] : svg = 'TRUE'
1110         else : svg = 'FALSE'
1111         txt += """
1112         svg <- %s
1113         """ % svg
1114         txt += """
1115         vertex.col <- cols
1116         if (!is.null(graph.simi$com)) {
1117             com <- graph.simi$com
1118             colm <- rainbow(length(com))
1119             if (vertex.size != 0 || graph.simi$halo) {
1120                 vertex.label.color <- 'black'
1121                 vertex.col <- colm[membership(com)]
1122             } else {
1123                 vertex.label.color <- colm[membership(com)]
1124             }
1125         }
1126         coords <- plot.simi(graph.simi, p.type='%s',filename="%s", vertex.label = label.v, edge.label = label.e, vertex.col = vertex.col, vertex.label.color = vertex.label.color, vertex.label.cex=label.cex, vertex.size = vertex.size, edge.col = cola, leg=leg, width = width, height = height, alpha = alpha, movie = film, svg = svg)
1127         save.image(file="%s")
1128         """ % (type, self.filename, ffr(self.pathout['RData']))
1129         
1130         self.add(txt)
1131         self.write()
1132
1133 class WordCloudRScript(PrintRScript) :
1134     def make_script(self) :
1135         self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1136         self.packages(['wordcloud'])
1137         bg_col = Rcolor(self.parametres['col_bg'])
1138         txt_col = Rcolor(self.parametres['col_text'])
1139         if self.parametres['svg'] :
1140             svg = 'TRUE'
1141         else :
1142             svg = 'FALSE'
1143         txt = """
1144         svg <- %s
1145         """ % svg
1146         txt += """
1147         act <- read.csv2("%s", header = FALSE, row.names=1, sep='\t')
1148         selected.col <- read.table("%s")
1149         toprint <- as.matrix(act[selected.col[,1] + 1,])
1150         rownames(toprint) <- rownames(act)[selected.col[,1] + 1]
1151         maxword <- %i
1152         if (nrow(toprint) > maxword) {
1153             toprint <- as.matrix(toprint[order(toprint[,1], decreasing=TRUE),])
1154             toprint <- as.matrix(toprint[1:maxword,])
1155         }
1156         open_file_graph("%s", width = %i, height = %i , svg = svg)
1157         par(bg=rgb%s)
1158         wordcloud(row.names(toprint), toprint[,1], scale=c(%f,%f), random.order=FALSE, colors=rgb%s)
1159         dev.off()
1160         """ % (ffr(self.analyse.pathout['actives_eff.csv']), ffr(self.analyse.pathout['selected.csv']), self.parametres['maxword'], ffr(self.parametres['graphout']), self.parametres['width'], self.parametres['height'], bg_col, self.parametres['maxcex'], self.parametres['mincex'], txt_col)
1161         self.add(txt)
1162         self.write()
1163
1164 class ProtoScript(PrintRScript) :
1165     def make_script(self) :
1166         self.sources([self.analyse.parent.RscriptsPath['Rgraph'], self.analyse.parent.RscriptsPath['prototypical.R']])
1167         self.packages(['wordcloud'])
1168         if self.parametres.get('cloud', False) :
1169             cloud = 'TRUE'
1170         else :
1171             cloud = 'FALSE'
1172         txt = """
1173         errorn <- function(x) {
1174             qnorm(0.975)*sd(x)/sqrt(lenght(n))
1175         }
1176         errort <- function(x) {
1177             qt(0.975,df=lenght(x)-1)*sd(x)/sqrt(lenght(x))
1178         }
1179         mat <- read.csv2("%s", header = FALSE, row.names=1, sep='\t', quote='"', dec='.')
1180         open_file_graph("%s",height=800, width=1000)
1181         prototypical(mat, mfreq = %s, mrank = %s, cloud = FALSE, cexrange=c(1,2.4), cexalpha= c(0.4, 1), type = '%s')
1182         dev.off()
1183         """ % (self.analyse.pathout['table.csv'], self.analyse.pathout['proto.png'], self.parametres['limfreq'], self.parametres['limrang'], self.parametres['typegraph'])
1184         self.add(txt)
1185         self.write()
1186
1187
1188 class ExportAfc(PrintRScript) :
1189     def make_script(self) :
1190         self.source([self.analyse.parent.RscriptsPath['Rgraph']])
1191         self.packages(['rgexf'])
1192         txt = """
1193         """
1194
1195 class TgenSpecScript(PrintRScript):
1196     def make_script(self):
1197         self.packages(['textometry'])
1198         txt = """
1199         tgen <- read.csv2("%s", row.names = 1, sep = '\\t')
1200         """ % ffr(self.parametres['tgeneff'])
1201         txt += """
1202         tot <- tgen[nrow(tgen), ]
1203         result <- NULL
1204         tgen <- tgen[-nrow(tgen),]
1205         for (i in 1:nrow(tgen)) {
1206             mat <- rbind(tgen[i,], tot - tgen[i,])
1207             specmat <- specificities(mat)
1208             result <- rbind(result, specmat[1,])
1209         }
1210         colnames(result) <- colnames(tgen)
1211         row.names(result) <- rownames(tgen)
1212         write.table(result, file = "%s", sep='\\t', col.names = NA)
1213         """ % self.pathout['tgenspec.csv']
1214         self.add(txt)
1215