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