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