correction of y label in zipf graphic
[iramuteq] / layout.py
1 #!/bin/env python
2 # -*- coding: utf-8 -*-
3 #Author: Pierre Ratinaud
4 #Copyright (c) 2008-2009 Pierre Ratinaud
5 #License: GNU/GPL
6
7 import os
8 import wx
9 import wx.lib.hyperlink as hl
10 import wx.lib.agw.aui as aui
11 from chemins import ConstructPathOut, ChdTxtPathOut, FFF, ffr, PathOut, StatTxtPathOut, simipath
12 from ConfigParser import ConfigParser
13 from functions import ReadProfileAsDico, GetTxtProfile, read_list_file, ReadList, exec_rcode, print_liste, BugReport, DoConf, indices_simi, check_Rresult, progressbar
14 from ProfList import ProfListctrlPanel
15 from guiparam3d import param3d, simi3d
16 from PrintRScript import write_afc_graph, print_simi3d, PrintSimiScript
17 from profile_segment import ProfileSegment
18 from functions import ReadList
19 from listlex import *
20 from Liste import *
21 from search_tools import SearchFrame
22 from dialog import PrefGraph, PrefExport, PrefSimpleFile, PrefDendro, SimpleDialog
23 from guifunct import SelectColumn, PrepSimi, PrefSimi
24 from webexport import WebExport
25 from corpus import Corpus
26 import datetime
27 import sys
28 import tempfile
29 from time import sleep
30 import shutil
31 import codecs
32 import logging
33
34 log = logging.getLogger('iramuteq.layout')
35
36
37 class GraphPanelAfc(wx.Panel):
38     def __init__(self, parent, dico, list_graph, clnb, itempath = 'liste_graph_afc', coding = sys.getdefaultencoding()):
39         wx.Panel.__init__(self,parent)
40         self.afcnb = 1
41         self.clnb = clnb
42         self.Dict = dico
43         self.coding = coding
44         self.itempath = itempath
45         self.parent = self.GetParent()#parent
46         self.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, "Arial"))
47         self.labels = []
48         self.listimg = []
49         self.buts = []
50         self.list_graph = list_graph
51         self.TabCHD = self.parent.GetParent()
52         self.nb = self.TabCHD.GetParent()
53         self.ira = self.nb.GetParent()
54         self.panel_1 = wx.ScrolledWindow(self, -1, style=wx.TAB_TRAVERSAL)
55         afc_img = wx.Image(os.path.join(self.ira.images_path,'button_afc.jpg'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
56         self.butafc = wx.BitmapButton(self, -1, afc_img)
57         self.Bind(wx.EVT_BUTTON, self.afc_graph, self.butafc)
58         self.dirout = os.path.dirname(self.Dict['ira'])
59         b = 0
60         todel = []
61         for i in range(0,len(list_graph)):
62             if os.path.exists(os.path.join(self.dirout,list_graph[i][0])) :
63                 filename, ext = os.path.splitext(list_graph[i][0])
64                 if ext == '.svg' or ext == '.html':
65                     self.listimg.append(hl.HyperLinkCtrl(self.panel_1, -1, os.path.join(self.dirout,list_graph[i][0]), URL=os.path.join(self.dirout,list_graph[i][0])))
66                 else :
67                     self.listimg.append(wx.StaticBitmap(self.panel_1, -1, wx.Bitmap(os.path.join(self.dirout,list_graph[i][0]), wx.BITMAP_TYPE_ANY)))
68                 if os.path.exists(os.path.join(self.dirout,list_graph[i][0] + '_notplotted.csv')) :
69                     txt = _(u"List of not plotted points : ").decode('utf8') + '%s' % os.path.join(self.dirout,list_graph[i][0] + '_notplotted.csv')
70                 else :
71                     txt = ''
72                 self.labels.append(wx.StaticText(self.panel_1, -1, list_graph[i][1] + txt))
73                 self.buts.append(wx.Button(self.panel_1, wx.ID_DELETE, name = `i - b`))
74             else :
75                 todel.append(i)
76                 b += 1
77         self.list_graph = [graph for i, graph in enumerate(self.list_graph) if i not in todel]
78                 
79         self.param = { 'typegraph' : 0, 
80               'width' : 800,
81               'height' : 800,
82               'what' : 0,
83               'qui' : 0,
84               'do_select_nb' : 0,
85               'do_select_chi' : 0,
86               'do_select_chi_classe' : 0,
87               'select_nb' : 50,
88               'select_chi' : 4,
89               'nbchic' : 30,
90               'over' : 0, 
91               'cex_txt' : 0,
92               'txt_min' : 5,
93               'txt_max' : 40,
94               'tchi' : 0,
95               'tchi_min' : 5,
96               'tchi_max' : 40,
97               'taillecar' : 9,
98               'facteur' : [1,2,3],
99               'alpha' : 10,
100               'clnb' : clnb,
101               'svg' : 0,
102                }
103
104         self.__set_properties()
105         self.__do_layout()
106
107     def __set_properties(self):
108         self.panel_1.EnableScrolling(True,True)
109         #self.panel_1.SetSize((1000,1000))
110         self.panel_1.SetScrollRate(20, 20)
111         self.panel_1.SetFocus()
112
113     def __do_layout(self):    
114         self.sizer_1 = wx.BoxSizer(wx.VERTICAL)
115         self.sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
116         self.sizer_3 = wx.BoxSizer(wx.VERTICAL)
117         self.sizer_2.Add(self.butafc, 0, 0, 0)
118         for i in range(0, len(self.listimg)):
119             self.sizer_3.Add(self.listimg[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
120             self.sizer_3.Add(self.labels[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
121             self.sizer_3.Add(self.buts[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
122             self.Bind(wx.EVT_BUTTON, self.on_delete_image, self.buts[i])
123         self.panel_1.SetSizer(self.sizer_3)
124         self.sizer_2.Add(self.panel_1, 1, wx.EXPAND, 0)
125         self.SetSizer(self.sizer_2) 
126
127     def on_delete_image(self, event) :
128         image_id = int(event.GetEventObject().GetName())
129         image_path = self.list_graph[image_id][0]
130         message = _(u'This file will be delete : ') + '%s.\n' % os.path.join(self.dirout, image_path) + _('Are you sure ?')
131         dial = wx.MessageDialog(self, message, style = wx.YES_NO)
132         res = dial.ShowModal()
133         if res == wx.ID_YES :
134             dial.Destroy()
135             log.info('delete image %i' % image_id)
136             oldimg = self.listimg.pop(image_id)
137             oldimg.Destroy()
138             oldlab = self.labels.pop(image_id)
139             oldlab.Destroy()
140             oldbut = self.buts.pop(image_id)
141             oldbut.Show(False)
142             for i, but in enumerate(self.buts) :
143                 but.SetName(`i`)
144             todel = self.list_graph.pop(image_id)
145             os.remove(os.path.join(self.dirout, todel[0]))
146             print_liste(self.Dict[self.itempath], self.list_graph)
147             self.sizer_3.Fit(self.panel_1)
148             self.Layout()
149         else :
150             dial.Destroy()
151         
152
153     def afc_graph(self,event):
154         #dirout = os.path.dirname(self.Dict['ira'])
155         dial = PrefGraph(self.parent,-1,self.param,'')
156         dial.CenterOnParent()
157         val = dial.ShowModal()
158         if val == wx.ID_OK :
159             if dial.choix_format.GetSelection() == 0 :
160                 svg = 0
161             else :
162                 svg = 1
163             typegraph = dial.choicetype.GetSelection()
164             typefile = '.png'
165             if self.clnb <= 3 and typegraph == 1 :
166                 typegraph = 2
167             if typegraph == 2:
168                 typefile = '.gexf'
169             while os.path.exists(os.path.join(self.dirout,'graph_afc_'+str(self.afcnb)+typefile)):
170                 self.afcnb +=1
171             self.fileout = ffr(os.path.join(self.dirout,'graph_afc_'+str(self.afcnb)+typefile))
172
173             self.param = {'typegraph' : typegraph,
174                           'width' : dial.spin1.GetValue(),
175                           'height' : dial.spin2.GetValue(),
176                           'what' : dial.choice1.GetSelection(),
177                           'qui' : dial.choice2.GetSelection(),
178                           'do_select_nb' : dial.check1.GetValue(),
179                           'do_select_chi' : dial.check2.GetValue(),
180                           'do_select_chi_classe' : dial.check_chic.GetValue(),
181                           'select_nb' : dial.spin_nb.GetValue(),
182                           'select_chi' : dial.spin_chi.GetValue(),
183                           'nbchic' : dial.spin_nbchic.GetValue(),
184                           'over' : dial.check3.GetValue(), 
185                           'cex_txt' : dial.check4.GetValue(),
186                           'txt_min' : dial.spin_min.GetValue(),
187                           'txt_max' : dial.spin_max.GetValue(),
188                           'tchi' : dial.check_tchi.GetValue(),
189                           'tchi_min' : dial.spin_min_tchi.GetValue(),
190                           'tchi_max' : dial.spin_max_tchi.GetValue(),
191                           'taillecar' : dial.spin3.GetValue(),
192                           'facteur' : [dial.spin_f1.GetValue(),dial.spin_f2.GetValue(), dial.spin_f3.GetValue()],
193                           'clnb' : self.clnb,
194                           'film' : str(dial.film.GetValue()).upper(),
195                           'alpha' : dial.slider_sphere.GetValue(),
196                           'svg' : svg
197                         }
198             self.nb.parent = self.ira
199             self.DictPathOut = self.Dict
200             self.RscriptsPath = self.ira.RscriptsPath
201             txt = """
202             load("%s")
203             """ % self.DictPathOut['RData']
204             if self.itempath == 'liste_graph_afcf' :
205                 txt += """
206                 afc <- afcf
207                 afc_table <- afcf_table
208                 chistabletot <- specfp
209                 """ 
210             elif self.itempath == 'liste_graph_afct' :
211                 txt +="""
212                 afc <- afct
213                 afc_table <- afct_table
214                 chistabletot <- spectp
215                 """
216             txt += write_afc_graph(self)
217             filetmp = tempfile.mktemp()
218             with open(filetmp, 'w') as f :
219                 f.write(txt)
220             pid = exec_rcode(self.ira.RPath, filetmp)
221             check_Rresult(self.ira, pid)
222             if self.param['typegraph'] in [0,2] :
223                 txt = 'Variables '
224                 if self.param['qui'] == 0 : value = u'actives'
225                 if self.param['qui'] == 1 : value = u'supplémentaires'
226                 if self.param['qui'] == 2 : value = u'étoilées'
227                 if self.param['qui'] == 3 : value = u'classes'
228                 txt += value + ' - '
229                 if self.param['what'] == 0 : value = u'Coordonnées'
230                 if self.param['what'] == 1 : value = u'Corrélations'
231                 txt += value + u' - facteur %i / %i' % (self.param['facteur'][0], self.param['facteur'][1])
232                 if self.param['do_select_nb'] : txt += u' - sélection de %i variables' % self.param['select_nb']
233                 if self.param['do_select_chi'] : txt += u' - sélection des variables avec chi2 > %i ' % self.param['select_chi']
234                 if self.param['over'] : txt += u' - Eviter les recouvrements'
235                 if self.param['cex_txt'] : txt += u' - taille du texte proportionnel Ã  la masse'
236                 if self.param['tchi'] : txt += u' - taille du texte proportionnel au chi2 d\'association'
237                 #list_graph = read_list_file(self.DictPathOut[self.itempath], self.coding)
238                 if self.param['svg'] :
239                     filename, ext = os.path.splitext(self.fileout)
240                     self.fileout = filename + '.svg'
241                 if self.param['typegraph'] == 2 :
242                     parametres = {'gexffile' :  self.fileout,
243                                   'titre': 'Le titre',
244                                   'nodemin': self.param['txt_min'],
245                                   'nodemax': self.param['txt_max'],
246                                   'bargraphw' : 60*int(self.param['clnb']),
247                     }
248                     web = WebExport(self.ira, parametres)
249                     self.fileout = web.exportafc()              
250                 self.list_graph.append([os.path.basename(self.fileout), txt])
251                 print_liste(self.DictPathOut[self.itempath], self.list_graph)
252                 if self.param['svg'] or self.param['typegraph'] == 2:
253                     self.listimg.append(hl.HyperLinkCtrl(self.panel_1, -1, self.fileout, URL=self.fileout))
254
255                 else :
256                     self.listimg.append(wx.StaticBitmap(self.panel_1, -1, wx.Bitmap(self.fileout, wx.BITMAP_TYPE_ANY)))
257                 self.sizer_3.Add( self.listimg[-1], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
258                 self.labels.append(wx.StaticText(self.panel_1,-1, txt))
259                 self.sizer_3.Add(self.labels[-1], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
260                 self.buts.append(wx.Button(self.panel_1, wx.ID_DELETE, name = `len(self.list_graph) - 1`))
261                 self.sizer_3.Add(self.buts[-1], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
262                 self.sizer_3.Fit(self.panel_1)
263                 self.Layout()
264     
265                 self.panel_1.Scroll(0,self.panel_1.GetScrollRange(wx.VERTICAL))
266 #             elif self.param['typegraph'] == 2 :
267 #                 parametres = {'gexffile' :  self.fileout,
268 #                               'titre': 'Le titre',
269 #                               'nodemin': self.param['txt_min'],
270 #                               'nodemax': self.param['txt_max'],
271 #                               'bargraphw' : 60*int(self.param['clnb']),
272 #                 }
273 #                 web = WebExport(self.ira, parametres)
274 #                 afcout = web.exportafc()
275 #                 dial = SimpleDialog(self.ira) 
276 #                 dial.link.SetLabel(afcout)
277 #                 dial.link.SetURL(afcout)
278 #                 dial.Layout()
279 #                 dial.ShowModal()
280             
281
282 class GraphPanel(wx.ScrolledWindow):
283     def __init__(self, parent, dico, list_graph, txt = '', style = wx.TAB_TRAVERSAL):
284         wx.ScrolledWindow.__init__(self, parent, style = style)
285         self.Dict = dico
286         self.txt = txt
287         self.parent = parent
288         self.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, "Arial"))
289         self.labels = []
290         self.listimg = []
291         self.dirout = os.path.dirname(self.Dict['ira'])
292         self.deb = wx.StaticText(self, -1, txt)
293         for i in range(0,len(list_graph)):
294             if os.path.exists(os.path.join(self.dirout,list_graph[i][0])) :
295                 filename, ext = os.path.splitext(list_graph[i][0])
296                 if ext == '.svg' :
297                     self.listimg.append(hl.HyperLinkCtrl(self, -1, os.path.join(self.dirout,list_graph[i][0]), URL=os.path.join(self.dirout,list_graph[i][0])))
298                 else :
299                     self.listimg.append(wx.StaticBitmap(self, -1, wx.Bitmap(os.path.join(self.dirout,list_graph[i][0]), wx.BITMAP_TYPE_ANY)))
300                 self.labels.append(wx.StaticText(self, -1, list_graph[i][1]))
301         self.Bind(wx.EVT_MOTION, self.onMouseMove) 
302         self.__set_properties()
303         self.__do_layout()
304
305     def __set_properties(self):
306         self.EnableScrolling(True,True)
307         self.SetScrollRate(20, 20)   
308         self.SetFocus()
309
310
311     def __do_layout(self):
312         self.sizer_1 = wx.BoxSizer(wx.VERTICAL)
313         self.sizer_2 = wx.BoxSizer(wx.VERTICAL)
314         self.sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
315         self.sizer_1.Add(self.deb)   
316         for i in range(0, len(self.listimg)):
317             self.sizer_1.Add(self.listimg[i], 1, wx.ALIGN_CENTER_HORIZONTAL, 0)
318             self.sizer_1.Add(self.labels[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
319         self.sizer_2.Add(self.sizer_1, 1, wx.EXPAND, 0)
320         self.SetSizer(self.sizer_1)
321         self.sizer_1.Fit(self)
322
323     def onMouseMove(self, event):
324         self.SetFocus()
325        
326
327 def open_antiprofil(panel, AntiProfile, encoding) :
328     DictAnti = ReadProfileAsDico(AntiProfile, True, encoding)
329     panel.AntiProfNB = aui.AuiNotebook(panel, -1, wx.DefaultPosition)
330     for i in range(0, panel.parametres['clnb']):
331         tabantiprofile = ProfListctrlPanel(panel, panel, DictAnti[str(i + 1)], True, i + 1)
332         panel.AntiProfNB.AddPage(tabantiprofile, 'classe %s' % str(i + 1))
333     panel.TabChdSim.AddPage(panel.AntiProfNB, _(u"Antiprofiles").decode('utf8'))
334
335
336
337 def getlemgram(corpus, lem) :
338     if not lem[6] in corpus.lems :
339         return lem[5]
340     else :
341         return corpus.lems[lem[6]].gram
342
343 class OpenCHDS():
344     def __init__(self, parent, corpus, parametres, Alceste=False):
345         #sep = u'\n ' 
346         sep=' '
347         self.parent = parent
348         self.corpus = corpus
349         self.parametres = parametres
350         self.pathout = PathOut(parametres['ira'])
351         self.pathout.basefiles(ChdTxtPathOut)
352         DictPathOut = self.pathout 
353         self.DictPathOut = DictPathOut
354         self.dictpathout = DictPathOut
355         self.parent = parent
356
357         Profile = DictPathOut['PROFILE_OUT']
358         AntiProfile = DictPathOut['ANTIPRO_OUT']
359         self.encoding = self.parametres['encoding']
360         if isinstance(self.corpus, Corpus) :
361             self.corpus.make_ucecl_from_R(self.pathout['uce'])
362             corpname = self.corpus.parametres['corpus_name']
363         else :
364             corpname = self.corpus.parametres['name']
365
366         clnb = parametres['clnb']
367         dlg = progressbar(self, maxi = 4 + clnb) 
368         self.clnb = clnb 
369         print 'lecture des profils'
370         dlg.Update(2, _(u"Reading profiles").decode('utf8'))
371   
372         DictProfile = ReadProfileAsDico(Profile, Alceste, self.encoding)
373         self.DictProfile = DictProfile
374         self.cluster_size = []
375         #print 'lecture des antiprofils'
376         #DictAnti = ReadProfileAsDico(self, AntiProfile, Alceste, self.encoding)
377
378         panel = wx.Panel(parent, -1)
379         sizer1 = wx.BoxSizer(wx.VERTICAL)
380
381         if os.path.exists(DictPathOut['pre_rapport']):
382             with codecs.open(DictPathOut['pre_rapport'], 'r', self.encoding) as f :
383                 txt = f.read()
384             self.debtext = txt
385         else :
386             self.debtext = ''
387 #       panel.chd_toolbar = wx.ToolBar(panel, -1, wx.DefaultPosition, wx.DefaultSize, wx.TB_FLAT | wx.TB_NODIVIDER)
388 #       panel.chd_toolbar.SetToolBitmapSize(wx.Size(16, 16))
389
390         if isinstance(self.corpus, Corpus) :
391             panel.corpus = self.corpus
392         else :
393             panel.tableau = self.corpus
394             #self.parent.tableau = panel.tableau
395         panel.dictpathout = self.DictPathOut
396         panel.pathout = self.DictPathOut
397         panel.parent = self.parent
398         panel.DictProfile = self.DictProfile
399         panel.cluster_size = self.cluster_size
400         panel.debtext = self.debtext
401
402 #       self.ID_rapport = wx.NewId()
403 #       #rap_img = wx.Image(os.path.join(self.parent.images_path,'icone_rap_16.png'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
404 #       #panel.chd_toolbar.AddLabelTool(self.ID_rapport, "rapport", rap_img, shortHelp=u"Produire le rapport", longHelp=u"Exporter un rapport en texte simple")
405 #       butrap = wx.Button(panel.chd_toolbar, self.ID_rapport, u"Rapport ")
406 #       panel.chd_toolbar.AddControl(butrap)
407 #       
408 #       panel.chd_toolbar.Realize()
409 #       sizer1.Add(panel.chd_toolbar,0, wx.EXPAND, 5)
410
411         #self.TabChdSim = wx.aui.AuiNotebook(self.parent.nb, -1, wx.DefaultPosition)
412         notebook_flags =  aui.AUI_NB_DEFAULT_STYLE | aui.AUI_NB_TAB_EXTERNAL_MOVE | aui.AUI_NB_TAB_MOVE | aui.AUI_NB_TAB_FLOAT| wx.NO_BORDER
413         panel.TabChdSim = aui.AuiNotebook(panel, -1, wx.DefaultPosition)
414         panel.TabChdSim.SetAGWWindowStyleFlag(notebook_flags)
415         panel.TabChdSim.SetArtProvider(aui.ChromeTabArt())
416         sizer1.Add(panel.TabChdSim,10, wx.EXPAND, 5)
417         panel.SetSizer(sizer1)
418         sizer1.Fit(panel)
419        
420
421         if isinstance(self.corpus, Corpus) :
422             panel.TabChdSim.corpus = corpus
423             panel.TabChdSim.corpus.dictpathout = self.DictPathOut
424         else :
425             panel.TabChdSim.tableau = corpus
426             panel.TabChdSim.tableau.dictpathout = self.DictPathOut
427         panel.parametres = self.parametres
428         self.panel = panel
429
430         self.notenb = self.parent.nb.GetPageCount()
431
432            
433         if os.path.exists(self.DictPathOut['liste_graph_chd']) :
434             list_graph = read_list_file(self.DictPathOut['liste_graph_chd'], self.encoding)
435             CHD = GraphPanelDendro(panel.TabChdSim, DictPathOut, list_graph, txt = self.debtext)
436             panel.TabChdSim.AddPage(CHD,'CHD')
437                
438         panel.ProfNB = aui.AuiNotebook(panel, -1, wx.DefaultPosition)
439         panel.ProfNB.SetArtProvider(aui.ChromeTabArt())
440         #self.ProfNB.SetTabCtrlHeight(100)
441         #panel.AntiProfNB = aui.AuiNotebook(panel, -1, wx.DefaultPosition)
442         if os.path.exists(DictPathOut['prof_seg']) :
443             prof_seg = ReadProfileAsDico(DictPathOut['prof_seg'], False, self.encoding)
444             self.prof_seg_nb = aui.AuiNotebook(panel, -1, wx.DefaultPosition)
445         for i in range(0, clnb):
446             self.cluster_size.append(DictProfile[str(i + 1)][0][0:3])
447             if isinstance(self.corpus, Corpus) :
448                 DictProfile[str(i + 1)][1:] = [val[0:5] + [getlemgram(self.corpus, val)] + val[6:] for val in DictProfile[str(i + 1)][1:]]
449             dlg.Update(3+i, 'Classe %i' %(i+1))
450             ind = '/'.join(DictProfile[str(i + 1)][0][0:2])
451             indpour = ' - '.join([ind, DictProfile[str(i + 1)][0][2]])
452             self.tabprofile = ProfListctrlPanel(self.parent, self.panel, DictProfile[str(i + 1)], Alceste, i + 1)
453             #self.tabantiprofile = ProfListctrlPanel(self.parent, self, DictAnti[str(i + 1)], Alceste, i + 1)
454             panel.ProfNB.AddPage(self.tabprofile, _(u"Cluster").decode('utf8') + ' %s %s(%s%%)' % (str(i + 1), sep, indpour))
455             #panel.AntiProfNB.AddPage(self.tabantiprofile, 'classe %s' % str(i + 1))
456             if os.path.exists(DictPathOut['prof_seg']) :
457                 self.tab_prof_seg = ProfListctrlPanel(self.parent, self, prof_seg[str(i + 1)], False, i + 1)
458                 self.prof_seg_nb.AddPage(self.tab_prof_seg, _(u"Cluster").decode('utf8') + ' %i' % (i + 1))
459
460         if clnb > 2 :
461             self.TabAFC = aui.AuiNotebook(panel.TabChdSim, -1, wx.DefaultPosition)
462             log.info('read AFC') 
463             list_graph=read_list_file(DictPathOut['liste_graph_afc'], self.encoding)
464             self.tabAFCGraph = GraphPanelAfc(self.TabAFC, DictPathOut, list_graph, self.clnb, coding=self.encoding)
465             self.TabAFC.AddPage(self.tabAFCGraph, _(u"CA").decode('utf8'))
466             
467             if os.path.exists(self.DictPathOut['afc_facteur']) :
468                 dictrow, first = ReadList(self.DictPathOut['afc_facteur'], self.encoding)
469                 self.TabAFC_facteur = ListForSpec(self.parent, parametres, dictrow, first)
470                 #dictrow, first = ReadList(self.DictPathOut['afc_row'], self.encoding)
471                 #self.TabAFC_ligne = ListForSpec(self.parent, self.parametres, dictrow, first)
472                 #dictrow, first = ReadList(self.DictPathOut['afc_col'], self.encoding)
473                 #self.TabAFC_colonne = ListForSpec(parent, self.parametres, dictrow, first)
474                 self.TabAFC.AddPage(self.TabAFC_facteur, _(u"Factor").decode('utf8'))
475                 #self.TabAFC.AddPage(self.TabAFC_colonne, u'Colonnes')
476                 #self.TabAFC.AddPage(self.TabAFC_ligne, u'Lignes')
477             
478             sizer_3 = wx.BoxSizer(wx.VERTICAL)
479             self.parent.nb_panel_2 = wx.Panel(panel.TabChdSim, -1)
480             self.parent.button_simi = wx.Button(self.parent.nb_panel_2, -1, "Voyager")
481             self.parent.simi3dpanel = simi3d(self.parent.nb_panel_2, -1)
482             sizer_3.Add(self.parent.simi3dpanel, 1, wx.EXPAND, 0)
483             sizer_3.Add(self.parent.button_simi, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
484             self.parent.nb_panel_2.SetSizer(sizer_3)
485             self.TabAFC.AddPage(self.parent.nb_panel_2, _(u"3D graph").decode('utf8'))
486             self.parent.Bind(wx.EVT_BUTTON, self.onsimi, self.parent.button_simi)
487               
488         panel.TabChdSim.AddPage(panel.ProfNB, _(u"Profiles").decode('utf8'))
489         #panel.TabChdSim.AddPage(panel.AntiProfNB, 'Antiprofils')
490         dlg.Update(4 + self.clnb, 'Affichage...')
491         if clnb > 2 :
492             panel.TabChdSim.AddPage(self.TabAFC, _(u"CA").decode('utf8'))
493         if os.path.exists(DictPathOut['prof_seg']) :
494             panel.TabChdSim.AddPage(self.prof_seg_nb, _(u"Repeated segments profiles").decode('utf8'))
495   
496 #       panel.Bind(wx.EVT_BUTTON, self.ongetrapport, id = self.ID_rapport)
497         self.parent.nb.AddPage(panel, _(u"Clustering").decode('utf8') + ' - %s' % corpname)
498         self.parent.ShowTab(True)
499         self.parent.nb.SetSelection(self.parent.nb.GetPageCount() - 1)     
500         #for pane in self.parent._mgr.GetAllPanes() :
501         #     if isinstance(pane.window, aui.AuiNotebook):
502         #         nb = pane.window
503         #         nb.SetAGWWindowStyleFlag(notebook_flags)
504         #         nb.SetArtProvider(aui.ChromeTabArt())
505         dlg.Destroy() 
506         self.parent._mgr.Update()
507         
508     def onsimi(self,event):
509         outfile = print_simi3d(self)
510         error = exec_rcode(self.parent.RPath, outfile, wait = True)
511
512     def onclusterstat(self, evt) :
513         dial = PrefSimpleFile(self, self.parent, **{'mask' : '*.csv', 'title': 'Stat par classe'})
514         dial.fbb.SetValue( os.path.join(os.path.dirname(self.corpus.dictpathout['ira']), 'stat_par_classe.csv'))
515         dial.CenterOnParent()
516         res = dial.ShowModal()
517         if res == wx.ID_OK :
518             fileout = dial.fbb.GetValue()
519             dial.Destroy()
520             self.corpus.get_stat_by_cluster(fileout)
521             msg = u"Fini !"
522             dlg = wx.MessageDialog(self.parent, msg, _(u"Stat by cluster").decode('utf8'), wx.OK | wx.NO_DEFAULT | wx.ICON_INFORMATION)
523             dlg.CenterOnParent()
524             if dlg.ShowModal() == wx.ID_OK :
525                 dlg.Destroy()
526
527     #def onsearchf(self, evt) :
528     #    if 'FrameSearch' not in dir(self.panel) :
529     #        self.panel.FrameSearch = SearchFrame(self.parent, -1, u"Rechercher...", self.corpus)
530     #    self.panel.FrameSearch.Show()
531
532 def PrintRapport(self, corpus, parametres, istxt = True):
533     sep = '\n'
534     txt = """
535 +-+-+-+-+-+-+-+-+
536 |i|R|a|M|u|T|e|Q| - %s
537 +-+-+-+-+-+-+-+-+
538
539
540 """ % datetime.datetime.now().ctime()
541     if istxt :
542         totocc = corpus.gettotocc()
543         txt += u'nombre de textes: %i%s' % (corpus.getucinb(), sep)
544         txt += u'nombre de segments de textes: %i%s' % (corpus.getucenb(), sep)
545         txt += u'nombre de formes: %i%s' % (len(corpus.formes), sep)
546         txt += u'nombre d\'occurrences: %i%s' % (totocc, sep)
547         txt += u'moyenne d\'occurrences par forme: %f%s' % (float(totocc) / float(len(self.corpus.formes)), sep)
548         txt += u'nombre de lemmes: %i%s' % (len(corpus.lems), sep)
549         txt += u'nombre de formes actives: %i%s' % (corpus.getactivesnb(1), sep)
550         txt += u'nombre de formes supplémentaires: %i%s' % (corpus.getactivesnb(2), sep)
551         txt += u'nombre de formes actives de fréquence >= %i: %i%s' % (parametres['eff_min_forme'], parametres['nbactives'], sep)
552         txt += u'moyenne d\'occurrences par segments :%f%s' % (float(totocc) / float(corpus.getucenb()), sep)
553         if 'tailleuc1' in parametres :
554             if parametres['classif_mode'] == 0 :
555                 txt += u'taille rst1 / rst2: %i / %i - %i / %i%s' % (parametres['tailleuc1'], parametres['tailleuc2'], parametres['lenuc1'], parametres['lenuc2'], sep)
556     else :
557         self.Ucenb = self.nbind
558         txt += u'nombre d\'individus : %i%s' % (self.nbind, sep)
559         txt += u'nombre de classes : %i%s' % (self.clnb, sep)
560     if istxt :
561         txt += u'nombre de classes : %i%s' % (parametres['clnb'], sep)
562         if parametres['classif_mode'] == 0 or parametres['classif_mode'] == 1 :
563             txt += u'%i segments classés sur %i (%.2f%%)%s' % (sum([len(cl) for cl in corpus.lc]), corpus.getucenb(), (float(sum([len(cl) for cl in corpus.lc])) / float(corpus.getucenb())) * 100, sep)
564         elif self.parametres['classif_mode'] == 2 :
565             txt += u'%i textes classés sur %i (%.2f%%)%s' % (sum([len(cl) for cl in corpus.lc]), corpus.getucinb(), (float(sum([len(cl) for cl in corpus.lc]))) / float(corpus.getucinb()) * 100, sep)
566     else :
567         txt += u'%i segments classées sur %i (%.2f%%)%s' % (self.ucecla, self.Ucenb, (float(self.ucecla) / float(self.Ucenb)) * 100, sep)
568  
569     txt += """
570 ###########################
571 temps d'analyse : %s
572 ###########################
573 """ % parametres.get('time', '')
574     with open(self.pathout['pre_rapport'], 'w') as f :
575         f.write(txt)
576
577
578 class SashList(wx.Panel) :
579     def __init__(self, parent) :
580         wx.Panel.__init__(self, parent, -1)
581         self.parent=parent
582         winids = []
583         #self.gparent=gparent
584         #self.dlist=dlist
585         #self.first = first
586         #self.menu = menu        
587         # A window to the left of the client window
588         #self.listlex = listlex
589         self.leftwin1 =  wx.SashLayoutWindow(
590                 self, -1, wx.DefaultPosition, (200, 300), 
591                 wx.NO_BORDER|wx.SW_3D
592                 )
593
594         self.leftwin1.SetDefaultSize((120, 1000))
595         self.leftwin1.SetOrientation(wx.LAYOUT_VERTICAL)
596         self.leftwin1.SetAlignment(wx.LAYOUT_LEFT)
597         self.leftwin1.SetBackgroundColour(wx.Colour(0, 255, 0))
598         self.leftwin1.SetSashVisible(wx.SASH_RIGHT, True)
599         self.leftwin1.SetExtraBorderSize(10)
600         
601         #textWindow = wx.TextCtrl(
602         #                leftwin1, -1, "", wx.DefaultPosition, wx.DefaultSize, 
603         #                wx.TE_MULTILINE|wx.SUNKEN_BORDER
604         #                )
605
606         #textWindow.SetValue("A sub window")
607
608         self.leftWindow1 = self.leftwin1
609         winids.append(self.leftwin1.GetId())
610         
611         rightwin1 =  wx.SashLayoutWindow(
612                 self, -1, wx.DefaultPosition, (200, 300), 
613                 wx.NO_BORDER|wx.SW_3D
614                 )
615
616         rightwin1.SetDefaultSize((120, 1000))
617         rightwin1.SetOrientation(wx.LAYOUT_VERTICAL)
618         rightwin1.SetAlignment(wx.LAYOUT_LEFT)
619         rightwin1.SetBackgroundColour(wx.Colour(0, 255, 0))
620         rightwin1.SetSashVisible(wx.SASH_RIGHT, True)
621         rightwin1.SetExtraBorderSize(10)
622         #textWindow = wx.TextCtrl(
623         #                leftwin1, -1, "", wx.DefaultPosition, wx.DefaultSize, 
624         #                wx.TE_MULTILINE|wx.SUNKEN_BORDER
625         #                )
626
627         #textWindow.SetValue("A sub window")
628
629         self.rightwin1 = rightwin1
630         winids.append(rightwin1.GetId())
631
632
633
634 class dolexlayout :
635     def __init__(self, ira, corpus, parametres):
636         self.pathout = PathOut(dirout = parametres['pathout'])
637         self.corpus = corpus
638         self.dictpathout = StatTxtPathOut(parametres['pathout'])
639         #self.corpus.read_corpus_from_shelves(self.corpus.dictpathout['db'])
640         self.parent = ira
641         self.encoding = self.corpus.parametres['syscoding']
642         self.parametres = parametres
643
644         self.DictSpec, first = ReadList(self.dictpathout['tablespecf'], self.corpus.parametres['syscoding'])
645         if os.path.exists(self.pathout['banalites.csv']) :
646             self.dictban, firstban = ReadList(self.pathout['banalites.csv'], self.corpus.parametres['syscoding'])
647         self.DictType, firstt = ReadList(self.dictpathout['tablespect'], self.corpus.parametres['syscoding'])
648         self.DictEff, firsteff = ReadList(self.dictpathout['tableafcm'], self.corpus.parametres['syscoding'])
649         self.DictEffType, firstefft = ReadList(self.dictpathout['tabletypem'], self.corpus.parametres['syscoding'])
650         self.DictEffRelForme, firsteffrelf = ReadList(self.dictpathout['eff_relatif_forme'], self.corpus.parametres['syscoding']) 
651         self.DictEffRelType, firsteffrelt = ReadList(self.dictpathout['eff_relatif_type'], self.corpus.parametres['syscoding'])    
652         
653         #sash = SashList(ira.nb)
654         
655         
656         self.TabStat = aui.AuiNotebook(ira.nb, -1, wx.DefaultPosition)
657         self.TabStat.parametres = parametres
658         self.ListPan = ListForSpec(ira, self, self.DictSpec, first)
659         if os.path.exists(self.pathout['banalites.csv']) :
660             self.listban = ListForSpec(ira, self, self.dictban, firstban)
661         #self.ListPan2 = ListForSpec(sash.rightwin1, self, self.DictSpec, first)
662         self.ListPant = ListForSpec(ira, self, self.DictType, firstt)
663         self.ListPanEff = ListForSpec(ira, self, self.DictEff, firsteff)
664         self.ListPanEffType = ListForSpec(ira, self, self.DictEffType, firstefft)
665         self.ListPanEffRelForme = ListForSpec(ira, self, self.DictEffRelForme, firsteffrelf)
666         self.ListPanEffRelType = ListForSpec(ira, self.parent, self.DictEffRelType, firsteffrelt)
667         
668         self.TabStat.AddPage(self.ListPan, u'formes') 
669         if os.path.exists(self.pathout['banalites.csv']) :
670             self.TabStat.AddPage(self.listban, u'banalités')
671         self.TabStat.AddPage(self.ListPant, u'Types')
672         self.TabStat.AddPage(self.ListPanEff, u'Effectifs formes')
673         self.TabStat.AddPage(self.ListPanEffType, u'Effectifs Type')
674         self.TabStat.AddPage(self.ListPanEffRelForme, u'Effectifs relatifs formes')
675         self.TabStat.AddPage(self.ListPanEffRelType, u'Effectifs relatifs Type')
676         if self.parametres['clnb'] > 2 :
677             self.TabAFC = aui.AuiNotebook(self.TabStat, -1, wx.DefaultPosition)
678             list_graph=read_list_file(self.dictpathout['liste_graph_afcf'], encoding = self.encoding)
679             self.tabAFCGraph = GraphPanelAfc(self.TabAFC, self.dictpathout, list_graph, self.parametres['clnb'], itempath ='liste_graph_afcf', coding = self.encoding)
680             self.TabAFC.AddPage(self.tabAFCGraph, 'AFC formes')
681             list_graph=read_list_file(self.dictpathout['liste_graph_afct'], encoding = self.encoding)
682             self.tabAFCTGraph = GraphPanelAfc(self.TabAFC, self.dictpathout, list_graph, self.parametres['clnb'], itempath ='liste_graph_afct', coding=self.encoding)
683             self.TabAFC.AddPage(self.tabAFCTGraph, 'AFC type')
684             self.TabStat.AddPage(self.TabAFC, 'AFC')
685            
686         
687         ira.nb.AddPage(self.TabStat, u'Spécificités')
688         
689         self.TabStat.corpus = self.corpus
690         ira.nb.SetSelection(self.parent.nb.GetPageCount() - 1)
691         ira.ShowAPane("Tab_content")
692
693 class StatLayout:
694     def __init__(self, ira, corpus, parametres):
695         self.pathout = PathOut(dirout = parametres['pathout'])
696         self.corpus = corpus
697         self.ira = ira
698         self.read_result()
699         self.TabStat = aui.AuiNotebook(ira.nb, -1, wx.DefaultPosition)
700         self.TabStat.parametres = parametres
701         self.TabStat.corpus = corpus
702         self.TabStat.pathout = self.pathout
703 #        CHD = GraphPanel(panel.TabChdSim, DictPathOut, list_graph, txt = self.debtext)
704         #      panel.TabChdSim.AddPage(CHD,'CHD')
705
706         #self.TabStatTot = wx.TextCtrl(self.TabStat, -1, style=wx.NO_BORDER | wx.TE_MULTILINE | wx.TE_RICH2)
707         list_graph = [['zipf.png', 'zipf']]
708         self.TabStatTot = GraphPanel(ira.nb, self.pathout, list_graph, self.result['glob'])
709         self.TabStat.AddPage(self.TabStatTot, 'global')
710         for item in self.result:
711             if item != 'glob':
712                 datam = [['forme', 'nb']]
713                 self.ListPan = ListPanel(ira, self, self.result[item])
714                 self.TabStat.AddPage(self.ListPan, ' '.join(item.split('_'))) 
715         ira.nb.AddPage(self.TabStat, '%s' % parametres['name'])
716         ira.nb.SetSelection(ira.nb.GetPageCount() - 1)
717         ira.ShowAPane("Tab_content")
718
719     def read_result(self) :
720         lcle = {'total' :u'total.csv', u'formes_actives':u'formes_actives.csv', u'formes_supplémentaires':u'formes_supplémentaires.csv', u'hapax': u'hapax.csv'}
721         self.result = {}
722         for key in lcle :
723             with open(self.pathout[lcle[key]], 'r') as f :
724                 self.result[key] = [line.split(';') for line in f.read().splitlines()]
725                 self.result[key] = dict([[i,[line[0],int(line[1]), line[2]]] for i, line in enumerate(self.result[key])])
726         with open(self.pathout['glob.txt'], 'r') as f :
727             self.result['glob'] = f.read()
728
729 class GraphPanelDendro(wx.Panel):
730     def __init__(self,parent, dico, list_graph, txt=False):
731         wx.Panel.__init__(self,parent)
732         self.graphnb = 1
733         self.dictpathout = dico
734         self.dirout = os.path.dirname(self.dictpathout['ira'])
735         self.list_graph = list_graph
736         self.parent = self.GetParent()#parent
737         self.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, "Arial"))
738         self.labels = []
739         self.listimg = []
740         self.tabchd = self.parent.GetParent()
741         self.ira = self.tabchd.GetParent()
742         self.panel_1 = wx.ScrolledWindow(self, -1, style=wx.TAB_TRAVERSAL)
743         self.panel_1.SetBackgroundColour('white')
744         self.deb = wx.StaticText(self.panel_1, -1, txt)
745         dendro_img = wx.Image(os.path.join(self.ira.images_path,'but_dendro.png'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
746         self.butdendro = wx.BitmapButton(self, -1, dendro_img)
747         self.butdendrotexte = wx.BitmapButton(self, -1, dendro_img)
748         self.butdendrocloud = wx.BitmapButton(self, -1, dendro_img)
749         
750         for i in range(0,len(list_graph)):
751             if os.path.exists(os.path.join(self.dirout,list_graph[i][0])) :
752                 self.listimg.append(wx.StaticBitmap(self.panel_1, -1, wx.Bitmap(os.path.join(self.dirout,list_graph[i][0]), wx.BITMAP_TYPE_ANY)))
753                 self.labels.append(wx.StaticText(self.panel_1, -1, list_graph[i][1]))
754                 
755         self.__set_properties()
756         self.__do_layout()
757
758     def __set_properties(self):
759         self.panel_1.EnableScrolling(True,True)
760         #self.panel_1.SetSize((1000,1000))
761         self.panel_1.SetScrollRate(20, 20)
762         self.panel_1.SetFocus()
763         self.Bind(wx.EVT_BUTTON, self.ondendro, self.butdendro)
764         self.Bind(wx.EVT_BUTTON, self.ondendrotexte, self.butdendrotexte)
765         self.Bind(wx.EVT_BUTTON, self.ondendrocloud, self.butdendrocloud)
766         self.param = {'width' : 700,
767                        'height': 500,
768                        'type_dendro': 0,
769                        'color_nb': 0,
770                        'taille_classe' : True,
771                        'type_tclasse' : 0
772                      }
773         self.type_dendro = [ u"phylogram", u"cladogram", u"fan", u"unrooted", u"radial" ]
774
775     def __do_layout(self):    
776         self.sizer_1 = wx.BoxSizer(wx.VERTICAL)
777         self.sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
778         self.sizer_3 = wx.BoxSizer(wx.VERTICAL)
779         self.sizer_3.Add(self.deb)
780         self.sizer_1.Add(self.butdendro, 0, 0, 0)
781         self.sizer_1.Add(self.butdendrotexte, 0, 0, 0)
782         self.sizer_1.Add(self.butdendrocloud, 0, 0, 0)
783
784         for i in range(0, len(self.listimg)):
785             self.sizer_3.Add(self.listimg[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
786             self.sizer_3.Add(self.labels[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
787         self.panel_1.SetSizer(self.sizer_3)
788         self.sizer_2.Add(self.sizer_1, 0, wx.EXPAND, 0)
789         self.sizer_2.Add(self.panel_1, 1, wx.EXPAND, 0)
790         self.SetSizer(self.sizer_2) 
791
792     def make_param(self, dial):
793         self.param['width'] = dial.m_spinCtrl2.GetValue()
794         self.param['height'] = dial.m_spinCtrl1.GetValue()
795         self.param['type_dendro'] = dial.m_choice1.GetSelection()
796         self.param['color_nb'] = dial.m_radioBox1.GetSelection()
797         self.param['taille_classe'] = dial.m_checkBox1.GetValue()
798         self.param['type_tclasse'] = dial.m_radioBox2.GetSelection()
799
800     def make_dendro(self, dendro = 'simple') :
801         while os.path.exists(os.path.join(self.dirout, 'dendrogamme_' + str(self.graphnb)+'.png')) :
802             self.graphnb += 1
803         fileout = ffr(os.path.join(self.dirout,'dendrogamme_' + str(self.graphnb)+'.png'))
804         width = self.param['width']
805         height = self.param['height']
806         type_dendro = self.type_dendro[self.param['type_dendro']]
807         if self.param['taille_classe'] :
808             tclasse = 'TRUE'
809         else :
810             tclasse = 'FALSE'
811         if self.param['color_nb'] == 0 :
812             bw = 'FALSE'
813         else :
814             bw = 'TRUE'
815         if self.param['type_tclasse'] == 0 :
816             histo='FALSE'
817         else :
818             histo = 'TRUE'
819         dendro_path = self.dictpathout['Rdendro']
820         classe_path = self.dictpathout['uce']
821         txt = """
822         library(ape)
823         load("%s")
824         source("%s")
825         classes <- read.csv2("%s", row.names=1)
826         classes <- classes[,1]
827         """ % (ffr(dendro_path), ffr(self.ira.RscriptsPath['Rgraph']),  ffr(classe_path))
828         if dendro == 'simple' :
829             txt += """
830             open_file_graph("%s", width=%i, height=%i)
831             plot.dendropr(tree.cut1$tree.cl, classes, type.dendro="%s", histo=%s, bw=%s, lab=NULL, tclasse=%s)
832             """ % (ffr(fileout), width, height, type_dendro, histo, bw, tclasse)
833         elif dendro == 'texte' :
834             txt += """
835             load("%s")
836             source("%s")
837             chistable <- chistabletot[1:(debsup-1),]
838             open_file_graph("%s", width=%i, height=%i)
839             plot.dendro.prof(tree.cut1$tree.cl, classes, chistable, nbbycl = 60, type.dendro="%s", bw=%s, lab=NULL)
840             """ % (ffr(self.dictpathout['RData.RData']), ffr(self.ira.RscriptsPath['Rgraph']), ffr(fileout), width, height, type_dendro, bw)
841         elif dendro == 'cloud' :
842             txt += """
843             load("%s")
844             source("%s")
845             chistable <- chistabletot[1:(debsup-1),]
846             open_file_graph("%s", width=%i, height=%i)
847             plot.dendro.cloud(tree.cut1$tree.cl, classes, chistable, nbbycl = 300, type.dendro="%s", bw=%s, lab=NULL)
848             """ % (ffr(self.dictpathout['RData.RData']), ffr(self.ira.RscriptsPath['Rgraph']), ffr(fileout), width, height, type_dendro, bw)
849
850
851         tmpfile = tempfile.mktemp()
852         with open(tmpfile, 'w') as f :
853             f.write(txt)
854         error = exec_rcode(self.ira.RPath, tmpfile, wait=True) 
855         check_Rresult(self.ira, error)
856         self.list_graph.append([fileout, 'Dendrogramme CHD1 - %s' %  type_dendro])
857         print_liste(self.dictpathout['liste_graph_chd'], self.list_graph)
858         self.sizer_3.Add(wx.StaticBitmap(self.panel_1, -1, wx.Bitmap(fileout, wx.BITMAP_TYPE_ANY)), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
859         self.sizer_3.Add(wx.StaticText(self.panel_1,-1, 'Dendrogramme CHD1 - %s' %  type_dendro), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
860         self.sizer_3.Fit(self.panel_1)
861         self.Layout()
862         self.panel_1.Scroll(0,self.panel_1.GetScrollRange(wx.VERTICAL))
863
864
865     def ondendro(self, evt):
866         dial = PrefDendro(self.ira, self.param)
867         val = dial.ShowModal()
868         if val == wx.ID_OK :
869             self.make_param(dial)
870             self.make_dendro()
871     
872     def ondendrotexte(self, evt):
873         dial = PrefDendro(self.ira, self.param)
874         val = dial.ShowModal()
875         if val == wx.ID_OK :
876             self.make_param(dial)
877             self.make_dendro(dendro = 'texte')
878
879     def ondendrocloud(self, evt):
880         dial = PrefDendro(self.ira, self.param)
881         val = dial.ShowModal()
882         if val == wx.ID_OK :
883             self.make_param(dial)
884             self.make_dendro(dendro = 'cloud')
885
886 class OpenCorpus :
887     def __init__(self, ira, parametres) :
888         #self.text = wx.TextCtrl(ira, -1, "", wx.Point(0, 0), wx.Size(200, 200), wx.NO_BORDER | wx.TE_MULTILINE | wx.TE_RICH2 | wx.TE_READONLY)
889         self.panel = CopusPanel(ira, parametres)
890         ira.nb.AddPage(self.panel, 'Description %s' % parametres['corpus_name'])
891         #self.text.write(DoConf().totext(parametres))
892         ira.nb.SetSelection(ira.nb.GetPageCount() - 1)
893         ira.ShowAPane("Tab_content")
894
895 class CopusPanel(wx.Panel) :
896     def __init__(self, parent, parametres) :
897         wx.Panel.__init__ ( self, parent, id = wx.ID_ANY, pos = wx.DefaultPosition, size = wx.Size( 500,300 ), style = wx.TAB_TRAVERSAL )
898         self.parametres = parametres
899         fgSizer5 = wx.FlexGridSizer( 0, 2, 0, 0 )
900         fgSizer5.SetFlexibleDirection( wx.BOTH )
901         fgSizer5.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED )        
902         self.fgSizer5 = fgSizer5
903         
904         self.m_staticText18 = wx.StaticText( self, wx.ID_ANY, u"Description du corpus", wx.DefaultPosition, wx.DefaultSize, 0 )
905
906         self.m_staticText18.Wrap( -1 )
907         fgSizer5.Add( self.m_staticText18, 0, wx.ALL, 5 )
908         
909         self.m_staticText19 = wx.StaticText( self, wx.ID_ANY, u"", wx.DefaultPosition, wx.DefaultSize, 0 )
910         self.m_staticText19.Wrap( -1 )
911         fgSizer5.Add( self.m_staticText19, 0, wx.ALL, 5 )
912
913         self.m_staticText20 = wx.StaticText( self, wx.ID_ANY, u"Nom", wx.DefaultPosition, wx.DefaultSize, 0 )
914         self.m_staticText20.Wrap( -1 )
915         fgSizer5.Add( self.m_staticText20, 0, wx.ALL, 5 )
916         
917         self.m_staticText21 = wx.StaticText( self, wx.ID_ANY, parametres['corpus_name'], wx.DefaultPosition, wx.DefaultSize, 0 )
918         self.m_staticText21.Wrap( -1 )
919         fgSizer5.Add( self.m_staticText21, 0, wx.ALL, 5 )
920
921         description = {'lang' : u'langue',
922                        'encoding' : u'encodage',
923                        'ucinb' : u'Nombre de textes',
924                        'ucenb' : u'Nombre de segments de texte',
925                        'formesnb' : u'Nombre de formes',
926                        'hapax' : u'Nombre d\'hapax'
927                       }
928
929         keys = ['lang', 'encoding', 'originalpath', 'pathout', 'date', 'time']
930
931         self.addkeys(keys, description)
932
933         self.m_staticText18 = wx.StaticText( self, wx.ID_ANY, u"Paramètres", wx.DefaultPosition, wx.DefaultSize, 0 )
934         self.m_staticText18.Wrap( -1 )
935         fgSizer5.Add( self.m_staticText18, 0, wx.ALL, 5 )
936         
937         self.m_staticText19 = wx.StaticText( self, wx.ID_ANY, u"", wx.DefaultPosition, wx.DefaultSize, 0 )
938         self.m_staticText19.Wrap( -1 )
939         fgSizer5.Add( self.m_staticText19, 0, wx.ALL, 5 )
940
941         keys = ['ucemethod', 'ucesize', 'keep_caract', 'expressions']
942         self.addkeys(keys, description)
943
944         self.m_staticText18 = wx.StaticText( self, wx.ID_ANY, u"Statistiques", wx.DefaultPosition, wx.DefaultSize, 0 )
945         self.m_staticText18.Wrap( -1 )
946         fgSizer5.Add( self.m_staticText18, 0, wx.ALL, 5 )
947         
948         self.m_staticText19 = wx.StaticText( self, wx.ID_ANY, u"", wx.DefaultPosition, wx.DefaultSize, 0 )
949         self.m_staticText19.Wrap( -1 )
950         fgSizer5.Add( self.m_staticText19, 0, wx.ALL, 5 )
951
952         keys = ['ucinb', 'ucenb', 'occurrences', 'formesnb', 'hapax']
953         self.addkeys(keys, description)
954
955         self.SetSizer( fgSizer5 )
956         self.Layout()
957
958     def addkeys(self, keys, description) :
959         for key in keys :
960             option = self.parametres.get(key,u'non défini')
961             if isinstance(option, int) :
962                 option = `option`
963             text = wx.StaticText( self, wx.ID_ANY, description.get(key, key), wx.DefaultPosition, wx.DefaultSize, 0 )
964             text.Wrap( -1 )
965             self.fgSizer5.Add( text, 0, wx.ALL, 5 )
966
967             text = wx.StaticText( self, wx.ID_ANY, option, wx.DefaultPosition, wx.DefaultSize, 0 )
968             text.Wrap( -1 )
969             self.fgSizer5.Add( text, 0, wx.ALL, 5 )
970
971 class DefaultTextLayout :
972     def __init__(self, ira, corpus, parametres) :
973         self.pathout = PathOut(dirout = parametres['pathout'])
974         self.ira = ira
975         self.parent = ira
976         self.parametres = parametres
977         self.corpus = corpus
978         self.dolayout()
979     
980     def dolayout(self) :
981         log.info('no layout yet')
982
983 class WordCloudLayout(DefaultTextLayout):
984     def dolayout(self):
985         self.pathout.basefiles(simipath)
986         self.Tab = aui.AuiNotebook(self.ira.nb, -1, wx.DefaultPosition)
987         if self.parametres['svg'] :
988             list_graph = [['nuage_1.svg', 'Nuage']]
989         else :
990             list_graph = [['nuage_1.png', 'Nuage']]
991         self.TabStatTot = GraphPanel(self.ira.nb, self.pathout, list_graph)
992         self.Tab.AddPage(self.TabStatTot, 'Nuage')
993         self.Tab.corpus = self.corpus
994         self.Tab.parametres = self.parametres
995         self.ira.nb.AddPage(self.Tab, '%s' % self.parametres['name'])
996         self.ira.nb.SetSelection(self.ira.nb.GetPageCount() - 1)
997         self.ira.ShowAPane("Tab_content")
998
999 class SimiLayout(DefaultTextLayout) :
1000     def dolayout(self) :
1001         self.pathout.basefiles(simipath)
1002         self.actives = None
1003         self.indices = indices_simi
1004         if os.path.exists(self.pathout['liste_graph']) :
1005             list_graph = read_list_file(self.pathout['liste_graph'])
1006         else : 
1007             list_graph = [['','']]
1008         notebook_flags =  aui.AUI_NB_DEFAULT_STYLE | aui.AUI_NB_TAB_EXTERNAL_MOVE | aui.AUI_NB_TAB_MOVE | aui.AUI_NB_TAB_FLOAT
1009         self.tabsimi = aui.AuiNotebook(self.ira.nb, -1, wx.DefaultPosition)
1010         self.tabsimi.SetAGWWindowStyleFlag(notebook_flags)
1011         self.tabsimi.SetArtProvider(aui.ChromeTabArt())
1012         self.tabsimi.corpus = self.corpus
1013         self.tabsimi.parametres = self.parametres
1014         self.graphpan = GraphPanelSimi(self.tabsimi, self.pathout, list_graph)
1015         self.graphpan.Bind(wx.EVT_BUTTON, self.redosimi, self.graphpan.butafc)
1016         self.graphpan.Bind(wx.EVT_BUTTON, self.export, self.graphpan.butexport)
1017         self.tabsimi.AddPage(self.graphpan, 'Graph')
1018         self.ira.nb.AddPage(self.tabsimi, 'Analyse de graph')
1019         self.ira.ShowTab(True)
1020         self.ira.nb.SetSelection(self.ira.nb.GetPageCount() - 1)
1021         
1022     def redosimi(self, evt) :
1023         with open(self.pathout['selected.csv'],'r') as f :
1024             selected = f.read()
1025         selected = [int(val) for val in selected.splitlines()]
1026         if self.actives is None :
1027             with codecs.open(self.pathout['actives.csv'], 'r', self.parametres['encoding']) as f :
1028                 self.actives = f.read()
1029             self.actives = self.actives.splitlines()#[act for act in self.actives.splitlines()]
1030         if os.path.exists(self.pathout['actives_nb.csv']) :
1031             with open(self.pathout['actives_nb.csv'], 'r') as f :
1032                 act_nb = f.read()
1033                 act_nb = act_nb.splitlines()
1034             dictcol = dict([[i, [self.actives[i], int(act_nb[i])]] for i, val in enumerate(self.actives)])
1035         else :
1036             dictcol = dict([[i, [act, self.corpus.getlemeff(act)]] for i, act in enumerate(self.actives)])
1037         #res = SelectColumn(self.ira, dictcol, self.actives, self.pathout['selected.csv'], selected = selected, dlg = True) 
1038         #if res.ok :
1039         prep = PrepSimi(self.ira, self, self.parametres,self.pathout['selected.csv'], self.actives, indices_simi, wordlist = dictcol, selected = selected)
1040         if prep.val == wx.ID_OK :
1041             self.parametres = prep.parametres
1042
1043             script = PrintSimiScript(self)
1044             script.make_script()
1045             pid = exec_rcode(self.ira.RPath, script.scriptout, wait = True)
1046             check_Rresult(self.ira, pid)
1047             if self.parametres['type_graph'] in [1,3] :
1048                 if self.parametres['svg'] :
1049                     filename, ext = os.path.splitext(script.filename)
1050                     fileout = filename + '.svg'
1051                 elif self.parametres['type_graph'] == 3 :
1052                     fileout = script.filename
1053                     parametres = {'gexffile' :  fileout,
1054                                   'dirout' : os.path.dirname(fileout),
1055                                   'titre': 'Le titre',
1056                                   #'nodemin': self.param['txt_min'],
1057                                   #'nodemax': self.param['txt_max'],
1058                                   #'bargraphw' : 60*int(self.param['clnb']),
1059                     }
1060                     web = WebExport(self.ira, parametres)
1061                     fileout = web.exportsimi()                         
1062                 else :
1063                     fileout = script.filename
1064                 if os.path.exists(self.pathout['liste_graph']):
1065                     graph_simi = read_list_file(self.pathout['liste_graph'])
1066                     graph_simi.append([os.path.basename(fileout), script.txtgraph])
1067                 else :
1068                     graph_simi = [[os.path.basename(fileout), script.txtgraph]]
1069                 print_liste(self.pathout['liste_graph'], graph_simi)
1070             DoConf().makeoptions([self.parametres['type']], [self.parametres], self.pathout['Analyse.ira'])
1071             if self.parametres['type_graph'] in [1,3] :
1072                 if self.parametres['svg'] or self.parametres['type_graph'] == 3 :
1073                     self.graphpan.sizer_3.Add(hl.HyperLinkCtrl(self.graphpan.panel_1, -1, fileout, URL = fileout), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
1074                 else :
1075                     self.graphpan.sizer_3.Add(wx.StaticBitmap(self.graphpan.panel_1, -1, wx.Bitmap(fileout, wx.BITMAP_TYPE_ANY)), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
1076                 self.graphpan.sizer_3.Add(wx.StaticText(self.graphpan.panel_1,-1, script.txtgraph), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
1077                 self.graphpan.sizer_3.Fit(self.graphpan.panel_1)
1078                 self.graphpan.Layout()
1079                 self.graphpan.panel_1.Scroll(0,self.graphpan.panel_1.GetScrollRange(wx.VERTICAL))
1080
1081     def export(self, evt) :
1082         nb = 1
1083         while os.path.exists(os.path.join(self.pathout.dirout,'graph_'+str(nb)+'.graphml')):
1084             nb +=1
1085         fileout = ffr(os.path.join(self.pathout.dirout,'graph_'+str(nb)+'.graphml'))
1086         txt = """
1087         library(igraph)
1088         load("%s")
1089         source("%s")
1090         fileout <- "%s"
1091         graph <- graph.simi$graph
1092         V(graph)$x <- graph.simi$layout[,1]
1093         V(graph)$y <- graph.simi$layout[,2]
1094         if (length(graph.simi$label.cex == 1)) {
1095             V(graph)$weight <- graph.simi$eff
1096         } else {
1097             V(graph)$weight <- graph.simi$label.cex
1098         }
1099         V(graph)$color <- vertex.label.color
1100         V(graph)$frequences <- graph.simi$mat.eff
1101         V(graph)$label <- as.character(graph.simi$v.label)
1102         E(graph)$weight <- graph.simi$we.width
1103         write.graph(graph, fileout, format = 'graphml')
1104         #saveAsGEXF(graph, filepath = fileout)
1105         """ % (self.pathout['RData.RData'], self.parent.RscriptsPath['simi'], fileout)
1106         filetmp = tempfile.mktemp()
1107         with open(filetmp, 'w') as f :
1108             f.write(txt)
1109         exec_rcode(self.ira.RPath, filetmp)
1110         mss = wx.MessageDialog(self.ira, fileout, u'Fichier exporté', wx.OK)
1111         mss.CenterOnParent()
1112         mss.ShowModal()
1113         mss.Destroy()
1114
1115 class DefaultMatLayout :
1116     def __init__(self, parent, tableau, parametres) :
1117         self.pathout = PathOut(dirout = parametres['pathout'])
1118         self.ira = parent
1119         self.parent = parent
1120         self.tableau = tableau
1121         self.parametres = parametres
1122         self.dolayout()
1123
1124     def dolayout(self) :
1125         pass
1126
1127 class ProtoLayout(DefaultMatLayout) :
1128     def dolayout(self) :
1129         list_graph = [['proto.png', 'Analyse prototypique']]
1130         #self.Tab = aui.AuiNotebook(self.ira.nb, -1, wx.DefaultPosition)
1131         #if self.parametres['svg'] :
1132         #    list_graph = [['nuage_1.svg', 'Nuage']]
1133         #else :
1134         #    list_graph = [['nuage_1.png', 'Nuage']]
1135         self.TabProto = GraphPanel(self.ira.nb, self.pathout, list_graph)
1136         #self.Tab.AddPage(self.TabProto, 'Analyse Prototypique')
1137         #self.Tab.corpus = self.corpus
1138         self.TabProto.parametres = self.parametres
1139         self.ira.nb.AddPage(self.TabProto, 'Analyse Prototypique - %s' % self.parametres['name'])
1140         self.ira.nb.SetSelection(self.ira.nb.GetPageCount() - 1)
1141         self.ira.ShowAPane("Tab_content")
1142
1143
1144 class SimiMatLayout(DefaultMatLayout) :
1145     def dolayout(self):
1146         self.pathout.basefiles(simipath)
1147         self.indices = indices_simi
1148         if os.path.exists(self.pathout['liste_graph']) :
1149             list_graph = read_list_file(self.pathout['liste_graph'])
1150         else : 
1151             list_graph = [['','']]
1152         notebook_flags =  aui.AUI_NB_DEFAULT_STYLE | aui.AUI_NB_TAB_EXTERNAL_MOVE | aui.AUI_NB_TAB_MOVE | aui.AUI_NB_TAB_FLOAT
1153         self.tabsimi = aui.AuiNotebook(self.parent.nb, -1, wx.DefaultPosition)
1154         self.tabsimi.SetAGWWindowStyleFlag(notebook_flags)
1155         self.tabsimi.SetArtProvider(aui.ChromeTabArt())
1156         self.graphpan = GraphPanelSimi(self.tabsimi, self.pathout, list_graph)
1157         self.graphpan.Bind(wx.EVT_BUTTON, self.redosimi, self.graphpan.butafc)
1158         self.graphpan.Bind(wx.EVT_BUTTON, self.export, self.graphpan.butexport)
1159         self.tabsimi.AddPage(self.graphpan, 'Graph')
1160         self.tabsimi.parametres = self.parametres
1161         self.parent.nb.AddPage(self.tabsimi, 'Analyse de graph')
1162         self.parent.ShowTab(True)
1163         self.parent.nb.SetSelection(self.parent.nb.GetPageCount() - 1)
1164
1165     def redosimi(self,evt) :
1166         with open(self.pathout['selected.csv'],'r') as f :
1167             selected = f.read()
1168         selected = [int(val) for val in selected.splitlines()]
1169         #if self.actives is None :
1170         #    with codecs.open(self.pathout['actives.csv'], 'r', self.parametres['encoding']) as f :
1171         #        self.actives = f.read()
1172         #    self.actives = self.actives.splitlines()#[act for act in self.actives.splitlines()]
1173         try :
1174             actives = [[val, self.tableau.actives[val][0]] for val in self.tableau.actives]
1175         except :
1176             actives = [[val, self.tableau.actives[val]] for val in self.tableau.actives]
1177
1178         #self.tableau.make_listactives()
1179         actives = dict([[i, val] for i, val in enumerate(actives)])
1180         #dictcol = dict([[i, [act, self.corpus.getlemeff(act)]] for i, act in enumerate(self.actives)])
1181         self.dial = PrefSimi(self.parent, -1, self.parametres, self.indices, wordlist = actives, selected = selected, actives = self.tableau.listactives)
1182         self.dial.CenterOnParent()
1183         self.val = self.dial.ShowModal()
1184         if self.val == wx.ID_OK :
1185             last = self.dial.listcol.GetFirstSelected()
1186             lastl = [self.dial.listcol.GetFirstSelected()]
1187             indexes = [self.dial.listcol.getColumnText(self.dial.listcol.GetFirstSelected(),0)]
1188             while self.dial.listcol.GetNextSelected(last) != -1:
1189                 last = self.dial.listcol.GetNextSelected(last)
1190                 lastl.append(last)
1191                 indexes.append(self.dial.listcol.getColumnText(last,0))
1192             self.column = [self.tableau.listactives.index(val) for val in indexes]
1193             self.column.sort()
1194             with open(self.pathout['selected.csv'], 'w') as f :
1195                 f.write('\n'.join([`val` for val in self.column]))
1196             self.make_param()
1197             self.dial.Destroy()
1198             self.script = PrintSimiScript(self)
1199             self.script.make_script()
1200             self.tmpfile = self.script.scriptout
1201             dlg = progressbar(self, maxi = 2)
1202             self.DoR(dlg)
1203             dlg.Destroy()
1204             if self.parametres['type_graph'] == 1:
1205                 if self.parametres['svg'] :
1206                     filename, ext = os.path.splitext(self.script.filename)
1207                     fileout = filename + '.svg'
1208                 else :
1209                     fileout = self.script.filename
1210                 if os.path.exists(self.pathout['liste_graph']):
1211                     graph_simi = read_list_file(self.pathout['liste_graph'])
1212                     graph_simi.append([os.path.basename(fileout), self.script.txtgraph])
1213                 else :
1214                     graph_simi = [[os.path.basename(fileout), self.script.txtgraph]]
1215                 print_liste(self.pathout['liste_graph'], graph_simi)            
1216             DoConf().makeoptions([self.parametres['type']], [self.parametres], self.pathout['Analyse.ira'])
1217             if self.parametres['type_graph'] == 1:
1218                 if self.parametres['svg'] :
1219                     self.graphpan.sizer_3.Add(hl.HyperLinkCtrl(self.graphpan.panel_1, -1, fileout, URL = fileout), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
1220                 else :
1221                     self.graphpan.sizer_3.Add(wx.StaticBitmap(self.graphpan.panel_1, -1, wx.Bitmap(self.script.filename, wx.BITMAP_TYPE_ANY)), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
1222                 self.graphpan.sizer_3.Add(wx.StaticText(self.graphpan.panel_1,-1, self.script.txtgraph), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
1223                 self.graphpan.sizer_3.Fit(self.graphpan.panel_1)
1224                 self.graphpan.Layout()
1225                 self.graphpan.panel_1.Scroll(0,self.graphpan.panel_1.GetScrollRange(wx.VERTICAL))
1226         else :
1227             self.dial.Destroy()
1228                
1229
1230     def make_param(self) :
1231         if self.parametres['first'] :
1232             keep_coord = False
1233         else :
1234             keep_coord = self.dial.check_coord.GetValue()
1235         #self.select = self.dial.check_colch.GetValue()
1236
1237         paramsimi = {'coeff' : self.dial.choice1.GetSelection(),
1238                           'layout' : self.dial.choice2.GetSelection(),
1239                           'type_graph' : self.dial.choice3.GetSelection(),
1240                           'arbremax' : self.dial.check1.GetValue(),
1241                           'coeff_tv' : self.dial.check_s_size.GetValue(),
1242                           'coeff_tv_nb' : self.dial.spin_tv.GetValue(),
1243                           'tvprop' : self.dial.check2.GetValue(),
1244                           'tvmin' : self.dial.spin_tvmin.GetValue(),
1245                           'tvmax' : self.dial.spin_tvmax.GetValue(),
1246                           'coeff_te' : self.dial.check3.GetValue(),
1247                           'coeff_temin' : self.dial.spin_temin.GetValue(),
1248                           'coeff_temax' : self.dial.spin_temax.GetValue(),
1249                           'label_e' : self.dial.check_elab.GetValue(),
1250                           'label_v' : self.dial.check_vlab.GetValue(),
1251                           'vcex' : self.dial.check_vcex.GetValue(),
1252                           'vcexmin' : self.dial.spin_vcexmin.GetValue(),
1253                           'vcexmax' : self.dial.spin_vcexmax.GetValue(),
1254                           'cex' : self.dial.spin_cex.GetValue(),
1255                           'seuil_ok' : self.dial.check_seuil.GetValue(),
1256                           'seuil' : self.dial.spin_seuil.GetValue(),
1257                           'cols' : self.dial.cols.GetColour(),
1258                           'cola' : self.dial.cola.GetColour(),
1259                           'width' : self.dial.spin_width.GetValue(),
1260                           'height' : self.dial.spin_height.GetValue(),
1261                           'first' : False,
1262                           'keep_coord' : keep_coord,
1263                           'alpha' : self.dial.slider_sphere.GetValue(),
1264                           'film' : self.dial.film.GetValue(),
1265                           'svg' : self.dial.choix_format.GetSelection(),
1266                           'halo' : self.dial.halo.GetValue(),
1267                           'com' : self.dial.comcheck.GetValue(),
1268                           'communities' : self.dial.choix_com.GetSelection(),
1269                           }        
1270         if 'cexfromchi' in self.parametres :
1271             paramsimi['cexfromchi'] = self.dial.checkit.GetValue()
1272         if 'sfromchi' in self.parametres :
1273             paramsimi['sfromchi'] = self.dial.checki.GetValue()
1274         if 'vlabcolor' in self.parametres :
1275             paramsimi['vlabcolor'] = self.parametres['vlabcolor']
1276         if 'check_bystar' in dir(self.dial) :
1277             paramsimi['bystar'] = self.dial.check_bystar.GetValue()
1278             paramsimi['stars'] = self.parametres['stars']
1279         self.parametres.update(paramsimi)
1280
1281     def DoR(self, dlg):
1282         if self.parametres['type_graph'] == 1 :
1283             graph = False
1284             wait = False
1285         else : 
1286             graph = True
1287             wait = True
1288         pid = exec_rcode(self.parent.RPath, self.tmpfile, wait = wait, graph = graph)
1289         if self.parametres['type_graph'] == 1 :
1290             while pid.poll() == None :
1291                 dlg.Pulse(u'R ...')
1292                 sleep(0.2)
1293             check_Rresult(self.parent, pid)
1294     
1295     def export(self, evt) : 
1296         nb = 1
1297         while os.path.exists(os.path.join(self.pathout.dirout,'graph_'+str(nb)+'.graphml')):
1298             nb +=1
1299         fileout = ffr(os.path.join(self.pathout.dirout,'graph_'+str(nb)+'.graphml'))
1300         txt = """
1301         library(igraph)
1302         load("%s")
1303         source("%s")
1304         fileout <- "%s"
1305         graph <- graph.simi$graph
1306         V(graph)$x <- graph.simi$layout[,1]
1307         V(graph)$y <- graph.simi$layout[,2]
1308         if (length(graph.simi$label.cex == 1)) {
1309             V(graph)$weight <- graph.simi$mat.eff
1310         } else {
1311             V(graph)$weight <- graph.simi$label.cex
1312         }
1313         V(graph)$color <- vertex.label.color
1314         V(graph)$frequences <- graph.simi$mat.eff
1315         V(graph)$fprop <- graph.simi$mat.eff/nrow(dm)
1316         V(graph)$label <- as.character(graph.simi$v.label)
1317         E(graph)$weight <- graph.simi$we.width
1318         write.graph(graph, fileout, format = 'graphml')
1319         #saveAsGEXF(graph, filepath = fileout)
1320         """ % (self.pathout['RData.RData'], self.parent.RscriptsPath['simi'], fileout)
1321         filetmp = tempfile.mktemp()
1322         with open(filetmp, 'w') as f :
1323             f.write(txt)
1324         exec_rcode(self.ira.RPath, filetmp)
1325         mss = wx.MessageDialog(self.ira, fileout, u'Fichier exporté', wx.OK)
1326         mss.CenterOnParent()
1327         mss.ShowModal()
1328         mss.Destroy()
1329
1330         
1331 class GraphPanelSimi(wx.Panel):
1332     def __init__(self,parent, dico, list_graph):
1333         wx.Panel.__init__(self,parent)
1334         self.afcnb = 1
1335         self.Dict = dico
1336         self.dirout = os.path.dirname(self.Dict['ira'])
1337         self.parent = self.GetParent()#parent
1338         self.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, "courier"))
1339         self.labels = []
1340         self.listimg = []
1341         self.tabsimi = self.parent.GetParent()
1342         self.ira = self.tabsimi.GetParent()
1343         self.panel_1 = wx.ScrolledWindow(self, -1, style=wx.TAB_TRAVERSAL)
1344         afc_img = wx.Image(os.path.join(self.ira.images_path,'button_simi.jpg'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
1345         self.butafc = wx.BitmapButton(self, -1, afc_img)
1346         export_img = wx.Image(os.path.join(self.ira.images_path,'button_export.jpg'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
1347         self.butexport = wx.BitmapButton(self, -1, export_img)
1348         for i in range(0,len(list_graph)):
1349             if os.path.exists(os.path.join(self.dirout,list_graph[i][0])) :
1350                 filename, ext = os.path.splitext(list_graph[i][0])
1351                 if ext in ['.svg', '.html'] :
1352                     self.listimg.append(hl.HyperLinkCtrl(self.panel_1, -1, os.path.join(self.dirout,list_graph[i][0]), URL=os.path.join(self.dirout,list_graph[i][0])))
1353                 else :
1354                     self.listimg.append(wx.StaticBitmap(self.panel_1, -1, wx.Bitmap(os.path.join(self.dirout,list_graph[i][0]), wx.BITMAP_TYPE_ANY)))
1355                 self.labels.append(wx.StaticText(self.panel_1, -1, list_graph[i][1]))
1356         self.panel_1.Bind(wx.EVT_MOTION, self.onMouseMove) 
1357         self.__set_properties()
1358         self.__do_layout()
1359
1360     def __set_properties(self):
1361         self.panel_1.EnableScrolling(True,True)
1362         #self.panel_1.SetSize((1000,1000))
1363         self.panel_1.SetScrollRate(20, 20)
1364         self.panel_1.SetFocus()
1365
1366     def __do_layout(self):    
1367         self.sizer_1 = wx.BoxSizer(wx.HORIZONTAL)
1368         self.sizer_2 = wx.BoxSizer(wx.VERTICAL)
1369         self.sizer_3 = wx.BoxSizer(wx.VERTICAL)
1370         self.sizer_2.Add(self.butafc, 0, 0, 0)
1371         self.sizer_2.Add(self.butexport, 0, 0, 0)
1372         for i in range(0, len(self.listimg)):
1373             self.sizer_3.Add(self.listimg[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
1374             self.sizer_3.Add(self.labels[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
1375         self.panel_1.SetSizer(self.sizer_3)
1376         self.sizer_1.Add(self.sizer_2, 0, wx.EXPAND, 0)
1377         self.sizer_1.Add(self.panel_1, 1, wx.EXPAND, 0)
1378         self.SetSizer(self.sizer_1) 
1379
1380     def onMouseMove(self, event):
1381         self.panel_1.SetFocus()