...
[iramuteq] / listlex.py
1 # -*- coding: utf-8 -*-
2
3 #----------------------------------------------------------------------------
4 # Author:       Pierre Ratinaud
5
6
7 #comes from ListCtrl.py from the demo tool of wxPython:
8 # Author:       Robin Dunn & Gary Dumer
9 #
10 # Created:
11 # Copyright:    (c) 1998 by Total Control Software
12 # Licence:      wxWindows license
13 #----------------------------------------------------------------------------
14
15 import os
16 import sys
17 import  wx
18 import  wx.lib.mixins.listctrl  as  listmix
19 import cStringIO
20 import tempfile
21 from functions import exec_rcode, MessageImage, doconcorde
22 from chemins import ffr
23 from PrintRScript import barplot
24 from dialog import SearchDial, message
25 from operator import itemgetter
26 #---------------------------------------------------------------------------
27
28 class ListForSpec(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.ColumnSorterMixin):
29     def __init__(self, parent,gparent, dlist = {}, first = [], menu = True):
30     #def  __init__(self, parent) :
31         wx.ListCtrl.__init__( self, parent, -1, style=wx.LC_REPORT|wx.LC_VIRTUAL|wx.LC_HRULES|wx.LC_VRULES)
32         self.parent=parent
33         self.gparent=gparent
34         self.dlist=dlist
35         self.first = first
36         self.tgen = False
37         if 'etoiles' in dir(self.gparent) :
38             self.etoiles = self.gparent.etoiles
39         else :
40             self.etoiles = []
41             for val in self.first :
42                 if val.startswith(u'X.') :
43                     val = val.replace(u'X.', u'*')
44                 self.etoiles.append(val)
45                 
46         self.menu = menu
47
48     #def start(self) :
49         search_id = wx.NewId()
50         self.parent.Bind(wx.EVT_MENU, self.onsearch, id = search_id)
51         self.accel_tbl = wx.AcceleratorTable([(wx.ACCEL_CTRL, ord('F'), search_id)])
52         self.SetAcceleratorTable(self.accel_tbl)
53
54         self.il = wx.ImageList(16, 16)
55         a={"sm_up":"GO_UP","sm_dn":"GO_DOWN","w_idx":"WARNING","e_idx":"ERROR","i_idx":"QUESTION"}
56         for k,v in a.items():
57             s="self.%s= self.il.Add(wx.ArtProvider_GetBitmap(wx.ART_%s,wx.ART_TOOLBAR,(16,16)))" % (k,v)
58             exec(s)
59         self.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
60
61         tID = wx.NewId()
62
63         self.attr1 = wx.ListItemAttr()
64         self.attr1.SetBackgroundColour((230, 230, 230))
65         self.attr2 = wx.ListItemAttr()
66         self.attr2.SetBackgroundColour("light blue")
67         self.attrselected = wx.ListItemAttr()
68         self.attrselected.SetBackgroundColour("red")
69         self.selected = {}
70         
71         i=0
72         for name in [u'formes'] + self.first :
73             self.InsertColumn(i,name,wx.LIST_FORMAT_LEFT)
74             i+=1
75             
76         self.SetColumnWidth(0, 180)
77
78         for i in range(0,len(self.first)):
79             self.SetColumnWidth(i + 1, self.checkcolumnwidth(len(self.first[i]) * 10))
80         
81         self.itemDataMap = self.dlist
82         self.itemIndexMap = self.dlist.keys()
83         self.SetItemCount(len(self.dlist))
84         
85         #listmix.ListCtrlAutoWidthMixin.__init__(self)
86         listmix.ColumnSorterMixin.__init__(self, len(self.first) + 1)
87         self.SortListItems(1, 0)
88         
89 #-----------------------------------------------------------------------------------------    
90         self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected, self)
91         
92         self.Bind(wx.EVT_LIST_ITEM_ACTIVATED , self.OnPopupTwo, self)
93         # for wxMSW
94         self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightClick)
95
96         # for wxGTK
97         self.Bind(wx.EVT_RIGHT_UP, self.OnRightClick)
98
99 #-----------------------------------------------------------------------------------------    
100     def RefreshData(self, data):
101         self.itemDataMap = data
102         self.itemIndexMap = data.keys()
103         self.SetItemCount(len(data))
104         self.Refresh()
105         
106     def checkcolumnwidth(self, width) :
107         if width < 80 :
108             return 80
109         else :
110             return width
111
112     def OnGetItemText(self, item, col):
113         index=self.itemIndexMap[item]
114         s = self.itemDataMap[index][col]
115         return s
116
117     def OnGetItemAttr(self, item):
118         if self.getColumnText(item, 0) not in self.selected :
119             if item % 2 :
120                 return self.attr1
121             else :
122                 return self.attr2
123         else :
124             return self.attrselected
125     
126     def GetItemByWord(self, word):
127         return [ val for val in self.dlist if self.dlist[val][0] == word ][0]
128
129     # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
130     def GetListCtrl(self):
131         return self
132
133     # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
134     def GetSortImages(self):
135         return (self.sm_dn, self.sm_up)
136     
137     def OnRightDown(self, event):
138         x = event.GetX()
139         y = event.GetY()
140         item, flags = self.HitTest((x, y))
141
142         if flags & wx.LIST_HITTEST_ONITEM:
143             self.Select(item)
144
145         event.Skip()
146     
147     def GetString(self, evt):
148         return self.getselectedwords()[0]
149     
150     def GetSelections(self):
151         return self.getselectedwords()
152
153     def getColumnText(self, index, col):
154         item = self.GetItem(index, col)
155         return item.GetText()
156
157     def GetItemData(self, item) :
158         index=self.itemIndexMap[item]
159         s = self.itemDataMap[index]
160         return s
161     
162     def SortItems(self,sorter=cmp):
163         items = list(self.itemDataMap.keys())
164         items.sort(sorter)
165         self.itemIndexMap = items
166         # redraw the list
167         self.Refresh()
168     
169     def OnItemSelected(self, event):
170         self.currentItem = event.m_itemIndex
171         event.Skip()
172
173     def onsearch(self, evt) :
174         self.dial = SearchDial(self, self, 0, True)
175         self.dial.CenterOnParent()
176         self.dial.Show()
177         #self.dial.Destroy()
178     
179     def OnRightClick(self, event):
180         if self.menu :
181             # only do this part the first time so the events are only bound once
182             if not hasattr(self, "popupID1"):
183                 self.popupID1 = wx.NewId()
184                 self.popupID2 = wx.NewId()
185                 self.popupID3 = wx.NewId()
186                 self.popup_Tgen_glob = wx.NewId()
187                 self.onmaketgen = wx.NewId()
188                 self.ID_stcaract = wx.NewId()
189
190                 self.Bind(wx.EVT_MENU, self.OnPopupOne, id=self.popupID1)
191                 self.Bind(wx.EVT_MENU, self.OnPopupTwo, id=self.popupID2)
192                 self.Bind(wx.EVT_MENU, self.OnPopupThree, id=self.popupID3)
193                 self.Bind(wx.EVT_MENU, self.OnTgen_glob, id=self.popup_Tgen_glob)
194                 self.Bind(wx.EVT_MENU, self.OnMakeTgen, id=self.onmaketgen)
195                 #self.Bind(wx.EVT_MENU, self.onstcaract, id = self.ID_stcaract)
196             # make a menu
197             menu = wx.Menu()
198             # add some items
199             menu.Append(self.popupID1, u"Formes associées")
200             menu.Append(self.popupID2, u"Concordancier")
201             menu.Append(self.popupID3, u"Graphique")
202             menu_stcaract = wx.Menu()
203             self.menuid = {}
204             for i, et in enumerate(self.etoiles) :
205                 nid = wx.NewId()
206                 self.menuid[nid] = i
207                 menu_stcaract.Append(nid, et)
208                 self.Bind(wx.EVT_MENU, self.onstcaract, id = nid)
209             menu.AppendMenu(-1, u"Segments de texte caractéristiques", menu_stcaract)
210             #menu.Append(self.popup_Tgen_glob, "Tgen global")
211             menu.Append(self.onmaketgen, "Make Tgen")
212             self.PopupMenu(menu)
213             menu.Destroy()
214
215     def getselectedwords(self) :
216         words = [self.getColumnText(self.GetFirstSelected(), 0)]
217         last = self.GetFirstSelected()
218         while self.GetNextSelected(last) != -1:
219             last = self.GetNextSelected(last)
220             words.append(self.getColumnText(last, 0))
221         return words
222
223     def OnPopupOne(self, event):
224         activenotebook = self.parent.nb.GetSelection()
225         page = self.parent.nb.GetPage(activenotebook)
226         corpus = page.corpus
227         word = self.getselectedwords()[0]
228         lems = corpus.getlems()
229         rep = []
230         for forme in lems[word].formes :
231             rep.append([corpus.getforme(forme).forme, corpus.getforme(forme).freq])
232         rep.sort(key = itemgetter(1), reverse = True)
233         win = message(self, u"Formes associées", (300, 200))
234         win.html = '<html>\n' + '<br>'.join([' : '.join([str(val) for val in forme]) for forme in rep]) + '\n</html>'
235         win.HtmlPage.SetPage(win.html)
236         win.Show(True)
237     
238     def onstcaract(self, evt) :
239         ind = self.menuid[evt.Id]
240         limite = 50
241         minind = 2
242         activenotebook = self.parent.nb.GetSelection()
243         page = self.parent.nb.GetPage(activenotebook)
244         item=self.getColumnText(self.GetFirstSelected(), 0)
245         corpus = page.corpus
246         parametres = page.parametres
247         paneff = self.gparent.ListPanEff
248         panchi = self.gparent.ListPan
249         #etoiles = self.gparent.etoiles
250         et = self.etoiles[ind]
251         
252         #if et.startswith(u'X.') :
253         #    et = et.replace(u'X.', u'*')
254         uces = corpus.getucesfrometoile(et)
255         self.la = [panchi.dlist[i][0] for i in range(0, len(panchi.dlist)) if panchi.dlist[i][ind+1] >= minind ]
256         self.lchi = [panchi.dlist[i][ind+1] for i in range(0, len(panchi.dlist)) if panchi.dlist[i][ind+1] >= minind ]
257         #lfreq = [paneff.dlist[i][ind+1] for i in range(0, len(panchi.dlist)) if panchi.dlist[i][ind+1] >= minind ]
258         if max(self.lchi) == float('inf') :
259             nchi = []
260             for val in self.lchi :
261                 if val == float('inf') :
262                     nchi.append(0)
263                 else :
264                     nchi.append(val)
265             nmax = max(nchi)
266             nchi = [val if val != float('inf') else nmax + 2 for val in self.lchi]
267             self.lchi = nchi
268         tab = corpus.make_pondtable_with_classe(uces, self.la)
269         tab.pop(0)
270         ntab = [round(sum([(self.lchi[i] * word) for i, word in enumerate(line) if word != 0]),2) for line in tab]
271         ntab2 = [[ntab[i], uces[i]] for i, val in enumerate(ntab) if ntab[i] != 0]
272         del ntab
273         ntab2.sort(reverse = True)
274         ntab2 = ntab2[:limite]
275         nuces = [val[1] for val in ntab2]
276         ucis_txt, ucestxt = doconcorde(corpus, nuces, self.la)
277         items = dict([[i, '<br>'.join([ucis_txt[i], '<table bgcolor = #1BF0F7 border=0><tr><td><b>score : %.2f</b></td></tr></table><br>' % ntab2[i][0], ucestxt[i]])] for i in range(0,len(ucestxt))])
278         win = message(self, items, u"Segments de texte caractéristiques - %s" % self.first[ind], (900, 600))
279         #win.html = '<html>\n' + '<br>'.join(['<br>'.join([ucis_txt[i], '<table bgcolor = #1BF0F7 border=0><tr><td><b>score : %.2f</b></td></tr></table>' % ntab2[i][0], ucestxt[i]]) for i in range(0,len(ucestxt))]) + '\n</html>'
280         #win.HtmlPage.SetPage(win.html)
281         win.Show(True)
282         
283     def OnPopupTwo(self, event):
284         if 'nb' in dir(self.parent) :
285             activenotebook = self.parent.nb.GetSelection()
286             page = self.parent.nb.GetPage(activenotebook)
287             corpus = page.corpus
288         else :
289             corpus = self.parent.parent.parent.corpus
290         item=self.getColumnText(self.GetFirstSelected(), 0)
291         uce_ok = corpus.getlemuces(item)
292         ira = wx.GetApp().GetTopWindow()
293         ucis_txt, ucestxt = doconcorde(corpus, uce_ok, [item])
294         items = dict([[i, '<br><br>'.join([ucis_txt[i], ucestxt[i]])] for i in range(0,len(ucestxt))])
295         win = message(ira, items, u"Concordancier - %s" % item, (800, 500))
296         #win = message(ira, u"Concordancier", (800, 500))
297         #win.html = ('<html>\n<h1>%s</h1>' % item) + '<br>'.join(['<br>'.join([ucis_txt[i], ucestxt[i]]) for i in range(0,len(ucestxt))]) + '\n</html>'
298         #win.HtmlPage.SetPage(win.html)
299         win.Show(True)
300
301     def getinf(self, txt) :
302         if txt == float('Inf') :
303             return 'Inf'
304         elif txt == float('-Inf') :
305             return '-Inf'
306         else :
307             return `txt`
308
309     def OnPopupThree(self, event) :
310         datas = [self.GetItemData(self.GetFirstSelected())]
311         last = self.GetFirstSelected()
312         while self.GetNextSelected(last) != -1:
313             last = self.GetNextSelected(last)
314             data = self.GetItemData(last)
315             datas += [data]
316         colnames = self.first
317         table = [[self.getinf(val) for val in line[1:]] for line in datas]
318         rownames = [val[0] for val in datas]
319         tmpgraph = tempfile.mktemp(dir=self.parent.TEMPDIR)
320         txt = barplot(table, rownames, colnames, self.parent.RscriptsPath['Rgraph'], tmpgraph)
321         tmpscript = tempfile.mktemp(dir=self.parent.TEMPDIR)
322         with open(tmpscript,'w') as f :
323             f.write(txt)
324         exec_rcode(self.parent.RPath, tmpscript, wait = True)
325         win = MessageImage(self, u"Graphique", size=(700, 500))
326         win.addsaveimage(tmpgraph)
327         txt = "<img src='%s'>" % tmpgraph
328         win.HtmlPage.SetPage(txt)
329         win.Show(True)
330
331     def OnTgen_glob(self, evt) :
332         activenotebook = self.parent.nb.GetSelection()
333         page = self.parent.nb.GetPage(activenotebook)
334         corpus = page.corpus
335
336         tmpgraph = tempfile.mktemp(dir=self.parent.TEMPDIR)
337         intxt = """
338         load("%s")
339         """ % corpus.dictpathout['RData']
340         intxt += """
341         Tgen.glob = NULL
342         tovire <- NULL
343         for (i in 1:ncol(dmf)) {
344             Tgen.glob <- rbind(Tgen.glob,colSums(dmf[which(specf[,i] > 3),]))
345             tovire <- append(tovire, which(specf[,i] > 3))
346         }
347         rownames(Tgen.glob) <- colnames(dmf)
348         Tgen.table <- dmf[-unique(tovire),]
349         Tgen.table<- rbind(Tgen.table, Tgen.glob)
350         spec.Tgen.glob <- AsLexico2(Tgen.table)
351         spec.Tgen.glob <- spec.Tgen.glob[[1]][((nrow(Tgen.table)-ncol(Tgen.table))+1):nrow(Tgen.table),]
352         di <- spec.Tgen.glob
353         """
354         txt = barplot('', '', '', self.parent.RscriptsPath['Rgraph'], tmpgraph, intxt = intxt) 
355         tmpscript = tempfile.mktemp(dir=self.parent.TEMPDIR)
356         with open(tmpscript, 'w') as f :
357             f.write(txt)
358         exec_rcode(self.parent.RPath, tmpscript, wait = True)
359         win = MessageImage(self, -1, u"Graphique", size=(700, 500),style = wx.DEFAULT_FRAME_STYLE)
360         win.addsaveimage(tmpgraph)
361         txt = "<img src='%s'>" % tmpgraph
362         win.HtmlPage.SetPage(txt)
363         win.Show(True)
364     
365     def OnMakeTgen(self, evt):
366         self.parent.tree.OnTgenEditor(self.getselectedwords())