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