from mac
[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         chd_graph_list = [[os.path.basename(self.dictpathout['dendro1']), u'dendrogramme à partir de chd1']]
115         chd_graph_list.append([os.path.basename(self.dictpathout['arbre1']), u'chd1'])
116         print_liste(self.dictpathout['liste_graph_afc'], afc_graph_list)
117         print_liste(self.dictpathout['liste_graph_chd'], chd_graph_list)
118
119         self.tableau = self.parent.tableau
120         #OpenCHDS(self.parent, self, self.dictpathout['ira'], False)
121 #------------------------------------------------------------
122         print 'fini', time.time() - self.t1
123         count += 1
124         self.dlg.Update(count, "Fini")
125     
126     def BuildProfile(self):
127         print 'build profile'
128         txt = ''
129         txt += """
130         source("%s")
131         """ % self.parent.RscriptsPath['chdfunct']
132         txt += """
133         load("%s")
134         """ % self.dictpathout['RData']
135         txt += """
136         dataact<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
137         """ % self.dictpathout['Contout']
138         txt += """
139         dataet<-read.csv2("%s", header = FALSE, sep = ';',quote = '\"', row.names = 1, na.strings = 'NA')
140         """ % self.dictpathout['ContEtOut']
141         txt += """
142         clnb<-%i
143         """ % self.clnb
144         txt += """
145         tablesqrpact<-BuildProf(as.matrix(dataact),n1,clnb)
146         tablesqrpet<-BuildProf(as.matrix(dataet),n1,clnb)
147         PrintProfile(n1,tablesqrpact[4],tablesqrpet[4],tablesqrpact[5],tablesqrpet[5],%i,"%s","%s")
148         """ % (self.clnb, self.dictpathout['PROFILE_OUT'], self.dictpathout['ANTIPRO_OUT'])
149         txt += """
150         colnames(tablesqrpact[[2]])<-paste('classe',1:clnb,sep=' ')
151         colnames(tablesqrpact[[1]])<-paste('classe',1:clnb,sep=' ')
152         colnames(tablesqrpet[[2]])<-paste('classe',1:clnb,sep=' ')
153         colnames(tablesqrpet[[1]])<-paste('classe',1:clnb,sep=' ')
154         chistabletot<-rbind(as.data.frame(tablesqrpact[2]),as.data.frame(tablesqrpet[2]))
155         ptabletot<-rbind(as.data.frame(tablesqrpact[1]),as.data.frame(tablesqrpet[1]))
156         gbcluster<-n1
157         write.csv2(chistabletot,file="%s")
158         """ % self.dictpathout['chisqtable']
159         txt += """
160         write.csv2(ptabletot,file="%s")
161         """ % self.dictpathout['ptable']
162         txt += """
163         write.csv2(gbcluster,file="%s")
164         """ % self.dictpathout['SbyClasseOut']
165         if self.clnb > 2 :
166             txt += """
167             library(ca)
168             rowtot<-nrow(dataact)+nrow(dataet)
169             afctable<-rbind(as.matrix(dataact),as.matrix(dataet))
170             colnames(afctable)<-paste('classe',1:clnb,sep=' ')
171             afc<-ca(afctable,suprow=((nrow(dataact)+1):rowtot),nd=(ncol(afctable)-1))
172             debet<-nrow(dataact)+1
173             debsup<-NULL
174             fin<-rowtot
175             afc<-AddCorrelationOk(afc)
176             source("%s")
177             """ % self.parent.RscriptsPath['Rgraph']
178     
179             txt += """
180             afc <- summary.ca.dm(afc)
181             afc_table <- create_afc_table(afc)
182             write.csv2(afc_table$facteur, file = "%s")
183             write.csv2(afc_table$colonne, file = "%s")
184             write.csv2(afc_table$ligne, file = "%s")
185             """ % (self.dictpathout['afc_facteur'], self.dictpathout['afc_col'], self.dictpathout['afc_row'])
186             
187             txt += """
188             xlab <- paste('facteur 1 - ', round(afc$facteur[1,2],2), sep = '')
189             ylab <- paste('facteur 2 - ', round(afc$facteur[2,2],2), sep = '')
190             xlab <- paste(xlab, ' %', sep = '')
191             ylab <- paste(ylab, ' %', sep = '')
192             """
193     
194             txt += """
195             PARCEX<-%s
196             """ % "0.9"
197             txt += """
198             xyminmax <- PlotAfc2dCoul(afc, as.data.frame(chistabletot), "%s", what='coord', deb=1, fin=(debet-1), xlab = xlab, ylab = ylab)
199             """ % (self.dictpathout['AFC2DL_OUT'])
200             txt += """
201             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])
202             """ % (self.dictpathout['AFC2DSL_OUT'])
203             txt += """
204             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])
205             """ % (self.dictpathout['AFC2DCL_OUT'])
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)