caracteristic segments for all clusters
[iramuteq] / tabchdalc.py
1 #!/bin/env python
2 # -*- coding: utf-8 -*-
3 #Author: Pierre Ratinaud
4 #Copyright (c) 2008-2009 Pierre Ratinaud
5 #License: GNU/GPL
6
7 from chemins import ConstructPathOut, ChdTxtPathOut, ConstructAfcUciPath, ffr, PathOut
8 from functions import sortedby, CreateIraFile, print_liste, exec_rcode, check_Rresult
9 from PrintRScript import RchdQuest
10 from layout import OpenCHDS, PrintRapport
11 from dialog import PrefQuestAlc
12 from analysematrix import AnalyseMatrix
13 import os
14 import sys
15 import wx
16 import tempfile
17 import time
18
19
20 class AnalyseQuest(AnalyseMatrix):
21     def doparametres(self, dlg = None):
22         if dlg is not None :
23             dial = PrefQuestAlc(self.parent, self.tableau)
24             dial.CenterOnParent()
25             self.val = dial.ShowModal()
26             #parametres = self.tableau.parametre
27             if self.val == wx.ID_OK :
28                 self.parametres['nbcl_p1'] = dial.spin_nbcl.GetValue()
29                 self.parametres['mincl'] = dial.spin_mincl.GetValue()
30                 if dial.m_radioBox1.GetSelection() == 1 :
31                     self.parametres['listact'] = dial.nactives
32                     self.parametres['listsup'] = dial.varsup
33                 else :
34                     self.parametres['formatted'] = 1
35             else :
36                 self.parametres = None
37             dial.Destroy()
38            # DoQuestAlceste(parent, parametres)
39
40 #class DoQuestAlceste(AnalyseMatrix):
41     def doanalyse(self):
42         #parametres['pathout'] = ConstructPathOut(parent.tableau.parametre['filename'], 'ReinertMatrix')
43         #self.parametres = parametres
44         #self.parametres['type'] = 'reinertmatrix'
45         self.DictForme = {}
46         self.DictFormeSup = {}
47         self.Min = 10
48         self.Linecontent = []
49         #self.parent = parent
50         #self.RPath = self.parent.PathPath.get('PATHS', 'rpath')
51         #self.dictpathout = PathOut(dirout = self.pathout)
52         #self.dictpathout = self.pathout
53         #self.dictpathout.basefiles(ChdTxtPathOut)
54         #self.pathout = self.dictpathout
55         self.clnb = ''
56         self.ListAct = self.parametres.get('listact', False)
57         self.ucecla = ''
58         #dlg = wx.ProgressDialog("Traitements",
59         #                       "Veuillez patienter...",
60         #                       maximum=5,
61         #                       parent=self.parent,
62         #                       style=wx.PD_APP_MODAL | wx.PD_AUTO_HIDE | wx.PD_ELAPSED_TIME
63         #                        )
64
65         #AnalyseMatrix.__init__(self, parent, parent.tableau, self.parametres, dlg = dlg)
66  
67
68
69 #-----------------------------------------------------------
70 #    def doanalyse(self) :
71 #-------------------------------------------------------------------               
72         #self.dictpathout = self.pathout
73         self.pathout.basefiles(ChdTxtPathOut)
74         self.tableau.pathout.basefiles(ChdTxtPathOut)
75 #        self.parent.tableau.dictpathout = self.dictpathout
76
77         self.dlg.Center()
78         count = 1
79         keepGoing = self.dlg.Update(count)
80 #-------------------------------------------------------------------
81         count += 1
82         self.dlg.Update(count, u"passage en O/1")
83         if 'formatted' in self.parametres:
84             self.tableau.make_01_alc_format(self.pathout['mat01.csv'])
85         else:
86             self.tableau.make_01_from_selection(self.parametres['listact'], self.parametres['listsup'])
87         file = open(self.pathout['listeuce1'], 'w')
88         file.write('num uce;num uc\n')
89         for i in range(0, len(self.tableau.linecontent)):
90             file.write('%i;%i\n' % (i, i))
91         file.close()
92         self.nbind = len(self.tableau.linecontent)
93 #------------------------------------------------------------
94         RchdQuest(self.pathout, self.parent.RscriptsPath, self.parametres['nbcl_p1'], self.parametres['mincl'])
95 #------------------------------------------------------------
96         count += 1
97         self.dlg.Update(count, u"Analyse (patientez...)")
98         
99         pid = exec_rcode(self.parent.RPath, self.pathout['Rchdquest'], wait = False)
100         while pid.poll() == None :
101             self.dlg.Pulse(u"Analyse (patientez...)")
102             time.sleep(0.2)
103         if not check_Rresult(self.parent, pid) :
104             if self.dlg :
105                 self.dlg.Destroy()
106             return 'NOK'
107 #------------------------------------------------------------
108         count += 1
109         self.dlg.Update(count, u"Ecriture des résultats")
110         self.tableau.buildprofil()
111         self.clnb = self.tableau.clnb
112         self.parametres['clnb'] = self.clnb
113         self.ucecla = self.tableau.ucecla
114         self.BuildProfile()
115         temps = time.time() - self.t1
116         PrintRapport(self, self, {}, istxt = False)
117         self.tableau.save_tableau(self.pathout['db'])
118         #CreateIraFile(self.dictpathout, self.clnb, corpname = os.path.basename(self.parent.filename), section = 'questionnaire')
119         afc_graph_list = [[os.path.basename(self.pathout['AFC2DL_OUT']), u'Variables actives - coordonnées - facteurs 1 / 2'],
120                          [os.path.basename(self.pathout['AFC2DSL_OUT']), u'variables illustratives - coordonnées - facteurs 1 / 2'],
121                          [os.path.basename(self.pathout['AFC2DCL_OUT']), u'Classes - Coordonnées - facteur 1 / 2'],]
122         chd_graph_list = [[os.path.basename(self.pathout['dendro1']), u'dendrogramme à partir de chd1']]
123         chd_graph_list.append([os.path.basename(self.pathout['arbre1']), u'chd1'])
124         print_liste(self.pathout['liste_graph_afc'], afc_graph_list)
125         print_liste(self.pathout['liste_graph_chd'], chd_graph_list)
126
127         #self.tableau = self.parent.tableau
128         #OpenCHDS(self.parent, self, self.dictpathout['ira'], False)
129 #------------------------------------------------------------
130         print 'fini', time.time() - self.t1
131         count += 1
132         self.dlg.Update(count, "Fini")
133     
134     def BuildProfile(self):
135         print 'build profile'
136         txt = ''
137         txt += """
138         source("%s")
139         """ % ffr(self.parent.RscriptsPath['chdfunct'])
140         txt += """
141         load("%s")
142         """ % ffr(self.pathout['RData'])
143         txt += """
144         dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
145         """ % ffr(self.pathout['Contout'])
146         txt += """
147         dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
148         """ % ffr(self.pathout['ContEtOut'])
149         txt += """
150         clnb<-%i
151         """ % self.clnb
152         txt += """
153         tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
154         tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
155         PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],%i,"%s","%s")
156         """ % (self.clnb, ffr(self.pathout['PROFILE_OUT']), ffr(self.pathout['ANTIPRO_OUT']))
157         txt += """
158         colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
159         colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
160         colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
161         colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
162         chistabletot<-rbind(as.data.frame(tablesqrpact[2]),as.data.frame(tablesqrpet[2]))
163         ptabletot<-rbind(as.data.frame(tablesqrpact[1]),as.data.frame(tablesqrpet[1]))
164         gbcluster<-n1
165         write.csv2(chistabletot,file="%s")
166         """ % ffr(self.pathout['chisqtable'])
167         txt += """
168         write.csv2(ptabletot,file="%s")
169         """ % ffr(self.pathout['ptable'])
170         txt += """
171         write.csv2(gbcluster,file="%s")
172         """ % ffr(self.pathout['SbyClasseOut'])
173         if self.clnb > 2 :
174             txt += """
175             library(ca)
176             rowtot<-nrow(dataact)+nrow(dataet)
177             afctable<-rbind(as.matrix(dataact),as.matrix(dataet))
178             colnames(afctable)<-paste('classe',1:clnb,sep=' ')
179             afc<-ca(afctable,suprow=((nrow(dataact)+1):rowtot),nd=(ncol(afctable)-1))
180             debet<-nrow(dataact)+1
181             debsup<-NULL
182             fin<-rowtot
183             afc<-AddCorrelationOk(afc)
184             source("%s")
185             """ % ffr(self.parent.RscriptsPath['Rgraph'])
186     
187             txt += """
188             afc <- summary.ca.dm(afc)
189             afc_table <- create_afc_table(afc)
190             write.csv2(afc_table$facteur, file = "%s")
191             write.csv2(afc_table$colonne, file = "%s")
192             write.csv2(afc_table$ligne, file = "%s")
193             """ % (ffr(self.pathout['afc_facteur']), ffr(self.pathout['afc_col']), ffr(self.pathout['afc_row']))
194             
195             txt += """
196             xlab <- paste('facteur 1 - ', round(afc$facteur[1,2],2), sep = '')
197             ylab <- paste('facteur 2 - ', round(afc$facteur[2,2],2), sep = '')
198             xlab <- paste(xlab, ' %', sep = '')
199             ylab <- paste(ylab, ' %', sep = '')
200             """
201     
202             txt += """
203             PARCEX<-%s
204             """ % "0.9"
205             txt += """
206             xyminmax <- PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=1, fin=(debet-1), xlab = xlab, ylab = ylab)
207             """ % (ffr(self.pathout['AFC2DL_OUT']))
208             txt += """
209             PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=debet, fin=fin, xlab = xlab, ylab = ylab, xmin = xyminmax$xminmax[1], xmax = xyminmax$xminmax[2], ymin = xyminmax$yminmax[1], ymax = xyminmax$yminmax[2])
210             """ % (ffr(self.pathout['AFC2DSL_OUT']))
211             txt += """
212             PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", col = TRUE, what='coord', xlab = xlab, ylab = ylab, xmin = xyminmax$xminmax[1], xmax = xyminmax$xminmax[2], ymin = xyminmax$yminmax[1], ymax = xyminmax$yminmax[2])
213             """ % (ffr(self.pathout['AFC2DCL_OUT']))
214         txt += """
215         save.image(file="%s")
216         """ % ffr(self.pathout['RData'])
217         tmpfile = tempfile.mktemp(dir=self.parent.TEMPDIR)
218         tmpscript = open(tmpfile, 'w')
219         tmpscript.write(txt)
220         tmpscript.close()
221         pid = exec_rcode(self.parent.RPath, tmpfile, wait = False)
222         while pid.poll() == None :
223             time.sleep(0.2)
224         check_Rresult(self.parent, pid)
225         temps = time.time() - self.t1
226         self.minutes, self.seconds = divmod(temps, 60)
227         self.hours, self.minutes = divmod(self.minutes, 60)