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