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