1 # -*- coding: utf-8 -*-
2 #Author: Pierre Ratinaud
3 #Copyright (c) 2008 Pierre Ratinaud
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
20 def RchdFunct(self,parent, rep_out, CLASSIF, encode, RscriptsPath):
25 """%RscriptsPath['chdfunct']
27 dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', na.strings = '')
28 """%ffr(rep_out['FILE_ACT_TEMP'])
30 dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', na.strings = '')
31 """%ffr(rep_out['FILE_ET_TEMP'])
33 fileout=tempfile.mktemp(dir=parent.TEMPDIR)
36 dissmat<-daisy(dataact, metric = 'gower', stand = FALSE)
37 chd<-diana(dissmat,diss=TRUE,)
39 sortheight<-sort(height,decreasing=TRUE)
40 BestCLusterNb<-as.matrix(FindBestCluster(sortheight))
41 write.csv2(BestCLusterNb,file="%s",row.names=FALSE)
46 Rtmp=tempfile.mktemp(dir=parent.TEMPDIR)
50 pid = exec_rcode(parent.RPath, Rtmp, wait = False)
51 while pid.poll() == None :
53 check_Rresult(parent, pid)
55 file=open(fileout,'rU')
58 ListClasseOk=[line.replace('\n','').replace('"','') for line in lcl]
61 clusterdlg = ClusterNbDialog(ListClasseOk, parent, -1, "Nombre de classe", size=(350, 200),
62 style = wx.DEFAULT_DIALOG_STYLE
64 clusterdlg.CenterOnParent()
66 # this does not return until the dialog is closed.
67 val = clusterdlg.ShowModal()
70 if type(ListClasseOk)!=float :
71 CLASSE_CH=ListClasseOk[clusterdlg.list_box_1.GetSelection()]
73 CLASSE_CH=ListClasseOk
75 print "You pressed Cancel\n"
77 ClusterNb=int(CLASSE_CH)
84 """% RscriptsPath['chdfunct']
89 classes<-as.data.frame(cutree(as.hclust(chd), k=clnb))[,1]
90 datatot<-cbind(dataact,dataet)
91 dataclasse<-cbind(datatot,classes)
92 dataactclasses<-cbind(dataact,classes)
93 dataetclasses<-cbind(dataet,classes)
94 afctableact<-BuildContTable(dataactclasses)
95 afctableet<-BuildContTable(dataetclasses)
96 tablesqrpact<-BuildProf(afctableact,dataactclasses,clnb)
97 tablesqrpet<-BuildProf(afctableet,dataetclasses,clnb)
98 chistabletot<-rbind(as.data.frame(tablesqrpact[2]),as.data.frame(tablesqrpet[2]))
99 ptabletot<-rbind(as.data.frame(tablesqrpact[1]),as.data.frame(tablesqrpet[1]))
100 cont_out<-rbind(as.data.frame(tablesqrpact[3]),as.data.frame(tablesqrpet[3]))
101 colnames(chistabletot)<-paste('classe',1:clnb,sep=' ')
102 colnames(ptabletot)<-paste('classe',1:clnb,sep=' ')
103 cont_out <- cont_out[,-ncol(cont_out)]
104 colnames(cont_out)<-paste('classe',1:clnb,sep=' ')
105 write.csv2(chistabletot,file="%s")
106 """%rep_out['chisqtable']
108 write.csv2(ptabletot,file="%s")
109 """%rep_out['ptable']
111 write.csv2(cont_out,file="%s")
112 """%rep_out['Contout']
114 PrintProfile(dataclasse,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s")
115 """%(rep_out['PROFILE_OUT'],rep_out['ANTIPRO_OUT'])
117 gbcluster<-dataclasse[ncol(dataclasse)]
118 write.csv2(gbcluster,file="%s")
119 """%rep_out['SbyClasseOut']
123 afctable<-rbind(afctableact,afctableet)
124 colnames(afctable)<-paste('classe',1:clnb,sep=' ')
125 afc<-ca(afctable,suprow=((nrow(afctableact)+1):nrow(cont_out)),nd=(ncol(afctable)-1))
126 debet<-nrow(afctableact)+1
130 afc<-AddCorrelationOk(afc)
131 afc <- summary.ca.dm(afc)
132 afc_table <- create_afc_table(afc)
133 """%RscriptsPath['Rgraph']
136 dendo <- as.dendrogram(as.hclust(chd))
137 hthr<-sortheight[clnb]
138 dendocut<-cut(dendo,h=hthr)
146 # PlotDendroComp(chd,"%s",200)
147 # """%rep_out['DENDROCOMP_OUT']
149 # PlotDendroHori(dendocut$upper,"%s",200)
150 # """%rep_out['DENDROH_OUT']
152 # PlotDendroCut(chd,"%s",200,clnb)
153 # """%rep_out['DENDROCUT_OUT']
158 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=1, fin=(debet-1))
159 """ % (rep_out['AFC2DL_OUT'])
161 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=debet, fin=fin)
162 """ % (rep_out['AFC2DSL_OUT'])
164 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col = TRUE, what='coord')
165 """ % (rep_out['AFC2DCL_OUT'])
167 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=1, fin=(debet-1))
168 """ % (rep_out['AFC2DCoul'])
170 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debet, fin=fin)
171 """ % (rep_out['AFC2DCoulSup'])
173 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col = TRUE, what='crl')
174 """ % (rep_out['AFC2DCoulCl'])
178 pid = exec_rcode(parent.RPath, Rtmp, wait = False)
179 while pid.poll() == None :
181 check_Rresult(parent, pid)
186 def __init__(self, parent, numactives, varsup):
188 #------------------------------------------------------
189 self.dlg=wx.ProgressDialog("Traitements",
190 "Veuillez patienter...",
193 style = wx.PD_APP_MODAL|wx.PD_AUTO_HIDE|wx.PD_ELAPSED_TIME
197 keepGoing = self.dlg.Update(self.count)
198 #-------------------------------------------------------
199 self.Filename=parent.filename
201 self.encode=parent.encode
202 self.numactives=numactives
204 #-------------------------------------------------------
206 keepGoing = self.dlg.Update(self.count)
208 #-------------------------------------------------------
210 PathOut=ConstructPathOut(self.parent.tableau.parametre['filename'],'CHDS')
211 self.pathout = PathOut
212 dictpathout = ChdTxtPathOut(PathOut)
213 self.dictpathout=dictpathout
214 self.parent.tableau.dictpathout = dictpathout
215 self.RPath=self.parent.PathPath.get('PATHS','rpath')
216 #-------------------------------------------------------
218 keepGoing = self.dlg.Update(self.count,u"lecture des données")
219 colact = self.parent.tableau.select_col(self.numactives)
220 colsup = self.parent.tableau.select_col(self.varsup)
221 self.parent.tableau.make_01_from_selection(self.numactives, self.varsup, False)
222 dictpathout['FILE_ACT_TEMP']=tempfile.mktemp(dir=self.parent.TEMPDIR)
223 savetxt(dictpathout['FILE_ACT_TEMP'],colact,fmt='%s',delimiter=';')
224 dictpathout['FILE_ET_TEMP']=tempfile.mktemp(dir=self.parent.TEMPDIR)
225 savetxt(dictpathout['FILE_ET_TEMP'],colsup,fmt='%s',delimiter=';')
227 #-------------------------------------------------------
229 keepGoing = self.dlg.Update(self.count,u"Analyse (patientez...)")
230 #------------FIXME----------
231 clnb=RchdFunct(self,self.parent,dictpathout, 'DIANA',self.parent.SysEncoding,self.parent.RscriptsPath)
233 #-------------------------------------------------------
235 keepGoing = self.dlg.Update(self.count,u"Ecriture des résultats")
236 return dictpathout,clnb
239 def PrintResult(self,dictpathout,clnb):
240 with open(self.dictpathout['SbyClasseOut'], 'rU') as filein :
241 content = filein.readlines()
243 for i, line in enumerate(content) :
244 line = line.replace('\n', '').replace('"', '').split(';')
245 self.parent.tableau.classes.append([int(line[0]) - 1, int(line[1])])
246 temps=time.time()-self.t1
247 self.minutes, self.seconds = divmod(temps, 60)
248 self.hours, self.minutes = divmod(self.minutes, 60)
249 #PrintRapport(self,'quest_simi')
250 self.parent.tableau.dictpathout = self.dictpathout
251 self.parent.tableau.save_tableau(self.dictpathout['db'])
252 CreateIraFile(dictpathout,clnb, corpname = os.path.basename(self.Filename), section = 'chd_dist_quest')
253 #-------------------------------------------------------
255 keepGoing = self.dlg.Update(self.count,u"Ouverture...")
256 afc_graph_list = [[os.path.basename(self.dictpathout['AFC2DL_OUT']), u'Variables actives - coordonnées - facteurs 1 / 2'],
257 [os.path.basename(self.dictpathout['AFC2DSL_OUT']), u'variables illustratives - coordonnées - facteurs 1 / 2'],
258 [os.path.basename(self.dictpathout['AFC2DCL_OUT']), u'Classes - Coordonnées - facteur 1 / 2'],
259 [os.path.basename(self.dictpathout['AFC2DCoul']), u'Variables actives - Corrélation - facteur 1/2'],
260 [os.path.basename(self.dictpathout['AFC2DCoulSup']), u'Variables illustratives - Corrélation - facteur 1 / 2'],
261 [os.path.basename(self.dictpathout['AFC2DCoulCl']), u'Classes - Corrélations - facteurs 1 / 2'], ]
262 chd_graph_list = [[os.path.basename(self.dictpathout['dendro1']), u'dendrogramme à partir de chd1']]
263 #chd_graph_list.append(['arbre1', u'chd1'])
264 print_liste(self.dictpathout['liste_graph_afc'], afc_graph_list)
265 print_liste(self.dictpathout['liste_graph_chd'], chd_graph_list)
266 self.tableau = self.parent.tableau
267 OpenAnalyse(self.parent, dictpathout['ira'], False)
268 #-------------------------------------------------------
270 keepGoing = self.dlg.Update(self.count,u"Fini")
274 def __init__(self,parent):
276 dlg = PrefQuestAlc(parent, sim = True)
277 #dlg = CHDDialog(parent,-1, u"Classification", size=(350, 400),style = wx.DEFAULT_DIALOG_STYLE)
279 self.val = dlg.ShowModal()
280 if self.val==wx.ID_OK :
281 numactives=dlg.nactives
283 chd=AnalyseCHDS(parent, numactives, varsup)
284 dictpathout,clnb=chd.OnAnalyse()
285 chd.PrintResult(dictpathout,clnb)
286 parent.ShowTab(wx.EVT_BUTTON)