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