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