multisplit
[iramuteq] / tabchddist.py
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
5 #License: GNU/GPL
6
7 #------------------------------------
8 # import des modules python
9 #------------------------------------
10 import os
11 import tempfile
12 import time
13
14 #------------------------------------
15 # import des modules wx
16 #------------------------------------
17 import wx
18
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
25
26
27 def RchdFunct(self,parent, rep_out, CLASSIF, encode, RscriptsPath):
28     SEUIL_CHI2_PROF=2
29     txt=""
30     txt+="""
31     source("%s")
32     """%RscriptsPath['chdfunct']
33     txt+="""
34     dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', na.strings = '')
35     """%ffr(rep_out['FILE_ACT_TEMP'])
36     txt+="""
37     dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', na.strings = '')
38     """%ffr(rep_out['FILE_ET_TEMP'])
39     
40     fileout=tempfile.mktemp(dir=parent.TEMPDIR)
41     
42     txt+="""
43     dissmat<-daisy(dataact, metric = 'gower', stand = FALSE)
44     chd<-diana(dissmat,diss=TRUE,)
45     height<-chd$height
46     sortheight<-sort(height,decreasing=TRUE)
47     BestCLusterNb<-as.matrix(FindBestCluster(sortheight))
48     write.csv2(BestCLusterNb,file="%s",row.names=FALSE)
49     """%ffr(fileout)
50     txt+="""
51     save.image(file="%s")
52     """%rep_out['RData']
53     Rtmp=tempfile.mktemp(dir=parent.TEMPDIR)
54     file=open(Rtmp,'w')
55     file.write(txt)
56     file.close()
57     pid = exec_rcode(parent.RPath, Rtmp, wait = False)
58     while pid.poll() == None :
59         time.sleep(0.2)
60     check_Rresult(parent, pid)
61     f=open(fileout,'r')
62     lcl=f.readlines()
63     f.close()
64     ListClasseOk=[line.replace('\n','').replace('"','') for line in lcl]
65     ListClasseOk.pop(0)
66     clusterdlg = ClusterNbDialog(ListClasseOk, parent, -1, "Nombre de classe", size=(350, 200),
67                      style = wx.DEFAULT_DIALOG_STYLE
68                      )
69     clusterdlg.CenterOnParent()
70     # this does not return until the dialog is closed.
71     val = clusterdlg.ShowModal()
72     if val == wx.ID_OK:
73         if type(ListClasseOk)!=float :
74             CLASSE_CH=ListClasseOk[clusterdlg.list_box_1.GetSelection()]
75         else :
76             CLASSE_CH=ListClasseOk
77     else:
78         print("You pressed Cancel\n")
79     clusterdlg.Destroy()
80     ClusterNb=int(CLASSE_CH)
81     txt=''
82     txt+="""
83     load("%s")
84     """%rep_out['RData']
85     txt += """
86     source("%s")
87     """% RscriptsPath['chdfunct']
88     txt+="""
89     clnb<-%i
90     """%ClusterNb
91     txt+="""
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']
110     txt+="""
111     write.csv2(ptabletot,file="%s")
112     """%rep_out['ptable']
113     txt+="""
114     write.csv2(cont_out,file="%s")
115     """%rep_out['Contout']
116     txt+="""
117     PrintProfile(dataclasse,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],clnb,"%s","%s")
118     """%(rep_out['PROFILE_OUT'],rep_out['ANTIPRO_OUT'])
119     txt+="""
120     gbcluster<-dataclasse[ncol(dataclasse)]
121     write.csv2(gbcluster,file="%s")
122     """%rep_out['SbyClasseOut']
123     txt+="""
124     library(ca)
125     library(cluster)
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
130     fin<-nrow(cont_out)
131     source("%s")
132     debsup<-NULL
133     afc<-AddCorrelationOk(afc)
134     afc <-  summary.ca.dm(afc)
135     afc_table <- create_afc_table(afc)
136     """%RscriptsPath['Rgraph']
137     txt+="""
138     dendo <- as.dendrogram(as.hclust(chd))
139     hthr<-sortheight[clnb]
140     dendocut<-cut(dendo,h=hthr)
141     save.image("%s")
142     """%rep_out['RData']
143 #    txt+="""
144 #    PARCEX<-%s
145 #    """%'0.9'
146 #    txt+="""
147 #    PlotDendroComp(chd,"%s",200)
148 #    """%rep_out['DENDROCOMP_OUT']
149 #    txt+="""
150 #    PlotDendroHori(dendocut$upper,"%s",200)
151 #    """%rep_out['DENDROH_OUT']
152 #    txt+="""
153 #    PlotDendroCut(chd,"%s",200,clnb)
154 #    """%rep_out['DENDROCUT_OUT'] 
155     txt += """
156     PARCEX<-%s
157     """ % "0.9"
158     txt += """
159     PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=1, fin=(debet-1))
160     """ % (rep_out['AFC2DL_OUT'])
161     txt += """
162     PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=debet, fin=fin)
163     """ % (rep_out['AFC2DSL_OUT'])
164     txt += """
165     PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col = TRUE, what='coord')
166     """ % (rep_out['AFC2DCL_OUT'])
167     txt += """
168     PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=1, fin=(debet-1))
169     """ % (rep_out['AFC2DCoul'])
170     txt += """
171     PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='crl', deb=debet, fin=fin)
172     """ % (rep_out['AFC2DCoulSup'])
173     txt += """
174     PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col = TRUE, what='crl')
175     """ % (rep_out['AFC2DCoulCl'])
176     f=open(Rtmp,'w')
177     f.write(txt)
178     f.close()
179     pid = exec_rcode(parent.RPath, Rtmp, wait = False)
180     while pid.poll() == None :
181         time.sleep(0.2)
182     check_Rresult(parent, pid)
183     return ClusterNb
184
185
186 class AnalyseCHDS():
187
188     def __init__(self, parent, numactives, varsup):
189         self.t1=time.time()
190         #------------------------------------------------------
191         self.dlg=wx.ProgressDialog("Traitements",
192                                "Veuillez patienter...",
193                                maximum = 7,
194                                parent=parent,
195                                style = wx.PD_APP_MODAL|wx.PD_AUTO_HIDE|wx.PD_ELAPSED_TIME
196                                 )
197         self.dlg.Center()
198         self.count = 1
199         keepGoing = self.dlg.Update(self.count)
200         #-------------------------------------------------------
201         self.Filename=parent.filename
202         self.parent=parent
203         self.encode=parent.encode
204         self.numactives=numactives
205         self.varsup=varsup
206         #-------------------------------------------------------
207         self.count += 1
208         keepGoing = self.dlg.Update(self.count)
209         #self.OnAnalyse()
210         #-------------------------------------------------------
211
212     def OnAnalyse(self):
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         #-------------------------------------------------------
220         self.count += 1
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         #-------------------------------------------------------
230         self.count += 1
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)
234         self.clnb=clnb
235         #-------------------------------------------------------
236         self.count += 1
237         keepGoing = self.dlg.Update(self.count,"Ecriture des résultats")
238         return dictpathout,clnb
239
240     def PrintResult(self,dictpathout,clnb):
241         with open(self.dictpathout['SbyClasseOut'], 'r') as filein :
242             content = filein.readlines()
243         content.pop(0)
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         #-------------------------------------------------------
255         self.count += 1
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         #-------------------------------------------------------
270         self.count += 1
271         keepGoing = self.dlg.Update(self.count,"Fini")
272
273
274 class ChdCluster():
275
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)
279         dlg.CenterOnParent()
280         self.val = dlg.ShowModal()
281         if self.val==wx.ID_OK :
282             numactives=dlg.nactives
283             varsup=dlg.varsup
284             chd=AnalyseCHDS(parent, numactives, varsup)
285             dictpathout,clnb=chd.OnAnalyse()
286             chd.PrintResult(dictpathout,clnb)
287             parent.ShowTab(wx.EVT_BUTTON)