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