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