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