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