textometrieR
[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['Act01'], 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     """ % taillecar
382         txt += """
383     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)
384     """ % (DictChdTxtOut['AFC2DL_OUT'])
385         txt += """
386     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)
387     """ % (DictChdTxtOut['AFC2DSL_OUT'])
388         txt += """
389     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)
390     """ % (DictChdTxtOut['AFC2DEL_OUT'])
391         txt += """
392     PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col=TRUE, what='coord', xlab = xlab, ylab = ylab, xmin=xmin, xmax=xmax, ymin = ymin, ymax=ymax)
393     """ % (DictChdTxtOut['AFC2DCL_OUT'])
394 #        txt += """
395  #   PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=1, fin=(debsup-1), xlab = xlab, ylab = ylab)
396  #   PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debsup, fin=(debet-1), xlab = xlab, ylab = ylab)
397   #  PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debet, fin=fin, xlab = xlab, ylab = ylab)
398  #   PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col=TRUE, what='crl', xlab = xlab, ylab = ylab)
399  #   """ % (DictChdTxtOut['AFC2DCoul'], DictChdTxtOut['AFC2DCoulSup'], DictChdTxtOut['AFC2DCoulEt'], DictChdTxtOut['AFC2DCoulCl'])
400        
401     txt += """
402 #rm(dataact)
403 #rm(datasup)
404 #rm(dataet)
405 rm(tablesqrpact)
406 rm(tablesqrpsup)
407 rm(tablesqrpet)
408 save.image(file="%s")
409 """ % DictChdTxtOut['RData']
410     file = open(DictChdTxtOut['RTxtProfGraph'], 'w')
411     file.write(txt)
412     file.close()
413
414
415 def write_afc_graph(self):
416     if self.param['over'] : over = 'TRUE'
417     else : over = 'FALSE'
418
419     if self.param['do_select_nb'] : do_select_nb = 'TRUE'
420     else : do_select_nb = 'FALSE'
421
422     if self.param['do_select_chi'] : do_select_chi = 'TRUE'
423     else : do_select_chi = 'FALSE'
424
425     if self.param['do_select_chi_classe'] : do_select_chi_classe = 'TRUE'
426     else : do_select_chi_classe = 'FALSE'
427
428     if self.param['cex_txt'] : cex_txt = 'TRUE'
429     else : cex_txt = 'FALSE'
430
431     if self.param['tchi'] : tchi = 'TRUE'
432     else : tchi = 'FALSE'
433
434     with open(self.RscriptsPath['afc_graph'], 'r') as f:
435         txt = f.read()
436
437 #    self.DictPathOut['RData'], \
438     scripts = txt % (self.RscriptsPath['Rgraph'],\
439     self.param['typegraph'], \
440     self.param['what'], \
441     self.param['facteur'][0],\
442     self.param['facteur'][1], \
443     self.param['facteur'][2], \
444     self.param['qui'], \
445     over,  do_select_nb, \
446     self.param['select_nb'],  \
447     do_select_chi, \
448     self.param['select_chi'], \
449     do_select_chi_classe, \
450     self.param['nbchic'], \
451     cex_txt, \
452     self.param['txt_min'], \
453     self.param['txt_max'], \
454     self.fileout, \
455     self.param['width'], \
456     self.param['height'],\
457     self.param['taillecar'], \
458     self.param['alpha'], \
459     self.param['film'], \
460     tchi,\
461     self.param['tchi_min'],\
462     self.param['tchi_max'],\
463     ffr(os.path.dirname(self.fileout)))
464     return scripts
465         
466 def print_simi3d(self):
467     simi3d = self.parent.simi3dpanel
468     txt = '#Fichier genere par Iramuteq'
469     if simi3d.movie.GetValue() :
470         movie = "'" + ffr(os.path.dirname(self.DictPathOut['RData'])) + "'"
471     else :
472         movie = 'NULL'
473     
474     #if self.corpus.parametres['type'] == 'corpus' :
475     #    header = 'TRUE'
476     #else :
477     #    header = 'FALSE'
478     header = 'FALSE'
479     txt += """
480     dm<-read.csv2("%s",row.names=1,header = %s)
481     load("%s")
482     """ % (self.DictPathOut['Contout'], header, self.DictPathOut['RData'])
483     
484     txt += """
485     source("%s")
486     """ % self.parent.RscriptsPath['Rgraph']
487
488
489     txt += """
490     make.simi.afc(dm,chistabletot, lim=%i, alpha = %.2f, movie = %s)
491     """ % (simi3d.spin_1.GetValue(), float(simi3d.slider_1.GetValue())/100, movie)
492     tmpfile = tempfile.mktemp(dir=self.parent.TEMPDIR)
493     tmp = open(tmpfile,'w')
494     tmp.write(txt)
495     tmp.close()
496     return tmpfile
497
498 def dendroandbarplot(table, rownames, colnames, rgraph, tmpgraph, intxt = False, dendro=False) :
499     if not intxt :
500         txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
501     rownb = len(rownames)
502     rownames = 'c("' + '","'.join(rownames) + '")'
503     colnames = 'c("' + '","'.join(colnames) + '")'
504     if not intxt :
505         #FIXME
506         txt = """
507             di <- matrix(data=%s, nrow=%i, byrow = TRUE)
508             rownames(di)<- %s
509             colnames(di) <- %s
510         """ % (txttable, rownb, rownames, colnames)
511     else :
512         txt = intxt
513     txt += """
514         load("%s")
515         library(ape)
516         source("%s")
517         height <- (30*ncol(di)) + (15*nrow(di))
518         height <- ifelse(height <= 400, 400, height)
519         width <- 500
520         open_file_graph("%s", width=width, height=height)
521         plot.dendro.lex(tree.cut1$tree.cl, di)
522         """ % (ffr(dendro),ffr(rgraph),  ffr(tmpgraph))
523     return txt
524
525 def barplot(table, rownames, colnames, rgraph, tmpgraph, intxt = False) :
526     if not intxt :
527         txttable = 'c(' + ','.join([','.join(line) for line in table]) + ')'
528     #width = 100 + (15 * len(rownames)) + (100 * len(colnames))
529     #height =  len(rownames) * 15
530     rownb = len(rownames)
531     #if height < 400 :
532     #    height = 400
533     rownames = 'c("' + '","'.join(rownames) + '")'
534     colnames = 'c("' + '","'.join(colnames) + '")'
535     if not intxt :
536         #FIXME
537         txt = """
538             di <- matrix(data=%s, nrow=%i, byrow = TRUE)
539             toinf <- which(di == Inf)
540             tominf <- which(di == -Inf)
541             if (length(toinf)) {
542                 di[toinf] <- NA
543                 di[toinf] <- max(di, na.rm = TRUE) + 2
544             }
545             if (length(tominf)) {
546                 di[tominf] <- NA
547                 di[tominf] <- min(di, na.rm = TRUE) - 2
548             }
549             rownames(di)<- %s
550             colnames(di) <- %s
551         """ % (txttable, rownb, rownames, colnames)
552     else :
553         txt = intxt
554     txt += """
555         source("%s")
556         color = rainbow(nrow(di))
557         width <- 100 + (20*length(rownames(di))) + (100 * length(colnames(di)))
558         height <- nrow(di) * 15
559         if (height < 400) { height <- 400}
560         open_file_graph("%s",width = width, height = height)
561         par(mar=c(0,0,0,0))
562             layout(matrix(c(1,2),1,2, byrow=TRUE),widths=c(3,lcm(7)))
563         par(mar=c(2,2,1,0))
564         yp = ifelse(length(toinf), 0.2, 0)
565         ym = ifelse(length(tominf), 0.2, 0)
566         ymin <- ifelse(!length(which(di < 0)), 0, min(di) - ym)
567         coord <- barplot(as.matrix(di), beside = TRUE, col = color, space = c(0.1,0.6), ylim=c(ymin, max(di) + yp))
568         if (length(toinf)) {
569             coordinf <- coord[toinf]
570             valinf <- di[toinf]
571             text(x=coordinf, y=valinf + 0.1, 'i')
572         }
573         if (length(tominf)) {
574             coordinf <- coord[toinf]
575             valinf <- di[toinf]
576             text(x=coordinf, y=valinf - 0.1, 'i')
577         }            
578         c <- colMeans(coord)
579         c1 <- c[-1]
580         c2 <- c[-length(c)]
581         cc <- cbind(c1,c2)
582         lcoord <- apply(cc, 1, mean)
583         abline(v=lcoord)
584         if (min(di) < 0) {
585             amp <- abs(max(di) - min(di))
586         } else {
587             amp <- max(di)
588         }
589         if (amp < 10) {
590             d <- 2
591         } else {
592             d <- signif(amp%%/%%10,1)
593         }
594         mn <- round(min(di))
595         mx <- round(max(di))
596         for (i in mn:mx) {
597             if ((i/d) == (i%%/%%d)) { 
598                 abline(h=i,lty=3)
599             }
600         }
601         par(mar=c(0,0,0,0))
602         plot(0, axes = FALSE, pch = '')
603         legend(x = 'center' , rownames(di), fill = color)
604         dev.off()
605         """ % (rgraph, ffr(tmpgraph))    
606     return txt
607
608 #def RAfcUci(DictAfcUciOut, nd=2, RscriptsPath='', PARCEX='0.8'):
609 #    txt = """
610 #    library(ca)
611 #    nd<-%i
612 #    """ % nd
613 #    txt += """
614 #    dataact<-read.csv2("%s")
615 #    """ % (DictAfcUciOut['TableCont'])#, encoding)
616 #    txt += """
617 #    datasup<-read.csv2("%s")
618 #    """ % (DictAfcUciOut['TableSup'])#, encoding)
619 #    txt += """
620 #    dataet<-read.csv2("%s")
621 #    """ % (DictAfcUciOut['TableEt'])#, encoding)
622 #    txt += """
623 #    datatotsup<-cbind(dataact,datasup)
624 #    datatotet<-cbind(dataact,dataet)
625 #    afcact<-ca(dataact,nd=nd)
626 #    afcsup<-ca(datatotsup,supcol=((ncol(dataact)+1):ncol(datatotsup)),nd=nd)
627 #    afcet<-ca(datatotet,supcol=((ncol(dataact)+1):ncol(datatotet)),nd=nd)
628 #    afctot<-afcsup$colcoord
629 #    rownames(afctot)<-afcsup$colnames
630 #    colnames(afctot)<-paste('coord. facteur',1:nd,sep=' ')
631 #    afctot<-cbind(afctot,mass=afcsup$colmass)
632 #    afctot<-cbind(afctot,distance=afcsup$coldist)
633 #    afctot<-cbind(afctot,intertie=afcsup$colinertia)
634 #    rcolet<-afcet$colsup
635 #    afctmp<-afcet$colcoord[rcolet,]
636 #    rownames(afctmp)<-afcet$colnames[rcolet]
637 #    afctmp<-cbind(afctmp,afcet$colmass[rcolet])
638 #    afctmp<-cbind(afctmp,afcet$coldist[rcolet])
639 #    afctmp<-cbind(afctmp,afcet$colinertia[rcolet])
640 #    afctot<-rbind(afctot,afctmp)
641 #    write.csv2(afctot,file = "%s")
642 #    source("%s")
643 #    """ % (DictAfcUciOut['afc_row'], RscriptsPath['Rgraph'])
644 #    txt += """
645 #    PARCEX=%s
646 #    """ % PARCEX
647 #    #FIXME
648 #    txt += """
649 #    PlotAfc(afcet,filename="%s",toplot=c%s, PARCEX=PARCEX)
650 #    """ % (DictAfcUciOut['AfcColAct'], "('none','active')")
651 #    txt += """
652 #    PlotAfc(afcsup,filename="%s",toplot=c%s, PARCEX=PARCEX)
653 #    """ % (DictAfcUciOut['AfcColSup'], "('none','passive')")
654 #    txt += """PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
655 #    """ % (DictAfcUciOut['AfcColEt'], "('none','passive')")
656 #    txt += """
657 #    PlotAfc(afcet,filename="%s", toplot=c%s, PARCEX=PARCEX)
658 #    """ % (DictAfcUciOut['AfcRow'], "('all','none')")
659 #    f = open(DictAfcUciOut['Rafcuci'], 'w')
660 #    f.write(txt)
661 #    f.close()
662
663 class PrintSimiScript(PrintRScript) :
664     def make_script(self) :
665         self.txtgraph = ''
666         self.packages(['igraph', 'proxy', 'Matrix'])
667         self.sources([self.analyse.parent.RscriptsPath['simi'], self.analyse.parent.RscriptsPath['Rgraph']])
668         txt = ''
669         if not self.parametres['keep_coord'] :
670             txt += """
671             dm.path <- "%s"
672             cn.path <- "%s"
673             selected.col <- "%s"
674             """ % (self.pathout['mat01.csv'], self.pathout['actives.csv'], self.pathout['selected.csv'])
675             txt += """
676             dm <-readMM(dm.path)
677             cn <- read.table(cn.path, sep=';', quote='"')
678             colnames(dm) <- cn[,1]
679             sel.col <- read.csv2(selected.col)
680             dm <- dm[, sel.col[,1] + 1]
681             """
682         else :
683             txt += """
684             load("%s")
685             """ % self.pathout['RData.RData']
686         
687         if self.parametres['coeff'] == 0 :
688             method = 'cooc'
689             if not self.parametres['keep_coord'] :
690                 txt += """
691                 method <- 'cooc'
692                 mat <- make.a(dm)
693                 """
694         else :
695             if not self.parametres['keep_coord'] :
696                 txt += """
697                 dm <- as.matrix(dm)
698                 """
699         if self.parametres['coeff'] == 1 :
700             method = 'prcooc'
701             txt += """
702             method <- 'Russel'
703             mat <- simil(dm, method = 'Russel', diag = TRUE, upper = TRUE, by_rows = FALSE)
704             """
705         elif self.analyse.indices[self.parametres['coeff']] == 'binomial' :
706             method = 'binomial'
707             if not self.parametres['keep_coord'] :
708                 txt += """
709                 method <- 'binomial'
710                 mat <- binom.sim(dm)
711                 """
712         elif self.parametres['coeff'] != 0 :
713             method = self.analyse.indices[self.parametres['coeff']]
714             if not self.parametres['keep_coord'] :
715                 txt += """
716                 method <-"%s"
717                 mat <- simil(dm, method = method, diag = TRUE, upper = TRUE, by_rows = FALSE)
718                 """ % self.analyse.indices[self.parametres['coeff']]
719         if not self.parametres['keep_coord'] :
720             txt += """
721             mat <- as.matrix(stats::as.dist(mat,diag=TRUE,upper=TRUE))
722             mat[is.na(mat)] <- 0
723             mat[is.infinite(mat)] <- 0
724             """
725         if self.parametres['layout'] == 0 : layout = 'random'
726         if self.parametres['layout'] == 1 : layout = 'circle'
727         if self.parametres['layout'] == 2 : layout = 'frutch'
728         if self.parametres['layout'] == 3 : layout = 'kawa'
729         if self.parametres['layout'] == 4 : layout = 'graphopt'
730
731
732         self.filename=''
733         if self.parametres['type_graph'] == 0 : type = 'tkplot'
734         if self.parametres['type_graph'] == 1 : 
735             graphnb = 1
736             type = 'nplot'
737             dirout = os.path.dirname(self.pathout['mat01'])
738             while os.path.exists(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png')):
739                 graphnb +=1
740             self.filename = ffr(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png'))
741         if self.parametres['type_graph'] == 2 : type = 'rgl'
742
743         if self.parametres['arbremax'] : 
744             arbremax = 'TRUE'
745             self.txtgraph += ' - arbre maximum'
746         else : arbremax = 'FALSE'
747         
748         if self.parametres['coeff_tv'] : 
749             coeff_tv = self.parametres['coeff_tv_nb']
750             tvminmax = 'c(NULL,NULL)'
751         elif not self.parametres['coeff_tv'] or self.parametres.get('sformchi', False) :
752             coeff_tv = 'NULL'
753             tvminmax = 'c(%i, %i)' %(self.parametres['tvmin'], self.parametres['tvmax'])
754         if self.parametres['coeff_te'] : coeff_te = 'c(%i,%i)' % (self.parametres['coeff_temin'], self.parametres['coeff_temax'])
755         else : coeff_te = 'NULL'
756         
757         if self.parametres['vcex'] or self.parametres.get('cexfromchi', False) :
758             vcexminmax = 'c(%i/10,%i/10)' % (self.parametres['vcexmin'],self.parametres['vcexmax'])
759         else :
760             vcexminmax = 'c(NULL,NULL)'
761         if not self.parametres['label_v'] : label_v = 'FALSE'
762         else : label_v = 'TRUE'
763
764         if not self.parametres['label_e'] : label_e = 'FALSE'
765         else : label_e = 'TRUE'
766         
767         if self.parametres['seuil_ok'] : seuil = str(self.parametres['seuil'])
768         else : seuil = 'NULL'
769             
770         cols = str(self.parametres['cols']).replace(')',', max=255)')
771         cola = str(self.parametres['cola']).replace(')',',max=255)')
772
773         txt += """
774         minmaxeff <- %s
775         """ % tvminmax
776         txt += """
777         vcexminmax <- %s
778         """ % vcexminmax
779         txt += """
780         cex = %i/10
781         """ % self.parametres['cex']
782
783         if self.parametres['film'] : 
784             txt += """
785             film <- "%s"
786             """ % self.pathout['film']
787         else : 
788             txt += """
789             film <- NULL
790             """
791         txt += """
792         seuil <- %s
793         """ % seuil
794         
795         txt += """
796         label.v <- %s
797         label.e <- %s
798         """ % (label_v, label_e)
799         txt += """
800         cols <- rgb%s
801         cola <- rgb%s
802         """ % (cols, cola)
803         txt += """
804         width <- %i
805         height <- %i
806         """ % (self.parametres['width'], self.parametres['height'])
807         if self.parametres['keep_coord'] :
808             txt += """
809             coords <- try(coords, TRUE)
810             if (!is.matrix(coords)) {
811                 coords<-NULL
812             }
813             """
814         else :
815             txt += """
816             coords <- NULL
817             """
818         txt += """
819         alpha <- %i/100
820         """ % self.parametres['alpha']
821         txt += """
822         alpha <- %i/100
823         """ % self.parametres['alpha']
824 #############################################
825         if  self.parametres.get('bystar',False) :
826             txt += """
827             et <- list()
828             """
829             for i, line in enumerate(self.parametres['listet']) :
830                 txt+= """
831                 et[[%i]] <- c(%s)
832                 """ % (i+1, ','.join([`val + 1` for val in line]))
833             txt+= """
834             unetoile <- c('%s')
835             """ % ("','".join([val for val in self.parametres['selectedstars']]))
836             txt += """
837             fsum <- NULL
838             rs <- rowSums(dm)
839             for (i in 1:length(unetoile)) {
840                 print(unetoile[i])
841                 tosum <- et[[i]]
842                 if (length(tosum) > 1) {
843                     fsum <- cbind(fsum, colSums(dm[tosum,]))
844                 } else {
845                     fsum <- cbind(fsum, dm[tosum,])
846                 }
847             }
848             source("%s")
849             lex <- AsLexico2(fsum, chip=TRUE)
850             dcol <- apply(lex[[4]],1,which.max)
851             toblack <- apply(lex[[4]],1,max)
852             gcol <- rainbow(length(unetoile))
853             #gcol[2] <- 'orange'
854             vertex.label.color <- gcol[dcol]
855             vertex.label.color[which(toblack <= 3.84)] <- 'black'
856             leg <- list(unetoile=unetoile, gcol=gcol)  
857             cols <- vertex.label.color
858             chivertex.size <- norm.vec(toblack, vcexminmax[1],  vcexminmax[2])
859             
860             """ % (self.analyse.parent.RscriptsPath['chdfunct'])
861         else :
862             txt += """
863             vertex.label.color <- 'black' 
864             chivertex.size <- 1
865             leg<-NULL
866             """
867 #############################################        
868
869 #        txt += """
870 #        eff <- colSums(dm)
871 #        g.ori <- graph.adjacency(mat, mode='lower', weighted = TRUE)
872 #        w.ori <- E(g.ori)$weight
873 #        if (max.tree) {
874 #            if (method == 'cooc') {
875 #                E(g.ori)$weight <- 1 / w.ori
876 #            } else {
877 #                E(g.ori)$weigth <- 1 - w.ori
878 #            }
879 #            g.max <- minimum.spanning.tree(g.ori)
880 #            if (method == 'cooc') {
881 #                E(g.max)$weight <- 1 / E(g.max)$weight
882 #            } else {
883 #                E(g.max)$weight <- 1 - E(g.max)$weight
884 #            }
885 #            g.toplot <- g.max
886 #        } else {
887 #            g.toplot <- g.ori
888 #        }
889 #        """
890         txt += """
891         eff <- colSums(dm)
892         x <- list(mat = mat, eff = eff)
893         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)
894         """ % (method, type, layout, arbremax, coeff_tv, coeff_te)
895             
896         if self.parametres.get('bystar',False) :
897             if self.parametres.get('cexfromchi', False) :
898                 txt+="""
899                     label.cex<-chivertex.size
900                     """
901             else :
902                 txt+="""
903                 label.cex <- NULL
904                 """
905             if self.parametres.get('sfromchi', False) :
906                 txt += """
907                 vertex.size <- norm.vec(toblack, minmaxeff[1], minmaxeff[2])
908                 """
909             else :
910                 txt += """
911                 vertex.size <- NULL
912                 """
913         else :
914             #FIXME
915             tmpchi = False
916             if tmpchi :
917                 txt += """
918                 lchi <- read.table("%s")
919                 lchi <- lchi[,1]
920                 """ % ffr(tmpchi)
921                 if 'selected_col' in dir(self.tableau) :
922                     txt += """
923                     lchi <- lchi[c%s+1]
924                     """ % datas
925             if tmpchi and self.parametres.get('cexfromchi', False) :
926                 txt += """ 
927                 label.cex <- norm.vec(lchi, vcexminmax[1], vcexminmax[2])
928                 """
929             else :
930                 txt += """
931             if (is.null(vcexminmax[1])) {
932                 label.cex <- NULL
933             } else {
934                 label.cex <- graph.simi$label.cex
935             }
936             """
937             if tmpchi and self.parametres.get('sfromchi', False) :
938                 txt += """ 
939                 vertex.size <- norm.vec(lchi, minmaxeff[1], minmaxeff[2])
940                 """
941             else :
942                 txt += """
943             if (is.null(minmaxeff[1])) {
944                 vertex.size <- NULL
945             } else {
946                 vertex.size <- graph.simi$eff
947             }
948             """
949         txt += """ vertex.size <- NULL """
950         txt += """
951         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)
952         save.image(file="%s")
953         """ % (type, self.filename, self.pathout['RData'])
954         
955         self.add(txt)
956         self.write()
957
958 class WordCloudRScript(PrintRScript) :
959     def make_script(self) :
960         self.sources([self.analyse.parent.RscriptsPath['Rgraph']])
961         self.packages(['wordcloud'])
962         bg_col = Rcolor(self.parametres['col_bg'])
963         txt_col = Rcolor(self.parametres['col_text'])
964         txt = """
965         act <- read.csv2("%s", header = FALSE, row.names=1, sep='\t')
966         selected.col <- read.table("%s")
967         toprint <- as.matrix(act[selected.col[,1] + 1,])
968         rownames(toprint) <- rownames(act)[selected.col[,1] + 1]
969         maxword <- %i
970         if (nrow(toprint) > maxword) {
971             toprint <- as.matrix(toprint[order(toprint[,1], decreasing=TRUE),])
972             toprint <- as.matrix(toprint[1:maxword,])
973         }
974         open_file_graph("%s", width = %i, height = %i)
975         par(bg=rgb%s)
976         wordcloud(row.names(toprint), toprint[,1], scale=c(%f,%f), random.order=FALSE, colors=rgb%s)
977         dev.off()
978         """ % (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)
979         self.add(txt)
980         self.write()