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