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