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