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