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