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