latin dictionary from Gonçalo Cordeiro and romania dictionary from Cristian Chirita
[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 = self.pathout['temp']
22         self.script =  u"#Script genere par IRaMuTeQ - %s\n" % datetime.now().ctime()
23     
24     def add(self, txt) :
25         self.script = '\n'.join([self.script, txt])
26     
27     def defvar(self, name, value) :
28         self.add(' <- '.join([name, value]))
29
30     def defvars(self, lvars) :
31         for val in lvars :
32             self.defvar(val[0],val[1])
33
34     def sources(self, lsources) :
35         for source in lsources :
36             self.add('source("%s", encoding = \'utf8\')' % ffr(source))
37
38     def packages(self, lpks) :
39         for pk in lpks :
40             self.add('library(%s)' % pk)
41
42     def load(self, l) :
43         for val in l :
44             self.add('load("%s")' % ffr(val))
45
46     def write(self) :
47         with open(self.scriptout, 'w') as f :
48             f.write(self.script)
49
50
51 class chdtxt(PrintRScript) :
52     pass
53
54 def Rcolor(color) :
55     return str(color).replace(')', ', max=255)')
56
57 class Alceste2(PrintRScript) :
58     def doscript(self) :
59         self.sources(['chdfunct'])
60         self.load(['Rdata'])
61         lvars = [['clnb', `self.analyse.clnb`], 
62                 ['Contout', '"%s"' % self.pathout['Contout']],
63                 ['ContSupOut', '"%s"' % self.pathout['ContSupOut']],
64                 ['ContEtOut', '"%s"' % self.pathout['ContEtOut']],
65                 ['profileout', '"%s"' % self.pathout['profils.csv']],
66                 ['antiout', '"%s"' % self.pathout['antiprofils.csv']],
67                 ['chisqtable', '"%s"' % self.pathout['chisqtable.csv']],
68                 ['ptable', '"%s"' % self.pathout['ptable.csv']]]
69        
70         self.defvars(lvars) 
71
72
73
74 #    txt = "clnb<-%i\n" % clnb
75 #    txt += """
76 #source("%s")
77 #load("%s")
78 #""" % (RscriptsPath['chdfunct'], DictChdTxtOut['RData'])
79 #    txt += """
80 #dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
81 #datasup<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
82 #dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
83 #""" % (DictChdTxtOut['Contout'], DictChdTxtOut['ContSupOut'], DictChdTxtOut['ContEtOut'])
84 #    txt += """
85 #tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
86 #tablesqrpsup<-BuildProf(as.matrix(datasup),n1,clnb)
87 #tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
88 #"""
89 #    txt += """
90 #PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s",tablesqrpsup[4],tablesqrpsup[5])
91 #""" % (DictChdTxtOut['PROFILE_OUT'], DictChdTxtOut['ANTIPRO_OUT'])
92 #    txt += """
93 #colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
94 #colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
95 #colnames(tablesqrpsup[[2]])<-paste('classe',1:clnb,sep=' ')
96 #colnames(tablesqrpsup[[1]])<-paste('classe',1:clnb,sep=' ')
97 #colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
98 #colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
99 #chistabletot<-rbind(tablesqrpact[2][[1]],tablesqrpsup[2][[1]])
100 #chistabletot<-rbind(chistabletot,tablesqrpet[2][[1]])
101 #ptabletot<-rbind(tablesqrpact[1][[1]],tablesqrpet[1][[1]])
102 #"""
103 #    txt += """
104 #write.csv2(chistabletot,file="%s")
105 #write.csv2(ptabletot,file="%s")
106 #gbcluster<-n1
107 #write.csv2(gbcluster,file="%s")
108 #""" % (DictChdTxtOut['chisqtable'], DictChdTxtOut['ptable'], DictChdTxtOut['SbyClasseOut'])
109 #
110
111
112 def RchdTxt(DicoPath, RscriptPath, mincl, classif_mode, nbt = 9, svdmethod = 'svdR', libsvdc = False, libsvdc_path = None, R_max_mem = False, mode_patate = False):
113     txt = """
114     source("%s")
115     source("%s")
116     source("%s")
117     source("%s")
118     """ % (ffr(RscriptPath['CHD']), ffr(RscriptPath['chdtxt']), ffr(RscriptPath['anacor']), ffr(RscriptPath['Rgraph']))
119     if R_max_mem :
120         txt += """
121     memory.limit(%i)
122         """ % R_max_mem
123
124     txt += """
125     nbt <- %i
126     """ % nbt
127     if svdmethod == 'svdlibc' and libsvdc :
128         txt += """
129         svd.method <- 'svdlibc'
130         libsvdc.path <- "%s"
131         """ % ffr(libsvdc_path)
132     elif svdmethod == 'irlba' :
133         txt += """
134         library(irlba)
135         svd.method <- 'irlba'
136         libsvdc.path <- NULL
137         """
138     else :
139         txt += """
140         svd.method = 'svdR'
141         libsvdc.path <- NULL
142         """
143     if mode_patate :
144         txt += """
145         mode.patate = TRUE
146         """
147     else :
148         txt += """
149         mode.patate = FALSE
150         """
151     txt +="""
152     library(Matrix)
153     data1 <- readMM("%s")
154     data1 <- as(data1, "dgCMatrix")
155     row.names(data1) <- 1:nrow(data1)
156     """ % ffr(DicoPath['TableUc1'])
157     
158     if classif_mode == 0:
159         txt += """
160         data2 <- readMM("%s")
161         data2 <- as(data2, "dgCMatrix")
162         row.names(data2) <- 1:nrow(data2)
163         """ % ffr(DicoPath['TableUc2'])
164     txt += """
165     log1 <- "%s"
166     chd1<-CHD(data1, x = nbt, mode.patate = mode.patate, svd.method = svd.method, libsvdc.path = libsvdc.path, log.file = log1)
167     """ % ffr(DicoPath['log-chd1.txt'])
168     
169     if classif_mode == 0:
170         txt += """
171     log2 <- "%s"
172     chd2<-CHD(data2, x = nbt, mode.patate = mode.patate, svd.method = svd.method, libsvdc.path = libsvdc.path, log.file = log2)
173     """ % ffr(DicoPath['log-chd2.txt'])
174     
175     txt += """
176     #lecture des uce
177     listuce1<-read.csv2("%s")
178     """ % ffr(DicoPath['listeuce1'])
179     
180     if classif_mode == 0:
181         txt += """
182         listuce2<-read.csv2("%s")
183         """ % ffr(DicoPath['listeuce2'])
184         
185     txt += """
186     rm(data1)
187     """
188     
189     if classif_mode == 0:
190         txt += """
191         rm(data2)
192         """
193     txt += """
194     classif_mode <- %i
195     mincl <- %i
196     uceout <- "%s"
197     if (classif_mode == 0) {
198         chd.result <- Rchdtxt(uceout, chd1, chd2 = chd2, mincl = mincl,classif_mode = classif_mode, nbt = nbt)
199     } else {
200         chd.result <- Rchdtxt(uceout, chd1, chd2 = chd1, mincl = mincl,classif_mode = classif_mode, nbt = nbt)
201     }
202     n1 <- chd.result$n1
203     classeuce1 <- chd.result$cuce1
204     classes<-n1[,ncol(n1)]
205     write.csv2(n1, file="%s")
206     rm(n1)
207     """ % (classif_mode, mincl, ffr(DicoPath['uce']), ffr(DicoPath['n1.csv']))
208     
209     txt += """
210     tree.tot1 <- make_tree_tot(chd1)
211 #    open_file_graph("%s", widt = 600, height=400)
212 #    plot(tree.tot1$tree.cl)
213 #    dev.off()
214     """ % ffr(DicoPath['arbre1'])
215     
216     if classif_mode == 0:
217         txt += """
218         classeuce2 <- chd.result$cuce2
219         tree.tot2 <- make_tree_tot(chd2)
220 #        open_file_graph("%s", width = 600, height=400)
221 #        plot(tree.tot2$tree.cl)
222 #        dev.off()
223         """ % ffr(DicoPath['arbre2'] ) 
224               
225     txt += """
226     tree.cut1 <- make_dendro_cut_tuple(tree.tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
227     save(tree.cut1, file="%s")
228     
229     open_file_graph("%s", width = 600, height=400)
230     plot.dendropr(tree.cut1$tree.cl,classes, histo=TRUE)
231     open_file_graph("%s", width = 600, height=400)
232     plot(tree.cut1$dendro_tot_cl)
233     dev.off()
234     """ % (ffr(DicoPath['Rdendro']), ffr(DicoPath['dendro1']), ffr(DicoPath['arbre1']))
235     
236     if classif_mode == 0:
237         txt += """
238         tree.cut2 <- make_dendro_cut_tuple(tree.tot2$dendro_tuple, chd.result$coord_ok, classeuce2, 2, nbt)
239         open_file_graph("%s", width = 600, height=400)
240         plot(tree.cut2$tree.cl)
241         dev.off()
242         open_file_graph("%s", width = 600, height=400)
243         plot(tree.cut2$dendro_tot_cl)
244         dev.off()
245         """ % (ffr(DicoPath['dendro2']), ffr(DicoPath['arbre2']))
246         
247     txt += """
248     
249     #save.image(file="%s")
250     """ % (ffr(DicoPath['RData']))
251     
252     fileout = open(DicoPath['Rchdtxt'], 'w')
253     fileout.write(txt)
254     fileout.close()
255
256 def RPamTxt(corpus, RscriptPath):
257     DicoPath = corpus.pathout
258     param = corpus.parametres
259     txt = """
260     source("%s")
261     """ % (RscriptPath['pamtxt'])
262     txt += """
263     source("%s")
264     """ % (RscriptPath['Rgraph'])
265     txt += """
266     result <- pamtxt("%s", "%s", "%s", method = "%s", clust_type = "%s", clnb = %i)
267     n1 <- result$uce
268     """ % (DicoPath['TableUc1'], DicoPath['listeuce1'], DicoPath['uce'], param['method'], param['cluster_type'], param['nbcl'] )
269     txt += """
270     open_file_graph("%s", width=400, height=400)
271     plot(result$cl)
272     dev.off()
273     """ % (DicoPath['arbre1'])
274     txt += """
275     save.image(file="%s")
276     """ % DicoPath['RData']
277     fileout = open(DicoPath['Rchdtxt'], 'w')
278     fileout.write(txt)
279     fileout.close()
280     
281
282 def RchdQuest(DicoPath, RscriptPath, nbcl = 10, mincl = 10):
283     txt = """
284     source("%s")
285     source("%s")
286     source("%s")
287     source("%s")
288     """ % (ffr(RscriptPath['CHD']), ffr(RscriptPath['chdquest']), ffr(RscriptPath['anacor']),ffr(RscriptPath['Rgraph']))
289
290     txt += """
291     nbt <- %i - 1
292     mincl <- %i
293     """ % (nbcl, mincl)
294
295     txt += """
296     chd.result<-Rchdquest("%s","%s","%s", nbt = nbt, mincl = mincl)
297     n1 <- chd.result$n1
298     classeuce1 <- chd.result$cuce1
299     """ % (ffr(DicoPath['mat01.csv']), ffr(DicoPath['listeuce1']), ffr(DicoPath['uce']))
300     
301     txt += """
302     tree_tot1 <- make_tree_tot(chd.result$chd)
303     open_file_graph("%s", width = 600, height=400)
304     plot(tree_tot1$tree.cl)
305     dev.off()
306     """ % ffr(DicoPath['arbre1'])
307     
308     txt += """
309     tree_cut1 <- make_dendro_cut_tuple(tree_tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
310     tree.cut1 <- tree_cut1
311     save(tree.cut1, file="%s")
312     open_file_graph("%s", width = 600, height=400)
313     classes<-n1[,ncol(n1)]
314     plot.dendropr(tree_cut1$tree.cl,classes, histo = TRUE)
315     """ % (ffr(DicoPath['Rdendro']), ffr(DicoPath['dendro1']))
316     
317     txt += """
318     save.image(file="%s")
319     """ % ffr(DicoPath['RData'])
320     fileout = open(DicoPath['Rchdquest'], 'w')
321     fileout.write(txt)
322     fileout.close()
323     
324 def ReinertTxtProf(DictChdTxtOut, RscriptsPath, clnb, taillecar):
325     txt = "clnb<-%i\n" % clnb
326     txt += """
327 source("%s")
328 #load("%s")
329 n1 <- read.csv2("%s")
330 """ % (ffr(RscriptsPath['chdfunct']), ffr(DictChdTxtOut['RData']), ffr(DictChdTxtOut['n1.csv']))
331     txt += """
332 dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
333 datasup<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
334 dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
335 """ % (ffr(DictChdTxtOut['Contout']), ffr(DictChdTxtOut['ContSupOut']), ffr(DictChdTxtOut['ContEtOut']))
336     txt += """
337 tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
338 tablesqrpsup<-BuildProf(as.matrix(datasup),n1,clnb)
339 tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
340 """
341     txt += """
342 PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s",tablesqrpsup[4],tablesqrpsup[5])
343 """ % (ffr(DictChdTxtOut['PROFILE_OUT']), ffr(DictChdTxtOut['ANTIPRO_OUT']))
344     txt += """
345 colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
346 colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
347 colnames(tablesqrpsup[[2]])<-paste('classe',1:clnb,sep=' ')
348 colnames(tablesqrpsup[[1]])<-paste('classe',1:clnb,sep=' ')
349 colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
350 colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
351 chistabletot<-rbind(tablesqrpact[2][[1]],tablesqrpsup[2][[1]])
352 chistabletot<-rbind(chistabletot,tablesqrpet[2][[1]])
353 ptabletot<-rbind(tablesqrpact[1][[1]],tablesqrpet[1][[1]])
354 """
355     txt += """
356 write.csv2(chistabletot,file="%s")
357 write.csv2(ptabletot,file="%s")
358 gbcluster<-n1
359 write.csv2(gbcluster,file="%s")
360 """ % (ffr(DictChdTxtOut['chisqtable']), ffr(DictChdTxtOut['ptable']), ffr(DictChdTxtOut['SbyClasseOut']))
361     if clnb > 2 :
362         txt += """
363     library(ca)
364     colnames(dataact)<-paste('classe',1:clnb,sep=' ')
365     colnames(datasup)<-paste('classe',1:clnb,sep=' ')
366     colnames(dataet)<-paste('classe',1:clnb,sep=' ')
367     rowtot<-nrow(dataact)+nrow(dataet)+nrow(datasup)
368     afctable<-rbind(as.matrix(dataact),as.matrix(datasup))
369     afctable<-rbind(afctable,as.matrix(dataet))
370     colnames(afctable)<-paste('classe',1:clnb,sep=' ')
371     afc<-ca(afctable,suprow=((nrow(dataact)+1):rowtot),nd=(ncol(afctable)-1))
372     debsup<-nrow(dataact)+1
373     debet<-nrow(dataact)+nrow(datasup)+1
374     fin<-rowtot
375     afc<-AddCorrelationOk(afc)
376     """
377     #FIXME : split this!!!
378         txt += """
379     source("%s")
380     """ % ffr(RscriptsPath['Rgraph'])
381     
382         txt += """
383         afc <- summary.ca.dm(afc)
384         afc_table <- create_afc_table(afc)
385         write.csv2(afc_table$facteur, file = "%s")
386         write.csv2(afc_table$colonne, file = "%s")
387         write.csv2(afc_table$ligne, file = "%s")
388         """ % (ffr(DictChdTxtOut['afc_facteur']), ffr(DictChdTxtOut['afc_col']), ffr(DictChdTxtOut['afc_row']))
389     
390         txt += """
391     PARCEX<-%s
392     """ % taillecar
393         txt += """
394     xyminmax <- PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
395     """ % (ffr(DictChdTxtOut['AFC2DL_OUT']))
396         txt += """
397     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)
398     """ % (ffr(DictChdTxtOut['AFC2DSL_OUT']))
399         txt += """
400         if ((fin - debet) > 2) {
401     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)
402         }
403     """ % (ffr(DictChdTxtOut['AFC2DEL_OUT']))
404         txt += """
405     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)
406     """ % (ffr(DictChdTxtOut['AFC2DCL_OUT']))
407 #        txt += """
408  #   PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
409  #   PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debsup, fin=(debet-1), xlab = xlab, ylab = ylab)
410   #  PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debet, fin=fin, xlab = xlab, ylab = ylab)
411  #   PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col=TRUE, what='crl', xlab = xlab, ylab = ylab)
412  #   """ % (DictChdTxtOut['AFC2DCoul'], DictChdTxtOut['AFC2DCoulSup'], DictChdTxtOut['AFC2DCoulEt'], DictChdTxtOut['AFC2DCoulCl'])
413        
414     txt += """
415 #rm(dataact)
416 #rm(datasup)
417 #rm(dataet)
418 rm(tablesqrpact)
419 rm(tablesqrpsup)
420 rm(tablesqrpet)
421 save.image(file="%s")
422 """ % ffr(DictChdTxtOut['RData'])
423     file = open(DictChdTxtOut['RTxtProfGraph'], 'w')
424     file.write(txt)
425     file.close()
426
427
428 def write_afc_graph(self):
429     if self.param['over'] : over = 'TRUE'
430     else : over = 'FALSE'
431
432     if self.param['do_select_nb'] : do_select_nb = 'TRUE'
433     else : do_select_nb = 'FALSE'
434
435     if self.param['do_select_chi'] : do_select_chi = 'TRUE'
436     else : do_select_chi = 'FALSE'
437
438     if self.param['do_select_chi_classe'] : do_select_chi_classe = 'TRUE'
439     else : do_select_chi_classe = 'FALSE'
440
441     if self.param['cex_txt'] : cex_txt = 'TRUE'
442     else : cex_txt = 'FALSE'
443
444     if self.param['tchi'] : tchi = 'TRUE'
445     else : tchi = 'FALSE'
446
447     if self.param['svg'] : svg = 'TRUE'
448     else : svg = 'FALSE'
449
450     with open(self.RscriptsPath['afc_graph'], 'r') as f:
451         txt = f.read()
452
453 #    self.DictPathOut['RData'], \
454     scripts = txt % (ffr(self.RscriptsPath['Rgraph']),\
455     self.param['typegraph'], \
456     self.param['what'], \
457     self.param['facteur'][0],\
458     self.param['facteur'][1], \
459     self.param['facteur'][2], \
460     self.param['qui'], \
461     over,  do_select_nb, \
462     self.param['select_nb'],  \
463     do_select_chi, \
464     self.param['select_chi'], \
465     do_select_chi_classe, \
466     self.param['nbchic'], \
467     cex_txt, \
468     self.param['txt_min'], \
469     self.param['txt_max'], \
470     self.fileout, \
471     self.param['width'], \
472     self.param['height'],\
473     self.param['taillecar'], \
474     self.param['alpha'], \
475     self.param['film'], \
476     tchi,\
477     self.param['tchi_min'],\
478     self.param['tchi_max'],\
479     ffr(os.path.dirname(self.fileout)),\
480     svg)
481     return scripts
482         
483 def print_simi3d(self):
484     simi3d = self.parent.simi3dpanel
485     txt = '#Fichier genere par Iramuteq'
486     if simi3d.movie.GetValue() :
487         movie = "'" + ffr(os.path.dirname(self.DictPathOut['RData'])) + "'"
488     else :
489         movie = 'NULL'
490     
491     #if self.corpus.parametres['type'] == 'corpus' :
492     #    header = 'TRUE'
493     #else :
494     #    header = 'FALSE'
495     header = 'FALSE'
496     txt += """
497     dm<-read.csv2("%s",row.names=1,header = %s)
498     load("%s")
499     """ % (self.DictPathOut['Contout'], header, self.DictPathOut['RData'])
500     
501     txt += """
502     source("%s")
503     """ % self.parent.RscriptsPath['Rgraph']
504
505
506     txt += """
507     make.simi.afc(dm,chistabletot, lim=%i, alpha = %.2f, movie = %s)
508     """ % (simi3d.spin_1.GetValue(), float(simi3d.slider_1.GetValue())/100, movie)
509     tmpfile = tempfile.mktemp(dir=self.parent.TEMPDIR)
510     tmp = open(tmpfile,'w')
511     tmp.write(txt)
512     tmp.close()
513     return tmpfile
514
515 def dendroandbarplot(table, rownames, colnames, rgraph, tmpgraph, intxt = False, dendro=False) :
516     if not intxt :
517         txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
518     rownb = len(rownames)
519     rownames = 'c("' + '","'.join(rownames) + '")'
520     colnames = 'c("' + '","'.join(colnames) + '")'
521     if not intxt :
522         #FIXME
523         txt = """
524             di <- matrix(data=%s, nrow=%i, byrow = TRUE)
525             rownames(di)<- %s
526             colnames(di) <- %s
527         """ % (txttable, rownb, rownames, colnames)
528     else :
529         txt = intxt
530     txt += """
531         load("%s")
532         library(ape)
533         source("%s")
534         height <- (30*ncol(di)) + (15*nrow(di))
535         height <- ifelse(height <= 400, 400, height)
536         width <- 500
537         open_file_graph("%s", width=width, height=height)
538         plot.dendro.lex(tree.cut1$tree.cl, di)
539         """ % (ffr(dendro),ffr(rgraph),  ffr(tmpgraph))
540     return txt
541
542 def barplot(table, parametres, intxt = False) :
543     if not intxt :
544         txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
545     #width = 100 + (15 * len(rownames)) + (100 * len(colnames))
546     #height =  len(rownames) * 15
547     rownb = len(parametres['rownames'])
548     #if height < 400 :
549     #    height = 400
550     rownames = 'c("' + '","'.join(parametres['rownames']) + '")'
551     colnames = 'c("' + '","'.join(parametres['colnames']) + '")'
552
553     if not intxt :
554         #FIXME
555         txt = """
556             di <- matrix(data=%s, nrow=%i, byrow = TRUE)
557             toinf <- which(di == Inf)
558             tominf <- which(di == -Inf)
559             if (length(toinf)) {
560                 di[toinf] <- NA
561                 valmax <- max(di, na.rm = TRUE)
562                 if (valmax <= 0) {
563                     valmax <- 2
564                 } else {
565                     valmax <- valmax + 2
566                 }
567                 di[toinf] <- valmax
568             }
569             if (length(tominf)) {
570                 di[tominf] <- NA
571                 valmin <- min(di, na.rm = TRUE)
572                 if (valmin >=0) {
573                     valmin <- -2
574                 } else {
575                     valmin <- valmin - 2
576                 }
577                 di[tominf] <- valmin
578             }
579             rownames(di)<- %s
580             colnames(di) <- %s
581         """ % (txttable, rownb, rownames, colnames)
582     else :
583         txt = intxt
584     if not 'tree' in parametres :
585         txt += """
586             source("%s")
587             color = rainbow(nrow(di))
588             width <- %i
589             height <- %i
590             open_file_graph("%s",width = width, height = height, svg = %s)
591                 par(mar=c(0,0,0,0))
592             layout(matrix(c(1,2),1,2, byrow=TRUE),widths=c(3,lcm(7)))
593             par(mar=c(8,4,1,0))
594             yp = ifelse(length(toinf), 0.2, 0)
595             ym = ifelse(length(tominf), 0.2, 0)
596             ymin <- ifelse(!length(which(di < 0)), 0, min(di) - ym)
597             coord <- barplot(as.matrix(di), beside = TRUE, col = color, space = c(0.1,0.6), ylim=c(ymin, max(di) + yp), las = 2)
598             if (length(toinf)) {
599                 coordinf <- coord[toinf]
600                 valinf <- di[toinf]
601                 text(x=coordinf, y=valinf + 0.1, 'i')
602             }
603             if (length(tominf)) {
604                 coordinf <- coord[toinf]
605                 valinf <- di[toinf]
606                 text(x=coordinf, y=valinf - 0.1, 'i')
607             }            
608             c <- colMeans(coord)
609             c1 <- c[-1]
610             c2 <- c[-length(c)]
611             cc <- cbind(c1,c2)
612             lcoord <- apply(cc, 1, mean)
613             abline(v=lcoord)
614             if (min(di) < 0) {
615                 amp <- abs(max(di) - min(di))
616             } else {
617                 amp <- max(di)
618             }
619             if (amp < 10) {
620                 d <- 2
621             } else {
622                 d <- signif(amp%%/%%10,1)
623             }
624             mn <- round(min(di))
625             mx <- round(max(di))
626             for (i in mn:mx) {
627                 if ((i/d) == (i%%/%%d)) { 
628                     abline(h=i,lty=3)
629                 }
630             }
631             par(mar=c(0,0,0,0))
632             plot(0, axes = FALSE, pch = '')
633             legend(x = 'center' , rownames(di), fill = color)
634             dev.off()
635             """ % (ffr(parametres['rgraph']), parametres['width'], parametres['height'], ffr(parametres['tmpgraph']), parametres['svg'])    
636     else :
637         txt += """
638         load("%s")
639         library(ape)
640         source("%s")
641         width = %i
642         height = %i
643         open_file_graph("%s", width=width, height=height, svg = %s)
644         plot.dendro.lex(tree.cut1$tree.cl, di)
645         """ % (ffr(parametres['tree']), ffr(parametres['rgraph']), parametres['width'], parametres['height'], ffr(parametres['tmpgraph']), parametres['svg'])
646     return txt
647
648 #def RAfcUci(DictAfcUciOut, nd=2, RscriptsPath='', PARCEX='0.8'):
649 #    txt = """
650 #    library(ca)
651 #    nd<-%i
652 #    """ % nd
653 #    txt += """
654 #    dataact<-read.csv2("%s")
655 #    """ % (DictAfcUciOut['TableCont'])#, encoding)
656 #    txt += """
657 #    datasup<-read.csv2("%s")
658 #    """ % (DictAfcUciOut['TableSup'])#, encoding)
659 #    txt += """
660 #    dataet<-read.csv2("%s")
661 #    """ % (DictAfcUciOut['TableEt'])#, encoding)
662 #    txt += """
663 #    datatotsup<-cbind(dataact,datasup)
664 #    datatotet<-cbind(dataact,dataet)
665 #    afcact<-ca(dataact,nd=nd)
666 #    afcsup<-ca(datatotsup,supcol=((ncol(dataact)+1):ncol(datatotsup)),nd=nd)
667 #    afcet<-ca(datatotet,supcol=((ncol(dataact)+1):ncol(datatotet)),nd=nd)
668 #    afctot<-afcsup$colcoord
669 #    rownames(afctot)<-afcsup$colnames
670 #    colnames(afctot)<-paste('coord. facteur',1:nd,sep=' ')
671 #    afctot<-cbind(afctot,mass=afcsup$colmass)
672 #    afctot<-cbind(afctot,distance=afcsup$coldist)
673 #    afctot<-cbind(afctot,intertie=afcsup$colinertia)
674 #    rcolet<-afcet$colsup
675 #    afctmp<-afcet$colcoord[rcolet,]
676 #    rownames(afctmp)<-afcet$colnames[rcolet]
677 #    afctmp<-cbind(afctmp,afcet$colmass[rcolet])
678 #    afctmp<-cbind(afctmp,afcet$coldist[rcolet])
679 #    afctmp<-cbind(afctmp,afcet$colinertia[rcolet])
680 #    afctot<-rbind(afctot,afctmp)
681 #    write.csv2(afctot,file = "%s")
682 #    source("%s")
683 #    """ % (DictAfcUciOut['afc_row'], RscriptsPath['Rgraph'])
684 #    txt += """
685 #    PARCEX=%s
686 #    """ % PARCEX
687 #    #FIXME
688 #    txt += """
689 #    PlotAfc(afcet,filename="%s",toplot=c%s, PARCEX=PARCEX)
690 #    """ % (DictAfcUciOut['AfcColAct'], "('none','active')")
691 #    txt += """
692 #    PlotAfc(afcsup,filename="%s",toplot=c%s, PARCEX=PARCEX)
693 #    """ % (DictAfcUciOut['AfcColSup'], "('none','passive')")
694 #    txt += """PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
695 #    """ % (DictAfcUciOut['AfcColEt'], "('none','passive')")
696 #    txt += """
697 #    PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
698 #    """ % (DictAfcUciOut['AfcRow'], "('all','none')")
699 #    f = open(DictAfcUciOut['Rafcuci'], 'w')
700 #    f.write(txt)
701 #    f.close()
702
703 class PrintSimiScript(PrintRScript) :
704     def make_script(self) :
705         self.txtgraph = ''
706         self.packages(['igraph', 'proxy', 'Matrix'])
707         self.sources([self.analyse.parent.RscriptsPath['simi'], self.analyse.parent.RscriptsPath['Rgraph']])
708         txt = ''
709         if not self.parametres['keep_coord'] and not (self.parametres['type'] == 'simimatrix' or self.parametres['type'] == 'simiclustermatrix') :
710             txt += """
711             dm.path <- "%s"
712             cn.path <- "%s"
713             selected.col <- "%s"
714             """ % (ffr(self.pathout['mat01.csv']), ffr(self.pathout['actives.csv']), ffr(self.pathout['selected.csv']))
715             if 'word' in self.parametres :
716                 txt += """
717                 word <- TRUE
718                 index <- %i + 1
719                 """ % self.parametres['word']
720             else :
721                 txt += """
722                 word <- FALSE
723                 """
724             txt += """
725             dm <-readMM(dm.path)
726             cn <- read.table(cn.path, sep='\t', quote='"')
727             colnames(dm) <- cn[,1]
728             if (file.exists(selected.col)) {
729                 sel.col <- read.csv2(selected.col, header = FALSE)
730                 sel.col <- sel.col[,1] + 1
731             } else {
732                 sel.col <- 1:ncol(dm)
733             }
734             if (!word) {
735                 dm <- dm[, sel.col]
736             } else {
737                 forme <- colnames(dm)[index]
738                 if (!index %in% sel.col) {
739                     sel.col <- append(sel.col, index)
740                 }
741                 dm <- dm[, sel.col]
742                 index <- which(colnames(dm) == forme)
743             }
744             """
745         elif not self.parametres['keep_coord'] and (self.parametres['type'] == 'simimatrix' or self.parametres['type'] == 'simiclustermatrix'):
746             txt += """
747             dm.path <- "%s"
748             selected.col <- "%s"
749             """ % (ffr(self.pathout['mat01.csv']), ffr(self.pathout['selected.csv']))
750             if 'word' in self.parametres :
751                 txt += """
752                 word <- TRUE
753                 index <- %i + 1
754                 """ % self.parametres['word']
755             else :
756                 txt += """
757                 word <- FALSE
758                 """
759             txt += """
760             dm <-read.csv2(dm.path)
761             dm <- as.matrix(dm)
762             if (file.exists(selected.col)) {
763                 sel.col <- read.csv2(selected.col, header = FALSE)
764                 sel.col <- sel.col[,1] + 1
765             } else {
766                 sel.col <- 1:ncol(dm)
767             }
768             if (!word) {
769                 dm <- dm[, sel.col]
770             } else {
771                 forme <- colnames(dm)[index]
772                 if (!index %in% sel.col) {
773                     sel.col <- append(sel.col, index)
774                 }
775                 dm <- dm[, sel.col]
776                 index <- which(colnames(dm) == forme)
777             }
778             """
779         else :
780             txt += """
781             load("%s")
782             """ % ffr(self.pathout['RData.RData'])
783         
784         if self.parametres['coeff'] == 0 :
785             method = 'cooc'
786             if not self.parametres['keep_coord'] :
787                 txt += """
788                 method <- 'cooc'
789                 mat <- make.a(dm)
790                 """
791         else :
792             if not self.parametres['keep_coord'] :
793                 txt += """
794                 dm <- as.matrix(dm)
795                 """
796         if self.parametres['coeff'] == 1 :
797             method = 'prcooc'
798             txt += """
799             method <- 'Russel'
800             mat <- simil(dm, method = 'Russel', diag = TRUE, upper = TRUE, by_rows = FALSE)
801             """
802         elif self.analyse.indices[self.parametres['coeff']] == 'binomial' :
803             method = 'binomial'
804             if not self.parametres['keep_coord'] :
805                 txt += """
806                 method <- 'binomial'
807                 mat <- binom.sim(dm)
808                 """
809         elif self.parametres['coeff'] != 0 :
810             method = self.analyse.indices[self.parametres['coeff']]
811             if not self.parametres['keep_coord'] :
812                 txt += """
813                 method <-"%s"
814                 mat <- simil(dm, method = method, diag = TRUE, upper = TRUE, by_rows = FALSE)
815                 """ % self.analyse.indices[self.parametres['coeff']]
816         if not self.parametres['keep_coord'] :
817             txt += """
818             mat <- as.matrix(stats::as.dist(mat,diag=TRUE,upper=TRUE))
819             mat[is.na(mat)] <- 0
820             if (length(which(mat == Inf))) {
821                 infp <- which(mat == Inf)
822                 mat[infp] <- NA
823                 maxmat <- max(mat, na.rm = TRUE)
824                 if (maxmat > 0) {
825                 maxmat <- maxmat + 1
826                 } else {
827                     maxmat <- 0
828                 }
829                 mat[infp] <- maxmat
830             }
831             if (length(which(mat == -Inf))) {
832                 infm <- which(mat == -Inf)
833                 mat[infm] <- NA
834                 minmat <- min(mat, na.rm = TRUE)
835                 if (maxmat < 0) {
836                 minmat <- minmat - 1
837                 } else {
838                     minmat <- 0
839                 }
840                 mat[infm] <- minmat
841             }
842             """
843         if 'word' in self.parametres and not self.parametres['keep_coord'] :
844             txt += """
845             mat <- graph.word(mat, index)
846             cs <- colSums(mat)
847             if (length(cs)) mat <- mat[,-which(cs==0)]
848             rs <- rowSums(mat)
849             if (length(rs)) mat <- mat[-which(rs==0),]
850             if (length(cs)) dm <- dm[, -which(cs==0)]
851             """
852
853         if self.parametres['layout'] == 0 : layout = 'random'
854         if self.parametres['layout'] == 1 : layout = 'circle'
855         if self.parametres['layout'] == 2 : layout = 'frutch'
856         if self.parametres['layout'] == 3 : layout = 'kawa'
857         if self.parametres['layout'] == 4 : layout = 'graphopt'
858
859
860         self.filename=''
861         if self.parametres['type_graph'] == 0 : type = 'tkplot'
862         if self.parametres['type_graph'] == 1 : 
863             graphnb = 1
864             type = 'nplot'
865             dirout = os.path.dirname(self.pathout['mat01.csv'])
866             while os.path.exists(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png')):
867                 graphnb +=1
868             self.filename = ffr(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png'))
869         if self.parametres['type_graph'] == 2 : type = 'rgl'
870         if self.parametres['type_graph'] == 3 : 
871             graphnb = 1
872             type = 'web'
873             dirout = os.path.dirname(self.pathout['mat01.csv'])
874             while os.path.exists(os.path.join(dirout,'web_'+str(graphnb))):
875                 graphnb +=1
876             self.filename = ffr(os.path.join(dirout,'web_'+str(graphnb)))
877             os.mkdir(self.filename)        
878             self.filename = os.path.join(self.filename, 'gexf.gexf')
879         if self.parametres['type_graph'] == 4 : 
880             graphnb = 1
881             type = 'rglweb'
882             dirout = os.path.dirname(self.pathout['mat01.csv'])
883             while os.path.exists(os.path.join(dirout,'webrgl_'+str(graphnb))):
884                 graphnb +=1
885             self.filename = ffr(os.path.join(dirout,'webrgl_'+str(graphnb)))
886             os.mkdir(self.filename)
887
888         if self.parametres['arbremax'] : 
889             arbremax = 'TRUE'
890             self.txtgraph += ' - arbre maximum'
891         else : arbremax = 'FALSE'
892         
893         if self.parametres['coeff_tv'] : 
894             coeff_tv = self.parametres['coeff_tv_nb']
895             tvminmax = 'c(NULL,NULL)'
896         elif not self.parametres['coeff_tv'] or self.parametres.get('sformchi', False) :
897             coeff_tv = 'NULL'
898             tvminmax = 'c(%i, %i)' %(self.parametres['tvmin'], self.parametres['tvmax'])
899         if self.parametres['coeff_te'] : coeff_te = 'c(%i,%i)' % (self.parametres['coeff_temin'], self.parametres['coeff_temax'])
900         else : coeff_te = 'NULL'
901         
902         if self.parametres['vcex'] or self.parametres.get('cexfromchi', False) :
903             vcexminmax = 'c(%i/10,%i/10)' % (self.parametres['vcexmin'],self.parametres['vcexmax'])
904         else :
905             vcexminmax = 'c(NULL,NULL)'
906         if not self.parametres['label_v'] : label_v = 'FALSE'
907         else : label_v = 'TRUE'
908
909         if not self.parametres['label_e'] : label_e = 'FALSE'
910         else : label_e = 'TRUE'
911         
912         if self.parametres['seuil_ok'] : seuil = str(self.parametres['seuil'])
913         else : seuil = 'NULL'
914         
915         if not self.parametres.get('edgecurved', False) :
916             ec = 'FALSE'
917         else :
918             ec = 'TRUE'
919         
920         txt += """
921         edge.curved <- %s
922         """ % ec
923         
924         cols = str(self.parametres['cols']).replace(')',', max=255)')
925         cola = str(self.parametres['cola']).replace(')',',max=255)')
926
927         txt += """
928         minmaxeff <- %s
929         """ % tvminmax
930         txt += """
931         vcexminmax <- %s
932         """ % vcexminmax
933         txt += """
934         cex = %i/10
935         """ % self.parametres['cex']
936
937         if self.parametres['film'] : 
938             txt += """
939             film <- "%s"
940             """ % self.pathout['film']
941         else : 
942             txt += """
943             film <- NULL
944             """
945         txt += """
946         seuil <- %s
947         if (!is.null(seuil)) {
948             if (method!='cooc') {
949                 seuil <- seuil/100
950             } 
951         }
952         """ % seuil
953         
954         txt += """
955         label.v <- %s
956         label.e <- %s
957         """ % (label_v, label_e)
958         txt += """
959         cols <- rgb%s
960         cola <- rgb%s
961         """ % (cols, cola)
962         txt += """
963         width <- %i
964         height <- %i
965         """ % (self.parametres['width'], self.parametres['height'])
966         if self.parametres['keep_coord'] :
967             txt += """
968             coords <- try(coords, TRUE)
969             if (!is.matrix(coords)) {
970                 coords<-NULL
971             }
972             """
973         else :
974             txt += """
975             coords <- NULL
976             """
977         txt += """
978         alpha <- %i/100
979         """ % self.parametres['alpha']
980         txt += """
981         alpha <- %i/100
982         """ % self.parametres['alpha']
983 #############################################
984         if  self.parametres.get('bystar',False) :
985             txt += """
986             et <- list()
987             """
988             for i, line in enumerate(self.parametres['listet']) :
989                 txt+= """
990                 et[[%i]] <- c(%s)
991                 """ % (i+1, ','.join([`val + 1` for val in line]))
992             txt+= """
993             unetoile <- c('%s')
994             """ % ("','".join([val for val in self.parametres['selectedstars']]))
995             txt += """
996             fsum <- NULL
997             rs <- rowSums(dm)
998             for (i in 1:length(unetoile)) {
999                 print(unetoile[i])
1000                 tosum <- et[[i]]
1001                 if (length(tosum) > 1) {
1002                     fsum <- cbind(fsum, colSums(dm[tosum,]))
1003                 } else {
1004                     fsum <- cbind(fsum, dm[tosum,])
1005                 }
1006             }
1007             source("%s")
1008             lex <- AsLexico2(fsum, chip=TRUE)
1009             dcol <- apply(lex[[4]],1,which.max)
1010             toblack <- apply(lex[[4]],1,max)
1011             gcol <- rainbow(length(unetoile))
1012             #gcol[2] <- 'orange'
1013             vertex.label.color <- gcol[dcol]
1014             vertex.label.color[which(toblack <= 3.84)] <- 'black'
1015             leg <- list(unetoile=unetoile, gcol=gcol)  
1016             cols <- vertex.label.color
1017             chivertex.size <- norm.vec(toblack, vcexminmax[1],  vcexminmax[2])
1018             
1019             """ % (ffr(self.analyse.parent.RscriptsPath['chdfunct']))
1020         else :
1021             txt += """
1022             vertex.label.color <- 'black' 
1023             chivertex.size <- 1
1024             leg<-NULL
1025             """
1026 #############################################        
1027
1028 #        txt += """
1029 #        eff <- colSums(dm)
1030 #        g.ori <- graph.adjacency(mat, mode='lower', weighted = TRUE)
1031 #        w.ori <- E(g.ori)$weight
1032 #        if (max.tree) {
1033 #            if (method == 'cooc') {
1034 #                E(g.ori)$weight <- 1 / w.ori
1035 #            } else {
1036 #                E(g.ori)$weigth <- 1 - w.ori
1037 #            }
1038 #            g.max <- minimum.spanning.tree(g.ori)
1039 #            if (method == 'cooc') {
1040 #                E(g.max)$weight <- 1 / E(g.max)$weight
1041 #            } else {
1042 #                E(g.max)$weight <- 1 - E(g.max)$weight
1043 #            }
1044 #            g.toplot <- g.max
1045 #        } else {
1046 #            g.toplot <- g.ori
1047 #        }
1048 #        """
1049         if self.parametres['com'] :
1050             com = `self.parametres['communities']`
1051         else :
1052             com = 'NULL'
1053         if self.parametres['halo'] :
1054             halo = 'TRUE'
1055         else :
1056             halo = 'FALSE'
1057         txt += """
1058         communities <- %s
1059         halo <- %s
1060         """ % (com, halo)
1061         txt += """
1062         eff <- colSums(dm)
1063         x <- list(mat = mat, eff = eff)
1064         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)
1065         """ % (method, type, layout, arbremax, coeff_tv, coeff_te)
1066             
1067         if self.parametres.get('bystar',False) :
1068             if self.parametres.get('cexfromchi', False) :
1069                 txt+="""
1070                     label.cex<-chivertex.size
1071                     """
1072             else :
1073                 txt+="""
1074                 label.cex <- cex
1075                 """
1076             if self.parametres.get('sfromchi', False) :
1077                 txt += """
1078                 vertex.size <- norm.vec(toblack, minmaxeff[1], minmaxeff[2])
1079                 """
1080             else :
1081                 txt += """
1082                 vertex.size <- NULL
1083                 """
1084         else :
1085             #print self.parametres
1086             if (self.parametres['type'] == 'clustersimitxt' and self.parametres.get('tmpchi', False)) or (self.parametres['type'] in ['simimatrix','simiclustermatrix'] and 'tmpchi' in self.parametres): 
1087                 txt += """
1088                 lchi <- read.table("%s")
1089                 lchi <- lchi[,1]
1090                 """ % ffr(self.parametres['tmpchi'])
1091                 txt += """
1092                     lchi <- lchi[sel.col]
1093                     """
1094             if self.parametres['type'] in ['clustersimitxt', 'simimatrix', 'simiclustermatrix'] and self.parametres.get('cexfromchi', False) :
1095                 txt += """ 
1096                 label.cex <- norm.vec(lchi, vcexminmax[1], vcexminmax[2])
1097                 """
1098             else :
1099                 txt += """
1100             if (is.null(vcexminmax[1])) {
1101                 label.cex <- cex
1102             } else {
1103                 label.cex <- graph.simi$label.cex
1104             }
1105             """
1106             if (self.parametres['type'] in ['clustersimitxt', 'simimatrix', 'simiclustermatrix']) and self.parametres.get('sfromchi', False):
1107                 txt += """ 
1108                 vertex.size <- norm.vec(lchi, minmaxeff[1], minmaxeff[2])
1109                 if (!length(vertex.size)) vertex.size <- 0
1110                 """
1111             else :
1112                 txt += """
1113             if (is.null(minmaxeff[1])) {
1114                 vertex.size <- 0
1115             } else {
1116                 vertex.size <- graph.simi$eff
1117             }
1118             """
1119         #txt += """ vertex.size <- NULL """
1120         if self.parametres['svg'] : svg = 'TRUE'
1121         else : svg = 'FALSE'
1122         txt += """
1123         svg <- %s
1124         """ % svg
1125         txt += """
1126         vertex.col <- cols
1127         if (!is.null(graph.simi$com)) {
1128             com <- graph.simi$com
1129             colm <- rainbow(length(com))
1130             if (vertex.size != 0 || graph.simi$halo) {
1131                 vertex.label.color <- 'black'
1132                 vertex.col <- colm[membership(com)]
1133             } else {
1134                 vertex.label.color <- colm[membership(com)]
1135             }
1136         }
1137         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)
1138         save.image(file="%s")
1139         """ % (type, self.filename, ffr(self.pathout['RData']))
1140         
1141         self.add(txt)
1142         self.write()
1143
1144 class WordCloudRScript(PrintRScript) :
1145     def make_script(self) :
1146         self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1147         self.packages(['wordcloud'])
1148         bg_col = Rcolor(self.parametres['col_bg'])
1149         txt_col = Rcolor(self.parametres['col_text'])
1150         if self.parametres['svg'] :
1151             svg = 'TRUE'
1152         else :
1153             svg = 'FALSE'
1154         txt = """
1155         svg <- %s
1156         """ % svg
1157         txt += """
1158         act <- read.csv2("%s", header = FALSE, row.names=1, sep='\t')
1159         selected.col <- read.table("%s")
1160         toprint <- as.matrix(act[selected.col[,1] + 1,])
1161         rownames(toprint) <- rownames(act)[selected.col[,1] + 1]
1162         maxword <- %i
1163         if (nrow(toprint) > maxword) {
1164             toprint <- as.matrix(toprint[order(toprint[,1], decreasing=TRUE),])
1165             toprint <- as.matrix(toprint[1:maxword,])
1166         }
1167         open_file_graph("%s", width = %i, height = %i , svg = svg)
1168         par(bg=rgb%s)
1169         wordcloud(row.names(toprint), toprint[,1], scale=c(%f,%f), random.order=FALSE, colors=rgb%s)
1170         dev.off()
1171         """ % (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)
1172         self.add(txt)
1173         self.write()
1174
1175 class ProtoScript(PrintRScript) :
1176     def make_script(self) :
1177         self.sources([self.analyse.parent.RscriptsPath['Rgraph'], self.analyse.parent.RscriptsPath['prototypical.R']])
1178         self.packages(['wordcloud'])
1179         if self.parametres.get('cloud', False) :
1180             cloud = 'TRUE'
1181         else :
1182             cloud = 'FALSE'
1183         txt = """
1184         errorn <- function(x) {
1185             qnorm(0.975)*sd(x)/sqrt(lenght(n))
1186         }
1187         errort <- function(x) {
1188             qt(0.975,df=lenght(x)-1)*sd(x)/sqrt(lenght(x))
1189         }
1190         mat <- read.csv2("%s", header = FALSE, row.names=1, sep='\t', quote='"', dec='.')
1191         open_file_graph("%s",height=800, width=1000)
1192         prototypical(mat, mfreq = %s, mrank = %s, cloud = FALSE, cexrange=c(1,2.4), cexalpha= c(0.4, 1), type = '%s')
1193         dev.off()
1194         """ % (ffr(self.analyse.pathout['table.csv']), ffr(self.analyse.pathout['proto.png']), self.parametres['limfreq'], self.parametres['limrang'], self.parametres['typegraph'])
1195         self.add(txt)
1196         self.write()
1197
1198
1199 class ExportAfc(PrintRScript) :
1200     def make_script(self) :
1201         self.source([self.analyse.parent.RscriptsPath['Rgraph']])
1202         self.packages(['rgexf'])
1203         txt = """
1204         """
1205
1206 class MergeGraphes(PrintRScript) :
1207     def __init__(self, parametres):
1208         self.script = u"#Script genere par IRaMuTeQ - %s\n" % datetime.now().ctime()
1209         self.pathout = PathOut()
1210         self.parametres = parametres
1211         self.scriptout = self.pathout['temp']
1212         
1213     def make_script(self) :
1214         #FIXME
1215         
1216         txt = """
1217         library(igraph)
1218         library(Matrix)
1219         graphs <- list()
1220         """
1221         load = """
1222         load("%s")
1223         g <- graph.simi$graph
1224         V(g)$weight <- (graph.simi$mat.eff/nrow(dm))*100
1225         graphs[['%s']] <- g
1226         """
1227         for i, graph in enumerate(self.parametres['lgraphes']) :
1228             path = os.path.dirname(graph)
1229             gname = ''.join(['g', `i`])
1230             RData = os.path.join(path,'RData.RData')
1231             txt += load % (ffr(RData), gname)
1232         self.add(txt)
1233         self.sources(['/home/pierre/workspace/iramuteq/Rscripts/simi.R'])
1234         txt = """
1235         ng <- merge.graph(graphs)
1236         ngraph <- list(graph=ng, layout=layout.fruchterman.reingold(ng, dim=3), labex.cex=V(ng)$weight)
1237         write.graph(ng, "%s", format = 'graphml')
1238         """ % ffr(self.parametres['grapheout'])
1239         self.add(txt)
1240     
1241 class TgenSpecScript(PrintRScript):
1242     def make_script(self):
1243         self.packages(['textometry'])
1244         txt = """
1245         tgen <- read.csv2("%s", row.names = 1, sep = '\\t')
1246         """ % ffr(self.parametres['tgeneff'])
1247         txt += """
1248         tot <- tgen[nrow(tgen), ]
1249         result <- NULL
1250         tgen <- tgen[-nrow(tgen),]
1251         for (i in 1:nrow(tgen)) {
1252             mat <- rbind(tgen[i,], tot - tgen[i,])
1253             specmat <- specificities(mat)
1254             result <- rbind(result, specmat[1,])
1255         }
1256         colnames(result) <- colnames(tgen)
1257         row.names(result) <- rownames(tgen)
1258         write.table(result, file = "%s", sep='\\t', col.names = NA)
1259         """ % ffr(self.pathout['tgenspec.csv'])
1260         self.add(txt)
1261         
1262 class TgenProfScript(PrintRScript):
1263     def make_script(self):
1264         self.sources([self.analyse.ira.RscriptsPath['chdfunct']])
1265         txt = """
1266         tgen <- read.csv2("%s", row.names = 1, sep = '\\t')
1267         """ % ffr(self.parametres['tgeneff'])
1268         txt += """
1269         res <- build.prof.tgen(tgen)
1270         write.table(res$chi2, file = "%s", sep='\\t', col.names = NA)
1271         write.table(res$pchi2, file = "%s", sep='\\t', col.names = NA)
1272         """ % (ffr(self.pathout['tgenchi2.csv']), ffr(self.pathout['tgenpchi2.csv']))
1273         self.add(txt)
1274         
1275 class FreqMultiScript(PrintRScript):
1276     def make_script(self):
1277         self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1278         txt = """
1279         freq <- read.csv2("%s", row.names=1, sep='\\t', dec='.')
1280         """ % ffr(self.pathout['frequences.csv'])
1281         txt += """
1282         toplot <- freq[order(freq[,2]) ,2]
1283         toplot.names = rownames(freq)[order(freq[,2])]
1284         h <- 80 + (20 * nrow(freq))
1285         open_file_graph("%s",height=h, width=500)
1286         par(mar=c(3,20,3,3))
1287         barplot(toplot, names = toplot.names, horiz=TRUE, las =1, col = rainbow(nrow(freq)))
1288         dev.off()
1289         """ % ffr(self.pathout['barplotfreq.png'])
1290         txt += """
1291         toplot <- freq[order(freq[,4]) ,4]
1292         toplot.names = rownames(freq)[order(freq[,4])]
1293         open_file_graph("%s",height=h, width=500)
1294         par(mar=c(3,20,3,3))
1295         barplot(toplot, names = toplot.names, horiz=TRUE, las =1, col = rainbow(nrow(freq)))
1296         dev.off()
1297         """ % ffr(self.pathout['barplotrow.png'])
1298         self.add(txt)
1299         self.write()