graph to json
[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, FreqMultiScript
17 from operator import itemgetter
18
19 class Frequences(AnalyseMatrix) :
20     def doparametres(self, dlg=None) :
21         if dlg is None :
22             return
23         else :
24             dial = FreqDialog(self.parent, self.tableau.get_colnames(), u"Fréquences")
25             dial.CenterOnParent()
26             val = dial.ShowModal()
27             if val == wx.ID_OK :
28                 self.parametres['colsel'] = dial.m_listBox1.GetSelections()
29                 self.parametres['header'] = dial.header
30                 self.parametres['NA'] = dial.includeNA.GetValue()
31             else :
32                 self.parametres = None
33             dial.Destroy()
34                 
35     def doanalyse(self):
36         self.pathout.createdir(self.parametres['pathout'])
37         header = self.tableau.get_colnames()
38         select = self.parametres['colsel']
39         self.listtitre = [header[i] for i in select]
40         b, self.outframe = tempfile.mkstemp()
41         self.fileforR = [ffr(os.path.join(self.pathout.dirout, 'freq_%i.png' % i)) for i in range(len(select))]
42         self.Rscript = PrintRScript(self)
43         sel = 'c(' + ','.join([str(val + 1) for val in select]) + ')'
44         listfiles = 'c("' + '","'.join(self.fileforR) + '")'
45         titles = 'c("' +  '","'.join(self.listtitre) + '")'
46         txt = """
47         filein <- "%s"
48         encoding <- '%s'
49         dm <- read.csv2(filein, encoding = encoding, header = TRUE, row.names = 1, sep='\\t', quote = '"', na.string = '')
50         """ %(ffr(self.tableau.parametres['csvfile']), self.tableau.parametres['syscoding'])
51         txt += """
52         outframe <- data.frame(cbind('***','****','****'))
53         colnames(outframe)<-c('effectif','pourcentage', 'labels')
54         select <- %s
55         listfiles <- %s
56         titles <- %s
57         compteur <- 1
58         """ % (sel, listfiles, titles)
59         
60         if self.parametres['NA'] :
61             txt += """
62             countNA <- TRUE
63             """
64         else :
65             txt += """
66             countNA <- FALSE
67             """
68         
69         txt += """
70         for (i in select) {
71             if (countNA) {
72                 freq <- table(dm[,i], useNA = 'ifany')
73             } else {
74                 freq <- table(dm[,i])
75             }
76             sumfreq <- sum(freq)
77             pour <- prop.table(as.matrix(freq), 2) * 100
78             sumpour <- sum(pour)
79             pour <- round(pour, 2)
80             ntable <- cbind(as.matrix(freq), pour)
81             graphout <- listfiles[compteur]  
82             if (Sys.info()["sysname"]=='Darwin') {
83                 quartz(file=graphout,type='png')
84                 par(cex=1)
85             } else {
86                 png(graphout)
87                 par(cex=0.3)
88                 }
89             if (max(nchar(rownames(ntable))) > 15) {
90                 lab.bar <- 1:nrow(ntable)
91             } else {
92                 lab.bar <- rownames(ntable)
93             }
94             barplot(ntable[,2],border=NA,beside=TRUE,names.arg=lab.bar)
95             ntable <- cbind(ntable, rownames(as.matrix(freq)))
96             colnames(ntable) <- c('effectif','pourcentage', 'labels')
97             title(main=titles[compteur])
98             dev.off()
99             ntable<-rbind(ntable,total=c(sumfreq,sumpour,''))
100             outframe<-rbind(outframe,c('***','****','****'))
101             #datasum[,1]<-as.character(datasum[,1])
102             #datasum[,2]<-as.character(datasum[,2])
103             outframe<-rbind(outframe,ntable)
104             compteur <- compteur + 1
105         }
106         outframe<-rbind(outframe,c('***','****','****'))
107         write.table(outframe, file="%s", sep="\\t")
108         """ % ffr(self.outframe)
109         self.Rscript.add(txt)
110         self.Rscript.write()
111         self.doR(self.Rscript.scriptout)
112         self.dolayout()
113         
114     def dolayout(self):
115         listtab = []
116         tab = []
117         with open(self.outframe) as f :
118             content = f.read().splitlines()
119         content.pop(0)
120         content.pop(0)
121         content = ['\t'.join(line.split('\t')[1:]).replace('"','') for line in content]
122         content = '\n'.join(content)
123         content = content.split(u'***\t****\t****')
124         content = [[line.split('\t') for line in tab.splitlines() if line.split('\t') != ['']] for tab in content]
125         listtab = [tab for tab in content if tab != []]
126         texte = ''
127         #for ligne in content:
128         #    ligne = ligne.replace('"', '')
129         #    ligne = ligne.split('\t')
130         #    if ligne[1] == u'***' :
131         #        if tab != []:
132         #            listtab.append(tab)
133         #        tab = []
134         #    else :
135         #        tab.append(ligne)
136         pretexte = u'''<html>
137         <meta http-equiv="content-Type" content="text/html; charset=%s" />
138         <body>\n<h1>Fréquences</h1>
139         <a name="deb"></a><br>
140         ''' % self.parent.SysEncoding
141         for i in range(0, len(listtab)):
142             pretexte += '<p><a href="#%s">%s</a></p>' % (str(i), self.listtitre[i])
143             texte += '<hr size="5" align="center" width="50%" color="green">\n'
144             texte += '<p><a href="#deb">Retour</a></p>\n'
145             texte += '<a name="%s"></a><h2>%s</h2>\n' % (str(i), self.listtitre[i])
146             texte += '<table>\n<tr><td>\n'
147             texte += '<table border=1><tr><td></td><td>Effectifs</td><td>pourcentage</td></tr>'
148             for line in listtab[i] :
149                 texte += '<tr>'
150                 texte += """
151                 <td>%s</td><td align=center>%s</td><td align=center>%s %%</td>
152                 """ % (line[2], line[0], line[1])
153                 texte += '</tr>'
154             texte += '</table></td>'
155             texte += """
156             <td><img src="%s" alt="graph"/></td></tr></table>\n
157             """ % os.path.basename(self.fileforR[i])
158             texte += '</body>\n</html>'
159         fileout = os.path.join(self.pathout.dirout, 'resultats.html')
160         with open(fileout, 'w') as f :
161             f.write(pretexte + texte)
162         #return fileout
163
164 class FreqMultiple(Frequences): 
165     def doanalyse(self):
166         select = self.parametres['colsel']
167         freq = self.tableau.countmultiple(select)
168         tot = sum([freq[forme][0] for forme in freq])
169         freq = [[forme, freq[forme][0], `round((float(freq[forme][0])/tot)*100, 2)`,`len(list(set(freq[forme][1])))`, `round((float(len(list(set(freq[forme][1]))))/self.tableau.rownb)*100,2)`] for forme in freq]
170         freq = sorted(freq, key=itemgetter(1), reverse=True)
171         freq = [[line[0], `line[1]`, line[2], line[3], line[4]] for line in freq]
172         freq.insert(0, [u'mod', 'freq', 'percent of total', 'row number', 'percent of rows'])
173         self.freq = freq
174         with open(self.pathout['frequences.csv'], 'w') as f :
175             f.write('\n'.join(['\t'.join(line) for line in freq]))
176         self.rscript = FreqMultiScript(self)
177         self.rscript.make_script()
178         self.doR(self.rscript.scriptout)
179         self.dolayout()
180     
181     def dolayout(self):
182         pretexte = u'''<html>
183         <meta http-equiv="content-Type" content="text/html; charset=%s" />
184         <body>\n<h1>Fréquences</h1>
185         <a name="deb"></a><br>
186         ''' % self.parent.SysEncoding       
187         txt = """
188         <table>\n<tr><td>\n
189         <table border=1><tr><td>
190         """
191         txt += '</td></tr><tr><td>'.join(['</td><td>'.join(line) for line in self.freq]) + '</td></tr></table></td></tr>'
192         txt += '<tr><td><img src="%s" alt="graph"/></td><td><img src="%s" alt="graph"/></td></tr></table>' % (os.path.basename(self.pathout['barplotfreq.png']), os.path.basename(self.pathout['barplotrow.png']))
193         txt += "</body>\n</html>"
194         with open(self.pathout['resultats.html'], 'w') as f :
195             f.write(pretexte + txt)
196         
197         
198         
199         
200         
201         
202         
203