2 # -*- coding: utf-8 -*-
3 #Author: Pierre Ratinaud
4 #Copyright (c) 2010 Pierre Ratinaud
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
22 if float(line[5]) <= 0.05 and line[6] != 'warning':
24 elif float(line[5]) <= 0.05 and line[6] == 'warning':
30 def clean_line(result) :
31 return [[val for val in line if val != '**'] for line in result]
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)]
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)]
39 def make_htmlgraphs(graphs) :
40 return ['<img src=%s>' % os.path.basename(val) for val in graphs]
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)]
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)]
49 chioption = { 'valobs' : True,
60 class ChiSquare(AnalyseMatrix):
61 def doparametres(self, dlg = None):
64 dial = ChiDialog(self.parent, -1, u"Chi2", chioption, self.tableau, size=(400, 350),
65 style = wx.DEFAULT_DIALOG_STYLE
68 val = dial.ShowModal()
70 self.colsel1 = dial.list_box_1.GetSelections()
71 self.colsel2 = dial.list_box_2.GetSelections()
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()
84 self.parametres.update(chioption)
85 self.chioption = chioption
90 self.parametres = None
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')
100 for i in self.colsel1 :
101 for j in self.colsel2 :
102 self.TextCroise.append(self.tableau.colnames[i] + ' / ' + self.tableau.colnames[j])
104 for val in self.chioption :
105 if self.chioption[val]:
106 rchioption[val] = 'TRUE'
108 rchioption[val] = 'FALSE'
111 """%ffr(self.parent.RscriptsPath['Rfunct'])
114 """ % ffr(self.parent.RscriptsPath['Rgraph'])
125 """ % (rchioption['valobs'], rchioption['valtheo'], rchioption['contrib'], rchioption['resi'], rchioption['pourcent'], rchioption['pourcentl'], rchioption['pourcentc'], rchioption['graph'], rchioption['bw'])
127 datadm <- read.csv2("%s", encoding="%s", header = TRUE, row.names = 1, sep='\\t', quote = '"', na.string = '')
131 """%(ffr(self.tableau.parametres['csvfile']), self.tableau.parametres['syscoding'])
132 if len(self.colsel1)==1:
133 strsel1=str(self.colsel1).replace(',','')
135 strsel1=str(self.colsel1)
136 if len(self.colsel2)==1:
137 strsel2=str(self.colsel2).replace(',','')
139 strsel2=str(self.colsel2)
141 for (i in c%s) {""" % strsel1
143 for (j in c%s) {""" % strsel2
145 tab<-table(datadm[,i+1],datadm[,j+1])
146 if (min(dim(tab)) != 1) {
151 chi$contrib<-(tab-chi$expected)/sqrt(chi$expected * ((1 - RS/GT) %%*%% t(1 - CS/GT)))
153 listcol[[cont]]<-ncol(tab)
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)
163 maxcol<-max(unlist(listcol))+1
164 if (maxcol<7) {maxcol<-7}
165 frameout<-matrix('*',1,maxcol)
167 for (chi in listres) {
168 if (min(chi$expected)<5) {
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)
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))
187 fileout<-paste('histo_',count,sep='')
188 fileout<-paste(fileout,'.png',sep='')
190 fileout<-file.path("%s",fileout)
191 if (max(nchar(colnames(chi$observed)))>15) {
192 leg <- 1:length(colnames(chi$observed))
194 leg <- colnames(chi$observed)
197 width<-ncol(chi$observed)*100
198 if (width < 350) {width <- 350}
199 open_file_graph(fileout,width = width, height = 300)
201 layout(matrix(c(1,2),1,2, byrow=TRUE),widths=c(3,1))
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)
209 plot(0, axes = FALSE, pch = '')
210 legend(x = 'center' , rownames(chi$observed), fill = colors)
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)
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,'**')
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,'**')
248 li<-matrix('*obs*',1,maxcol)
249 frameout<-rbind(frameout,li)
250 frameout<-rbind(frameout,nom_col)
251 frameout<-rbind(frameout,chi$observed)
254 li<-matrix('*exp*',1,maxcol)
255 frameout<-rbind(frameout,li)
256 frameout<-rbind(frameout,nom_col)
257 frameout<-rbind(frameout,chi$expected)
260 li<-matrix('*resi*',1,maxcol)
261 frameout<-rbind(frameout,li)
262 frameout<-rbind(frameout,nom_colresi)
263 frameout<-rbind(frameout,chi$residuals)
266 li<-matrix('*contrib*',1,maxcol)
267 frameout<-rbind(frameout,li)
268 frameout<-rbind(frameout,nom_colresi)
269 frameout<-rbind(frameout,chi$contrib)
272 li<-matrix('*pr*', 1, maxcol)
273 frameout<-rbind(frameout,li)
274 frameout<-rbind(frameout,nom_col)
275 frameout<-rbind(frameout,chi$pr)
278 li<-matrix('*prl*', 1, maxcol)
279 frameout<-rbind(frameout,li)
280 frameout<-rbind(frameout,nom_col)
281 frameout<-rbind(frameout,chi$prl)
284 li<-matrix('*prc*', 1, maxcol)
285 frameout<-rbind(frameout,li)
286 frameout<-rbind(frameout,nom_colresi)
287 frameout<-rbind(frameout,chi$prc)
289 res<-c('****','chi',chi$statistic,'p',chi$p.value,att,fileout)
290 frameout<-rbind(frameout,res)
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)
298 tmpscript=open(tmpfile,'w')
301 pid = exec_rcode(self.RPath, tmpfile, wait = False)
302 while pid.poll() == None :
304 check_Rresult(self.parent, pid)
306 keepGoing = self.dlg.Update(self.count,u"Ecriture des résultats")
308 listfileout = self.dolayout(self.chioption)
309 #listfileout=dlg.ShowChi2(ColSel1,ColSel2)
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)
321 # keepGoing = self.dlg.Update(self.count,u"Fini")
323 def dolayout(self, option):
325 file=open(self.OutFrame,'rU')
326 content=file.readlines()
328 lcont = [line.replace('"','').replace('\n','').split(';') for line in content]
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']
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')
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')
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)
371 graphs = [line[7] for line in res]
373 html_graphs = make_htmlgraphs(graphs)
374 allhtml.append(html_graphs)
378 <meta http-equiv="content-Type" content="text/html; charset=%s" />\n
380 <h1>Test du Chi2</h1>\n
382 <table border=1><tr><td>
384 <font color=green>p <= 0.05</font><br>
385 <font color=blue>p <= 0.05 mais il y a des valeurs théoriques < 5</font><br>
386 <font color=red>p > 0.05</font>
387 </td></tr></table><br><br>
388 """%self.parent.SysEncoding
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>'
394 fileout=os.path.join(self.parametres['pathout'],'resultats-chi2.html')
395 with open(fileout, 'w') as f :
397 ListFile.append(fileout)