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