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