vocabulaire...
[iramuteq] / ProfList.py
1 # -*- coding: utf-8 -*-
2
3 #----------------------------------------------------------------------------
4 # Name:         ListCtrl.py
5 # Author:       Pierre Ratinaud
6
7
8 #comes from ListCtrl.py from the demo tool of wxPython:
9 # Author:       Robin Dunn & Gary Dumer
10 #
11 # Created:
12 # Copyright:    (c) 1998 by Total Control Software
13 # Licence:      wxWindows license
14 #----------------------------------------------------------------------------
15
16 import os
17 import sys
18 import  wx
19 import  wx.lib.mixins.listctrl  as  listmix
20 #from tabsimi import DoSimi
21 from listlex import ListForSpec
22 from chemins import ConstructPathOut, ffr
23 from dialog import PrefExport, PrefUCECarac, SearchDial, message
24 from tableau import Tableau
25 from search_tools import SearchFrame
26 import webbrowser
27 #import cStringIO
28 import tempfile
29 import codecs
30 from functions import exec_rcode, MessageImage, progressbar, treat_var_mod
31 from PrintRScript import barplot
32 from textclassechd import ClasseCHD
33 from shutil import copyfile
34 from operator import itemgetter
35
36 #---------------------------------------------------------------------------
37 class ProfListctrlPanel(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.ColumnSorterMixin):
38     def __init__(self, parent, gparent, profclasse, Alceste=False, cl=0):
39         wx.ListCtrl.__init__( self, parent, -1, style=wx.LC_REPORT|wx.LC_VIRTUAL|wx.LC_HRULES|wx.LC_VRULES)
40
41         self.parent = parent
42         self.Alceste = Alceste
43         self.Source = gparent
44         self.cl = cl
45         self.var_mod = {}
46
47         line1 = profclasse.pop(0)
48         classen = [line for line in profclasse if line[0] != '*' and line[0] != '*****']
49         try :
50             self.lenact = profclasse.index([u'*****', u'*', u'*', u'*', u'*', u'*', '', ''])
51             profclasse.pop(self.lenact)
52         except ValueError:
53             try :
54                 self.lenact = profclasse.index([u'*', u'*', u'*', u'*', u'*', u'*', '', ''])
55                 profclasse.pop(self.lenact)
56             except ValueError:
57                 self.lenact = len(profclasse)
58         try :
59             self.lensup = profclasse.index([u'*', u'*', u'*', u'*', u'*', u'*', '', ''])
60             self.lensup = self.lensup - self.lenact
61             profclasse.pop(self.lensup)
62         except ValueError: 
63             self.lensup = len(profclasse) - self.lenact
64         self.lenet = len(profclasse) - (self.lenact + self.lensup)
65 #        print self.lenact, self.lensup, self.lenet
66         for i,  line in enumerate(classen) :
67             line[0] = i
68         dictdata = dict(zip([i for i in range(0,len(classen))], classen))
69
70         if self.lenact != 0 :
71             self.la = [dictdata[i][6] for i in range(0, self.lenact)]
72             self.lchi = [dictdata[i][4] for i in range(0, self.lenact)]
73             self.lfreq = [dictdata[i][1] for i in range(0, self.lenact)]
74         else :
75             self.la = []
76             self.lchi = []
77             self.lfreq = []
78         self.tmpchi = None
79             
80         #adding some art
81         self.il = wx.ImageList(16, 16)
82         a={"sm_up":"GO_UP","sm_dn":"GO_DOWN","w_idx":"WARNING","e_idx":"ERROR","i_idx":"QUESTION"}
83         for k,v in a.items():
84             s="self.%s= self.il.Add(wx.ArtProvider_GetBitmap(wx.ART_%s,wx.ART_TOOLBAR,(16,16)))" % (k,v)
85             exec(s)
86         self.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
87
88         #adding some attributes (colourful background for each item rows)
89         self.attr1 = wx.ListItemAttr()
90         self.attr1.SetBackgroundColour((220, 220, 220))
91         self.attrsg = wx.ListItemAttr()
92         self.attrsg.SetBackgroundColour((230, 230, 230))
93         self.attr2 = wx.ListItemAttr()
94         self.attr2.SetBackgroundColour((190, 249, 236))
95         self.attr2s = wx.ListItemAttr()
96         self.attr2s.SetBackgroundColour((211, 252, 244))        
97         self.attr3 = wx.ListItemAttr()
98         self.attr3.SetBackgroundColour((245, 180, 180))
99         self.attr3s = wx.ListItemAttr()
100         self.attr3s.SetBackgroundColour((245, 190, 190))
101
102
103         self.InsertColumn(0, "num", wx.LIST_FORMAT_RIGHT)
104         self.InsertColumn(1, "eff. s.t.", wx.LIST_FORMAT_RIGHT)
105         self.InsertColumn(2, "eff. total", wx.LIST_FORMAT_RIGHT)
106         self.InsertColumn(3, "pourcentage", wx.LIST_FORMAT_RIGHT)
107         self.InsertColumn(4, "chi2", wx.LIST_FORMAT_RIGHT)
108         self.InsertColumn(5, "Type", wx.LIST_FORMAT_RIGHT)
109         self.InsertColumn(6, "forme", wx.LIST_FORMAT_RIGHT)
110         self.InsertColumn(7, "p", wx.LIST_FORMAT_RIGHT)
111         
112
113         self.SetColumnWidth(0, 60)
114         self.SetColumnWidth(1, 70)
115         self.SetColumnWidth(2, 80)
116         self.SetColumnWidth(3, 100)
117         self.SetColumnWidth(4, 70)
118         self.SetColumnWidth(5, 60)
119         self.SetColumnWidth(6, 140)
120         self.SetColumnWidth(7, wx.LIST_AUTOSIZE)
121
122         #These two should probably be passed to init more cleanly
123         #setting the numbers of items = number of elements in the dictionary
124         self.itemDataMap = dictdata
125         self.itemIndexMap = dictdata.keys()
126         self.SetItemCount(len(dictdata))
127         
128         #mixins
129         listmix.ListCtrlAutoWidthMixin.__init__(self)
130         listmix.ColumnSorterMixin.__init__(self, len(classen[0]))
131
132         #sort by genre (column 2), A->Z ascending order (1)
133         self.SortListItems(0, 1)
134
135         #events
136         #self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
137         #self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated)
138         #self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnItemDeselected)
139         self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick)
140
141         # for wxMSW
142         self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightClick)
143
144         # for wxGTK
145         self.Bind(wx.EVT_RIGHT_UP, self.OnRightClick)
146
147         #for searching
148         search_id = wx.NewId()
149         searchall_id = wx.NewId()
150         self.parent.Bind(wx.EVT_MENU, self.onsearch, id = search_id)
151         self.parent.Bind(wx.EVT_MENU, self.onsearchall, id = searchall_id)
152         self.accel_tbl = wx.AcceleratorTable([(wx.ACCEL_CTRL, ord('F'), search_id),
153                                               (wx.ACCEL_CTRL|wx.ACCEL_SHIFT, ord('F'), searchall_id)])
154         self.SetAcceleratorTable(self.accel_tbl)
155
156
157
158     def OnColClick(self,event):
159         event.Skip()
160
161     def OnItemSelected(self, event):
162         self.currentItem = event.m_itemIndex
163
164     def OnItemActivated(self, event):
165         self.currentItem = event.m_itemIndex
166
167     def getColumnText(self, index, col):
168         item = self.GetItem(index, col)
169         return item.GetText()
170
171     def OnItemDeselected(self, evt):
172         pass
173     #---------------------------------------------------
174     # These methods are callbacks for implementing the
175     # "virtualness" of the list...
176
177     def OnGetItemText(self, item, col):
178         index=self.itemIndexMap[item]
179         s = self.itemDataMap[index][col]
180         return s
181
182     def OnGetItemImage(self, item):
183         index=self.itemIndexMap[item]
184         genre=self.itemDataMap[index][2]
185
186         if genre=="Rock":
187             return self.w_idx
188         elif genre=="Jazz":
189             return self.e_idx
190         elif genre=="New Age":
191             return self.i_idx
192         else:
193             return -1
194
195     def OnGetItemAttr(self, item):
196         index=self.itemIndexMap[item]
197         if index < self.lenact :
198             if item % 2 :
199                 return self.attr1
200             else :
201                 return self.attrsg
202         elif index >= self.lenact and index < (self.lenact + self.lensup) :
203             if item % 2 :
204                 return self.attr2
205             else :
206                 return self.attr2s
207         elif index >= (self.lenact + self.lensup) :
208             if item % 2 :
209                 return self.attr3
210             else :
211                 return self.attr3s
212         else :
213             return None
214
215     #---------------------------------------------------
216     # Matt C, 2006/02/22
217     # Here's a better SortItems() method --
218     # the ColumnSorterMixin.__ColumnSorter() method already handles the ascending/descending,
219     # and it knows to sort on another column if the chosen columns have the same value.
220
221     def SortItems(self,sorter=cmp):
222         items = list(self.itemDataMap.keys())
223         items.sort(sorter)
224         self.itemIndexMap = items
225         
226         # redraw the list
227         self.Refresh()
228
229     # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
230     def GetListCtrl(self):
231         return self
232
233     # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
234     def GetSortImages(self):
235         return (self.sm_dn, self.sm_up)
236
237     def onsearch(self, evt) :
238         self.dial = SearchDial(self, self, 6, True)
239         self.dial.CenterOnParent()
240         self.dial.Show()
241         #self.dial.Destroy()
242
243     def onsearchall(self, evt) :
244         if 'FrameSearch' not in dir(self.Source) :
245             self.Source.FrameSearch = SearchFrame(self.parent, -1, u"Rechercher...", self.Source.corpus)
246         self.dial = SearchDial(self, self.Source.FrameSearch.liste, 1, False)
247         self.dial.CenterOnParent()
248         self.dial.Show()
249         #self.dial.Destroy()
250
251     def OnRightClick(self, event):
252
253         # only do this part the first time so the events are only bound once
254         if self.Alceste:
255             if not hasattr(self, "popupID1"):
256                 self.popupID1 = wx.NewId()
257                 self.popupID2 = wx.NewId()
258                 self.popupID3 = wx.NewId()
259                 self.popupID4 = wx.NewId()
260                 self.popupID5 = wx.NewId()
261                 self.popupID6 = wx.NewId()
262                 self.popupID7 = wx.NewId()
263                 self.popupID8 = wx.NewId()
264                 self.popupID9 = wx.NewId()
265                 #self.popupID10 = wx.NewId()
266                 self.popupIDgraph = wx.NewId()
267                 self.idseg = wx.NewId()
268                 self.iducecarac = wx.NewId()
269                 self.idtablex = wx.NewId()
270                 self.idchimod = wx.NewId()
271                 self.idwordgraph = wx.NewId()
272                 self.popup_proxe = wx.NewId()
273                 self.idlexdendro = wx.NewId()
274                 self.idexport = wx.NewId()
275             #    self.export_classes = wx.NewId()
276    
277                 self.Bind(wx.EVT_MENU, self.OnPopupOne, id=self.popupID1)
278                 self.Bind(wx.EVT_MENU, self.OnPopupTwo, id=self.popupID2)
279                 self.Bind(wx.EVT_MENU, self.OnPopupThree, id=self.popupID3)
280                 self.Bind(wx.EVT_MENU, self.OnPopupFour, id=self.popupID4)
281                 self.Bind(wx.EVT_MENU, self.OnPopupFive, id=self.popupID5)
282                 self.Bind(wx.EVT_MENU, self.OnPopupSix, id=self.popupID6)
283                 self.Bind(wx.EVT_MENU, self.OnPopupSeven, id=self.popupID7)
284                 self.Bind(wx.EVT_MENU, self.OnPopupHeight, id=self.popupID8)
285                 self.Bind(wx.EVT_MENU, self.OnPopupNine, id=self.popupID9)
286                 #self.Bind(wx.EVT_MENU, self.OnPopupSpec, id=self.popupID10)
287                 self.Bind(wx.EVT_MENU, self.on_graph, id=self.popupIDgraph)
288                 self.Bind(wx.EVT_MENU, self.on_segments, id=self.idseg)
289                 self.Bind(wx.EVT_MENU, self.on_uce_carac, id = self.iducecarac)
290                 self.Bind(wx.EVT_MENU, self.on_tablex, id = self.idtablex)
291                 self.Bind(wx.EVT_MENU, self.quest_var_mod, id = self.idchimod)
292                 self.Bind(wx.EVT_MENU, self.onwordgraph, id = self.idwordgraph)
293                 self.Bind(wx.EVT_MENU, self.onproxe, id = self.popup_proxe)
294                 self.Bind(wx.EVT_MENU, self.onlexdendro, id = self.idlexdendro)
295                 self.Bind(wx.EVT_MENU, self.onexport, id = self.idexport)
296              #  self.Bind(wx.EVT_MENU, self.on_export_classes, id = self.export_classes)
297    #            self.Bind(wx.EVT_MENU, self.OnPopupThree, id=self.popupID3)
298     
299             # make a menu
300             menu = wx.Menu()
301             menu.Append(self.popupID1, u"Formes associées")
302             menu.Append(self.idtablex, u"Chi2 par classe")
303             menu.Append(self.idlexdendro, u"Chi2 par classe + dendro")
304             menu.Append(self.idchimod, u"Chi2 modalités de la variable")
305             menu.Append(self.idwordgraph, u"Graphe du mot")
306             #menu.Append(self.export_classes, u"Exporter le corpus...") 
307             
308             #menu.Append(self.popupID10, u"Spécificités")
309
310             menu_conc = wx.Menu()
311             menu_conc.Append(self.popupID2, u"dans les segments de texte de la classe")
312             menu_conc.Append(self.popupID3, u"dans les segments de texte classés")
313             menu_conc.Append(self.popupID4, u"dans tous les segments de texte")
314             menu.AppendMenu(-1, u"Concordancier", menu_conc) 
315             menu_cnrtl = wx.Menu()      
316             menu_cnrtl.Append(self.popupID5, u"Définition")
317             menu_cnrtl.Append(self.popupID6, u"Etymologie")
318             menu_cnrtl.Append(self.popupID7, u"Synonymie")
319             menu_cnrtl.Append(self.popupID8, u"Antonymie")
320             menu_cnrtl.Append(self.popupID9, u"Morphologie")
321             menu_cnrtl.Append(self.popup_proxe, u"Proxémie")
322             menu.AppendMenu(-1, u"Outils du CNRTL", menu_cnrtl)
323             menu.AppendSeparator()
324             menu.Append(self.popupIDgraph, u"Graphe de la classe")
325             menu.Append(self.idseg, u"Segments répétés")
326             menu.Append(self.iducecarac, u"Segments de texte caractéristiques")
327             menu.Append(self.idexport, 'Exporter...')
328             #menu.Append(self.popupID2, u"Concordancier")
329     #        menu.Append(self.popupID3, "recharger")
330     
331             self.PopupMenu(menu)
332             menu.Destroy()
333         elif 'tableau' in dir(self.Source) :
334             if not hasattr(self, "pop1"):
335                 self.pop1 = wx.NewId()
336                 self.pop2 = wx.NewId()
337                 self.pop3 = wx.NewId()
338                 self.Bind(wx.EVT_MENU, self.quest_simi, id=self.pop1)
339                 self.Bind(wx.EVT_MENU, self.on_tablex, id=self.pop2)
340                 self.Bind(wx.EVT_MENU, self.quest_var_mod, id=self.pop3)
341
342             menu = wx.Menu()
343             menu.Append(self.pop2, u"Chi2 par classe")
344             menu.Append(self.pop3, u"Chi2 modalités de la variable")
345             menu.AppendSeparator()
346             menu.Append(self.pop1, u"Graph de la classe")
347             self.PopupMenu(menu)
348             menu.Destroy()
349
350     def onexport(self, evt) :
351         if 'corpus' in dir(self.Source):
352             corpus = self.Source.corpus
353             corpus.export_classe(self.Source.pathout['classe_%i_export.txt' % self.cl], self.cl)
354         dial = wx.MessageDialog(self, self.Source.pathout['classe_%i_export.txt' % self.cl], u"Export", wx.OK|wx.ICON_INFORMATION)
355         dial.ShowModal()
356         dial.Destroy()
357         #if 'corpus' in dir(self.Source):
358         #    corpus = self.Source.corpus
359         #ClasseCHD(self.parent, corpus, self.cl)
360
361     def getselectedwords(self) :
362         words = [self.getColumnText(self.GetFirstSelected(), 6)]
363         last = self.GetFirstSelected()
364         while self.GetNextSelected(last) != -1:
365             last = self.GetNextSelected(last)
366             words.append(self.getColumnText(last, 6))
367         return words
368
369     def quest_var_mod(self, evt) :
370         if 'corpus' in dir(self.Source):
371             corpus = self.Source.corpus
372             if self.var_mod == {} :
373                 self.var_mod = self.Source.corpus.make_etoiles_dict()
374         else :
375             corpus = self.Source.tableau
376             if self.var_mod == {} :
377                 self.var_mod = treat_var_mod([val for val in corpus.actives] + [val for val in corpus.sups])
378         with codecs.open(self.Source.pathout['chisqtable'], 'r', corpus.parametres['syscoding']) as f :
379             chistable = [line.replace('\n','').replace('\r','').replace('"','').replace(',','.').split(';') for line in f]
380         title = chistable[0]
381         title.pop(0)
382         chistable.pop(0)
383         vchistable = [line[1:] for line in chistable]
384         fchistable = [line[0] for line in chistable]
385         word = self.getselectedwords()[0]
386         if len(word.split('_')) > 1 :
387             var = word.split('_')
388             #words = ['_'.join([var[0],word]) for word in self.var_mod[var[0]]]
389             words = [word for word in self.var_mod[var[0]]]
390             words.sort()
391             tableout = []
392             kwords = []
393             for word in words :
394                 if word in fchistable :
395                     tableout.append(vchistable[fchistable.index(word)])
396                     kwords.append(word)
397             tmpgraph = tempfile.mktemp(dir=self.Source.parent.TEMPDIR)
398             txt = barplot(tableout, kwords, title, self.Source.parent.RscriptsPath['Rgraph'], tmpgraph)
399             tmpscript = tempfile.mktemp(dir=self.Source.parent.TEMPDIR)
400             file = open(tmpscript,'w')
401             file.write(txt)
402             file.close()
403             exec_rcode(self.Source.parent.RPath, tmpscript, wait = True)
404             win = MessageImage(self,u"Graphique", size=(700, 500))
405             win.addsaveimage(tmpgraph)
406             txt = "<img src='%s'>" % tmpgraph
407             win.HtmlPage.SetPage(txt)
408             win.Show(True)
409         else :
410             dial = wx.MessageDialog(self, u"Ce n'est pas une forme du type variable_modalité", u"Problème", wx.OK | wx.ICON_WARNING)
411             dial.CenterOnParent()
412             dial.ShowModal()
413             dial.Destroy()
414
415     def quest_simi(self, evt) :
416         tableau = self.Source.tableau
417         tab = tableau.make_table_from_classe(self.cl, self.la)
418         pathout = ConstructPathOut(self.Source.pathout.dirout, 'simi_classe_%i' %self.cl)
419         self.filename = os.path.join(pathout,'mat01.csv')
420         tableau.printtable(self.filename, tab)
421         del tab
422         paramsimi = {'coeff' : 0,
423                           'layout' : 2,
424                           'type_graph' : 1,
425                           'arbremax' : 1,
426                           'coeff_tv' : 1,
427                           'coeff_tv_nb' : 0,
428                           'tvprop' : 0,
429                           'tvmin' : 5,
430                           'tvmax' : 30,
431                           'coeff_te' : 1,
432                           'coeff_temin' : 1,
433                           'coeff_temax' : 10,
434                           'label_v': 1,
435                           'label_e': 1,
436                           'vcex' : 0,
437                           'vcexmin' : 10,
438                           'vcexmax' : 25,
439                           'cex' : 10,
440                           'cexfromchi' : True,
441                           'sfromchi': False,
442                           'seuil_ok' : 0,
443                           'seuil' : 1,
444                           'cols' : (255,0,0),
445                           'cola' : (200,200,200),
446                           'width' : 1000,
447                           'height' : 1000,
448                           'first' : True,
449                           'keep_coord' : True,
450                           'alpha' : 20,
451                           'film': False,
452                           'com' : 0,
453                           'communities' : 0,
454                           'halo' : 0
455                           }
456         act = {}
457         tableau.chi = {}
458         tableau.lchi = self.lchi
459         tableau.parametre['fromprof'] = True
460         for i, val in enumerate(self.la) :
461             act[val] = [self.lfreq[i]]
462             tableau.chi[val] = [self.lchi[i]]
463         self.parent.SimiCluster(parametres = paramsimi, fromprof = ffr(self.filename), pathout = pathout, listactives = self.la, actives = act, tableau = tableau)
464
465     def onwordgraph(self, evt):
466         word = self.getColumnText(self.GetFirstSelected(), 6)
467         if self.tmpchi is None :
468             self.tmpchi = tempfile.mktemp(dir=self.Source.parent.TEMPDIR)
469             with open(self.tmpchi, 'w') as f:
470                 f.write('\n'.join([str(val) for val in self.lchi]))
471         index = self.la.index(word)
472         parametres = {'type' : 'clustersimitxt', 
473                         'pathout' : self.Source.parametres['pathout'],
474                         'word' : index ,
475                         'lem' : self.Source.parametres['lem'],
476                         'tmpchi' : self.tmpchi}
477         #try :
478         self.parent.SimiFromCluster(self.parent, self.Source.corpus, self.la, self.lfreq, self.lchi, self.cl - 1, parametres = parametres, dlg = progressbar(self, 4))
479         #except :
480         #    print 'not acitve'
481
482     def on_graph(self, evt):
483         if self.tmpchi is None :
484             self.tmpchi = tempfile.mktemp(dir=self.Source.parent.TEMPDIR)
485             with open(self.tmpchi, 'w') as f:
486                 f.write('\n'.join([str(val) for val in self.lchi]))
487         parametres = {'type' : 'clustersimitxt', 
488                         'pathout' : self.Source.parametres['pathout'],
489                         'lem' : self.Source.parametres['lem'],
490                         'tmpchi' : self.tmpchi}
491
492         self.parent.SimiFromCluster(self.parent, self.Source.corpus, self.la, self.lfreq, self.lchi, self.cl - 1, parametres = parametres, dlg = progressbar(self, 4))
493
494     def on_segments(self,evt) :
495         dlg = progressbar(self, 2)
496         corpus = self.Source.corpus
497         uces = corpus.lc[self.cl-1]
498         l = []
499         dlg.Update(1, u'Segments...')
500         for i in range(2,10) :
501             li = corpus.find_segments_in_classe(uces, i, 1000)
502             if li == [] :
503                 break
504             else :
505                 l += li
506         l.sort(reverse = True)
507         d = {}
508         dlg.Update(2, 'Tri...')
509         for i, line in enumerate(l) :
510             d[i] = [line[1],line[0], line[2]]
511         first = ['','','']
512         para={'dico': d,'fline':first}
513         dlg.Destroy()
514         win = wliste(self, -1, u"Segments répétés - Classe %i" % self.cl, d, first, size=(600, 500))
515         win.Show(True)
516
517     def on_uce_carac(self,evt) :
518         dial = PrefUCECarac(self, self.parent)
519         dial.CenterOnParent()
520         if dial.ShowModal() == wx.ID_OK :
521             limite = dial.spin_eff.GetValue()
522             atype = dial.radio_type.GetSelection()
523             dlg = progressbar(self,maxi = 4)
524             corpus = self.Source.corpus
525             uces = corpus.lc[self.cl-1]
526             tab = corpus.make_table_with_classe(uces, self.la)
527             tab.pop(0)
528             dlg.Update(2, u'score...')
529             if atype == 0 :
530                 ntab = [round(sum([self.lchi[i] for i, word in enumerate(line) if word == 1]),2) for line in tab]
531             else :
532                 ntab = [round(sum([self.lchi[i] for i, word in enumerate(line) if word == 1])/float(sum(line)),2) if sum(line)!=0 else 0 for line in tab]
533             ntab2 = [[ntab[i], uces[i]] for i, val in enumerate(ntab)]
534             del ntab
535             ntab2.sort(reverse = True)
536             ntab2 = ntab2[:limite]
537             nuces = [val[1] for val in ntab2]
538             dlg.Update(3, u'concordancier...')
539             #ucestxt = [corpus.ucis_paras_uces[val[1][0]][val[1][1]][val[1][2]] for val in ntab2]
540             ucestxt1 = [row for row in corpus.getconcorde(nuces)]
541             ucestxt = []
542             ucis_txt = []
543             for uce in ucestxt1 :
544                 ucetxt = ' '+uce[1]+' '
545                 ucis_txt.append(' '.join(corpus.ucis[corpus.getucefromid(uce[0]).uci].etoiles) + '<br>')
546                 for lem in self.la :
547                     listmot = corpus.getlems()[lem].formes
548                     for id in listmot :
549                         forme = corpus.getforme(id).forme
550                         ucetxt = ucetxt.replace(' '+forme+' ', '<font color=red> ' + forme + ' </font>')
551                 ucestxt.append(ucetxt)        
552             #ucestxt = [corpus.make_concord(self.la, ' '.join(uce), 'red') for uce in ucestxt]
553             dlg.Update(4, u'texte...')
554             #ucis_txt = [' '.join(corpus.ucis[val[1][0]][0]) for val in ntab2]
555             win = message(self, u"Segments de texte caractéristiques - Classe %i" % self.cl, (750, 600))
556             win.html = '<html>\n' + '<br><br>'.join(['<br>'.join([ucis_txt[i], 'score : ' + str(ntab2[i][0]), ucestxt[i]]) for i in range(0,len(ucestxt))]) + '\n</html>'
557             win.HtmlPage.SetPage(win.html)
558             dlg.Destroy()
559             win.Show(True)
560     
561     def on_tablex(self, evt):
562         if 'corpus' in dir(self.Source):
563             corpus = self.Source.corpus
564         else :
565             corpus = self.Source.tableau
566         with codecs.open(self.Source.pathout['chisqtable'], 'r', corpus.parametres['syscoding']) as f :
567             chistable = [line.replace('\n','').replace('\r','').replace('"','').replace(',','.').split(';') for line in f]
568         title = chistable[0]
569         title.pop(0)
570         chistable.pop(0)
571         vchistable = [line[1:] for line in chistable]
572         fchistable = [line[0] for line in chistable]
573         words = self.getselectedwords()
574         tableout = [vchistable[fchistable.index(word)] for word in words]
575         tmpgraph = tempfile.mktemp(dir=self.Source.parent.TEMPDIR)
576         nbcl = len(title)
577         nbwords = len(words)
578         txt = barplot(tableout, words, title, self.Source.parent.RscriptsPath['Rgraph'], tmpgraph)
579         #print 'ATTENTION TEST R'
580         #txt = """
581         #sink('/Users/pierre/Desktop/qdfqsdfqsdfqsdf.txt')
582         #Sys.getlocale()
583         #sink()
584         #"""
585         tmpscript = tempfile.mktemp(dir=self.Source.parent.TEMPDIR)
586         file = open(tmpscript,'w')
587         file.write(txt)
588         file.close()
589         exec_rcode(self.Source.parent.RPath, tmpscript, wait = True)
590         w = 100 + (20 * nbwords) + (100 * nbcl)
591         h = 100 + (nbwords * 15)
592         if w > 1100 : w = 1100
593         if h > 800 : h = 800
594         if h < 450 : h = 450
595         win = MessageImage(self, u"Graphique", size=(w, h))
596         win.addsaveimage(tmpgraph)
597         txt = "<img src='%s'>" % tmpgraph
598         win.HtmlPage.SetPage(txt)
599         win.Show(True)
600
601     def onlexdendro(self, evt):
602         if 'corpus' in dir(self.Source):
603             corpus = self.Source.corpus
604         else :
605             corpus = self.Source.tableau
606         with codecs.open(self.Source.pathout['chisqtable'], 'r', corpus.parametres['syscoding']) as f :
607             chistable = [line.replace('\n','').replace('\r','').replace('"','').replace(',','.').split(';') for line in f]
608         title = chistable[0]
609         title.pop(0)
610         chistable.pop(0)
611         vchistable = [line[1:] for line in chistable]
612         fchistable = [line[0] for line in chistable]
613         words = self.getselectedwords()
614         tableout = [vchistable[fchistable.index(word)] for word in words]
615         tmpgraph = tempfile.mktemp(dir=self.Source.parent.TEMPDIR)
616         txttable = 'c(' + ','.join([','.join(line) for line in tableout]) + ')'
617         rownames = 'c("' + '","'.join(words) + '")'
618         colnames = 'c("' + '","'.join(title) + '")'
619         nbcl = len(title)
620         rownb = len(words)
621         txt = """
622         load("%s")
623         di <- matrix(data=%s, nrow=%i, byrow = TRUE)
624         rownames(di)<- %s
625         colnames(di) <- %s
626         library(ape)
627         source("%s")
628         height <- (30*ncol(di)) + (15*nrow(di))
629         height <- ifelse(height <= 400, 400, height)
630         width <- 500
631         open_file_graph("%s", width=width, height=height)
632         plot.dendro.lex(tree.cut1$tree.cl, di)
633         """ % (self.Source.pathout['Rdendro'], txttable, rownb, rownames, colnames, self.Source.parent.RscriptsPath['Rgraph'], ffr(tmpgraph))
634         tmpscript = tempfile.mktemp(dir=self.Source.parent.TEMPDIR)
635         file = open(tmpscript,'w')
636         file.write(txt)
637         file.close()
638         exec_rcode(self.Source.parent.RPath, tmpscript, wait = True)
639         win = MessageImage(self, u"Graphique", size=(700, 500))
640         win.addsaveimage(tmpgraph)
641         txt = "<img src='%s'>" % tmpgraph
642         win.HtmlPage.SetPage(txt)
643         win.Show(True)
644
645
646     def make_concord(self, uces, title, color = 'red') :
647         corpus = self.Source.corpus
648         ListWord = [self.getColumnText(self.GetFirstSelected(), 6)]
649         last = self.GetFirstSelected()
650         while self.GetNextSelected(last) != -1:
651             last = self.GetNextSelected(last)
652             ListWord.append(self.getColumnText(last, 6))
653         listmot = [forme for item in ListWord for forme in corpus.getlems()[item].formes]
654         win = message(self, title, size=(750, 600))
655         toshow = ['<html>\n<H1>Concordancier</H1>\n']
656         toshow.append('<h3><font color=%s>' % color + ' '.join(ListWord) + '</font></h3><br>')
657         duce = {}
658         ucef = []
659         for word in ListWord : 
660             ucef += list(set(corpus.getlemuces(word)).intersection(uces))
661         ucef = list(set(ucef))
662         ucef.sort()
663         res = corpus.getconcorde(ucef)
664         txt = '<br>'.join(toshow) +'<br><br>'
665         for uce in res :
666             ucetxt = ' '+uce[1]+' '
667             txt += ' '.join(corpus.ucis[corpus.getucefromid(uce[0]).uci].etoiles) + '<br>'
668             for forme in listmot:
669                 forme = corpus.getforme(forme).forme
670                 ucetxt = ucetxt.replace(' '+forme+' ', '<font color=red> ' + forme + ' </font>')
671             txt += ucetxt + '<br><br>'
672         win.HtmlPage.SetPage(txt)
673         return win
674
675     def OnPopupTwo(self, event):
676         corpus = self.Source.corpus
677         uces = corpus.lc[self.cl-1]
678         win = self.make_concord(uces, "Concordancier - Classe %i" % self.cl)
679         win.Show(True)
680     
681     def OnPopupThree(self, event):
682         corpus = self.Source.corpus
683         uces = [classe[i] for classe in corpus.lc for i in range(0,len(classe))]
684         win = self.make_concord(uces, "Concordancier - UCE classées")
685         win.Show(True)
686         
687     def OnPopupFour(self, event):
688         corpus = self.Source.corpus
689         uces = [classe[i] for classe in corpus.lc for i in range(0,len(classe))] + corpus.lc0
690         win = self.make_concord(uces, "Concordancier - Toutes les UCE")
691         win.Show(True)
692
693     def OnPopupFive(self, event):
694         word = self.getColumnText(self.GetFirstSelected(), 6)
695         lk = "http://www.cnrtl.fr/definition/" + word
696         webbrowser.open(lk)
697
698     def OnPopupSix(self, event):  
699         word = self.getColumnText(self.GetFirstSelected(), 6)
700         lk = "http://www.cnrtl.fr/etymologie/" + word
701         webbrowser.open(lk)
702         
703     def OnPopupSeven(self, event):        
704         word = self.getColumnText(self.GetFirstSelected(), 6)
705         lk = "http://www.cnrtl.fr/synonymie/" + word
706         webbrowser.open(lk)
707         
708     def OnPopupHeight(self, event):  
709         word = self.getColumnText(self.GetFirstSelected(), 6)
710         lk = "http://www.cnrtl.fr/antonymie/" + word
711         webbrowser.open(lk)
712         
713     def OnPopupNine(self, event):            
714         word = self.getColumnText(self.GetFirstSelected(), 6)
715         lk = "http://www.cnrtl.fr/morphologie/" + word
716         webbrowser.open(lk)
717
718     def onproxe(self, evt) :
719         word = self.getColumnText(self.GetFirstSelected(), 6)
720         lk = "http://www.cnrtl.fr/proxemie/" + word
721         webbrowser.open(lk)
722
723     def OnPopupOne(self, event):
724         corpus = self.Source.corpus
725         #print 'ATTENTION PRINT ET TABLE'
726         #corpus.make_et_table()
727         word = self.getColumnText(self.GetFirstSelected(), 6)
728         lems = corpus.getlems()
729         uces = corpus.lc[self.cl-1]
730         rep = []
731         #FIXME : donner aussi eff reel a la place de nb uce
732         for forme in lems[word].formes :
733             ucef = list(set(corpus.getworduces(forme)).intersection(uces))
734             #ucef = [uce for uce in corpus.formes[forme][1] if uce in uces]
735             if ucef != [] :
736                 nb = len(ucef)
737                 rep.append([corpus.getforme(forme).forme, nb])
738         rep.sort(key = itemgetter(1), reverse = True)
739         win = message(self, u"Formes associées", wx.Size(300, 200))
740         win.html = '<html>\n' + '<br>'.join([' : '.join([str(val) for val in forme]) for forme in rep]) + '\n</html>'
741         win.HtmlPage.SetPage(win.html)
742         win.Show(True)
743
744
745 class wliste(wx.Frame):
746     def __init__(self, parent, id, title, d, fline, size=(600, 500)):
747         wx.Frame.__init__(self, parent, id)
748         self.liste = ListForSpec(self, parent, d, fline, menu = False)
749         self.button_1 = wx.Button(self, -1, "Fermer")
750         self.Bind(wx.EVT_BUTTON, self.OnCloseMe, self.button_1)
751         self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
752         self.__do_layout()
753
754     def __do_layout(self):
755         sizer_1 = wx.BoxSizer(wx.VERTICAL)
756         sizer_2 = wx.BoxSizer(wx.VERTICAL)
757         sizer_2.Add(self.liste, 1, wx.EXPAND | wx.ADJUST_MINSIZE, 0)
758         sizer_2.Add(self.button_1, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ADJUST_MINSIZE, 0)
759         sizer_1.Add(sizer_2, 1, wx.EXPAND, 0)
760         self.SetAutoLayout(True)
761         self.SetSizer(sizer_1)
762         self.Layout()
763         
764     def OnCloseMe(self, event):
765         self.Close(True)
766
767     def OnCloseWindow(self, event):
768         self.Destroy()