...
[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
61 class MakeChi2():
62     def __init__(self, parent, select1, select2, chioption, tableau):
63         self.tableau = tableau
64         self.OutFrame=tempfile.mktemp(dir=parent.TEMPDIR)
65         print self.OutFrame
66         self.parent=parent
67         self.encode=self.parent.encode
68         self.TEMPDIR=parent.TEMPDIR
69         self.RPath=parent.PathPath.get('PATHS','rpath')
70         self.TextCroise=[]
71         for i in select1 :
72             for j in select2 :
73                 self.TextCroise.append(self.tableau.colnames[i] + ' / ' + self.tableau.colnames[j])
74         rchioption = {}
75         for val in chioption :
76             if chioption[val]:
77                 rchioption[val] = 'TRUE'
78             else :
79                 rchioption[val] = 'FALSE'
80         txt="""
81         source("%s")
82         """%self.parent.RscriptsPath['Rfunct']
83 #        if parent.tableau.: rownames=1
84 #        else : rownames='NULL'
85 #        if parent.g_header : header = 'TRUE'
86 #        else : header = 'FALSE'
87         txt += """
88         source("%s")
89         """ % ffr(self.parent.RscriptsPath['Rgraph'])
90         txt += """
91         doobs <- %s
92         doexp <- %s
93         docontrib <- %s
94         doresi <- %s
95         dopr <- %s
96         doprl <- %s
97         doprc <- %s
98         dograph <- %s
99         bw <- %s
100         """ % (rchioption['valobs'], rchioption['valtheo'], rchioption['contrib'], rchioption['resi'], rchioption['pourcent'], rchioption['pourcentl'], rchioption['pourcentc'], rchioption['graph'], rchioption['bw'])
101         txt+="""
102         datadm <- read.csv2("%s", encoding="%s", header = TRUE, row.names = 1, sep='\\t', quote = '"', na.string = '')
103         listres<-list()
104         listcol<-list()
105         cont<-1
106         """%(ffr(self.tableau.parametres['csvfile']), self.tableau.parametres['syscoding'])
107         if len(select1)==1:
108             strsel1=str(select1).replace(',','')
109         else:
110             strsel1=str(select1)
111         if len(select2)==1:
112             strsel2=str(select2).replace(',','')
113         else:
114             strsel2=str(select2)
115         txt+="""
116         for (i in c%s) {"""%strsel1
117         txt+="""
118             for (j in c%s) {"""%strsel2
119         txt+="""
120                 tab<-table(datadm[,i+1],datadm[,j+1])
121                 if (min(dim(tab)) != 1) {
122                     chi<-chisq.test(tab)
123                     CS<-colSums(tab)
124                     RS<-rowSums(tab)
125                     GT<-sum(tab)
126                     chi$contrib<-(tab-chi$expected)/sqrt(chi$expected * ((1 - RS/GT) %%*%% t(1 - CS/GT)))
127                     listres[[cont]]<-chi
128                     listcol[[cont]]<-ncol(tab)
129                     cont<-cont+1
130                 } else {
131                     chi <- list(observed = tab, residuals = tab, contrib = tab, statistic = 0, p.value = 1, expected = tab, message = 'pas de calcul')
132                     listres[[cont]] <- chi
133                     listcol[[cont]]<-ncol(tab)
134                     cont <- cont + 1
135                 }
136             }
137         }
138         maxcol<-max(unlist(listcol))+1
139         if (maxcol<7) {maxcol<-7}
140         frameout<-matrix('*',1,maxcol)
141         count<-0
142         for (chi in listres) {
143             if (min(chi$expected)<5) {
144                 att<-"warning"
145             } else {
146                 att<-""
147             }
148             if ('message' %%in%% attributes(chi)$names) {
149                 att <- "Ce chi2 n\'a pas été calculé"
150                 nom_colresi<-colnames(chi$observed)
151                 chi$prl <- chi$expected
152                 chi$prc <- chi$expected
153                 st <- sum(chi$observed)
154             } else {
155                 nom_colresi<-colnames(chi$observed)
156                 st <- sum(chi$observed)
157                 sc <- colSums(chi$observed)
158                 sr <- rowSums(chi$observed)
159                 chi$prl <- round((chi$observed/sr)*100,2)
160                 chi$prc <- t(round((t(chi$observed)/sc)*100,2))
161             }
162             fileout<-paste('histo_',count,sep='')
163             fileout<-paste(fileout,'.png',sep='')
164             count<-count+1
165             fileout<-file.path("%s",fileout)
166             if (max(nchar(colnames(chi$observed)))>15) {
167                 leg <- 1:length(colnames(chi$observed))
168             } else {
169                 leg <- colnames(chi$observed)
170             }
171             if (dograph) {
172                 width<-ncol(chi$observed)*100
173                 if (width < 350) {width <- 350}
174                 open_file_graph(fileout,width = width, height = 300)
175                 par(mar=c(0,0,0,0))
176                 layout(matrix(c(1,2),1,2, byrow=TRUE),widths=c(3,1))
177                 par(mar=c(2,2,1,0))
178                 par(cex=0.8)
179                 if (!bw) colors <- rainbow(length(rownames(chi$observed)))
180                 else colors <- gray.colors(length(rownames(chi$observed)))
181                 barplot(chi$prl,names.arg = leg, beside=TRUE,border=NA, col=colors)
182                 par(mar=c(0,0,0,0))
183                 par(cex=0.8)
184                 plot(0, axes = FALSE, pch = '')
185                 legend(x = 'center' , rownames(chi$observed), fill = colors)
186                 dev.off()
187             }
188             chi$prl <- cbind(chi$prl, total = rowSums(chi$prl))
189             chi$prc <- rbind(chi$prc, total = colSums(chi$prc))
190             chi$observed<-rbind(chi$observed,total=colSums(chi$observed))
191             chi$observed<-cbind(chi$observed,total=rowSums(chi$observed))
192             chi$pr <- round((chi$observed/st)*100,2)
193             chi$expected<-rbind(chi$expected,total=colSums(chi$expected))
194             chi$expected<-cbind(chi$expected,total=rowSums(chi$expected))
195             chi$expected<-round(chi$expected,digits=2)
196             chi$residuals<-round(chi$residuals,digits=2)
197             chi$contrib<-round(chi$contrib, digits=2)
198             nom_col<-colnames(chi$observed)
199            
200             if (ncol(chi$observed)<maxcol) {
201                 for (i in 1:(maxcol-ncol(chi$observed))) {
202                     chi$observed<-cbind(chi$observed,'**')
203                     chi$pr<-cbind(chi$pr,'**')
204                     chi$prl<-cbind(chi$prl,'**')
205                     chi$prc<-cbind(chi$prc,'**')
206                     chi$expected<-cbind(chi$expected,'**')
207                     chi$residuals<-cbind(chi$residuals,'**')
208                     chi$contrib<-cbind(chi$contrib,'**')
209                     nom_col<-append(nom_col,'**')
210                     nom_colresi<-append(nom_colresi,'**')
211                 }
212                 chi$residuals<-cbind(chi$residuals,'**')
213                 chi$contrib<-cbind(chi$contrib,'**')
214                 nom_colresi<-append(nom_colresi,'**')
215                 chi$prc<-cbind(chi$prc,'**')
216             } else if (ncol(chi$observed)==maxcol) {
217                 chi$residuals<-cbind(chi$residuals,'**')
218                 chi$contrib<-cbind(chi$contrib,'**')
219                 nom_colresi<-append(nom_colresi,'**')
220                 chi$prc<-cbind(chi$prc,'**')
221             }
222             if (doobs) {
223                 li<-matrix('*obs*',1,maxcol)
224                 frameout<-rbind(frameout,li)
225                 frameout<-rbind(frameout,nom_col)
226                 frameout<-rbind(frameout,chi$observed)
227             }
228             if (doexp) {
229                 li<-matrix('*exp*',1,maxcol)
230                 frameout<-rbind(frameout,li)
231                 frameout<-rbind(frameout,nom_col)
232                 frameout<-rbind(frameout,chi$expected)
233             }
234             if (doresi) {
235                 li<-matrix('*resi*',1,maxcol)
236                 frameout<-rbind(frameout,li)
237                 frameout<-rbind(frameout,nom_colresi)
238                 frameout<-rbind(frameout,chi$residuals)
239             }
240             if (docontrib) {
241                 li<-matrix('*contrib*',1,maxcol)
242                 frameout<-rbind(frameout,li)
243                 frameout<-rbind(frameout,nom_colresi)
244                 frameout<-rbind(frameout,chi$contrib)
245             }
246             if (dopr) {
247                 li<-matrix('*pr*', 1, maxcol)
248                 frameout<-rbind(frameout,li)
249                 frameout<-rbind(frameout,nom_col)
250                 frameout<-rbind(frameout,chi$pr)
251             }
252             if (doprl) {
253                 li<-matrix('*prl*', 1, maxcol)
254                 frameout<-rbind(frameout,li)
255                 frameout<-rbind(frameout,nom_col)
256                 frameout<-rbind(frameout,chi$prl)
257             }
258             if (doprc) {
259                 li<-matrix('*prc*', 1, maxcol)
260                 frameout<-rbind(frameout,li)
261                 frameout<-rbind(frameout,nom_colresi)
262                 frameout<-rbind(frameout,chi$prc)
263             }
264             res<-c('****','chi',chi$statistic,'p',chi$p.value,att,fileout)
265             frameout<-rbind(frameout,res)
266         }
267         li<-matrix('fin_analyse',1,maxcol)
268         frameout<-rbind(frameout,li)
269         write.csv2(frameout,file="%s")
270         """ % (ffr(parent.TEMPDIR),ffr(self.OutFrame))
271         tmpfile=tempfile.mktemp(dir=self.TEMPDIR)
272         print tmpfile
273         tmpscript=open(tmpfile,'w')
274         tmpscript.write(txt)
275         tmpscript.close()
276         pid = exec_rcode(self.RPath, tmpfile, wait = False)
277         while pid.poll() == None :
278             sleep(0.2)
279         check_Rresult(self.parent, pid)
280
281     def dolayout(self, option):
282         ListFile=[False]
283         file=open(self.OutFrame,'rU')
284         content=file.readlines()
285         file.close()
286         lcont = [line.replace('"','').replace('\n','').split(';') for line in content]
287     
288         lcont.pop(0)
289         lcont.pop(0)
290         
291         allcoord = []
292         names = []
293
294         res = [chi for chi in lcont if chi[0]=='res']
295         res = [make_res(line) for line in res]
296         coord_res = [i for i,chi in enumerate(lcont) if chi[0]=='res']
297         if option['valobs']:
298             allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*obs*'])
299             names.append(u'Valeurs observées')
300         if option['valtheo'] :
301             allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*exp*'])
302             names.append(u'Valeurs théoriques')
303         if option['resi'] :
304             allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*resi*'])
305             names.append(u'Residuals')
306         if option['contrib'] :
307             allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*contrib*'])
308             names.append(u'Contributions a posteriori')
309         if option['pourcent'] : 
310             allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*pr*'])
311             names.append(u'Pourcentages')
312         if option['pourcentl'] :
313             allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*prl*'])
314             names.append(u'Pourcentages en ligne')
315         if option['pourcentc'] :
316             allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*prc*'])
317             names.append(u'Pourcentages en colonne')
318     
319         allcoord.append(coord_res)
320         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]
321     
322         allhtml = [make_table(val,names[i],res) for i,val in enumerate(allhtml)]
323     
324         links = make_link_list(res, self.TextCroise)
325         #colors = [line[-1] for line in res]
326     
327     #    good = [i for i,chi in enumerate(res) if chi[-1] == 'green' or chi[-1] == 'blue']
328         #select_good = [[val[i] for i in good] for val in tout]
329     
330     
331         html_res = make_restab(res)
332         allhtml.insert(0,html_res)
333
334         titles = make_title(res, self.TextCroise)
335         allhtml.insert(0,titles)
336         
337         if option['graph'] :
338             graphs = [line[7] for line in res]
339             ListFile += graphs
340             html_graphs = make_htmlgraphs(graphs)
341             allhtml.append(html_graphs)
342
343         header=u"""
344         <html>\n
345         <meta http-equiv="content-Type" content="text/html; charset=%s" />\n
346         <body>\n
347         <h1>Test du Chi2</h1>\n
348         <br>
349         <table border=1><tr><td>
350         Légende : <br>
351         <font color=green>p &lt;= 0.05</font><br>
352         <font color=blue>p &lt;= 0.05 mais il y a des valeurs théoriques &lt; 5</font><br>
353         <font color=red>p &gt; 0.05</font>
354         </td></tr></table><br><br>
355         """%self.parent.SysEncoding
356
357     
358         pretxt = '<br>\n'.join(links)+'<br><hr><br>\n'
359         txt = '<br><hr><br>\n'.join(['<br><br>'.join([tab[i] for tab in allhtml]) for i,val in enumerate(res)])
360         txt = header + pretxt + txt + '\n</body></html>'
361
362         fileout=os.path.join(self.parametres['pathout'],'resultats-chi2.html')
363         with open(fileout, 'w') as f :
364             f.write(txt)
365         ListFile.append(fileout)         
366         return ListFile
367
368 class ChiSquare(AnalyseMatrix):
369     def doparametres(self, dlg = None):
370         if dlg is None :
371             return
372         dial = ChiDialog(self.parent, -1, u"Chi2", chioption, self.tableau, size=(400, 350),
373                      style = wx.DEFAULT_DIALOG_STYLE
374                      )
375         dial.CenterOnParent()
376         val = dial.ShowModal()
377         if val==wx.ID_OK : 
378             dlg.Center()
379             self.count = 1
380             keepGoing = dlg.Update(self.count)
381             
382             self.colsel1 = dial.list_box_1.GetSelections()
383             self.colsel2 = dial.list_box_2.GetSelections()
384             if dial.chiopt :
385                 chioption['valobs'] = dial.dial.check1.GetValue()
386                 chioption['valtheo'] = dial.dial.check2.GetValue()
387                 chioption['resi'] = dial.dial.check3.GetValue()
388                 chioption['contrib'] = dial.dial.check4.GetValue()
389                 chioption['pourcent'] = dial.dial.check5.GetValue()
390                 chioption['pourcentl'] = dial.dial.check6.GetValue()
391                 chioption['pourcentc'] = dial.dial.check7.GetValue()
392                 chioption['graph'] = dial.dial.check8.GetValue()
393                 chioption['bw'] = dial.dial.checkbw.GetValue()
394                 dial.dial.Destroy()
395             dial.Destroy()
396             self.parametres.update(chioption)
397             self.chioption = chioption
398         else :
399             if dial.chiopt :
400                 dial.dial.Destroy()
401             dial.Destroy()
402             self.parametres = None
403             
404     def doanalyse(self):
405
406
407             #self.dlg=wx.ProgressDialog("Traitements",
408             #           "Veuillez patienter...",
409             #           maximum = 4,
410             #           parent=parent,
411             #           style = wx.PD_APP_MODAL|wx.PD_AUTO_HIDE|wx.PD_ELAPSED_TIME
412             #            )
413
414
415             
416         self.count += 1
417         keepGoing = self.dlg.Update(self.count,u"Analyse dans R...")
418         #analyse=MakeChi2(self.parent, self.colsel1, self.colsel2, self.chioption, self.tableau)
419         #self.tableau = tableau
420         self.OutFrame=tempfile.mktemp(dir=self.parent.TEMPDIR)
421         print self.OutFrame
422         #self.parent=parent
423         self.encode=self.parent.encode
424         self.TEMPDIR=self.parent.TEMPDIR
425         self.RPath=self.parent.PathPath.get('PATHS','rpath')
426         self.TextCroise=[]
427         for i in self.colsel1 :
428             for j in self.colsel2 :
429                 self.TextCroise.append(self.tableau.colnames[i] + ' / ' + self.tableau.colnames[j])
430         rchioption = {}
431         for val in self.chioption :
432             if self.chioption[val]:
433                 rchioption[val] = 'TRUE'
434             else :
435                 rchioption[val] = 'FALSE'
436         txt="""
437         source("%s")
438         """%self.parent.RscriptsPath['Rfunct']
439 #        if parent.tableau.: rownames=1
440 #        else : rownames='NULL'
441 #        if parent.g_header : header = 'TRUE'
442 #        else : header = 'FALSE'
443         txt += """
444         source("%s")
445         """ % ffr(self.parent.RscriptsPath['Rgraph'])
446         txt += """
447         doobs <- %s
448         doexp <- %s
449         docontrib <- %s
450         doresi <- %s
451         dopr <- %s
452         doprl <- %s
453         doprc <- %s
454         dograph <- %s
455         bw <- %s
456         """ % (rchioption['valobs'], rchioption['valtheo'], rchioption['contrib'], rchioption['resi'], rchioption['pourcent'], rchioption['pourcentl'], rchioption['pourcentc'], rchioption['graph'], rchioption['bw'])
457         txt+="""
458         datadm <- read.csv2("%s", encoding="%s", header = TRUE, row.names = 1, sep='\\t', quote = '"', na.string = '')
459         listres<-list()
460         listcol<-list()
461         cont<-1
462         """%(ffr(self.tableau.parametres['csvfile']), self.tableau.parametres['syscoding'])
463         if len(self.colsel1)==1:
464             strsel1=str(self.colsel1).replace(',','')
465         else:
466             strsel1=str(self.colsel1)
467         if len(self.colsel2)==1:
468             strsel2=str(self.colsel2).replace(',','')
469         else:
470             strsel2=str(self.colsel2)
471         txt+="""
472         for (i in c%s) {""" % strsel1
473         txt+="""
474             for (j in c%s) {""" % strsel2
475         txt+="""
476                 tab<-table(datadm[,i+1],datadm[,j+1])
477                 if (min(dim(tab)) != 1) {
478                     chi<-chisq.test(tab)
479                     CS<-colSums(tab)
480                     RS<-rowSums(tab)
481                     GT<-sum(tab)
482                     chi$contrib<-(tab-chi$expected)/sqrt(chi$expected * ((1 - RS/GT) %%*%% t(1 - CS/GT)))
483                     listres[[cont]]<-chi
484                     listcol[[cont]]<-ncol(tab)
485                     cont<-cont+1
486                 } else {
487                     chi <- list(observed = tab, residuals = tab, contrib = tab, statistic = 0, p.value = 1, expected = tab, message = 'pas de calcul')
488                     listres[[cont]] <- chi
489                     listcol[[cont]]<-ncol(tab)
490                     cont <- cont + 1
491                 }
492             }
493         }
494         maxcol<-max(unlist(listcol))+1
495         if (maxcol<7) {maxcol<-7}
496         frameout<-matrix('*',1,maxcol)
497         count<-0
498         for (chi in listres) {
499             if (min(chi$expected)<5) {
500                 att<-"warning"
501             } else {
502                 att<-""
503             }
504             if ('message' %%in%% attributes(chi)$names) {
505                 att <- "Ce chi2 n\'a pas été calculé"
506                 nom_colresi<-colnames(chi$observed)
507                 chi$prl <- chi$expected
508                 chi$prc <- chi$expected
509                 st <- sum(chi$observed)
510             } else {
511                 nom_colresi<-colnames(chi$observed)
512                 st <- sum(chi$observed)
513                 sc <- colSums(chi$observed)
514                 sr <- rowSums(chi$observed)
515                 chi$prl <- round((chi$observed/sr)*100,2)
516                 chi$prc <- t(round((t(chi$observed)/sc)*100,2))
517             }
518             fileout<-paste('histo_',count,sep='')
519             fileout<-paste(fileout,'.png',sep='')
520             count<-count+1
521             fileout<-file.path("%s",fileout)
522             if (max(nchar(colnames(chi$observed)))>15) {
523                 leg <- 1:length(colnames(chi$observed))
524             } else {
525                 leg <- colnames(chi$observed)
526             }
527             if (dograph) {
528                 width<-ncol(chi$observed)*100
529                 if (width < 350) {width <- 350}
530                 open_file_graph(fileout,width = width, height = 300)
531                 par(mar=c(0,0,0,0))
532                 layout(matrix(c(1,2),1,2, byrow=TRUE),widths=c(3,1))
533                 par(mar=c(2,2,1,0))
534                 par(cex=0.8)
535                 if (!bw) colors <- rainbow(length(rownames(chi$observed)))
536                 else colors <- gray.colors(length(rownames(chi$observed)))
537                 barplot(chi$prl,names.arg = leg, beside=TRUE,border=NA, col=colors)
538                 par(mar=c(0,0,0,0))
539                 par(cex=0.8)
540                 plot(0, axes = FALSE, pch = '')
541                 legend(x = 'center' , rownames(chi$observed), fill = colors)
542                 dev.off()
543             }
544             chi$prl <- cbind(chi$prl, total = rowSums(chi$prl))
545             chi$prc <- rbind(chi$prc, total = colSums(chi$prc))
546             chi$observed<-rbind(chi$observed,total=colSums(chi$observed))
547             chi$observed<-cbind(chi$observed,total=rowSums(chi$observed))
548             chi$pr <- round((chi$observed/st)*100,2)
549             chi$expected<-rbind(chi$expected,total=colSums(chi$expected))
550             chi$expected<-cbind(chi$expected,total=rowSums(chi$expected))
551             chi$expected<-round(chi$expected,digits=2)
552             chi$residuals<-round(chi$residuals,digits=2)
553             chi$contrib<-round(chi$contrib, digits=2)
554             nom_col<-colnames(chi$observed)
555            
556             if (ncol(chi$observed)<maxcol) {
557                 for (i in 1:(maxcol-ncol(chi$observed))) {
558                     chi$observed<-cbind(chi$observed,'**')
559                     chi$pr<-cbind(chi$pr,'**')
560                     chi$prl<-cbind(chi$prl,'**')
561                     chi$prc<-cbind(chi$prc,'**')
562                     chi$expected<-cbind(chi$expected,'**')
563                     chi$residuals<-cbind(chi$residuals,'**')
564                     chi$contrib<-cbind(chi$contrib,'**')
565                     nom_col<-append(nom_col,'**')
566                     nom_colresi<-append(nom_colresi,'**')
567                 }
568                 chi$residuals<-cbind(chi$residuals,'**')
569                 chi$contrib<-cbind(chi$contrib,'**')
570                 nom_colresi<-append(nom_colresi,'**')
571                 chi$prc<-cbind(chi$prc,'**')
572             } else if (ncol(chi$observed)==maxcol) {
573                 chi$residuals<-cbind(chi$residuals,'**')
574                 chi$contrib<-cbind(chi$contrib,'**')
575                 nom_colresi<-append(nom_colresi,'**')
576                 chi$prc<-cbind(chi$prc,'**')
577             }
578             if (doobs) {
579                 li<-matrix('*obs*',1,maxcol)
580                 frameout<-rbind(frameout,li)
581                 frameout<-rbind(frameout,nom_col)
582                 frameout<-rbind(frameout,chi$observed)
583             }
584             if (doexp) {
585                 li<-matrix('*exp*',1,maxcol)
586                 frameout<-rbind(frameout,li)
587                 frameout<-rbind(frameout,nom_col)
588                 frameout<-rbind(frameout,chi$expected)
589             }
590             if (doresi) {
591                 li<-matrix('*resi*',1,maxcol)
592                 frameout<-rbind(frameout,li)
593                 frameout<-rbind(frameout,nom_colresi)
594                 frameout<-rbind(frameout,chi$residuals)
595             }
596             if (docontrib) {
597                 li<-matrix('*contrib*',1,maxcol)
598                 frameout<-rbind(frameout,li)
599                 frameout<-rbind(frameout,nom_colresi)
600                 frameout<-rbind(frameout,chi$contrib)
601             }
602             if (dopr) {
603                 li<-matrix('*pr*', 1, maxcol)
604                 frameout<-rbind(frameout,li)
605                 frameout<-rbind(frameout,nom_col)
606                 frameout<-rbind(frameout,chi$pr)
607             }
608             if (doprl) {
609                 li<-matrix('*prl*', 1, maxcol)
610                 frameout<-rbind(frameout,li)
611                 frameout<-rbind(frameout,nom_col)
612                 frameout<-rbind(frameout,chi$prl)
613             }
614             if (doprc) {
615                 li<-matrix('*prc*', 1, maxcol)
616                 frameout<-rbind(frameout,li)
617                 frameout<-rbind(frameout,nom_colresi)
618                 frameout<-rbind(frameout,chi$prc)
619             }
620             res<-c('****','chi',chi$statistic,'p',chi$p.value,att,fileout)
621             frameout<-rbind(frameout,res)
622         }
623         li<-matrix('fin_analyse',1,maxcol)
624         frameout<-rbind(frameout,li)
625         write.csv2(frameout,file="%s")
626         """ % (ffr(self.parametres['pathout']),ffr(self.OutFrame))
627         tmpfile=tempfile.mktemp(dir=self.TEMPDIR)
628         print tmpfile
629         tmpscript=open(tmpfile,'w')
630         tmpscript.write(txt)
631         tmpscript.close()
632         pid = exec_rcode(self.RPath, tmpfile, wait = False)
633         while pid.poll() == None :
634             sleep(0.2)
635         check_Rresult(self.parent, pid)            
636         self.count += 1
637         keepGoing = self.dlg.Update(self.count,u"Ecriture des résultats")
638          
639         listfileout = self.dolayout(self.chioption)
640             #listfileout=dlg.ShowChi2(ColSel1,ColSel2)
641             #parent.FreqNum += 1
642             #parent.DictTab[u"Chi2_%s*"%parent.FreqNum]=listfileout
643 #             parent.newtab = wx.html.HtmlWindow(parent.nb, -1)
644 #             if "gtk2" in wx.PlatformInfo:
645 #                 parent.newtab.SetStandardFonts()
646 #             parent.newtab.LoadPage(listfileout[len(listfileout)-1])
647 #             parent.nb.AddPage(parent.newtab,u"Chi2_%s*"%parent.FreqNum)
648 #             parent.nb.SetSelection(parent.nb.GetPageCount()-1)
649 #             parent.ShowTab(wx.EVT_BUTTON)
650 #             parent.DisEnSaveTabAs(True)
651         self.count += 1
652         keepGoing = self.dlg.Update(self.count,u"Fini")
653
654     def dolayout(self, option):
655         ListFile=[False]
656         file=open(self.OutFrame,'rU')
657         content=file.readlines()
658         file.close()
659         lcont = [line.replace('"','').replace('\n','').split(';') for line in content]
660     
661         lcont.pop(0)
662         lcont.pop(0)
663         
664         allcoord = []
665         names = []
666
667         res = [chi for chi in lcont if chi[0]=='res']
668         res = [make_res(line) for line in res]
669         coord_res = [i for i,chi in enumerate(lcont) if chi[0]=='res']
670         if option['valobs']:
671             allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*obs*'])
672             names.append(u'Valeurs observées')
673         if option['valtheo'] :
674             allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*exp*'])
675             names.append(u'Valeurs théoriques')
676         if option['resi'] :
677             allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*resi*'])
678             names.append(u'Residuals')
679         if option['contrib'] :
680             allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*contrib*'])
681             names.append(u'Contributions a posteriori')
682         if option['pourcent'] : 
683             allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*pr*'])
684             names.append(u'Pourcentages')
685         if option['pourcentl'] :
686             allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*prl*'])
687             names.append(u'Pourcentages en ligne')
688         if option['pourcentc'] :
689             allcoord.append([i for i,chi in enumerate(lcont) if chi[1]=='*prc*'])
690             names.append(u'Pourcentages en colonne')
691     
692         allcoord.append(coord_res)
693         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]
694     
695         allhtml = [make_table(val,names[i],res) for i,val in enumerate(allhtml)]
696     
697         links = make_link_list(res, self.TextCroise)
698         #colors = [line[-1] for line in res]
699     
700     #    good = [i for i,chi in enumerate(res) if chi[-1] == 'green' or chi[-1] == 'blue']
701         #select_good = [[val[i] for i in good] for val in tout]
702     
703     
704         html_res = make_restab(res)
705         allhtml.insert(0,html_res)
706
707         titles = make_title(res, self.TextCroise)
708         allhtml.insert(0,titles)
709         
710         if option['graph'] :
711             graphs = [line[7] for line in res]
712             ListFile += graphs
713             html_graphs = make_htmlgraphs(graphs)
714             allhtml.append(html_graphs)
715
716         header=u"""
717         <html>\n
718         <meta http-equiv="content-Type" content="text/html; charset=%s" />\n
719         <body>\n
720         <h1>Test du Chi2</h1>\n
721         <br>
722         <table border=1><tr><td>
723         Légende : <br>
724         <font color=green>p &lt;= 0.05</font><br>
725         <font color=blue>p &lt;= 0.05 mais il y a des valeurs théoriques &lt; 5</font><br>
726         <font color=red>p &gt; 0.05</font>
727         </td></tr></table><br><br>
728         """%self.parent.SysEncoding
729
730     
731         pretxt = '<br>\n'.join(links)+'<br><hr><br>\n'
732         txt = '<br><hr><br>\n'.join(['<br><br>'.join([tab[i] for tab in allhtml]) for i,val in enumerate(res)])
733         txt = header + pretxt + txt + '\n</body></html>'
734
735         fileout=os.path.join(self.parametres['pathout'],'resultats-chi2.html')
736         with open(fileout, 'w') as f :
737             f.write(txt)
738         ListFile.append(fileout)         
739         return ListFile