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