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