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