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