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