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