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