1 # -*- coding: utf-8 -*-
2 #Author: Pierre Ratinaud
3 #Copyright (c) 2008-2020 Pierre Ratinaud
4 #modification pour python 3 : Laurent Mérat, 6x7 - mai 2020
7 #------------------------------------
8 # import des modules python
9 #------------------------------------
14 #------------------------------------
15 # import des modules wx
16 #------------------------------------
19 #------------------------------------
20 # import des fichiers du projet
21 #------------------------------------
22 from chemins import ffr, ConstructPathOut,ChdTxtPathOut
23 from functions import CreateIraFile, print_liste, exec_rcode, check_Rresult
24 from dialog import PrefQuestAlc, ClusterNbDialog
27 def RchdFunct(self,parent, rep_out, CLASSIF, encode, RscriptsPath):
32 """%RscriptsPath['chdfunct']
34 dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', na.strings = '')
35 """%ffr(rep_out['FILE_ACT_TEMP'])
37 dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', na.strings = '')
38 """%ffr(rep_out['FILE_ET_TEMP'])
40 fileout=tempfile.mktemp(dir=parent.TEMPDIR)
43 dissmat<-daisy(dataact, metric = 'gower', stand = FALSE)
44 chd<-diana(dissmat,diss=TRUE,)
46 sortheight<-sort(height,decreasing=TRUE)
47 BestCLusterNb<-as.matrix(FindBestCluster(sortheight))
48 write.csv2(BestCLusterNb,file="%s",row.names=FALSE)
53 Rtmp=tempfile.mktemp(dir=parent.TEMPDIR)
57 pid = exec_rcode(parent.RPath, Rtmp, wait = False)
58 while pid.poll() == None :
60 check_Rresult(parent, pid)
64 ListClasseOk=[line.replace('\n','').replace('"','') for line in lcl]
66 clusterdlg = ClusterNbDialog(ListClasseOk, parent, -1, "Nombre de classe", size=(350, 200),
67 style = wx.DEFAULT_DIALOG_STYLE
69 clusterdlg.CenterOnParent()
70 # this does not return until the dialog is closed.
71 val = clusterdlg.ShowModal()
73 if type(ListClasseOk)!=float :
74 CLASSE_CH=ListClasseOk[clusterdlg.list_box_1.GetSelection()]
76 CLASSE_CH=ListClasseOk
78 print("You pressed Cancel\n")
80 ClusterNb=int(CLASSE_CH)
87 """% RscriptsPath['chdfunct']
92 classes<-as.data.frame(cutree(as.hclust(chd), k=clnb))[,1]
93 datatot<-cbind(dataact,dataet)
94 dataclasse<-cbind(datatot,classes)
95 dataactclasses<-cbind(dataact,classes)
96 dataetclasses<-cbind(dataet,classes)
97 afctableact<-BuildContTable(dataactclasses)
98 afctableet<-BuildContTable(dataetclasses)
99 tablesqrpact<-BuildProf(afctableact,dataactclasses,clnb)
100 tablesqrpet<-BuildProf(afctableet,dataetclasses,clnb)
101 chistabletot<-rbind(as.data.frame(tablesqrpact[2]),as.data.frame(tablesqrpet[2]))
102 ptabletot<-rbind(as.data.frame(tablesqrpact[1]),as.data.frame(tablesqrpet[1]))
103 cont_out<-rbind(as.data.frame(tablesqrpact[3]),as.data.frame(tablesqrpet[3]))
104 colnames(chistabletot)<-paste('classe',1:clnb,sep=' ')
105 colnames(ptabletot)<-paste('classe',1:clnb,sep=' ')
106 cont_out <- cont_out[,-ncol(cont_out)]
107 colnames(cont_out)<-paste('classe',1:clnb,sep=' ')
108 write.csv2(chistabletot,file="%s")
109 """%rep_out['chisqtable']
111 write.csv2(ptabletot,file="%s")
112 """%rep_out['ptable']
114 write.csv2(cont_out,file="%s")
115 """%rep_out['Contout']
117 PrintProfile(dataclasse,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s")
118 """%(rep_out['PROFILE_OUT'],rep_out['ANTIPRO_OUT'])
120 gbcluster<-dataclasse[ncol(dataclasse)]
121 write.csv2(gbcluster,file="%s")
122 """%rep_out['SbyClasseOut']
126 afctable<-rbind(afctableact,afctableet)
127 colnames(afctable)<-paste('classe',1:clnb,sep=' ')
128 afc<-ca(afctable,suprow=((nrow(afctableact)+1):nrow(cont_out)),nd=(ncol(afctable)-1))
129 debet<-nrow(afctableact)+1
133 afc<-AddCorrelationOk(afc)
134 afc <- summary.ca.dm(afc)
135 afc_table <- create_afc_table(afc)
136 """%RscriptsPath['Rgraph']
138 dendo <- as.dendrogram(as.hclust(chd))
139 hthr<-sortheight[clnb]
140 dendocut<-cut(dendo,h=hthr)
147 # PlotDendroComp(chd,"%s",200)
148 # """%rep_out['DENDROCOMP_OUT']
150 # PlotDendroHori(dendocut$upper,"%s",200)
151 # """%rep_out['DENDROH_OUT']
153 # PlotDendroCut(chd,"%s",200,clnb)
154 # """%rep_out['DENDROCUT_OUT']
159 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=1, fin=(debet-1))
160 """ % (rep_out['AFC2DL_OUT'])
162 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=debet, fin=fin)
163 """ % (rep_out['AFC2DSL_OUT'])
165 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col = TRUE, what='coord')
166 """ % (rep_out['AFC2DCL_OUT'])
168 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=1, fin=(debet-1))
169 """ % (rep_out['AFC2DCoul'])
171 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debet, fin=fin)
172 """ % (rep_out['AFC2DCoulSup'])
174 PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col = TRUE, what='crl')
175 """ % (rep_out['AFC2DCoulCl'])
179 pid = exec_rcode(parent.RPath, Rtmp, wait = False)
180 while pid.poll() == None :
182 check_Rresult(parent, pid)
188 def __init__(self, parent, numactives, varsup):
190 #------------------------------------------------------
191 self.dlg=wx.ProgressDialog("Traitements",
192 "Veuillez patienter...",
195 style = wx.PD_APP_MODAL|wx.PD_AUTO_HIDE|wx.PD_ELAPSED_TIME
199 keepGoing = self.dlg.Update(self.count)
200 #-------------------------------------------------------
201 self.Filename=parent.filename
203 self.encode=parent.encode
204 self.numactives=numactives
206 #-------------------------------------------------------
208 keepGoing = self.dlg.Update(self.count)
210 #-------------------------------------------------------
213 PathOut=ConstructPathOut(self.parent.tableau.parametre['filename'],'CHDS')
214 self.pathout = PathOut
215 dictpathout = ChdTxtPathOut(PathOut)
216 self.dictpathout=dictpathout
217 self.parent.tableau.dictpathout = dictpathout
218 self.RPath=self.parent.PathPath.get('PATHS','rpath')
219 #-------------------------------------------------------
221 keepGoing = self.dlg.Update(self.count,"lecture des données")
222 colact = self.parent.tableau.select_col(self.numactives)
223 colsup = self.parent.tableau.select_col(self.varsup)
224 self.parent.tableau.make_01_from_selection(self.numactives, self.varsup, False)
225 dictpathout['FILE_ACT_TEMP']=tempfile.mktemp(dir=self.parent.TEMPDIR)
226 savetxt(dictpathout['FILE_ACT_TEMP'],colact,fmt='%s',delimiter=';')
227 dictpathout['FILE_ET_TEMP']=tempfile.mktemp(dir=self.parent.TEMPDIR)
228 savetxt(dictpathout['FILE_ET_TEMP'],colsup,fmt='%s',delimiter=';')
229 #-------------------------------------------------------
231 keepGoing = self.dlg.Update(self.count,"Analyse (patientez...)")
232 #------------FIXME----------
233 clnb=RchdFunct(self,self.parent,dictpathout, 'DIANA',self.parent.SysEncoding,self.parent.RscriptsPath)
235 #-------------------------------------------------------
237 keepGoing = self.dlg.Update(self.count,"Ecriture des résultats")
238 return dictpathout,clnb
240 def PrintResult(self,dictpathout,clnb):
241 with open(self.dictpathout['SbyClasseOut'], 'r') as filein :
242 content = filein.readlines()
244 for i, line in enumerate(content) :
245 line = line.replace('\n', '').replace('"', '').split(';')
246 self.parent.tableau.classes.append([int(line[0]) - 1, int(line[1])])
247 temps=time.time()-self.t1
248 self.minutes, self.seconds = divmod(temps, 60)
249 self.hours, self.minutes = divmod(self.minutes, 60)
250 #PrintRapport(self,'quest_simi')
251 self.parent.tableau.dictpathout = self.dictpathout
252 self.parent.tableau.save_tableau(self.dictpathout['db'])
253 CreateIraFile(dictpathout,clnb, corpname = os.path.basename(self.Filename), section = 'chd_dist_quest')
254 #-------------------------------------------------------
256 keepGoing = self.dlg.Update(self.count,"Ouverture...")
257 afc_graph_list = [[os.path.basename(self.dictpathout['AFC2DL_OUT']), 'Variables actives - coordonnées - facteurs 1 / 2'],
258 [os.path.basename(self.dictpathout['AFC2DSL_OUT']), 'variables illustratives - coordonnées - facteurs 1 / 2'],
259 [os.path.basename(self.dictpathout['AFC2DCL_OUT']), 'Classes - Coordonnées - facteur 1 / 2'],
260 [os.path.basename(self.dictpathout['AFC2DCoul']), 'Variables actives - Corrélation - facteur 1/2'],
261 [os.path.basename(self.dictpathout['AFC2DCoulSup']), 'Variables illustratives - Corrélation - facteur 1 / 2'],
262 [os.path.basename(self.dictpathout['AFC2DCoulCl']), 'Classes - Corrélations - facteurs 1 / 2'], ]
263 chd_graph_list = [[os.path.basename(self.dictpathout['dendro1']), 'dendrogramme à partir de chd1']]
264 #chd_graph_list.append(['arbre1', 'chd1'])
265 print_liste(self.dictpathout['liste_graph_afc'], afc_graph_list)
266 print_liste(self.dictpathout['liste_graph_chd'], chd_graph_list)
267 self.tableau = self.parent.tableau
268 OpenAnalyse(self.parent, dictpathout['ira'], False)
269 #-------------------------------------------------------
271 keepGoing = self.dlg.Update(self.count,"Fini")
276 def __init__(self,parent):
277 dlg = PrefQuestAlc(parent, sim = True)
278 #dlg = CHDDialog(parent,-1, u"Classification", size=(350, 400),style = wx.DEFAULT_DIALOG_STYLE)
280 self.val = dlg.ShowModal()
281 if self.val==wx.ID_OK :
282 numactives=dlg.nactives
284 chd=AnalyseCHDS(parent, numactives, varsup)
285 dictpathout,clnb=chd.OnAnalyse()
286 chd.PrintResult(dictpathout,clnb)
287 parent.ShowTab(wx.EVT_BUTTON)