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