d2facad6fd2230ddb0117aa8f539811c643a41e9
[iramuteq] / tabsimi.py
1 #!/bin/env python
2 # -*- coding: utf-8 -*-
3 #Author: Pierre Ratinaud
4 #Copyright (c) 2009-2010 Pierre Ratinaud
5 #Lisense: GNU/GPL
6
7 from chemins import ConstructPathOut, simipath, ffr
8 from functions import print_liste, exec_rcode, read_list_file, check_Rresult, indices_simi, treat_var_mod
9 from dialog import SelectColDial, FreqDialog
10 from guifunct import PrefSimi
11 from analysematrix import AnalyseMatrix
12 from PrintRScript import PrintSimiScript
13 from listlex import *
14 import wx
15 #if wx.__version__ >= '2.11' :
16 #    import wx.lib.agw.aui as aui
17 #else :
18 #    import aui
19 import os
20 import tempfile
21 import datetime
22 from ConfigParser import RawConfigParser
23 from time import sleep
24 from uuid import uuid4
25
26
27 class DoSimi(AnalyseMatrix):
28     def __init__(self, parent, param = None, isopen = False, fromprof = False, pathout = False, filename ='', gparent = False, wordgraph = False, listactives = False, actives = False, cmd = False, openfromprof=False):
29 #------------------------------------------------------------------- 
30         self.fromprof = fromprof
31         self.wordgraph = wordgraph
32         self.listactives = listactives
33         self.actives = actives
34         self.openfromprof = openfromprof
35         self.cmd = cmd
36         if param is not None and fromprof:
37             self.paramsimi = param
38         else :
39             self.paramsimi = {'coeff' : 0,
40                           'layout' : 2,
41                           'type_graph' : 1,
42                           'arbremax' : 1,
43                           'coeff_tv' : 0,
44                           'coeff_tv_nb' : 10,
45                           'tvprop' : 1,
46                           'tvmin' : 5,
47                           'tvmax' : 30,
48                           'coeff_te' : 1,
49                           'coeff_temin' : 1,
50                           'coeff_temax' : 10,
51                           'label_v': 1,
52                           'label_e': 1,
53                           'vcex' : 0,
54                           'vcexmin' : 8,
55                           'vcexmax' : 25,
56                           'cex' : 10,
57                           'seuil_ok' : 0,
58                           'seuil' : 1,
59                           'cols' : (255,0,0),
60                           'cola' : (200,200,200),
61                           'width' : 800,
62                           'height' : 800,
63                           'first' : True,
64                           'keep_coord' : False,
65                           'alpha' : 10,
66                           'film' : False,
67                           'svg' : 0,
68                           'halo' : 0,
69                           'com' : 0,
70                           'communities' : 0,
71                           }
72         self.indices = indices_simi
73         if fromprof :
74             self.parent = parent.parent
75             self.Source = parent
76         else :
77             self.parent = parent   
78             self.Source = None
79            
80         self.RPath = self.parent.PathPath.get('PATHS', 'rpath')
81         if not isopen :
82             if not fromprof :
83                 self.tableau = self.parent.tableau
84             else :
85                 self.tableau = parent.tableau
86             self.tableau.parametre['mineff'] = 0
87             dialcol = FreqDialog(self.parent, -1, self.tableau.get_colnames(), u"Sélectionnez les colonnes", size=(600, 250))
88             dialcol.CenterOnParent()            
89             res = dialcol.ShowModal()
90             if res == wx.ID_OK :
91                 self.tableau.selected_col = dialcol.list_box_1.GetSelections()
92                 actives = self.tableau.getactlistfromselection(self.tableau.selected_col)
93                 self.tableau.make_listactives()
94                 actives = dict([[i, val] for i, val in enumerate(actives)])
95                 self.dial = PrefSimi(parent, -1, self.paramsimi, self.indices, wordlist = actives)
96                 self.dial.CenterOnParent()
97                 self.val = self.dial.ShowModal()
98                 if self.val == wx.ID_OK :
99                     last = self.dial.listcol.GetFirstSelected()
100                     lastl = [self.dial.listcol.GetFirstSelected()]
101                     indexes = [self.dial.listcol.getColumnText(self.dial.listcol.GetFirstSelected(),0)]
102                     while self.dial.listcol.GetNextSelected(last) != -1:
103                         last = self.dial.listcol.GetNextSelected(last)
104                         lastl.append(last)
105                         indexes.append(self.dial.listcol.getColumnText(last,0))
106                     self.column = [self.tableau.listactives.index(val) for val in indexes]
107                     self.column.sort()
108                     self.paramsimi = self.make_param()
109                     self.parametres = self.paramsimi
110                     self.parametres['type'] = 'simimatrix'
111                     self.parametres['pathout'] = ConstructPathOut(self.tableau.parametre['filename'], 'SimiMatrix')
112                     self.parametres['filename'] = self.tableau.parametres['filename']
113                     self.dial.Destroy()
114                     dlg = wx.ProgressDialog("Traitements",
115                                    "Veuillez patienter...",
116                                    maximum=4,
117                                    parent=self.parent,
118                                    style=wx.PD_APP_MODAL | wx.PD_AUTO_HIDE | wx.PD_ELAPSED_TIME
119                                     )
120                     dlg.Center()
121                     AnalyseMatrix.__init__(self, parent, self.tableau, self.paramsimi, dlg = dlg)
122                 else :
123                     self.dial.Destroy()
124             else :
125                 dialcol.Destroy()
126
127     def doanalyse(self) :
128
129         self.pathout.basefiles(simipath)
130         with open(self.pathout['selected.csv'], 'w') as f :
131              f.write('\n'.join([`val` for val in self.column]))
132
133         count = 1
134         keepGoing = self.dlg.Update(count)
135     #----------------------------------------------------------------
136         self.DictForme = {}
137         self.Min = 10
138         self.Linecontent = []
139     #--------------------------------------------------------
140         count += 1
141         #if not self.fromprof :
142             #self.pathout = ConstructPathOut(self.tableau.parametre['filename'], 'Simi')
143             #self.DictPathOut = construct_simipath(self.pathout)
144         self.parent.tableau.dictpathout = self.pathout
145         self.dlg.Update(count, u"passage en O/1")
146         self.parent.tableau.make_01_from_selection(self.tableau.selected_col)
147             #self.Linecontent = parent.table
148             #self.ListTo01Form()
149         #else :
150             #self.pathout = pathout
151             #self.DictPathOut = construct_simipath(self.pathout)
152         self.DictPathOut = self.pathout
153             #self.DictPathOut['mat01'] = fromprof
154         self.script = PrintSimiScript(self)
155         self.script.make_script()
156         #self.PrintScript()
157         count += 1
158         self.dlg.Update(count, u"R...") 
159         #self.DoR(script.scriptout, dlg = self.dlg, message = 'R...')
160         self.tmpfile = self.script.scriptout
161         self.DoR(self.dlg)
162         self.addgraph()
163         self.tableau.save_tableau(self.pathout['db'])
164         #self.make_ira()
165         count += 1
166         self.dlg.Update(count, u"") 
167         self.dlg.Destroy()
168         #self.dial.Destroy()
169         #self.dolayout()
170         if self.fromprof :
171             fromprof = True
172         else:
173             fromprof = False
174         #OpenAnalyse(self.parent, self.DictPathOut['ira'], False, simifromprof=fromprof)
175 #        else :
176 #            self.tableau = gparent.tableau
177 #            if 'corpus' in dir(gparent) :
178 #                self.Source = gparent
179 #            self.tableau.parametre['mineff'] = 0
180 #            self.DictPathOut = construct_simipath(os.path.abspath(os.path.dirname(filename)))
181 #            self.dolayout()
182 #            self.paramsimi['first'] = False
183 #            self.paramsimi['coeff'] = int(param.get('simi', 'indice'))
184 #            self.paramsimi['layout'] = int(param.get('simi', 'layout'))
185 #            self.paramsimi['seuil_ok'] = param.getboolean('simi', 'seuil_ok')
186 #            self.paramsimi['seuil'] = int(param.get('simi', 'seuil'))
187 #            if param.get('simi', 'wordgraph') == 'False' :
188 #                self.wordgraph = False
189 #            else :
190 #                self.wordgraph = param.get('simi', 'wordgraph')
191 #            if 'listet' in dir(self.tableau) :
192 #                self.paramsimi['stars'] = self.tableau.listet
193 #                self.paramsimi['bystar'] = False
194 #                self.paramsimi['cexfromchi'] = True
195 #                self.paramsimi['tvprop'] = False
196 #                self.paramsimi['sfromchi'] = False
197 #                self.paramsimi['coeff_te'] = True
198 #                self.paramsimi['coeff_tv'] = True
199 #                self.paramsimi['coeff_tv_nb'] = 0
200 #                self.paramsimi['label_e'] = False
201 #                self.paramsimi['width'] = 1000
202 #                self.paramsimi['height'] = 1000
203          
204
205     def make_param(self) :
206         if self.paramsimi['first'] :
207             keep_coord = False
208         else :
209             keep_coord = self.dial.check_coord.GetValue()
210         #self.select = self.dial.check_colch.GetValue()
211
212         paramsimi = {'coeff' : self.dial.choice1.GetSelection(),
213                           'layout' : self.dial.choice2.GetSelection(),
214                           'type_graph' : self.dial.choice3.GetSelection(),
215                           'arbremax' : self.dial.check1.GetValue(),
216                           'coeff_tv' : self.dial.check_s_size.GetValue(),
217                           'coeff_tv_nb' : self.dial.spin_tv.GetValue(),
218                           'tvprop' : self.dial.check2.GetValue(),
219                           'tvmin' : self.dial.spin_tvmin.GetValue(),
220                           'tvmax' : self.dial.spin_tvmax.GetValue(),
221                           'coeff_te' : self.dial.check3.GetValue(),
222                           'coeff_temin' : self.dial.spin_temin.GetValue(),
223                           'coeff_temax' : self.dial.spin_temax.GetValue(),
224                           'label_e' : self.dial.check_elab.GetValue(),
225                           'label_v' : self.dial.check_vlab.GetValue(),
226                           'vcex' : self.dial.check_vcex.GetValue(),
227                           'vcexmin' : self.dial.spin_vcexmin.GetValue(),
228                           'vcexmax' : self.dial.spin_vcexmax.GetValue(),
229                           'cex' : self.dial.spin_cex.GetValue(),
230                           'seuil_ok' : self.dial.check_seuil.GetValue(),
231                           'seuil' : self.dial.spin_seuil.GetValue(),
232                           'cols' : self.dial.cols.GetColour(),
233                           'cola' : self.dial.cola.GetColour(),
234                           'width' : self.dial.spin_width.GetValue(),
235                           'height' : self.dial.spin_height.GetValue(),
236                           'first' : False,
237                           'keep_coord' : keep_coord,
238                           'alpha' : self.dial.slider_sphere.GetValue(),
239                           'film' : self.dial.film.GetValue(),
240                           'svg' : self.dial.choix_format.GetSelection(),
241                           'halo' : self.dial.halo.GetValue(),
242                           'com' : self.dial.comcheck.GetValue(),
243                           'communities' :self.dial.choix_com.GetSelection(),
244                           }
245         if 'cexfromchi' in self.paramsimi :
246             paramsimi['cexfromchi'] = self.dial.checkit.GetValue()
247         if 'sfromchi' in self.paramsimi :
248             paramsimi['sfromchi'] = self.dial.checki.GetValue()
249         if 'vlabcolor' in self.paramsimi :
250            paramsimi['vlabcolor'] = self.paramsimi['vlabcolor']
251         if 'check_bystar' in dir(self.dial) :
252             paramsimi['bystar'] = self.dial.check_bystar.GetValue()
253             paramsimi['stars'] = self.paramsimi['stars']
254         return paramsimi
255         
256 #    def make_ira(self):
257 #        self.tableau.save_tableau(self.DictPathOut['db'])
258 #        conf = RawConfigParser()
259 #        conf.read(self.DictPathOut['ira'])
260 #        if not 'simi' in conf.sections() :
261 #            conf.add_section('simi')
262 #        date = datetime.datetime.now().ctime()
263 #        if self.fromprof :
264 #            conf.set('simi', 'corpus', self.Source.corpus.parametres['uuid'])
265 #        conf.set('simi', 'uuid', str(uuid4()))
266 #        conf.set('simi', 'date', str(date))
267 #        conf.set('simi', 'indice', self.paramsimi['coeff'])
268 #        conf.set('simi','layout', self.paramsimi['layout'])
269 #        conf.set('simi', 'seuil_ok', self.paramsimi['seuil_ok'])
270 #        conf.set('simi', 'seuil', str(self.paramsimi['seuil']))
271 #        conf.set('simi', 'wordgraph', self.wordgraph)
272 #        fileout = open(self.DictPathOut['ira'], 'w')
273 #        conf.write(fileout)
274 #        fileout.close()
275 #        
276     def addgraph(self) :
277         if self.parametres['type_graph'] == 1:
278             if self.parametres['svg'] :
279                 filename, ext = os.path.splitext(self.script.filename)
280                 fileout = filename + '.svg'
281             else :
282                 fileout = self.script.filename
283             if os.path.exists(self.DictPathOut['liste_graph']):
284                 graph_simi = read_list_file(self.DictPathOut['liste_graph'])
285                 graph_simi.append([os.path.basename(fileout), self.script.txtgraph])
286             else :
287                 graph_simi = [[os.path.basename(fileout), self.script.txtgraph]]
288             print_liste(self.DictPathOut['liste_graph'], graph_simi)
289         
290     def DoR(self, dlg):
291         if self.paramsimi['type'] == 1 :
292             graph = False
293             wait = False
294         else : 
295             graph = True
296             wait = True
297         pid = exec_rcode(self.RPath, self.tmpfile, wait = wait, graph = graph)
298         if self.paramsimi['type'] == 1 :
299             while pid.poll() == None :
300                     if not self.cmd :
301                         dlg.Pulse(u'R ...')
302                         sleep(0.2)
303                     else :
304                         sleep(0.2)
305             check_Rresult(self.parent, pid)
306     
307