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