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