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