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