solve clustering on text when segment have been made
[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         self.Bind(wx.EVT_LIST_ITEM_ACTIVATED , self.OnPopupTwo, self)
80         # for wxMSW
81         self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightClick)
82
83         # for wxGTK
84         self.Bind(wx.EVT_RIGHT_UP, self.OnRightClick)
85
86 #-----------------------------------------------------------------------------------------    
87         
88     def checkcolumnwidth(self, width) :
89         if width < 80 :
90             return 80
91         else :
92             return width
93
94     def OnGetItemText(self, item, col):
95         index=self.itemIndexMap[item]
96         s = self.itemDataMap[index][col]
97         return s
98
99     def OnGetItemAttr(self, item):
100         if item % 2 :
101             return self.attr1
102         else :
103             return self.attr2
104
105
106     # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
107     def GetListCtrl(self):
108         return self
109
110     # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
111     def GetSortImages(self):
112         return (self.sm_dn, self.sm_up)
113     
114     def OnRightDown(self, event):
115         x = event.GetX()
116         y = event.GetY()
117         item, flags = self.HitTest((x, y))
118
119         if flags & wx.LIST_HITTEST_ONITEM:
120             self.Select(item)
121
122         event.Skip()
123
124     def getColumnText(self, index, col):
125         item = self.GetItem(index, col)
126         return item.GetText()
127
128     def GetItemData(self, item) :
129         index=self.itemIndexMap[item]
130         s = self.itemDataMap[index]
131         return s
132     
133     def SortItems(self,sorter=cmp):
134         items = list(self.itemDataMap.keys())
135         items.sort(sorter)
136         self.itemIndexMap = items
137         # redraw the list
138         self.Refresh()
139     
140     def OnItemSelected(self, event):
141         self.currentItem = event.m_itemIndex
142         event.Skip()
143
144     def onsearch(self, evt) :
145         self.dial = SearchDial(self, self, 0, True)
146         self.dial.CenterOnParent()
147         self.dial.Show()
148         #self.dial.Destroy()
149     
150     def OnRightClick(self, event):
151         if self.menu :
152             # only do this part the first time so the events are only bound once
153             if not hasattr(self, "popupID1"):
154                 self.popupID1 = wx.NewId()
155                 self.popupID2 = wx.NewId()
156                 self.popupID3 = wx.NewId()
157                 self.popup_Tgen_glob = wx.NewId()
158                 self.ID_stcaract = wx.NewId()
159
160                 self.Bind(wx.EVT_MENU, self.OnPopupOne, id=self.popupID1)
161                 self.Bind(wx.EVT_MENU, self.OnPopupTwo, id=self.popupID2)
162                 self.Bind(wx.EVT_MENU, self.OnPopupThree, id=self.popupID3)
163                 self.Bind(wx.EVT_MENU, self.OnTgen_glob, id=self.popup_Tgen_glob)
164                 #self.Bind(wx.EVT_MENU, self.onstcaract, id = self.ID_stcaract)
165             # make a menu
166             menu = wx.Menu()
167             # add some items
168             menu.Append(self.popupID1, u"Formes associées")
169             menu.Append(self.popupID2, u"Concordancier")
170             menu.Append(self.popupID3, "Graphique")
171             menu_stcaract = wx.Menu()
172             self.menuid = {}
173             for i, et in enumerate(self.first[1:]) :
174                 nid = wx.NewId()
175                 self.menuid[nid] = i
176                 menu_stcaract.Append(nid, et)
177                 self.Bind(wx.EVT_MENU, self.onstcaract, id = nid)
178             menu.AppendMenu(-1, u"Segments de texte caractéristiques", menu_stcaract)
179             #menu.Append(self.popup_Tgen_glob, "Tgen global")
180             self.PopupMenu(menu)
181             menu.Destroy()
182
183     def getselectedwords(self) :
184         words = [self.getColumnText(self.GetFirstSelected(), 0)]
185         last = self.GetFirstSelected()
186         while self.GetNextSelected(last) != -1:
187             last = self.GetNextSelected(last)
188             words.append(self.getColumnText(last, 1))
189         return words
190
191     def OnPopupOne(self, event):
192         activenotebook = self.parent.nb.GetSelection()
193         page = self.parent.nb.GetPage(activenotebook)
194         corpus = page.corpus
195         word = self.getselectedwords()[0]
196         lems = corpus.getlems()
197         rep = []
198         for forme in lems[word].formes :
199             rep.append([corpus.getforme(forme).forme, corpus.getforme(forme).freq])
200         rep.sort(key = itemgetter(1), reverse = True)
201         win = message(self, u"Formes associées", (300, 200))
202         win.html = '<html>\n' + '<br>'.join([' : '.join([str(val) for val in forme]) for forme in rep]) + '\n</html>'
203         win.HtmlPage.SetPage(win.html)
204         win.Show(True)
205     
206     def onstcaract(self, evt) :
207         ind = self.menuid[evt.Id]
208         limite = 50
209         minind = 2
210         activenotebook = self.parent.nb.GetSelection()
211         page = self.parent.nb.GetPage(activenotebook)
212         item=self.getColumnText(self.GetFirstSelected(), 0)
213         corpus = page.corpus
214         parametres = page.parametres
215         paneff = self.gparent.ListPanEff
216         panchi = self.gparent.ListPan
217         et = self.first[ind+1]
218         if et.startswith(u'X.') :
219             et = et.replace(u'X.', u'*')
220         uces = corpus.getucesfrometoile(et)
221         self.la = [panchi.dlist[i][0] for i in range(0, len(panchi.dlist)) if panchi.dlist[i][ind+1] >= minind ]
222         self.lchi = [panchi.dlist[i][ind+1] for i in range(0, len(panchi.dlist)) if panchi.dlist[i][ind+1] >= minind ]
223         #lfreq = [paneff.dlist[i][ind+1] for i in range(0, len(panchi.dlist)) if panchi.dlist[i][ind+1] >= minind ]
224         if max(self.lchi) == float('inf') :
225             nchi = []
226             for val in self.lchi :
227                 if val == float('inf') :
228                     nchi.append(0)
229                 else :
230                     nchi.append(val)
231             nmax = max(nchi)
232             nchi = [val if val != float('inf') else nmax + 2 for val in self.lchi]
233             self.lchi = nchi
234         tab = corpus.make_pondtable_with_classe(uces, self.la)
235         tab.pop(0)
236         ntab = [round(sum([(self.lchi[i] * word) for i, word in enumerate(line) if word != 0]),2) for line in tab]
237         ntab2 = [[ntab[i], uces[i]] for i, val in enumerate(ntab) if ntab[i] != 0]
238         del ntab
239         ntab2.sort(reverse = True)
240         ntab2 = ntab2[:limite]
241         nuces = [val[1] for val in ntab2]
242         ucis_txt, ucestxt = doconcorde(corpus, nuces, self.la)
243         win = message(self, u"Segments de texte caractéristiques - %s" % self.first[ind], (750, 600))
244         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>'
245         win.HtmlPage.SetPage(win.html)
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)