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