2 # -*- coding: utf-8 -*-
3 #Author: Pierre Ratinaud
4 #Copyright (c) 2016 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 McNemar(AnalyseMatrix):
61 def doparametres(self, dlg = None):
64 dial = ChiDialog(self.parent, -1, u"Chi2 McNemar", 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) {
147 chi <- mcnemar.test(tab)
148 #chi<-chisq.test(tab)
156 #chi$contrib<-(tab-chi$expected)/sqrt(chi$expected * ((1 - RS/GT) %%*%% t(1 - CS/GT)))
158 listcol[[cont]]<-ncol(tab)
161 chi <- list(observed = tab, residuals = tab, contrib = tab, statistic = 0, p.value = 1, expected = tab, message = 'pas de calcul')
162 listres[[cont]] <- chi
163 listcol[[cont]]<-ncol(tab)
168 maxcol<-max(unlist(listcol))+1
169 if (maxcol<7) {maxcol<-7}
170 frameout<-matrix('*',1,maxcol)
172 for (chi in listres) {
173 if (min(chi$expected)<5) {
178 if ('message' %%in%% attributes(chi)$names) {
179 att <- "Ce chi2 n\'a pas été calculé"
180 nom_colresi<-colnames(chi$observed)
181 chi$prl <- chi$expected
182 chi$prc <- chi$expected
183 st <- sum(chi$observed)
185 nom_colresi<-colnames(chi$observed)
186 st <- sum(chi$observed)
187 sc <- colSums(chi$observed)
188 sr <- rowSums(chi$observed)
189 chi$prl <- round((chi$observed/sr)*100,2)
190 chi$prc <- t(round((t(chi$observed)/sc)*100,2))
192 fileout<-paste('histo_',count,sep='')
193 fileout<-paste(fileout,'.png',sep='')
195 fileout<-file.path("%s",fileout)
196 if (max(nchar(colnames(chi$observed)))>15) {
197 leg <- 1:length(colnames(chi$observed))
199 leg <- colnames(chi$observed)
202 width<-ncol(chi$observed)*100
203 if (width < 350) {width <- 350}
204 open_file_graph(fileout,width = width, height = 300)
206 layout(matrix(c(1,2),1,2, byrow=TRUE),widths=c(3,1))
209 if (!bw) colors <- rainbow(length(rownames(chi$observed)))
210 else colors <- gray.colors(length(rownames(chi$observed)))
211 barplot(chi$prl,names.arg = leg, beside=TRUE,border=NA, col=colors)
214 plot(0, axes = FALSE, pch = '')
215 legend(x = 'center' , rownames(chi$observed), fill = colors)
218 chi$prl <- cbind(chi$prl, total = rowSums(chi$prl))
219 chi$prc <- rbind(chi$prc, total = colSums(chi$prc))
220 chi$observed<-rbind(chi$observed,total=colSums(chi$observed))
221 chi$observed<-cbind(chi$observed,total=rowSums(chi$observed))
222 chi$pr <- round((chi$observed/st)*100,2)
223 chi$expected<-rbind(chi$expected,total=colSums(chi$expected))
224 chi$expected<-cbind(chi$expected,total=rowSums(chi$expected))
225 chi$expected<-round(chi$expected,digits=2)
226 chi$residuals<-round(chi$residuals,digits=2)
227 chi$contrib<-round(chi$contrib, digits=2)
228 nom_col<-colnames(chi$observed)
230 if (ncol(chi$observed)<maxcol) {
231 for (i in 1:(maxcol-ncol(chi$observed))) {
232 chi$observed<-cbind(chi$observed,'**')
233 chi$pr<-cbind(chi$pr,'**')
234 chi$prl<-cbind(chi$prl,'**')
235 chi$prc<-cbind(chi$prc,'**')
236 chi$expected<-cbind(chi$expected,'**')
237 chi$residuals<-cbind(chi$residuals,'**')
238 chi$contrib<-cbind(chi$contrib,'**')
239 nom_col<-append(nom_col,'**')
240 nom_colresi<-append(nom_colresi,'**')
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 } else if (ncol(chi$observed)==maxcol) {
247 chi$residuals<-cbind(chi$residuals,'**')
248 chi$contrib<-cbind(chi$contrib,'**')
249 nom_colresi<-append(nom_colresi,'**')
250 chi$prc<-cbind(chi$prc,'**')
253 li<-matrix('*obs*',1,maxcol)
254 frameout<-rbind(frameout,li)
255 frameout<-rbind(frameout,nom_col)
256 frameout<-rbind(frameout,chi$observed)
259 li<-matrix('*exp*',1,maxcol)
260 frameout<-rbind(frameout,li)
261 frameout<-rbind(frameout,nom_col)
262 frameout<-rbind(frameout,chi$expected)
265 li<-matrix('*resi*',1,maxcol)
266 frameout<-rbind(frameout,li)
267 frameout<-rbind(frameout,nom_colresi)
268 frameout<-rbind(frameout,chi$residuals)
271 li<-matrix('*contrib*',1,maxcol)
272 frameout<-rbind(frameout,li)
273 frameout<-rbind(frameout,nom_colresi)
274 frameout<-rbind(frameout,chi$contrib)
277 li<-matrix('*pr*', 1, maxcol)
278 frameout<-rbind(frameout,li)
279 frameout<-rbind(frameout,nom_col)
280 frameout<-rbind(frameout,chi$pr)
283 li<-matrix('*prl*', 1, maxcol)
284 frameout<-rbind(frameout,li)
285 frameout<-rbind(frameout,nom_col)
286 frameout<-rbind(frameout,chi$prl)
289 li<-matrix('*prc*', 1, maxcol)
290 frameout<-rbind(frameout,li)
291 frameout<-rbind(frameout,nom_colresi)
292 frameout<-rbind(frameout,chi$prc)
294 res<-c('****','chi',chi$statistic,'p',chi$p.value,att,fileout)
295 frameout<-rbind(frameout,res)
297 li<-matrix('fin_analyse',1,maxcol)
298 frameout<-rbind(frameout,li)
299 write.csv2(frameout,file="%s")
300 """ % (ffr(self.parametres['pathout']),ffr(self.OutFrame))
301 tmpfile=tempfile.mktemp(dir=self.TEMPDIR)
303 tmpscript=open(tmpfile,'w')
306 pid = exec_rcode(self.RPath, tmpfile, wait = False)
307 while pid.poll() == None :
309 check_Rresult(self.parent, pid)
311 keepGoing = self.dlg.Update(self.count,u"Ecriture des résultats")
313 listfileout = self.dolayout(self.chioption)
314 #listfileout=dlg.ShowChi2(ColSel1,ColSel2)
316 #parent.DictTab[u"Chi2_%s*"%parent.FreqNum]=listfileout
317 # parent.newtab = wx.html.HtmlWindow(parent.nb, -1)
318 # if "gtk2" in wx.PlatformInfo:
319 # parent.newtab.SetStandardFonts()
320 # parent.newtab.LoadPage(listfileout[len(listfileout)-1])
321 # parent.nb.AddPage(parent.newtab,u"Chi2_%s*"%parent.FreqNum)
322 # parent.nb.SetSelection(parent.nb.GetPageCount()-1)
323 # parent.ShowTab(wx.EVT_BUTTON)
324 # parent.DisEnSaveTabAs(True)
326 # keepGoing = self.dlg.Update(self.count,u"Fini")
328 def dolayout(self, option):
330 file=open(self.OutFrame,'rU')
331 content=file.readlines()
333 lcont = [line.replace('"','').replace('\n','').split(';') for line in content]
341 res = [chi for chi in lcont if chi[0]=='res']
342 res = [make_res(line) for line in res]
343 coord_res = [i for i,chi in enumerate(lcont) if chi[0]=='res']
345 allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*obs*'])
346 names.append(u'Valeurs observées')
347 if option['valtheo'] :
348 allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*exp*'])
349 names.append(u'Valeurs théoriques')
351 allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*resi*'])
352 names.append(u'Residuals')
353 if option['contrib'] :
354 allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*contrib*'])
355 names.append(u'Contributions a posteriori')
356 if option['pourcent'] :
357 allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*pr*'])
358 names.append(u'Pourcentages')
359 if option['pourcentl'] :
360 allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*prl*'])
361 names.append(u'Pourcentages en ligne')
362 if option['pourcentc'] :
363 allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*prc*'])
364 names.append(u'Pourcentages en colonne')
366 allcoord.append(coord_res)
367 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]
368 allhtml = [make_table(val,names[i],res) for i,val in enumerate(allhtml)]
369 links = make_link_list(res, self.TextCroise)
370 html_res = make_restab(res)
371 allhtml.insert(0,html_res)
372 titles = make_title(res, self.TextCroise)
373 allhtml.insert(0,titles)
376 graphs = [line[7] for line in res]
378 html_graphs = make_htmlgraphs(graphs)
379 allhtml.append(html_graphs)
383 <meta http-equiv="content-Type" content="text/html; charset=%s" />\n
385 <h1>Test du Chi2</h1>\n
387 <table border=1><tr><td>
389 <font color=green>p <= 0.05</font><br>
390 <font color=blue>p <= 0.05 mais il y a des valeurs théoriques < 5</font><br>
391 <font color=red>p > 0.05</font>
392 </td></tr></table><br><br>
393 """%self.parent.SysEncoding
395 pretxt = '<br>\n'.join(links)+'<br><hr><br>\n'
396 txt = '<br><hr><br>\n'.join(['<br><br>'.join([tab[i] for tab in allhtml]) for i,val in enumerate(res)])
397 txt = header + pretxt + txt + '\n</body></html>'
399 fileout=os.path.join(self.parametres['pathout'],'resultats-chi2.html')
400 with open(fileout, 'w') as f :
402 ListFile.append(fileout)