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