switch of 'lastRscript'
[iramuteq] / tabchi2.py
1 #!/bin/env python
2 # -*- coding: utf-8 -*-
3 #Author: Pierre Ratinaud
4 #Copyright (c) 2010 Pierre Ratinaud
5 #License: GNU/GPL
6
7 import HTML
8 import os
9 import string
10 import wx
11 import os
12 import sys
13 import tempfile
14 from chemins import ffr,FFF
15 import wx.lib.sized_controls as sc
16 from time import sleep
17 from functions import exec_rcode, check_Rresult
18 from dialog import ChiDialog, PrefChi
19 from analysematrix import AnalyseMatrix
20                     
21 def make_res(line) :
22     if float(line[5]) <= 0.05 and line[6] != 'warning':
23         line.append('green')
24     elif float(line[5]) <= 0.05 and line[6] == 'warning':
25         line.append('blue')
26     else :
27         line.append('red')
28     return line
29
30 def clean_line(result) :
31     return [[val for val in line if val != '**'] for line in result]
32
33 def make_table(tabs, tab_title, res) :
34     return ['<br>'.join(['<font color=%s>%s</font>' % (res[i][-1], tab_title), HTML.table(tab)]) for i,tab in enumerate(tabs)]
35
36 def make_restab(res) :
37     return ['<br>'.join(['<font color=%s>%s</font>'% (line[-1], u'Résultats'),HTML.table([['chi', line[3]],['p', line[5]]])]) for i,line in enumerate(res)]
38
39 def make_htmlgraphs(graphs) :
40     return ['<img src=%s>' % os.path.basename(val) for val in graphs]
41
42 def make_link_list(res, text) :
43     return ['<a name=back_%i></a><a href=#%i><font color=%s>%s</font></a>' % (i, i, chi[-1], text[i]) for i, chi in enumerate(res)]
44
45 def make_title(res, text) :
46     return ['<a name=%i></a><br><font color=%s>%s</font><br><a href=#back_%i>retour</a><br>' % (i, val[-1], text[i], i) for i, val in enumerate(res)] 
47
48
49 chioption = { 'valobs' : True,
50               'valtheo' : True,
51               'resi' : False,
52               'contrib' : True,
53               'pourcent' : False,
54               'pourcentl' : True,
55               'pourcentc' : True,
56               'graph' : True,
57               'bw' : False,
58               }
59
60 class ChiSquare(AnalyseMatrix):
61     def doparametres(self, dlg = None):
62         if dlg is None :
63             return
64         dial = ChiDialog(self.parent, -1, u"Chi2", chioption, self.tableau, size=(400, 350),
65                      style = wx.DEFAULT_DIALOG_STYLE
66                      )
67         dial.CenterOnParent()
68         val = dial.ShowModal()
69         if val==wx.ID_OK :     
70             self.colsel1 = dial.list_box_1.GetSelections()
71             self.colsel2 = dial.list_box_2.GetSelections()
72             if dial.chiopt :
73                 chioption['valobs'] = dial.dial.check1.GetValue()
74                 chioption['valtheo'] = dial.dial.check2.GetValue()
75                 chioption['resi'] = dial.dial.check3.GetValue()
76                 chioption['contrib'] = dial.dial.check4.GetValue()
77                 chioption['pourcent'] = dial.dial.check5.GetValue()
78                 chioption['pourcentl'] = dial.dial.check6.GetValue()
79                 chioption['pourcentc'] = dial.dial.check7.GetValue()
80                 chioption['graph'] = dial.dial.check8.GetValue()
81                 chioption['bw'] = dial.dial.checkbw.GetValue()
82                 dial.dial.Destroy()
83             dial.Destroy()
84             self.parametres.update(chioption)
85             self.chioption = chioption
86         else :
87             if dial.chiopt :
88                 dial.dial.Destroy()
89             dial.Destroy()
90             self.parametres = None
91             
92     def doanalyse(self):
93         self.count = 1
94         keepGoing = self.dlg.Update(self.count,u"Analyse dans R...")
95         self.OutFrame=tempfile.mktemp(dir=self.parent.TEMPDIR)
96         self.encode=self.parent.encode
97         self.TEMPDIR=self.parent.TEMPDIR
98         self.RPath=self.parent.PathPath.get('PATHS','rpath')
99         self.TextCroise=[]
100         for i in self.colsel1 :
101             for j in self.colsel2 :
102                 self.TextCroise.append(self.tableau.colnames[i] + ' / ' + self.tableau.colnames[j])
103         rchioption = {}
104         for val in self.chioption :
105             if self.chioption[val]:
106                 rchioption[val] = 'TRUE'
107             else :
108                 rchioption[val] = 'FALSE'
109         txt="""
110         source("%s")
111         """%ffr(self.parent.RscriptsPath['Rfunct'])
112         txt += """
113         source("%s")
114         """ % ffr(self.parent.RscriptsPath['Rgraph'])
115         txt += """
116         doobs <- %s
117         doexp <- %s
118         docontrib <- %s
119         doresi <- %s
120         dopr <- %s
121         doprl <- %s
122         doprc <- %s
123         dograph <- %s
124         bw <- %s
125         """ % (rchioption['valobs'], rchioption['valtheo'], rchioption['contrib'], rchioption['resi'], rchioption['pourcent'], rchioption['pourcentl'], rchioption['pourcentc'], rchioption['graph'], rchioption['bw'])
126         txt+="""
127         datadm <- read.csv2("%s", encoding="%s", header = TRUE, row.names = 1, sep='\\t', quote = '"', na.string = '')
128         listres<-list()
129         listcol<-list()
130         cont<-1
131         """%(ffr(self.tableau.parametres['csvfile']), self.tableau.parametres['syscoding'])
132         if len(self.colsel1)==1:
133             strsel1=str(self.colsel1).replace(',','')
134         else:
135             strsel1=str(self.colsel1)
136         if len(self.colsel2)==1:
137             strsel2=str(self.colsel2).replace(',','')
138         else:
139             strsel2=str(self.colsel2)
140         txt+="""
141         for (i in c%s) {""" % strsel1
142         txt+="""
143             for (j in c%s) {""" % strsel2
144         txt+="""
145                 tab<-table(datadm[,i+1],datadm[,j+1])
146                 if (min(dim(tab)) != 1) {
147                     chi<-chisq.test(tab)
148                     CS<-colSums(tab)
149                     RS<-rowSums(tab)
150                     GT<-sum(tab)
151                     chi$contrib<-(tab-chi$expected)/sqrt(chi$expected * ((1 - RS/GT) %%*%% t(1 - CS/GT)))
152                     listres[[cont]]<-chi
153                     listcol[[cont]]<-ncol(tab)
154                     cont<-cont+1
155                 } else {
156                     chi <- list(observed = tab, residuals = tab, contrib = tab, statistic = 0, p.value = 1, expected = tab, message = 'pas de calcul')
157                     listres[[cont]] <- chi
158                     listcol[[cont]]<-ncol(tab)
159                     cont <- cont + 1
160                 }
161             }
162         }
163         maxcol<-max(unlist(listcol))+1
164         if (maxcol<7) {maxcol<-7}
165         frameout<-matrix('*',1,maxcol)
166         count<-0
167         for (chi in listres) {
168             if (min(chi$expected)<5) {
169                 att<-"warning"
170             } else {
171                 att<-""
172             }
173             if ('message' %%in%% attributes(chi)$names) {
174                 att <- "Ce chi2 n\'a pas été calculé"
175                 nom_colresi<-colnames(chi$observed)
176                 chi$prl <- chi$expected
177                 chi$prc <- chi$expected
178                 st <- sum(chi$observed)
179             } else {
180                 nom_colresi<-colnames(chi$observed)
181                 st <- sum(chi$observed)
182                 sc <- colSums(chi$observed)
183                 sr <- rowSums(chi$observed)
184                 chi$prl <- round((chi$observed/sr)*100,2)
185                 chi$prc <- t(round((t(chi$observed)/sc)*100,2))
186             }
187             fileout<-paste('histo_',count,sep='')
188             fileout<-paste(fileout,'.png',sep='')
189             count<-count+1
190             fileout<-file.path("%s",fileout)
191             if (max(nchar(colnames(chi$observed)))>15) {
192                 leg <- 1:length(colnames(chi$observed))
193             } else {
194                 leg <- colnames(chi$observed)
195             }
196             if (dograph) {
197                 width<-ncol(chi$observed)*100
198                 if (width < 350) {width <- 350}
199                 open_file_graph(fileout,width = width, height = 300)
200                 par(mar=c(0,0,0,0))
201                 layout(matrix(c(1,2),1,2, byrow=TRUE),widths=c(3,1))
202                 par(mar=c(2,2,1,0))
203                 par(cex=0.8)
204                 if (!bw) colors <- rainbow(length(rownames(chi$observed)))
205                 else colors <- gray.colors(length(rownames(chi$observed)))
206                 barplot(chi$prl,names.arg = leg, beside=TRUE,border=NA, col=colors)
207                 par(mar=c(0,0,0,0))
208                 par(cex=0.8)
209                 plot(0, axes = FALSE, pch = '')
210                 legend(x = 'center' , rownames(chi$observed), fill = colors)
211                 dev.off()
212             }
213             chi$prl <- cbind(chi$prl, total = rowSums(chi$prl))
214             chi$prc <- rbind(chi$prc, total = colSums(chi$prc))
215             chi$observed<-rbind(chi$observed,total=colSums(chi$observed))
216             chi$observed<-cbind(chi$observed,total=rowSums(chi$observed))
217             chi$pr <- round((chi$observed/st)*100,2)
218             chi$expected<-rbind(chi$expected,total=colSums(chi$expected))
219             chi$expected<-cbind(chi$expected,total=rowSums(chi$expected))
220             chi$expected<-round(chi$expected,digits=2)
221             chi$residuals<-round(chi$residuals,digits=2)
222             chi$contrib<-round(chi$contrib, digits=2)
223             nom_col<-colnames(chi$observed)
224            
225             if (ncol(chi$observed)<maxcol) {
226                 for (i in 1:(maxcol-ncol(chi$observed))) {
227                     chi$observed<-cbind(chi$observed,'**')
228                     chi$pr<-cbind(chi$pr,'**')
229                     chi$prl<-cbind(chi$prl,'**')
230                     chi$prc<-cbind(chi$prc,'**')
231                     chi$expected<-cbind(chi$expected,'**')
232                     chi$residuals<-cbind(chi$residuals,'**')
233                     chi$contrib<-cbind(chi$contrib,'**')
234                     nom_col<-append(nom_col,'**')
235                     nom_colresi<-append(nom_colresi,'**')
236                 }
237                 chi$residuals<-cbind(chi$residuals,'**')
238                 chi$contrib<-cbind(chi$contrib,'**')
239                 nom_colresi<-append(nom_colresi,'**')
240                 chi$prc<-cbind(chi$prc,'**')
241             } else if (ncol(chi$observed)==maxcol) {
242                 chi$residuals<-cbind(chi$residuals,'**')
243                 chi$contrib<-cbind(chi$contrib,'**')
244                 nom_colresi<-append(nom_colresi,'**')
245                 chi$prc<-cbind(chi$prc,'**')
246             }
247             if (doobs) {
248                 li<-matrix('*obs*',1,maxcol)
249                 frameout<-rbind(frameout,li)
250                 frameout<-rbind(frameout,nom_col)
251                 frameout<-rbind(frameout,chi$observed)
252             }
253             if (doexp) {
254                 li<-matrix('*exp*',1,maxcol)
255                 frameout<-rbind(frameout,li)
256                 frameout<-rbind(frameout,nom_col)
257                 frameout<-rbind(frameout,chi$expected)
258             }
259             if (doresi) {
260                 li<-matrix('*resi*',1,maxcol)
261                 frameout<-rbind(frameout,li)
262                 frameout<-rbind(frameout,nom_colresi)
263                 frameout<-rbind(frameout,chi$residuals)
264             }
265             if (docontrib) {
266                 li<-matrix('*contrib*',1,maxcol)
267                 frameout<-rbind(frameout,li)
268                 frameout<-rbind(frameout,nom_colresi)
269                 frameout<-rbind(frameout,chi$contrib)
270             }
271             if (dopr) {
272                 li<-matrix('*pr*', 1, maxcol)
273                 frameout<-rbind(frameout,li)
274                 frameout<-rbind(frameout,nom_col)
275                 frameout<-rbind(frameout,chi$pr)
276             }
277             if (doprl) {
278                 li<-matrix('*prl*', 1, maxcol)
279                 frameout<-rbind(frameout,li)
280                 frameout<-rbind(frameout,nom_col)
281                 frameout<-rbind(frameout,chi$prl)
282             }
283             if (doprc) {
284                 li<-matrix('*prc*', 1, maxcol)
285                 frameout<-rbind(frameout,li)
286                 frameout<-rbind(frameout,nom_colresi)
287                 frameout<-rbind(frameout,chi$prc)
288             }
289             res<-c('****','chi',chi$statistic,'p',chi$p.value,att,fileout)
290             frameout<-rbind(frameout,res)
291         }
292         li<-matrix('fin_analyse',1,maxcol)
293         frameout<-rbind(frameout,li)
294         write.csv2(frameout,file="%s")
295         """ % (ffr(self.parametres['pathout']),ffr(self.OutFrame))
296         tmpfile=tempfile.mktemp(dir=self.TEMPDIR)
297         print tmpfile
298         tmpscript=open(tmpfile,'w')
299         tmpscript.write(txt)
300         tmpscript.close()
301         pid = exec_rcode(self.RPath, tmpfile, wait = False)
302         while pid.poll() == None :
303             sleep(0.2)
304         check_Rresult(self.parent, pid)            
305         self.count += 1
306         keepGoing = self.dlg.Update(self.count,u"Ecriture des résultats")
307          
308         listfileout = self.dolayout(self.chioption)
309             #listfileout=dlg.ShowChi2(ColSel1,ColSel2)
310             #parent.FreqNum += 1
311             #parent.DictTab[u"Chi2_%s*"%parent.FreqNum]=listfileout
312 #             parent.newtab = wx.html.HtmlWindow(parent.nb, -1)
313 #             if "gtk2" in wx.PlatformInfo:
314 #                 parent.newtab.SetStandardFonts()
315 #             parent.newtab.LoadPage(listfileout[len(listfileout)-1])
316 #             parent.nb.AddPage(parent.newtab,u"Chi2_%s*"%parent.FreqNum)
317 #             parent.nb.SetSelection(parent.nb.GetPageCount()-1)
318 #             parent.ShowTab(wx.EVT_BUTTON)
319 #             parent.DisEnSaveTabAs(True)
320 #        self.count += 1
321 #        keepGoing = self.dlg.Update(self.count,u"Fini")
322
323     def dolayout(self, option):
324         ListFile=[False]
325         file=open(self.OutFrame,'rU')
326         content=file.readlines()
327         file.close()
328         lcont = [line.replace('"','').replace('\n','').split(';') for line in content]
329     
330         lcont.pop(0)
331         lcont.pop(0)
332         
333         allcoord = []
334         names = []
335
336         res = [chi for chi in lcont if chi[0]=='res']
337         res = [make_res(line) for line in res]
338         coord_res = [i for i,chi in enumerate(lcont) if chi[0]=='res']
339         if option['valobs']:
340             allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*obs*'])
341             names.append(u'Valeurs observées')
342         if option['valtheo'] :
343             allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*exp*'])
344             names.append(u'Valeurs théoriques')
345         if option['resi'] :
346             allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*resi*'])
347             names.append(u'Residuals')
348         if option['contrib'] :
349             allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*contrib*'])
350             names.append(u'Contributions a posteriori')
351         if option['pourcent'] : 
352             allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*pr*'])
353             names.append(u'Pourcentages')
354         if option['pourcentl'] :
355             allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*prl*'])
356             names.append(u'Pourcentages en ligne')
357         if option['pourcentc'] :
358             allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*prc*'])
359             names.append(u'Pourcentages en colonne')
360     
361         allcoord.append(coord_res)
362         allhtml = [[clean_line(lcont[allcoord[i][j]+1:allcoord[i+1][j]]) for j, line in enumerate(allcoord[i])] for i, tab in enumerate(allcoord) if i!=len(allcoord)-1]
363         allhtml = [make_table(val,names[i],res) for i,val in enumerate(allhtml)]
364         links = make_link_list(res, self.TextCroise)
365         html_res = make_restab(res)
366         allhtml.insert(0,html_res)
367         titles = make_title(res, self.TextCroise)
368         allhtml.insert(0,titles)
369         
370         if option['graph'] :
371             graphs = [line[7] for line in res]
372             ListFile += graphs
373             html_graphs = make_htmlgraphs(graphs)
374             allhtml.append(html_graphs)
375
376         header=u"""
377         <html>\n
378         <meta http-equiv="content-Type" content="text/html; charset=%s" />\n
379         <body>\n
380         <h1>Test du Chi2</h1>\n
381         <br>
382         <table border=1><tr><td>
383         Légende : <br>
384         <font color=green>p &lt;= 0.05</font><br>
385         <font color=blue>p &lt;= 0.05 mais il y a des valeurs théoriques &lt; 5</font><br>
386         <font color=red>p &gt; 0.05</font>
387         </td></tr></table><br><br>
388         """%self.parent.SysEncoding
389
390         pretxt = '<br>\n'.join(links)+'<br><hr><br>\n'
391         txt = '<br><hr><br>\n'.join(['<br><br>'.join([tab[i] for tab in allhtml]) for i,val in enumerate(res)])
392         txt = header + pretxt + txt + '\n</body></html>'
393
394         fileout=os.path.join(self.parametres['pathout'],'resultats-chi2.html')
395         with open(fileout, 'w') as f :
396             f.write(txt)
397         ListFile.append(fileout)         
398         return ListFile