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