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
19 def RchdFunct(self,parent, rep_out, CLASSIF, encode, RscriptsPath):
24 """%RscriptsPath['chdfunct']
26 dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', na.strings = '')
27 """%ffr(rep_out['FILE_ACT_TEMP'])
29 dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', na.strings = '')
30 """%ffr(rep_out['FILE_ET_TEMP'])
32 fileout=tempfile.mktemp(dir=parent.TEMPDIR)
35 dissmat<-daisy(dataact, metric = 'gower', stand = FALSE)
36 chd<-diana(dissmat,diss=TRUE,)
38 sortheight<-sort(height,decreasing=TRUE)
39 BestCLusterNb<-as.matrix(FindBestCluster(sortheight))
40 write.csv2(BestCLusterNb,file="%s",row.names=FALSE)
45 Rtmp=tempfile.mktemp(dir=parent.TEMPDIR)
49 pid = exec_rcode(parent.RPath, Rtmp, wait = False)
50 while pid.poll() == None :
52 check_Rresult(parent, pid)
54 file=open(fileout,'rU')
57 ListClasseOk=[line.replace('\n','').replace('"','') for line in lcl]
60 clusterdlg = ClusterNbDialog(ListClasseOk, parent, -1, "Nombre de classe", size=(350, 200),
61 style = wx.DEFAULT_DIALOG_STYLE
63 clusterdlg.CenterOnParent()
65 # this does not return until the dialog is closed.
66 val = clusterdlg.ShowModal()
69 if type(ListClasseOk)!=float :
70 CLASSE_CH=ListClasseOk[clusterdlg.list_box_1.GetSelection()]
72 CLASSE_CH=ListClasseOk
74 print "You pressed Cancel\n"
76 ClusterNb=int(CLASSE_CH)
83 """% RscriptsPath['chdfunct']
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']
107 write.csv2(ptabletot,file="%s")
108 """%rep_out['ptable']
110 write.csv2(cont_out,file="%s")
111 """%rep_out['Contout']
113 PrintProfile(dataclasse,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s")
114 """%(rep_out['PROFILE_OUT'],rep_out['ANTIPRO_OUT'])
116 gbcluster<-dataclasse[ncol(dataclasse)]
117 write.csv2(gbcluster,file="%s")
118 """%rep_out['SbyClasseOut']
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
129 afc<-AddCorrelationOk(afc)
130 afc <- summary.ca.dm(afc)
131 afc_table <- create_afc_table(afc)
132 """%RscriptsPath['Rgraph']
135 dendo <- as.dendrogram(as.hclust(chd))
136 hthr<-sortheight[clnb]
137 dendocut<-cut(dendo,h=hthr)
145 # PlotDendroComp(chd,"%s",200)
146 # """%rep_out['DENDROCOMP_OUT']
148 # PlotDendroHori(dendocut$upper,"%s",200)
149 # """%rep_out['DENDROH_OUT']
151 # PlotDendroCut(chd,"%s",200,clnb)
152 # """%rep_out['DENDROCUT_OUT']
157 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=1, fin=(debet-1))
158 """ % (rep_out['AFC2DL_OUT'])
160 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=debet, fin=fin)
161 """ % (rep_out['AFC2DSL_OUT'])
163 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col = TRUE, what='coord')
164 """ % (rep_out['AFC2DCL_OUT'])
166 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=1, fin=(debet-1))
167 """ % (rep_out['AFC2DCoul'])
169 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debet, fin=fin)
170 """ % (rep_out['AFC2DCoulSup'])
172 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col = TRUE, what='crl')
173 """ % (rep_out['AFC2DCoulCl'])
177 pid = exec_rcode(parent.RPath, Rtmp, wait = False)
178 while pid.poll() == None :
180 check_Rresult(parent, pid)
185 def __init__(self, parent, numactives, varsup):
187 #------------------------------------------------------
188 self.dlg=wx.ProgressDialog("Traitements",
189 "Veuillez patienter...",
192 style = wx.PD_APP_MODAL|wx.PD_AUTO_HIDE|wx.PD_ELAPSED_TIME
196 keepGoing = self.dlg.Update(self.count)
197 #-------------------------------------------------------
198 self.Filename=parent.filename
200 self.encode=parent.encode
201 self.numactives=numactives
203 #-------------------------------------------------------
205 keepGoing = self.dlg.Update(self.count)
207 #-------------------------------------------------------
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 #-------------------------------------------------------
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=';')
226 #-------------------------------------------------------
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)
232 #-------------------------------------------------------
234 keepGoing = self.dlg.Update(self.count,u"Ecriture des résultats")
235 return dictpathout,clnb
238 def PrintResult(self,dictpathout,clnb):
239 with open(self.dictpathout['SbyClasseOut'], 'rU') as filein :
240 content = filein.readlines()
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 #-------------------------------------------------------
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 #-------------------------------------------------------
269 keepGoing = self.dlg.Update(self.count,u"Fini")
273 def __init__(self,parent):
275 dlg = PrefQuestAlc(parent, sim = True)
276 #dlg = CHDDialog(parent,-1, u"Classification", size=(350, 400),style = wx.DEFAULT_DIALOG_STYLE)
278 self.val = dlg.ShowModal()
279 if self.val==wx.ID_OK :
280 numactives=dlg.nactives
282 chd=AnalyseCHDS(parent, numactives, varsup)
283 dictpathout,clnb=chd.OnAnalyse()
284 chd.PrintResult(dictpathout,clnb)
285 parent.ShowTab(wx.EVT_BUTTON)