1 # -*- coding: utf-8 -*-
2 #Author: Pierre Ratinaud
3 #Copyright (c) 2008 Pierre Ratinaud
8 from chemins import ffr, ConstructPathOut,ChdTxtPathOut
9 from functions import CreateIraFile, print_liste, exec_rcode, check_Rresult
10 from dialog import PrefQuestAlc, ClusterNbDialog
15 def RchdFunct(self,parent, rep_out, CLASSIF, encode, RscriptsPath):
20 """%RscriptsPath['chdfunct']
22 dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', na.strings = '')
23 """%ffr(rep_out['FILE_ACT_TEMP'])
25 dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', na.strings = '')
26 """%ffr(rep_out['FILE_ET_TEMP'])
28 fileout=tempfile.mktemp(dir=parent.TEMPDIR)
31 dissmat<-daisy(dataact, metric = 'gower', stand = FALSE)
32 chd<-diana(dissmat,diss=TRUE,)
34 sortheight<-sort(height,decreasing=TRUE)
35 BestCLusterNb<-as.matrix(FindBestCluster(sortheight))
36 write.csv2(BestCLusterNb,file="%s",row.names=FALSE)
41 Rtmp=tempfile.mktemp(dir=parent.TEMPDIR)
45 pid = exec_rcode(parent.RPath, Rtmp, wait = False)
46 while pid.poll() == None :
48 check_Rresult(parent, pid)
53 ListClasseOk=[line.replace('\n','').replace('"','') for line in lcl]
56 clusterdlg = ClusterNbDialog(ListClasseOk, parent, -1, "Nombre de classe", size=(350, 200),
57 style = wx.DEFAULT_DIALOG_STYLE
59 clusterdlg.CenterOnParent()
61 # this does not return until the dialog is closed.
62 val = clusterdlg.ShowModal()
65 if type(ListClasseOk)!=float :
66 CLASSE_CH=ListClasseOk[clusterdlg.list_box_1.GetSelection()]
68 CLASSE_CH=ListClasseOk
70 print "You pressed Cancel\n"
72 ClusterNb=int(CLASSE_CH)
79 """% RscriptsPath['chdfunct']
84 classes<-as.data.frame(cutree(as.hclust(chd), k=clnb))[,1]
85 datatot<-cbind(dataact,dataet)
86 dataclasse<-cbind(datatot,classes)
87 dataactclasses<-cbind(dataact,classes)
88 dataetclasses<-cbind(dataet,classes)
89 afctableact<-BuildContTable(dataactclasses)
90 afctableet<-BuildContTable(dataetclasses)
91 tablesqrpact<-BuildProf(afctableact,dataactclasses,clnb)
92 tablesqrpet<-BuildProf(afctableet,dataetclasses,clnb)
93 chistabletot<-rbind(as.data.frame(tablesqrpact[2]),as.data.frame(tablesqrpet[2]))
94 ptabletot<-rbind(as.data.frame(tablesqrpact[1]),as.data.frame(tablesqrpet[1]))
95 cont_out<-rbind(as.data.frame(tablesqrpact[3]),as.data.frame(tablesqrpet[3]))
96 colnames(chistabletot)<-paste('classe',1:clnb,sep=' ')
97 colnames(ptabletot)<-paste('classe',1:clnb,sep=' ')
98 cont_out <- cont_out[,-ncol(cont_out)]
99 colnames(cont_out)<-paste('classe',1:clnb,sep=' ')
100 write.csv2(chistabletot,file="%s")
101 """%rep_out['chisqtable']
103 write.csv2(ptabletot,file="%s")
104 """%rep_out['ptable']
106 write.csv2(cont_out,file="%s")
107 """%rep_out['Contout']
109 PrintProfile(dataclasse,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s")
110 """%(rep_out['PROFILE_OUT'],rep_out['ANTIPRO_OUT'])
112 gbcluster<-dataclasse[ncol(dataclasse)]
113 write.csv2(gbcluster,file="%s")
114 """%rep_out['SbyClasseOut']
118 afctable<-rbind(afctableact,afctableet)
119 colnames(afctable)<-paste('classe',1:clnb,sep=' ')
120 afc<-ca(afctable,suprow=((nrow(afctableact)+1):nrow(cont_out)),nd=(ncol(afctable)-1))
121 debet<-nrow(afctableact)+1
125 afc<-AddCorrelationOk(afc)
126 afc <- summary.ca.dm(afc)
127 afc_table <- create_afc_table(afc)
128 """%RscriptsPath['Rgraph']
131 dendo <- as.dendrogram(as.hclust(chd))
132 hthr<-sortheight[clnb]
133 dendocut<-cut(dendo,h=hthr)
141 # PlotDendroComp(chd,"%s",200)
142 # """%rep_out['DENDROCOMP_OUT']
144 # PlotDendroHori(dendocut$upper,"%s",200)
145 # """%rep_out['DENDROH_OUT']
147 # PlotDendroCut(chd,"%s",200,clnb)
148 # """%rep_out['DENDROCUT_OUT']
153 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=1, fin=(debet-1))
154 """ % (rep_out['AFC2DL_OUT'])
156 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=debet, fin=fin)
157 """ % (rep_out['AFC2DSL_OUT'])
159 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col = TRUE, what='coord')
160 """ % (rep_out['AFC2DCL_OUT'])
162 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=1, fin=(debet-1))
163 """ % (rep_out['AFC2DCoul'])
165 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debet, fin=fin)
166 """ % (rep_out['AFC2DCoulSup'])
168 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col = TRUE, what='crl')
169 """ % (rep_out['AFC2DCoulCl'])
173 pid = exec_rcode(parent.RPath, Rtmp, wait = False)
174 while pid.poll() == None :
176 check_Rresult(parent, pid)
181 def __init__(self, parent, numactives, varsup):
183 #------------------------------------------------------
184 self.dlg=wx.ProgressDialog("Traitements",
185 "Veuillez patienter...",
188 style = wx.PD_APP_MODAL|wx.PD_AUTO_HIDE|wx.PD_ELAPSED_TIME
192 keepGoing = self.dlg.Update(self.count)
193 #-------------------------------------------------------
194 self.Filename=parent.filename
196 self.encode=parent.encode
197 self.numactives=numactives
199 #-------------------------------------------------------
201 keepGoing = self.dlg.Update(self.count)
203 #-------------------------------------------------------
205 PathOut=ConstructPathOut(self.parent.tableau.parametre['filename'],'CHDS')
206 self.pathout = PathOut
207 dictpathout = ChdTxtPathOut(PathOut)
208 self.dictpathout=dictpathout
209 self.parent.tableau.dictpathout = dictpathout
210 self.RPath=self.parent.PathPath.get('PATHS','rpath')
211 #-------------------------------------------------------
213 keepGoing = self.dlg.Update(self.count,u"lecture des données")
214 colact = self.parent.tableau.select_col(self.numactives)
215 colsup = self.parent.tableau.select_col(self.varsup)
216 self.parent.tableau.make_01_from_selection(self.numactives, self.varsup, False)
217 dictpathout['FILE_ACT_TEMP']=tempfile.mktemp(dir=self.parent.TEMPDIR)
218 savetxt(dictpathout['FILE_ACT_TEMP'],colact,fmt='%s',delimiter=';')
219 dictpathout['FILE_ET_TEMP']=tempfile.mktemp(dir=self.parent.TEMPDIR)
220 savetxt(dictpathout['FILE_ET_TEMP'],colsup,fmt='%s',delimiter=';')
222 #-------------------------------------------------------
224 keepGoing = self.dlg.Update(self.count,u"Analyse (patientez...)")
225 #------------FIXME----------
226 clnb=RchdFunct(self,self.parent,dictpathout, 'DIANA',self.parent.SysEncoding,self.parent.RscriptsPath)
228 #-------------------------------------------------------
230 keepGoing = self.dlg.Update(self.count,u"Ecriture des résultats")
231 return dictpathout,clnb
234 def PrintResult(self,dictpathout,clnb):
235 with open(self.dictpathout['SbyClasseOut'], 'rU') as filein :
236 content = filein.readlines()
238 for i, line in enumerate(content) :
239 line = line.replace('\n', '').replace('"', '').split(';')
240 self.parent.tableau.classes.append([int(line[0]) - 1, int(line[1])])
241 temps=time.time()-self.t1
242 self.minutes, self.seconds = divmod(temps, 60)
243 self.hours, self.minutes = divmod(self.minutes, 60)
244 #PrintRapport(self,'quest_simi')
245 self.parent.tableau.dictpathout = self.dictpathout
246 self.parent.tableau.save_tableau(self.dictpathout['db'])
247 CreateIraFile(dictpathout,clnb, corpname = os.path.basename(self.Filename), section = 'chd_dist_quest')
248 #-------------------------------------------------------
250 keepGoing = self.dlg.Update(self.count,u"Ouverture...")
251 afc_graph_list = [[os.path.basename(self.dictpathout['AFC2DL_OUT']), u'Variables actives - coordonnées - facteurs 1 / 2'],
252 [os.path.basename(self.dictpathout['AFC2DSL_OUT']), u'variables illustratives - coordonnées - facteurs 1 / 2'],
253 [os.path.basename(self.dictpathout['AFC2DCL_OUT']), u'Classes - Coordonnées - facteur 1 / 2'],
254 [os.path.basename(self.dictpathout['AFC2DCoul']), u'Variables actives - Corrélation - facteur 1/2'],
255 [os.path.basename(self.dictpathout['AFC2DCoulSup']), u'Variables illustratives - Corrélation - facteur 1 / 2'],
256 [os.path.basename(self.dictpathout['AFC2DCoulCl']), u'Classes - Corrélations - facteurs 1 / 2'], ]
257 chd_graph_list = [[os.path.basename(self.dictpathout['dendro1']), u'dendrogramme à partir de chd1']]
258 #chd_graph_list.append(['arbre1', u'chd1'])
259 print_liste(self.dictpathout['liste_graph_afc'], afc_graph_list)
260 print_liste(self.dictpathout['liste_graph_chd'], chd_graph_list)
261 self.tableau = self.parent.tableau
262 OpenAnalyse(self.parent, dictpathout['ira'], False)
263 #-------------------------------------------------------
265 keepGoing = self.dlg.Update(self.count,u"Fini")
269 def __init__(self,parent):
271 dlg = PrefQuestAlc(parent, sim = True)
272 #dlg = CHDDialog(parent,-1, u"Classification", size=(350, 400),style = wx.DEFAULT_DIALOG_STYLE)
274 self.val = dlg.ShowModal()
275 if self.val==wx.ID_OK :
276 numactives=dlg.nactives
278 chd=AnalyseCHDS(parent, numactives, varsup)
279 dictpathout,clnb=chd.OnAnalyse()
280 chd.PrintResult(dictpathout,clnb)
281 parent.ShowTab(wx.EVT_BUTTON)