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