copycorpus
[iramuteq] / tabchddist.py
1 # -*- coding: utf-8 -*-
2 #Author: Pierre Ratinaud
3 #Copyright (c) 2008 Pierre Ratinaud
4 #Lisense: GNU/GPL
5
6 import wx
7 import os
8 #from rchdng import RchdFunct
9 from chemins import ffr, ConstructPathOut,ChdTxtPathOut
10 #from layout import PrintRapport
11 from openanalyse import OpenAnalyse
12 from ConfigParser import ConfigParser
13 from functions import CreateIraFile, print_liste, exec_rcode, check_Rresult
14 from dialog import CHDDialog, PrefQuestAlc, ClusterNbDialog
15 import tempfile
16 import time
17
18
19 def RchdFunct(self,parent, rep_out, CLASSIF, encode, RscriptsPath):
20     SEUIL_CHI2_PROF=2
21     txt=""
22     txt+="""
23     source("%s")
24     """%RscriptsPath['chdfunct']
25     txt+="""
26     dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', na.strings = '')
27     """%ffr(rep_out['FILE_ACT_TEMP'])
28     txt+="""
29     dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', na.strings = '')
30     """%ffr(rep_out['FILE_ET_TEMP'])
31     
32     fileout=tempfile.mktemp(dir=parent.TEMPDIR)
33     
34     txt+="""
35     dissmat<-daisy(dataact, metric = 'gower', stand = FALSE)
36     chd<-diana(dissmat,diss=TRUE,)
37     height<-chd$height
38     sortheight<-sort(height,decreasing=TRUE)
39     BestCLusterNb<-as.matrix(FindBestCluster(sortheight))
40     write.csv2(BestCLusterNb,file="%s",row.names=FALSE)
41     """%ffr(fileout)
42     txt+="""
43     save.image(file="%s")
44     """%rep_out['RData']
45     Rtmp=tempfile.mktemp(dir=parent.TEMPDIR)
46     file=open(Rtmp,'w')
47     file.write(txt)
48     file.close()
49     pid = exec_rcode(parent.RPath, Rtmp, wait = False)
50     while pid.poll() == None :
51         time.sleep(0.2)
52     check_Rresult(parent, pid)
53     
54     file=open(fileout,'rU')
55     lcl=file.readlines()
56     file.close()
57     ListClasseOk=[line.replace('\n','').replace('"','') for line in lcl]
58     ListClasseOk.pop(0)
59
60     clusterdlg = ClusterNbDialog(ListClasseOk, parent, -1, "Nombre de classe", size=(350, 200),
61                      style = wx.DEFAULT_DIALOG_STYLE
62                      )
63     clusterdlg.CenterOnParent()
64
65     # this does not return until the dialog is closed.
66     val = clusterdlg.ShowModal()
67     
68     if val == wx.ID_OK:
69         if type(ListClasseOk)!=float :
70             CLASSE_CH=ListClasseOk[clusterdlg.list_box_1.GetSelection()]
71         else :
72             CLASSE_CH=ListClasseOk
73     else:
74         print "You pressed Cancel\n"
75     clusterdlg.Destroy()
76     ClusterNb=int(CLASSE_CH)
77     txt=''
78     txt+="""
79     load("%s")
80     """%rep_out['RData']
81     txt += """
82     source("%s")
83     """% RscriptsPath['chdfunct']
84     txt+="""
85     clnb<-%i
86     """%ClusterNb
87     txt+="""
88     classes<-as.data.frame(cutree(as.hclust(chd), k=clnb))[,1]
89     datatot<-cbind(dataact,dataet)
90     dataclasse<-cbind(datatot,classes)
91     dataactclasses<-cbind(dataact,classes)
92     dataetclasses<-cbind(dataet,classes)
93     afctableact<-BuildContTable(dataactclasses)
94     afctableet<-BuildContTable(dataetclasses)
95     tablesqrpact<-BuildProf(afctableact,dataactclasses,clnb)
96     tablesqrpet<-BuildProf(afctableet,dataetclasses,clnb)
97     chistabletot<-rbind(as.data.frame(tablesqrpact[2]),as.data.frame(tablesqrpet[2]))
98     ptabletot<-rbind(as.data.frame(tablesqrpact[1]),as.data.frame(tablesqrpet[1]))
99     cont_out<-rbind(as.data.frame(tablesqrpact[3]),as.data.frame(tablesqrpet[3]))
100     colnames(chistabletot)<-paste('classe',1:clnb,sep=' ')
101     colnames(ptabletot)<-paste('classe',1:clnb,sep=' ')
102     cont_out <- cont_out[,-ncol(cont_out)]
103     colnames(cont_out)<-paste('classe',1:clnb,sep=' ')
104     write.csv2(chistabletot,file="%s")
105     """%rep_out['chisqtable']
106     txt+="""
107     write.csv2(ptabletot,file="%s")
108     """%rep_out['ptable']
109     txt+="""
110     write.csv2(cont_out,file="%s")
111     """%rep_out['Contout']
112     txt+="""
113     PrintProfile(dataclasse,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s")
114     """%(rep_out['PROFILE_OUT'],rep_out['ANTIPRO_OUT'])
115     txt+="""
116     gbcluster<-dataclasse[ncol(dataclasse)]
117     write.csv2(gbcluster,file="%s")
118     """%rep_out['SbyClasseOut']
119     txt+="""
120     library(ca)
121     library(cluster)
122     afctable<-rbind(afctableact,afctableet)
123     colnames(afctable)<-paste('classe',1:clnb,sep=' ')
124     afc<-ca(afctable,suprow=((nrow(afctableact)+1):nrow(cont_out)),nd=(ncol(afctable)-1))
125     debet<-nrow(afctableact)+1
126     fin<-nrow(cont_out)
127     source("%s")
128     debsup<-NULL
129     afc<-AddCorrelationOk(afc)
130     afc <-  summary.ca.dm(afc)
131     afc_table <- create_afc_table(afc)
132     """%RscriptsPath['Rgraph']
133     
134     txt+="""
135     dendo <- as.dendrogram(as.hclust(chd))
136     hthr<-sortheight[clnb]
137     dendocut<-cut(dendo,h=hthr)
138     save.image("%s")
139     """%rep_out['RData']
140     
141 #    txt+="""
142 #    PARCEX<-%s
143 #    """%'0.9'
144 #    txt+="""
145 #    PlotDendroComp(chd,"%s",200)
146 #    """%rep_out['DENDROCOMP_OUT']
147 #    txt+="""
148 #    PlotDendroHori(dendocut$upper,"%s",200)
149 #    """%rep_out['DENDROH_OUT']
150 #    txt+="""
151 #    PlotDendroCut(chd,"%s",200,clnb)
152 #    """%rep_out['DENDROCUT_OUT'] 
153     txt += """
154     PARCEX<-%s
155     """ % "0.9"
156     txt += """
157     PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=1, fin=(debet-1))
158     """ % (rep_out['AFC2DL_OUT'])
159     txt += """
160     PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=debet, fin=fin)
161     """ % (rep_out['AFC2DSL_OUT'])
162     txt += """
163     PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col = TRUE, what='coord')
164     """ % (rep_out['AFC2DCL_OUT'])
165     txt += """
166     PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=1, fin=(debet-1))
167     """ % (rep_out['AFC2DCoul'])
168     txt += """
169     PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debet, fin=fin)
170     """ % (rep_out['AFC2DCoulSup'])
171     txt += """
172     PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col = TRUE, what='crl')
173     """ % (rep_out['AFC2DCoulCl'])
174     file=open(Rtmp,'w')
175     file.write(txt)
176     file.close()
177     pid = exec_rcode(parent.RPath, Rtmp, wait = False)
178     while pid.poll() == None :
179         time.sleep(0.2)
180     check_Rresult(parent, pid)
181     return ClusterNb
182
183
184 class AnalyseCHDS():
185     def __init__(self, parent, numactives, varsup):
186         self.t1=time.time()
187 #------------------------------------------------------
188         self.dlg=wx.ProgressDialog("Traitements",
189                                "Veuillez patienter...",
190                                maximum = 7,
191                                parent=parent,
192                                style = wx.PD_APP_MODAL|wx.PD_AUTO_HIDE|wx.PD_ELAPSED_TIME
193                                 )
194         self.dlg.Center()
195         self.count = 1
196         keepGoing = self.dlg.Update(self.count)
197 #-------------------------------------------------------
198         self.Filename=parent.filename
199         self.parent=parent
200         self.encode=parent.encode
201         self.numactives=numactives
202         self.varsup=varsup
203 #-------------------------------------------------------
204         self.count += 1
205         keepGoing = self.dlg.Update(self.count)
206         #self.OnAnalyse()
207 #-------------------------------------------------------
208     def OnAnalyse(self):
209         PathOut=ConstructPathOut(self.parent.tableau.parametre['filename'],'CHDS')
210         self.pathout = PathOut
211         dictpathout = ChdTxtPathOut(PathOut)
212         self.dictpathout=dictpathout
213         self.parent.tableau.dictpathout = dictpathout
214         self.RPath=self.parent.PathPath.get('PATHS','rpath')
215 #-------------------------------------------------------
216         self.count += 1
217         keepGoing = self.dlg.Update(self.count,u"lecture des données")
218         colact = self.parent.tableau.select_col(self.numactives)
219         colsup = self.parent.tableau.select_col(self.varsup)
220         self.parent.tableau.make_01_from_selection(self.numactives, self.varsup, False)
221         dictpathout['FILE_ACT_TEMP']=tempfile.mktemp(dir=self.parent.TEMPDIR)
222         savetxt(dictpathout['FILE_ACT_TEMP'],colact,fmt='%s',delimiter=';')
223         dictpathout['FILE_ET_TEMP']=tempfile.mktemp(dir=self.parent.TEMPDIR)
224         savetxt(dictpathout['FILE_ET_TEMP'],colsup,fmt='%s',delimiter=';')
225         
226 #-------------------------------------------------------
227         self.count += 1
228         keepGoing = self.dlg.Update(self.count,u"Analyse (patientez...)")
229 #------------FIXME----------
230         clnb=RchdFunct(self,self.parent,dictpathout, 'DIANA',self.parent.SysEncoding,self.parent.RscriptsPath)
231         self.clnb=clnb
232 #-------------------------------------------------------
233         self.count += 1
234         keepGoing = self.dlg.Update(self.count,u"Ecriture des résultats")
235         return dictpathout,clnb
236         
237    
238     def PrintResult(self,dictpathout,clnb):
239         with open(self.dictpathout['SbyClasseOut'], 'rU') as filein :
240             content = filein.readlines()
241         content.pop(0)
242         for i, line in enumerate(content) :
243             line = line.replace('\n', '').replace('"', '').split(';')
244             self.parent.tableau.classes.append([int(line[0]) - 1, int(line[1])])        
245         temps=time.time()-self.t1
246         self.minutes, self.seconds = divmod(temps, 60)
247         self.hours, self.minutes = divmod(self.minutes, 60)  
248         #PrintRapport(self,'quest_simi')
249         self.parent.tableau.dictpathout = self.dictpathout
250         self.parent.tableau.save_tableau(self.dictpathout['db'])
251         CreateIraFile(dictpathout,clnb, corpname = os.path.basename(self.Filename), section = 'chd_dist_quest')
252 #-------------------------------------------------------
253         self.count += 1
254         keepGoing = self.dlg.Update(self.count,u"Ouverture...")
255         afc_graph_list = [[os.path.basename(self.dictpathout['AFC2DL_OUT']), u'Variables actives - coordonnées - facteurs 1 / 2'],
256                           [os.path.basename(self.dictpathout['AFC2DSL_OUT']), u'variables illustratives - coordonnées - facteurs 1 / 2'],
257                           [os.path.basename(self.dictpathout['AFC2DCL_OUT']), u'Classes - Coordonnées - facteur 1 / 2'],
258                           [os.path.basename(self.dictpathout['AFC2DCoul']), u'Variables actives - Corrélation - facteur 1/2'],
259                           [os.path.basename(self.dictpathout['AFC2DCoulSup']), u'Variables illustratives - Corrélation - facteur 1 / 2'],
260                           [os.path.basename(self.dictpathout['AFC2DCoulCl']), u'Classes - Corrélations - facteurs 1 / 2'], ]
261         chd_graph_list = [[os.path.basename(self.dictpathout['dendro1']), u'dendrogramme à partir de chd1']]
262         #chd_graph_list.append(['arbre1', u'chd1'])
263         print_liste(self.dictpathout['liste_graph_afc'], afc_graph_list)
264         print_liste(self.dictpathout['liste_graph_chd'], chd_graph_list)
265         self.tableau = self.parent.tableau
266         OpenAnalyse(self.parent, dictpathout['ira'], False)
267 #-------------------------------------------------------
268         self.count += 1
269         keepGoing = self.dlg.Update(self.count,u"Fini")
270
271
272 class ChdCluster():
273     def __init__(self,parent):
274
275         dlg = PrefQuestAlc(parent, sim = True)
276         #dlg = CHDDialog(parent,-1, u"Classification", size=(350, 400),style = wx.DEFAULT_DIALOG_STYLE)
277         dlg.CenterOnParent()
278         self.val = dlg.ShowModal()
279         if self.val==wx.ID_OK :
280             numactives=dlg.nactives
281             varsup=dlg.varsup
282             chd=AnalyseCHDS(parent, numactives, varsup)
283             dictpathout,clnb=chd.OnAnalyse()
284             chd.PrintResult(dictpathout,clnb)
285             parent.ShowTab(wx.EVT_BUTTON)
286