translators
[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             print self.parametres['listsup']
87             self.tableau.make_01_from_selection(self.parametres['listact'], self.parametres['listsup'])
88         file = open(self.pathout['listeuce1'], 'w')
89         file.write('num uce;num uc\n')
90         for i in range(0, len(self.tableau.linecontent)):
91             file.write('%i;%i\n' % (i, i))
92         file.close()
93         self.nbind = len(self.tableau.linecontent)
94 #------------------------------------------------------------
95         RchdQuest(self.pathout, self.parent.RscriptsPath, self.parametres['nbcl_p1'], self.parametres['mincl'])
96 #------------------------------------------------------------
97         count += 1
98         self.dlg.Update(count, u"Analyse (patientez...)")
99         
100         pid = exec_rcode(self.parent.RPath, self.pathout['Rchdquest'], wait = False)
101         while pid.poll() == None :
102             self.dlg.Pulse(u"Analyse (patientez...)")
103             time.sleep(0.2)
104         if not check_Rresult(self.parent, pid) :
105             if self.dlg :
106                 self.dlg.Destroy()
107             return 'NOK'
108 #------------------------------------------------------------
109         count += 1
110         self.dlg.Update(count, u"Ecriture des résultats")
111         self.tableau.buildprofil()
112         self.clnb = self.tableau.clnb
113         self.parametres['clnb'] = self.clnb
114         self.ucecla = self.tableau.ucecla
115         self.BuildProfile()
116         temps = time.time() - self.t1
117         PrintRapport(self, self, {}, istxt = False)
118         self.tableau.save_tableau(self.pathout['db'])
119         #CreateIraFile(self.dictpathout, self.clnb, corpname = os.path.basename(self.parent.filename), section = 'questionnaire')
120         afc_graph_list = [[os.path.basename(self.pathout['AFC2DL_OUT']), u'Variables actives - coordonnées - facteurs 1 / 2'],
121                          [os.path.basename(self.pathout['AFC2DSL_OUT']), u'variables illustratives - coordonnées - facteurs 1 / 2'],
122                          [os.path.basename(self.pathout['AFC2DCL_OUT']), u'Classes - Coordonnées - facteur 1 / 2'],]
123         chd_graph_list = [[os.path.basename(self.pathout['dendro1']), u'dendrogramme à partir de chd1']]
124         chd_graph_list.append([os.path.basename(self.pathout['arbre1']), u'chd1'])
125         print_liste(self.pathout['liste_graph_afc'], afc_graph_list)
126         print_liste(self.pathout['liste_graph_chd'], chd_graph_list)
127
128         #self.tableau = self.parent.tableau
129         #OpenCHDS(self.parent, self, self.dictpathout['ira'], False)
130 #------------------------------------------------------------
131         print 'fini', time.time() - self.t1
132         count += 1
133         self.dlg.Update(count, "Fini")
134     
135     def BuildProfile(self):
136         print 'build profile'
137         txt = ''
138         txt += """
139         source("%s")
140         """ % ffr(self.parent.RscriptsPath['chdfunct'])
141         txt += """
142         load("%s")
143         """ % ffr(self.pathout['RData'])
144         txt += """
145         dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
146         """ % ffr(self.pathout['Contout'])
147         txt += """
148         dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
149         """ % ffr(self.pathout['ContEtOut'])
150         txt += """
151         clnb<-%i
152         """ % self.clnb
153         txt += """
154         tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
155         tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
156         PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],%i,"%s","%s")
157         """ % (self.clnb, ffr(self.pathout['PROFILE_OUT']), ffr(self.pathout['ANTIPRO_OUT']))
158         txt += """
159         colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
160         colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
161         colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
162         colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
163         chistabletot<-rbind(as.data.frame(tablesqrpact[2]),as.data.frame(tablesqrpet[2]))
164         ptabletot<-rbind(as.data.frame(tablesqrpact[1]),as.data.frame(tablesqrpet[1]))
165         gbcluster<-n1
166         write.csv2(chistabletot,file="%s")
167         """ % ffr(self.pathout['chisqtable'])
168         txt += """
169         write.csv2(ptabletot,file="%s")
170         """ % ffr(self.pathout['ptable'])
171         txt += """
172         write.csv2(gbcluster,file="%s")
173         """ % ffr(self.pathout['SbyClasseOut'])
174         if self.clnb > 2 :
175             txt += """
176             library(ca)
177             rowtot<-nrow(dataact)+nrow(dataet)
178             afctable<-rbind(as.matrix(dataact),as.matrix(dataet))
179             colnames(afctable)<-paste('classe',1:clnb,sep=' ')
180             afc<-ca(afctable,suprow=((nrow(dataact)+1):rowtot),nd=(ncol(afctable)-1))
181             debet<-nrow(dataact)+1
182             debsup<-NULL
183             fin<-rowtot
184             afc<-AddCorrelationOk(afc)
185             source("%s")
186             """ % ffr(self.parent.RscriptsPath['Rgraph'])
187     
188             txt += """
189             afc <- summary.ca.dm(afc)
190             afc_table <- create_afc_table(afc)
191             write.csv2(afc_table$facteur, file = "%s")
192             write.csv2(afc_table$colonne, file = "%s")
193             write.csv2(afc_table$ligne, file = "%s")
194             """ % (ffr(self.pathout['afc_facteur']), ffr(self.pathout['afc_col']), ffr(self.pathout['afc_row']))
195             
196             txt += """
197             xlab <- paste('facteur 1 - ', round(afc$facteur[1,2],2), sep = '')
198             ylab <- paste('facteur 2 - ', round(afc$facteur[2,2],2), sep = '')
199             xlab <- paste(xlab, ' %', sep = '')
200             ylab <- paste(ylab, ' %', sep = '')
201             """
202     
203             txt += """
204             PARCEX<-%s
205             """ % "0.9"
206             txt += """
207             xyminmax <- PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=1, fin=(debet-1), xlab = xlab, ylab = ylab)
208             """ % (ffr(self.pathout['AFC2DL_OUT']))
209             txt += """
210             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])
211             """ % (ffr(self.pathout['AFC2DSL_OUT']))
212             txt += """
213             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])
214             """ % (ffr(self.pathout['AFC2DCL_OUT']))
215         txt += """
216         save.image(file="%s")
217         """ % ffr(self.pathout['RData'])
218         tmpfile = tempfile.mktemp(dir=self.parent.TEMPDIR)
219         tmpscript = open(tmpfile, 'w')
220         tmpscript.write(txt)
221         tmpscript.close()
222         pid = exec_rcode(self.parent.RPath, tmpfile, wait = False)
223         while pid.poll() == None :
224             time.sleep(0.2)
225         check_Rresult(self.parent, pid)
226         temps = time.time() - self.t1
227         self.minutes, self.seconds = divmod(temps, 60)
228         self.hours, self.minutes = divmod(self.minutes, 60)