MacOS Big Sur and R > 4 under windows
[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, parametres = None):
17         log.info('Rscript')
18         self.pathout = analyse.pathout
19         self.analyse = analyse
20         if parametres is None :
21             self.parametres = analyse.parametres
22         else :
23             self.parametres = parametres
24         #self.scriptout = ffr(self.pathout['lastRscript.R'])
25         self.scriptout = self.pathout['temp']
26         self.script =  u"#Script genere par IRaMuTeQ - %s\n" % datetime.now().ctime()
27
28     def add(self, txt) :
29         self.script = '\n'.join([self.script, txt])
30
31     def defvar(self, name, value) :
32         self.add(' <- '.join([name, value]))
33
34     def defvars(self, lvars) :
35         for val in lvars :
36             self.defvar(val[0],val[1])
37
38     def sources(self, lsources) :
39         for source in lsources :
40             self.add('source("%s", encoding = \'utf8\')' % ffr(source))
41
42     def packages(self, lpks) :
43         for pk in lpks :
44             self.add('library(%s)' % pk)
45
46     def load(self, l) :
47         for val in l :
48             self.add('load("%s")' % ffr(val))
49
50     def write(self) :
51         with open(self.scriptout, 'w') as f :
52             f.write(self.script)
53
54
55 class chdtxt(PrintRScript) :
56     pass
57
58 def Rcolor(color) :
59     return str(color).replace(')', ', max=255)')
60
61 class Alceste2(PrintRScript) :
62     def doscript(self) :
63         self.sources(['chdfunct'])
64         self.load(['Rdata'])
65         lvars = [['clnb', `self.analyse.clnb`], 
66                 ['Contout', '"%s"' % self.pathout['Contout']],
67                 ['ContSupOut', '"%s"' % self.pathout['ContSupOut']],
68                 ['ContEtOut', '"%s"' % self.pathout['ContEtOut']],
69                 ['profileout', '"%s"' % self.pathout['profils.csv']],
70                 ['antiout', '"%s"' % self.pathout['antiprofils.csv']],
71                 ['chisqtable', '"%s"' % self.pathout['chisqtable.csv']],
72                 ['ptable', '"%s"' % self.pathout['ptable.csv']]]
73        
74         self.defvars(lvars) 
75
76
77
78 #    txt = "clnb<-%i\n" % clnb
79 #    txt += """
80 #source("%s")
81 #load("%s")
82 #""" % (RscriptsPath['chdfunct'], DictChdTxtOut['RData'])
83 #    txt += """
84 #dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
85 #datasup<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
86 #dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
87 #""" % (DictChdTxtOut['Contout'], DictChdTxtOut['ContSupOut'], DictChdTxtOut['ContEtOut'])
88 #    txt += """
89 #tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
90 #tablesqrpsup<-BuildProf(as.matrix(datasup),n1,clnb)
91 #tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
92 #"""
93 #    txt += """
94 #PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s",tablesqrpsup[4],tablesqrpsup[5])
95 #""" % (DictChdTxtOut['PROFILE_OUT'], DictChdTxtOut['ANTIPRO_OUT'])
96 #    txt += """
97 #colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
98 #colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
99 #colnames(tablesqrpsup[[2]])<-paste('classe',1:clnb,sep=' ')
100 #colnames(tablesqrpsup[[1]])<-paste('classe',1:clnb,sep=' ')
101 #colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
102 #colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
103 #chistabletot<-rbind(tablesqrpact[2][[1]],tablesqrpsup[2][[1]])
104 #chistabletot<-rbind(chistabletot,tablesqrpet[2][[1]])
105 #ptabletot<-rbind(tablesqrpact[1][[1]],tablesqrpet[1][[1]])
106 #"""
107 #    txt += """
108 #write.csv2(chistabletot,file="%s")
109 #write.csv2(ptabletot,file="%s")
110 #gbcluster<-n1
111 #write.csv2(gbcluster,file="%s")
112 #""" % (DictChdTxtOut['chisqtable'], DictChdTxtOut['ptable'], DictChdTxtOut['SbyClasseOut'])
113 #
114
115
116 def RchdTxt(DicoPath, RscriptPath, mincl, classif_mode, nbt = 9, svdmethod = 'svdR', libsvdc = False, libsvdc_path = None, R_max_mem = False, mode_patate = False, nbproc=1):
117     txt = """
118     source("%s")
119     source("%s")
120     source("%s")
121     source("%s")
122     """ % (ffr(RscriptPath['CHD']), ffr(RscriptPath['chdtxt']), ffr(RscriptPath['anacor']), ffr(RscriptPath['Rgraph']))
123     if R_max_mem :
124         txt += """
125     memory.limit(%i)
126         """ % R_max_mem
127
128     txt += """
129     nbt <- %i
130     """ % nbt
131     if svdmethod == 'svdlibc' and libsvdc :
132         txt += """
133         svd.method <- 'svdlibc'
134         libsvdc.path <- "%s"
135         """ % ffr(libsvdc_path)
136     elif svdmethod == 'irlba' :
137         txt += """
138         library(irlba)
139         svd.method <- 'irlba'
140         libsvdc.path <- NULL
141         """
142     else :
143         txt += """
144         svd.method = 'svdR'
145         libsvdc.path <- NULL
146         """
147     if mode_patate :
148         txt += """
149         mode.patate = TRUE
150         """
151     else :
152         txt += """
153         mode.patate = FALSE
154         """
155     txt +="""
156     library(Matrix)
157     data1 <- readMM("%s")
158     data1 <- as(data1, "dgCMatrix")
159     row.names(data1) <- 1:nrow(data1)
160     """ % ffr(DicoPath['TableUc1'])
161
162     if classif_mode == 0:
163         txt += """
164         data2 <- readMM("%s")
165         data2 <- as(data2, "dgCMatrix")
166         row.names(data2) <- 1:nrow(data2)
167         """ % ffr(DicoPath['TableUc2'])
168     txt += """
169     log1 <- "%s"
170     #print('FIXME : source newCHD')
171     #source('/home/pierre/workspace/iramuteq/Rscripts/newCHD.R')
172     #nbproc <- %s
173     #chd1<-CHD(data1, x = nbt, mode.patate = mode.patate, svd.method = svd.method, libsvdc.path = libsvdc.path, find='matrix', select.next='size', sample=20, amp=500, proc.nb=nbproc)
174     chd1<-CHD(data1, x = nbt, mode.patate = mode.patate, svd.method = svd.method, libsvdc.path = libsvdc.path)#, log.file = log1)
175     """ % (ffr(DicoPath['log-chd1.txt']), nbproc)
176
177     if classif_mode == 0:
178         txt += """
179     log2 <- "%s"
180     chd2<-CHD(data2, x = nbt, mode.patate = mode.patate, svd.method =
181     svd.method, libsvdc.path = libsvdc.path)#, log.file = log2)
182     """ % ffr(DicoPath['log-chd2.txt'])
183
184     txt += """
185     #lecture des uce
186     listuce1<-read.csv2("%s")
187     """ % ffr(DicoPath['listeuce1'])
188
189     if classif_mode == 0:
190         txt += """
191         listuce2<-read.csv2("%s")
192         """ % ffr(DicoPath['listeuce2'])
193
194     txt += """
195     rm(data1)
196     """
197
198     if classif_mode == 0:
199         txt += """
200         rm(data2)
201         """
202     txt += """
203     classif_mode <- %i
204     mincl <- %i
205     if (mincl == 0) {mincl <- round(nrow(chd1$n1)/(nbt+1))}
206     uceout <- "%s"
207     write.csv2(chd1$n1, file="%s")
208     if (classif_mode == 0) {
209         chd.result <- Rchdtxt(uceout, chd1, chd2 = chd2, mincl = mincl,classif_mode = classif_mode, nbt = nbt)
210         classeuce1 <- chd.result$cuce1
211         tree.tot1 <- make_tree_tot(chd1)
212         tree.cut1 <- make_dendro_cut_tuple(tree.tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
213
214     } else {
215         #chd.result <- Rchdtxt(uceout, chd1, chd2 = chd1, mincl = mincl,classif_mode = classif_mode, nbt = nbt)
216         tree.tot1 <- make_tree_tot(chd1)
217         terminales <- find.terminales(chd1$n1, chd1$list_mere, chd1$list_fille, mincl)
218         tree.cut1 <- make.classes(terminales, chd1$n1, tree.tot1$tree.cl, chd1$list_fille)
219         write.csv2(tree.cut1$n1, uceout)
220         chd.result <- tree.cut1
221     }
222     classes<-chd.result$n1[,ncol(chd.result$n1)]
223     write.csv2(chd.result$n1, file="%s")
224     """ % (classif_mode, mincl, ffr(DicoPath['uce']), ffr(DicoPath['n1-1.csv']), ffr(DicoPath['n1.csv']))
225
226     txt += """
227 #    tree.tot1 <- make_tree_tot(chd1)
228 #    open_file_graph("%s", widt = 600, height=400)
229 #    plot(tree.tot1$tree.cl)
230 #    dev.off()
231     """ % ffr(DicoPath['arbre1'])
232
233     if classif_mode == 0:
234         txt += """
235         classeuce2 <- chd.result$cuce2
236         tree.tot2 <- make_tree_tot(chd2)
237 #        open_file_graph("%s", width = 600, height=400)
238 #        plot(tree.tot2$tree.cl)
239 #        dev.off()
240         """ % ffr(DicoPath['arbre2'] )
241
242     txt += """
243         save(tree.cut1, file="%s")
244
245     open_file_graph("%s", width = 600, height=400)
246     plot.dendropr(tree.cut1$tree.cl,classes, histo=TRUE)
247     open_file_graph("%s", width = 600, height=400)
248     plot(tree.cut1$dendro_tot_cl)
249     dev.off()
250     """ % (ffr(DicoPath['Rdendro']), ffr(DicoPath['dendro1']), ffr(DicoPath['arbre1']))
251
252     if classif_mode == 0:
253         txt += """
254         tree.cut2 <- make_dendro_cut_tuple(tree.tot2$dendro_tuple, chd.result$coord_ok, classeuce2, 2, nbt)
255         open_file_graph("%s", width = 600, height=400)
256         plot(tree.cut2$tree.cl)
257         dev.off()
258         open_file_graph("%s", width = 600, height=400)
259         plot(tree.cut2$dendro_tot_cl)
260         dev.off()
261         """ % (ffr(DicoPath['dendro2']), ffr(DicoPath['arbre2']))
262
263     txt += """
264
265     #save.image(file="%s")
266     """ % (ffr(DicoPath['RData']))
267
268     fileout = open(DicoPath['Rchdtxt'], 'w')
269     fileout.write(txt)
270     fileout.close()
271
272 def RPamTxt(corpus, RscriptPath):
273     DicoPath = corpus.pathout
274     param = corpus.parametres
275     txt = """
276     source("%s")
277     """ % (RscriptPath['pamtxt'])
278     txt += """
279     source("%s")
280     """ % (RscriptPath['Rgraph'])
281     txt += """
282     result <- pamtxt("%s", "%s", "%s", method = "%s", clust_type = "%s", clnb = %i)
283     n1 <- result$uce
284     """ % (DicoPath['TableUc1'], DicoPath['listeuce1'], DicoPath['uce'], param['method'], param['cluster_type'], param['nbcl'] )
285     txt += """
286     open_file_graph("%s", width=400, height=400)
287     plot(result$cl)
288     dev.off()
289     """ % (DicoPath['arbre1'])
290     txt += """
291     save.image(file="%s")
292     """ % DicoPath['RData']
293     fileout = open(DicoPath['Rchdtxt'], 'w')
294     fileout.write(txt)
295     fileout.close()
296     
297
298 def RchdQuest(DicoPath, RscriptPath, nbcl = 10, mincl = 10):
299     txt = """
300     source("%s")
301     source("%s")
302     source("%s")
303     source("%s")
304     """ % (ffr(RscriptPath['CHD']), ffr(RscriptPath['chdquest']), ffr(RscriptPath['anacor']),ffr(RscriptPath['Rgraph']))
305
306     txt += """
307     nbt <- %i - 1
308     mincl <- %i
309     """ % (nbcl, mincl)
310
311     txt += """
312     chd.result<-Rchdquest("%s","%s","%s", nbt = nbt, mincl = mincl)
313     n1 <- chd.result$n1
314     classeuce1 <- chd.result$cuce1
315     """ % (ffr(DicoPath['mat01.csv']), ffr(DicoPath['listeuce1']), ffr(DicoPath['uce']))
316     
317     txt += """
318     tree_tot1 <- make_tree_tot(chd.result$chd)
319     open_file_graph("%s", width = 600, height=400)
320     plot(tree_tot1$tree.cl)
321     dev.off()
322     """ % ffr(DicoPath['arbre1'])
323     
324     txt += """
325     tree_cut1 <- make_dendro_cut_tuple(tree_tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
326     tree.cut1 <- tree_cut1
327     save(tree.cut1, file="%s")
328     open_file_graph("%s", width = 600, height=400)
329     classes<-n1[,ncol(n1)]
330     plot.dendropr(tree_cut1$tree.cl,classes, histo = TRUE)
331     """ % (ffr(DicoPath['Rdendro']), ffr(DicoPath['dendro1']))
332     
333     txt += """
334     save.image(file="%s")
335     """ % ffr(DicoPath['RData'])
336     fileout = open(DicoPath['Rchdquest'], 'w')
337     fileout.write(txt)
338     fileout.close()
339     
340 def ReinertTxtProf(DictChdTxtOut, RscriptsPath, clnb, taillecar):
341     txt = "clnb<-%i\n" % clnb
342     txt += """
343 source("%s")
344 #load("%s")
345 n1 <- read.csv2("%s")
346 """ % (ffr(RscriptsPath['chdfunct']), ffr(DictChdTxtOut['RData']), ffr(DictChdTxtOut['n1.csv']))
347     txt += """
348 dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
349 datasup<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
350 dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
351 """ % (ffr(DictChdTxtOut['Contout']), ffr(DictChdTxtOut['ContSupOut']), ffr(DictChdTxtOut['ContEtOut']))
352     txt += """
353 print('ATTENTION NEW BUILD PROF')
354 #tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
355 #tablesqrpsup<-BuildProf(as.matrix(datasup),n1,clnb)
356 #tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
357 tablesqrpact<-new.build.prof(as.matrix(dataact),n1,clnb)
358 tablesqrpsup<-new.build.prof(as.matrix(datasup),n1,clnb)
359 tablesqrpet<-new.build.prof(as.matrix(dataet),n1,clnb)
360
361 """
362     txt += """
363 PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s",tablesqrpsup[4],tablesqrpsup[5])
364 """ % (ffr(DictChdTxtOut['PROFILE_OUT']), ffr(DictChdTxtOut['ANTIPRO_OUT']))
365     txt += """
366 colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
367 colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
368 colnames(tablesqrpsup[[2]])<-paste('classe',1:clnb,sep=' ')
369 colnames(tablesqrpsup[[1]])<-paste('classe',1:clnb,sep=' ')
370 colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
371 colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
372 chistabletot<-rbind(tablesqrpact[2][[1]],tablesqrpsup[2][[1]])
373 chistabletot<-rbind(chistabletot,tablesqrpet[2][[1]])
374 ptabletot<-rbind(tablesqrpact[1][[1]],tablesqrpet[1][[1]])
375 """
376     txt += """
377 write.csv2(chistabletot,file="%s")
378 write.csv2(ptabletot,file="%s")
379 gbcluster<-n1
380 write.csv2(gbcluster,file="%s")
381 """ % (ffr(DictChdTxtOut['chisqtable']), ffr(DictChdTxtOut['ptable']), ffr(DictChdTxtOut['SbyClasseOut']))
382     if clnb > 2 :
383         txt += """
384     library(ca)
385     colnames(dataact)<-paste('classe',1:clnb,sep=' ')
386     colnames(datasup)<-paste('classe',1:clnb,sep=' ')
387     colnames(dataet)<-paste('classe',1:clnb,sep=' ')
388     rowtot<-nrow(dataact)+nrow(dataet)+nrow(datasup)
389     afctable<-rbind(as.matrix(dataact),as.matrix(datasup))
390     afctable<-rbind(afctable,as.matrix(dataet))
391     colnames(afctable)<-paste('classe',1:clnb,sep=' ')
392     afc<-ca(afctable,suprow=((nrow(dataact)+1):rowtot),nd=(ncol(afctable)-1))
393     debsup<-nrow(dataact)+1
394     debet<-nrow(dataact)+nrow(datasup)+1
395     fin<-rowtot
396     afc<-AddCorrelationOk(afc)
397     """
398     #FIXME : split this!!!
399         txt += """
400     source("%s")
401     """ % ffr(RscriptsPath['Rgraph'])
402     
403         txt += """
404         afc <- summary.ca.dm(afc)
405         afc_table <- create_afc_table(afc)
406         write.csv2(afc_table$facteur, file = "%s")
407         write.csv2(afc_table$colonne, file = "%s")
408         write.csv2(afc_table$ligne, file = "%s")
409         """ % (ffr(DictChdTxtOut['afc_facteur']), ffr(DictChdTxtOut['afc_col']), ffr(DictChdTxtOut['afc_row']))
410     
411         txt += """
412     PARCEX<-%s
413     """ % taillecar
414         txt += """
415     xyminmax <- PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
416     """ % (ffr(DictChdTxtOut['AFC2DL_OUT']))
417         txt += """
418     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)
419     """ % (ffr(DictChdTxtOut['AFC2DSL_OUT']))
420         txt += """
421         if ((fin - debet) > 2) {
422     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)
423         }
424     """ % (ffr(DictChdTxtOut['AFC2DEL_OUT']))
425         txt += """
426     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)
427     """ % (ffr(DictChdTxtOut['AFC2DCL_OUT']))
428 #        txt += """
429  #   PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
430  #   PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debsup, fin=(debet-1), xlab = xlab, ylab = ylab)
431   #  PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debet, fin=fin, xlab = xlab, ylab = ylab)
432  #   PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col=TRUE, what='crl', xlab = xlab, ylab = ylab)
433  #   """ % (DictChdTxtOut['AFC2DCoul'], DictChdTxtOut['AFC2DCoulSup'], DictChdTxtOut['AFC2DCoulEt'], DictChdTxtOut['AFC2DCoulCl'])
434        
435     txt += """
436 #rm(dataact)
437 #rm(datasup)
438 #rm(dataet)
439 rm(tablesqrpact)
440 rm(tablesqrpsup)
441 rm(tablesqrpet)
442 save.image(file="%s")
443 """ % ffr(DictChdTxtOut['RData'])
444     file = open(DictChdTxtOut['RTxtProfGraph'], 'w')
445     file.write(txt)
446     file.close()
447
448
449 def write_afc_graph(self):
450     if self.param['over'] : over = 'TRUE'
451     else : over = 'FALSE'
452
453     if self.param['do_select_nb'] : do_select_nb = 'TRUE'
454     else : do_select_nb = 'FALSE'
455
456     if self.param['do_select_chi'] : do_select_chi = 'TRUE'
457     else : do_select_chi = 'FALSE'
458
459     if self.param['do_select_chi_classe'] : do_select_chi_classe = 'TRUE'
460     else : do_select_chi_classe = 'FALSE'
461
462     if self.param['cex_txt'] : cex_txt = 'TRUE'
463     else : cex_txt = 'FALSE'
464
465     if self.param['tchi'] : tchi = 'TRUE'
466     else : tchi = 'FALSE'
467
468     if self.param['svg'] : svg = 'TRUE'
469     else : svg = 'FALSE'
470
471     if self.param['typegraph'] == 4 :
472         nodesfile = os.path.join(os.path.dirname(self.fileout),'nodes.csv')
473         edgesfile = os.path.join(os.path.dirname(self.fileout),'edges.csv')
474     else :
475         nodesfile = 'NULL'
476         edgesfile = 'NULL'
477
478     with open(self.RscriptsPath['afc_graph'], 'r') as f:
479         txt = f.read()
480
481 #    self.DictPathOut['RData'], \
482     scripts = txt % (ffr(self.RscriptsPath['Rgraph']),\
483     self.param['typegraph'], \
484     edgesfile, nodesfile, \
485     self.param['what'], \
486     self.param['facteur'][0],\
487     self.param['facteur'][1], \
488     self.param['facteur'][2], \
489     self.param['qui'], \
490     over,  do_select_nb, \
491     self.param['select_nb'],  \
492     do_select_chi, \
493     self.param['select_chi'], \
494     do_select_chi_classe, \
495     self.param['nbchic'], \
496     cex_txt, \
497     self.param['txt_min'], \
498     self.param['txt_max'], \
499     self.fileout, \
500     self.param['width'], \
501     self.param['height'],\
502     self.param['taillecar'], \
503     self.param['alpha'], \
504     self.param['film'], \
505     tchi,\
506     self.param['tchi_min'],\
507     self.param['tchi_max'],\
508     ffr(os.path.dirname(self.fileout)),\
509     svg)
510     return scripts
511         
512 def print_simi3d(self):
513     simi3d = self.parent.simi3dpanel
514     txt = '#Fichier genere par Iramuteq'
515     if simi3d.movie.GetValue() :
516         movie = "'" + ffr(os.path.dirname(self.DictPathOut['RData'])) + "'"
517     else :
518         movie = 'NULL'
519     
520     #if self.corpus.parametres['type'] == 'corpus' :
521     #    header = 'TRUE'
522     #else :
523     #    header = 'FALSE'
524     header = 'FALSE'
525     txt += """
526     dm<-read.csv2("%s",row.names=1,header = %s)
527     load("%s")
528     """ % (self.DictPathOut['Contout'], header, self.DictPathOut['RData'])
529     
530     txt += """
531     source("%s")
532     """ % self.parent.RscriptsPath['Rgraph']
533
534
535     txt += """
536     make.simi.afc(dm,chistabletot, lim=%i, alpha = %.2f, movie = %s)
537     """ % (simi3d.spin_1.GetValue(), float(simi3d.slider_1.GetValue())/100, movie)
538     tmpfile = tempfile.mktemp(dir=self.parent.TEMPDIR)
539     tmp = open(tmpfile,'w')
540     tmp.write(txt)
541     tmp.close()
542     return tmpfile
543
544 def dendroandbarplot(table, rownames, colnames, rgraph, tmpgraph, intxt = False, dendro=False) :
545     if not intxt :
546         txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
547     rownb = len(rownames)
548     rownames = 'c("' + '","'.join(rownames) + '")'
549     colnames = 'c("' + '","'.join(colnames) + '")'
550     if not intxt :
551         #FIXME
552         txt = """
553             di <- matrix(data=%s, nrow=%i, byrow = TRUE)
554             rownames(di)<- %s
555             colnames(di) <- %s
556         """ % (txttable, rownb, rownames, colnames)
557     else :
558         txt = intxt
559     txt += """
560         load("%s")
561         library(ape)
562         source("%s")
563         height <- (30*ncol(di)) + (15*nrow(di))
564         height <- ifelse(height <= 400, 400, height)
565         width <- 500
566         open_file_graph("%s", width=width, height=height)
567         plot.dendro.lex(tree.cut1$tree.cl, di)
568         """ % (ffr(dendro),ffr(rgraph),  ffr(tmpgraph))
569     return txt
570
571 def barplot(table, parametres, intxt = False) :
572     if not intxt :
573         txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
574     #width = 100 + (15 * len(rownames)) + (100 * len(colnames))
575     #height =  len(rownames) * 15
576     rownb = len(parametres['rownames'])
577     #if height < 400 :
578     #    height = 400
579     rownames = 'c("' + '","'.join(parametres['rownames']) + '")'
580     colnames = 'c("' + '","'.join(parametres['colnames']) + '")'
581
582     if not intxt :
583         #FIXME
584         txt = """
585             di <- matrix(data=%s, nrow=%i, byrow = TRUE)
586             toinf <- which(di == Inf)
587             tominf <- which(di == -Inf)
588             if (length(toinf)) {
589                 di[toinf] <- NA
590                 valmax <- max(di, na.rm = TRUE)
591                 if (valmax <= 0) {
592                     valmax <- 2
593                 } else {
594                     valmax <- valmax + 2
595                 }
596                 di[toinf] <- valmax
597             }
598             if (length(tominf)) {
599                 di[tominf] <- NA
600                 valmin <- min(di, na.rm = TRUE)
601                 if (valmin >=0) {
602                     valmin <- -2
603                 } else {
604                     valmin <- valmin - 2
605                 }
606                 di[tominf] <- valmin
607             }
608             rownames(di)<- %s
609             colnames(di) <- %s
610         """ % (txttable, rownb, rownames, colnames)
611     else :
612         txt = intxt
613     if not 'tree' in parametres :
614         txt += """
615             source("%s")
616             color = rainbow(nrow(di))
617             width <- %i
618             height <- %i
619             open_file_graph("%s",width = width, height = height, svg = %s)
620                 par(mar=c(0,0,0,0))
621             layout(matrix(c(1,2),1,2, byrow=TRUE),widths=c(3,lcm(12)))
622             par(mar=c(8,4,1,0))
623             yp = ifelse(length(toinf), 0.2, 0)
624             ym = ifelse(length(tominf), 0.2, 0)
625             ymin <- ifelse(!length(which(di < 0)), 0, min(di) - ym)
626             coord <- barplot(as.matrix(di), beside = TRUE, col = color, space = c(0.1,0.6), ylim=c(ymin, max(di) + yp), las = 2)
627             if (length(toinf)) {
628                 coordinf <- coord[toinf]
629                 valinf <- di[toinf]
630                 text(x=coordinf, y=valinf + 0.1, 'i')
631             }
632             if (length(tominf)) {
633                 coordinf <- coord[toinf]
634                 valinf <- di[toinf]
635                 text(x=coordinf, y=valinf - 0.1, 'i')
636             }            
637             c <- colMeans(coord)
638             c1 <- c[-1]
639             c2 <- c[-length(c)]
640             cc <- cbind(c1,c2)
641             lcoord <- apply(cc, 1, mean)
642             abline(v=lcoord)
643             if (min(di) < 0) {
644                 amp <- abs(max(di) - min(di))
645             } else {
646                 amp <- max(di)
647             }
648             if (amp < 10) {
649                 d <- 2
650             } else {
651                 d <- signif(amp%%/%%10,1)
652             }
653             mn <- round(min(di))
654             mx <- round(max(di))
655             for (i in mn:mx) {
656                 if ((i/d) == (i%%/%%d)) { 
657                     abline(h=i,lty=3)
658                 }
659             }
660             par(mar=c(0,0,0,0))
661             plot(0, axes = FALSE, pch = '')
662             legend(x = 'center' , rownames(di), fill = color)
663             dev.off()
664             """ % (ffr(parametres['rgraph']), parametres['width'], parametres['height'], ffr(parametres['tmpgraph']), parametres['svg'])    
665     else :
666         txt += """
667         load("%s")
668         library(ape)
669         source("%s")
670         width = %i
671         height = %i
672         open_file_graph("%s", width=width, height=height, svg = %s)
673         plot.dendro.lex(tree.cut1$tree.cl, di)
674         """ % (ffr(parametres['tree']), ffr(parametres['rgraph']), parametres['width'], parametres['height'], ffr(parametres['tmpgraph']), parametres['svg'])
675     return txt
676
677 #def RAfcUci(DictAfcUciOut, nd=2, RscriptsPath='', PARCEX='0.8'):
678 #    txt = """
679 #    library(ca)
680 #    nd<-%i
681 #    """ % nd
682 #    txt += """
683 #    dataact<-read.csv2("%s")
684 #    """ % (DictAfcUciOut['TableCont'])#, encoding)
685 #    txt += """
686 #    datasup<-read.csv2("%s")
687 #    """ % (DictAfcUciOut['TableSup'])#, encoding)
688 #    txt += """
689 #    dataet<-read.csv2("%s")
690 #    """ % (DictAfcUciOut['TableEt'])#, encoding)
691 #    txt += """
692 #    datatotsup<-cbind(dataact,datasup)
693 #    datatotet<-cbind(dataact,dataet)
694 #    afcact<-ca(dataact,nd=nd)
695 #    afcsup<-ca(datatotsup,supcol=((ncol(dataact)+1):ncol(datatotsup)),nd=nd)
696 #    afcet<-ca(datatotet,supcol=((ncol(dataact)+1):ncol(datatotet)),nd=nd)
697 #    afctot<-afcsup$colcoord
698 #    rownames(afctot)<-afcsup$colnames
699 #    colnames(afctot)<-paste('coord. facteur',1:nd,sep=' ')
700 #    afctot<-cbind(afctot,mass=afcsup$colmass)
701 #    afctot<-cbind(afctot,distance=afcsup$coldist)
702 #    afctot<-cbind(afctot,intertie=afcsup$colinertia)
703 #    rcolet<-afcet$colsup
704 #    afctmp<-afcet$colcoord[rcolet,]
705 #    rownames(afctmp)<-afcet$colnames[rcolet]
706 #    afctmp<-cbind(afctmp,afcet$colmass[rcolet])
707 #    afctmp<-cbind(afctmp,afcet$coldist[rcolet])
708 #    afctmp<-cbind(afctmp,afcet$colinertia[rcolet])
709 #    afctot<-rbind(afctot,afctmp)
710 #    write.csv2(afctot,file = "%s")
711 #    source("%s")
712 #    """ % (DictAfcUciOut['afc_row'], RscriptsPath['Rgraph'])
713 #    txt += """
714 #    PARCEX=%s
715 #    """ % PARCEX
716 #    #FIXME
717 #    txt += """
718 #    PlotAfc(afcet,filename="%s",toplot=c%s, PARCEX=PARCEX)
719 #    """ % (DictAfcUciOut['AfcColAct'], "('none','active')")
720 #    txt += """
721 #    PlotAfc(afcsup,filename="%s",toplot=c%s, PARCEX=PARCEX)
722 #    """ % (DictAfcUciOut['AfcColSup'], "('none','passive')")
723 #    txt += """PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
724 #    """ % (DictAfcUciOut['AfcColEt'], "('none','passive')")
725 #    txt += """
726 #    PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
727 #    """ % (DictAfcUciOut['AfcRow'], "('all','none')")
728 #    f = open(DictAfcUciOut['Rafcuci'], 'w')
729 #    f.write(txt)
730 #    f.close()
731
732 class PrintSimiScript(PrintRScript) :
733     def make_script(self) :
734         self.txtgraph = ''
735         self.packages(['igraph', 'proxy', 'Matrix'])
736         self.sources([self.analyse.parent.RscriptsPath['simi'], self.analyse.parent.RscriptsPath['Rgraph']])
737         txt = ''
738         if not self.parametres['keep_coord'] and not (self.parametres['type'] == 'simimatrix' or self.parametres['type'] == 'simiclustermatrix') :
739             txt += """
740             dm.path <- "%s"
741             cn.path <- "%s"
742             selected.col <- "%s"
743             """ % (ffr(self.pathout['mat01.csv']), ffr(self.pathout['actives.csv']), ffr(self.pathout['selected.csv']))
744             if 'word' in self.parametres :
745                 txt += """
746                 word <- TRUE
747                 index <- %i + 1
748                 """ % self.parametres['word']
749             else :
750                 txt += """
751                 word <- FALSE
752                 index <- NULL
753                 """
754             txt += """
755             dm <-readMM(dm.path)
756             cn <- read.table(cn.path, sep="\t", quote='"')
757             colnames(dm) <- cn[,1]
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         elif not self.parametres['keep_coord'] and (self.parametres['type'] == 'simimatrix' or self.parametres['type'] == 'simiclustermatrix'):
776             txt += """
777             dm.path <- "%s"
778             selected.col <- "%s"
779             """ % (ffr(self.pathout['mat01.csv']), ffr(self.pathout['selected.csv']))
780             if 'word' in self.parametres :
781                 txt += """
782                 word <- TRUE
783                 index <- %i + 1
784                 """ % self.parametres['word']
785             else :
786                 txt += """
787                 word <- FALSE
788                 """
789             txt += """
790             dm <-read.csv2(dm.path)
791             dm <- as.matrix(dm)
792             if (file.exists(selected.col)) {
793                 sel.col <- read.csv2(selected.col, header = FALSE)
794                 sel.col <- sel.col[,1] + 1
795             } else {
796                 sel.col <- 1:ncol(dm)
797             }
798             if (!word) {
799                 dm <- dm[, sel.col]
800             } else {
801                 forme <- colnames(dm)[index]
802                 if (!index %in% sel.col) {
803                     sel.col <- append(sel.col, index)
804                 }
805                 dm <- dm[, sel.col]
806                 index <- which(colnames(dm) == forme)
807             }
808             """
809         else :
810             txt += """
811             load("%s")
812             """ % ffr(self.pathout['RData.RData'])
813
814         if self.parametres['coeff'] == 0 :
815             method = 'cooc'
816             if not self.parametres['keep_coord'] :
817                 txt += """
818                 method <- 'cooc'
819                 mat <- make.a(dm)
820                 """
821         elif self.analyse.indices[self.parametres['coeff']] == 'Jaccard' :
822             method = 'Jaccard'
823             if not self.parametres['keep_coord'] :
824                 txt += """
825                 method <- 'Jaccard'
826                 mat <- sparse.jaccard(dm)
827                 """
828         else :
829             if not self.parametres['keep_coord'] :
830                 txt += """
831                 dm <- as.matrix(dm)
832                 """
833         if self.parametres['coeff'] == 1 :
834             method = 'prcooc'
835             txt += """
836             method <- 'Russel'
837             mat <- simil(dm, method = 'Russel', diag = TRUE, upper = TRUE, by_rows = FALSE)
838             """
839         elif self.analyse.indices[self.parametres['coeff']] == 'binomial' :
840             method = 'binomial'
841             if not self.parametres['keep_coord'] :
842                 txt += """
843                 method <- 'binomial'
844                 mat <- binom.sim(dm)
845                 """
846         elif self.parametres['coeff'] != 0 and self.analyse.indices[self.parametres['coeff']] != 'Jaccard':
847             method = self.analyse.indices[self.parametres['coeff']]
848             if not self.parametres['keep_coord'] :
849                 txt += """
850                 method <-"%s"
851                 mat <- simil(dm, method = method, diag = TRUE, upper = TRUE, by_rows = FALSE)
852                 """ % self.analyse.indices[self.parametres['coeff']]
853         if not self.parametres['keep_coord'] :
854             txt += """
855             mat <- as.matrix(stats::as.dist(mat,diag=TRUE,upper=TRUE))
856             mat[is.na(mat)] <- 0
857             if (length(which(mat == Inf))) {
858                 infp <- which(mat == Inf)
859                 mat[infp] <- NA
860                 maxmat <- max(mat, na.rm = TRUE)
861                 if (maxmat > 0) {
862                 maxmat <- maxmat + 1
863                 } else {
864                     maxmat <- 0
865                 }
866                 mat[infp] <- maxmat
867             }
868             if (length(which(mat == -Inf))) {
869                 infm <- which(mat == -Inf)
870                 mat[infm] <- NA
871                 minmat <- min(mat, na.rm = TRUE)
872                 if (maxmat < 0) {
873                 minmat <- minmat - 1
874                 } else {
875                     minmat <- 0
876                 }
877                 mat[infm] <- minmat
878             }
879             """
880         if 'word' in self.parametres and not self.parametres['keep_coord'] :
881             txt += """
882             mat <- graph.word(mat, index)
883             cs <- colSums(mat)
884             if (length(which(cs==0))) mat <- mat[,-which(cs==0)]
885             rs <- rowSums(mat)
886             if (length(which(rs==0))) mat <- mat[-which(rs==0),]
887             if (length(which(cs==0))) dm <- dm[,-which(cs==0)]
888             if (word) {
889                 index <- which(colnames(mat)==forme)
890             }
891             """
892
893         if self.parametres['layout'] == 0 : layout = 'random'
894         if self.parametres['layout'] == 1 : layout = 'circle'
895         if self.parametres['layout'] == 2 : layout = 'frutch'
896         if self.parametres['layout'] == 3 : layout = 'kawa'
897         if self.parametres['layout'] == 4 : layout = 'graphopt'
898         if self.parametres['layout'] == 5 : layout = 'spirale'
899         if self.parametres['layout'] == 6 : layout = 'spirale3D'
900
901
902         self.filename=''
903         if self.parametres['type_graph'] == 0 : type = 'tkplot'
904         if self.parametres['type_graph'] == 1 : 
905             graphnb = 1
906             type = 'nplot'
907             dirout = os.path.dirname(self.pathout['mat01.csv'])
908             while os.path.exists(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png')):
909                 graphnb +=1
910             self.filename = ffr(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png'))
911         if self.parametres['type_graph'] == 2 : type = 'rgl'
912         if self.parametres['type_graph'] == 3 : 
913             graphnb = 1
914             type = 'web'
915             dirout = os.path.dirname(self.pathout['mat01.csv'])
916             while os.path.exists(os.path.join(dirout,'web_'+str(graphnb))):
917                 graphnb +=1
918             self.filename = ffr(os.path.join(dirout,'web_'+str(graphnb)))
919             os.mkdir(self.filename)
920             self.filename = os.path.join(self.filename, 'gexf.gexf')
921         if self.parametres['type_graph'] == 4 : 
922             graphnb = 1
923             type = 'rglweb'
924             dirout = os.path.dirname(self.pathout['mat01.csv'])
925             while os.path.exists(os.path.join(dirout,'webrgl_'+str(graphnb))):
926                 graphnb +=1
927             self.filename = ffr(os.path.join(dirout,'webrgl_'+str(graphnb)))
928             os.mkdir(self.filename)
929
930         if self.parametres['arbremax'] : 
931             arbremax = 'TRUE'
932             self.txtgraph += ' - arbre maximum'
933         else : arbremax = 'FALSE'
934         
935         if self.parametres['coeff_tv'] : 
936             coeff_tv = self.parametres['coeff_tv_nb']
937             tvminmax = 'c(NULL,NULL)'
938         elif not self.parametres['coeff_tv'] or self.parametres.get('sformchi', False) :
939             coeff_tv = 'NULL'
940             tvminmax = 'c(%i, %i)' %(self.parametres['tvmin'], self.parametres['tvmax'])
941         if self.parametres['coeff_te'] : coeff_te = 'c(%i,%i)' % (self.parametres['coeff_temin'], self.parametres['coeff_temax'])
942         else : coeff_te = 'NULL'
943         
944         if self.parametres['vcex'] or self.parametres.get('cexfromchi', False) :
945             vcexminmax = 'c(%i/10,%i/10)' % (self.parametres['vcexmin'],self.parametres['vcexmax'])
946         else :
947             vcexminmax = 'c(NULL,NULL)'
948         if not self.parametres['label_v'] : label_v = 'FALSE'
949         else : label_v = 'TRUE'
950
951         if not self.parametres['label_e'] : label_e = 'FALSE'
952         else : label_e = 'TRUE'
953         
954         if self.parametres['seuil_ok'] : seuil = str(self.parametres['seuil'])
955         else : seuil = 'NULL'
956         
957         if not self.parametres.get('edgecurved', False) :
958             ec = 'FALSE'
959         else :
960             ec = 'TRUE'
961         
962         txt += """
963         edge.curved <- %s
964         """ % ec
965         
966         cols = str(self.parametres['cols']).replace(')',', max=255)')
967         cola = str(self.parametres['cola']).replace(')',',max=255)')
968
969         txt += """
970         minmaxeff <- %s
971         """ % tvminmax
972         txt += """
973         vcexminmax <- %s
974         """ % vcexminmax
975         txt += """
976         cex = %i/10
977         """ % self.parametres['cex']
978
979         if self.parametres['film'] : 
980             txt += """
981             film <- "%s"
982             """ % ffr(self.pathout['film'])
983         else : 
984             txt += """
985             film <- NULL
986             """
987         txt += """
988         seuil <- %s
989         if (!is.null(seuil)) {
990             if (method!='cooc') {
991                 seuil <- seuil/1000
992             } 
993         }
994         """ % seuil
995         
996         txt += """
997         label.v <- %s
998         label.e <- %s
999         """ % (label_v, label_e)
1000         txt += """
1001         cols <- rgb%s
1002         cola <- rgb%s
1003         """ % (cols, cola)
1004         txt += """
1005         width <- %i
1006         height <- %i
1007         """ % (self.parametres['width'], self.parametres['height'])
1008         if self.parametres['keep_coord'] :
1009             txt += """
1010             coords <- try(coords, TRUE)
1011             if (!is.matrix(coords)) {
1012                 coords<-NULL
1013             }
1014             """
1015         else :
1016             txt += """
1017             coords <- NULL
1018             """
1019         txt += """
1020         alpha <- %i/100
1021         """ % self.parametres['alpha']
1022         txt += """
1023         alpha <- %i/100
1024         """ % self.parametres['alpha']
1025 #############################################
1026         if  self.parametres.get('bystar',False) :
1027             txt += """
1028             et <- list()
1029             """
1030             for i, line in enumerate(self.parametres['listet']) :
1031                 txt+= """
1032                 et[[%i]] <- c(%s)
1033                 """ % (i+1, ','.join([`val + 1` for val in line]))
1034             txt+= """
1035             unetoile <- c('%s')
1036             """ % ("','".join([val for val in self.parametres['selectedstars']]))
1037             txt += """
1038             fsum <- NULL
1039             rs <- rowSums(dm)
1040             for (i in 1:length(unetoile)) {
1041                 print(unetoile[i])
1042                 tosum <- et[[i]]
1043                 if (length(tosum) > 1) {
1044                     fsum <- cbind(fsum, colSums(dm[tosum,]))
1045                 } else {
1046                     fsum <- cbind(fsum, dm[tosum,])
1047                 }
1048             }
1049             source("%s")
1050             lex <- AsLexico2(fsum, chip=TRUE)
1051             dcol <- apply(lex[[4]],1,which.max)
1052             toblack <- apply(lex[[4]],1,max)
1053             gcol <- rainbow(length(unetoile))
1054             #gcol[2] <- 'orange'
1055             vertex.label.color <- gcol[dcol]
1056             vertex.label.color[which(toblack <= 3.84)] <- 'black'
1057             leg <- list(unetoile=unetoile, gcol=gcol)  
1058             cols <- vertex.label.color
1059             chivertex.size <- norm.vec(toblack, vcexminmax[1],  vcexminmax[2])
1060             
1061             """ % (ffr(self.analyse.parent.RscriptsPath['chdfunct']))
1062         else :
1063             txt += """
1064             vertex.label.color <- 'black' 
1065             chivertex.size <- 1
1066             leg<-NULL
1067             """
1068 #############################################        
1069
1070 #        txt += """
1071 #        eff <- colSums(dm)
1072 #        g.ori <- graph.adjacency(mat, mode='lower', weighted = TRUE)
1073 #        w.ori <- E(g.ori)$weight
1074 #        if (max.tree) {
1075 #            if (method == 'cooc') {
1076 #                E(g.ori)$weight <- 1 / w.ori
1077 #            } else {
1078 #                E(g.ori)$weigth <- 1 - w.ori
1079 #            }
1080 #            g.max <- minimum.spanning.tree(g.ori)
1081 #            if (method == 'cooc') {
1082 #                E(g.max)$weight <- 1 / E(g.max)$weight
1083 #            } else {
1084 #                E(g.max)$weight <- 1 - E(g.max)$weight
1085 #            }
1086 #            g.toplot <- g.max
1087 #        } else {
1088 #            g.toplot <- g.ori
1089 #        }
1090 #        """
1091         if self.parametres['com'] :
1092             com = `self.parametres['communities']`
1093         else :
1094             com = 'NULL'
1095         if self.parametres['halo'] :
1096             halo = 'TRUE'
1097         else :
1098             halo = 'FALSE'
1099         txt += """
1100         communities <- %s
1101         halo <- %s
1102         """ % (com, halo)
1103         txt += """
1104         eff <- colSums(dm)
1105         x <- list(mat = mat, eff = eff)
1106         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, index.word=index)
1107         """ % (method, type, layout, arbremax, coeff_tv, coeff_te)
1108             
1109         if self.parametres.get('bystar',False) :
1110             if self.parametres.get('cexfromchi', False) :
1111                 txt+="""
1112                     label.cex<-chivertex.size
1113                     """
1114             else :
1115                 txt+="""
1116                 label.cex <- cex
1117                 """
1118             if self.parametres.get('sfromchi', False) :
1119                 txt += """
1120                 vertex.size <- norm.vec(toblack, minmaxeff[1], minmaxeff[2])
1121                 """
1122             else :
1123                 txt += """
1124                 vertex.size <- NULL
1125                 """
1126         else :
1127             #print self.parametres
1128             if (self.parametres['type'] == 'clustersimitxt' and self.parametres.get('tmpchi', False)) or (self.parametres['type'] in ['simimatrix','simiclustermatrix'] and 'tmpchi' in self.parametres): 
1129                 txt += """
1130                 lchi <- read.table("%s")
1131                 lchi <- lchi[,1]
1132                 """ % ffr(self.parametres['tmpchi'])
1133                 txt += """
1134                     lchi <- lchi[sel.col]
1135                     """
1136             if self.parametres['type'] in ['clustersimitxt', 'simimatrix', 'simiclustermatrix'] and self.parametres.get('cexfromchi', False) :
1137                 txt += """ 
1138                 label.cex <- norm.vec(lchi, vcexminmax[1], vcexminmax[2])
1139                 """
1140             else :
1141                 txt += """
1142             if (is.null(vcexminmax[1])) {
1143                 label.cex <- cex
1144             } else {
1145                 label.cex <- graph.simi$label.cex
1146             }
1147             """
1148             if (self.parametres['type'] in ['clustersimitxt', 'simimatrix', 'simiclustermatrix']) and self.parametres.get('sfromchi', False):
1149                 txt += """ 
1150                 vertex.size <- norm.vec(lchi, minmaxeff[1], minmaxeff[2])
1151                 if (!length(vertex.size)) vertex.size <- 0
1152                 """
1153             else :
1154                 txt += """
1155             if (is.null(minmaxeff[1])) {
1156                 vertex.size <- 0
1157             } else {
1158                 vertex.size <- graph.simi$eff
1159             }
1160             """
1161         #txt += """ vertex.size <- NULL """
1162         if self.parametres['svg'] : svg = 'TRUE'
1163         else : svg = 'FALSE'
1164         txt += """
1165         svg <- %s
1166         """ % svg
1167         txt += """
1168         vertex.col <- cols
1169         col.from.proto <- F
1170         if (col.from.proto) {
1171             proto.col <- read.table('/tmp/matcol.csv')
1172             v.proto.names <- make.names(proto.col[,1])
1173             v.proto.col <- as.character(proto.col[,2])
1174             v.proto.col[which(v.proto.col=='black')] <- 'yellow'
1175             v.names <- V(graph.simi$graph)$name
1176             num.color <- sapply(v.names, function(x) {if (x %%in%% v.proto.names) {v.proto.col[which(v.proto.names==x)]} else {'pink'}})
1177             vertex.col <- num.color
1178             V(graph.simi$graph)$proto.color <- vertex.col
1179         }
1180         if (!is.null(graph.simi$com)) {
1181             com <- graph.simi$com
1182             colm <- rainbow(length(com))
1183             if (vertex.size != 0 || graph.simi$halo) {
1184                 vertex.label.color <- 'black'
1185                 vertex.col <- colm[membership(com)]
1186             } else {
1187                 vertex.label.color <- colm[membership(com)]
1188             }
1189         }
1190         if (!length(graph.simi$elim)==0) {
1191             vertex.label.color <- vertex.label.color[-graph.simi$elim]
1192             if (length(label.cex > 1)) {
1193                  label.cex <- label.cex[-graph.simi$elim]
1194             }
1195         }
1196         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)
1197         save.image(file="%s")
1198         """ % (type, self.filename, ffr(self.pathout['RData']))
1199         
1200         self.add(txt)
1201         self.write()
1202
1203 class WordCloudRScript(PrintRScript) :
1204     def make_script(self) :
1205         self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1206         self.packages(['wordcloud'])
1207         bg_col = Rcolor(self.parametres['col_bg'])
1208         txt_col = Rcolor(self.parametres['col_text'])
1209         if self.parametres['svg'] :
1210             svg = 'TRUE'
1211         else :
1212             svg = 'FALSE'
1213         txt = """
1214         svg <- %s
1215         """ % svg
1216         txt += """
1217         act <- read.csv2("%s", header = FALSE, row.names=1, sep='\t')
1218         selected.col <- read.table("%s")
1219         toprint <- as.matrix(act[selected.col[,1] + 1,])
1220         rownames(toprint) <- rownames(act)[selected.col[,1] + 1]
1221         maxword <- %i
1222         if (nrow(toprint) > maxword) {
1223             toprint <- as.matrix(toprint[order(toprint[,1], decreasing=TRUE),])
1224             toprint <- as.matrix(toprint[1:maxword,])
1225         }
1226         open_file_graph("%s", width = %i, height = %i , svg = svg)
1227         par(bg=rgb%s)
1228         wordcloud(row.names(toprint), toprint[,1], scale=c(%f,%f), random.order=FALSE, colors=rgb%s)
1229         dev.off()
1230         """ % (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)
1231         self.add(txt)
1232         self.write()
1233
1234 class ProtoScript(PrintRScript) :
1235     def make_script(self) :
1236         self.sources([self.analyse.parent.RscriptsPath['Rgraph'], self.analyse.parent.RscriptsPath['prototypical.R']])
1237         self.packages(['wordcloud'])
1238         if self.parametres.get('cloud', False) :
1239             cloud = 'TRUE'
1240         else :
1241             cloud = 'FALSE'
1242         txt = """
1243         errorn <- function(x) {
1244             qnorm(0.975)*sd(x)/sqrt(lenght(n))
1245         }
1246         errort <- function(x) {
1247             qt(0.975,df=lenght(x)-1)*sd(x)/sqrt(lenght(x))
1248         }
1249         mat <- read.csv2("%s", header = FALSE, row.names=1, sep='\t', quote='"', dec='.')
1250         open_file_graph("%s",height=800, width=1000)
1251         prototypical(mat, mfreq = %s, mrank = %s, cloud = FALSE, cexrange=c(1,2.4), cexalpha= c(0.4, 1), type = '%s', mat.col.path='/tmp/matcol.csv')
1252         dev.off()
1253         """ % (ffr(self.analyse.pathout['table.csv']), ffr(self.analyse.pathout['proto.png']), self.parametres['limfreq'], self.parametres['limrang'], self.parametres['typegraph'])
1254         self.add(txt)
1255         self.write()
1256
1257
1258 class ExportAfc(PrintRScript) :
1259     def make_script(self) :
1260         self.source([self.analyse.parent.RscriptsPath['Rgraph']])
1261         self.packages(['rgexf'])
1262         txt = """
1263         """
1264
1265 class MergeGraphes(PrintRScript) :
1266     def __init__(self, analyse):
1267         self.script = u"#Script genere par IRaMuTeQ - %s\n" % datetime.now().ctime()
1268         self.pathout = PathOut()
1269         self.parametres = analyse.parametres
1270         self.scriptout = self.pathout['temp']
1271         self.analyse = analyse 
1272
1273     def make_script(self) :
1274         #FIXME
1275
1276         txt = """
1277         library(igraph)
1278         library(Matrix)
1279         graphs <- list()
1280         """
1281         load = """
1282         load("%s")
1283         g <- graph.simi$graph
1284         V(g)$weight <- (graph.simi$mat.eff/nrow(dm))*100
1285         graphs[['%s']] <- g
1286         """
1287         for i, graph in enumerate(self.parametres['graphs']) :
1288             path = os.path.dirname(graph)
1289             gname = ''.join(['g', `i`])
1290             RData = os.path.join(path,'RData.RData')
1291             txt += load % (ffr(RData), gname)
1292         self.add(txt)
1293         self.sources([self.analyse.parent.RscriptsPath['simi']])
1294         txt = """
1295         merge.type <- 'proto'
1296         if (merge.type == 'normal') {
1297             ng <- merge.graph(graphs)
1298         } else {
1299             ng <- merge.graph.proto(graphs)
1300         }
1301         ngraph <- list(graph=ng, layout=layout.fruchterman.reingold(ng, dim=3), labex.cex=V(ng)$weight)
1302         write.graph(ng, "%s", format = 'graphml')
1303         """ % ffr(self.parametres['grapheout'])
1304         self.add(txt)
1305     
1306 class TgenSpecScript(PrintRScript):
1307     def make_script(self):
1308         self.packages(['textometry'])
1309         txt = """
1310         tgen <- read.csv2("%s", row.names = 1, sep = '\\t')
1311         """ % ffr(self.parametres['tgeneff'])
1312         txt += """
1313         tot <- tgen[nrow(tgen), ]
1314         result <- NULL
1315         tgen <- tgen[-nrow(tgen),]
1316         for (i in 1:nrow(tgen)) {
1317             mat <- rbind(tgen[i,], tot - tgen[i,])
1318             specmat <- specificities(mat)
1319             result <- rbind(result, specmat[1,])
1320         }
1321         colnames(result) <- colnames(tgen)
1322         row.names(result) <- rownames(tgen)
1323         write.table(result, file = "%s", sep='\\t', col.names = NA)
1324         """ % ffr(self.pathout['tgenspec.csv'])
1325         self.add(txt)
1326         
1327 class TgenProfScript(PrintRScript):
1328     def make_script(self):
1329         self.sources([self.analyse.ira.RscriptsPath['chdfunct']])
1330         txt = """
1331         tgen <- read.csv2("%s", row.names = 1, sep = '\\t')
1332         """ % ffr(self.parametres['tgeneff'])
1333         txt += """
1334         tgenlem <- read.csv2("%s", row.names = 1, sep = '\\t')
1335         """ % ffr(self.parametres['tgenlemeff'])
1336         txt += """
1337         res <- build.prof.tgen(tgen)
1338         write.table(res$chi2, file = "%s", sep='\\t', col.names = NA)
1339         write.table(res$pchi2, file = "%s", sep='\\t', col.names = NA)
1340         """ % (ffr(self.pathout['tgenchi2.csv']), ffr(self.pathout['tgenpchi2.csv']))
1341         txt += """
1342         reslem <- build.prof.tgen(tgenlem)
1343         write.table(reslem$chi2, file = "%s", sep='\\t', col.names = NA)
1344         write.table(reslem$pchi2, file = "%s", sep='\\t', col.names = NA)
1345         """ % (ffr(self.pathout['tgenlemchi2.csv']), ffr(self.pathout['tgenlempchi2.csv']))        
1346         self.add(txt)
1347         
1348 class FreqMultiScript(PrintRScript):
1349     def make_script(self):
1350         self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1351         txt = """
1352         freq <- read.csv2("%s", row.names=1, sep='\\t', dec='.')
1353         """ % ffr(self.pathout['frequences.csv'])
1354         txt += """
1355         toplot <- freq[order(freq[,2]) ,2]
1356         toplot.names = rownames(freq)[order(freq[,2])]
1357         h <- 80 + (20 * nrow(freq))
1358         open_file_graph("%s",height=h, width=500)
1359         par(mar=c(3,20,3,3))
1360         barplot(toplot, names = toplot.names, horiz=TRUE, las =1, col = rainbow(nrow(freq)))
1361         dev.off()
1362         """ % ffr(self.pathout['barplotfreq.png'])
1363         txt += """
1364         toplot <- freq[order(freq[,4]) ,4]
1365         toplot.names = rownames(freq)[order(freq[,4])]
1366         open_file_graph("%s",height=h, width=500)
1367         par(mar=c(3,20,3,3))
1368         barplot(toplot, names = toplot.names, horiz=TRUE, las =1, col = rainbow(nrow(freq)))
1369         dev.off()
1370         """ % ffr(self.pathout['barplotrow.png'])
1371         self.add(txt)
1372         self.write()
1373
1374 class LabbeScript(PrintRScript) :
1375     def make_script(self) :
1376         self.sources([self.analyse.parent.RscriptsPath['distance-labbe.R'],
1377                       self.analyse.parent.RscriptsPath['Rgraph']])
1378         txt = """
1379         tab <- read.csv2("%s", header=TRUE, sep=';', row.names=1)
1380         """ % (ffr(self.pathout['tableafcm.csv']))
1381         txt += """
1382         dist.mat <- dist.labbe(tab)
1383         dist.mat <- as.dist(dist.mat, upper=F, diag=F)
1384         write.table(as.matrix(dist.mat), "%s", sep='\t')
1385         library(cluster)
1386         library(ape)
1387         chd <- hclust(dist.mat, method="ward.D2")
1388         open_file_graph("%s", width=1000, height=1000, svg=F)
1389         par(cex=1.2)
1390         plot.phylo(as.phylo(chd), type='unrooted', lab4ut="axial")
1391         dev.off()
1392         """ % (ffr(self.pathout['distmat.csv']), ffr(self.pathout['labbe-tree.png']))
1393         txt +="""
1394         open_file_graph("%s", width=1000, height=1000, svg=F)
1395         par(mar=c(10,1,1,10))
1396         heatmap(as.matrix(dist.mat), symm = T, distfun=function(x) as.dist(x), margins=c(10,10))
1397         dev.off()
1398         """ % ffr(self.pathout['labbe-heatmap.png'])
1399         txt += """
1400         #http://stackoverflow.com/questions/3081066/what-techniques-exists-in-r-to-visualize-a-distance-matrix
1401         dst <- data.matrix(dist.mat)
1402         dim <- ncol(dst)
1403         rn <- row.names(as.matrix(dist.mat))
1404         open_file_graph("%s", width=1500, height=1000, svg=F)
1405         par(mar=c(10,10,3,3))
1406         image(1:dim, 1:dim, dst, axes = FALSE, xlab="", ylab="", col=heat.colors(99), breaks=seq(0.01,1,0.01))
1407         axis(1, 1:dim, rn, cex.axis = 0.9, las=3)
1408         axis(2, 1:dim, rn, cex.axis = 0.9, las=1)
1409         text(expand.grid(1:dim, 1:dim), sprintf("%%0.2f", dst), cex=0.6)
1410         dev.off()
1411         """  % ffr(self.pathout['labbe-matrix.png'])
1412         txt += """
1413         library(igraph)
1414         g <- graph.adjacency(as.matrix(1-dist.mat), mode="lower", weighted=T)
1415         write.graph(g, file="%s", format='graphml')
1416         open_file_graph("%s", width=1000, height=1000, svg=F)
1417         plot(g)
1418         dev.off()
1419         E(g)$weight <- 1 - E(g)$weight
1420         g <- minimum.spanning.tree(g)
1421         E(g)$weight <- 1 - E(g)$weight
1422         write.graph(g, file="%s", format='graphml')
1423         open_file_graph("%s", width=1000, height=1000, svg=F)
1424         plot(g)
1425         dev.off()
1426         """ % (ffr(self.pathout['graph_tot.graphml']), ffr(self.pathout['graph_tot.png']), ffr(self.pathout['graph_min.graphml']), ffr(self.pathout['graph_min.png']))
1427         self.add(txt)
1428         self.write()
1429
1430 class ChronoChi2Script(PrintRScript) :
1431     def make_script(self) :
1432         self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1433         print self.parametres
1434         txt = """
1435         inRData <- "%s"
1436         dendrof <- "%s"
1437         load(inRData)
1438         load(dendrof)
1439         """ % (ffr(self.pathout['RData.RData']), ffr(self.pathout['dendrogramme.RData']))
1440         txt += """
1441         svg <- %s
1442         """ % self.parametres['svg']
1443         txt += """
1444         tc <- which(grepl("%s",rownames(chistabletot)))
1445         rn <- rownames(chistabletot)[tc]
1446         tc <- tc[order(rn)]
1447         dpt <- chistabletot[tc,]
1448         tot <- afctable[tc,]
1449         tcp <- rowSums(tot)
1450         ptc <- tcp/sum(tcp)
1451         dpt <- t(dpt)
1452         dd <- dpt
1453         """ % self.parametres['var'].replace(u'*', u"\\\\*")
1454         txt += """
1455         classes <- n1[,ncol(n1)]
1456         tcl <- table(classes)
1457         if ('0' %in% names(tcl)) {
1458             to.vire <- which(names(tcl) == '0')
1459             tcl <- tcl[-to.vire]
1460         }
1461         tclp <- tcl/sum(tcl)
1462
1463         #chi2 colors
1464         library(ape)
1465         k <- 1e-02
1466         lcol <- NULL
1467         lk <- k
1468         for (i in 1:5) {
1469             lcol <- c(lcol, qchisq(1-k,1))
1470             k <- k/10
1471             lk <- c(lk,k)
1472         }
1473         lcol <- c(3.84, lcol)
1474         lcol <- c(-Inf,lcol)
1475         lcol <- c(lcol, Inf)
1476         lk <- c(0.05,lk)
1477         breaks <- lcol
1478         alphas <- seq(0,1, length.out=length(breaks))
1479         clod <- rev(as.numeric(tree.cut1$tree.cl$tip.label))
1480         #end
1481         """
1482         txt += """
1483         open_file_graph("%s", w=%i, h=%i, svg=svg)
1484         """ % (ffr(self.parametres['tmpgraph']), self.parametres['width'], self.parametres['height'])
1485         txt += """
1486         par(mar=c(3,3,3,3))
1487         mat.graphic <- matrix(c(rep(1,nrow(dd)),c(2:(nrow(dd)+1))), ncol=2)
1488         mat.graphic <- rbind(mat.graphic, c(max(mat.graphic) + 1 , max(mat.graphic) + 2))
1489         hauteur <- tclp[clod] * 0.9
1490         heights.graphic <- append(hauteur, 0.1)
1491         layout(mat.graphic, heights=heights.graphic, widths=c(0.15,0.85))
1492         par(mar=c(0,0,0,0))
1493         tree.toplot <- tree.cut1$tree.cl
1494         num.label <- as.numeric(tree.cut1$tree.cl$tip.label)
1495         col.tree <- rainbow(length(num.label))[num.label]
1496         #tree.toplot$tip.label <- paste('classe ', tree.toplot$tip.label)
1497         plot.phylo(tree.toplot,label.offset=0.1, cex=1.1, no.margin=T, tip.color = col.tree)
1498         for (i in clod) {
1499             print(i)
1500             par(mar=c(0,0,0,0))
1501             lcol <- cut(dd[i,], breaks, include.lowest=TRUE)
1502             ulcol <- names(table(lcol))
1503             lcol <- as.character(lcol)
1504             for (j in 1:length(ulcol)) {
1505                 lcol[which(lcol==ulcol[j])] <- j
1506             }
1507             lcol <- as.numeric(lcol)
1508             mcol <- rainbow(nrow(dd))[i]
1509             last.col <- NULL
1510             for (k in alphas) {
1511                 last.col <- c(last.col, rgb(r=col2rgb(mcol)[1]/255, g=col2rgb(mcol)[2]/255, b=col2rgb(mcol)[3]/255, a=k))
1512             }
1513             #print(last.col)
1514
1515             barplot(rep(1,ncol(dd)), width=ptc, names.arg=FALSE, axes=FALSE, col=last.col[lcol], border=rgb(r=0, g=0, b=0, a=0.3))
1516         }
1517         plot(0,type='n',axes=FALSE,ann=FALSE)
1518         label.coords <- barplot(rep(1, ncol(dd)), width=ptc, names.arg = F, las=2, axes=F, ylim=c(0,1), plot=T, col='white')
1519         text(x=label.coords, y=0.5, labels=rn[order(rn)], srt=90)
1520         dev.off()
1521         """
1522         self.add(txt)
1523         self.write()
1524
1525 class ChronoPropScript(PrintRScript) :
1526     def make_script(self) :
1527         self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1528         print self.parametres
1529         txt = """
1530         inRData <- "%s"
1531         dendrof <- "%s"
1532         load(inRData)
1533         load(dendrof)
1534         """ % (ffr(self.pathout['RData.RData']), ffr(self.pathout['dendrogramme.RData']))
1535         txt += """
1536         svg <- %s
1537         """ % self.parametres['svg']
1538         txt += """
1539         tc <- which(grepl("%s",rownames(chistabletot)))
1540         rn <- rownames(chistabletot)[tc]
1541         tc <- tc[order(rn)]
1542         dpt <- chistabletot[tc,]
1543         tot <- afctable[tc,]
1544         tcp <- rowSums(tot)
1545         ptc <- tcp/sum(tcp)
1546         dpt <- t(dpt)
1547         dd <- dpt
1548         """ % self.parametres['var'].replace(u'*', u"\\\\*")
1549         txt += """
1550         classes <- n1[,ncol(n1)]
1551         tcl <- table(classes)
1552         if ('0' %in% names(tcl)) {
1553             to.vire <- which(names(tcl) == '0')
1554             tcl <- tcl[-to.vire]
1555         }
1556         tclp <- tcl/sum(tcl)
1557         """
1558         txt += """
1559         open_file_graph("%s", w=%i, h=%i, svg=svg)
1560         """ % (ffr(self.parametres['tmpgraph']), self.parametres['width'], self.parametres['height'])
1561         txt+= """
1562         ptt <- prop.table(as.matrix(tot), 1)
1563         par(mar=c(10,2,2,2))
1564         barplot(t(ptt)[as.numeric(tree.cut1$tree.cl$tip.label),], col=rainbow(ncol(ptt))[as.numeric(tree.cut1$tree.cl$tip.label)], width=ptc, las=3, space=0.05, cex.axis=0.7, border=NA)
1565         dev.off()
1566         """
1567         self.add(txt)
1568         self.write()
1569
1570 class ChronoggScript(PrintRScript) :
1571     def make_script(self) :
1572         self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1573         print self.parametres
1574         txt = """
1575         library(ggplot2)
1576         inRData <- "%s"
1577         dendrof <- "%s"
1578         load(inRData)
1579         load(dendrof)
1580         """ % (ffr(self.pathout['RData.RData']), ffr(self.pathout['dendrogramme.RData']))
1581         txt += """
1582         svg <- %s
1583         """ % self.parametres['svg']
1584         txt += """
1585         tc <- which(grepl("%s",rownames(chistabletot)))
1586         rn <- rownames(chistabletot)[tc]
1587         tc <- tc[order(rn)]
1588         dpt <- chistabletot[tc,]
1589         tot <- afctable[tc,]
1590         tcp <- rowSums(tot)
1591         ptc <- tcp/sum(tcp)
1592         dpt <- t(dpt)
1593         dd <- dpt
1594         """ % self.parametres['var'].replace(u'*', u"\\\\*")
1595         txt += """
1596         classes <- n1[,ncol(n1)]
1597         tcl <- table(classes)
1598         if ('0' %in% names(tcl)) {
1599             to.vire <- which(names(tcl) == '0')
1600             tcl <- tcl[-to.vire]
1601         }
1602         tclp <- tcl/sum(tcl)
1603         ptt <- prop.table(as.matrix(tot), 1)
1604         ptt <- ptt[,as.numeric(tree.cut1$tree.cl$tip.label)]
1605         rownames(ptt) <- cumsum(ptc)
1606         nptt<-as.data.frame(as.table(ptt))
1607         nptt[,1]<-as.numeric(as.character(nptt[,1]))
1608         col <- rainbow(ncol(ptt))[as.numeric(tree.cut1$tree.cl$tip.label)]
1609         """
1610         txt += """
1611         open_file_graph("%s", w=%i, h=%i, svg=svg)
1612         """ % (ffr(self.parametres['tmpgraph']), self.parametres['width'], self.parametres['height'])
1613         txt+= """
1614         par(mar=c(10,2,2,2))
1615         gg <- ggplot(data=nptt, aes(x=Var1,y=Freq,fill=Var2)) + geom_area(alpha=1 , size=0.5, colour="black")
1616         gg + scale_fill_manual(values=col)
1617         dev.off()
1618         """
1619         self.add(txt)
1620         self.write()
1621
1622 class DendroScript(PrintRScript) :
1623     def make_script(self) :
1624         if self.parametres['svg'] :
1625             typefile = '.svg'
1626         else :
1627             typefile = '.png'
1628         fileout = self.parametres['fileout']
1629         width = self.parametres['width']
1630         height = self.parametres['height']
1631         type_dendro = self.parametres['dendro_type']
1632         if self.parametres['taille_classe'] :
1633             tclasse = 'TRUE'
1634         else :
1635             tclasse = 'FALSE'
1636         if self.parametres['color_nb'] == 0 :
1637             bw = 'FALSE'
1638         else :
1639             bw = 'TRUE'
1640         if self.parametres['type_tclasse'] == 0 :
1641             histo='FALSE'
1642         else :
1643             histo = 'TRUE'
1644         if self.parametres['svg'] :
1645             svg = 'TRUE'
1646         else :
1647             svg = 'FALSE'
1648         dendro_path = self.pathout['Rdendro']
1649         classe_path = self.pathout['uce']
1650         txt = """
1651         library(ape)
1652         load("%s")
1653         source("%s")
1654         classes <- read.csv2("%s", row.names=1)
1655         classes <- classes[,1]
1656         """ % (ffr(dendro_path), ffr(self.parametres['Rgraph']),  ffr(classe_path))
1657         if self.parametres['dendro'] == 'simple' :
1658             txt += """
1659             open_file_graph("%s", width=%i, height=%i, svg=%s)
1660             plot.dendropr(tree.cut1$tree.cl, classes, type.dendro="%s", histo=%s, bw=%s, lab=NULL, tclasse=%s)
1661             """ % (ffr(fileout), width, height, svg, type_dendro, histo, bw, tclasse)
1662         elif self.parametres['dendro'] == 'texte' :
1663             txt += """
1664             load("%s")
1665             source("%s")
1666             if (is.null(debsup)) {
1667                 debsup <- debet
1668             }
1669             chistable <- chistabletot[1:(debsup-1),]
1670             """ % (ffr(self.pathout['RData.RData']), ffr(self.parametres['Rgraph']))
1671             if self.parametres.get('translation', False) :
1672                 txt += """
1673                 rn <- read.csv2("%s", header=FALSE, sep='\t')
1674                 rnchis <- row.names(chistable)
1675                 commun <- intersect(rnchis, unique(rn[,2]))
1676                 idrnchis <- sapply(commun, function(x) {which(rnchis==x)})
1677                 idrn <- sapply(commun, function(x) {which(as.vector(rn[,2])==x)[1]})
1678                 rownames(chistable)[idrnchis] <- as.vector(rn[idrn,1])
1679                 """ % ffr(self.parametres['translation'])
1680             txt += """
1681             open_file_graph("%s", width=%i, height=%i, svg = %s)
1682             plot.dendro.prof(tree.cut1$tree.cl, classes, chistable, nbbycl = 60, type.dendro="%s", bw=%s, lab=NULL)
1683             """ % (ffr(fileout), width, height, svg, type_dendro, bw)
1684         elif self.parametres['dendro'] == 'cloud' :
1685             txt += """
1686             load("%s")
1687             source("%s")
1688             if (is.null(debsup)) {
1689                 debsup <- debet
1690             }
1691             chistable <- chistabletot[1:(debsup-1),]
1692             open_file_graph("%s", width=%i, height=%i, svg=%s)
1693             plot.dendro.cloud(tree.cut1$tree.cl, classes, chistable, nbbycl = 300, type.dendro="%s", bw=%s, lab=NULL)
1694             """ % (ffr(self.pathout['RData.RData']), ffr(self.parametres['Rgraph']), ffr(fileout), width, height, svg, type_dendro, bw)
1695         self.add(txt)
1696         self.write()
1697
1698
1699 class ReDoProfScript(PrintRScript) :
1700     def make_script(self) :
1701         self.sources([self.analyse.parent.RscriptsPath['chdfunct.R']])
1702         print self.parametres
1703