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