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