modif chdtxt, a tester, problemes sur double sur rst
[iramuteq] / layout.py
1 #!/bin/env python
2 # -*- coding: utf-8 -*-
3 #Author: Pierre Ratinaud
4 #Copyright (c) 2008-2009 Pierre Ratinaud
5 #Lisense: GNU/GPL
6
7 import os
8 import wx
9 import wx.lib.hyperlink as hl
10 if wx.__version__ >= '2.11' :
11     import wx.lib.agw.aui as aui
12 else :
13     import aui
14 from chemins import ConstructPathOut, ChdTxtPathOut, FFF, ffr, PathOut, StatTxtPathOut, simipath
15 from ConfigParser import ConfigParser
16 from functions import ReadProfileAsDico, GetTxtProfile, read_list_file, ReadList, exec_rcode, print_liste, BugReport, DoConf, indices_simi, check_Rresult, progressbar
17 from ProfList import ProfListctrlPanel
18 from guiparam3d import param3d, simi3d
19 from PrintRScript import write_afc_graph, print_simi3d, PrintSimiScript
20 from profile_segment import ProfileSegment
21 from functions import ReadList
22 from listlex import *
23 from Liste import *
24 from search_tools import SearchFrame
25 from dialog import PrefGraph, PrefExport, PrefSimpleFile, PrefDendro
26 from guifunct import SelectColumn, PrepSimi
27 from corpus import Corpus
28 import datetime
29 import sys
30 import tempfile
31 import shutil
32 import codecs
33 import logging
34
35 log = logging.getLogger('iramuteq.layout')
36
37
38 class GraphPanelAfc(wx.Panel):
39     def __init__(self, parent, dico, list_graph, clnb, itempath = 'liste_graph_afc', coding = sys.getdefaultencoding()):
40         wx.Panel.__init__(self,parent)
41         self.afcnb = 1
42         self.clnb = clnb
43         self.Dict = dico
44         self.coding = coding
45         self.itempath = itempath
46         self.parent = self.GetParent()#parent
47         self.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, "courier"))
48         self.labels = []
49         self.listimg = []
50         self.buts = []
51         self.list_graph = list_graph
52         self.TabCHD = self.parent.GetParent()
53         self.nb = self.TabCHD.GetParent()
54         self.ira = self.nb.GetParent()
55         self.panel_1 = wx.ScrolledWindow(self, -1, style=wx.TAB_TRAVERSAL)
56         afc_img = wx.Image(os.path.join(self.ira.images_path,'button_afc.jpg'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
57         self.butafc = wx.BitmapButton(self, -1, afc_img)
58         self.Bind(wx.EVT_BUTTON, self.afc_graph, self.butafc)
59         self.dirout = os.path.dirname(self.Dict['ira'])
60         b = 0
61         todel = []
62         for i in range(0,len(list_graph)):
63             if os.path.exists(os.path.join(self.dirout,list_graph[i][0])) :
64                 filename, ext = os.path.splitext(list_graph[i][0])
65                 if ext == '.svg' :
66                     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])))
67                 else :
68                     self.listimg.append(wx.StaticBitmap(self.panel_1, -1, wx.Bitmap(os.path.join(self.dirout,list_graph[i][0]), wx.BITMAP_TYPE_ANY)))
69                 self.labels.append(wx.StaticText(self.panel_1, -1, list_graph[i][1]))
70                 self.buts.append(wx.Button(self.panel_1, wx.ID_DELETE, name = `i - b`))
71             else :
72                 todel.append(i)
73                 b += 1
74         self.list_graph = [graph for i, graph in enumerate(self.list_graph) if i not in todel]
75                 
76         self.param = { 'typegraph' : 0, 
77               'width' : 800,
78               'height' : 800,
79               'what' : 0,
80               'qui' : 0,
81               'do_select_nb' : 0,
82               'do_select_chi' : 0,
83               'do_select_chi_classe' : 0,
84               'select_nb' : 50,
85               'select_chi' : 4,
86               'nbchic' : 30,
87               'over' : 0, 
88               'cex_txt' : 0,
89               'txt_min' : 5,
90               'txt_max' : 40,
91               'tchi' : 0,
92               'tchi_min' : 5,
93               'tchi_max' : 40,
94               'taillecar' : 9,
95               'facteur' : [1,2,3],
96               'alpha' : 10,
97               'clnb' : clnb,
98               'svg' : 0,
99             }
100
101         self.__set_properties()
102         self.__do_layout()
103
104     def __set_properties(self):
105         self.panel_1.EnableScrolling(True,True)
106         #self.panel_1.SetSize((1000,1000))
107         self.panel_1.SetScrollRate(20, 20)
108
109     def __do_layout(self):    
110         self.sizer_1 = wx.BoxSizer(wx.VERTICAL)
111         self.sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
112         self.sizer_3 = wx.BoxSizer(wx.VERTICAL)
113         self.sizer_2.Add(self.butafc, 0, 0, 0)
114         for i in range(0, len(self.listimg)):
115             self.sizer_3.Add(self.listimg[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
116             self.sizer_3.Add(self.labels[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
117             self.sizer_3.Add(self.buts[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
118             self.Bind(wx.EVT_BUTTON, self.on_delete_image, self.buts[i])
119         self.panel_1.SetSizer(self.sizer_3)
120         self.sizer_2.Add(self.panel_1, 1, wx.EXPAND, 0)
121         self.SetSizer(self.sizer_2) 
122
123     def on_delete_image(self, event) :
124         image_id = int(event.GetEventObject().GetName())
125         image_path = self.list_graph[image_id][0]
126         message = 'This file will be delete : %s.\nAre you sure ?' % os.path.join(self.dirout, image_path)
127         dial = wx.MessageDialog(self, message, style = wx.YES_NO)
128         res = dial.ShowModal()
129         if res == wx.ID_YES :
130             dial.Destroy()
131             log.info('delete image %i' % image_id)
132             oldimg = self.listimg.pop(image_id)
133             oldimg.Destroy()
134             oldlab = self.labels.pop(image_id)
135             oldlab.Destroy()
136             oldbut = self.buts.pop(image_id)
137             oldbut.Show(False)
138             for i, but in enumerate(self.buts) :
139                 but.SetName(`i`)
140             todel = self.list_graph.pop(image_id)
141             os.remove(os.path.join(self.dirout, todel[0]))
142             print_liste(self.Dict[self.itempath], self.list_graph)
143             self.sizer_3.Fit(self.panel_1)
144             self.Layout()
145         else :
146             dial.Destroy()
147         
148
149     def afc_graph(self,event):
150         #dirout = os.path.dirname(self.Dict['ira'])
151         while os.path.exists(os.path.join(self.dirout,'graph_afc_'+str(self.afcnb)+'.png')):
152             self.afcnb +=1
153         self.fileout = ffr(os.path.join(self.dirout,'graph_afc_'+str(self.afcnb)+'.png'))
154         dial = PrefGraph(self.parent,-1,self.param,'')
155         dial.CenterOnParent()
156         val = dial.ShowModal()
157         if val == wx.ID_OK :
158             if dial.choix_format.GetSelection() == 0 :
159                 svg = 0
160             else :
161                 svg = 1
162             self.param = {'typegraph' : dial.choicetype.GetSelection(),
163                           'width' : dial.spin1.GetValue(),
164                           'height' : dial.spin2.GetValue(),
165                           'what' : dial.choice1.GetSelection(),
166                           'qui' : dial.choice2.GetSelection(),
167                           'do_select_nb' : dial.check1.GetValue(),
168                           'do_select_chi' : dial.check2.GetValue(),
169                           'do_select_chi_classe' : dial.check_chic.GetValue(),
170                           'select_nb' : dial.spin_nb.GetValue(),
171                           'select_chi' : dial.spin_chi.GetValue(),
172                           'nbchic' : dial.spin_nbchic.GetValue(),
173                           'over' : dial.check3.GetValue(), 
174                           'cex_txt' : dial.check4.GetValue(),
175                           'txt_min' : dial.spin_min.GetValue(),
176                           'txt_max' : dial.spin_max.GetValue(),
177                           'tchi' : dial.check_tchi.GetValue(),
178                           'tchi_min' : dial.spin_min_tchi.GetValue(),
179                           'tchi_max' : dial.spin_max_tchi.GetValue(),
180                           'taillecar' : dial.spin3.GetValue(),
181                           'facteur' : [dial.spin_f1.GetValue(),dial.spin_f2.GetValue(), dial.spin_f3.GetValue()],
182                           'clnb' : self.clnb,
183                           'film' : str(dial.film.GetValue()).upper(),
184                           'alpha' : dial.slider_sphere.GetValue(),
185                           'svg' : svg
186                         }
187             self.nb.parent = self.ira
188             self.DictPathOut = self.Dict
189             self.RscriptsPath = self.ira.RscriptsPath
190             txt = """
191             load("%s")
192             """ % self.DictPathOut['RData']
193             if self.itempath == 'liste_graph_afcf' :
194                 txt += """
195                 afc <- afcf
196                 afc_table <- afcf_table
197                 chistabletot <- specfp
198                 """ 
199             elif self.itempath == 'liste_graph_afct' :
200                 txt +="""
201                 afc <- afct
202                 afc_table <- afct_table
203                 chistabletot <- spectp
204                 """
205             txt += write_afc_graph(self)
206             filetmp = tempfile.mktemp()
207             with open(filetmp, 'w') as f :
208                 f.write(txt)
209             pid = exec_rcode(self.ira.RPath, filetmp)
210             check_Rresult(self.ira, pid)
211             if self.param['typegraph'] == 0 :
212                 txt = 'Variables '
213                 if self.param['qui'] == 0 : value = u'actives'
214                 if self.param['qui'] == 1 : value = u'supplémentaires'
215                 if self.param['qui'] == 2 : value = u'étoilées'
216                 if self.param['qui'] == 3 : value = u'classes'
217                 txt += value + ' - '
218                 if self.param['what'] == 0 : value = u'Coordonnées'
219                 if self.param['what'] == 1 : value = u'Corrélations'
220                 txt += value + u' - facteur %i / %i' % (self.param['facteur'][0], self.param['facteur'][1])
221                 if self.param['do_select_nb'] : txt += u' - sélection de %i variables' % self.param['select_nb']
222                 if self.param['do_select_chi'] : txt += u' - sélection des variables avec chi2 > %i ' % self.param['select_chi']
223                 if self.param['over'] : txt += u' - Eviter les recouvrements'
224                 if self.param['cex_txt'] : txt += u' - taille du texte proportionnel à la masse'
225                 if self.param['tchi'] : txt += u' - taille du texte proportionnel au chi2 d\'association'
226                 #list_graph = read_list_file(self.DictPathOut[self.itempath], self.coding)
227                 if self.param['svg'] :
228                     filename, ext = os.path.splitext(self.fileout)
229                     self.fileout = filename + '.svg'
230                 self.list_graph.append([os.path.basename(self.fileout), txt])
231                 print_liste(self.DictPathOut[self.itempath], self.list_graph)
232                 if not self.param['svg'] :
233                     self.listimg.append(wx.StaticBitmap(self.panel_1, -1, wx.Bitmap(self.fileout, wx.BITMAP_TYPE_ANY)))
234                 else :
235                     self.listimg.append(hl.HyperLinkCtrl(self.panel_1, -1, self.fileout, URL=self.fileout))
236                 self.sizer_3.Add( self.listimg[-1], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
237                 self.labels.append(wx.StaticText(self.panel_1,-1, txt))
238                 self.sizer_3.Add(self.labels[-1], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
239                 self.buts.append(wx.Button(self.panel_1, wx.ID_DELETE, name = `len(self.list_graph) - 1`))
240                 self.sizer_3.Add(self.buts[-1], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
241                 self.sizer_3.Fit(self.panel_1)
242                 self.Layout()
243     
244                 self.panel_1.Scroll(0,self.panel_1.GetScrollRange(wx.VERTICAL))
245             
246
247 class GraphPanel(wx.ScrolledWindow):
248     def __init__(self, parent, dico, list_graph, txt = '', style = wx.TAB_TRAVERSAL):
249         wx.ScrolledWindow.__init__(self, parent, style = style)
250         self.Dict = dico
251         self.txt = txt
252         self.parent = parent
253         self.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.FONTWEIGHT_BOLD, 0, "courier"))
254         self.labels = []
255         self.listimg = []
256         self.dirout = os.path.dirname(self.Dict['ira'])
257         self.deb = wx.StaticText(self, -1, txt)
258         for i in range(0,len(list_graph)):
259             if os.path.exists(os.path.join(self.dirout,list_graph[i][0])) :
260                 self.listimg.append(wx.StaticBitmap(self, -1, wx.Bitmap(os.path.join(self.dirout,list_graph[i][0]), wx.BITMAP_TYPE_ANY)))
261                 self.labels.append(wx.StaticText(self, -1, list_graph[i][1]))
262                 
263         self.__set_properties()
264         self.__do_layout()
265
266     def __set_properties(self):
267         self.SetScrollRate(20, 20)   
268
269     def __do_layout(self):
270         self.sizer_1 = wx.BoxSizer(wx.VERTICAL)
271         self.sizer_2 = wx.BoxSizer(wx.VERTICAL)
272         self.sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
273         self.sizer_1.Add(self.deb)   
274         for i in range(0, len(self.listimg)):
275             self.sizer_1.Add(self.listimg[i], 1, wx.ALIGN_CENTER_HORIZONTAL, 0)
276             self.sizer_1.Add(self.labels[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
277         self.sizer_2.Add(self.sizer_1, 1, wx.EXPAND, 0)
278         self.SetSizer(self.sizer_1)
279         self.sizer_1.Fit(self)
280        
281
282 def open_antiprofil(panel, AntiProfile, encoding) :
283     DictAnti = ReadProfileAsDico(AntiProfile, True, encoding)
284     panel.AntiProfNB = aui.AuiNotebook(panel, -1, wx.DefaultPosition)
285     for i in range(0, panel.parametres['clnb']):
286         tabantiprofile = ProfListctrlPanel(panel, panel, DictAnti[str(i + 1)], True, i + 1)
287         panel.AntiProfNB.AddPage(tabantiprofile, 'classe %s' % str(i + 1))
288     panel.TabChdSim.AddPage(panel.AntiProfNB, 'Antiprofils')
289
290
291
292 class OpenCHDS():
293     def __init__(self, parent, corpus, parametres, Alceste=False):
294        #sep = u'\n ' 
295        sep=' '
296        self.parent = parent
297        self.corpus = corpus
298        self.parametres = parametres
299        self.pathout = PathOut(parametres['ira'])
300        self.pathout.basefiles(ChdTxtPathOut)
301        DictPathOut = self.pathout 
302        self.DictPathOut = DictPathOut
303        self.dictpathout = DictPathOut
304        self.parent = parent
305
306        Profile = DictPathOut['PROFILE_OUT']
307        AntiProfile = DictPathOut['ANTIPRO_OUT']
308        self.encoding = self.corpus.parametres['syscoding']
309        if isinstance(self.corpus, Corpus) :
310             self.corpus.make_ucecl_from_R(self.pathout['uce'])
311             corpname = self.corpus.parametres['corpus_name']
312        else :
313            corpname = self.corpus.parametres['name']
314
315        clnb = parametres['clnb']
316        dlg = progressbar(self, maxi = 4 + clnb) 
317        self.clnb = clnb 
318        print 'lecture des profils'
319        dlg.Update(2, u'lecture des profils')
320  
321        DictProfile = ReadProfileAsDico(Profile, Alceste, self.encoding)
322        self.DictProfile = DictProfile
323        self.cluster_size = []
324        #print 'lecture des antiprofils'
325        #DictAnti = ReadProfileAsDico(self, AntiProfile, Alceste, self.encoding)
326
327        panel = wx.Panel(parent, -1)
328        sizer1 = wx.BoxSizer(wx.VERTICAL)
329
330        if os.path.exists(DictPathOut['pre_rapport']):
331            with codecs.open(DictPathOut['pre_rapport'], 'r', self.encoding) as f :
332                 txt = f.read()
333            self.debtext = txt
334        else :
335            self.debtext = ''
336 #       panel.chd_toolbar = wx.ToolBar(panel, -1, wx.DefaultPosition, wx.DefaultSize, wx.TB_FLAT | wx.TB_NODIVIDER)
337 #       panel.chd_toolbar.SetToolBitmapSize(wx.Size(16, 16))
338
339        if isinstance(self.corpus, Corpus) :
340            panel.corpus = self.corpus
341        else :
342            panel.tableau = self.corpus
343        panel.dictpathout = self.DictPathOut
344        panel.pathout = self.DictPathOut
345        panel.parent = self.parent
346        panel.DictProfile = self.DictProfile
347        panel.cluster_size = self.cluster_size
348        panel.debtext = self.debtext
349
350 #       self.ID_rapport = wx.NewId()
351 #       #rap_img = wx.Image(os.path.join(self.parent.images_path,'icone_rap_16.png'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
352 #       #panel.chd_toolbar.AddLabelTool(self.ID_rapport, "rapport", rap_img, shortHelp=u"Produire le rapport", longHelp=u"Exporter un rapport en texte simple")
353 #       butrap = wx.Button(panel.chd_toolbar, self.ID_rapport, u"Rapport ")
354 #       panel.chd_toolbar.AddControl(butrap)
355 #       
356 #       panel.chd_toolbar.Realize()
357 #       sizer1.Add(panel.chd_toolbar,0, wx.EXPAND, 5)
358
359        #self.TabChdSim = wx.aui.AuiNotebook(self.parent.nb, -1, wx.DefaultPosition)
360        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
361        panel.TabChdSim = aui.AuiNotebook(panel, -1, wx.DefaultPosition)
362        panel.TabChdSim.SetAGWWindowStyleFlag(notebook_flags)
363        panel.TabChdSim.SetArtProvider(aui.ChromeTabArt())
364        sizer1.Add(panel.TabChdSim,10, wx.EXPAND, 5)
365        panel.SetSizer(sizer1)
366        sizer1.Fit(panel)
367        
368
369        if isinstance(self.corpus, Corpus) :
370            panel.TabChdSim.corpus = corpus
371            panel.TabChdSim.corpus.dictpathout = self.DictPathOut
372        else :
373            panel.TabChdSim.tableau = corpus
374            panel.TabChdSim.tableau.dictpathout = self.DictPathOut
375        panel.parametres = self.parametres
376        self.panel = panel
377
378        self.notenb = self.parent.nb.GetPageCount()
379
380            
381        if os.path.exists(self.DictPathOut['liste_graph_chd']) :
382            list_graph = read_list_file(self.DictPathOut['liste_graph_chd'], self.encoding)
383            CHD = GraphPanelDendro(panel.TabChdSim, DictPathOut, list_graph, txt = self.debtext)
384            panel.TabChdSim.AddPage(CHD,'CHD')
385                
386        panel.ProfNB = aui.AuiNotebook(panel, -1, wx.DefaultPosition)
387        panel.ProfNB.SetArtProvider(aui.ChromeTabArt())
388        #self.ProfNB.SetTabCtrlHeight(100)
389        #panel.AntiProfNB = aui.AuiNotebook(panel, -1, wx.DefaultPosition)
390        if os.path.exists(DictPathOut['prof_seg']) :
391             prof_seg = ReadProfileAsDico(DictPathOut['prof_seg'], False, self.encoding)
392             self.prof_seg_nb = aui.AuiNotebook(panel, -1, wx.DefaultPosition)
393        for i in range(0, clnb):
394             self.cluster_size.append(DictProfile[str(i + 1)][0][0:3]) 
395             dlg.Update(3+i, 'Classe %i' %(i+1))
396             ind = '/'.join(DictProfile[str(i + 1)][0][0:2])
397             indpour = ' - '.join([ind, DictProfile[str(i + 1)][0][2]])
398             self.tabprofile = ProfListctrlPanel(self.parent, self.panel, DictProfile[str(i + 1)], Alceste, i + 1)
399             #self.tabantiprofile = ProfListctrlPanel(self.parent, self, DictAnti[str(i + 1)], Alceste, i + 1)
400             panel.ProfNB.AddPage(self.tabprofile, 'classe %s %s(%s%%)' % (str(i + 1), sep, indpour))
401             #panel.AntiProfNB.AddPage(self.tabantiprofile, 'classe %s' % str(i + 1))
402             if os.path.exists(DictPathOut['prof_seg']) :
403                 self.tab_prof_seg = ProfListctrlPanel(self.parent, self, prof_seg[str(i + 1)], False, i + 1)
404                 self.prof_seg_nb.AddPage(self.tab_prof_seg, 'classe %i' % (i + 1))
405
406        if clnb > 2 :
407            self.TabAFC = aui.AuiNotebook(panel.TabChdSim, -1, wx.DefaultPosition)
408            log.info('read AFC') 
409            list_graph=read_list_file(DictPathOut['liste_graph_afc'], self.encoding)
410            self.tabAFCGraph = GraphPanelAfc(self.TabAFC, DictPathOut, list_graph, self.clnb, coding=self.encoding)
411            self.TabAFC.AddPage(self.tabAFCGraph, 'AFC')
412            
413            if os.path.exists(self.DictPathOut['afc_facteur']) :
414                dictrow, first = ReadList(self.DictPathOut['afc_facteur'], self.encoding)
415                self.TabAFC_facteur = ListForSpec(self.parent, parametres, dictrow, first)
416                #dictrow, first = ReadList(self.DictPathOut['afc_row'], self.encoding)
417                #self.TabAFC_ligne = ListForSpec(self.parent, self.parametres, dictrow, first)
418                #dictrow, first = ReadList(self.DictPathOut['afc_col'], self.encoding)
419                #self.TabAFC_colonne = ListForSpec(parent, self.parametres, dictrow, first)
420                self.TabAFC.AddPage(self.TabAFC_facteur, 'Facteurs')
421                #self.TabAFC.AddPage(self.TabAFC_colonne, u'Colonnes')
422                #self.TabAFC.AddPage(self.TabAFC_ligne, u'Lignes')
423            
424            sizer_3 = wx.BoxSizer(wx.VERTICAL)
425            self.parent.nb_panel_2 = wx.Panel(panel.TabChdSim, -1)
426            self.parent.button_simi = wx.Button(self.parent.nb_panel_2, -1, "Voyager")
427            self.parent.simi3dpanel = simi3d(self.parent.nb_panel_2, -1)
428            sizer_3.Add(self.parent.simi3dpanel, 1, wx.EXPAND, 0)
429            sizer_3.Add(self.parent.button_simi, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
430            self.parent.nb_panel_2.SetSizer(sizer_3)
431            self.TabAFC.AddPage(self.parent.nb_panel_2, "graph 3D")
432            self.parent.Bind(wx.EVT_BUTTON, self.onsimi, self.parent.button_simi)
433        
434        panel.TabChdSim.AddPage(panel.ProfNB, 'Profils')
435        #panel.TabChdSim.AddPage(panel.AntiProfNB, 'Antiprofils')
436        dlg.Update(4 + self.clnb, 'Affichage...')
437        if clnb > 2 :
438            panel.TabChdSim.AddPage(self.TabAFC, 'AFC')
439        if os.path.exists(DictPathOut['prof_seg']) :
440            panel.TabChdSim.AddPage(self.prof_seg_nb, u'Profils des segments répétés')
441       
442 #       panel.Bind(wx.EVT_BUTTON, self.ongetrapport, id = self.ID_rapport)
443        self.parent.nb.AddPage(panel, 'Classification - %s' % corpname)
444        self.parent.ShowTab(True)
445        self.parent.nb.SetSelection(self.parent.nb.GetPageCount() - 1)     
446        #for pane in self.parent._mgr.GetAllPanes() :
447        #     if isinstance(pane.window, aui.AuiNotebook):
448        #         nb = pane.window
449        #         nb.SetAGWWindowStyleFlag(notebook_flags)
450        #         nb.SetArtProvider(aui.ChromeTabArt())
451        dlg.Destroy() 
452        self.parent._mgr.Update()
453         
454     def onsimi(self,event):
455         outfile = print_simi3d(self)
456         error = exec_rcode(self.parent.RPath, outfile, wait = True)
457
458 #    def ongetrapport(self, event) :
459 #        dial = PrefSimpleFile(self, self.parent, **{'mask' : '*.txt', 'title': 'Rapport'})
460 #        dial.fbb.SetValue(self.DictPathOut['rapport'])
461 #        dial.CenterOnParent()
462 #        res = dial.ShowModal()
463 #        if res == wx.ID_OK :
464 #            fileout = dial.fbb.GetValue()
465 #            dial.Destroy()
466 #            with open(fileout, 'w') as f :
467 #                f.write(self.debtext + '\n' + GetTxtProfile(self.DictProfile, self.cluster_size))
468 #            msg = u"Fini !"
469 #            dlg = wx.MessageDialog(self.parent, msg, u"Rapport", wx.OK | wx.NO_DEFAULT | wx.ICON_INFORMATION)
470 #            dlg.CenterOnParent()
471 #            dlg.ShowModal()
472 #            dlg.Destroy()
473 #        else :
474 #            dial.Destroy()
475
476 #    def on_export_classes(self, event) :
477 #        corpus = self.parent.nb.GetPage(self.parent.nb.GetSelection()).corpus
478 #        dial = PrefExport(self, self.parent)
479 #        dial.fbb.SetValue(os.path.join(os.path.dirname(corpus.dictpathout['ira']), 'export_corpus.txt'))
480 #        dial.CenterOnParent()
481 #        res = dial.ShowModal()
482 #        if res == wx.ID_OK :
483 #            if dial.radio_type.GetSelection() == 0 : alc = True
484 #            else : alc = False
485 #            if dial.radio_lem.GetSelection() == 0 : lem = True
486 #            else : lem = False
487 #            self.corpus.export_corpus_classes(dial.fbb.GetValue(), alc = alc, lem = lem)
488 #            msg = u"Fini !"
489 #            dial.Destroy()
490 #            dlg = wx.MessageDialog(self.parent, msg, u"Export", wx.OK | wx.NO_DEFAULT | wx.ICON_INFORMATION)
491 #            dlg.CenterOnParent()
492 #            dlg.ShowModal()
493 #            dlg.Destroy()
494
495 #    def onprofseg(self, event):
496 #        #try :
497 #            print 'plus de bug profseg'
498 #            print self.parametres
499 #            corpus = self.parent.nb.GetPage(self.parent.nb.GetSelection()).corpus
500 #            ProfileSegment(self.parent, self.dictpathout, self.parametres, corpus)
501 #        #except :
502 #        #    BugReport(self.parent)
503 #
504 #    def onproftype(self, event):
505 #        try :
506 #            corpus = self.parent.nb.GetPage(self.parent.nb.GetSelection()).corpus
507 #            ProfilType(self.parent, corpus)
508 #        except :
509 #            BugReport(self.parent)
510 #
511 #    def oncolored(self,evt) :
512 #        dial = PrefSimpleFile(self, self.parent, **{'mask' : '*.html', 'title': 'Corpus en couleur'})
513 #        dial.fbb.SetValue(os.path.join(os.path.dirname(self.corpus.dictpathout['ira']), 'corpus_couleur.html'))
514 #        dial.CenterOnParent()
515 #        res = dial.ShowModal()
516 #        if res == wx.ID_OK :
517 #            fileout = dial.fbb.GetValue()
518 #            dial.Destroy()
519 #            txt = self.corpus.make_colored_corpus()
520 #            with open(fileout, 'w') as f :
521 #                f.write(txt)
522 #            msg = u"Fini !\nVoulez-vous ouvrir le corpus dans votre navigateur ?"
523 #            dlg = wx.MessageDialog(self.parent, msg, u"Corpus en couleur", wx.NO | wx.YES | wx.NO_DEFAULT | wx.ICON_QUESTION)
524 #            dlg.CenterOnParent()
525 #            if dlg.ShowModal() == wx.ID_YES :
526 #                webbrowser.open(fileout)
527 #            dlg.Destroy()
528
529     def onclusterstat(self, evt) :
530         dial = PrefSimpleFile(self, self.parent, **{'mask' : '*.csv', 'title': 'Stat par classe'})
531         dial.fbb.SetValue( os.path.join(os.path.dirname(self.corpus.dictpathout['ira']), 'stat_par_classe.csv'))
532         dial.CenterOnParent()
533         res = dial.ShowModal()
534         if res == wx.ID_OK :
535             fileout = dial.fbb.GetValue()
536             dial.Destroy()
537             print fileout
538             self.corpus.get_stat_by_cluster(fileout)
539             msg = u"Fini !"
540             dlg = wx.MessageDialog(self.parent, msg, u"Stat par classe", wx.OK | wx.NO_DEFAULT | wx.ICON_INFORMATION)
541             dlg.CenterOnParent()
542             if dlg.ShowModal() == wx.ID_OK :
543                 dlg.Destroy()
544
545     #def onsearchf(self, evt) :
546     #    if 'FrameSearch' not in dir(self.panel) :
547     #        self.panel.FrameSearch = SearchFrame(self.parent, -1, u"Rechercher...", self.corpus)
548     #    self.panel.FrameSearch.Show()
549     
550         
551
552 def PrintRapport(self, corpus, parametres, istxt = True):
553     #if sys.platform == 'win32':
554     #    sep = '\r\n'
555     #else:
556     sep = '\n'
557     txt = """
558 +-+-+-+-+-+-+-+-+
559 |i|R|a|M|u|T|e|Q| - %s
560 +-+-+-+-+-+-+-+-+
561
562
563 """ % datetime.datetime.now().ctime()
564     if istxt :
565         totocc = corpus.gettotocc()
566         txt += u'nombre de textes: %i%s' % (corpus.getucinb(), sep)
567         txt += u'nombre de segments de textes: %i%s' % (corpus.getucenb(), sep)
568         txt += u'nombre de formes: %i%s' % (len(corpus.formes), sep)
569         txt += u'nombre d\'occurrences: %i%s' % (totocc, sep)
570         txt += u'moyenne d\'occurrences par forme: %f%s' % (float(totocc) / float(len(self.corpus.formes)), sep)
571         txt += u'nombre de lemmes: %i%s' % (len(corpus.lems), sep)
572         txt += u'nombre de formes actives: %i%s' % (corpus.getactivesnb(1), sep)
573         txt += u'nombre de formes supplémentaires: %i%s' % (corpus.getactivesnb(2), sep)
574         txt += u'nombre de formes actives de fréquence >= %i: %i%s' % (parametres['eff_min_forme'], parametres['nbactives'], sep)
575         txt += u'moyenne d\'occurrences par uce :%f%s' % (float(totocc) / float(corpus.getucenb()), sep)
576         if 'tailleuc1' in parametres :
577             if parametres['classif_mode'] == 0 :
578                 txt += u'taille rst1 / rst2: %i / %i - %i / %i%s' % (parametres['tailleuc1'], parametres['tailleuc2'], parametres['lenuc1'], parametres['lenuc2'], sep)
579     else :
580         self.Ucenb = self.nbind
581         txt += u'nombre d\'individus : %i%s' % (self.nbind, sep)
582         txt += u'nombre de classes : %i%s' % (self.clnb, sep)
583     if istxt :
584         txt += u'nombre de classes : %i%s' % (parametres['clnb'], sep)
585         if parametres['classif_mode'] == 0 or parametres['classif_mode'] == 1 :
586             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)
587         elif self.parametres['classif_mode'] == 2 :
588             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)
589     else :
590         txt += u'%i uce classées sur %i (%.2f%%)%s' % (self.ucecla, self.Ucenb, (float(self.ucecla) / float(self.Ucenb)) * 100, sep)
591  
592     txt += """
593 ###########################
594 temps d'analyse : %s
595 ###########################
596 """ % parametres.get('time', '')
597     with open(self.pathout['pre_rapport'], 'w') as f :
598         f.write(txt)
599
600 class dolexlayout :
601     def __init__(self, ira, corpus, parametres):
602         self.pathout = PathOut(dirout = parametres['pathout'])
603         self.corpus = corpus
604         self.dictpathout = StatTxtPathOut(parametres['pathout'])
605         #self.corpus.read_corpus_from_shelves(self.corpus.dictpathout['db'])
606         self.parent = ira
607         self.encoding = self.corpus.parametres['syscoding']
608         self.parametres = parametres
609
610         self.DictSpec, first = ReadList(self.dictpathout['tablespecf'], self.corpus.parametres['syscoding'])
611         self.DictType, firstt = ReadList(self.dictpathout['tablespect'], self.corpus.parametres['syscoding'])
612         self.DictEff, firsteff = ReadList(self.dictpathout['tableafcm'], self.corpus.parametres['syscoding'])
613         self.DictEffType, firstefft = ReadList(self.dictpathout['tabletypem'], self.corpus.parametres['syscoding'])
614         self.DictEffRelForme, firsteffrelf = ReadList(self.dictpathout['eff_relatif_forme'], self.corpus.parametres['syscoding']) 
615         self.DictEffRelType, firsteffrelt = ReadList(self.dictpathout['eff_relatif_type'], self.corpus.parametres['syscoding'])    
616         
617         self.TabStat = aui.AuiNotebook(ira.nb, -1, wx.DefaultPosition)
618         self.TabStat.parametres = parametres
619         self.ListPan = ListForSpec(ira, self.parent, self.DictSpec, first)
620         self.ListPant = ListForSpec(ira, self.parent, self.DictType, firstt)
621         self.ListPanEff = ListForSpec(ira, self.parent, self.DictEff, firsteff)
622         self.ListPanEffType = ListForSpec(ira, self.parent, self.DictEffType, firstefft)
623         self.ListPanEffRelForme = ListForSpec(ira, self.parent, self.DictEffRelForme, firsteffrelf)
624         self.ListPanEffRelType = ListForSpec(ira, self.parent, self.DictEffRelType, firsteffrelt)
625         
626         self.TabStat.AddPage(self.ListPan, u'formes') 
627         self.TabStat.AddPage(self.ListPant, u'Types')
628         self.TabStat.AddPage(self.ListPanEff, u'Effectifs formes')
629         self.TabStat.AddPage(self.ListPanEffType, u'Effectifs Type')
630         self.TabStat.AddPage(self.ListPanEffRelForme, u'Effectifs relatifs formes')
631         self.TabStat.AddPage(self.ListPanEffRelType, u'Effectifs relatifs Type')
632         if self.parametres['clnb'] > 2 :
633            self.TabAFC = aui.AuiNotebook(self.TabStat, -1, wx.DefaultPosition)
634            list_graph=read_list_file(self.dictpathout['liste_graph_afcf'], encoding = self.encoding)
635            self.tabAFCGraph = GraphPanelAfc(self.TabAFC, self.dictpathout, list_graph, self.parametres['clnb'], itempath ='liste_graph_afcf', coding = self.encoding)
636            self.TabAFC.AddPage(self.tabAFCGraph, 'AFC formes')
637            list_graph=read_list_file(self.dictpathout['liste_graph_afct'], encoding = self.encoding)
638            self.tabAFCTGraph = GraphPanelAfc(self.TabAFC, self.dictpathout, list_graph, self.parametres['clnb'], itempath ='liste_graph_afct', coding=self.encoding)
639            self.TabAFC.AddPage(self.tabAFCTGraph, 'AFC type')
640            self.TabStat.AddPage(self.TabAFC, 'AFC')
641            
642         
643         ira.nb.AddPage(self.TabStat, u'Spécificités')
644         
645         self.TabStat.corpus = self.corpus
646         ira.nb.SetSelection(self.parent.nb.GetPageCount() - 1)
647         ira.ShowAPane("Tab_content")
648
649 class StatLayout:
650     def __init__(self, ira, corpus, parametres):
651         self.pathout = PathOut(dirout = parametres['pathout'])
652         self.corpus = corpus
653         self.ira = ira
654         self.read_result()
655         self.TabStat = aui.AuiNotebook(ira.nb, -1, wx.DefaultPosition)
656         self.TabStat.parametres = parametres
657 #        CHD = GraphPanel(panel.TabChdSim, DictPathOut, list_graph, txt = self.debtext)
658          #      panel.TabChdSim.AddPage(CHD,'CHD')
659
660         #self.TabStatTot = wx.TextCtrl(self.TabStat, -1, style=wx.NO_BORDER | wx.TE_MULTILINE | wx.TE_RICH2)
661         list_graph = [['zipf.png', 'zipf']]
662         self.TabStatTot = GraphPanel(ira.nb, self.pathout, list_graph, self.result['glob'])
663         #self.TabStatTot.write(self.result['glob'])
664         self.TabStat.AddPage(self.TabStatTot, 'global')
665         for item in self.result:
666             if item != 'glob':
667                 datam = [['forme', 'nb']]
668                 self.ListPan = ListPanel(ira, self, self.result[item])
669                 self.TabStat.AddPage(self.ListPan, item) 
670         ira.nb.AddPage(self.TabStat, 'Stat')
671         ira.nb.SetSelection(ira.nb.GetPageCount() - 1)
672         ira.ShowAPane("Tab_content")
673
674     def read_result(self) :
675         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'}
676         self.result = {}
677         for key in lcle :
678             with open(self.pathout[lcle[key]], 'r') as f :
679                 self.result[key] = [line.split(';') for line in f.read().splitlines()]
680                 self.result[key] = dict([[i,[line[0],int(line[1]), line[2]]] for i, line in enumerate(self.result[key])])
681         with open(self.pathout['glob.txt'], 'r') as f :
682             self.result['glob'] = f.read()
683
684 class GraphPanelDendro(wx.Panel):
685     def __init__(self,parent, dico, list_graph, txt=False):
686         wx.Panel.__init__(self,parent)
687         self.graphnb = 1
688         self.dictpathout = dico
689         self.dirout = os.path.dirname(self.dictpathout['ira'])
690         self.list_graph = list_graph
691         self.parent = self.GetParent()#parent
692         self.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, "Arial"))
693         self.labels = []
694         self.listimg = []
695         self.tabchd = self.parent.GetParent()
696         self.ira = self.tabchd.GetParent()
697         self.panel_1 = wx.ScrolledWindow(self, -1, style=wx.TAB_TRAVERSAL)
698         self.panel_1.SetBackgroundColour('white')
699         self.deb = wx.StaticText(self.panel_1, -1, txt)
700         dendro_img = wx.Image(os.path.join(self.ira.images_path,'but_dendro.png'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
701         self.butdendro = wx.BitmapButton(self, -1, dendro_img)
702         
703         for i in range(0,len(list_graph)):
704             if os.path.exists(os.path.join(self.dirout,list_graph[i][0])) :
705                 self.listimg.append(wx.StaticBitmap(self.panel_1, -1, wx.Bitmap(os.path.join(self.dirout,list_graph[i][0]), wx.BITMAP_TYPE_ANY)))
706                 self.labels.append(wx.StaticText(self.panel_1, -1, list_graph[i][1]))
707                 
708         self.__set_properties()
709         self.__do_layout()
710
711     def __set_properties(self):
712         self.panel_1.EnableScrolling(True,True)
713         #self.panel_1.SetSize((1000,1000))
714         self.panel_1.SetScrollRate(20, 20)
715         self.Bind(wx.EVT_BUTTON, self.ondendro, self.butdendro)
716         self.param = {'width' : 700,
717                        'height': 500,
718                        'type_dendro': 0,
719                        'color_nb': 0,
720                        'taille_classe' : True,
721                        'type_tclasse' : 0
722                      }
723         self.type_dendro = [ u"phylogram", u"cladogram", u"fan", u"unrooted", u"radial" ]
724
725     def __do_layout(self):    
726         self.sizer_1 = wx.BoxSizer(wx.VERTICAL)
727         self.sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
728         self.sizer_3 = wx.BoxSizer(wx.VERTICAL)
729         self.sizer_3.Add(self.deb)
730         self.sizer_2.Add(self.butdendro, 0, 0, 0)
731         for i in range(0, len(self.listimg)):
732             self.sizer_3.Add(self.listimg[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
733             self.sizer_3.Add(self.labels[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
734         self.panel_1.SetSizer(self.sizer_3)
735         self.sizer_2.Add(self.panel_1, 1, wx.EXPAND, 0)
736         self.SetSizer(self.sizer_2) 
737
738     def make_param(self, dial):
739         self.param['width'] = dial.m_spinCtrl2.GetValue()
740         self.param['height'] = dial.m_spinCtrl1.GetValue()
741         self.param['type_dendro'] = dial.m_choice1.GetSelection()
742         self.param['color_nb'] = dial.m_radioBox1.GetSelection()
743         self.param['taille_classe'] = dial.m_checkBox1.GetValue()
744         self.param['type_tclasse'] = dial.m_radioBox2.GetSelection()
745
746     def make_dendro(self) :
747         while os.path.exists(os.path.join(self.dirout, 'dendrogamme_' + str(self.graphnb)+'.png')) :
748             self.graphnb += 1
749         fileout = ffr(os.path.join(self.dirout,'dendrogamme_' + str(self.graphnb)+'.png'))
750         width = self.param['width']
751         height = self.param['height']
752         type_dendro = self.type_dendro[self.param['type_dendro']]
753         if self.param['taille_classe'] :
754             tclasse = 'TRUE'
755         else :
756             tclasse = 'FALSE'
757         if self.param['color_nb'] == 0 :
758             bw = 'FALSE'
759         else :
760             bw = 'TRUE'
761         if self.param['type_tclasse'] == 0 :
762             histo='FALSE'
763         else :
764             histo = 'TRUE'
765         dendro_path = self.dictpathout['Rdendro']
766         classe_path = self.dictpathout['uce']
767         txt = """
768         library(ape)
769         load("%s")
770         source("%s")
771         classes <- read.csv2("%s", row.names=1)
772         classes <- classes[,1]
773         open_file_graph("%s", width=%i, height=%i)
774         plot.dendropr(tree.cut1$tree.cl, classes, type.dendro="%s", histo=%s, bw=%s, lab=NULL, tclasse=%s)
775         """ % (ffr(dendro_path), ffr(self.ira.RscriptsPath['Rgraph']), ffr(classe_path), ffr(fileout), width, height, type_dendro, histo, bw, tclasse)
776         
777         tmpfile = tempfile.mktemp()
778         with open(tmpfile, 'w') as f :
779             f.write(txt)
780         error = exec_rcode(self.ira.RPath, tmpfile, wait=True) 
781         check_Rresult(self.ira, error)
782         self.list_graph.append([fileout, 'Dendrogramme CHD1 - %s' %  type_dendro])
783         print_liste(self.dictpathout['liste_graph_chd'], self.list_graph)
784         self.sizer_3.Add(wx.StaticBitmap(self.panel_1, -1, wx.Bitmap(fileout, wx.BITMAP_TYPE_ANY)), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
785         self.sizer_3.Add(wx.StaticText(self.panel_1,-1, 'Dendrogramme CHD1 - %s' %  type_dendro), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
786         self.sizer_3.Fit(self.panel_1)
787         self.Layout()
788         self.panel_1.Scroll(0,self.panel_1.GetScrollRange(wx.VERTICAL))
789
790
791     def ondendro(self, evt):
792         dial = PrefDendro(self.ira, self.param)
793         val = dial.ShowModal()
794         if val == wx.ID_OK :
795             self.make_param(dial)
796             self.make_dendro()
797
798
799
800 class OpenCorpus :
801     def __init__(self, ira, parametres) :
802         #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)
803         self.panel = CopusPanel(ira, parametres)
804         ira.nb.AddPage(self.panel, 'Description %s' % parametres['corpus_name'])
805         #self.text.write(DoConf().totext(parametres))
806         ira.nb.SetSelection(ira.nb.GetPageCount() - 1)
807         ira.ShowAPane("Tab_content")
808
809 class CopusPanel(wx.Panel) :
810     def __init__(self, parent, parametres) :
811         wx.Panel.__init__ ( self, parent, id = wx.ID_ANY, pos = wx.DefaultPosition, size = wx.Size( 500,300 ), style = wx.TAB_TRAVERSAL )
812         self.parametres = parametres
813         fgSizer5 = wx.FlexGridSizer( 0, 2, 0, 0 )
814         fgSizer5.SetFlexibleDirection( wx.BOTH )
815         fgSizer5.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED )        
816         self.fgSizer5 = fgSizer5
817         
818         self.m_staticText18 = wx.StaticText( self, wx.ID_ANY, u"Description du corpus", wx.DefaultPosition, wx.DefaultSize, 0 )
819
820         self.m_staticText18.Wrap( -1 )
821         fgSizer5.Add( self.m_staticText18, 0, wx.ALL, 5 )
822         
823         self.m_staticText19 = wx.StaticText( self, wx.ID_ANY, u"", wx.DefaultPosition, wx.DefaultSize, 0 )
824         self.m_staticText19.Wrap( -1 )
825         fgSizer5.Add( self.m_staticText19, 0, wx.ALL, 5 )
826
827         self.m_staticText20 = wx.StaticText( self, wx.ID_ANY, u"Nom", wx.DefaultPosition, wx.DefaultSize, 0 )
828         self.m_staticText20.Wrap( -1 )
829         fgSizer5.Add( self.m_staticText20, 0, wx.ALL, 5 )
830         
831         self.m_staticText21 = wx.StaticText( self, wx.ID_ANY, parametres['corpus_name'], wx.DefaultPosition, wx.DefaultSize, 0 )
832         self.m_staticText21.Wrap( -1 )
833         fgSizer5.Add( self.m_staticText21, 0, wx.ALL, 5 )
834
835         description = {'lang' : u'langue',
836                         'encoding' : u'encodage'}
837
838         keys = ['lang', 'encoding', 'originalpath', 'pathout', 'date', 'time']
839
840         self.addkeys(keys, description)
841
842         self.m_staticText18 = wx.StaticText( self, wx.ID_ANY, u"Paramètres", wx.DefaultPosition, wx.DefaultSize, 0 )
843         self.m_staticText18.Wrap( -1 )
844         fgSizer5.Add( self.m_staticText18, 0, wx.ALL, 5 )
845         
846         self.m_staticText19 = wx.StaticText( self, wx.ID_ANY, u"", wx.DefaultPosition, wx.DefaultSize, 0 )
847         self.m_staticText19.Wrap( -1 )
848         fgSizer5.Add( self.m_staticText19, 0, wx.ALL, 5 )
849
850         keys = ['ucemethod', 'ucesize', 'keep_caract', 'expressions']
851         self.addkeys(keys, description)
852
853         self.m_staticText18 = wx.StaticText( self, wx.ID_ANY, u"Statistiques", wx.DefaultPosition, wx.DefaultSize, 0 )
854         self.m_staticText18.Wrap( -1 )
855         fgSizer5.Add( self.m_staticText18, 0, wx.ALL, 5 )
856         
857         self.m_staticText19 = wx.StaticText( self, wx.ID_ANY, u"", wx.DefaultPosition, wx.DefaultSize, 0 )
858         self.m_staticText19.Wrap( -1 )
859         fgSizer5.Add( self.m_staticText19, 0, wx.ALL, 5 )
860
861         keys = ['ucinb', 'ucenb', 'occurrences', 'formesnb', 'hapax']
862         self.addkeys(keys, description)
863
864         self.SetSizer( fgSizer5 )
865         self.Layout()
866
867     def addkeys(self, keys, description) :
868         for key in keys :
869             option = self.parametres.get(key,u'non défnini')
870             if isinstance(option, int) :
871                 option = `option`
872             text = wx.StaticText( self, wx.ID_ANY, description.get(key, key), wx.DefaultPosition, wx.DefaultSize, 0 )
873             text.Wrap( -1 )
874             self.fgSizer5.Add( text, 0, wx.ALL, 5 )
875
876             text = wx.StaticText( self, wx.ID_ANY, option, wx.DefaultPosition, wx.DefaultSize, 0 )
877             text.Wrap( -1 )
878             self.fgSizer5.Add( text, 0, wx.ALL, 5 )
879
880 class GraphPanelSimi(wx.Panel):
881     def __init__(self, parent, dico, list_graph):
882         wx.Panel.__init__(self,parent)
883         self.afcnb = 1
884         self.Dict = dico
885         self.dirout = os.path.dirname(self.Dict['ira'])
886         self.parent = self.GetParent()#parent
887         self.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, "courier"))
888         self.labels = []
889         self.listimg = []
890         self.tabsimi = self.parent.GetParent()
891         self.ira = self.tabsimi.GetParent()
892         self.panel_1 = wx.ScrolledWindow(self, -1, style=wx.TAB_TRAVERSAL)
893         afc_img = wx.Image(os.path.join(self.ira.images_path,'button_simi.jpg'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
894         self.butafc = wx.BitmapButton(self, -1, afc_img)
895         export_img = wx.Image(os.path.join(self.ira.images_path,'button_export.jpg'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
896         self.butexport = wx.BitmapButton(self, -1, export_img)
897         
898         for i in range(0,len(list_graph)):
899             if os.path.exists(os.path.join(self.dirout,list_graph[i][0])) and list_graph[i][0] != '' :
900                 self.listimg.append(wx.StaticBitmap(self.panel_1, -1, wx.Bitmap(os.path.join(self.dirout,list_graph[i][0]), wx.BITMAP_TYPE_ANY)))
901                 self.labels.append(wx.StaticText(self.panel_1, -1, list_graph[i][1]))
902                 
903         self.__set_properties()
904         self.__do_layout()
905
906     def __set_properties(self):
907         self.panel_1.EnableScrolling(True,True)
908         #self.panel_1.SetSize((1000,1000))
909         self.panel_1.SetScrollRate(20, 20)
910
911     def __do_layout(self):    
912         self.sizer_1 = wx.BoxSizer(wx.HORIZONTAL)
913         self.sizer_2 = wx.BoxSizer(wx.VERTICAL)
914         self.sizer_3 = wx.BoxSizer(wx.VERTICAL)
915         self.sizer_2.Add(self.butafc, 0, 0, 0)
916         self.sizer_2.Add(self.butexport, 0, 0, 0)
917         for i in range(0, len(self.listimg)):
918             self.sizer_3.Add(self.listimg[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
919             self.sizer_3.Add(self.labels[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
920         self.panel_1.SetSizer(self.sizer_3)
921         self.sizer_1.Add(self.sizer_2, 0, wx.EXPAND, 0)
922         self.sizer_1.Add(self.panel_1, 1, wx.EXPAND, 0)
923         self.SetSizer(self.sizer_1)
924
925 class DefaultTextLayout :
926     def __init__(self, ira, corpus, parametres) :
927         self.pathout = PathOut(dirout = parametres['pathout'])
928         self.ira = ira
929         self.parent = ira
930         self.parametres = parametres
931         self.corpus = corpus
932         self.dolayout()
933     
934     def dolayout(self) :
935         log.info('no layout yet')
936
937 class WordCloudLayout(DefaultTextLayout):
938     def dolayout(self):
939         #self.dictpathout = parent.corpus.dictpathout
940         #self.pathout = os.path.dirname(filename)
941         #self.corpus = parent.corpus
942     #    self.read_result()
943         self.pathout.basefiles(simipath)
944         self.Tab = aui.AuiNotebook(self.ira.nb, -1, wx.DefaultPosition)
945 #        if os.path.exists(self.pathout['liste_graph']) :
946 #            list_graph = read_list_file(self.pathout['liste_graph'])
947 #        else : 
948 #            list_graph = [['','']]
949         list_graph = [['nuage_1.png', 'Nuage']]
950         self.TabStatTot = GraphPanel(self.ira.nb, self.pathout, list_graph)
951         #self.TabStatTot.write(self.result['glob'])
952         self.Tab.AddPage(self.TabStatTot, 'Nuage')
953         self.Tab.corpus = self.corpus
954         self.Tab.parametres = self.parametres
955         self.ira.nb.AddPage(self.Tab, 'WordCloud %s' % self.parametres.get('corpus_name','corpus_name'))
956         self.ira.nb.SetSelection(self.ira.nb.GetPageCount() - 1)
957         self.ira.ShowAPane("Tab_content")
958
959 class SimiLayout(DefaultTextLayout) :
960     def dolayout(self) :
961         self.pathout.basefiles(simipath)
962         self.actives = None
963         self.indices = indices_simi
964         if os.path.exists(self.pathout['liste_graph']) :
965             list_graph = read_list_file(self.pathout['liste_graph'])
966         else : 
967             list_graph = [['','']]
968         notebook_flags =  aui.AUI_NB_DEFAULT_STYLE | aui.AUI_NB_TAB_EXTERNAL_MOVE | aui.AUI_NB_TAB_MOVE | aui.AUI_NB_TAB_FLOAT
969         self.tabsimi = aui.AuiNotebook(self.ira.nb, -1, wx.DefaultPosition)
970         self.tabsimi.SetAGWWindowStyleFlag(notebook_flags)
971         self.tabsimi.SetArtProvider(aui.ChromeTabArt())
972         self.tabsimi.corpus = self.corpus
973         self.tabsimi.parametres = self.parametres
974         self.graphpan = GraphPanelSimi(self.tabsimi, self.pathout, list_graph)
975         self.graphpan.Bind(wx.EVT_BUTTON, self.redosimi, self.graphpan.butafc)
976         self.graphpan.Bind(wx.EVT_BUTTON, self.export, self.graphpan.butexport)
977         self.tabsimi.AddPage(self.graphpan, 'Graph')
978         self.ira.nb.AddPage(self.tabsimi, 'Analyse de graph')
979         self.ira.ShowTab(True)
980         self.ira.nb.SetSelection(self.ira.nb.GetPageCount() - 1)
981         
982     def redosimi(self, evt) :
983         with open(self.pathout['selected.csv'],'r') as f :
984             selected = f.read()
985         selected = [int(val) for val in selected.splitlines()]
986         if self.actives is None :
987             with codecs.open(self.pathout['actives.csv'], 'r', self.parametres['encoding']) as f :
988                 self.actives = f.read()
989             self.actives = self.actives.splitlines()#[act for act in self.actives.splitlines()]
990         dictcol = dict([[i, [act, self.corpus.getlemeff(act)]] for i, act in enumerate(self.actives)])
991         #res = SelectColumn(self.ira, dictcol, self.actives, self.pathout['selected.csv'], selected = selected, dlg = True) 
992         #if res.ok :
993         prep = PrepSimi(self.ira, self, self.parametres,self.pathout['selected.csv'], self.actives, indices_simi, wordlist = dictcol, selected = selected)
994         if prep.val == wx.ID_OK :
995             self.parametres = prep.parametres
996
997             script = PrintSimiScript(self)
998             script.make_script()
999             pid = exec_rcode(self.ira.RPath, script.scriptout, wait = True)
1000             check_Rresult(self.ira, pid)
1001             if self.parametres['type_graph'] == 1:
1002                 if os.path.exists(self.pathout['liste_graph']):
1003                     graph_simi = read_list_file(self.pathout['liste_graph'])
1004                     graph_simi.append([os.path.basename(script.filename), script.txtgraph])
1005                 else :
1006                     graph_simi = [[os.path.basename(script.filename), script.txtgraph]]
1007                 print_liste(self.pathout['liste_graph'], graph_simi)
1008             DoConf().makeoptions([self.parametres['type']], [self.parametres], self.pathout['Analyse.ira'])
1009             if self.parametres['type_graph'] == 1:
1010                 self.graphpan.sizer_3.Add(wx.StaticBitmap(self.graphpan.panel_1, -1, wx.Bitmap(script.filename, wx.BITMAP_TYPE_ANY)), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
1011                 self.graphpan.sizer_3.Add(wx.StaticText(self.graphpan.panel_1,-1, script.txtgraph), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
1012                 self.graphpan.sizer_3.Fit(self.graphpan.panel_1)
1013                 self.graphpan.Layout()
1014                 self.graphpan.panel_1.Scroll(0,self.graphpan.panel_1.GetScrollRange(wx.VERTICAL))
1015
1016     def export(self, evt) :
1017         pass
1018    # def read_result(self) :
1019    #     #self.corpus.read_corpus_from_shelves(self.corpus.dictpathout['db'])
1020    #     #self.corpus.make_et_table()
1021    #     self.result = {}
1022    #     with open(os.path.join(self.pathout,'glob.txt'), 'r') as f :
1023    #         self.result['glob'] = f.read()
1024