antipro pour matrix
[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 from dialog import FreqDialog
17
18         
19 class Frequences():
20     def __init__(self, parent):
21         #self.Filename = parent.filename
22         self.fileforR = parent.tableau.parametre['csvfile']
23         self.TEMPDIR = parent.TEMPDIR
24         self.num = parent.FreqNum
25         self.DICTFILE = {}
26         self.RPath = parent.PathPath.get('PATHS', 'rpath')
27         self.parent=parent
28         self.tableau = parent.tableau
29         dlg = FreqDialog(parent, -1, self.tableau.get_colnames(), u"Fréquences", size=(350, 200))
30         dlg.CenterOnParent()
31         val = dlg.ShowModal()
32         if val == wx.ID_OK :
33             ColSel = dlg.list_box_1.GetSelections()
34             self.header=dlg.header
35             dlg.Destroy()
36             listfileout = self.ShowFreq(ColSel)
37             parent.FreqNum += 1
38             parent.DictTab[u"Fréquences_%s*" % parent.FreqNum] = listfileout
39             parent.FileTabList.append(listfileout)
40             parent.newtab = wx.html.HtmlWindow(parent.nb, -1)
41             if "gtk2" in wx.PlatformInfo:
42                parent.newtab.SetStandardFonts()
43             parent.newtab.LoadPage(listfileout[len(listfileout) - 1])
44             parent.nb.AddPage(parent.newtab, u"Fréquences_%s*" % parent.FreqNum)
45             parent.nb.SetSelection(parent.nb.GetPageCount() - 1)
46             parent.ShowAPane("Tab_content")
47             parent.DisEnSaveTabAs(True) 
48         else :
49             dlg.Destroy()
50
51     def ShowFreq(self, select):
52         listfile = []
53         listfile.append(False)
54         self.ListFileForR = []
55         self.ListTitre = []
56         self.OutFrame = tempfile.mktemp(dir=self.TEMPDIR)
57         if self.parent.g_id: rownames = '1'
58         else: rownames = 'NULL'
59         if self.parent.g_header : header = 'TRUE'
60         else : header = 'FALSE'
61         self.ListTitre = [self.header[i] for i in select]
62         self.ListFileForR = [ffr(os.path.join(self.TEMPDIR, 'freq%s_%s.jpeg' % (str(self.num), i))) for i in range(len(select))]
63         listfile = [os.path.join(self.TEMPDIR, 'freq%s_%s.jpeg' % (str(self.num), i)) for i in range(len(select))]
64         sel = 'c(' + ','.join([str(val + 1) for val in select]) + ')'
65         listfiles = 'c("' + '","'.join(self.ListFileForR) + '")'
66         titles = 'c("' +  '","'.join(self.ListTitre) + '")'
67         txt = """
68         source("%s")
69         """ % self.parent.RscriptsPath['Rfunct']
70
71         txt += """
72         datadm <- ReadData("%s", encoding="%s", header = TRUE, sep = ";",quote = "\\%s", na.strings = "%s",rownames=1)
73         """ % (ffr(self.fileforR), self.parent.encode, self.parent.tableau.parametre['txtsep'], self.parent.nastrings)
74         txt += """
75         outframe<-data.frame(cbind('***','****'))
76         colnames(outframe)<-c('effectif','pourcentage')
77         select <- %s
78         listfiles <- %s
79         titles <- %s
80         compteur <- 1
81         """ % (sel, listfiles, titles)
82         txt += """
83         for (i in select) {
84             datasum<-as.matrix(summary(datadm[,i]))
85             if (rownames(datasum)[1]=='Min.' && rownames(datasum)[3]=='Median') {
86                 dtype<-'num'
87             } else if (datasum[1] == "logical") {
88                 dtype <- 'char'
89                 datasum <- as.matrix(as.integer(datasum[2]))
90                 rownames(datasum) <- 'NA'
91             } else {
92                 dtype<-'char'
93             }
94             datasum<-as.data.frame(datasum)
95             if (dtype=='char') {
96                 datasum[,2]<-round((datasum[,1]/sum(datasum[,1]))*100,digits=2)
97             } else {
98                 datasum[,2]<-datasum[,1]
99             }
100             colnames(datasum)<-c('effectif','pourcentage')
101             graphout <- listfiles[compteur]  
102             if (Sys.info()["sysname"]=='Darwin') {
103                 quartz(file=graphout,type='jpeg')
104                 par(cex=1)
105             } else {
106                 jpeg(graphout,res=200)
107                 par(cex=0.3)
108                 }
109             if (max(nchar(rownames(datasum))) > 15) {
110                 lab.bar <- 1:nrow(datasum)
111             } else {
112                 lab.bar <- rownames(datasum)
113             }
114             barplot(datasum[,2],border=NA,beside=TRUE,names.arg=lab.bar)
115             title(main=titles[compteur])
116             dev.off()
117             datasum<-rbind(datasum,total=colSums(datasum))
118             outframe<-rbind(outframe,c('***','****'))
119             datasum[,1]<-as.character(datasum[,1])
120             datasum[,2]<-as.character(datasum[,2])
121             outframe<-rbind(outframe,datasum)
122             compteur <- compteur + 1
123             }
124         outframe<-rbind(outframe,c('***','****'))
125         write.csv2(outframe,file="%s")
126         """ % ffr(self.OutFrame)
127         tmpfile = tempfile.mktemp(dir=self.TEMPDIR)
128         tmpscript = open(tmpfile, 'w')
129         tmpscript.write(txt)
130         tmpscript.close()
131         pid = exec_rcode(self.RPath, tmpfile, wait = False)
132         while pid.poll() == None :
133            sleep(0.2)
134         check_Rresult(self.parent, pid)
135         fileout = self.DoLayout()
136         listfile.append(fileout)
137         self.DICTFILE[self.num] = listfile
138         return listfile
139
140
141     def DoLayout(self):
142         listtab = []
143         tab = []
144         filein = open(self.OutFrame, 'rU')
145         content = filein.readlines()
146         filein.close()
147         content.pop(0)
148         content.pop(0)
149         texte = ''
150         for ligne in content:
151             ligne = ligne.replace('"', '').replace('\n', '')
152             ligne = ligne.split(';')
153             if ligne[1] == u'***' :
154                 if tab != []:
155                     listtab.append(tab)
156                 tab = []
157             else :
158                 tab.append(ligne)
159         pretexte = u'''<html>
160         <meta http-equiv="content-Type" content="text/html; charset=%s" />
161         <body>\n<h1>Fréquences</h1>
162         <a name="deb"></a><br>
163         ''' % self.parent.SysEncoding
164         for i in range(0, len(listtab)):
165             pretexte += '<p><a href="#%s">%s</a></p>' % (str(i), self.ListTitre[i])
166             texte += '<hr size="5" align="center" width="50%" color="green">\n'
167             texte += '<p><a href="#deb">Retour</a></p>\n'
168             texte += '<a name="%s"></a><h2>%s</h2>\n' % (str(i), self.ListTitre[i])
169             texte += '<table>\n<tr><td>\n'
170             texte += '<table border=1><tr><td></td><td>Effectifs</td><td>pourcentage</td></tr>'
171             for line in listtab[i] :
172                 texte += '<tr>'
173                 texte += """
174                 <td>%s</td><td align=center>%s</td><td align=center>%s %%</td>
175                 """ % (line[0], line[1], line[2])
176                 texte += '</tr>'
177             texte += '</table></td>'
178             texte += """
179             <td><img src="%s" alt="graph"/></td></tr></table>\n
180             """ % os.path.basename(self.ListFileForR[i])
181             texte += '</body>\n</html>'
182         fileout = os.path.join(self.TEMPDIR, 'resultats%s-freq.html' % str(self.num))
183         FILE = open(fileout, 'w')
184         FILE.write(pretexte + texte)
185         FILE.close()
186         return fileout
187
188