...
[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, construct_simipath, ffr
8 from functions import print_liste, exec_rcode, read_list_file, check_Rresult, indices_simi, treat_var_mod
9 from dialog import PrefSimi, SelectColDial, OptLexi
10 from listlex import *
11 import wx
12 import wx.lib.agw.aui as aui
13 from numpy import *
14 import os
15 import tempfile
16 import datetime
17 from ConfigParser import RawConfigParser
18 from time import sleep
19 from uuid import uuid4
20
21
22 class DoSimi():
23     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):
24 #------------------------------------------------------------------- 
25         self.fromprof = fromprof
26         self.wordgraph = wordgraph
27         self.listactives = listactives
28         self.actives = actives
29         self.openfromprof = openfromprof
30         self.cmd = cmd
31         if param is not None and fromprof:
32             self.paramsimi = param
33         else :
34             self.paramsimi = {'coeff' : 0,
35                           'layout' : 2,
36                           'type_graph' : 1,
37                           'arbremax' : 1,
38                           'coeff_tv' : 0,
39                           'coeff_tv_nb' : 10,
40                           'tvprop' : 1,
41                           'tvmin' : 5,
42                           'tvmax' : 30,
43                           'coeff_te' : 1,
44                           'coeff_temin' : 1,
45                           'coeff_temax' : 10,
46                           'label_v': 1,
47                           'label_e': 1,
48                           'vcex' : 0,
49                           'vcexmin' : 8,
50                           'vcexmax' : 25,
51                           'cex' : 10,
52                           'seuil_ok' : 0,
53                           'seuil' : 1,
54                           'cols' : (255,0,0),
55                           'cola' : (200,200,200),
56                           'width' : 800,
57                           'height' : 800,
58                           'first' : True,
59                           'keep_coord' : False,
60                           'alpha' : 10,
61                           'film' : False,
62                           }
63         self.types = indices_simi
64         if fromprof :
65             self.parent = parent.parent
66             self.Source = parent
67         else :
68             self.parent = parent   
69             self.Source = None
70            
71         self.RPath = self.parent.PathPath.get('PATHS', 'rpath')
72         if not isopen :
73             if not fromprof :
74                 self.tableau = self.parent.tableau
75             else :
76                 self.tableau = parent.tableau
77             self.tableau.parametre['mineff'] = 0
78             self.dial = PrefSimi(parent, -1, self.paramsimi, self.types)
79             self.dial.CenterOnParent()
80             self.val = self.dial.ShowModal()
81             if self.val == wx.ID_OK :
82                 self.paramsimi = self.make_param()
83                 self.dial.Destroy()
84                 if self.paramsimi.get('bystar', False) :
85                     variables = treat_var_mod(self.tableau.listet)
86                     dial = OptLexi(self.parent)
87                     dial.listet = self.tableau.listet
88                     var = [v for v in variables]
89                     dial.variables = var
90                     for et in var :
91                         dial.list_box_1.Append(et)
92                     dial.CenterOnParent()
93                     val = dial.ShowModal()
94                     if val == wx.ID_OK :
95                         if dial.choice.GetSelection() == 1 :
96                             listet = [self.tableau.listet[i] for i in dial.list_box_1.GetSelections()]
97                         else :
98                             listet = variables[var[dial.list_box_1.GetSelections()[0]]]
99                         dial.Destroy()
100                         self.tableau.etline = self.Source.corpus.make_etline(listet)
101
102                 dlg = wx.ProgressDialog("Traitements",
103                                        "Veuillez patienter...",
104                                        maximum=4,
105                                        parent=self.parent,
106                                        style=wx.PD_APP_MODAL | wx.PD_AUTO_HIDE | wx.PD_ELAPSED_TIME
107                                         )
108                 dlg.Center()
109                 count = 1
110                 keepGoing = dlg.Update(count)
111         #-------------------------------------------------------------------
112                 self.DictForme = {}
113                 self.Min = 10
114                 self.Linecontent = []
115         #-----------------------------------------------------------
116                 count += 1
117                 if not fromprof :
118                     self.pathout = ConstructPathOut(parent.tableau.parametre['filename'], 'Simi')
119                     self.DictPathOut = construct_simipath(self.pathout)
120                     self.parent.tableau.dictpathout = self.DictPathOut
121                     dlg.Update(count, u"passage en O/1")
122                     self.parent.tableau.make_01_from_selection(range(0,self.parent.tableau.colnb))
123                     #self.Linecontent = parent.table
124                     #self.ListTo01Form()
125                 else :
126                     self.pathout = pathout
127                     self.DictPathOut = construct_simipath(self.pathout)
128                     self.DictPathOut['mat01'] = fromprof
129                 self.PrintScript()
130                 count += 1
131                 dlg.Update(count, u"R...") 
132                 self.DoR(dlg)
133                 self.make_ira()
134                 count += 1
135                 dlg.Update(count, u"") 
136                 dlg.Destroy()
137                 #self.dial.Destroy()
138                 #self.dolayout()
139                 from openanalyse import OpenAnalyse
140                 if self.fromprof :
141                     fromprof = True
142                 else:
143                     fromprof = False
144                 OpenAnalyse(self.parent, self.DictPathOut['ira'], False, simifromprof=fromprof)
145             else:
146                 self.dial.Destroy()
147         else :
148             self.tableau = gparent.tableau
149             if 'corpus' in dir(gparent) :
150                 self.Source = gparent
151             self.tableau.parametre['mineff'] = 0
152             self.DictPathOut = construct_simipath(os.path.abspath(os.path.dirname(filename)))
153             self.dolayout()
154             self.paramsimi['first'] = False
155             self.paramsimi['coeff'] = int(param.get('simi', 'indice'))
156             self.paramsimi['layout'] = int(param.get('simi', 'layout'))
157             self.paramsimi['seuil_ok'] = param.getboolean('simi', 'seuil_ok')
158             self.paramsimi['seuil'] = int(param.get('simi', 'seuil'))
159             if param.get('simi', 'wordgraph') == 'False' :
160                 self.wordgraph = False
161             else :
162                 self.wordgraph = param.get('simi', 'wordgraph')
163             if 'listet' in dir(self.tableau) :
164                 self.paramsimi['stars'] = self.tableau.listet
165                 self.paramsimi['bystar'] = False
166                 self.paramsimi['cexfromchi'] = True
167                 self.paramsimi['tvprop'] = False
168                 self.paramsimi['sfromchi'] = False
169                 self.paramsimi['coeff_te'] = True
170                 self.paramsimi['coeff_tv'] = True
171                 self.paramsimi['coeff_tv_nb'] = 0
172                 self.paramsimi['label_e'] = False
173                 self.paramsimi['width'] = 1000
174                 self.paramsimi['height'] = 1000
175          
176
177     def make_param(self) :
178         if self.paramsimi['first'] :
179             keep_coord = False
180         else :
181             keep_coord = self.dial.check_coord.GetValue()
182         self.select = self.dial.check_colch.GetValue()
183
184         paramsimi = {'coeff' : self.dial.choice1.GetSelection(),
185                           'layout' : self.dial.choice2.GetSelection(),
186                           'type_graph' : self.dial.choice3.GetSelection(),
187                           'arbremax' : self.dial.check1.GetValue(),
188                           'coeff_tv' : self.dial.check_s_size.GetValue(),
189                           'coeff_tv_nb' : self.dial.spin_tv.GetValue(),
190                           'tvprop' : self.dial.check2.GetValue(),
191                           'tvmin' : self.dial.spin_tvmin.GetValue(),
192                           'tvmax' : self.dial.spin_tvmax.GetValue(),
193                           'coeff_te' : self.dial.check3.GetValue(),
194                           'coeff_temin' : self.dial.spin_temin.GetValue(),
195                           'coeff_temax' : self.dial.spin_temax.GetValue(),
196                           'label_e' : self.dial.check_elab.GetValue(),
197                           'label_v' : self.dial.check_vlab.GetValue(),
198                           'vcex' : self.dial.check_vcex.GetValue(),
199                           'vcexmin' : self.dial.spin_vcexmin.GetValue(),
200                           'vcexmax' : self.dial.spin_vcexmax.GetValue(),
201                           'cex' : self.dial.spin_cex.GetValue(),
202                           'seuil_ok' : self.dial.check_seuil.GetValue(),
203                           'seuil' : self.dial.spin_seuil.GetValue(),
204                           'cols' : self.dial.cols.GetColour(),
205                           'cola' : self.dial.cola.GetColour(),
206                           'width' : self.dial.spin_width.GetValue(),
207                           'height' : self.dial.spin_height.GetValue(),
208                           'first' : False,
209                           'keep_coord' : keep_coord,
210                           'alpha' : self.dial.slider_sphere.GetValue(),
211                           'film' : self.dial.film.GetValue()
212                           }
213         if 'cexfromchi' in self.paramsimi :
214             paramsimi['cexfromchi'] = self.dial.checkit.GetValue()
215         if 'sfromchi' in self.paramsimi :
216             paramsimi['sfromchi'] = self.dial.checki.GetValue()
217         if 'vlabcolor' in self.paramsimi :
218            paramsimi['vlabcolor'] = self.paramsimi['vlabcolor']
219         if 'check_bystar' in dir(self.dial) :
220             paramsimi['bystar'] = self.dial.check_bystar.GetValue()
221             paramsimi['stars'] = self.paramsimi['stars']
222         return paramsimi
223         
224     def make_ira(self):
225         self.tableau.save_tableau(self.DictPathOut['db'])
226         conf = RawConfigParser()
227         conf.read(self.DictPathOut['ira'])
228         if not 'simi' in conf.sections() :
229             conf.add_section('simi')
230         date = datetime.datetime.now().ctime()
231         if self.fromprof :
232             conf.set('simi', 'corpus', self.Source.corpus.parametres['uuid'])
233         conf.set('simi', 'uuid', str(uuid4()))
234         conf.set('simi', 'date', str(date))
235         conf.set('simi', 'indice', self.paramsimi['coeff'])
236         conf.set('simi','layout', self.paramsimi['layout'])
237         conf.set('simi', 'seuil_ok', self.paramsimi['seuil_ok'])
238         conf.set('simi', 'seuil', str(self.paramsimi['seuil']))
239         conf.set('simi', 'wordgraph', self.wordgraph)
240         fileout = open(self.DictPathOut['ira'], 'w')
241         conf.write(fileout)
242         fileout.close()
243         
244     def PrintScript(self):
245         if self.select :
246             if self.listactives :
247                 lactives = self.listactives
248             else :
249                 lactives = self.tableau.listactives
250             if self.actives :
251                 acts = self.actives
252             else :
253                 acts = self.tableau.actives
254             dictcol = [[i, [active, acts[active][0]]] for i, active in enumerate(lactives)]
255             dictcol = dict(dictcol)
256             dlg = SelectColDial(self.parent)
257             listcol = ListForSpec(dlg, self, dictcol, ['forme', 'eff'])
258             dlg.bSizer2.Add( listcol, 2, wx.ALL|wx.EXPAND, 5 )
259             dlg.m_sdbSizer2.AddButton( dlg.m_sdbSizer2OK )
260             dlg.m_sdbSizer2.Realize()
261             dlg.bSizer2.Add( dlg.m_sdbSizer2, 0, wx.EXPAND, 5 )
262             dlg.Layout()
263             if not 'selected_col' in dir(self.tableau) :
264                 for row in xrange(listcol.list.GetItemCount()):
265                     listcol.list.Select(row)
266             else :
267                 for row in self.tableau.selected_col :
268                     listcol.list.Select(row)
269             dlg.CenterOnParent()
270             val = dlg.ShowModal()
271             datas = [listcol.getColumnText(listcol.list.GetFirstSelected(),0)]
272             last = listcol.list.GetFirstSelected()
273             lastl = [listcol.list.GetFirstSelected()]
274             while listcol.list.GetNextSelected(last) != -1:
275                 last = listcol.list.GetNextSelected(last)
276                 lastl.append(last)
277                 datas.append(listcol.getColumnText(last,0))
278             dlg.Destroy()
279             datas = [lactives.index(val) for val in datas]
280             self.tableau.selected_col = lastl
281             self.tableau.datas = datas
282             datas = str(tuple(datas))
283         elif not self.select and 'selected_col' in dir(self.tableau) :
284             datas = str(tuple(self.tableau.datas))
285         elif self.wordgraph :
286             col = self.tableau.listactives.index(self.wordgraph)
287
288         tmpchi = False
289         if (self.fromprof or self.openfromprof) and (self.paramsimi.get('cexfromchi', False) or self.paramsimi.get('sfromchi', False)):
290             if 'lchi' in dir(self.tableau) :
291                 tmpchi = tempfile.mktemp(dir=self.parent.TEMPDIR)
292                 with open(tmpchi, 'w') as f:
293                     f.write('\n'.join([str(val) for val in self.tableau.lchi]))
294
295         active_file = tempfile.mktemp(dir=self.parent.TEMPDIR)
296         if self.listactives :
297             lactives = self.listactives
298         else :
299             lactives = self.tableau.listactives
300         self.tableau.listactives = lactives
301         with open(active_file, 'w') as f: 
302             f.write('\n'.join(lactives))
303
304         txt = '#script genere par Iramuteq'
305         txt += """
306         library('igraph')
307         library('proxy')
308         library('Matrix')
309         """
310         if os.path.exists(self.DictPathOut['RData']) :
311             txt += """
312             load("%s")
313             """ % self.DictPathOut['RData']
314         if not self.paramsimi['keep_coord'] :
315             #FIXME : beurk!!
316             i = 0
317             market = False
318             with open(self.DictPathOut['mat01'],'r') as f :
319                 for line in f.readlines() :
320                     if 'MatrixMarket' in line :
321                         market = True
322                         break
323                     elif i >= 1 :
324                         market = False
325                         break
326                     i += 1
327             print market
328             #if (self.fromprof or 'fromtxt' in self.tableau.parametre or self.openfromprof) and not self.actives :
329             if market :
330                 txt += """
331                 dm <-readMM("%s")
332                 """ % self.DictPathOut['mat01']
333             else :
334                 txt += """
335                 dm <- read.csv2("%s")
336                 """ % self.DictPathOut['mat01']
337             txt += """    
338             dm <- as.matrix(dm)
339             #dml <- apply(dm, 2, as.logical)
340             """
341             if not self.paramsimi['keep_coord'] :
342                 txt += """
343                 cn <- read.table("%s", sep=';', quote='"')
344                 colnames(dm) <- cn[,1]
345                 #colnames(dml) <- cn[,1]
346                 """ % ffr(active_file)
347         if 'selected_col' in dir(self.tableau) and not self.paramsimi['keep_coord']:
348             txt += """
349             #dml <- dml[, c%s+1]
350             dm <- dm[, c%s+1]
351             """ % (datas, datas)
352         txt += """
353         source("%s")
354         source("%s")
355         """ % (self.parent.RscriptsPath['simi'],self.parent.RscriptsPath['Rgraph'])
356
357         self.txtgraph = ''
358         self.txtgraph += self.types[self.paramsimi['coeff']]
359         if not self.paramsimi['keep_coord'] :
360             if self.paramsimi['coeff'] == 0 :
361                 method = 'cooc'
362                 txt += """
363                 method <- 'cooc'
364                 mat <- make.a(dm)
365                 """
366             elif self.paramsimi['coeff'] == 1 :
367                 method = 'prcooc'
368                 txt += """
369                 method <- 'Russel'
370                 mat <- simil(dm, method = 'Russel', diag = TRUE, upper = TRUE, by_rows = FALSE)
371                 """
372             elif self.types[self.paramsimi['coeff']] == 'binomial' :
373                 method = 'binomial'
374                 txt += """
375                 method <- 'binomial'
376                 mat <- binom.sim(dm)
377                 """
378             else :
379                 method = self.types[self.paramsimi['coeff']]
380                 txt += """
381                 method <-"%s"
382                 mat <- simil(dm, method = method, diag = TRUE, upper = TRUE, by_rows = FALSE)
383                 """ % self.types[self.paramsimi['coeff']]
384             txt += """
385             mat <- as.matrix(stats::as.dist(mat,diag=TRUE,upper=TRUE))
386             mat[is.na(mat)] <- 0
387             mat[is.infinite(mat)] <- 0
388             """
389             if self.types[self.paramsimi['coeff']] not in ['cooccurrence', 'Chi-squared', 'Mozley', 'Stiles'] :
390                 txt += """
391                 mat <- mat * 100
392                 """
393             if self.wordgraph :
394                 txt += """
395                 mat <- graph.word(mat, %i)
396                 """ % (col + 1)
397             txt += """
398             eff <- colSums(dm)
399             x <- list(mat = mat, eff = eff)
400             """
401         else :
402             method = ''
403         if self.paramsimi['layout'] == 0 : layout = 'random'
404         if self.paramsimi['layout'] == 1 : layout = 'circle'
405         if self.paramsimi['layout'] == 2 : layout = 'frutch'
406         if self.paramsimi['layout'] == 3 : layout = 'kawa'
407         if self.paramsimi['layout'] == 4 : layout = 'graphopt'
408         
409         self.filename=''
410         if self.paramsimi['type_graph'] == 0 : type = 'tkplot'
411         if self.paramsimi['type_graph'] == 1 : 
412             graphnb = 1
413             type = 'nplot'
414             dirout = os.path.dirname(self.DictPathOut['mat01'])
415             while os.path.exists(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png')):
416                 graphnb +=1
417             self.filename = ffr(os.path.join(dirout,'graph_simi_'+str(graphnb)+'.png'))
418         if self.paramsimi['type_graph'] == 2 : type = 'rgl'
419      
420         if self.paramsimi['arbremax'] : 
421             arbremax = 'TRUE'
422             self.txtgraph += ' - arbre maximum'
423         else : arbremax = 'FALSE'
424         
425         if self.paramsimi['coeff_tv'] : 
426             coeff_tv = self.paramsimi['coeff_tv_nb']
427             tvminmax = 'c(NULL,NULL)'
428         elif not self.paramsimi['coeff_tv'] or self.paramsimi.get('sformchi', False) :
429             coeff_tv = 'NULL'
430             tvminmax = 'c(%i, %i)' %(self.paramsimi['tvmin'], self.paramsimi['tvmax'])
431         txt += """
432         minmaxeff <- %s
433         """ % tvminmax
434         
435         if self.paramsimi['coeff_te'] : coeff_te = 'c(%i,%i)' % (self.paramsimi['coeff_temin'], self.paramsimi['coeff_temax'])
436         else : coeff_te = 'NULL'
437         
438         if self.paramsimi['vcex'] or self.paramsimi.get('cexfromchi', False) :
439             vcexminmax = 'c(%i/10,%i/10)' % (self.paramsimi['vcexmin'],self.paramsimi['vcexmax'])
440         else :
441             vcexminmax = 'c(NULL,NULL)'   
442
443         txt += """
444         vcexminmax <- %s
445         """ % vcexminmax
446
447         txt += """
448         cex = %i/10
449         """ % self.paramsimi['cex']
450
451         if not self.paramsimi['label_v'] : label_v = 'FALSE'
452         else : label_v = 'TRUE'
453
454         if not self.paramsimi['label_e'] : label_e = 'FALSE'
455         else : label_e = 'TRUE'
456         
457         if self.paramsimi['seuil_ok'] : seuil = str(self.paramsimi['seuil'])
458         else : seuil = 'NULL'
459
460         if self.paramsimi['film'] : 
461             txt += """
462             film <- "%s"
463             """ % self.DictPathOut['film']
464         else : 
465             txt += """
466             film <- NULL
467             """
468
469         txt += """
470         seuil <- %s
471         """ % seuil
472         
473         txt += """
474         label.v <- %s
475         label.e <- %s
476         """ % (label_v, label_e)
477
478         cols = str(self.paramsimi['cols']).replace(')',', max=255)')
479         cola = str(self.paramsimi['cola']).replace(')',',max=255)')
480
481         txt += """
482         cols <- rgb%s
483         cola <- rgb%s
484         """ % (cols, cola)
485
486         txt += """
487         width <- %i
488         height <- %i
489         """ % (self.paramsimi['width'], self.paramsimi['height'])
490
491         if self.paramsimi['keep_coord'] :
492             txt += """
493             coords <- try(coords, TRUE)
494             if (!is.matrix(coords)) {
495                 coords<-NULL
496             }
497             """
498         else :
499             txt += """
500             coords <- NULL
501             """
502         txt += """
503         alpha <- %i/100
504         """ % self.paramsimi['alpha']
505
506         if  self.paramsimi.get('bystar',False) :
507             txt += """
508             et <- list()
509             """
510             for i,et in enumerate(self.tableau.etline) :
511                 txt+= """
512                 et[[%i]] <- c(%s)
513                 """ % (i+1, ','.join(et[1:]))
514             txt+= """
515             unetoile <- c('%s')
516             """ % ("','".join([val[0] for val in self.tableau.etline]))
517             txt += """
518             fsum <- NULL
519             rs <- rowSums(dm)
520             for (i in 1:length(unetoile)) {
521                 print(unetoile[i])
522                 tosum <- et[[i]]
523                 if (length(tosum) > 1) {
524                     fsum <- cbind(fsum, colSums(dm[tosum,]))
525                 } else {
526                     fsum <- cbind(fsum, dm[tosum,])
527                 }
528             }
529             source("%s")
530             lex <- AsLexico2(fsum, chip=TRUE)
531             dcol <- apply(lex[[4]],1,which.max)
532             toblack <- apply(lex[[4]],1,max)
533             gcol <- rainbow(length(unetoile))
534             #gcol[2] <- 'orange'
535             vertex.label.color <- gcol[dcol]
536             vertex.label.color[which(toblack <= 3.84)] <- 'black'
537             leg <- list(unetoile=unetoile, gcol=gcol)  
538             cols <- vertex.label.color
539             chivertex.size <- norm.vec(toblack, vcexminmax[1],  vcexminmax[2])
540             
541             """ % (self.parent.RscriptsPath['chdfunct'])
542         else :
543             txt += """
544             vertex.label.color <- 'black' 
545             chivertex.size <- 1
546             leg<-NULL
547             """
548         #if not self.paramsimi['keep_coord'] :
549         txt += """
550             graph.simi <- do.simi(x, method='%s', seuil = seuil, p.type = '%s', layout.type = '%s', max.tree = %s, coeff.vertex=%s, coeff.edge = %s, minmaxeff = minmaxeff, vcexminmax = vcexminmax, cex = cex, coords = coords)
551             """ % (method, type, layout, arbremax, coeff_tv, coeff_te)
552         #txt += """
553         if self.paramsimi.get('bystar',False) :
554             if self.paramsimi.get('cexfromchi', False) :
555                 txt+="""
556                     label.cex<-chivertex.size
557                     """
558             else :
559                 txt+="""
560                 label.cex <- NULL
561                 """
562             if self.paramsimi.get('sfromchi', False) :
563                 txt += """
564                 vertex.size <- norm.vec(toblack, minmaxeff[1], minmaxeff[2])
565                 """
566             else :
567                 txt += """
568                 vertex.size <- NULL
569                 """
570         else :
571             if tmpchi :
572                 txt += """
573                 lchi <- read.table("%s")
574                 lchi <- lchi[,1]
575                 """ % ffr(tmpchi)
576                 if 'selected_col' in dir(self.tableau) :
577                     txt += """
578                     lchi <- lchi[c%s+1]
579                     """ % datas
580             if tmpchi and self.paramsimi.get('cexfromchi', False) :
581                 txt += """ 
582                 label.cex <- norm.vec(lchi, vcexminmax[1], vcexminmax[2])
583                 """
584             else :
585                 txt += """
586             if (is.null(vcexminmax[1])) {
587                 label.cex <- NULL
588             } else {
589                 label.cex <- graph.simi$label.cex
590             }
591             """
592             if tmpchi and self.paramsimi.get('sfromchi', False) :
593                 txt += """ 
594                 vertex.size <- norm.vec(lchi, minmaxeff[1], minmaxeff[2])
595                 """
596             else :
597                 txt += """
598             if (is.null(minmaxeff[1])) {
599                 vertex.size <- NULL
600             } else {
601                 vertex.size <- graph.simi$eff
602             }
603             """
604         txt += """ vertex.size <- NULL """
605         txt += """
606         coords <- plot.simi(graph.simi, p.type='%s',filename="%s", vertex.label = label.v, edge.label = label.e, vertex.col = cols, vertex.label.color = vertex.label.color, vertex.label.cex=label.cex, vertex.size = vertex.size, edge.col = cola, leg=leg, width = width, height = height, alpha = alpha, movie = film)
607         save.image(file="%s")
608         """ % (type, self.filename, self.DictPathOut['RData'])
609
610         self.tmpfile = tempfile.mktemp(dir=self.parent.TEMPDIR)
611         tmpscript = open(self.tmpfile, 'w')
612         tmpscript.write(txt)
613         tmpscript.close()
614
615         if type == 'nplot':
616             if os.path.exists(self.DictPathOut['liste_graph']):
617                 graph_simi = read_list_file(self.DictPathOut['liste_graph'])
618                 graph_simi.append([os.path.basename(self.filename), self.txtgraph])
619             else :
620                 graph_simi = [[os.path.basename(self.filename), self.txtgraph]]
621             print_liste(self.DictPathOut['liste_graph'], graph_simi)
622         
623     def DoR(self, dlg):
624         if self.paramsimi['type'] == 1 :
625             graph = False
626             wait = False
627         else : 
628             graph = True
629             wait = True
630         pid = exec_rcode(self.RPath, self.tmpfile, wait = wait, graph = graph)
631         if self.paramsimi['type'] == 1 :
632             while pid.poll() == None :
633                     if not self.cmd :
634                         dlg.Pulse(u'R ...')
635                         sleep(0.2)
636                     else :
637                         sleep(0.2)
638             check_Rresult(self.parent, pid)
639     
640     def dolayout(self):
641         if os.path.exists(self.DictPathOut['liste_graph']) :
642             list_graph = read_list_file(self.DictPathOut['liste_graph'])
643         else : 
644             list_graph = [['','']]
645         notebook_flags =  aui.AUI_NB_DEFAULT_STYLE | aui.AUI_NB_TAB_EXTERNAL_MOVE | aui.AUI_NB_TAB_MOVE | aui.AUI_NB_TAB_FLOAT
646         self.tabsimi = aui.AuiNotebook(self.parent.nb, -1, wx.DefaultPosition)
647         self.tabsimi.SetAGWWindowStyleFlag(notebook_flags)
648         self.tabsimi.SetArtProvider(aui.ChromeTabArt())
649         if 'corpus' in dir(self.Source) :
650             self.tabsimi.corpus = self.Source.corpus
651         self.graphpan = GraphPanelSimi(self.tabsimi, self.DictPathOut, list_graph)
652         self.graphpan.Bind(wx.EVT_BUTTON, self.redosimi, self.graphpan.butafc)
653         self.graphpan.Bind(wx.EVT_BUTTON, self.export, self.graphpan.butexport)
654         self.tabsimi.AddPage(self.graphpan, 'Graph')
655         self.parent.nb.AddPage(self.tabsimi, 'Analyse de graph')
656         self.parent.ShowTab(True)
657         self.parent.nb.SetSelection(self.parent.nb.GetPageCount() - 1)
658
659     def export(self, evt) :
660         fileout = os.path.join(os.path.dirname(self.DictPathOut['ira']), "graphout")
661         format_graph = 'gml'
662         i=1
663         while os.path.exists(fileout + '_%i.' % i + format_graph) :
664             i += 1
665         fileout_graph = fileout + '_%i.' % i + format_graph 
666         fileout_table = fileout + '_table_%i.csv' % i
667         Rtxt = """
668         library(igraph)
669         load("%s")
670         fileout <- "%s"
671         fileout.table <- "%s"
672         format <- "%s"
673         id <- (1:length(graph.simi$mat.eff)) - 1
674         id <- paste(id, '.0', sep='')
675         table.out <- cbind(Id=id, Label=id, Name=graph.simi$v.label, labelcex=graph.simi$label.cex, eff=graph.simi$mat.eff)
676         write.graph(graph.simi$graph, fileout, format=format)
677         write.csv2(table.out, file = fileout.table, row.names=FALSE)
678         """ % (self.DictPathOut['RData'], ffr(fileout_graph), ffr(fileout_table), format_graph)
679         tmpfile = tempfile.mktemp(dir=self.parent.TEMPDIR)
680         with open(tmpfile, 'w') as f :
681             f.write(Rtxt)
682         res =  exec_rcode(self.RPath, tmpfile, wait = False)
683         check_Rresult(self.parent,res)
684         print 'export', Rtxt
685  
686     def redosimi(self,evt) :
687         if self.openfromprof :
688             if 'cexfromchi' not in self.paramsimi:
689                 self.paramsimi['cexfromchi'] = False
690                 self.paramsimi['sfromchi'] = False
691         self.dial = PrefSimi(self.parent, -1, self.paramsimi, self.types)
692         self.dial.CenterOnParent()
693         val = self.dial.ShowModal()
694         if val == wx.ID_OK :
695             self.paramsimi = self.make_param()
696             self.dial.Destroy()
697             if self.paramsimi.get('bystar',False) :
698                 variables = treat_var_mod(self.paramsimi['stars'])
699                 dial = OptLexi(self.parent)
700                 dial.listet = self.paramsimi['stars']
701                 var = [v for v in variables]
702                 dial.variables = var
703                 for et in var :
704                     dial.list_box_1.Append(et)
705                 dial.CenterOnParent()
706                 val = dial.ShowModal()
707                 if val == wx.ID_OK :
708                     if dial.choice.GetSelection() == 1 :
709                         listet = [dial.listet[i] for i in dial.list_box_1.GetSelections()]
710                     else :
711                         listet = variables[var[dial.list_box_1.GetSelections()[0]]]
712                     self.tableau.etline = self.Source.corpus.make_etline(listet)
713
714             dlg = wx.ProgressDialog("Traitements",
715                                     "Veuillez patienter...",
716                                      maximum=2,
717                                      parent=self.parent,
718                                      style=wx.PD_APP_MODAL | wx.PD_AUTO_HIDE | wx.PD_ELAPSED_TIME | wx.PD_CAN_ABORT)
719             dlg.Center()
720             self.PrintScript()
721             self.DoR(dlg)
722             dlg.Destroy()
723             self.make_ira()
724             if self.paramsimi['type'] == 1:
725                 self.graphpan.sizer_3.Add(wx.StaticBitmap(self.graphpan.panel_1, -1, wx.Bitmap(self.filename, wx.BITMAP_TYPE_ANY)), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
726                 self.graphpan.sizer_3.Add(wx.StaticText(self.graphpan.panel_1,-1,self.txtgraph), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
727                 self.graphpan.sizer_3.Fit(self.graphpan.panel_1)
728                 self.graphpan.Layout()
729                 self.graphpan.panel_1.Scroll(0,self.graphpan.panel_1.GetScrollRange(wx.VERTICAL))
730         else :
731             self.dial.Destroy()
732
733         
734 class GraphPanelSimi(wx.Panel):
735     def __init__(self,parent, dico, list_graph):
736         wx.Panel.__init__(self,parent)
737         self.afcnb = 1
738         self.Dict = dico
739         self.dirout = os.path.dirname(self.Dict['ira'])
740         self.parent = self.GetParent()#parent
741         self.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, "courier"))
742         self.labels = []
743         self.listimg = []
744         self.tabsimi = self.parent.GetParent()
745         self.ira = self.tabsimi.GetParent()
746         self.panel_1 = wx.ScrolledWindow(self, -1, style=wx.TAB_TRAVERSAL)
747         afc_img = wx.Image(os.path.join(self.ira.images_path,'button_simi.jpg'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
748         self.butafc = wx.BitmapButton(self, -1, afc_img)
749         export_img = wx.Image(os.path.join(self.ira.images_path,'button_export.jpg'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
750         self.butexport = wx.BitmapButton(self, -1, export_img)
751         
752         for i in range(0,len(list_graph)):
753             if os.path.exists(os.path.join(self.dirout,list_graph[i][0])) :
754                 self.listimg.append(wx.StaticBitmap(self.panel_1, -1, wx.Bitmap(os.path.join(self.dirout,list_graph[i][0]), wx.BITMAP_TYPE_ANY)))
755                 self.labels.append(wx.StaticText(self.panel_1, -1, list_graph[i][1]))
756                 
757         self.__set_properties()
758         self.__do_layout()
759
760     def __set_properties(self):
761         self.panel_1.EnableScrolling(True,True)
762         #self.panel_1.SetSize((1000,1000))
763         self.panel_1.SetScrollRate(20, 20)
764
765     def __do_layout(self):    
766         self.sizer_1 = wx.BoxSizer(wx.HORIZONTAL)
767         self.sizer_2 = wx.BoxSizer(wx.VERTICAL)
768         self.sizer_3 = wx.BoxSizer(wx.VERTICAL)
769         self.sizer_2.Add(self.butafc, 0, 0, 0)
770         self.sizer_2.Add(self.butexport, 0, 0, 0)
771         for i in range(0, len(self.listimg)):
772             self.sizer_3.Add(self.listimg[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
773             self.sizer_3.Add(self.labels[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
774         self.panel_1.SetSizer(self.sizer_3)
775         self.sizer_1.Add(self.sizer_2, 0, wx.EXPAND, 0)
776         self.sizer_1.Add(self.panel_1, 1, wx.EXPAND, 0)
777         self.SetSizer(self.sizer_1)