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