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