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