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