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