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