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