factiva
[iramuteq] / tabfrequence.py
1 #!/bin/env python
2 # -*- coding: utf-8 -*-
3 #Author: Pierre Ratinaud
4 #Copyright (c) 2008 Pierre Ratinaud
5 #Lisense: GNU/GPL
6
7 #from __future__ import division
8 import os
9 import sys
10 import wx
11 import wx.html
12 from chemins import ffr, FFF
13 import tempfile
14 from time import sleep
15 from functions import exec_rcode, check_Rresult
16
17 class FreqDialog(wx.Dialog):
18     def __init__(
19             self, parent, ID, title, size=wx.DefaultSize, pos=wx.DefaultPosition,
20             style=wx.DEFAULT_DIALOG_STYLE | wx.CANCEL | wx.OK
21             ):
22         pre = wx.PreDialog()
23         pre.SetExtraStyle(wx.DIALOG_EX_CONTEXTHELP)
24         pre.Create(parent, ID, title, pos, size, style)
25         self.PostCreate(pre)
26         self.parent = parent 
27         sizer = wx.BoxSizer(wx.VERTICAL)
28         self.content = parent.content
29         self.header = parent.tableau.get_colnames()
30         LABELLIST = []
31         for i in self.header:
32             forme = i
33             if len(forme) > 60 :
34                 LABELLIST.append(i[0:60])
35             else:
36                 LABELLIST.append(i)
37         self.list_box_1 = wx.ListBox(self, -1, choices=LABELLIST, style=wx.LB_EXTENDED | wx.LB_HSCROLL)
38         sizer.Add(self.list_box_1, 0, 5)
39         
40         btnsizer = wx.BoxSizer(wx.HORIZONTAL)
41         
42         btn = wx.Button(self, wx.ID_CANCEL)
43         btn.SetHelpText("Annuler")
44         btnsizer.Add(btn)
45         
46         btn = wx.Button(self, wx.ID_OK)
47         btn.SetHelpText("Valider")
48         btn.SetDefault()
49         btnsizer.Add(btn)
50         
51         sizer.Add(btnsizer, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL, 5)
52         self.SetSizer(sizer)
53         sizer.Fit(self)
54         self.SetTitle(u"Sélection")
55   
56         # end wxGlade
57         
58 class Frequences():
59     def __init__(self, parent):
60         #self.Filename = parent.filename
61         self.fileforR = parent.tableau.parametre['csvfile']
62         self.TEMPDIR = parent.TEMPDIR
63         self.num = parent.FreqNum
64         self.DICTFILE = {}
65         self.RPath = parent.PathPath.get('PATHS', 'rpath')
66         self.parent=parent
67         dlg = FreqDialog(parent, -1, u"Fréquences", size=(350, 200),
68                 style=wx.DEFAULT_DIALOG_STYLE)
69         dlg.CenterOnParent()
70         val = dlg.ShowModal()
71         if val == wx.ID_OK :
72             ColSel = dlg.list_box_1.GetSelections()
73             self.header=dlg.header
74             dlg.Destroy()
75             listfileout = self.ShowFreq(ColSel)
76             parent.FreqNum += 1
77             parent.DictTab[u"Fréquences_%s*" % parent.FreqNum] = listfileout
78             parent.FileTabList.append(listfileout)
79             parent.newtab = wx.html.HtmlWindow(parent.nb, -1)
80             if "gtk2" in wx.PlatformInfo:
81                parent.newtab.SetStandardFonts()
82             parent.newtab.LoadPage(listfileout[len(listfileout) - 1])
83             parent.nb.AddPage(parent.newtab, u"Fréquences_%s*" % parent.FreqNum)
84             parent.nb.SetSelection(parent.nb.GetPageCount() - 1)
85             parent.ShowAPane("Tab_content")
86             parent.DisEnSaveTabAs(True) 
87         else :
88             dlg.Destroy()
89
90     def ShowFreq(self, select):
91         listfile = []
92         listfile.append(False)
93         self.ListFileForR = []
94         self.ListTitre = []
95         self.OutFrame = tempfile.mktemp(dir=self.TEMPDIR)
96         if self.parent.g_id: rownames = '1'
97         else: rownames = 'NULL'
98         if self.parent.g_header : header = 'TRUE'
99         else : header = 'FALSE'
100         self.ListTitre = [self.header[i] for i in select]
101         self.ListFileForR = [ffr(os.path.join(self.TEMPDIR, 'freq%s_%s.jpeg' % (str(self.num), i))) for i in range(len(select))]
102         listfile = [os.path.join(self.TEMPDIR, 'freq%s_%s.jpeg' % (str(self.num), i)) for i in range(len(select))]
103         sel = 'c(' + ','.join([str(val + 1) for val in select]) + ')'
104         listfiles = 'c("' + '","'.join(self.ListFileForR) + '")'
105         titles = 'c("' +  '","'.join(self.ListTitre) + '")'
106         txt = """
107         source("%s")
108         """ % self.parent.RscriptsPath['Rfunct']
109
110         txt += """
111         datadm <- ReadData("%s", encoding="%s", header = TRUE, sep = ";",quote = "\\%s", na.strings = "%s",rownames=1)
112         """ % (ffr(self.fileforR), self.parent.encode, self.parent.tableau.parametre['txtsep'], self.parent.nastrings)
113         txt += """
114         outframe<-data.frame(cbind('***','****'))
115         colnames(outframe)<-c('effectif','pourcentage')
116         select <- %s
117         listfiles <- %s
118         titles <- %s
119         compteur <- 1
120         """ % (sel, listfiles, titles)
121         txt += """
122         for (i in select) {
123             datasum<-as.matrix(summary(datadm[,i]))
124             if (rownames(datasum)[1]=='Min.' && rownames(datasum)[3]=='Median') {
125                 dtype<-'num'
126             } else if (datasum[1] == "logical") {
127                 dtype <- 'char'
128                 datasum <- as.matrix(as.integer(datasum[2]))
129                 rownames(datasum) <- 'NA'
130             } else {
131                 dtype<-'char'
132             }
133             datasum<-as.data.frame(datasum)
134             if (dtype=='char') {
135                 datasum[,2]<-round((datasum[,1]/sum(datasum[,1]))*100,digits=2)
136             } else {
137                 datasum[,2]<-datasum[,1]
138             }
139             colnames(datasum)<-c('effectif','pourcentage')
140             graphout <- listfiles[compteur]  
141             if (Sys.info()["sysname"]=='Darwin') {
142                 quartz(file=graphout,type='jpeg')
143                 par(cex=1)
144             } else {
145                 jpeg(graphout,res=200)
146                 par(cex=0.3)
147                 }
148             if (max(nchar(rownames(datasum))) > 15) {
149                 lab.bar <- 1:nrow(datasum)
150             } else {
151                 lab.bar <- rownames(datasum)
152             }
153             barplot(datasum[,2],border=NA,beside=TRUE,names.arg=lab.bar)
154             title(main=titles[compteur])
155             dev.off()
156             datasum<-rbind(datasum,total=colSums(datasum))
157             outframe<-rbind(outframe,c('***','****'))
158             datasum[,1]<-as.character(datasum[,1])
159             datasum[,2]<-as.character(datasum[,2])
160             outframe<-rbind(outframe,datasum)
161             compteur <- compteur + 1
162             }
163         outframe<-rbind(outframe,c('***','****'))
164         write.csv2(outframe,file="%s")
165         """ % ffr(self.OutFrame)
166         tmpfile = tempfile.mktemp(dir=self.TEMPDIR)
167         tmpscript = open(tmpfile, 'w')
168         tmpscript.write(txt)
169         tmpscript.close()
170         pid = exec_rcode(self.RPath, tmpfile, wait = False)
171         while pid.poll() == None :
172            sleep(0.2)
173         check_Rresult(self.parent, pid)
174         fileout = self.DoLayout()
175         listfile.append(fileout)
176         self.DICTFILE[self.num] = listfile
177         return listfile
178
179
180     def DoLayout(self):
181         listtab = []
182         tab = []
183         filein = open(self.OutFrame, 'rU')
184         content = filein.readlines()
185         filein.close()
186         content.pop(0)
187         content.pop(0)
188         texte = ''
189         for ligne in content:
190             ligne = ligne.replace('"', '').replace('\n', '')
191             ligne = ligne.split(';')
192             if ligne[1] == u'***' :
193                 if tab != []:
194                     listtab.append(tab)
195                 tab = []
196             else :
197                 tab.append(ligne)
198         pretexte = u'''<html>
199         <meta http-equiv="content-Type" content="text/html; charset=%s" />
200         <body>\n<h1>Fréquences</h1>
201         <a name="deb"></a><br>
202         ''' % self.parent.SysEncoding
203         for i in range(0, len(listtab)):
204             pretexte += '<p><a href="#%s">%s</a></p>' % (str(i), self.ListTitre[i])
205             texte += '<hr size="5" align="center" width="50%" color="green">\n'
206             texte += '<p><a href="#deb">Retour</a></p>\n'
207             texte += '<a name="%s"></a><h2>%s</h2>\n' % (str(i), self.ListTitre[i])
208             texte += '<table>\n<tr><td>\n'
209             texte += '<table border=1><tr><td></td><td>Effectifs</td><td>pourcentage</td></tr>'
210             for line in listtab[i] :
211                 texte += '<tr>'
212                 texte += """
213                 <td>%s</td><td align=center>%s</td><td align=center>%s %%</td>
214                 """ % (line[0], line[1], line[2])
215                 texte += '</tr>'
216             texte += '</table></td>'
217             texte += """
218             <td><img src="%s" alt="graph"/></td></tr></table>\n
219             """ % os.path.basename(self.ListFileForR[i])
220             texte += '</body>\n</html>'
221         fileout = os.path.join(self.TEMPDIR, 'resultats%s-freq.html' % str(self.num))
222         FILE = open(fileout, 'w')
223         FILE.write(pretexte + texte)
224         FILE.close()
225         return fileout
226
227