Merge branch 'master' of http://www.netdig.org/git/iramuteq
[iramuteq] / PrintRScript.py
1 # -*- coding: utf-8 -*-
2 #Author: Pierre Ratinaud
3 #Copyright (c) 2008-2011 Pierre Ratinaud
4 #Lisense: GNU/GPL
5
6 import tempfile
7 from chemins import ffr
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")' % 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")' % 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     """ % (RscriptPath['CHD'], RscriptPath['chdtxt'], RscriptPath['anacor'], 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     """ % 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         """ % DicoPath['TableUc2']
164     txt += """
165     chd1<-CHD(data1, x = nbt, mode.patate = mode.patate, svd.method = svd.method, libsvdc.path = libsvdc.path)
166     """
167     
168     if classif_mode == 0:
169         txt += """
170     chd2<-CHD(data2, x = nbt, mode.patate = mode.patate, svd.method = svd.method, libsvdc.path = libsvdc.path)
171     """
172     else:
173         txt += """
174     chd2<-chd1
175     """    
176     
177     txt += """
178     #lecture des uce
179     listuce1<-read.csv2("%s")
180     """ % DicoPath['listeuce1']
181     
182     if classif_mode == 0:
183         txt += """
184         listuce2<-read.csv2("%s")
185         """ % DicoPath['listeuce2']
186         
187     txt += """
188     rm(data1)
189     """
190     
191     if classif_mode == 0:
192         txt += """
193         rm(data2)
194         """
195     txt += """
196     classif_mode <- %i
197     mincl <- %i
198     uceout <- "%s"
199     if (classif_mode == 0) {
200         chd.result <- Rchdtxt(uceout, chd1, chd2 = chd2, mincl = mincl,classif_mode = classif_mode, nbt = nbt)
201     } else {
202         chd.result <- Rchdtxt(uceout, chd1, chd2 = chd1, mincl = mincl,classif_mode = classif_mode, nbt = nbt)
203     }
204     n1 <- chd.result$n1
205     classeuce1 <- chd.result$cuce1
206     classeuce2 <- chd.result$cuce2
207     """ % (classif_mode, mincl, DicoPath['uce'])
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     """%DicoPath['arbre1']
215     
216     if classif_mode == 0:
217         txt += """
218         tree.tot2 <- make_tree_tot(chd2)
219 #        open_file_graph("%s", width = 600, height=400)
220 #        plot(tree.tot2$tree.cl)
221 #        dev.off()
222         """ % DicoPath['arbre2']  
223               
224     txt += """
225     tree.cut1 <- make_dendro_cut_tuple(tree.tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
226     save(tree.cut1, file="%s")
227     classes<-n1[,ncol(n1)]
228     open_file_graph("%s", width = 600, height=400)
229     plot.dendropr(tree.cut1$tree.cl,classes, histo=TRUE)
230     open_file_graph("%s", width = 600, height=400)
231     plot(tree.cut1$dendro_tot_cl)
232     dev.off()
233     """ % (DicoPath['Rdendro'], DicoPath['dendro1'], DicoPath['arbre1'])
234     
235     if classif_mode == 0:
236         txt += """
237         tree.cut2 <- make_dendro_cut_tuple(tree.tot2$dendro_tuple, chd.result$coord_ok, classeuce2, 2, nbt)
238         open_file_graph("%s", width = 600, height=400)
239         plot(tree.cut2$tree.cl)
240         dev.off()
241         open_file_graph("%s", width = 600, height=400)
242         plot(tree.cut1$dendro_tot_cl)
243         dev.off()
244         """ % (DicoPath['dendro2'], DicoPath['arbre2'])
245         
246     txt += """
247     save.image(file="%s")
248     """ % DicoPath['RData']
249     fileout = open(DicoPath['Rchdtxt'], 'w')
250     fileout.write(txt)
251     fileout.close()
252
253 def RPamTxt(corpus, RscriptPath):
254     DicoPath = corpus.pathout
255     param = corpus.parametres
256     print param
257     txt = """
258     source("%s")
259     """ % (RscriptPath['pamtxt'])
260     txt += """
261     source("%s")
262     """ % (RscriptPath['Rgraph'])
263     txt += """
264     result <- pamtxt("%s", "%s", "%s", method = "%s", clust_type = "%s", clnb = %i)
265     n1 <- result$uce
266     """ % (DicoPath['TableUc1'], DicoPath['listeuce1'], DicoPath['uce'], param['method'], param['cluster_type'], param['nbcl'] )
267     txt += """
268     open_file_graph("%s", width=400, height=400)
269     plot(result$cl)
270     dev.off()
271     """ % (DicoPath['arbre1'])
272     txt += """
273     save.image(file="%s")
274     """ % DicoPath['RData']
275     fileout = open(DicoPath['Rchdtxt'], 'w')
276     fileout.write(txt)
277     fileout.close()
278     
279
280 def RchdQuest(DicoPath, RscriptPath, nbcl = 10, mincl = 10):
281     txt = """
282     source("%s")
283     source("%s")
284     source("%s")
285     source("%s")
286     """ % (RscriptPath['CHD'], RscriptPath['chdquest'], RscriptPath['anacor'],RscriptPath['Rgraph'])
287
288     txt += """
289     nbt <- %i - 1
290     mincl <- %i
291     """ % (nbcl, mincl)
292
293     txt += """
294     chd.result<-Rchdquest("%s","%s","%s", nbt = nbt, mincl = mincl)
295     n1 <- chd.result$n1
296     classeuce1 <- chd.result$cuce1
297     """ % (DicoPath['mat01'], DicoPath['listeuce1'], DicoPath['uce'])
298     
299     txt += """
300     tree_tot1 <- make_tree_tot(chd.result$chd)
301     open_file_graph("%s", width = 600, height=400)
302     plot(tree_tot1$tree.cl)
303     dev.off()
304     """%DicoPath['arbre1']
305     
306     txt += """
307     tree_cut1 <- make_dendro_cut_tuple(tree_tot1$dendro_tuple, chd.result$coord_ok, classeuce1, 1, nbt)
308     tree.cut1 <- tree_cut1
309     save(tree.cut1, file="%s")
310     open_file_graph("%s", width = 600, height=400)
311     classes<-n1[,ncol(n1)]
312     plot.dendropr(tree_cut1$tree.cl,classes, histo = TRUE)
313     """ % (DicoPath['Rdendro'],DicoPath['dendro1'])
314     
315     txt += """
316     save.image(file="%s")
317     """ % DicoPath['RData']
318     fileout = open(DicoPath['Rchdquest'], 'w')
319     fileout.write(txt)
320     fileout.close()
321     
322 def AlcesteTxtProf(DictChdTxtOut, RscriptsPath, clnb, taillecar):
323     txt = "clnb<-%i\n" % clnb
324     txt += """
325 source("%s")
326 load("%s")
327 """ % (RscriptsPath['chdfunct'], DictChdTxtOut['RData'])
328     txt += """
329 dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
330 datasup<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
331 dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
332 """ % (DictChdTxtOut['Contout'], DictChdTxtOut['ContSupOut'], DictChdTxtOut['ContEtOut'])
333     txt += """
334 tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
335 tablesqrpsup<-BuildProf(as.matrix(datasup),n1,clnb)
336 tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
337 """
338     txt += """
339 PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s",tablesqrpsup[4],tablesqrpsup[5])
340 """ % (DictChdTxtOut['PROFILE_OUT'], DictChdTxtOut['ANTIPRO_OUT'])
341     txt += """
342 colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
343 colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
344 colnames(tablesqrpsup[[2]])<-paste('classe',1:clnb,sep=' ')
345 colnames(tablesqrpsup[[1]])<-paste('classe',1:clnb,sep=' ')
346 colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
347 colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
348 chistabletot<-rbind(tablesqrpact[2][[1]],tablesqrpsup[2][[1]])
349 chistabletot<-rbind(chistabletot,tablesqrpet[2][[1]])
350 ptabletot<-rbind(tablesqrpact[1][[1]],tablesqrpet[1][[1]])
351 """
352     txt += """
353 write.csv2(chistabletot,file="%s")
354 write.csv2(ptabletot,file="%s")
355 gbcluster<-n1
356 write.csv2(gbcluster,file="%s")
357 """ % (DictChdTxtOut['chisqtable'], DictChdTxtOut['ptable'], DictChdTxtOut['SbyClasseOut'])
358     if clnb > 2 :
359         txt += """
360     library(ca)
361     colnames(dataact)<-paste('classe',1:clnb,sep=' ')
362     colnames(datasup)<-paste('classe',1:clnb,sep=' ')
363     colnames(dataet)<-paste('classe',1:clnb,sep=' ')
364     rowtot<-nrow(dataact)+nrow(dataet)+nrow(datasup)
365     afctable<-rbind(as.matrix(dataact),as.matrix(datasup))
366     afctable<-rbind(afctable,as.matrix(dataet))
367     colnames(afctable)<-paste('classe',1:clnb,sep=' ')
368     afc<-ca(afctable,suprow=((nrow(dataact)+1):rowtot),nd=(ncol(afctable)-1))
369     debsup<-nrow(dataact)+1
370     debet<-nrow(dataact)+nrow(datasup)+1
371     fin<-rowtot
372     afc<-AddCorrelationOk(afc)
373     """
374     #FIXME : split this!!!
375         txt += """
376     source("%s")
377     """ % RscriptsPath['Rgraph']
378     
379         txt += """
380         afc <- summary.ca.dm(afc)
381         afc_table <- create_afc_table(afc)
382         write.csv2(afc_table$facteur, file = "%s")
383         write.csv2(afc_table$colonne, file = "%s")
384         write.csv2(afc_table$ligne, file = "%s")
385         """ % (DictChdTxtOut['afc_facteur'], DictChdTxtOut['afc_col'], DictChdTxtOut['afc_row'])
386     
387         txt += """
388     PARCEX<-%s
389     """ % taillecar
390         txt += """
391     xyminmax <- PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
392     """ % (DictChdTxtOut['AFC2DL_OUT'])
393         txt += """
394     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])
395     """ % (DictChdTxtOut['AFC2DSL_OUT'])
396         txt += """
397     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])
398     """ % (DictChdTxtOut['AFC2DEL_OUT'])
399         txt += """
400     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])
401     """ % (DictChdTxtOut['AFC2DCL_OUT'])
402 #        txt += """
403  #   PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
404  #   PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debsup, fin=(debet-1), xlab = xlab, ylab = ylab)
405   #  PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debet, fin=fin, xlab = xlab, ylab = ylab)
406  #   PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col=TRUE, what='crl', xlab = xlab, ylab = ylab)
407  #   """ % (DictChdTxtOut['AFC2DCoul'], DictChdTxtOut['AFC2DCoulSup'], DictChdTxtOut['AFC2DCoulEt'], DictChdTxtOut['AFC2DCoulCl'])
408        
409     txt += """
410 #rm(dataact)
411 #rm(datasup)
412 #rm(dataet)
413 rm(tablesqrpact)
414 rm(tablesqrpsup)
415 rm(tablesqrpet)
416 save.image(file="%s")
417 """ % DictChdTxtOut['RData']
418     file = open(DictChdTxtOut['RTxtProfGraph'], 'w')
419     file.write(txt)
420     file.close()
421
422
423 def write_afc_graph(self):
424     if self.param['over'] : over = 'TRUE'
425     else : over = 'FALSE'
426
427     if self.param['do_select_nb'] : do_select_nb = 'TRUE'
428     else : do_select_nb = 'FALSE'
429
430     if self.param['do_select_chi'] : do_select_chi = 'TRUE'
431     else : do_select_chi = 'FALSE'
432
433     if self.param['do_select_chi_classe'] : do_select_chi_classe = 'TRUE'
434     else : do_select_chi_classe = 'FALSE'
435
436     if self.param['cex_txt'] : cex_txt = 'TRUE'
437     else : cex_txt = 'FALSE'
438
439     if self.param['tchi'] : tchi = 'TRUE'
440     else : tchi = 'FALSE'
441
442     if self.param['svg'] : svg = 'TRUE'
443     else : svg = 'FALSE'
444
445     with open(self.RscriptsPath['afc_graph'], 'r') as f:
446         txt = f.read()
447
448 #    self.DictPathOut['RData'], \
449     scripts = txt % (self.RscriptsPath['Rgraph'],\
450     self.param['typegraph'], \
451     self.param['what'], \
452     self.param['facteur'][0],\
453     self.param['facteur'][1], \
454     self.param['facteur'][2], \
455     self.param['qui'], \
456     over,  do_select_nb, \
457     self.param['select_nb'],  \
458     do_select_chi, \
459     self.param['select_chi'], \
460     do_select_chi_classe, \
461     self.param['nbchic'], \
462     cex_txt, \
463     self.param['txt_min'], \
464     self.param['txt_max'], \
465     self.fileout, \
466     self.param['width'], \
467     self.param['height'],\
468     self.param['taillecar'], \
469     self.param['alpha'], \
470     self.param['film'], \
471     tchi,\
472     self.param['tchi_min'],\
473     self.param['tchi_max'],\
474     ffr(os.path.dirname(self.fileout)),\
475     svg)
476     return scripts
477         
478 def print_simi3d(self):
479     simi3d = self.parent.simi3dpanel
480     txt = '#Fichier genere par Iramuteq'
481     if simi3d.movie.GetValue() :
482         movie = "'" + ffr(os.path.dirname(self.DictPathOut['RData'])) + "'"
483     else :
484         movie = 'NULL'
485     
486     #if self.corpus.parametres['type'] == 'corpus' :
487     #    header = 'TRUE'
488     #else :
489     #    header = 'FALSE'
490     header = 'FALSE'
491     txt += """
492     dm<-read.csv2("%s",row.names=1,header = %s)
493     load("%s")
494     """ % (self.DictPathOut['Contout'], header, self.DictPathOut['RData'])
495     
496     txt += """
497     source("%s")
498     """ % self.parent.RscriptsPath['Rgraph']
499
500
501     txt += """
502     make.simi.afc(dm,chistabletot, lim=%i, alpha = %.2f, movie = %s)
503     """ % (simi3d.spin_1.GetValue(), float(simi3d.slider_1.GetValue())/100, movie)
504     tmpfile = tempfile.mktemp(dir=self.parent.TEMPDIR)
505     tmp = open(tmpfile,'w')
506     tmp.write(txt)
507     tmp.close()
508     return tmpfile
509
510 def dendroandbarplot(table, rownames, colnames, rgraph, tmpgraph, intxt = False, dendro=False) :
511     if not intxt :
512         txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
513     rownb = len(rownames)
514     rownames = 'c("' + '","'.join(rownames) + '")'
515     colnames = 'c("' + '","'.join(colnames) + '")'
516     if not intxt :
517         #FIXME
518         txt = """
519             di <- matrix(data=%s, nrow=%i, byrow = TRUE)
520             rownames(di)<- %s
521             colnames(di) <- %s
522         """ % (txttable, rownb, rownames, colnames)
523     else :
524         txt = intxt
525     txt += """
526         load("%s")
527         library(ape)
528         source("%s")
529         height <- (30*ncol(di)) + (15*nrow(di))
530         height <- ifelse(height <= 400, 400, height)
531         width <- 500
532         open_file_graph("%s", width=width, height=height)
533         plot.dendro.lex(tree.cut1$tree.cl, di)
534         """ % (ffr(dendro),ffr(rgraph),  ffr(tmpgraph))
535     return txt
536
537 def barplot(table, rownames, colnames, rgraph, tmpgraph, intxt = False) :
538     if not intxt :
539         txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
540     #width = 100 + (15 * len(rownames)) + (100 * len(colnames))
541     #height =  len(rownames) * 15
542     rownb = len(rownames)
543     #if height < 400 :
544     #    height = 400
545     rownames = 'c("' + '","'.join(rownames) + '")'
546     colnames = 'c("' + '","'.join(colnames) + '")'
547     if not intxt :
548         #FIXME
549         txt = """
550             di <- matrix(data=%s, nrow=%i, byrow = TRUE)
551             toinf <- which(di == Inf)
552             tominf <- which(di == -Inf)
553             if (length(toinf)) {
554                 di[toinf] <- NA
555                 valmax <- max(di, na.rm = TRUE)
556                 if (valmax <= 0) {
557                     valmax <- 2
558                 } else {
559                     valmax <- valmax + 2
560                 }
561                 di[toinf] <- valmax
562             }
563             if (length(tominf)) {
564                 di[tominf] <- NA
565                 valmin <- min(di, na.rm = TRUE)
566                 if (valmin >=0) {
567                     valmin <- -2
568                 } else {
569                     valmin <- valmin - 2
570                 }
571                 di[tominf] <- valmin
572             }
573             rownames(di)<- %s
574             colnames(di) <- %s
575         """ % (txttable, rownb, rownames, colnames)
576     else :
577         txt = intxt
578     txt += """
579         source("%s")
580         color = rainbow(nrow(di))
581         width <- 100 + (20*length(rownames(di))) + (100 * length(colnames(di)))
582         height <- nrow(di) * 15
583         if (height < 400) { height <- 400}
584         open_file_graph("%s",width = width, height = height)
585         par(mar=c(0,0,0,0))
586             layout(matrix(c(1,2),1,2, byrow=TRUE),widths=c(3,lcm(7)))
587         par(mar=c(2,2,1,0))
588         yp = ifelse(length(toinf), 0.2, 0)
589         ym = ifelse(length(tominf), 0.2, 0)
590         ymin <- ifelse(!length(which(di < 0)), 0, min(di) - ym)
591         coord <- barplot(as.matrix(di), beside = TRUE, col = color, space = c(0.1,0.6), ylim=c(ymin, max(di) + yp))
592         if (length(toinf)) {
593             coordinf <- coord[toinf]
594             valinf <- di[toinf]
595             text(x=coordinf, y=valinf + 0.1, 'i')
596         }
597         if (length(tominf)) {
598             coordinf <- coord[toinf]
599             valinf <- di[toinf]
600             text(x=coordinf, y=valinf - 0.1, 'i')
601         }            
602         c <- colMeans(coord)
603         c1 <- c[-1]
604         c2 <- c[-length(c)]
605         cc <- cbind(c1,c2)
606         lcoord <- apply(cc, 1, mean)
607         abline(v=lcoord)
608         if (min(di) < 0) {
609             amp <- abs(max(di) - min(di))
610         } else {
611             amp <- max(di)
612         }
613         if (amp < 10) {
614             d <- 2
615         } else {
616             d <- signif(amp%%/%%10,1)
617         }
618         mn <- round(min(di))
619         mx <- round(max(di))
620         for (i in mn:mx) {
621             if ((i/d) == (i%%/%%d)) { 
622                 abline(h=i,lty=3)
623             }
624         }
625         par(mar=c(0,0,0,0))
626         plot(0, axes = FALSE, pch = '')
627         legend(x = 'center' , rownames(di), fill = color)
628         dev.off()
629         """ % (rgraph, ffr(tmpgraph))    
630     return txt
631
632 #def RAfcUci(DictAfcUciOut, nd=2, RscriptsPath='', PARCEX='0.8'):
633 #    txt = """
634 #    library(ca)
635 #    nd<-%i
636 #    """ % nd
637 #    txt += """
638 #    dataact<-read.csv2("%s")
639 #    """ % (DictAfcUciOut['TableCont'])#, encoding)
640 #    txt += """
641 #    datasup<-read.csv2("%s")
642 #    """ % (DictAfcUciOut['TableSup'])#, encoding)
643 #    txt += """
644 #    dataet<-read.csv2("%s")
645 #    """ % (DictAfcUciOut['TableEt'])#, encoding)
646 #    txt += """
647 #    datatotsup<-cbind(dataact,datasup)
648 #    datatotet<-cbind(dataact,dataet)
649 #    afcact<-ca(dataact,nd=nd)
650 #    afcsup<-ca(datatotsup,supcol=((ncol(dataact)+1):ncol(datatotsup)),nd=nd)
651 #    afcet<-ca(datatotet,supcol=((ncol(dataact)+1):ncol(datatotet)),nd=nd)
652 #    afctot<-afcsup$colcoord
653 #    rownames(afctot)<-afcsup$colnames
654 #    colnames(afctot)<-paste('coord. facteur',1:nd,sep=' ')
655 #    afctot<-cbind(afctot,mass=afcsup$colmass)
656 #    afctot<-cbind(afctot,distance=afcsup$coldist)
657 #    afctot<-cbind(afctot,intertie=afcsup$colinertia)
658 #    rcolet<-afcet$colsup
659 #    afctmp<-afcet$colcoord[rcolet,]
660 #    rownames(afctmp)<-afcet$colnames[rcolet]
661 #    afctmp<-cbind(afctmp,afcet$colmass[rcolet])
662 #    afctmp<-cbind(afctmp,afcet$coldist[rcolet])
663 #    afctmp<-cbind(afctmp,afcet$colinertia[rcolet])
664 #    afctot<-rbind(afctot,afctmp)
665 #    write.csv2(afctot,file = "%s")
666 #    source("%s")
667 #    """ % (DictAfcUciOut['afc_row'], RscriptsPath['Rgraph'])
668 #    txt += """
669 #    PARCEX=%s
670 #    """ % PARCEX
671 #    #FIXME
672 #    txt += """
673 #    PlotAfc(afcet,filename="%s",toplot=c%s, PARCEX=PARCEX)
674 #    """ % (DictAfcUciOut['AfcColAct'], "('none','active')")
675 #    txt += """
676 #    PlotAfc(afcsup,filename="%s",toplot=c%s, PARCEX=PARCEX)
677 #    """ % (DictAfcUciOut['AfcColSup'], "('none','passive')")
678 #    txt += """PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
679 #    """ % (DictAfcUciOut['AfcColEt'], "('none','passive')")
680 #    txt += """
681 #    PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
682 #    """ % (DictAfcUciOut['AfcRow'], "('all','none')")
683 #    f = open(DictAfcUciOut['Rafcuci'], 'w')
684 #    f.write(txt)
685 #    f.close()
686
687 class PrintSimiScript(PrintRScript) :
688     def make_script(self) :
689         self.txtgraph = ''
690         self.packages(['igraph', 'proxy', 'Matrix'])
691         self.sources([self.analyse.parent.RscriptsPath['simi'], self.analyse.parent.RscriptsPath['Rgraph']])
692         txt = ''
693         if not self.parametres['keep_coord'] and not self.parametres['type'] == 'simimatrix':
694             txt += """
695             dm.path <- "%s"
696             cn.path <- "%s"
697             selected.col <- "%s"
698             """ % (self.pathout['mat01.csv'], self.pathout['actives.csv'], self.pathout['selected.csv'])
699             if 'word' in self.parametres :
700                 txt += """
701                 word <- TRUE
702                 index <- %i + 1
703                 """ % self.parametres['word']
704             else :
705                 txt += """
706                 word <- FALSE
707                 """
708             txt += """
709             dm <-readMM(dm.path)
710             cn <- read.table(cn.path, sep='\t', quote='"')
711             colnames(dm) <- cn[,1]
712             sel.col <- read.csv2(selected.col, header = FALSE)
713             sel.col <- sel.col[,1] + 1
714             if (!word) {
715                 dm <- dm[, sel.col]
716             } else {
717                 forme <- colnames(dm)[index]
718                 if (!index %in% sel.col) {
719                     sel.col <- append(sel.col, index)
720                 }
721                 dm <- dm[, sel.col]
722                 index <- which(colnames(dm) == forme)
723             }
724             """
725         elif not self.parametres['keep_coord'] and self.parametres['type'] == 'simimatrix' :
726             txt += """
727             dm.path <- "%s"
728             selected.col <- "%s"
729             """ % (self.pathout['mat01.csv'], self.pathout['selected.csv'])
730             if 'word' in self.parametres :
731                 txt += """
732                 word <- TRUE
733                 index <- %i + 1
734                 """ % self.parametres['word']
735             else :
736                 txt += """
737                 word <- FALSE
738                 """
739             txt += """
740             dm <-read.csv2(dm.path)
741             dm <- as.matrix(dm)
742             sel.col <- read.csv2(selected.col, header = FALSE)
743             sel.col <- sel.col[,1] + 1
744             if (!word) {
745                 dm <- dm[, sel.col]
746             } else {
747                 forme <- colnames(dm)[index]
748                 if (!index %in% sel.col) {
749                     sel.col <- append(sel.col, index)
750                 }
751                 dm <- dm[, sel.col]
752                 index <- which(colnames(dm) == forme)
753             }
754             """
755         else :
756             txt += """
757             load("%s")
758             """ % self.pathout['RData.RData']
759         
760         if self.parametres['coeff'] == 0 :
761             method = 'cooc'
762             if not self.parametres['keep_coord'] :
763                 txt += """
764                 method <- 'cooc'
765                 mat <- make.a(dm)
766                 """
767         else :
768             if not self.parametres['keep_coord'] :
769                 txt += """
770                 dm <- as.matrix(dm)
771                 """
772         if self.parametres['coeff'] == 1 :
773             method = 'prcooc'
774             txt += """
775             method <- 'Russel'
776             mat <- simil(dm, method = 'Russel', diag = TRUE, upper = TRUE, by_rows = FALSE)
777             """
778         elif self.analyse.indices[self.parametres['coeff']] == 'binomial' :
779             method = 'binomial'
780             if not self.parametres['keep_coord'] :
781                 txt += """
782                 method <- 'binomial'
783                 mat <- binom.sim(dm)
784                 """
785         elif self.parametres['coeff'] != 0 :
786             method = self.analyse.indices[self.parametres['coeff']]
787             if not self.parametres['keep_coord'] :
788                 txt += """
789                 method <-"%s"
790                 mat <- simil(dm, method = method, diag = TRUE, upper = TRUE, by_rows = FALSE)
791                 """ % self.analyse.indices[self.parametres['coeff']]
792         if not self.parametres['keep_coord'] :
793             txt += """
794             mat <- as.matrix(stats::as.dist(mat,diag=TRUE,upper=TRUE))
795             mat[is.na(mat)] <- 0
796             if (length(which(mat == Inf))) {
797                 infp <- which(mat == Inf)
798                 mat[infp] <- NA
799                 maxmat <- max(mat, na.rm = TRUE)
800                 if (maxmat > 0) {
801                 maxmat <- maxmat + 1
802                 } else {
803                     maxmat <- 0
804                 }
805                 mat[infp] <- maxmat
806             }
807             if (length(which(mat == -Inf))) {
808                 infm <- which(mat == -Inf)
809                 mat[infm] <- NA
810                 minmat <- min(mat, na.rm = TRUE)
811                 if (maxmat < 0) {
812                 minmat <- minmat - 1
813                 } else {
814                     minmat <- 0
815                 }
816                 mat[infm] <- minmat
817             }
818             """
819         if 'word' in self.parametres and not self.parametres['keep_coord'] :
820             txt += """
821             mat <- graph.word(mat, index)
822             cs <- colSums(mat)
823             if (length(cs)) mat <- mat[,-which(cs==0)]
824             rs <- rowSums(mat)
825             if (length(rs)) mat <- mat[-which(rs==0),]
826             if (length(cs)) dm <- dm[, -which(cs==0)]
827             """
828
829         if self.parametres['layout'] == 0 : layout = 'random'
830         if self.parametres['layout'] == 1 : layout = 'circle'
831         if self.parametres['layout'] == 2 : layout = 'frutch'
832         if self.parametres['layout'] == 3 : layout = 'kawa'
833         if self.parametres['layout'] == 4 : layout = 'graphopt'
834
835
836         self.filename=''
837         if self.parametres['type_graph'] == 0 : type = 'tkplot'
838         if self.parametres['type_graph'] == 1 : 
839             graphnb = 1
840             type = 'nplot'
841             dirout = os.path.dirname(self.pathout['mat01'])
842             while os.path.exists(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png')):
843                 graphnb +=1
844             self.filename = ffr(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png'))
845         if self.parametres['type_graph'] == 2 : type = 'rgl'
846
847         if self.parametres['arbremax'] : 
848             arbremax = 'TRUE'
849             self.txtgraph += ' - arbre maximum'
850         else : arbremax = 'FALSE'
851         
852         if self.parametres['coeff_tv'] : 
853             coeff_tv = self.parametres['coeff_tv_nb']
854             tvminmax = 'c(NULL,NULL)'
855         elif not self.parametres['coeff_tv'] or self.parametres.get('sformchi', False) :
856             coeff_tv = 'NULL'
857             tvminmax = 'c(%i, %i)' %(self.parametres['tvmin'], self.parametres['tvmax'])
858         if self.parametres['coeff_te'] : coeff_te = 'c(%i,%i)' % (self.parametres['coeff_temin'], self.parametres['coeff_temax'])
859         else : coeff_te = 'NULL'
860         
861         if self.parametres['vcex'] or self.parametres.get('cexfromchi', False) :
862             vcexminmax = 'c(%i/10,%i/10)' % (self.parametres['vcexmin'],self.parametres['vcexmax'])
863         else :
864             vcexminmax = 'c(NULL,NULL)'
865         if not self.parametres['label_v'] : label_v = 'FALSE'
866         else : label_v = 'TRUE'
867
868         if not self.parametres['label_e'] : label_e = 'FALSE'
869         else : label_e = 'TRUE'
870         
871         if self.parametres['seuil_ok'] : seuil = str(self.parametres['seuil'])
872         else : seuil = 'NULL'
873             
874         cols = str(self.parametres['cols']).replace(')',', max=255)')
875         cola = str(self.parametres['cola']).replace(')',',max=255)')
876
877         txt += """
878         minmaxeff <- %s
879         """ % tvminmax
880         txt += """
881         vcexminmax <- %s
882         """ % vcexminmax
883         txt += """
884         cex = %i/10
885         """ % self.parametres['cex']
886
887         if self.parametres['film'] : 
888             txt += """
889             film <- "%s"
890             """ % self.pathout['film']
891         else : 
892             txt += """
893             film <- NULL
894             """
895         txt += """
896         seuil <- %s
897         """ % seuil
898         
899         txt += """
900         label.v <- %s
901         label.e <- %s
902         """ % (label_v, label_e)
903         txt += """
904         cols <- rgb%s
905         cola <- rgb%s
906         """ % (cols, cola)
907         txt += """
908         width <- %i
909         height <- %i
910         """ % (self.parametres['width'], self.parametres['height'])
911         if self.parametres['keep_coord'] :
912             txt += """
913             coords <- try(coords, TRUE)
914             if (!is.matrix(coords)) {
915                 coords<-NULL
916             }
917             """
918         else :
919             txt += """
920             coords <- NULL
921             """
922         txt += """
923         alpha <- %i/100
924         """ % self.parametres['alpha']
925         txt += """
926         alpha <- %i/100
927         """ % self.parametres['alpha']
928 #############################################
929         if  self.parametres.get('bystar',False) :
930             txt += """
931             et <- list()
932             """
933             for i, line in enumerate(self.parametres['listet']) :
934                 txt+= """
935                 et[[%i]] <- c(%s)
936                 """ % (i+1, ','.join([`val + 1` for val in line]))
937             txt+= """
938             unetoile <- c('%s')
939             """ % ("','".join([val for val in self.parametres['selectedstars']]))
940             txt += """
941             fsum <- NULL
942             rs <- rowSums(dm)
943             for (i in 1:length(unetoile)) {
944                 print(unetoile[i])
945                 tosum <- et[[i]]
946                 if (length(tosum) > 1) {
947                     fsum <- cbind(fsum, colSums(dm[tosum,]))
948                 } else {
949                     fsum <- cbind(fsum, dm[tosum,])
950                 }
951             }
952             source("%s")
953             lex <- AsLexico2(fsum, chip=TRUE)
954             dcol <- apply(lex[[4]],1,which.max)
955             toblack <- apply(lex[[4]],1,max)
956             gcol <- rainbow(length(unetoile))
957             #gcol[2] <- 'orange'
958             vertex.label.color <- gcol[dcol]
959             vertex.label.color[which(toblack <= 3.84)] <- 'black'
960             leg <- list(unetoile=unetoile, gcol=gcol)  
961             cols <- vertex.label.color
962             chivertex.size <- norm.vec(toblack, vcexminmax[1],  vcexminmax[2])
963             
964             """ % (self.analyse.parent.RscriptsPath['chdfunct'])
965         else :
966             txt += """
967             vertex.label.color <- 'black' 
968             chivertex.size <- 1
969             leg<-NULL
970             """
971 #############################################        
972
973 #        txt += """
974 #        eff <- colSums(dm)
975 #        g.ori <- graph.adjacency(mat, mode='lower', weighted = TRUE)
976 #        w.ori <- E(g.ori)$weight
977 #        if (max.tree) {
978 #            if (method == 'cooc') {
979 #                E(g.ori)$weight <- 1 / w.ori
980 #            } else {
981 #                E(g.ori)$weigth <- 1 - w.ori
982 #            }
983 #            g.max <- minimum.spanning.tree(g.ori)
984 #            if (method == 'cooc') {
985 #                E(g.max)$weight <- 1 / E(g.max)$weight
986 #            } else {
987 #                E(g.max)$weight <- 1 - E(g.max)$weight
988 #            }
989 #            g.toplot <- g.max
990 #        } else {
991 #            g.toplot <- g.ori
992 #        }
993 #        """
994         if self.parametres['com'] :
995             com = `self.parametres['communities']`
996         else :
997             com = 'NULL'
998         if self.parametres['halo'] :
999             halo = 'TRUE'
1000         else :
1001             halo = 'FALSE'
1002         txt += """
1003         communities <- %s
1004         halo <- %s
1005         """ % (com, halo)
1006         txt += """
1007         eff <- colSums(dm)
1008         x <- list(mat = mat, eff = eff)
1009         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)
1010         """ % (method, type, layout, arbremax, coeff_tv, coeff_te)
1011             
1012         if self.parametres.get('bystar',False) :
1013             if self.parametres.get('cexfromchi', False) :
1014                 txt+="""
1015                     label.cex<-chivertex.size
1016                     """
1017             else :
1018                 txt+="""
1019                 label.cex <- NULL
1020                 """
1021             if self.parametres.get('sfromchi', False) :
1022                 txt += """
1023                 vertex.size <- norm.vec(toblack, minmaxeff[1], minmaxeff[2])
1024                 """
1025             else :
1026                 txt += """
1027                 vertex.size <- NULL
1028                 """
1029         else :
1030             if self.parametres['type'] == 'clustersimitxt' : 
1031                 txt += """
1032                 lchi <- read.table("%s")
1033                 lchi <- lchi[,1]
1034                 """ % ffr(self.parametres['tmpchi'])
1035                 txt += """
1036                     lchi <- lchi[sel.col]
1037                     """
1038             if self.parametres['type'] == 'clustersimitxt' and self.parametres.get('cexfromchi', False) :
1039                 txt += """ 
1040                 label.cex <- norm.vec(lchi, vcexminmax[1], vcexminmax[2])
1041                 """
1042             else :
1043                 txt += """
1044             if (is.null(vcexminmax[1])) {
1045                 label.cex <- NULL
1046             } else {
1047                 label.cex <- graph.simi$label.cex
1048             }
1049             """
1050             if self.parametres['type'] == 'clustersimitxt' and self.parametres.get('sfromchi', False) :
1051                 txt += """ 
1052                 vertex.size <- norm.vec(lchi, minmaxeff[1], minmaxeff[2])
1053                 if (!length(vertex.size)) vertex.size <- 0
1054                 """
1055             else :
1056                 txt += """
1057             if (is.null(minmaxeff[1])) {
1058                 vertex.size <- 0
1059             } else {
1060                 vertex.size <- graph.simi$eff
1061             }
1062             """
1063         #txt += """ vertex.size <- NULL """
1064         if self.parametres['svg'] : svg = 'TRUE'
1065         else : svg = 'FALSE'
1066         txt += """
1067         svg <- %s
1068         """ % svg
1069         txt += """
1070         vertex.col <- cols
1071         if (!is.null(graph.simi$com)) {
1072             com <- graph.simi$com
1073             colm <- rainbow(length(com))
1074             if (vertex.size != 0 || graph.simi$halo) {
1075                 vertex.label.color <- 'black'
1076                 vertex.col <- colm[membership(com)]
1077             } else {
1078                 vertex.label.color <- colm[membership(com)]
1079             }
1080         }
1081         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, svg = svg)
1082         save.image(file="%s")
1083         """ % (type, self.filename, self.pathout['RData'])
1084         
1085         self.add(txt)
1086         self.write()
1087
1088 class WordCloudRScript(PrintRScript) :
1089     def make_script(self) :
1090         self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
1091         self.packages(['wordcloud'])
1092         bg_col = Rcolor(self.parametres['col_bg'])
1093         txt_col = Rcolor(self.parametres['col_text'])
1094         txt = """
1095         act <- read.csv2("%s", header = FALSE, row.names=1, sep='\t')
1096         selected.col <- read.table("%s")
1097         toprint <- as.matrix(act[selected.col[,1] + 1,])
1098         rownames(toprint) <- rownames(act)[selected.col[,1] + 1]
1099         maxword <- %i
1100         if (nrow(toprint) > maxword) {
1101             toprint <- as.matrix(toprint[order(toprint[,1], decreasing=TRUE),])
1102             toprint <- as.matrix(toprint[1:maxword,])
1103         }
1104         open_file_graph("%s", width = %i, height = %i)
1105         par(bg=rgb%s)
1106         wordcloud(row.names(toprint), toprint[,1], scale=c(%f,%f), random.order=FALSE, colors=rgb%s)
1107         dev.off()
1108         """ % (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)
1109         self.add(txt)
1110         self.write()