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