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