...
[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, self.tableau.get_colnames(), u"Fréquences")
24             dial.CenterOnParent()
25             val = dial.ShowModal()
26             if val == wx.ID_OK :
27                 self.parametres['colsel'] = dial.m_listBox1.GetSelections()
28                 self.parametres['header'] = dial.header
29                 self.parametres['NA'] = dial.includeNA.GetValue()
30             else :
31                 self.parametres = None
32             dial.Destroy()
33                 
34     def doanalyse(self):
35         self.pathout.createdir(self.parametres['pathout'])
36         header = self.tableau.get_colnames()
37         select = self.parametres['colsel']
38         self.listtitre = [header[i] for i in select]
39         b, self.outframe = tempfile.mkstemp()
40         self.fileforR = [ffr(os.path.join(self.pathout.dirout, 'freq_%i.png' % i)) for i in range(len(select))]
41         self.Rscript = PrintRScript(self)
42         sel = 'c(' + ','.join([str(val + 1) for val in select]) + ')'
43         listfiles = 'c("' + '","'.join(self.fileforR) + '")'
44         titles = 'c("' +  '","'.join(self.listtitre) + '")'
45         txt = """
46         filein <- "%s"
47         encoding <- '%s'
48         dm <- read.csv2(filein, encoding = encoding, header = TRUE, row.names = 1, sep='\\t', quote = '"', na.string = '')
49         """ %(ffr(self.tableau.parametres['csvfile']), self.tableau.parametres['syscoding'])
50         txt += """
51         outframe <- data.frame(cbind('***','****','****'))
52         colnames(outframe)<-c('effectif','pourcentage', 'labels')
53         select <- %s
54         listfiles <- %s
55         titles <- %s
56         compteur <- 1
57         """ % (sel, listfiles, titles)
58         
59         if self.parametres['NA'] :
60             txt += """
61             countNA <- TRUE
62             """
63         else :
64             txt += """
65             countNA <- FALSE
66             """
67         
68         txt += """
69         for (i in select) {
70             if (countNA) {
71                 freq <- table(dm[,i], useNA = 'ifany')
72             } else {
73                 freq <- table(dm[,i])
74             }
75             sumfreq <- sum(freq)
76             pour <- prop.table(as.matrix(freq), 2) * 100
77             sumpour <- sum(pour)
78             pour <- round(pour, 2)
79             ntable <- cbind(as.matrix(freq), pour)
80             graphout <- listfiles[compteur]  
81             if (Sys.info()["sysname"]=='Darwin') {
82                 quartz(file=graphout,type='png')
83                 par(cex=1)
84             } else {
85                 png(graphout)
86                 par(cex=0.3)
87                 }
88             if (max(nchar(rownames(ntable))) > 15) {
89                 lab.bar <- 1:nrow(ntable)
90             } else {
91                 lab.bar <- rownames(ntable)
92             }
93             barplot(ntable[,2],border=NA,beside=TRUE,names.arg=lab.bar)
94             ntable <- cbind(ntable, rownames(as.matrix(freq)))
95             colnames(ntable) <- c('effectif','pourcentage', 'labels')
96             title(main=titles[compteur])
97             dev.off()
98             ntable<-rbind(ntable,total=c(sumfreq,sumpour,''))
99             outframe<-rbind(outframe,c('***','****','****'))
100             #datasum[,1]<-as.character(datasum[,1])
101             #datasum[,2]<-as.character(datasum[,2])
102             outframe<-rbind(outframe,ntable)
103             compteur <- compteur + 1
104         }
105         outframe<-rbind(outframe,c('***','****','****'))
106         write.table(outframe, file="%s", sep="\\t")
107         """ % ffr(self.outframe)
108         self.Rscript.add(txt)
109         self.Rscript.write()
110         self.doR(self.Rscript.scriptout)
111         self.dolayout()
112         
113     def dolayout(self):
114         listtab = []
115         tab = []
116         with open(self.outframe) as f :
117             content = f.read().splitlines()
118         content.pop(0)
119         content.pop(0)
120         content = ['\t'.join(line.split('\t')[1:]).replace('"','') for line in content]
121         content = '\n'.join(content)
122         content = content.split(u'***\t****\t****')
123         content = [[line.split('\t') for line in tab.splitlines() if line.split('\t') != ['']] for tab in content]
124         listtab = [tab for tab in content if tab != []]
125         texte = ''
126         #for ligne in content:
127         #    ligne = ligne.replace('"', '')
128         #    ligne = ligne.split('\t')
129         #    if ligne[1] == u'***' :
130         #        if tab != []:
131         #            listtab.append(tab)
132         #        tab = []
133         #    else :
134         #        tab.append(ligne)
135         pretexte = u'''<html>
136         <meta http-equiv="content-Type" content="text/html; charset=%s" />
137         <body>\n<h1>Fréquences</h1>
138         <a name="deb"></a><br>
139         ''' % self.parent.SysEncoding
140         for i in range(0, len(listtab)):
141             pretexte += '<p><a href="#%s">%s</a></p>' % (str(i), self.listtitre[i])
142             texte += '<hr size="5" align="center" width="50%" color="green">\n'
143             texte += '<p><a href="#deb">Retour</a></p>\n'
144             texte += '<a name="%s"></a><h2>%s</h2>\n' % (str(i), self.listtitre[i])
145             texte += '<table>\n<tr><td>\n'
146             texte += '<table border=1><tr><td></td><td>Effectifs</td><td>pourcentage</td></tr>'
147             for line in listtab[i] :
148                 texte += '<tr>'
149                 texte += """
150                 <td>%s</td><td align=center>%s</td><td align=center>%s %%</td>
151                 """ % (line[2], line[0], line[1])
152                 texte += '</tr>'
153             texte += '</table></td>'
154             texte += """
155             <td><img src="%s" alt="graph"/></td></tr></table>\n
156             """ % os.path.basename(self.fileforR[i])
157             texte += '</body>\n</html>'
158         fileout = os.path.join(self.pathout.dirout, 'resultats.html')
159         with open(fileout, 'w') as f :
160             f.write(pretexte + texte)
161         #return fileout
162