310b3ff212a07163a5294582c708f21b0bf09775
[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, "Arial"))
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.NORMAL, 0, "Arial"))
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            #self.parent.tableau = panel.tableau
345        panel.dictpathout = self.DictPathOut
346        panel.pathout = self.DictPathOut
347        panel.parent = self.parent
348        panel.DictProfile = self.DictProfile
349        panel.cluster_size = self.cluster_size
350        panel.debtext = self.debtext
351
352 #       self.ID_rapport = wx.NewId()
353 #       #rap_img = wx.Image(os.path.join(self.parent.images_path,'icone_rap_16.png'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
354 #       #panel.chd_toolbar.AddLabelTool(self.ID_rapport, "rapport", rap_img, shortHelp=u"Produire le rapport", longHelp=u"Exporter un rapport en texte simple")
355 #       butrap = wx.Button(panel.chd_toolbar, self.ID_rapport, u"Rapport ")
356 #       panel.chd_toolbar.AddControl(butrap)
357 #       
358 #       panel.chd_toolbar.Realize()
359 #       sizer1.Add(panel.chd_toolbar,0, wx.EXPAND, 5)
360
361        #self.TabChdSim = wx.aui.AuiNotebook(self.parent.nb, -1, wx.DefaultPosition)
362        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
363        panel.TabChdSim = aui.AuiNotebook(panel, -1, wx.DefaultPosition)
364        panel.TabChdSim.SetAGWWindowStyleFlag(notebook_flags)
365        panel.TabChdSim.SetArtProvider(aui.ChromeTabArt())
366        sizer1.Add(panel.TabChdSim,10, wx.EXPAND, 5)
367        panel.SetSizer(sizer1)
368        sizer1.Fit(panel)
369        
370
371        if isinstance(self.corpus, Corpus) :
372            panel.TabChdSim.corpus = corpus
373            panel.TabChdSim.corpus.dictpathout = self.DictPathOut
374        else :
375            panel.TabChdSim.tableau = corpus
376            panel.TabChdSim.tableau.dictpathout = self.DictPathOut
377        panel.parametres = self.parametres
378        self.panel = panel
379
380        self.notenb = self.parent.nb.GetPageCount()
381
382            
383        if os.path.exists(self.DictPathOut['liste_graph_chd']) :
384            list_graph = read_list_file(self.DictPathOut['liste_graph_chd'], self.encoding)
385            CHD = GraphPanelDendro(panel.TabChdSim, DictPathOut, list_graph, txt = self.debtext)
386            panel.TabChdSim.AddPage(CHD,'CHD')
387                
388        panel.ProfNB = aui.AuiNotebook(panel, -1, wx.DefaultPosition)
389        panel.ProfNB.SetArtProvider(aui.ChromeTabArt())
390        #self.ProfNB.SetTabCtrlHeight(100)
391        #panel.AntiProfNB = aui.AuiNotebook(panel, -1, wx.DefaultPosition)
392        if os.path.exists(DictPathOut['prof_seg']) :
393             prof_seg = ReadProfileAsDico(DictPathOut['prof_seg'], False, self.encoding)
394             self.prof_seg_nb = aui.AuiNotebook(panel, -1, wx.DefaultPosition)
395        for i in range(0, clnb):
396             self.cluster_size.append(DictProfile[str(i + 1)][0][0:3]) 
397             dlg.Update(3+i, 'Classe %i' %(i+1))
398             ind = '/'.join(DictProfile[str(i + 1)][0][0:2])
399             indpour = ' - '.join([ind, DictProfile[str(i + 1)][0][2]])
400             self.tabprofile = ProfListctrlPanel(self.parent, self.panel, DictProfile[str(i + 1)], Alceste, i + 1)
401             #self.tabantiprofile = ProfListctrlPanel(self.parent, self, DictAnti[str(i + 1)], Alceste, i + 1)
402             panel.ProfNB.AddPage(self.tabprofile, 'classe %s %s(%s%%)' % (str(i + 1), sep, indpour))
403             #panel.AntiProfNB.AddPage(self.tabantiprofile, 'classe %s' % str(i + 1))
404             if os.path.exists(DictPathOut['prof_seg']) :
405                 self.tab_prof_seg = ProfListctrlPanel(self.parent, self, prof_seg[str(i + 1)], False, i + 1)
406                 self.prof_seg_nb.AddPage(self.tab_prof_seg, 'classe %i' % (i + 1))
407
408        if clnb > 2 :
409            self.TabAFC = aui.AuiNotebook(panel.TabChdSim, -1, wx.DefaultPosition)
410            log.info('read AFC') 
411            list_graph=read_list_file(DictPathOut['liste_graph_afc'], self.encoding)
412            self.tabAFCGraph = GraphPanelAfc(self.TabAFC, DictPathOut, list_graph, self.clnb, coding=self.encoding)
413            self.TabAFC.AddPage(self.tabAFCGraph, 'AFC')
414            
415            if os.path.exists(self.DictPathOut['afc_facteur']) :
416                dictrow, first = ReadList(self.DictPathOut['afc_facteur'], self.encoding)
417                self.TabAFC_facteur = ListForSpec(self.parent, parametres, dictrow, first)
418                #dictrow, first = ReadList(self.DictPathOut['afc_row'], self.encoding)
419                #self.TabAFC_ligne = ListForSpec(self.parent, self.parametres, dictrow, first)
420                #dictrow, first = ReadList(self.DictPathOut['afc_col'], self.encoding)
421                #self.TabAFC_colonne = ListForSpec(parent, self.parametres, dictrow, first)
422                self.TabAFC.AddPage(self.TabAFC_facteur, 'Facteurs')
423                #self.TabAFC.AddPage(self.TabAFC_colonne, u'Colonnes')
424                #self.TabAFC.AddPage(self.TabAFC_ligne, u'Lignes')
425            
426            sizer_3 = wx.BoxSizer(wx.VERTICAL)
427            self.parent.nb_panel_2 = wx.Panel(panel.TabChdSim, -1)
428            self.parent.button_simi = wx.Button(self.parent.nb_panel_2, -1, "Voyager")
429            self.parent.simi3dpanel = simi3d(self.parent.nb_panel_2, -1)
430            sizer_3.Add(self.parent.simi3dpanel, 1, wx.EXPAND, 0)
431            sizer_3.Add(self.parent.button_simi, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
432            self.parent.nb_panel_2.SetSizer(sizer_3)
433            self.TabAFC.AddPage(self.parent.nb_panel_2, "graph 3D")
434            self.parent.Bind(wx.EVT_BUTTON, self.onsimi, self.parent.button_simi)
435        
436        panel.TabChdSim.AddPage(panel.ProfNB, 'Profils')
437        #panel.TabChdSim.AddPage(panel.AntiProfNB, 'Antiprofils')
438        dlg.Update(4 + self.clnb, 'Affichage...')
439        if clnb > 2 :
440            panel.TabChdSim.AddPage(self.TabAFC, 'AFC')
441        if os.path.exists(DictPathOut['prof_seg']) :
442            panel.TabChdSim.AddPage(self.prof_seg_nb, u'Profils des segments répétés')
443       
444 #       panel.Bind(wx.EVT_BUTTON, self.ongetrapport, id = self.ID_rapport)
445        self.parent.nb.AddPage(panel, 'Classification - %s' % corpname)
446        self.parent.ShowTab(True)
447        self.parent.nb.SetSelection(self.parent.nb.GetPageCount() - 1)     
448        #for pane in self.parent._mgr.GetAllPanes() :
449        #     if isinstance(pane.window, aui.AuiNotebook):
450        #         nb = pane.window
451        #         nb.SetAGWWindowStyleFlag(notebook_flags)
452        #         nb.SetArtProvider(aui.ChromeTabArt())
453        dlg.Destroy() 
454        self.parent._mgr.Update()
455         
456     def onsimi(self,event):
457         outfile = print_simi3d(self)
458         error = exec_rcode(self.parent.RPath, outfile, wait = True)
459
460 #    def ongetrapport(self, event) :
461 #        dial = PrefSimpleFile(self, self.parent, **{'mask' : '*.txt', 'title': 'Rapport'})
462 #        dial.fbb.SetValue(self.DictPathOut['rapport'])
463 #        dial.CenterOnParent()
464 #        res = dial.ShowModal()
465 #        if res == wx.ID_OK :
466 #            fileout = dial.fbb.GetValue()
467 #            dial.Destroy()
468 #            with open(fileout, 'w') as f :
469 #                f.write(self.debtext + '\n' + GetTxtProfile(self.DictProfile, self.cluster_size))
470 #            msg = u"Fini !"
471 #            dlg = wx.MessageDialog(self.parent, msg, u"Rapport", wx.OK | wx.NO_DEFAULT | wx.ICON_INFORMATION)
472 #            dlg.CenterOnParent()
473 #            dlg.ShowModal()
474 #            dlg.Destroy()
475 #        else :
476 #            dial.Destroy()
477
478 #    def on_export_classes(self, event) :
479 #        corpus = self.parent.nb.GetPage(self.parent.nb.GetSelection()).corpus
480 #        dial = PrefExport(self, self.parent)
481 #        dial.fbb.SetValue(os.path.join(os.path.dirname(corpus.dictpathout['ira']), 'export_corpus.txt'))
482 #        dial.CenterOnParent()
483 #        res = dial.ShowModal()
484 #        if res == wx.ID_OK :
485 #            if dial.radio_type.GetSelection() == 0 : alc = True
486 #            else : alc = False
487 #            if dial.radio_lem.GetSelection() == 0 : lem = True
488 #            else : lem = False
489 #            self.corpus.export_corpus_classes(dial.fbb.GetValue(), alc = alc, lem = lem)
490 #            msg = u"Fini !"
491 #            dial.Destroy()
492 #            dlg = wx.MessageDialog(self.parent, msg, u"Export", wx.OK | wx.NO_DEFAULT | wx.ICON_INFORMATION)
493 #            dlg.CenterOnParent()
494 #            dlg.ShowModal()
495 #            dlg.Destroy()
496
497 #    def onprofseg(self, event):
498 #        #try :
499 #            print 'plus de bug profseg'
500 #            print self.parametres
501 #            corpus = self.parent.nb.GetPage(self.parent.nb.GetSelection()).corpus
502 #            ProfileSegment(self.parent, self.dictpathout, self.parametres, corpus)
503 #        #except :
504 #        #    BugReport(self.parent)
505 #
506 #    def onproftype(self, event):
507 #        try :
508 #            corpus = self.parent.nb.GetPage(self.parent.nb.GetSelection()).corpus
509 #            ProfilType(self.parent, corpus)
510 #        except :
511 #            BugReport(self.parent)
512 #
513 #    def oncolored(self,evt) :
514 #        dial = PrefSimpleFile(self, self.parent, **{'mask' : '*.html', 'title': 'Corpus en couleur'})
515 #        dial.fbb.SetValue(os.path.join(os.path.dirname(self.corpus.dictpathout['ira']), 'corpus_couleur.html'))
516 #        dial.CenterOnParent()
517 #        res = dial.ShowModal()
518 #        if res == wx.ID_OK :
519 #            fileout = dial.fbb.GetValue()
520 #            dial.Destroy()
521 #            txt = self.corpus.make_colored_corpus()
522 #            with open(fileout, 'w') as f :
523 #                f.write(txt)
524 #            msg = u"Fini !\nVoulez-vous ouvrir le corpus dans votre navigateur ?"
525 #            dlg = wx.MessageDialog(self.parent, msg, u"Corpus en couleur", wx.NO | wx.YES | wx.NO_DEFAULT | wx.ICON_QUESTION)
526 #            dlg.CenterOnParent()
527 #            if dlg.ShowModal() == wx.ID_YES :
528 #                webbrowser.open(fileout)
529 #            dlg.Destroy()
530
531     def onclusterstat(self, evt) :
532         dial = PrefSimpleFile(self, self.parent, **{'mask' : '*.csv', 'title': 'Stat par classe'})
533         dial.fbb.SetValue( os.path.join(os.path.dirname(self.corpus.dictpathout['ira']), 'stat_par_classe.csv'))
534         dial.CenterOnParent()
535         res = dial.ShowModal()
536         if res == wx.ID_OK :
537             fileout = dial.fbb.GetValue()
538             dial.Destroy()
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         self.TabStat.corpus = corpus
659         self.TabStat.pathout = self.pathout
660 #        CHD = GraphPanel(panel.TabChdSim, DictPathOut, list_graph, txt = self.debtext)
661          #      panel.TabChdSim.AddPage(CHD,'CHD')
662
663         #self.TabStatTot = wx.TextCtrl(self.TabStat, -1, style=wx.NO_BORDER | wx.TE_MULTILINE | wx.TE_RICH2)
664         list_graph = [['zipf.png', 'zipf']]
665         self.TabStatTot = GraphPanel(ira.nb, self.pathout, list_graph, self.result['glob'])
666         self.TabStat.AddPage(self.TabStatTot, 'global')
667         for item in self.result:
668             if item != 'glob':
669                 datam = [['forme', 'nb']]
670                 self.ListPan = ListPanel(ira, self, self.result[item])
671                 self.TabStat.AddPage(self.ListPan, ' '.join(item.split('_'))) 
672         ira.nb.AddPage(self.TabStat, '%s' % parametres['name'])
673         ira.nb.SetSelection(ira.nb.GetPageCount() - 1)
674         ira.ShowAPane("Tab_content")
675
676     def read_result(self) :
677         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'}
678         self.result = {}
679         for key in lcle :
680             with open(self.pathout[lcle[key]], 'r') as f :
681                 self.result[key] = [line.split(';') for line in f.read().splitlines()]
682                 self.result[key] = dict([[i,[line[0],int(line[1]), line[2]]] for i, line in enumerate(self.result[key])])
683         with open(self.pathout['glob.txt'], 'r') as f :
684             self.result['glob'] = f.read()
685
686 class GraphPanelDendro(wx.Panel):
687     def __init__(self,parent, dico, list_graph, txt=False):
688         wx.Panel.__init__(self,parent)
689         self.graphnb = 1
690         self.dictpathout = dico
691         self.dirout = os.path.dirname(self.dictpathout['ira'])
692         self.list_graph = list_graph
693         self.parent = self.GetParent()#parent
694         self.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, "Arial"))
695         self.labels = []
696         self.listimg = []
697         self.tabchd = self.parent.GetParent()
698         self.ira = self.tabchd.GetParent()
699         self.panel_1 = wx.ScrolledWindow(self, -1, style=wx.TAB_TRAVERSAL)
700         self.panel_1.SetBackgroundColour('white')
701         self.deb = wx.StaticText(self.panel_1, -1, txt)
702         dendro_img = wx.Image(os.path.join(self.ira.images_path,'but_dendro.png'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
703         self.butdendro = wx.BitmapButton(self, -1, dendro_img)
704         
705         for i in range(0,len(list_graph)):
706             if os.path.exists(os.path.join(self.dirout,list_graph[i][0])) :
707                 self.listimg.append(wx.StaticBitmap(self.panel_1, -1, wx.Bitmap(os.path.join(self.dirout,list_graph[i][0]), wx.BITMAP_TYPE_ANY)))
708                 self.labels.append(wx.StaticText(self.panel_1, -1, list_graph[i][1]))
709                 
710         self.__set_properties()
711         self.__do_layout()
712
713     def __set_properties(self):
714         self.panel_1.EnableScrolling(True,True)
715         #self.panel_1.SetSize((1000,1000))
716         self.panel_1.SetScrollRate(20, 20)
717         self.Bind(wx.EVT_BUTTON, self.ondendro, self.butdendro)
718         self.param = {'width' : 700,
719                        'height': 500,
720                        'type_dendro': 0,
721                        'color_nb': 0,
722                        'taille_classe' : True,
723                        'type_tclasse' : 0
724                      }
725         self.type_dendro = [ u"phylogram", u"cladogram", u"fan", u"unrooted", u"radial" ]
726
727     def __do_layout(self):    
728         self.sizer_1 = wx.BoxSizer(wx.VERTICAL)
729         self.sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
730         self.sizer_3 = wx.BoxSizer(wx.VERTICAL)
731         self.sizer_3.Add(self.deb)
732         self.sizer_2.Add(self.butdendro, 0, 0, 0)
733         for i in range(0, len(self.listimg)):
734             self.sizer_3.Add(self.listimg[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
735             self.sizer_3.Add(self.labels[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
736         self.panel_1.SetSizer(self.sizer_3)
737         self.sizer_2.Add(self.panel_1, 1, wx.EXPAND, 0)
738         self.SetSizer(self.sizer_2) 
739
740     def make_param(self, dial):
741         self.param['width'] = dial.m_spinCtrl2.GetValue()
742         self.param['height'] = dial.m_spinCtrl1.GetValue()
743         self.param['type_dendro'] = dial.m_choice1.GetSelection()
744         self.param['color_nb'] = dial.m_radioBox1.GetSelection()
745         self.param['taille_classe'] = dial.m_checkBox1.GetValue()
746         self.param['type_tclasse'] = dial.m_radioBox2.GetSelection()
747
748     def make_dendro(self) :
749         while os.path.exists(os.path.join(self.dirout, 'dendrogamme_' + str(self.graphnb)+'.png')) :
750             self.graphnb += 1
751         fileout = ffr(os.path.join(self.dirout,'dendrogamme_' + str(self.graphnb)+'.png'))
752         width = self.param['width']
753         height = self.param['height']
754         type_dendro = self.type_dendro[self.param['type_dendro']]
755         if self.param['taille_classe'] :
756             tclasse = 'TRUE'
757         else :
758             tclasse = 'FALSE'
759         if self.param['color_nb'] == 0 :
760             bw = 'FALSE'
761         else :
762             bw = 'TRUE'
763         if self.param['type_tclasse'] == 0 :
764             histo='FALSE'
765         else :
766             histo = 'TRUE'
767         dendro_path = self.dictpathout['Rdendro']
768         classe_path = self.dictpathout['uce']
769         txt = """
770         library(ape)
771         load("%s")
772         source("%s")
773         classes <- read.csv2("%s", row.names=1)
774         classes <- classes[,1]
775         open_file_graph("%s", width=%i, height=%i)
776         plot.dendropr(tree.cut1$tree.cl, classes, type.dendro="%s", histo=%s, bw=%s, lab=NULL, tclasse=%s)
777         """ % (ffr(dendro_path), ffr(self.ira.RscriptsPath['Rgraph']), ffr(classe_path), ffr(fileout), width, height, type_dendro, histo, bw, tclasse)
778         
779         tmpfile = tempfile.mktemp()
780         with open(tmpfile, 'w') as f :
781             f.write(txt)
782         error = exec_rcode(self.ira.RPath, tmpfile, wait=True) 
783         check_Rresult(self.ira, error)
784         self.list_graph.append([fileout, 'Dendrogramme CHD1 - %s' %  type_dendro])
785         print_liste(self.dictpathout['liste_graph_chd'], self.list_graph)
786         self.sizer_3.Add(wx.StaticBitmap(self.panel_1, -1, wx.Bitmap(fileout, wx.BITMAP_TYPE_ANY)), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
787         self.sizer_3.Add(wx.StaticText(self.panel_1,-1, 'Dendrogramme CHD1 - %s' %  type_dendro), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
788         self.sizer_3.Fit(self.panel_1)
789         self.Layout()
790         self.panel_1.Scroll(0,self.panel_1.GetScrollRange(wx.VERTICAL))
791
792
793     def ondendro(self, evt):
794         dial = PrefDendro(self.ira, self.param)
795         val = dial.ShowModal()
796         if val == wx.ID_OK :
797             self.make_param(dial)
798             self.make_dendro()
799
800
801
802 class OpenCorpus :
803     def __init__(self, ira, parametres) :
804         #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)
805         self.panel = CopusPanel(ira, parametres)
806         ira.nb.AddPage(self.panel, 'Description %s' % parametres['corpus_name'])
807         #self.text.write(DoConf().totext(parametres))
808         ira.nb.SetSelection(ira.nb.GetPageCount() - 1)
809         ira.ShowAPane("Tab_content")
810
811 class CopusPanel(wx.Panel) :
812     def __init__(self, parent, parametres) :
813         wx.Panel.__init__ ( self, parent, id = wx.ID_ANY, pos = wx.DefaultPosition, size = wx.Size( 500,300 ), style = wx.TAB_TRAVERSAL )
814         self.parametres = parametres
815         fgSizer5 = wx.FlexGridSizer( 0, 2, 0, 0 )
816         fgSizer5.SetFlexibleDirection( wx.BOTH )
817         fgSizer5.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED )        
818         self.fgSizer5 = fgSizer5
819         
820         self.m_staticText18 = wx.StaticText( self, wx.ID_ANY, u"Description du corpus", wx.DefaultPosition, wx.DefaultSize, 0 )
821
822         self.m_staticText18.Wrap( -1 )
823         fgSizer5.Add( self.m_staticText18, 0, wx.ALL, 5 )
824         
825         self.m_staticText19 = wx.StaticText( self, wx.ID_ANY, u"", wx.DefaultPosition, wx.DefaultSize, 0 )
826         self.m_staticText19.Wrap( -1 )
827         fgSizer5.Add( self.m_staticText19, 0, wx.ALL, 5 )
828
829         self.m_staticText20 = wx.StaticText( self, wx.ID_ANY, u"Nom", wx.DefaultPosition, wx.DefaultSize, 0 )
830         self.m_staticText20.Wrap( -1 )
831         fgSizer5.Add( self.m_staticText20, 0, wx.ALL, 5 )
832         
833         self.m_staticText21 = wx.StaticText( self, wx.ID_ANY, parametres['corpus_name'], wx.DefaultPosition, wx.DefaultSize, 0 )
834         self.m_staticText21.Wrap( -1 )
835         fgSizer5.Add( self.m_staticText21, 0, wx.ALL, 5 )
836
837         description = {'lang' : u'langue',
838                         'encoding' : u'encodage'}
839
840         keys = ['lang', 'encoding', 'originalpath', 'pathout', 'date', 'time']
841
842         self.addkeys(keys, description)
843
844         self.m_staticText18 = wx.StaticText( self, wx.ID_ANY, u"Paramètres", wx.DefaultPosition, wx.DefaultSize, 0 )
845         self.m_staticText18.Wrap( -1 )
846         fgSizer5.Add( self.m_staticText18, 0, wx.ALL, 5 )
847         
848         self.m_staticText19 = wx.StaticText( self, wx.ID_ANY, u"", wx.DefaultPosition, wx.DefaultSize, 0 )
849         self.m_staticText19.Wrap( -1 )
850         fgSizer5.Add( self.m_staticText19, 0, wx.ALL, 5 )
851
852         keys = ['ucemethod', 'ucesize', 'keep_caract', 'expressions']
853         self.addkeys(keys, description)
854
855         self.m_staticText18 = wx.StaticText( self, wx.ID_ANY, u"Statistiques", wx.DefaultPosition, wx.DefaultSize, 0 )
856         self.m_staticText18.Wrap( -1 )
857         fgSizer5.Add( self.m_staticText18, 0, wx.ALL, 5 )
858         
859         self.m_staticText19 = wx.StaticText( self, wx.ID_ANY, u"", wx.DefaultPosition, wx.DefaultSize, 0 )
860         self.m_staticText19.Wrap( -1 )
861         fgSizer5.Add( self.m_staticText19, 0, wx.ALL, 5 )
862
863         keys = ['ucinb', 'ucenb', 'occurrences', 'formesnb', 'hapax']
864         self.addkeys(keys, description)
865
866         self.SetSizer( fgSizer5 )
867         self.Layout()
868
869     def addkeys(self, keys, description) :
870         for key in keys :
871             option = self.parametres.get(key,u'non défnini')
872             if isinstance(option, int) :
873                 option = `option`
874             text = wx.StaticText( self, wx.ID_ANY, description.get(key, key), wx.DefaultPosition, wx.DefaultSize, 0 )
875             text.Wrap( -1 )
876             self.fgSizer5.Add( text, 0, wx.ALL, 5 )
877
878             text = wx.StaticText( self, wx.ID_ANY, option, wx.DefaultPosition, wx.DefaultSize, 0 )
879             text.Wrap( -1 )
880             self.fgSizer5.Add( text, 0, wx.ALL, 5 )
881
882 class DefaultTextLayout :
883     def __init__(self, ira, corpus, parametres) :
884         self.pathout = PathOut(dirout = parametres['pathout'])
885         self.ira = ira
886         self.parent = ira
887         self.parametres = parametres
888         self.corpus = corpus
889         self.dolayout()
890     
891     def dolayout(self) :
892         log.info('no layout yet')
893
894 class WordCloudLayout(DefaultTextLayout):
895     def dolayout(self):
896         #self.dictpathout = parent.corpus.dictpathout
897         #self.pathout = os.path.dirname(filename)
898         #self.corpus = parent.corpus
899     #    self.read_result()
900         self.pathout.basefiles(simipath)
901         self.Tab = aui.AuiNotebook(self.ira.nb, -1, wx.DefaultPosition)
902 #        if os.path.exists(self.pathout['liste_graph']) :
903 #            list_graph = read_list_file(self.pathout['liste_graph'])
904 #        else : 
905 #            list_graph = [['','']]
906         list_graph = [['nuage_1.png', 'Nuage']]
907         self.TabStatTot = GraphPanel(self.ira.nb, self.pathout, list_graph)
908         #self.TabStatTot.write(self.result['glob'])
909         self.Tab.AddPage(self.TabStatTot, 'Nuage')
910         self.Tab.corpus = self.corpus
911         self.Tab.parametres = self.parametres
912         self.ira.nb.AddPage(self.Tab, '%s' % self.parametres['name'])
913         self.ira.nb.SetSelection(self.ira.nb.GetPageCount() - 1)
914         self.ira.ShowAPane("Tab_content")
915
916 class SimiLayout(DefaultTextLayout) :
917     def dolayout(self) :
918         self.pathout.basefiles(simipath)
919         self.actives = None
920         self.indices = indices_simi
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         notebook_flags =  aui.AUI_NB_DEFAULT_STYLE | aui.AUI_NB_TAB_EXTERNAL_MOVE | aui.AUI_NB_TAB_MOVE | aui.AUI_NB_TAB_FLOAT
926         self.tabsimi = aui.AuiNotebook(self.ira.nb, -1, wx.DefaultPosition)
927         self.tabsimi.SetAGWWindowStyleFlag(notebook_flags)
928         self.tabsimi.SetArtProvider(aui.ChromeTabArt())
929         self.tabsimi.corpus = self.corpus
930         self.tabsimi.parametres = self.parametres
931         self.graphpan = GraphPanelSimi(self.tabsimi, self.pathout, list_graph)
932         self.graphpan.Bind(wx.EVT_BUTTON, self.redosimi, self.graphpan.butafc)
933         self.graphpan.Bind(wx.EVT_BUTTON, self.export, self.graphpan.butexport)
934         self.tabsimi.AddPage(self.graphpan, 'Graph')
935         self.ira.nb.AddPage(self.tabsimi, 'Analyse de graph')
936         self.ira.ShowTab(True)
937         self.ira.nb.SetSelection(self.ira.nb.GetPageCount() - 1)
938         
939     def redosimi(self, evt) :
940         with open(self.pathout['selected.csv'],'r') as f :
941             selected = f.read()
942         selected = [int(val) for val in selected.splitlines()]
943         if self.actives is None :
944             with codecs.open(self.pathout['actives.csv'], 'r', self.parametres['encoding']) as f :
945                 self.actives = f.read()
946             self.actives = self.actives.splitlines()#[act for act in self.actives.splitlines()]
947         if os.path.exists(self.pathout['actives_nb.csv']) :
948             with open(self.pathout['actives_nb.csv'], 'r') as f :
949                 act_nb = f.read()
950                 act_nb = act_nb.splitlines()
951             dictcol = dict([[i, [self.actives[i], int(act_nb[i])]] for i, val in enumerate(self.actives)])
952         else :
953             dictcol = dict([[i, [act, self.corpus.getlemeff(act)]] for i, act in enumerate(self.actives)])
954         #res = SelectColumn(self.ira, dictcol, self.actives, self.pathout['selected.csv'], selected = selected, dlg = True) 
955         #if res.ok :
956         prep = PrepSimi(self.ira, self, self.parametres,self.pathout['selected.csv'], self.actives, indices_simi, wordlist = dictcol, selected = selected)
957         if prep.val == wx.ID_OK :
958             self.parametres = prep.parametres
959
960             script = PrintSimiScript(self)
961             script.make_script()
962             pid = exec_rcode(self.ira.RPath, script.scriptout, wait = True)
963             check_Rresult(self.ira, pid)
964             if self.parametres['type_graph'] == 1:
965                 if self.parametres['svg'] :
966                     filename, ext = os.path.splitext(script.filename)
967                     fileout = filename + '.svg'
968                 else :
969                     fileout = script.filename
970                 if os.path.exists(self.pathout['liste_graph']):
971                     graph_simi = read_list_file(self.pathout['liste_graph'])
972                     graph_simi.append([os.path.basename(fileout), script.txtgraph])
973                 else :
974                     graph_simi = [[os.path.basename(fileout), script.txtgraph]]
975                 print_liste(self.pathout['liste_graph'], graph_simi)
976             DoConf().makeoptions([self.parametres['type']], [self.parametres], self.pathout['Analyse.ira'])
977             if self.parametres['type_graph'] == 1:
978                 if self.parametres['svg'] :
979                     self.graphpan.sizer_3.Add(hl.HyperLinkCtrl(self.graphpan.panel_1, -1, fileout, URL = fileout), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
980                 else :
981                     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)
982                 self.graphpan.sizer_3.Add(wx.StaticText(self.graphpan.panel_1,-1, script.txtgraph), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
983                 self.graphpan.sizer_3.Fit(self.graphpan.panel_1)
984                 self.graphpan.Layout()
985                 self.graphpan.panel_1.Scroll(0,self.graphpan.panel_1.GetScrollRange(wx.VERTICAL))
986
987     def export(self, evt) :
988         nb = 1
989         while os.path.exists(os.path.join(self.pathout.dirout,'graph_'+str(nb)+'.graphml')):
990             nb +=1
991         fileout = ffr(os.path.join(self.pathout.dirout,'graph_'+str(nb)+'.graphml'))
992         txt = """
993         library(igraph)
994         load("%s")
995         fileout <- "%s"
996         graph <- graph.simi$graph
997         V(graph)$x <- graph.simi$layout[,1]
998         V(graph)$y <- graph.simi$layout[,2]
999         V(graph)$weight <- graph.simi$label.cex
1000         V(graph)$colors <- vertex.label.color
1001         E(graph)$weigth <- graph.simi$we.width
1002         write.graph(graph, fileout, format = 'graphml')
1003         """ % (self.pathout['RData.RData'], fileout)
1004         filetmp = tempfile.mktemp()
1005         with open(filetmp, 'w') as f :
1006             f.write(txt)
1007         exec_rcode(self.ira.RPath, filetmp)
1008         mss = wx.MessageDialog(self.ira, fileout, u'Fichier exporté', wx.OK)
1009         mss.CenterOnParent()
1010         mss.ShowModal()
1011         mss.Destroy()
1012
1013 class DefaultMatLayout :
1014     def __init__(self, parent, tableau, parametres) :
1015         self.pathout = PathOut(dirout = parametres['pathout'])
1016         self.ira = parent
1017         self.parent = parent
1018         self.tableau = tableau
1019         self.parametres = parametres
1020         self.dolayout()
1021
1022     def dolayout(self) :
1023         pass
1024
1025 class SimiMatLayout(DefaultMatLayout) :
1026     def dolayout(self):
1027         self.pathout.basefiles(simipath)
1028         self.indices = indices_simi
1029         if os.path.exists(self.pathout['liste_graph']) :
1030             list_graph = read_list_file(self.pathout['liste_graph'])
1031         else : 
1032             list_graph = [['','']]
1033         notebook_flags =  aui.AUI_NB_DEFAULT_STYLE | aui.AUI_NB_TAB_EXTERNAL_MOVE | aui.AUI_NB_TAB_MOVE | aui.AUI_NB_TAB_FLOAT
1034         self.tabsimi = aui.AuiNotebook(self.parent.nb, -1, wx.DefaultPosition)
1035         self.tabsimi.SetAGWWindowStyleFlag(notebook_flags)
1036         self.tabsimi.SetArtProvider(aui.ChromeTabArt())
1037         self.graphpan = GraphPanelSimi(self.tabsimi, self.pathout, list_graph)
1038         self.graphpan.Bind(wx.EVT_BUTTON, self.redosimi, self.graphpan.butafc)
1039         self.graphpan.Bind(wx.EVT_BUTTON, self.export, self.graphpan.butexport)
1040         self.tabsimi.AddPage(self.graphpan, 'Graph')
1041         self.tabsimi.parametres = self.parametres
1042         self.parent.nb.AddPage(self.tabsimi, 'Analyse de graph')
1043         self.parent.ShowTab(True)
1044         self.parent.nb.SetSelection(self.parent.nb.GetPageCount() - 1)
1045
1046     def redosimi(self,evt) :
1047         with open(self.pathout['selected.csv'],'r') as f :
1048             selected = f.read()
1049         selected = [int(val) for val in selected.splitlines()]
1050         #if self.actives is None :
1051         #    with codecs.open(self.pathout['actives.csv'], 'r', self.parametres['encoding']) as f :
1052         #        self.actives = f.read()
1053         #    self.actives = self.actives.splitlines()#[act for act in self.actives.splitlines()]
1054         try :
1055             actives = [[val, self.tableau.actives[val][0]] for val in self.tableau.actives]
1056         except :
1057             actives = [[val, self.tableau.actives[val]] for val in self.tableau.actives]
1058
1059         #self.tableau.make_listactives()
1060         actives = dict([[i, val] for i, val in enumerate(actives)])
1061         #dictcol = dict([[i, [act, self.corpus.getlemeff(act)]] for i, act in enumerate(self.actives)])
1062         self.dial = PrefSimi(self.parent, -1, self.parametres, self.indices, wordlist = actives, selected = selected, actives = self.tableau.listactives)
1063         self.dial.CenterOnParent()
1064         self.val = self.dial.ShowModal()
1065         if self.val == wx.ID_OK :
1066             last = self.dial.listcol.GetFirstSelected()
1067             lastl = [self.dial.listcol.GetFirstSelected()]
1068             indexes = [self.dial.listcol.getColumnText(self.dial.listcol.GetFirstSelected(),0)]
1069             while self.dial.listcol.GetNextSelected(last) != -1:
1070                 last = self.dial.listcol.GetNextSelected(last)
1071                 lastl.append(last)
1072                 indexes.append(self.dial.listcol.getColumnText(last,0))
1073             self.column = [self.tableau.listactives.index(val) for val in indexes]
1074             self.column.sort()
1075             with open(self.pathout['selected.csv'], 'w') as f :
1076                 f.write('\n'.join([`val` for val in self.column]))
1077             self.make_param()
1078             self.dial.Destroy()
1079             self.script = PrintSimiScript(self)
1080             self.script.make_script()
1081             self.tmpfile = self.script.scriptout
1082             dlg = progressbar(self, maxi = 2)
1083             self.DoR(dlg)
1084             dlg.Destroy()
1085             if self.parametres['type_graph'] == 1:
1086                 if self.parametres['svg'] :
1087                     filename, ext = os.path.splitext(self.script.filename)
1088                     fileout = filename + '.svg'
1089                 else :
1090                     fileout = self.script.filename
1091                 if os.path.exists(self.pathout['liste_graph']):
1092                     graph_simi = read_list_file(self.pathout['liste_graph'])
1093                     graph_simi.append([os.path.basename(fileout), self.script.txtgraph])
1094                 else :
1095                     graph_simi = [[os.path.basename(fileout), self.script.txtgraph]]
1096                 print_liste(self.pathout['liste_graph'], graph_simi)            
1097             DoConf().makeoptions([self.parametres['type']], [self.parametres], self.pathout['Analyse.ira'])
1098             if self.parametres['type_graph'] == 1:
1099                 if self.parametres['svg'] :
1100                     self.graphpan.sizer_3.Add(hl.HyperLinkCtrl(self.graphpan.panel_1, -1, fileout, URL = fileout), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
1101                 else :
1102                     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)
1103                 self.graphpan.sizer_3.Add(wx.StaticText(self.graphpan.panel_1,-1, self.script.txtgraph), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
1104                 self.graphpan.sizer_3.Fit(self.graphpan.panel_1)
1105                 self.graphpan.Layout()
1106                 self.graphpan.panel_1.Scroll(0,self.graphpan.panel_1.GetScrollRange(wx.VERTICAL))
1107         else :
1108             self.dial.Destroy()
1109                
1110
1111     def make_param(self) :
1112         if self.parametres['first'] :
1113             keep_coord = False
1114         else :
1115             keep_coord = self.dial.check_coord.GetValue()
1116         #self.select = self.dial.check_colch.GetValue()
1117
1118         paramsimi = {'coeff' : self.dial.choice1.GetSelection(),
1119                           'layout' : self.dial.choice2.GetSelection(),
1120                           'type_graph' : self.dial.choice3.GetSelection(),
1121                           'arbremax' : self.dial.check1.GetValue(),
1122                           'coeff_tv' : self.dial.check_s_size.GetValue(),
1123                           'coeff_tv_nb' : self.dial.spin_tv.GetValue(),
1124                           'tvprop' : self.dial.check2.GetValue(),
1125                           'tvmin' : self.dial.spin_tvmin.GetValue(),
1126                           'tvmax' : self.dial.spin_tvmax.GetValue(),
1127                           'coeff_te' : self.dial.check3.GetValue(),
1128                           'coeff_temin' : self.dial.spin_temin.GetValue(),
1129                           'coeff_temax' : self.dial.spin_temax.GetValue(),
1130                           'label_e' : self.dial.check_elab.GetValue(),
1131                           'label_v' : self.dial.check_vlab.GetValue(),
1132                           'vcex' : self.dial.check_vcex.GetValue(),
1133                           'vcexmin' : self.dial.spin_vcexmin.GetValue(),
1134                           'vcexmax' : self.dial.spin_vcexmax.GetValue(),
1135                           'cex' : self.dial.spin_cex.GetValue(),
1136                           'seuil_ok' : self.dial.check_seuil.GetValue(),
1137                           'seuil' : self.dial.spin_seuil.GetValue(),
1138                           'cols' : self.dial.cols.GetColour(),
1139                           'cola' : self.dial.cola.GetColour(),
1140                           'width' : self.dial.spin_width.GetValue(),
1141                           'height' : self.dial.spin_height.GetValue(),
1142                           'first' : False,
1143                           'keep_coord' : keep_coord,
1144                           'alpha' : self.dial.slider_sphere.GetValue(),
1145                           'film' : self.dial.film.GetValue(),
1146                           'svg' : self.dial.choix_format.GetSelection(),
1147                           'halo' : self.dial.halo.GetValue(),
1148                           'com' : self.dial.comcheck.GetValue(),
1149                           'communities' : self.dial.choix_com.GetSelection(),
1150                           }        
1151         if 'cexfromchi' in self.parametres :
1152             paramsimi['cexfromchi'] = self.dial.checkit.GetValue()
1153         if 'sfromchi' in self.parametres :
1154             paramsimi['sfromchi'] = self.dial.checki.GetValue()
1155         if 'vlabcolor' in self.parametres :
1156            paramsimi['vlabcolor'] = self.parametres['vlabcolor']
1157         if 'check_bystar' in dir(self.dial) :
1158             paramsimi['bystar'] = self.dial.check_bystar.GetValue()
1159             paramsimi['stars'] = self.parametres['stars']
1160         self.parametres.update(paramsimi)
1161
1162     def DoR(self, dlg):
1163         if self.parametres['type_graph'] == 1 :
1164             graph = False
1165             wait = False
1166         else : 
1167             graph = True
1168             wait = True
1169         pid = exec_rcode(self.parent.RPath, self.tmpfile, wait = wait, graph = graph)
1170         if self.parametres['type_graph'] == 1 :
1171             while pid.poll() == None :
1172                 dlg.Pulse(u'R ...')
1173                 sleep(0.2)
1174             check_Rresult(self.parent, pid)
1175     
1176     def export(self, evt) : 
1177         nb = 1
1178         while os.path.exists(os.path.join(self.pathout.dirout,'graph_'+str(nb)+'.graphml')):
1179             nb +=1
1180         fileout = ffr(os.path.join(self.pathout.dirout,'graph_'+str(nb)+'.graphml'))
1181         txt = """
1182         library(igraph)
1183         load("%s")
1184         fileout <- "%s"
1185         graph <- graph.simi$graph
1186         V(graph)$x <- graph.simi$layout[,1]
1187         V(graph)$y <- graph.simi$layout[,2]
1188         V(graph)$weight <- graph.simi$label.cex
1189         V(graph)$colors <- vertex.label.color
1190         E(graph)$weigth <- graph.simi$we.width
1191         write.graph(graph, fileout, format = 'graphml')
1192         """ % (self.pathout['RData.RData'], fileout)
1193         filetmp = tempfile.mktemp()
1194         with open(filetmp, 'w') as f :
1195             f.write(txt)
1196         exec_rcode(self.ira.RPath, filetmp)
1197         mss = wx.MessageDialog(self.ira, fileout, u'Fichier exporté', wx.OK)
1198         mss.CenterOnParent()
1199         mss.ShowModal()
1200         mss.Destroy()
1201
1202         
1203 class GraphPanelSimi(wx.Panel):
1204     def __init__(self,parent, dico, list_graph):
1205         wx.Panel.__init__(self,parent)
1206         self.afcnb = 1
1207         self.Dict = dico
1208         self.dirout = os.path.dirname(self.Dict['ira'])
1209         self.parent = self.GetParent()#parent
1210         self.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, "courier"))
1211         self.labels = []
1212         self.listimg = []
1213         self.tabsimi = self.parent.GetParent()
1214         self.ira = self.tabsimi.GetParent()
1215         self.panel_1 = wx.ScrolledWindow(self, -1, style=wx.TAB_TRAVERSAL)
1216         afc_img = wx.Image(os.path.join(self.ira.images_path,'button_simi.jpg'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
1217         self.butafc = wx.BitmapButton(self, -1, afc_img)
1218         export_img = wx.Image(os.path.join(self.ira.images_path,'button_export.jpg'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
1219         self.butexport = wx.BitmapButton(self, -1, export_img)
1220         for i in range(0,len(list_graph)):
1221             if os.path.exists(os.path.join(self.dirout,list_graph[i][0])) :
1222                 filename, ext = os.path.splitext(list_graph[i][0])
1223                 if ext == '.svg' :
1224                     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])))
1225                 else :
1226                     self.listimg.append(wx.StaticBitmap(self.panel_1, -1, wx.Bitmap(os.path.join(self.dirout,list_graph[i][0]), wx.BITMAP_TYPE_ANY)))
1227                 self.labels.append(wx.StaticText(self.panel_1, -1, list_graph[i][1]))
1228                 
1229         self.__set_properties()
1230         self.__do_layout()
1231
1232     def __set_properties(self):
1233         self.panel_1.EnableScrolling(True,True)
1234         #self.panel_1.SetSize((1000,1000))
1235         self.panel_1.SetScrollRate(20, 20)
1236
1237     def __do_layout(self):    
1238         self.sizer_1 = wx.BoxSizer(wx.HORIZONTAL)
1239         self.sizer_2 = wx.BoxSizer(wx.VERTICAL)
1240         self.sizer_3 = wx.BoxSizer(wx.VERTICAL)
1241         self.sizer_2.Add(self.butafc, 0, 0, 0)
1242         self.sizer_2.Add(self.butexport, 0, 0, 0)
1243         for i in range(0, len(self.listimg)):
1244             self.sizer_3.Add(self.listimg[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
1245             self.sizer_3.Add(self.labels[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
1246         self.panel_1.SetSizer(self.sizer_3)
1247         self.sizer_1.Add(self.sizer_2, 0, wx.EXPAND, 0)
1248         self.sizer_1.Add(self.panel_1, 1, wx.EXPAND, 0)
1249         self.SetSizer(self.sizer_1)