correction labbé
[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, title = _(u"Antiprofiles").decode('utf8'), translation = False, lems=None) :
355     if not translation :
356         DictAnti = ReadProfileAsDico(AntiProfile, True, encoding)
357     else :
358         DictAnti = AntiProfile
359     panel.AntiProfNB = aui.AuiNotebook(panel, -1, wx.DefaultPosition)
360     for i in range(0, panel.parametres['clnb']):
361         tabantiprofile = ProfListctrlPanel(panel.parent, panel, DictAnti[str(i + 1)], True, i + 1, translation = translation)
362         tabantiprofile.lems = lems
363         panel.AntiProfNB.AddPage(tabantiprofile, 'classe %s' % str(i + 1))
364     panel.TabChdSim.AddPage(panel.AntiProfNB, title)
365
366 def getlemgram(corpus, lem) :
367     if not lem[6] in corpus.lems :
368         return lem[5]
369     else :
370         return corpus.lems[lem[6]].gram
371
372 class OpenCHDS():
373     def __init__(self, parent, corpus, parametres, Alceste=False):
374         #sep = u'\n '
375         sep=' '
376         self.parent = parent
377         self.corpus = corpus
378         self.parametres = parametres
379         self.pathout = PathOut(parametres['ira'])
380         self.pathout.basefiles(ChdTxtPathOut)
381         DictPathOut = self.pathout
382         self.DictPathOut = DictPathOut
383         self.dictpathout = DictPathOut
384         self.Alceste = Alceste
385
386         Profile = DictPathOut['PROFILE_OUT']
387         AntiProfile = DictPathOut['ANTIPRO_OUT']
388         self.encoding = self.parametres['encoding']
389         if isinstance(self.corpus, Corpus) :
390             self.corpus.make_ucecl_from_R(self.pathout['uce'])
391             corpname = self.corpus.parametres['corpus_name']
392         else :
393             corpname = self.corpus.parametres['matrix_name']
394             if os.path.exists(self.pathout['analyse.db']) :
395                 self.corpus.read_tableau(self.pathout['analyse.db'])
396
397         clnb = parametres['clnb']
398         dlg = progressbar(self, maxi = 4 + clnb)
399         self.clnb = clnb
400         print 'lecture des profils'
401         dlg.Update(2, _(u"Reading profiles").decode('utf8'))
402
403         DictProfile = ReadProfileAsDico(Profile, Alceste, self.encoding)
404         self.DictProfile = DictProfile
405         self.cluster_size = []
406         clusternames = {}
407         for i in range(0, clnb) :
408             clusternames[i] = ' '.join([u'%i' % (i + 1), _(u'Cluster').decode('utf8'),  u'%i' % (i + 1)])
409         if os.path.exists(self.pathout['classes_names.txt']) :
410             with codecs.open(self.pathout['classes_names.txt'], 'r', self.parent.syscoding) as f :
411                 clusternames_ = f.read()
412             clusternames_ =  dict([[i, ' '.join([`i + 1`, line])] for i, line in enumerate(clusternames_.splitlines())])
413             clusternames.update(clusternames_)
414         #print 'lecture des antiprofils'
415         #DictAnti = ReadProfileAsDico(self, AntiProfile, Alceste, self.encoding)
416
417         panel = wx.Panel(parent, -1)
418         sizer1 = wx.BoxSizer(wx.VERTICAL)
419
420         if os.path.exists(DictPathOut['pre_rapport']):
421             with codecs.open(DictPathOut['pre_rapport'], 'r', self.encoding) as f :
422                 txt = f.read()
423             self.debtext = txt
424         else :
425             self.debtext = ''
426 #       panel.chd_toolbar = wx.ToolBar(panel, -1, wx.DefaultPosition, wx.DefaultSize, wx.TB_FLAT | wx.TB_NODIVIDER)
427 #       panel.chd_toolbar.SetToolBitmapSize(wx.Size(16, 16))
428
429         if isinstance(self.corpus, Corpus) :
430             panel.corpus = self.corpus
431         else :
432             panel.tableau = self.corpus
433             #self.parent.tableau = panel.tableau
434         panel.dictpathout = self.DictPathOut
435         panel.pathout = self.DictPathOut
436         panel.parent = self.parent
437         panel.DictProfile = self.DictProfile
438         panel.cluster_size = self.cluster_size
439         panel.debtext = self.debtext
440
441 #       self.ID_rapport = wx.NewId()
442 #       #rap_img = wx.Image(os.path.join(self.parent.images_path,'icone_rap_16.png'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
443 #       #panel.chd_toolbar.AddLabelTool(self.ID_rapport, "rapport", rap_img, shortHelp=u"Produire le rapport", longHelp=u"Exporter un rapport en texte simple")
444 #       butrap = wx.Button(panel.chd_toolbar, self.ID_rapport, u"Rapport ")
445 #       panel.chd_toolbar.AddControl(butrap)
446 #
447 #       panel.chd_toolbar.Realize()
448 #       sizer1.Add(panel.chd_toolbar,0, wx.EXPAND, 5)
449
450         #self.TabChdSim = wx.aui.AuiNotebook(self.parent.nb, -1, wx.DefaultPosition)
451         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
452         panel.TabChdSim = aui.AuiNotebook(panel, -1, wx.DefaultPosition)
453         #panel.TabChdSim = LB.LabelBook(panel, -1, agwStyle = INB_TOP|INB_SHOW_ONLY_TEXT|INB_FIT_LABELTEXT)
454         panel.TabChdSim.SetAGWWindowStyleFlag(notebook_flags)
455         panel.TabChdSim.SetArtProvider(aui.ChromeTabArt())
456         sizer1.Add(panel.TabChdSim,10, wx.EXPAND, 5)
457         panel.SetSizer(sizer1)
458         sizer1.Fit(panel)
459
460
461         if isinstance(self.corpus, Corpus) :
462             panel.TabChdSim.corpus = corpus
463             panel.TabChdSim.corpus.dictpathout = self.DictPathOut
464         else :
465             panel.TabChdSim.tableau = corpus
466             panel.TabChdSim.tableau.dictpathout = self.DictPathOut
467         panel.parametres = self.parametres
468         self.panel = panel
469
470         self.notenb = self.parent.nb.GetPageCount()
471
472
473         if os.path.exists(self.DictPathOut['liste_graph_chd']) :
474             list_graph = read_list_file(self.DictPathOut['liste_graph_chd'], self.encoding)
475             CHD = GraphPanelDendro(panel.TabChdSim, DictPathOut, list_graph, txt = self.debtext)
476             panel.TabChdSim.AddPage(CHD,'CHD')
477
478
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
489
490         panel.ProfNB = aui.AuiNotebook(panel, -1, wx.DefaultPosition)
491         notebook_flags |= aui.AUI_NB_WINDOWLIST_BUTTON
492         panel.ProfNB.SetAGWWindowStyleFlag(notebook_flags)
493         for i in range(0, clnb):
494             self.cluster_size.append(DictProfile[str(i + 1)][0][0:3])
495             if isinstance(self.corpus, Corpus) :
496                 DictProfile[str(i + 1)][1:] = [val[0:5] + [getlemgram(self.corpus, val)] + val[6:] for val in DictProfile[str(i + 1)][1:]]
497             dlg.Update(3+i, 'Classe %i' %(i+1))
498             ind = '/'.join(DictProfile[str(i + 1)][0][0:2]).strip()
499             indpour = '\n'.join([ind, DictProfile[str(i + 1)][0][2]])
500             self.tabprofile = ProfListctrlPanel(self.parent, self.panel, DictProfile[str(i + 1)], Alceste, i + 1)
501             #self.tabantiprofile = ProfListctrlPanel(self.parent, self, DictAnti[str(i + 1)], Alceste, i + 1)
502             panel.ProfNB.AddPage(self.tabprofile, clusternames[i] + '\n%s%%' % indpour, True)
503             panel.ProfNB.SetPageTextColour(i, '#890909')
504             panel.ProfNB.SetRenamable(i, True)
505             #panel.AntiProfNB.AddPage(self.tabantiprofile, 'classe %s' % str(i + 1))
506             if os.path.exists(DictPathOut['prof_seg']) :
507                 self.tab_prof_seg = ProfListctrlPanel(self.parent, self, prof_seg[str(i + 1)], False, i + 1)
508                 self.prof_seg_nb.AddPage(self.tab_prof_seg, _(u"Cluster").decode('utf8') + ' %i' % (i + 1))
509         panel.ProfNB.SetSelection(0)
510
511         if clnb > 2 :
512             self.TabAFC = aui.AuiNotebook(panel.TabChdSim, -1, wx.DefaultPosition)
513             log.info('read AFC')
514             list_graph=read_list_file(DictPathOut['liste_graph_afc'], self.encoding)
515             self.tabAFCGraph = GraphPanelAfc(self.TabAFC, DictPathOut, list_graph, self.clnb, coding=self.encoding)
516             self.TabAFC.AddPage(self.tabAFCGraph, _(u"CA").decode('utf8'))
517
518             if os.path.exists(self.DictPathOut['afc_facteur']) :
519                 dictrow, first = ReadList(self.DictPathOut['afc_facteur'], self.encoding)
520                 self.TabAFC_facteur = ListForSpec(self.parent, parametres, dictrow, first[1:])
521                 #dictrow, first = ReadList(self.DictPathOut['afc_row'], self.encoding)
522                 #self.TabAFC_ligne = ListForSpec(self.parent, self.parametres, dictrow, first)
523                 #dictrow, first = ReadList(self.DictPathOut['afc_col'], self.encoding)
524                 #self.TabAFC_colonne = ListForSpec(parent, self.parametres, dictrow, first)
525                 self.TabAFC.AddPage(self.TabAFC_facteur, _(u"Factor").decode('utf8'))
526                 #self.TabAFC.AddPage(self.TabAFC_colonne, u'Colonnes')
527                 #self.TabAFC.AddPage(self.TabAFC_ligne, u'Lignes')
528
529             sizer_3 = wx.BoxSizer(wx.VERTICAL)
530             self.parent.nb_panel_2 = wx.Panel(panel.TabChdSim, -1)
531             self.parent.button_simi = wx.Button(self.parent.nb_panel_2, -1, "Voyager")
532             self.parent.simi3dpanel = simi3d(self.parent.nb_panel_2, -1)
533             sizer_3.Add(self.parent.simi3dpanel, 1, wx.EXPAND, 0)
534             sizer_3.Add(self.parent.button_simi, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
535             self.parent.nb_panel_2.SetSizer(sizer_3)
536             self.TabAFC.AddPage(self.parent.nb_panel_2, _(u"3D graph").decode('utf8'))
537             self.parent.Bind(wx.EVT_BUTTON, self.onsimi, self.parent.button_simi)
538
539         panel.TabChdSim.AddPage(panel.ProfNB, _(u"Profiles").decode('utf8'))
540         #panel.TabChdSim.AddPage(panel.AntiProfNB, 'Antiprofils')
541         dlg.Update(4 + self.clnb, 'Affichage...')
542         if clnb > 2 :
543             panel.TabChdSim.AddPage(self.TabAFC, _(u"CA").decode('utf8'))
544         if os.path.exists(DictPathOut['prof_seg']) :
545             panel.TabChdSim.AddPage(self.prof_seg_nb, _(u"Repeated segments profiles").decode('utf8'))
546
547 #       panel.Bind(wx.EVT_BUTTON, self.ongetrapport, id = self.ID_rapport)
548         if os.path.exists(os.path.join(self.parametres['pathout'], 'tgenchi2.csv')) :
549             self.parametres['tgenspec'] = os.path.join(self.parametres['pathout'], 'tgenchi2.csv')
550             TgenLayout(panel)
551
552         if os.path.exists(self.dictpathout['translations.txt']) :
553             with codecs.open(self.dictpathout['translations.txt'], 'r', 'utf8') as f:
554                 translist = f.read()
555             translist = [line.split('\t') for line in translist.splitlines()]
556             for line in translist :
557                 self.opentrans(line)
558
559         panel.TabChdSim.SetSelection(0)
560         self.parent.nb.AddPage(panel, _(u"Clustering").decode('utf8') + ' - %s' % corpname)
561         self.parent.ShowTab(True)
562         self.parent.nb.SetSelection(self.parent.nb.GetPageCount() - 1)
563         #for pane in self.parent._mgr.GetAllPanes() :
564         #     if isinstance(pane.window, aui.AuiNotebook):
565         #         nb = pane.window
566         #         nb.SetAGWWindowStyleFlag(notebook_flags)
567         #         nb.SetArtProvider(aui.ChromeTabArt())
568         dlg.Destroy()
569
570
571         self.parent._mgr.Update()
572
573     def opentrans(self, trans) :
574         prof = ReadProfileAsDico(self.dictpathout[trans[0]], False, 'utf8')
575         with codecs.open(self.dictpathout[trans[1]], 'r', 'utf8') as f :
576             lems = f.read()
577         lems = [line.split('\t') for line in lems.splitlines()]
578         lems = dict(lems)
579         open_antiprofil(self.panel, prof, 'utf8', title = trans[0], translation=True, lems=lems)
580         self.panel.lems = lems
581         self.panel.TabChdSim.SetSelection(self.panel.TabChdSim.GetPageCount() - 1)
582
583     def onsimi(self,event):
584         outfile = print_simi3d(self)
585         error = exec_rcode(self.parent.RPath, outfile, wait = True)
586
587     def onclusterstat(self, evt) :
588         dial = PrefSimpleFile(self, self.parent, **{'mask' : '*.csv', 'title': 'Stat par classe'})
589         dial.fbb.SetValue( os.path.join(os.path.dirname(self.corpus.dictpathout['ira']), 'stat_par_classe.csv'))
590         dial.CenterOnParent()
591         res = dial.ShowModal()
592         if res == wx.ID_OK :
593             fileout = dial.fbb.GetValue()
594             dial.Destroy()
595             self.corpus.get_stat_by_cluster(fileout)
596             msg = u"Fini !"
597             dlg = wx.MessageDialog(self.parent, msg, _(u"Stat by cluster").decode('utf8'), wx.OK | wx.ICON_INFORMATION)
598             dlg.CenterOnParent()
599             if dlg.ShowModal() == wx.ID_OK :
600                 dlg.Destroy()
601
602     #def onsearchf(self, evt) :
603     #    if 'FrameSearch' not in dir(self.panel) :
604     #        self.panel.FrameSearch = SearchFrame(self.parent, -1, u"Rechercher...", self.corpus)
605     #    self.panel.FrameSearch.Show()
606
607 def PrintRapport(self, corpus, parametres, istxt = True):
608     sep = '\n'
609     txt = """
610 +-+-+-+-+-+-+-+-+
611 |i|R|a|M|u|T|e|Q| - %s
612 +-+-+-+-+-+-+-+-+
613
614
615 """ % datetime.datetime.now().ctime()
616     if istxt :
617         totocc = corpus.gettotocc()
618         txt += ': '.join([_(u'Number of texts').decode('utf8'),  u'%i%s' % (corpus.getucinb(), sep)])
619         txt += ': '.join([_(u'Number of text segments').decode('utf8'),  '%i%s' % (corpus.getucenb(), sep)])
620         txt += ': '.join([_(u'Number of forms').decode('utf8'), '%i%s' % (len(corpus.formes), sep)])
621         txt += ': '.join([_(u'Number of occurrences').decode('utf8'), '%i%s' % (totocc, sep)])
622         #txt += u'moyenne d\'occurrences par forme: %f%s' % (float(totocc) / float(len(self.corpus.formes)), sep)
623         txt += ': '.join([_(u'Number of lemmas').decode('utf8'), '%i%s' % (len(corpus.lems), sep)])
624         txt += ': '.join([_(u'Number of active forms').decode('utf8'), '%i%s' % (corpus.getactivesnb(1), sep)])
625         txt += ': '.join([_(u'Number of supplementary forms').decode('utf8'), '%i%s' % (corpus.getactivesnb(2), sep)])
626         txt += ' >= '.join([_(u'Number of active forms with a frequency').decode('utf8'), '%i: %i%s' % (parametres['eff_min_forme'], parametres['nbactives'], sep)])
627         txt += ': '.join([_(u'Mean of forms by segment').decode('utf8'), '%f%s' % (float(totocc) / float(corpus.getucenb()), sep)])
628         if 'tailleuc1' in parametres :
629             if parametres['classif_mode'] == 0 :
630                 txt += ': '.join([_(u'Size of rst1 / rst2').decode('utf8'), '%i / %i - %i / %i%s' % (parametres['tailleuc1'], parametres['tailleuc2'], parametres['lenuc1'], parametres['lenuc2'], sep)])
631     else :
632         self.Ucenb = self.nbind
633         txt += ': '.join([_(u'Number of lines').decode('utf8'), '%i%s' % (self.nbind, sep)])
634         txt += ': '.join([_(u'Number of clusters').decode('utf8'), '%i%s' % (self.clnb, sep)])
635     if istxt :
636         txt += ': '.join([_(u'Number of clusters').decode('utf8'), '%i%s' % (parametres['clnb'], sep)])
637         if parametres['classif_mode'] == 0 or parametres['classif_mode'] == 1 :
638             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)])
639         elif self.parametres['classif_mode'] == 2 :
640             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)])
641     else :
642         txt += ' '.join(['%i' % self.ucecla, _(u'line classified on').decode('utf8'), '%i (%.2f%%)%s' % (self.Ucenb, (float(self.ucecla) / float(self.Ucenb)) * 100, sep)])
643
644     txt += ''.join([sep, u'###########################', sep, _(u'time').decode('utf8'), ' : %s' % parametres.get('time', ''), sep, u'###########################', sep])
645
646     with open(self.pathout['pre_rapport'], 'w') as f :
647         f.write(txt)
648
649
650 class SashList(wx.Panel) :
651     def __init__(self, parent) :
652         wx.Panel.__init__(self, parent, -1)
653         self.parent=parent
654         winids = []
655         #self.gparent=gparent
656         #self.dlist=dlist
657         #self.first = first
658         #self.menu = menu
659         # A window to the left of the client window
660         #self.listlex = listlex
661         self.leftwin1 =  wx.SashLayoutWindow(
662                 self, -1, wx.DefaultPosition, (200, 300),
663                 wx.NO_BORDER|wx.SW_3D
664                 )
665
666         self.leftwin1.SetDefaultSize((120, 1000))
667         self.leftwin1.SetOrientation(wx.LAYOUT_VERTICAL)
668         self.leftwin1.SetAlignment(wx.LAYOUT_LEFT)
669         self.leftwin1.SetBackgroundColour(wx.Colour(0, 255, 0))
670         self.leftwin1.SetSashVisible(wx.SASH_RIGHT, True)
671         self.leftwin1.SetExtraBorderSize(10)
672
673         #textWindow = wx.TextCtrl(
674         #                leftwin1, -1, "", wx.DefaultPosition, wx.DefaultSize,
675         #                wx.TE_MULTILINE|wx.SUNKEN_BORDER
676         #                )
677
678         #textWindow.SetValue("A sub window")
679
680         self.leftWindow1 = self.leftwin1
681         winids.append(self.leftwin1.GetId())
682
683         rightwin1 =  wx.SashLayoutWindow(
684                 self, -1, wx.DefaultPosition, (200, 300),
685                 wx.NO_BORDER|wx.SW_3D
686                 )
687
688         rightwin1.SetDefaultSize((120, 1000))
689         rightwin1.SetOrientation(wx.LAYOUT_VERTICAL)
690         rightwin1.SetAlignment(wx.LAYOUT_LEFT)
691         rightwin1.SetBackgroundColour(wx.Colour(0, 255, 0))
692         rightwin1.SetSashVisible(wx.SASH_RIGHT, True)
693         rightwin1.SetExtraBorderSize(10)
694         #textWindow = wx.TextCtrl(
695         #                leftwin1, -1, "", wx.DefaultPosition, wx.DefaultSize,
696         #                wx.TE_MULTILINE|wx.SUNKEN_BORDER
697         #                )
698
699         #textWindow.SetValue("A sub window")
700
701         self.rightwin1 = rightwin1
702         winids.append(rightwin1.GetId())
703
704 class TgenLayout :
705     def __init__(self, page):
706         self.page = page
707         parametres = self.page.parametres
708         ira = wx.GetApp().GetTopWindow()
709         tgenpath = os.path.join(parametres['pathout'], 'tgen.csv')
710         self.page.tgens, etoiles =  ReadList(parametres['tgenspec'], ira.syscoding, sep="\t")
711         tgen = TGen(path = tgenpath, encoding = parametres['encoding'])
712         tgen.read()
713         tgenlempath = os.path.join(parametres['pathout'], 'tgenlemchi2.csv')
714         if os.path.exists(tgenlempath) :
715             self.page.parametres['tgenlemspec'] = tgenlempath
716             self.page.tgenlem, etoiles = ReadList(self.page.parametres['tgenlemspec'], ira.syscoding, sep="\t")
717         tgentab = False
718         gparent = None
719         if 'TabChdSim' in dir(page) :
720             page = page.TabChdSim
721         for i in range(page.GetPageCount()) :
722             tab = page.GetPage(i)
723             if 'gparent' in dir(tab) :
724                 if tab.gparent is not None :
725                     gparent = tab.gparent
726             if 'tgen' in dir(tab) :
727                 if tab.tgen :
728                     tgentab = tab
729                     break
730
731         if tgentab :
732             self.page.tgentab.RefreshData(self.page.tgens)
733             self.page.tgentab.tgens = tgen.tgen
734             self.page.tgentab.tgenlem = self.page.tgenlem
735             page.SetSelection(i)
736         else :
737             self.page.tgentab = ListForSpec(ira, gparent, self.page.tgens, etoiles[1:])
738             self.page.tgentab.tgen = True
739             self.page.tgentab.tgens = tgen.tgen
740             if os.path.exists(tgenlempath) :
741                 self.page.tgentab.tgenlem = self.page.tgenlem
742             page.AddPage(self.page.tgentab, _(u'Tgens Specificities').decode('utf8'))
743             page.SetSelection(page.GetPageCount() - 1)
744
745 class dolexlayout :
746     def __init__(self, ira, corpus, parametres):
747         self.pathout = PathOut(dirout = parametres['pathout'])
748         self.corpus = corpus
749         self.dictpathout = StatTxtPathOut(parametres['pathout'])
750         #self.corpus.read_corpus_from_shelves(self.corpus.dictpathout['db'])
751         self.parent = ira
752         self.encoding = self.corpus.parametres['syscoding']
753         self.parametres = parametres
754
755         self.DictSpec, first = ReadList(self.dictpathout['tablespecf'], self.corpus.parametres['syscoding'])
756         if os.path.exists(self.pathout['banalites.csv']) :
757             self.dictban, firstban = ReadList(self.pathout['banalites.csv'], self.corpus.parametres['syscoding'])
758         self.DictType, firstt = ReadList(self.dictpathout['tablespect'], self.corpus.parametres['syscoding'])
759         self.DictEff, firsteff = ReadList(self.dictpathout['tableafcm'], self.corpus.parametres['syscoding'])
760         self.DictEffType, firstefft = ReadList(self.dictpathout['tabletypem'], self.corpus.parametres['syscoding'])
761         self.DictEffRelForme, firsteffrelf = ReadList(self.dictpathout['eff_relatif_forme'], self.corpus.parametres['syscoding'])
762         self.DictEffRelType, firsteffrelt = ReadList(self.dictpathout['eff_relatif_type'], self.corpus.parametres['syscoding'])
763         self.etoiles = firsteff[1:]
764         #sash = SashList(ira.nb)
765
766
767         self.TabStat = aui.AuiNotebook(ira.nb, -1, wx.DefaultPosition)
768         self.TabStat.parametres = parametres
769         self.ListPan = ListForSpec(ira, self, self.DictSpec, self.etoiles)
770         self.ListPan.pathout = self.pathout
771         if os.path.exists(self.pathout['banalites.csv']) :
772             self.listban = ListForSpec(ira, self, self.dictban, ['eff'] + self.etoiles, usefirst = True)
773         #self.ListPan2 = ListForSpec(sash.rightwin1, self, self.DictSpec, first)
774         self.ListPant = ListForSpec(ira, self, self.DictType, self.etoiles)
775         self.ListPant.pathout = self.pathout
776         self.ListPanEff = ListForSpec(ira, self, self.DictEff, self.etoiles)
777         self.ListPanEff.pathout = self.pathout
778         self.ListPanEffType = ListForSpec(ira, self, self.DictEffType, self.etoiles)
779         self.ListPanEffType.pathout = self.pathout
780         self.ListPanEffRelForme = ListForSpec(ira, self, self.DictEffRelForme, self.etoiles)
781         self.ListPanEffRelForme.pathout = self.pathout
782         self.ListPanEffRelType = ListForSpec(ira, self, self.DictEffRelType, self.etoiles)
783         self.ListPanEffRelType.pathout = self.pathout
784
785         self.TabStat.AddPage(self.ListPan, _(u'Forms').decode('utf8'))
786         if os.path.exists(self.pathout['banalites.csv']) :
787             self.TabStat.AddPage(self.listban, _(u'Banal forms').decode('utf8'))
788         self.TabStat.AddPage(self.ListPant, _(u'POS').decode('utf8'))
789         self.TabStat.AddPage(self.ListPanEff, _(u'Forms frequencies').decode('utf8'))
790         self.TabStat.AddPage(self.ListPanEffType, _(u'POS frequencies').decode('utf8'))
791         self.TabStat.AddPage(self.ListPanEffRelForme, _(u'Forms relative frequencies').decode('utf8'))
792         self.TabStat.AddPage(self.ListPanEffRelType, _(u'POS relative frequencies').decode('utf8'))
793         if self.parametres['clnb'] > 2 :
794             self.TabAFC = aui.AuiNotebook(self.TabStat, -1, wx.DefaultPosition)
795             list_graph=read_list_file(self.dictpathout['liste_graph_afcf'], encoding = self.encoding)
796             self.tabAFCGraph = GraphPanelAfc(self.TabAFC, self.dictpathout, list_graph, self.parametres['clnb'], itempath ='liste_graph_afcf', coding = self.encoding)
797             self.TabAFC.AddPage(self.tabAFCGraph, _(u'CA forms').decode('utf8'))
798             list_graph=read_list_file(self.dictpathout['liste_graph_afct'], encoding = self.encoding)
799             self.tabAFCTGraph = GraphPanelAfc(self.TabAFC, self.dictpathout, list_graph, self.parametres['clnb'], itempath ='liste_graph_afct', coding=self.encoding)
800             self.TabAFC.AddPage(self.tabAFCTGraph, _(u'CA POS').decode('utf8'))
801             self.TabStat.AddPage(self.TabAFC, _(u'CA').decode('utf8'))
802
803         ira.nb.AddPage(self.TabStat, ' - '.join([_(u'Specificities').decode('utf8'), self.parametres['name']]))
804         self.ira = ira
805
806         self.TabStat.corpus = self.corpus
807         self.TabStat.etoiles = self.etoiles
808         self.TabStat.pathout = self.pathout
809         if os.path.exists(os.path.join(self.parametres['pathout'], 'tgenspec.csv')) :
810             self.parametres['tgenspec'] = os.path.join(self.parametres['pathout'], 'tgenspec.csv')
811             TgenLayout(self.TabStat)
812         self.TabStat.SetSelection(0)
813         ira.nb.SetSelection(self.parent.nb.GetPageCount() - 1)
814         ira.ShowAPane("Tab_content")
815
816 class StatLayout:
817     def __init__(self, ira, corpus, parametres):
818         self.pathout = PathOut(dirout = parametres['pathout'])
819         self.corpus = corpus
820         self.ira = ira
821         self.read_result()
822         self.parametres = parametres
823         self.TabStat = aui.AuiNotebook(ira.nb, -1, wx.DefaultPosition)
824         self.TabStat.parametres = parametres
825         self.TabStat.corpus = corpus
826         self.TabStat.pathout = self.pathout
827 #        CHD = GraphPanel(panel.TabChdSim, DictPathOut, list_graph, txt = self.debtext)
828         #      panel.TabChdSim.AddPage(CHD,'CHD')
829
830         #self.TabStatTot = wx.TextCtrl(self.TabStat, -1, style=wx.NO_BORDER | wx.TE_MULTILINE | wx.TE_RICH2)
831         list_graph = [['zipf.png', 'zipf']]
832         if os.path.exists(self.pathout['segments_size.png']) :
833             list_graph.append(['segments_size.png', _(u'Taille des segments')])
834         self.TabStatTot = GraphPanel(ira.nb, self.pathout, list_graph, self.result['glob'])
835         self.TabStat.AddPage(self.TabStatTot, _(u'Abstract').decode('utf8'))
836
837         dictlabel = {'total' : _(u'Total').decode('utf8'),
838                      u'formes_actives' : _(u'Actives forms').decode('utf8'),
839                      u'formes_supplémentaires': _(u'Supplementary forms').decode('utf8'),
840                      u'hapax' : _(u'Hapax').decode('utf8'),
841                      }
842
843         for item in self.result:
844             if item != 'glob':
845                 datam = [['forme', 'nb']]
846                 self.ListPan = ListPanel(ira, self, self.result[item])
847                 self.TabStat.AddPage(self.ListPan, dictlabel[item])
848         ira.nb.AddPage(self.TabStat, '%s' % parametres['name'])
849         ira.nb.SetSelection(ira.nb.GetPageCount() - 1)
850         ira.ShowAPane("Tab_content")
851
852     def read_result(self) :
853         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'}
854         self.result = {}
855         for key in lcle :
856             with codecs.open(self.pathout[lcle[key]], 'r', sys.getdefaultencoding()) as f :
857                 self.result[key] = [line.split(';') for line in f.read().splitlines()]
858                 self.result[key] = dict([[i,[line[0],int(line[1]), line[2]]] for i, line in enumerate(self.result[key])])
859         with open(self.pathout['glob.txt'], 'r') as f :
860             self.result['glob'] = f.read()
861
862 class GraphPanelDendro(wx.Panel):
863     def __init__(self,parent, dico, list_graph, txt=False):
864         wx.Panel.__init__(self,parent)
865         self.graphnb = 1
866         self.dictpathout = dico
867         self.dirout = os.path.dirname(self.dictpathout['ira'])
868         self.pathout = self.dictpathout
869         self.list_graph = list_graph
870         self.parent = self.GetParent()#parent
871         self.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, "Arial"))
872         self.labels = []
873         self.listimg = []
874         self.tabchd = self.parent.GetParent()
875         self.ira = self.tabchd.GetParent()
876         self.panel_1 = wx.ScrolledWindow(self, -1, style=wx.TAB_TRAVERSAL)
877         self.panel_1.SetBackgroundColour('white')
878         self.deb = wx.StaticText(self.panel_1, -1, txt)
879         dendro_img = wx.Image(os.path.join(self.ira.images_path,'but_dendro.png'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
880         dendro_liste_img = wx.Image(os.path.join(self.ira.images_path,'but_dendro_liste.png'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
881         dendro_cloud_img= wx.Image(os.path.join(self.ira.images_path,'but_dendro_cloud.png'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
882         self.butdendro = wx.BitmapButton(self, -1, dendro_img)
883         self.butdendrotexte = wx.BitmapButton(self, -1, dendro_liste_img)
884         self.butdendrocloud = wx.BitmapButton(self, -1, dendro_cloud_img)
885
886         for i in range(0,len(list_graph)):
887             if os.path.exists(os.path.join(self.dirout,list_graph[i][0])) :
888                 filename, ext = os.path.splitext(list_graph[i][0])
889                 if ext == '.svg' :
890                     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])))
891                 else :
892                     self.listimg.append(wx.StaticBitmap(self.panel_1, -1, wx.Bitmap(os.path.join(self.dirout,list_graph[i][0]), wx.BITMAP_TYPE_ANY)))
893                 self.labels.append(wx.StaticText(self.panel_1, -1, list_graph[i][1]))
894
895         self.__set_properties()
896         self.__do_layout()
897
898     def __set_properties(self):
899         self.panel_1.EnableScrolling(True,True)
900         #self.panel_1.SetSize((1000,1000))
901         self.panel_1.SetScrollRate(20, 20)
902         self.panel_1.SetFocus()
903         self.Bind(wx.EVT_BUTTON, self.ondendro, self.butdendro)
904         self.Bind(wx.EVT_BUTTON, self.ondendrotexte, self.butdendrotexte)
905         self.Bind(wx.EVT_BUTTON, self.ondendrocloud, self.butdendrocloud)
906         self.param = {'width' : 700,
907                        'height': 500,
908                        'type_dendro': 0,
909                        'color_nb': 0,
910                        'taille_classe' : True,
911                        'type_tclasse' : 0,
912                        'svg' : 0
913                      }
914         self.type_dendro = [ u"phylogram", u"cladogram", u"fan", u"unrooted", u"radial" ]
915
916     def __do_layout(self):
917         self.sizer_1 = wx.BoxSizer(wx.VERTICAL)
918         self.sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
919         self.sizer_3 = wx.BoxSizer(wx.VERTICAL)
920         self.sizer_3.Add(self.deb)
921         self.sizer_1.Add(self.butdendro, 0, 0, 0)
922         self.sizer_1.Add(self.butdendrotexte, 0, 0, 0)
923         self.sizer_1.Add(self.butdendrocloud, 0, 0, 0)
924
925         for i in range(0, len(self.listimg)):
926             self.sizer_3.Add(self.listimg[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
927             self.sizer_3.Add(self.labels[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
928         self.panel_1.SetSizer(self.sizer_3)
929         self.sizer_2.Add(self.sizer_1, 0, wx.EXPAND, 0)
930         self.sizer_2.Add(self.panel_1, 1, wx.EXPAND, 0)
931         self.SetSizer(self.sizer_2)
932
933     def make_param(self, dial):
934         self.param['width'] = dial.m_spinCtrl2.GetValue()
935         self.param['height'] = dial.m_spinCtrl1.GetValue()
936         self.param['type_dendro'] = dial.m_choice1.GetSelection()
937         self.param['svg'] = dial.choice_format.GetSelection()
938         if self.param['typedendro'] == 'classique' :
939             self.param['color_nb'] = dial.m_radioBox1.GetSelection()
940             self.param['taille_classe'] = dial.m_checkBox1.GetValue()
941             self.param['type_tclasse'] = dial.m_radioBox2.GetSelection()
942         if self.param.get('translation', False) :
943             if dial.trans.GetSelection() == 0 :
944                 del self.param['translation']
945             else :
946                 self.param['translation'] = self.param['translation'][dial.trans.GetSelection()-1][1]
947
948     def make_dendro(self, dendro = 'simple') :
949         if self.param['svg'] :
950             typefile = '.svg'
951         else :
952             typefile = '.png'
953         while os.path.exists(os.path.join(self.dirout, 'dendrogramme_' + str(self.graphnb)+typefile)) :
954             self.graphnb += 1
955         fileout = ffr(os.path.join(self.dirout,'dendrogramme_' + str(self.graphnb)+typefile))
956         width = self.param['width']
957         height = self.param['height']
958         type_dendro = self.type_dendro[self.param['type_dendro']]
959         if self.param['taille_classe'] :
960             tclasse = 'TRUE'
961         else :
962             tclasse = 'FALSE'
963         if self.param['color_nb'] == 0 :
964             bw = 'FALSE'
965         else :
966             bw = 'TRUE'
967         if self.param['type_tclasse'] == 0 :
968             histo='FALSE'
969         else :
970             histo = 'TRUE'
971         if self.param['svg'] :
972             svg = 'TRUE'
973         else :
974             svg = 'FALSE'
975         dendro_path = self.dictpathout['Rdendro']
976         classe_path = self.dictpathout['uce']
977         txt = """
978         library(ape)
979         load("%s")
980         source("%s")
981         classes <- read.csv2("%s", row.names=1)
982         classes <- classes[,1]
983         """ % (ffr(dendro_path), ffr(self.ira.RscriptsPath['Rgraph']),  ffr(classe_path))
984         if dendro == 'simple' :
985             txt += """
986             open_file_graph("%s", width=%i, height=%i, svg=%s)
987             plot.dendropr(tree.cut1$tree.cl, classes, type.dendro="%s", histo=%s, bw=%s, lab=NULL, tclasse=%s)
988             """ % (ffr(fileout), width, height, svg, type_dendro, histo, bw, tclasse)
989         elif dendro == 'texte' :
990             txt += """
991             load("%s")
992             source("%s")
993             if (is.null(debsup)) {
994                 debsup <- debet
995             }
996             chistable <- chistabletot[1:(debsup-1),]
997             """ % (ffr(self.dictpathout['RData.RData']), ffr(self.ira.RscriptsPath['Rgraph']))
998             if self.param.get('translation', False) :
999                 txt += """
1000                 rn <- read.csv2("%s", header=FALSE, sep='\t')
1001                 rnchis <- row.names(chistable)
1002                 commun <- intersect(rnchis, unique(rn[,2]))
1003                 idrnchis <- sapply(commun, function(x) {which(rnchis==x)})
1004                 idrn <- sapply(commun, function(x) {which(as.vector(rn[,2])==x)[1]})
1005                 rownames(chistable)[idrnchis] <- as.vector(rn[idrn,1])
1006                 """ % ffr(self.param['translation'])
1007             txt += """
1008             open_file_graph("%s", width=%i, height=%i, svg = %s)
1009             plot.dendro.prof(tree.cut1$tree.cl, classes, chistable, nbbycl = 60, type.dendro="%s", bw=%s, lab=NULL)
1010             """ % (ffr(fileout), width, height, svg, type_dendro, bw)
1011         elif dendro == 'cloud' :
1012             txt += """
1013             load("%s")
1014             source("%s")
1015             if (is.null(debsup)) {
1016                 debsup <- debet
1017             }
1018             chistable <- chistabletot[1:(debsup-1),]
1019             open_file_graph("%s", width=%i, height=%i, svg=%s)
1020             plot.dendro.cloud(tree.cut1$tree.cl, classes, chistable, nbbycl = 300, type.dendro="%s", bw=%s, lab=NULL)
1021             """ % (ffr(self.dictpathout['RData.RData']), ffr(self.ira.RscriptsPath['Rgraph']), ffr(fileout), width, height, svg, type_dendro, bw)
1022
1023
1024         tmpfile = tempfile.mktemp()
1025         with open(tmpfile, 'w') as f :
1026             f.write(txt)
1027         busy = wx.BusyInfo(_("Please wait...").decode('utf8'), self.parent)
1028         wx.SafeYield()
1029         error = exec_rcode(self.ira.RPath, tmpfile, wait=True)
1030         del busy
1031         check_Rresult(self.ira, error)
1032         self.list_graph.append([fileout, 'Dendrogramme CHD1 - %s' %  type_dendro])
1033         print_liste(self.dictpathout['liste_graph_chd'], self.list_graph)
1034         if self.param['svg'] :
1035             self.sizer_3.Add(hl.HyperLinkCtrl(self.panel_1, -1, fileout, URL=fileout), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
1036         else :
1037             self.sizer_3.Add(wx.StaticBitmap(self.panel_1, -1, wx.Bitmap(fileout, wx.BITMAP_TYPE_ANY)), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
1038         self.sizer_3.Add(wx.StaticText(self.panel_1,-1, 'Dendrogramme CHD1 - %s' %  type_dendro), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
1039         self.sizer_3.Fit(self.panel_1)
1040         self.Layout()
1041         self.panel_1.Scroll(0,self.panel_1.GetScrollRange(wx.VERTICAL))
1042
1043
1044     def ondendro(self, evt):
1045         self.param['typedendro'] = 'classique'
1046         dial = PrefDendro(self.ira, self.param)
1047         val = dial.ShowModal()
1048         if val == wx.ID_OK :
1049             self.make_param(dial)
1050             self.make_dendro()
1051
1052     def ondendrotexte(self, evt):
1053         self.param['typedendro'] = 'texte'
1054         if os.path.exists(self.dictpathout['translations.txt']) :
1055             with codecs.open(self.dictpathout['translations.txt'], 'r', 'utf8') as f :
1056                 content = f.read()
1057             print content
1058             trans = [line.split('\t')[1] for line in content.splitlines()]
1059             trans = [[val, self.dictpathout[val]] for val in trans]
1060             self.param['translation'] = trans
1061         dial = PrefDendro(self.ira, self.param)
1062         val = dial.ShowModal()
1063         if val == wx.ID_OK :
1064             self.make_param(dial)
1065             self.make_dendro(dendro = 'texte')
1066
1067     def ondendrocloud(self, evt):
1068         self.param['typedendro'] = 'cloud'
1069         dial = PrefDendro(self.ira, self.param)
1070         val = dial.ShowModal()
1071         if val == wx.ID_OK :
1072             self.make_param(dial)
1073             self.make_dendro(dendro = 'cloud')
1074
1075 class OpenCorpus :
1076     def __init__(self, ira, parametres) :
1077         #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)
1078         self.panel = CopusPanel(ira, parametres)
1079         ira.nb.AddPage(self.panel, 'Description %s' % parametres['corpus_name'])
1080         #self.text.write(DoConf().totext(parametres))
1081         ira.nb.SetSelection(ira.nb.GetPageCount() - 1)
1082         ira.ShowAPane("Tab_content")
1083
1084 class MatLayout :
1085     def __init__(self, ira, matrix):
1086         #self.parent.content = self.csvtable
1087         self.sheet = MySheet(ira.nb)
1088         ira.nb.AddPage(self.sheet, matrix.parametres['matrix_name'])
1089         self.sheet.Populate(matrix.csvtable)
1090         self.sheet.parametres = matrix.parametres
1091         ira.nb.SetSelection(ira.nb.GetPageCount() - 1)
1092         ira.ShowAPane("Tab_content")
1093
1094 class CopusPanel(wx.Panel) :
1095     def __init__(self, parent, parametres) :
1096         wx.Panel.__init__ ( self, parent, id = wx.ID_ANY, pos = wx.DefaultPosition, size = wx.Size( 500,300 ), style = wx.TAB_TRAVERSAL )
1097         self.parametres = parametres
1098         fgSizer5 = wx.FlexGridSizer( 0, 2, 0, 0 )
1099         fgSizer5.SetFlexibleDirection( wx.BOTH )
1100         fgSizer5.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED )
1101         self.fgSizer5 = fgSizer5
1102
1103         self.m_staticText18 = wx.StaticText( self, wx.ID_ANY, _(u"Description of corpus").decode('utf8'), wx.DefaultPosition, wx.DefaultSize, 0 )
1104
1105         self.m_staticText18.Wrap( -1 )
1106         fgSizer5.Add( self.m_staticText18, 0, wx.ALL, 5 )
1107
1108         self.m_staticText19 = wx.StaticText( self, wx.ID_ANY, u"", wx.DefaultPosition, wx.DefaultSize, 0 )
1109         self.m_staticText19.Wrap( -1 )
1110         fgSizer5.Add( self.m_staticText19, 0, wx.ALL, 5 )
1111
1112         self.m_staticText20 = wx.StaticText( self, wx.ID_ANY, u"Nom", wx.DefaultPosition, wx.DefaultSize, 0 )
1113         self.m_staticText20.Wrap( -1 )
1114         fgSizer5.Add( self.m_staticText20, 0, wx.ALL, 5 )
1115
1116         self.m_staticText21 = wx.StaticText( self, wx.ID_ANY, parametres['corpus_name'], wx.DefaultPosition, wx.DefaultSize, 0 )
1117         self.m_staticText21.Wrap( -1 )
1118         fgSizer5.Add( self.m_staticText21, 0, wx.ALL, 5 )
1119
1120         description = {'lang' : _(u'Language').decode('utf8'),
1121                        'encoding' : _(u'Characters set').decode('utf8'),
1122                        'ucinb' : _(u'Number of texts').decode('utf8'),
1123                        'ucenb' : _(u'Number of text segments').decode('utf8'),
1124                        'formesnb' : _(u'Number of forms').decode('utf8'),
1125                        'hapax' : _(u'Number of hapax').decode('utf8'),
1126                       }
1127
1128         keys = ['lang', 'encoding', 'originalpath', 'pathout', 'date', 'time']
1129
1130         self.addkeys(keys, description)
1131
1132         self.m_staticText18 = wx.StaticText( self, wx.ID_ANY, u"Paramètres", wx.DefaultPosition, wx.DefaultSize, 0 )
1133         self.m_staticText18.Wrap( -1 )
1134         fgSizer5.Add( self.m_staticText18, 0, wx.ALL, 5 )
1135
1136         self.m_staticText19 = wx.StaticText( self, wx.ID_ANY, u"", wx.DefaultPosition, wx.DefaultSize, 0 )
1137         self.m_staticText19.Wrap( -1 )
1138         fgSizer5.Add( self.m_staticText19, 0, wx.ALL, 5 )
1139
1140         keys = ['ucemethod', 'ucesize', 'keep_caract', 'expressions']
1141         self.addkeys(keys, description)
1142
1143         self.m_staticText18 = wx.StaticText( self, wx.ID_ANY, u"Statistiques", wx.DefaultPosition, wx.DefaultSize, 0 )
1144         self.m_staticText18.Wrap( -1 )
1145         fgSizer5.Add( self.m_staticText18, 0, wx.ALL, 5 )
1146
1147         self.m_staticText19 = wx.StaticText( self, wx.ID_ANY, u"", wx.DefaultPosition, wx.DefaultSize, 0 )
1148         self.m_staticText19.Wrap( -1 )
1149         fgSizer5.Add( self.m_staticText19, 0, wx.ALL, 5 )
1150
1151         keys = ['ucinb', 'ucenb', 'occurrences', 'formesnb', 'hapax']
1152         self.addkeys(keys, description)
1153
1154         self.SetSizer( fgSizer5 )
1155         self.Layout()
1156
1157     def addkeys(self, keys, description) :
1158         for key in keys :
1159             option = self.parametres.get(key,u'non défini')
1160             if isinstance(option, int) :
1161                 option = `option`
1162             text = wx.StaticText( self, wx.ID_ANY, description.get(key, key), wx.DefaultPosition, wx.DefaultSize, 0 )
1163             text.Wrap( -1 )
1164             self.fgSizer5.Add( text, 0, wx.ALL, 5 )
1165
1166             text = wx.StaticText( self, wx.ID_ANY, option, wx.DefaultPosition, wx.DefaultSize, 0 )
1167             text.Wrap( -1 )
1168             self.fgSizer5.Add( text, 0, wx.ALL, 5 )
1169
1170 class DefaultTextLayout :
1171     def __init__(self, ira, corpus, parametres, cmd = False) :
1172         self.pathout = PathOut(dirout = parametres['pathout'])
1173         self.ira = ira
1174         self.parent = ira
1175         self.parametres = parametres
1176         self.corpus = corpus
1177         self.cmd = cmd
1178         self.dolayout()
1179
1180     def dolayout(self, cmd) :
1181         log.info('no layout yet')
1182
1183 class WordCloudLayout(DefaultTextLayout):
1184     def dolayout(self):
1185         self.pathout.basefiles(simipath)
1186         self.Tab = aui.AuiNotebook(self.ira.nb, -1, wx.DefaultPosition)
1187         if self.parametres['svg'] :
1188             list_graph = [['nuage_1.svg', 'Nuage']]
1189         else :
1190             list_graph = [['nuage_1.png', 'Nuage']]
1191         self.TabStatTot = GraphPanel(self.ira.nb, self.pathout, list_graph)
1192         self.Tab.AddPage(self.TabStatTot, 'Nuage')
1193         self.Tab.corpus = self.corpus
1194         self.Tab.parametres = self.parametres
1195         self.ira.nb.AddPage(self.Tab, '%s' % self.parametres['name'])
1196         self.ira.nb.SetSelection(self.ira.nb.GetPageCount() - 1)
1197         self.ira.ShowAPane("Tab_content")
1198
1199 class LabbeLayout(DefaultTextLayout):
1200     def dolayout(self):
1201         self.Tab = aui.AuiNotebook(self.ira.nb, -1, wx.DefaultPosition)
1202         #if self.parametres['svg'] :
1203         #    list_graph = [['nuage_1.svg', 'Nuage']]
1204         #else :
1205         #    list_graph = [['nuage_1.png', 'Nuage']]
1206         list_graph = [['labbe-tree.png', _(u'Ward clustering (method ward2)').decode('utf8')],
1207                      ['labbe-heatmap.png', _(u'Heatmap').decode('utf8')],
1208                      ['labbe-matrix.png', _(u'Matrix').decode('utf8')]]
1209         for val in list_graph :
1210             #self.TabStatTot = GraphPanel(self.ira.nb, self.pathout, [val])
1211             self.Tab.AddPage(GraphPanel(self.Tab, self.pathout, [val]), val[1])
1212         self.Tab.corpus = self.corpus
1213         self.Tab.parametres = self.parametres
1214         self.ira.nb.AddPage(self.Tab, u'%s' % self.parametres['name'])
1215         self.ira.nb.SetSelection(self.ira.nb.GetPageCount() - 1)
1216         self.ira.ShowAPane("Tab_content")
1217
1218 def blender(self):
1219     nodesfile = self.pathout['nodes.csv']
1220     edgesfile = self.pathout['edges.csv']
1221     jsonout = self.pathout.makenew('graphe_json', 'json')
1222     txt = """
1223     library(igraph)
1224     load("%s")
1225     source("%s")
1226     """ % (ffr(self.pathout['RData.RData']), ffr(self.parent.RscriptsPath['Rgraph']))
1227     txt += """
1228     nodesf <- "%s"
1229     edgesf <- "%s"
1230     """ % (ffr(nodesfile), ffr(edgesfile))
1231     txt += """
1232     if ("communities" %in% names(graph.simi)) {
1233         community = TRUE
1234     } else {
1235         community = FALSE
1236     }
1237     graph.to.file(graph.simi, nodesfile = nodesf, edgesfile = edgesf, community = community)
1238     """
1239     filetmp = tempfile.mktemp()
1240     with open(filetmp, 'w') as f :
1241         f.write(txt)
1242     exec_rcode(self.ira.RPath, filetmp)
1243     GraphToJson(nodesfile, edgesfile, jsonout)
1244     launchcommand(['/home/pierre/prog/blender-2.73-linux-glibc211-x86_64/blender', '-P', os.path.join(self.ira.AppliPath, 'network_to_blender.py'), jsonout])
1245
1246
1247 class SimiLayout(DefaultTextLayout) :
1248     def dolayout(self) :
1249         self.pathout.basefiles(simipath)
1250         self.actives = None
1251         self.indices = indices_simi
1252         if os.path.exists(self.pathout['liste_graph']) :
1253             list_graph = read_list_file(self.pathout['liste_graph'])
1254         else :
1255             list_graph = [['','']]
1256         if not self.cmd :
1257             notebook_flags =  aui.AUI_NB_DEFAULT_STYLE | aui.AUI_NB_TAB_EXTERNAL_MOVE | aui.AUI_NB_TAB_MOVE | aui.AUI_NB_TAB_FLOAT
1258             self.tabsimi = aui.AuiNotebook(self.ira.nb, -1, wx.DefaultPosition)
1259             self.tabsimi.SetAGWWindowStyleFlag(notebook_flags)
1260             self.tabsimi.SetArtProvider(aui.ChromeTabArt())
1261             self.tabsimi.corpus = self.corpus
1262             self.tabsimi.parametres = self.parametres
1263             self.graphpan = GraphPanelSimi(self.tabsimi, self.pathout, list_graph)
1264             self.graphpan.Bind(wx.EVT_BUTTON, self.redosimi, self.graphpan.butafc)
1265             self.graphpan.Bind(wx.EVT_BUTTON, self.export, self.graphpan.butexport)
1266             self.graphpan.Bind(wx.EVT_BUTTON, self.blender, self.graphpan.butblender)
1267             self.tabsimi.AddPage(self.graphpan, 'Graph')
1268             self.ira.nb.AddPage(self.tabsimi, _(u'Graph analysis').decode('utf8'))
1269             self.ira.ShowTab(True)
1270             self.ira.nb.SetSelection(self.ira.nb.GetPageCount() - 1)
1271
1272     def redosimi(self, evt) :
1273         redosimi(self, evt)
1274 #         with open(self.pathout['selected.csv'],'r') as f :
1275 #             selected = f.read()
1276 #         selected = [int(val) for val in selected.splitlines()]
1277 #         if self.actives is None :
1278 #             with codecs.open(self.pathout['actives.csv'], 'r', self.parametres['encoding']) as f :
1279 #                 self.actives = f.read()
1280 #             self.actives = self.actives.splitlines()#[act for act in self.actives.splitlines()]
1281 #         if os.path.exists(self.pathout['actives_nb.csv']) :
1282 #             with open(self.pathout['actives_nb.csv'], 'r') as f :
1283 #                 act_nb = f.read()
1284 #                 act_nb = act_nb.splitlines()
1285 #             dictcol = dict([[i, [self.actives[i], int(act_nb[i])]] for i, val in enumerate(self.actives)])
1286 #         else :
1287 #             dictcol = dict([[i, [act, self.corpus.getlemeff(act)]] for i, act in enumerate(self.actives)])
1288 #         #res = SelectColumn(self.ira, dictcol, self.actives, self.pathout['selected.csv'], selected = selected, dlg = True)
1289 #         #if res.ok :
1290 #         prep = PrepSimi(self.ira, self, self.parametres,self.pathout['selected.csv'], self.actives, indices_simi, wordlist = dictcol, selected = selected)
1291 #         if prep.val == wx.ID_OK :
1292 #             self.parametres = prep.parametres
1293 #
1294 #             script = PrintSimiScript(self)
1295 #             script.make_script()
1296 #             pid = exec_rcode(self.ira.RPath, script.scriptout, wait = True)
1297 #             check_Rresult(self.ira, pid)
1298 #             if self.parametres['type_graph'] in [1,3] :
1299 #                 if self.parametres['svg'] :
1300 #                     filename, ext = os.path.splitext(script.filename)
1301 #                     fileout = filename + '.svg'
1302 #                 elif self.parametres['type_graph'] == 3 :
1303 #                     fileout = script.filename
1304 #                     parametres = {'gexffile' :  fileout,
1305 #                                   'dirout' : os.path.dirname(fileout),
1306 #                                   'titre': 'Le titre',
1307 #                                   #'nodemin': self.param['txt_min'],
1308 #                                   #'nodemax': self.param['txt_max'],
1309 #                                   #'bargraphw' : 60*int(self.param['clnb']),
1310 #                     }
1311 #                     web = WebExport(self.ira, parametres)
1312 #                     fileout = web.exportsimi()
1313 #                 else :
1314 #                     fileout = script.filename
1315 #                 if os.path.exists(self.pathout['liste_graph']):
1316 #                     graph_simi = read_list_file(self.pathout['liste_graph'])
1317 #                     graph_simi.append([os.path.basename(fileout), script.txtgraph])
1318 #                 else :
1319 #                     graph_simi = [[os.path.basename(fileout), script.txtgraph]]
1320 #                 print_liste(self.pathout['liste_graph'], graph_simi)
1321 #             DoConf().makeoptions([self.parametres['type']], [self.parametres], self.pathout['Analyse.ira'])
1322 #             if self.parametres['type_graph'] in [1,3] :
1323 #                 if self.parametres['svg'] or self.parametres['type_graph'] == 3 :
1324 #                     self.graphpan.sizer_3.Add(hl.HyperLinkCtrl(self.graphpan.panel_1, -1, fileout, URL = fileout), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
1325 #                 else :
1326 #                     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)
1327 #                 self.graphpan.sizer_3.Add(wx.StaticText(self.graphpan.panel_1,-1, script.txtgraph), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
1328 #                 self.graphpan.sizer_3.Fit(self.graphpan.panel_1)
1329 #                 self.graphpan.Layout()
1330 #                 self.graphpan.panel_1.Scroll(0,self.graphpan.panel_1.GetScrollRange(wx.VERTICAL))
1331
1332     def export(self, evt) :
1333         nb = 1
1334         while os.path.exists(os.path.join(self.pathout.dirout,'graph_'+str(nb)+'.graphml')):
1335             nb +=1
1336         fileout = ffr(os.path.join(self.pathout.dirout,'graph_'+str(nb)+'.graphml'))
1337         txt = """
1338         library(igraph)
1339         load("%s")
1340         source("%s")
1341         fileout <- "%s"
1342         graph <- graph.simi$graph
1343         V(graph)$x <- graph.simi$layout[,1]
1344         V(graph)$y <- graph.simi$layout[,2]
1345         if (length(graph.simi$label.cex == 1)) {
1346             V(graph)$weight <- graph.simi$eff
1347         } else {
1348             V(graph)$weight <- graph.simi$label.cex
1349         }
1350         V(graph)$rcolor <- vertex.label.color
1351         V(graph)$frequences <- graph.simi$mat.eff
1352         V(graph)$label <- as.character(graph.simi$v.label)
1353         E(graph)$weight <- graph.simi$we.width
1354         write.graph(graph, fileout, format = 'graphml')
1355         #saveAsGEXF(graph, filepath = fileout)
1356         """ % (ffr(self.pathout['RData.RData']), ffr(self.parent.RscriptsPath['simi']), fileout)
1357         filetmp = tempfile.mktemp()
1358         with open(filetmp, 'w') as f :
1359             f.write(txt)
1360         exec_rcode(self.ira.RPath, filetmp)
1361         mss = wx.MessageDialog(self.ira, fileout, _(u'File exported').decode('utf8'), wx.OK)
1362         mss.CenterOnParent()
1363         mss.ShowModal()
1364         mss.Destroy()
1365
1366     def blender(self, evt):
1367         blender(self)
1368
1369
1370 class DefaultMatLayout :
1371     def __init__(self, parent, tableau, parametres) :
1372         self.pathout = PathOut(dirout = parametres['pathout'])
1373         self.ira = parent
1374         self.parent = parent
1375         self.tableau = tableau
1376         self.parametres = parametres
1377         if os.path.exists(self.pathout['analyse.db']) :
1378             self.tableau.read_tableau(self.pathout['analyse.db'])
1379         self.dolayout()
1380         self.ira.nb.SetSelection(self.ira.nb.GetPageCount() - 1)
1381         self.ira.ShowAPane("Tab_content")
1382
1383     def dolayout(self) :
1384         pass
1385
1386 class FreqLayout(DefaultMatLayout) :
1387     def dolayout(self) :
1388         self.tab = wx.html.HtmlWindow(self.ira.nb, -1)
1389         #self.tab = wx.html2.WebView.New(self)
1390         res = normpath_win32(self.pathout['resultats.html']).replace('\\','/')
1391         self.tab.LoadPage(res)
1392         #self.tab.LoadURL(res)
1393         self.tab.parametres = self.parametres
1394         self.ira.nb.AddPage(self.tab, ' - '.join([_(u"Frequency").decode('utf8'), self.parametres['name']]))
1395
1396
1397 class Chi2Layout(DefaultMatLayout) :
1398     def dolayout(self):
1399         self.tab = wx.html.HtmlWindow(self.ira.nb, -1)
1400         if "gtk2" in wx.PlatformInfo:
1401             self.tab.SetStandardFonts()
1402         res = normpath_win32(self.pathout['resultats-chi2.html']).replace('\\','/')
1403         self.tab.LoadPage(res)
1404         self.tab.parametres = self.parametres
1405         self.ira.nb.AddPage(self.tab, ' - '.join([u"Chi2", self.parametres['name']]))
1406         #self.ira.nb.SetSelection(self.ira.nb.GetPageCount() - 1)
1407         #self.ira.ShowAPane("Tab_content")
1408
1409
1410 class ProtoLayout(DefaultMatLayout) :
1411     def dolayout(self) :
1412         list_graph = [['proto.png', _(u'Prototypical analysis').decode('utf8')]]
1413         #self.Tab = aui.AuiNotebook(self.ira.nb, -1, wx.DefaultPosition)
1414         #if self.parametres['svg'] :
1415         #    list_graph = [['nuage_1.svg', 'Nuage']]
1416         #else :
1417         #    list_graph = [['nuage_1.png', 'Nuage']]
1418         self.TabProto = GraphPanel(self.ira.nb, self.pathout, list_graph)
1419         #self.Tab.AddPage(self.TabProto, 'Analyse Prototypique')
1420         #self.Tab.corpus = self.corpus
1421         self.TabProto.parametres = self.parametres
1422         self.ira.nb.AddPage(self.TabProto, ' - '.join([_(u'Prototypical analysis').decode('utf8'), self.parametres['name']]))
1423         #self.ira.nb.SetSelection(self.ira.nb.GetPageCount() - 1)
1424         #self.ira.ShowAPane("Tab_content")
1425
1426
1427 class SimiMatLayout(DefaultMatLayout) :
1428     def dolayout(self):
1429         self.pathout.basefiles(simipath)
1430         self.indices = indices_simi
1431         if os.path.exists(self.pathout['liste_graph']) :
1432             list_graph = read_list_file(self.pathout['liste_graph'])
1433         else :
1434             list_graph = [['','']]
1435         notebook_flags =  aui.AUI_NB_DEFAULT_STYLE | aui.AUI_NB_TAB_EXTERNAL_MOVE | aui.AUI_NB_TAB_MOVE | aui.AUI_NB_TAB_FLOAT
1436         self.tabsimi = aui.AuiNotebook(self.parent.nb, -1, wx.DefaultPosition)
1437         self.tabsimi.SetAGWWindowStyleFlag(notebook_flags)
1438         self.tabsimi.SetArtProvider(aui.ChromeTabArt())
1439         self.graphpan = GraphPanelSimi(self.tabsimi, self.pathout, list_graph)
1440         self.graphpan.Bind(wx.EVT_BUTTON, self.redosimi, self.graphpan.butafc)
1441         self.graphpan.Bind(wx.EVT_BUTTON, self.export, self.graphpan.butexport)
1442         self.graphpan.Bind(wx.EVT_BUTTON, self.blender, self.graphpan.butblender)
1443         self.tabsimi.AddPage(self.graphpan, 'Graph')
1444         self.tabsimi.parametres = self.parametres
1445         self.parent.nb.AddPage(self.tabsimi, ' - '.join([_(u'Graph analysis').decode('utf8'), self.parametres['name']]))
1446         #self.parent.ShowTab(True)
1447         #self.parent.nb.SetSelection(self.parent.nb.GetPageCount() - 1)
1448
1449     def redosimi(self,evt) :
1450         with open(self.pathout['selected.csv'],'r') as f :
1451             selected = f.read()
1452         selected = [int(val) for val in selected.splitlines()]
1453         #if self.actives is None :
1454         #    with codecs.open(self.pathout['actives.csv'], 'r', self.parametres['encoding']) as f :
1455         #        self.actives = f.read()
1456         #    self.actives = self.actives.splitlines()#[act for act in self.actives.splitlines()]
1457         try :
1458             actives = [[val, self.tableau.actives[val][0]] for val in self.tableau.actives]
1459         except :
1460             actives = [[val, self.tableau.actives[val]] for val in self.tableau.actives]
1461
1462         #self.tableau.make_listactives()
1463         actives = dict([[i, val] for i, val in enumerate(actives)])
1464         #dictcol = dict([[i, [act, self.corpus.getlemeff(act)]] for i, act in enumerate(self.actives)])
1465         self.dial = PrefSimi(self.parent, -1, self.parametres, self.indices, wordlist = actives, selected = selected, actives = self.tableau.listactives)
1466         self.dial.CenterOnParent()
1467         self.val = self.dial.ShowModal()
1468         if self.val == wx.ID_OK :
1469             last = self.dial.listcol.GetFirstSelected()
1470             lastl = [self.dial.listcol.GetFirstSelected()]
1471             indexes = [self.dial.listcol.getColumnText(self.dial.listcol.GetFirstSelected(),0)]
1472             while self.dial.listcol.GetNextSelected(last) != -1:
1473                 last = self.dial.listcol.GetNextSelected(last)
1474                 lastl.append(last)
1475                 indexes.append(self.dial.listcol.getColumnText(last,0))
1476             self.column = [self.tableau.listactives.index(val) for val in indexes]
1477             self.column.sort()
1478             with open(self.pathout['selected.csv'], 'w') as f :
1479                 f.write('\n'.join([`val` for val in self.column]))
1480             self.make_param()
1481             self.dial.Destroy()
1482             self.script = PrintSimiScript(self)
1483             self.script.make_script()
1484             self.tmpfile = self.script.scriptout
1485             dlg = progressbar(self, maxi = 2)
1486             self.DoR(dlg)
1487             dlg.Destroy()
1488             if self.parametres['type_graph'] == 1:
1489                 if self.parametres['svg'] :
1490                     filename, ext = os.path.splitext(self.script.filename)
1491                     fileout = filename + '.svg'
1492                 else :
1493                     fileout = self.script.filename
1494                 fileout = normpath_win32(fileout)
1495                 if os.path.exists(self.pathout['liste_graph']):
1496                     graph_simi = read_list_file(self.pathout['liste_graph'])
1497                     graph_simi.append([os.path.basename(fileout), self.script.txtgraph])
1498                 else :
1499                     graph_simi = [[os.path.basename(fileout), self.script.txtgraph]]
1500                 print_liste(self.pathout['liste_graph'], graph_simi)
1501             DoConf().makeoptions([self.parametres['type']], [self.parametres], self.pathout['Analyse.ira'])
1502             if self.parametres['type_graph'] == 1:
1503                 if self.parametres['svg'] :
1504                     self.graphpan.sizer_3.Add(hl.HyperLinkCtrl(self.graphpan.panel_1, -1, fileout, URL = fileout), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
1505                 else :
1506                     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)
1507                 self.graphpan.sizer_3.Add(wx.StaticText(self.graphpan.panel_1,-1, self.script.txtgraph), 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
1508                 self.graphpan.sizer_3.Fit(self.graphpan.panel_1)
1509                 self.graphpan.Layout()
1510                 self.graphpan.panel_1.Scroll(0,self.graphpan.panel_1.GetScrollRange(wx.VERTICAL))
1511         else :
1512             self.dial.Destroy()
1513
1514
1515     def make_param(self) :
1516         if self.parametres['first'] :
1517             keep_coord = False
1518         else :
1519             keep_coord = self.dial.check_coord.GetValue()
1520         #self.select = self.dial.check_colch.GetValue()
1521
1522         paramsimi = {'coeff' : self.dial.choice1.GetSelection(),
1523                           'layout' : self.dial.choice2.GetSelection(),
1524                           'type_graph' : self.dial.choice3.GetSelection(),
1525                           'arbremax' : self.dial.check1.GetValue(),
1526                           'coeff_tv' : self.dial.check_s_size.GetValue(),
1527                           'coeff_tv_nb' : self.dial.spin_tv.GetValue(),
1528                           'tvprop' : self.dial.check2.GetValue(),
1529                           'tvmin' : self.dial.spin_tvmin.GetValue(),
1530                           'tvmax' : self.dial.spin_tvmax.GetValue(),
1531                           'coeff_te' : self.dial.check3.GetValue(),
1532                           'coeff_temin' : self.dial.spin_temin.GetValue(),
1533                           'coeff_temax' : self.dial.spin_temax.GetValue(),
1534                           'label_e' : self.dial.check_elab.GetValue(),
1535                           'label_v' : self.dial.check_vlab.GetValue(),
1536                           'vcex' : self.dial.check_vcex.GetValue(),
1537                           'vcexmin' : self.dial.spin_vcexmin.GetValue(),
1538                           'vcexmax' : self.dial.spin_vcexmax.GetValue(),
1539                           'cex' : self.dial.spin_cex.GetValue(),
1540                           'seuil_ok' : self.dial.check_seuil.GetValue(),
1541                           'seuil' : self.dial.spin_seuil.GetValue(),
1542                           'cols' : self.dial.cols.GetColour(),
1543                           'cola' : self.dial.cola.GetColour(),
1544                           'width' : self.dial.spin_width.GetValue(),
1545                           'height' : self.dial.spin_height.GetValue(),
1546                           'first' : False,
1547                           'keep_coord' : keep_coord,
1548                           'alpha' : self.dial.slider_sphere.GetValue(),
1549                           'film' : self.dial.film.GetValue(),
1550                           'svg' : self.dial.choix_format.GetSelection(),
1551                           'halo' : self.dial.halo.GetValue(),
1552                           'com' : self.dial.comcheck.GetValue(),
1553                           'communities' : self.dial.choix_com.GetSelection(),
1554                           'edgecurved' : self.dial.check_curved.GetValue(),
1555                           }
1556         if 'cexfromchi' in self.parametres :
1557             paramsimi['cexfromchi'] = self.dial.checkit.GetValue()
1558         if 'sfromchi' in self.parametres :
1559             paramsimi['sfromchi'] = self.dial.checki.GetValue()
1560         if 'vlabcolor' in self.parametres :
1561             paramsimi['vlabcolor'] = self.parametres['vlabcolor']
1562         if 'check_bystar' in dir(self.dial) :
1563             paramsimi['bystar'] = self.dial.check_bystar.GetValue()
1564             paramsimi['stars'] = self.parametres['stars']
1565         self.parametres.update(paramsimi)
1566
1567     def DoR(self, dlg):
1568         if self.parametres['type_graph'] == 1 :
1569             graph = False
1570             wait = False
1571         else :
1572             graph = True
1573             wait = True
1574         pid = exec_rcode(self.parent.RPath, self.tmpfile, wait = wait, graph = graph)
1575         if self.parametres['type_graph'] == 1 :
1576             while pid.poll() == None :
1577                 dlg.Pulse(u'R ...')
1578                 sleep(0.2)
1579             check_Rresult(self.parent, pid)
1580
1581     def export(self, evt) :
1582         nb = 1
1583         while os.path.exists(os.path.join(self.pathout.dirout,'graph_'+str(nb)+'.graphml')):
1584             nb +=1
1585         fileout = ffr(os.path.join(self.pathout.dirout,'graph_'+str(nb)+'.graphml'))
1586         txt = """
1587         library(igraph)
1588         load("%s")
1589         source("%s")
1590         fileout <- "%s"
1591         graph <- graph.simi$graph
1592         V(graph)$x <- graph.simi$layout[,1]
1593         V(graph)$y <- graph.simi$layout[,2]
1594         if (length(graph.simi$label.cex == 1)) {
1595             V(graph)$weight <- graph.simi$mat.eff
1596         } else {
1597             V(graph)$weight <- graph.simi$label.cex
1598         }
1599         V(graph)$color <- vertex.label.color
1600         V(graph)$frequences <- graph.simi$mat.eff
1601         V(graph)$fprop <- graph.simi$mat.eff/nrow(dm)
1602         V(graph)$label <- as.character(graph.simi$v.label)
1603         E(graph)$weight <- graph.simi$we.width
1604         write.graph(graph, fileout, format = 'graphml')
1605         #saveAsGEXF(graph, filepath = fileout)
1606         """ % (ffr(self.pathout['RData.RData']), ffr(self.parent.RscriptsPath['simi']), fileout)
1607         filetmp = tempfile.mktemp()
1608         with open(filetmp, 'w') as f :
1609             f.write(txt)
1610         exec_rcode(self.ira.RPath, filetmp)
1611         mss = wx.MessageDialog(self.ira, fileout, _(u'File exported').decode('utf8'), wx.OK)
1612         mss.CenterOnParent()
1613         mss.ShowModal()
1614         mss.Destroy()
1615
1616     def blender(self, evt):
1617         blender(self)
1618
1619
1620 class GraphPanelSimi(wx.Panel):
1621     def __init__(self,parent, dico, list_graph):
1622         wx.Panel.__init__(self,parent)
1623         self.afcnb = 1
1624         self.Dict = dico
1625         self.dirout = os.path.dirname(self.Dict['ira'])
1626         self.parent = self.GetParent()#parent
1627         self.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, "courier"))
1628         self.labels = []
1629         self.listimg = []
1630         self.tabsimi = self.parent.GetParent()
1631         self.ira = self.tabsimi.GetParent()
1632         self.panel_1 = wx.ScrolledWindow(self, -1, style=wx.TAB_TRAVERSAL)
1633         afc_img = wx.Image(os.path.join(self.ira.images_path,'button_simi.jpg'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
1634         self.butafc = wx.BitmapButton(self, -1, afc_img)
1635         export_img = wx.Image(os.path.join(self.ira.images_path,'button_export.jpg'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
1636         self.butexport = wx.BitmapButton(self, -1, export_img)
1637         blender_img = wx.Image(os.path.join(self.ira.images_path,'button_blender.png'), wx.BITMAP_TYPE_ANY)
1638         blender_img.Rescale(32,32)
1639         blender_img = blender_img.ConvertToBitmap()
1640         self.butblender = wx.BitmapButton(self, -1, blender_img)
1641         for i in range(0,len(list_graph)):
1642             if os.path.exists(os.path.join(self.dirout,list_graph[i][0])) :
1643                 filename, ext = os.path.splitext(list_graph[i][0])
1644                 if ext in ['.svg', '.html'] :
1645                     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])))
1646                 else :
1647                     self.listimg.append(wx.StaticBitmap(self.panel_1, -1, wx.Bitmap(os.path.join(self.dirout,list_graph[i][0]), wx.BITMAP_TYPE_ANY)))
1648                 self.labels.append(wx.StaticText(self.panel_1, -1, list_graph[i][1]))
1649         self.panel_1.Bind(wx.EVT_MOTION, self.onMouseMove)
1650         self.__set_properties()
1651         self.__do_layout()
1652
1653     def __set_properties(self):
1654         self.panel_1.EnableScrolling(True,True)
1655         #self.panel_1.SetSize((1000,1000))
1656         self.panel_1.SetScrollRate(20, 20)
1657         self.panel_1.SetFocus()
1658
1659     def __do_layout(self):
1660         self.sizer_1 = wx.BoxSizer(wx.HORIZONTAL)
1661         self.sizer_2 = wx.BoxSizer(wx.VERTICAL)
1662         self.sizer_3 = wx.BoxSizer(wx.VERTICAL)
1663         self.sizer_2.Add(self.butafc, 0, 0, 0)
1664         self.sizer_2.Add(self.butexport, 0, 0, 0)
1665         self.sizer_2.Add(self.butblender, 0, 0, 0)
1666         for i in range(0, len(self.listimg)):
1667             self.sizer_3.Add(self.listimg[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
1668             self.sizer_3.Add(self.labels[i], 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
1669         self.panel_1.SetSizer(self.sizer_3)
1670         self.sizer_1.Add(self.sizer_2, 0, wx.EXPAND, 0)
1671         self.sizer_1.Add(self.panel_1, 1, wx.EXPAND, 0)
1672         self.SetSizer(self.sizer_1)
1673
1674     def onMouseMove(self, event):
1675         self.panel_1.SetFocus()
1676