...
[iramuteq] / tabfrequence.py
1 #!/bin/env python
2 # -*- coding: utf-8 -*-
3 #Author: Pierre Ratinaud
4 #Copyright (c) 2008 Pierre Ratinaud
5 #License: GNU/GPL
6
7 #from __future__ import division
8 import os
9 import wx
10 from chemins import ffr, FFF
11 import tempfile
12 from time import sleep
13 from analysematrix import AnalyseMatrix
14 from functions import exec_rcode, check_Rresult
15 from dialog import FreqDialog
16 from PrintRScript import PrintRScript
17
18 class Frequences(AnalyseMatrix) :
19     def doparametres(self, dlg=None) :
20         if dlg is None :
21             return
22         else :
23             dial = FreqDialog(self.parent, -1, self.tableau.get_colnames(), u"Fréquences", size=(350, 200))
24             dial.CenterOnParent()
25             val = dial.ShowModal()
26             if val == wx.ID_OK :
27                 self.parametres['colsel'] = dial.list_box_1.GetSelections()
28                 self.parametres['header'] = dial.header
29             else :
30                 self.parametres = None
31             dial.Destroy()
32                 
33     def doanalyse(self):
34         self.pathout.createdir(self.parametres['pathout'])
35         header = self.tableau.get_colnames()
36         select = self.parametres['colsel']
37         self.listtitre = [header[i] for i in select]
38         b, self.outframe = tempfile.mkstemp()
39         self.fileforR = [ffr(os.path.join(self.pathout.dirout, 'freq_%i.png' % i)) for i in range(len(select))]
40         self.Rscript = PrintRScript(self)
41         sel = 'c(' + ','.join([str(val + 1) for val in select]) + ')'
42         listfiles = 'c("' + '","'.join(self.fileforR) + '")'
43         titles = 'c("' +  '","'.join(self.listtitre) + '")'
44         txt = """
45         filein <- "%s"
46         encoding <- '%s'
47         dm <- read.csv2(filein, encoding = encoding, header = TRUE, row.names = 1, sep='\\t', quote = '"', na.string = '')
48         """ %(ffr(self.tableau.parametres['csvfile']), self.tableau.parametres['syscoding'])
49         txt += """
50         outframe <- data.frame(cbind('***','****','****'))
51         colnames(outframe)<-c('effectif','pourcentage', 'labels')
52         select <- %s
53         listfiles <- %s
54         titles <- %s
55         compteur <- 1
56         """ % (sel, listfiles, titles)
57         
58         txt += """
59         for (i in select) {
60             freq <- table(dm[,i])
61             sumfreq <- sum(freq)
62             pour <- prop.table(as.matrix(freq), 2) * 100
63             sumpour <- sum(pour)
64             ntable <- cbind(as.matrix(freq), pour)
65             graphout <- listfiles[compteur]  
66             if (Sys.info()["sysname"]=='Darwin') {
67                 quartz(file=graphout,type='png')
68                 par(cex=1)
69             } else {
70                 png(graphout)
71                 par(cex=0.3)
72                 }
73             if (max(nchar(rownames(ntable))) > 15) {
74                 lab.bar <- 1:nrow(ntable)
75             } else {
76                 lab.bar <- rownames(ntable)
77             }
78             barplot(ntable[,2],border=NA,beside=TRUE,names.arg=lab.bar)
79             ntable <- cbind(ntable, rownames(as.matrix(freq)))
80             colnames(ntable) <- c('effectif','pourcentage', 'labels')
81             title(main=titles[compteur])
82             dev.off()
83             ntable<-rbind(ntable,total=c(sumfreq,sumpour,''))
84             outframe<-rbind(outframe,c('***','****','****'))
85             #datasum[,1]<-as.character(datasum[,1])
86             #datasum[,2]<-as.character(datasum[,2])
87             outframe<-rbind(outframe,ntable)
88             compteur <- compteur + 1
89         }
90         outframe<-rbind(outframe,c('***','****','****'))
91         write.table(outframe, file="%s", sep="\\t")
92         """ % ffr(self.outframe)
93         self.Rscript.add(txt)
94         self.Rscript.write()
95         self.doR(self.Rscript.scriptout)
96         self.dolayout()
97         
98     def dolayout(self):
99         listtab = []
100         tab = []
101         with open(self.outframe) as f :
102             content = f.read().splitlines()
103         content.pop(0)
104         content.pop(0)
105         content = ['\t'.join(line.split('\t')[1:]).replace('"','') for line in content]
106         content = '\n'.join(content)
107         content = content.split(u'***\t****\t****')
108         content = [[line.split('\t') for line in tab.splitlines() if line.split('\t') != ['']] for tab in content]
109         listtab = [tab for tab in content if tab != []]
110         texte = ''
111         #for ligne in content:
112         #    ligne = ligne.replace('"', '')
113         #    ligne = ligne.split('\t')
114         #    if ligne[1] == u'***' :
115         #        if tab != []:
116         #            listtab.append(tab)
117         #        tab = []
118         #    else :
119         #        tab.append(ligne)
120         pretexte = u'''<html>
121         <meta http-equiv="content-Type" content="text/html; charset=%s" />
122         <body>\n<h1>Fréquences</h1>
123         <a name="deb"></a><br>
124         ''' % self.parent.SysEncoding
125         for i in range(0, len(listtab)):
126             pretexte += '<p><a href="#%s">%s</a></p>' % (str(i), self.listtitre[i])
127             texte += '<hr size="5" align="center" width="50%" color="green">\n'
128             texte += '<p><a href="#deb">Retour</a></p>\n'
129             texte += '<a name="%s"></a><h2>%s</h2>\n' % (str(i), self.listtitre[i])
130             texte += '<table>\n<tr><td>\n'
131             texte += '<table border=1><tr><td></td><td>Effectifs</td><td>pourcentage</td></tr>'
132             for line in listtab[i] :
133                 texte += '<tr>'
134                 texte += """
135                 <td>%s</td><td align=center>%s</td><td align=center>%s %%</td>
136                 """ % (line[2], line[0], line[1])
137                 texte += '</tr>'
138             texte += '</table></td>'
139             texte += """
140             <td><img src="%s" alt="graph"/></td></tr></table>\n
141             """ % os.path.basename(self.fileforR[i])
142             texte += '</body>\n</html>'
143         fileout = os.path.join(self.pathout.dirout, 'resultats.html')
144         with open(fileout, 'w') as f :
145             f.write(pretexte + texte)
146         #return fileout
147