multisplit
[iramuteq] / listlex.py
1 # -*- coding: utf-8 -*-
2 #Author: Pierre Ratinaud
3 #Copyright (c) 2008-2020 Pierre Ratinaud
4 #modification pour python 3 : Laurent Mérat, 6x7 - mai 2020
5 #License: GNU/GPL
6
7 #----------------------------------------------------------------------------
8 #comes from ListCtrl.py from the demo tool of wxPython:
9 # Author:       Robin Dunn & Gary Dumer
10 #
11 # Created:
12 # Copyright:    (c) 1998 by Total Control Software
13 # Licence:      wxWindows license
14 #----------------------------------------------------------------------------
15
16 #------------------------------------
17 # import des modules python
18 #------------------------------------
19 import os
20 import sys
21 import tempfile
22 from operator import itemgetter
23
24 import langue
25 langue.run()
26
27 #------------------------------------
28 # import des modules wx
29 #------------------------------------
30 import wx
31 import wx.lib.mixins.listctrl as listmix
32
33 #------------------------------------
34 # import des fichiers du projet
35 #------------------------------------
36 from functions import exec_rcode, doconcorde
37 from chemins import ffr
38 from PrintRScript import barplot
39 from dialog import SearchDial, message, BarGraphDialog, BarFrame
40
41
42 class ListForSpec(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.ColumnSorterMixin):
43
44     def __init__(self, parent,gparent, dlist = {}, first = [], usefirst = False, menu = True):
45         wx.ListCtrl.__init__( self, parent, -1, style=wx.LC_REPORT|wx.LC_VIRTUAL|wx.LC_HRULES|wx.LC_VRULES)
46         self.parent=parent
47         self.gparent=gparent
48         self.dlist=dlist
49         self.first = first
50         self.tgen = False
51         self.tgenlem = False
52         if 'etoiles' in dir(self.gparent) and not usefirst :
53             self.etoiles = self.gparent.etoiles
54         else :
55             self.etoiles = []
56             for val in self.first :
57                 if val.startswith('X.') :
58                     val = val.replace('X.', '*')
59                 self.etoiles.append(val)
60         self.menu = menu
61         #def start(self) :
62         search_id = wx.NewId()
63         self.parent.Bind(wx.EVT_MENU, self.onsearch, id = search_id)
64         self.accel_tbl = wx.AcceleratorTable([(wx.ACCEL_CTRL, ord('F'), search_id)])
65         self.SetAcceleratorTable(self.accel_tbl)
66         self.il = wx.ImageList(16, 16)
67         a={"sm_up":"GO_UP","sm_dn":"GO_DOWN","w_idx":"WARNING","e_idx":"ERROR","i_idx":"QUESTION"}
68         for k,v in list(a.items()):
69             s="self.%s= self.il.Add(wx.ArtProvider.GetBitmap(wx.ART_%s,wx.ART_TOOLBAR,(16,16)))" % (k,v)
70             exec(s)
71         self.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
72         tID = wx.NewId()
73         self.attr1 = wx.ListItemAttr()
74         self.attr1.SetBackgroundColour((230, 230, 230))
75         self.attr2 = wx.ListItemAttr()
76         self.attr2.SetBackgroundColour("light blue")
77         self.attrselected = wx.ListItemAttr()
78         self.attrselected.SetBackgroundColour("red")
79         self.selected = {}
80         i=0
81         for name in ['formes'] + self.etoiles :
82             self.InsertColumn(i,name,wx.LIST_FORMAT_LEFT)
83             i+=1
84         self.SetColumnWidth(0, 180)
85         for i in range(0,len(self.etoiles)):
86             self.SetColumnWidth(i + 1, self.checkcolumnwidth(len(self.etoiles[i]) * 10))
87         self.itemDataMap = self.dlist
88         self.itemIndexMap = list(self.dlist.keys())
89         self.SetItemCount(len(self.dlist))
90         listmix.ColumnSorterMixin.__init__(self, len(self.first) + 1)
91         self.SortListItems(1, False)
92         #-----------------------------------------------------------------------------------------    
93         self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected, self)
94         self.Bind(wx.EVT_LIST_ITEM_ACTIVATED , self.OnPopupTwo, self)
95         # for wxMSW
96         self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightClick)
97         # for wxGTK
98         self.Bind(wx.EVT_RIGHT_UP, self.OnRightClick)
99 #-----------------------------------------------------------------------------------------    
100
101     def OnGetItemColumnImage(self, item, col):
102         return -1
103
104     def OnGetItemImage(self, item):
105         pass
106
107     def RefreshData(self, data):
108         self.itemDataMap = data
109         self.itemIndexMap = list(data.keys())
110         self.SetItemCount(len(data))
111         self.Refresh()
112
113     def checkcolumnwidth(self, width) :
114         if width < 80 :
115             return 80
116         else :
117             return width
118
119     def OnGetItemText(self, item, col):
120         index=self.itemIndexMap[item]
121         s = self.itemDataMap[index][col]
122         if isinstance(s, (int, float)):
123             return str(s)
124         else:
125             return s #modification pour python 3
126
127     def OnGetItemAttr(self, item):
128         index=self.itemIndexMap[item]
129         if self.IsSelected(index) == False :
130             if item % 2 :
131                 return self.attr1
132             else :
133                 return self.attr2
134         else :
135             return self.attrselected
136
137     def GetItemByWord(self, word):
138         return [ val for val in self.dlist if self.dlist[val][0] == word ][0]
139
140     # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
141     def GetListCtrl(self):
142         return self
143
144     # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
145     def GetSortImages(self):
146         return (self.sm_dn, self.sm_up)
147     
148     def OnRightDown(self, event):
149         x = event.GetX()
150         y = event.GetY()
151         item, flags = self.HitTest((x, y))
152         if flags & wx.LIST_HITTEST_ONITEM:
153             self.Select(item)
154         event.Skip()
155
156     def GetString(self, evt):
157         return self.getselectedwords()[0]
158
159     def GetSelections(self):
160         return self.getselectedwords()
161
162     def getColumnText(self, index, col):
163         item = self.GetItem(index, col)
164         return item.GetText()
165
166     def GetItemData(self, item) :
167         index=self.itemIndexMap[item]
168         s = self.itemDataMap[index]
169         return s
170     
171 #    def SortItems(self,sorter=cmp): # modification pour python 3
172     def SortItems(self, sorter=None):
173         listTemp = sorted(self.itemDataMap.items(),
174             key=lambda x:x[1][self._col], reverse= (self._colSortFlag[self._col]!=True))
175         dlist = dict([[line[0],line[1]] for line in listTemp])
176         self.itemDataMap = dlist
177         self.itemIndexMap = list(dlist.keys())
178         self.Refresh() # redraw the list
179
180     def OnItemSelected(self, event):
181         self.currentItem = event.GetIndex() #event.m_itemIndex
182         event.Skip()
183
184     def onsearch(self, evt) :
185         self.dial = SearchDial(self, self, 0, True)
186         self.dial.CenterOnParent()
187         self.dial.Show()
188         #self.dial.Destroy()
189     
190     def OnRightClick(self, event):
191         if self.menu :
192             # only do this part the first time so the events are only bound once
193             if not hasattr(self, "popupID1"):
194                 self.popupID1 = wx.NewId()
195                 self.popupID2 = wx.NewId()
196                 self.popupID3 = wx.NewId()
197                 self.popup_Tgen_glob = wx.NewId()
198                 self.onmaketgen = wx.NewId()
199                 self.ID_stcaract = wx.NewId()
200                 self.id_tgendetails = wx.NewId()
201                 # on attache les événements aux éléments
202                 self.Bind(wx.EVT_MENU, self.OnPopupOne, id = self.popupID1)
203                 self.Bind(wx.EVT_MENU, self.OnPopupTwo, id = self.popupID2)
204                 self.Bind(wx.EVT_MENU, self.OnPopupThree, id = self.popupID3)
205                 self.Bind(wx.EVT_MENU, self.OnTgen_glob, id = self.popup_Tgen_glob)
206                 self.Bind(wx.EVT_MENU, self.OnMakeTgen, id = self.onmaketgen)
207                 self.Bind(wx.EVT_MENU, self.OnTgenDetails, id = self.id_tgendetails)
208                 #self.Bind(wx.EVT_MENU, self.onstcaract, id = self.ID_stcaract)
209             # make a menu
210             menu = wx.Menu()
211             # add some items
212             menu.Append(self.popupID1, _("Associated forms"))
213             menu.Append(self.popupID2, _("Concordance"))
214             menu.Append(self.popupID3, _("Graphic"))
215             menu_stcaract = wx.Menu()
216             self.menuid = {}
217             if not self.tgen :
218                 for i, et in enumerate(self.etoiles) :
219                     nid = wx.NewId()
220                     self.menuid[nid] = i
221                     menu_stcaract.Append(nid, et)
222                     self.Bind(wx.EVT_MENU, self.onstcaract, id = nid)
223                 menu.Append(-1, _("Typical text segments"), menu_stcaract) #modifié
224                 menu.Append(self.onmaketgen, _("Make Tgen"))
225             else :
226                 menu.Append(self.id_tgendetails, _('Tgen details'))
227             self.PopupMenu(menu)
228             menu.Destroy()
229
230     def getselectedwords(self) :
231         words = [self.getColumnText(self.GetFirstSelected(), 0)]
232         last = self.GetFirstSelected()
233         while self.GetNextSelected(last) != -1:
234             last = self.GetNextSelected(last)
235             words.append(self.getColumnText(last, 0))
236         return words
237
238     def OnPopupOne(self, event):
239         activenotebook = self.parent.nb.GetSelection()
240         page = self.parent.nb.GetPage(activenotebook)
241         corpus = page.corpus
242         word = self.getselectedwords()[0]
243         lems = corpus.getlems()
244         rep = []
245         for forme in lems[word].formes :
246             rep.append([corpus.getforme(forme).forme, corpus.getforme(forme).freq])
247         rep.sort(key = itemgetter(1), reverse = True)
248         items = dict([[i, '<font face="courier">' + '\t:\t'.join([str(val) for val in forme]) + '</font>'] for i, forme in enumerate(rep)])
249         win = message(self, items, _("Associated forms"), (300, 200))
250         #win = message(self, u"Formes associées", (300, 200))
251         #win.html = '<html>\n' + '<br>'.join([' : '.join([str(val) for val in forme]) for forme in rep]) + '\n</html>'
252         #win.HtmlPage.SetPage(win.html)
253         win.Show(True)
254
255     def onstcaract(self, evt) :
256         ind = self.menuid[evt.Id]
257         limite = 50
258         minind = 2
259         activenotebook = self.parent.nb.GetSelection()
260         page = self.parent.nb.GetPage(activenotebook)
261         item=self.getColumnText(self.GetFirstSelected(), 0)
262         corpus = page.corpus
263         parametres = page.parametres
264         paneff = self.gparent.ListPanEff
265         panchi = self.gparent.ListPan
266         et = self.etoiles[ind]
267         uces = corpus.getucesfrometoile(et)
268         self.la = [panchi.dlist[i][0] for i in range(0, len(panchi.dlist)) if panchi.dlist[i][ind+1] >= minind ]
269         self.lchi = [panchi.dlist[i][ind+1] for i in range(0, len(panchi.dlist)) if panchi.dlist[i][ind+1] >= minind ]
270         if max(self.lchi) == float('inf') :
271             nchi = []
272             for val in self.lchi :
273                 if val == float('inf') :
274                     nchi.append(0)
275                 else :
276                     nchi.append(val)
277             nmax = max(nchi)
278             nchi = [val if val != float('inf') else nmax + 2 for val in self.lchi]
279             self.lchi = nchi
280         tab = corpus.make_pondtable_with_classe(uces, self.la)
281         tab.pop(0)
282         ntab = [round(sum([(self.lchi[i] * word) for i, word in enumerate(line) if word != 0]),2) for line in tab]
283         ntab2 = [[ntab[i], uces[i]] for i, val in enumerate(ntab) if ntab[i] != 0]
284         del ntab
285         ntab2.sort(reverse = True)
286         ntab2 = ntab2[:limite]
287         nuces = [val[1] for val in ntab2]
288         ucis_txt, ucestxt = doconcorde(corpus, nuces, self.la)
289         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))])
290         win = message(self, items, ' - '.join([_("Typical text segments"), "%s" % self.first[ind]]), (900, 600))
291         win.Show(True)
292         
293     def OnPopupTwo(self, event):
294         if 'nb' in dir(self.parent) :
295             activenotebook = self.parent.nb.GetSelection()
296             page = self.parent.nb.GetPage(activenotebook)
297             corpus = page.corpus
298         else :
299             corpus = self.parent.parent.parent.corpus
300         ira = wx.GetApp().GetTopWindow()
301         item=self.getColumnText(self.GetFirstSelected(), 0)
302         if not self.tgen :
303             uce_ok = corpus.getlemuces(item)
304             wordlist = [item]
305         else :
306             uce_ok = corpus.gettgenst(self.tgens[item])
307             wordlist = [val for val in self.tgens[item] if val in corpus.lems]
308         ucis_txt, ucestxt = doconcorde(corpus, uce_ok, wordlist)
309         items = dict([[i, '<br><br>'.join([ucis_txt[i], ucestxt[i]])] for i in range(0,len(ucestxt))])
310         win = message(ira, items, ' - '.join([_("Concordance"), "%s" % item]), (800, 500), uceids = uce_ok)
311         win.Show(True)
312
313     def getinf(self, txt) :
314         if txt == float('Inf') :
315             return 'Inf'
316         elif txt == float('-Inf') :
317             return '-Inf'
318         else :
319             return repr(txt)
320
321     def OnPopupThree(self, event) :
322         datas = [self.GetItemData(self.GetFirstSelected())]
323         last = self.GetFirstSelected()
324         while self.GetNextSelected(last) != -1:
325             last = self.GetNextSelected(last)
326             data = self.GetItemData(last)
327             datas += [data]
328         colnames = self.first
329         table = [[self.getinf(val) for val in line[1:]] for line in datas]
330         rownames = [val[0] for val in datas]
331         BarFrame(self.parent, table, colnames, rownames)
332
333     def OnTgen_glob(self, evt) :
334         activenotebook = self.parent.nb.GetSelection()
335         page = self.parent.nb.GetPage(activenotebook)
336         corpus = page.corpus
337         # préparation du script R
338         tmpgraph = tempfile.mktemp(dir=self.parent.TEMPDIR)
339         intxt = """
340         load("%s")
341         """ % corpus.dictpathout['RData']
342         intxt += """
343         Tgen.glob = NULL
344         tovire <- NULL
345         for (i in 1:ncol(dmf)) {
346             Tgen.glob <- rbind(Tgen.glob,colSums(dmf[which(specf[,i] > 3),]))
347             tovire <- append(tovire, which(specf[,i] > 3))
348         }
349         rownames(Tgen.glob) <- colnames(dmf)
350         Tgen.table <- dmf[-unique(tovire),]
351         Tgen.table<- rbind(Tgen.table, Tgen.glob)
352         spec.Tgen.glob <- AsLexico2(Tgen.table)
353         spec.Tgen.glob <- spec.Tgen.glob[[1]][((nrow(Tgen.table)-ncol(Tgen.table))+1):nrow(Tgen.table),]
354         di <- spec.Tgen.glob
355         """
356         txt = barplot('', '', '', self.parent.RscriptsPath['Rgraph'], tmpgraph, intxt = intxt) 
357         # ecriture du script dans un fichier
358         tmpscript = tempfile.mktemp(dir=self.parent.TEMPDIR)
359         with open(tmpscript, 'w') as f :
360             f.write(txt)
361         # excution du script
362         exec_rcode(self.parent.RPath, tmpscript, wait = True)
363         win = MessageImage(self, -1, _("Graphic"), size=(700, 500),style = wx.DEFAULT_FRAME_STYLE)
364         win.addsaveimage(tmpgraph)
365         txt = "<img src='%s'>" % tmpgraph
366         win.HtmlPage.SetPage(txt)
367         win.Show(True)
368     
369     def OnTgenDetails(self, evt):
370         if 'nb' in dir(self.parent) :
371             activenotebook = self.parent.nb.GetSelection()
372             page = self.parent.nb.GetPage(activenotebook)
373             corpus = page.corpus
374         else :
375             corpus = self.parent.parent.parent.corpus
376         ira = wx.GetApp().GetTopWindow()
377         item=self.getColumnText(self.GetFirstSelected(), 0)
378         wordlist = [val for val in self.tgens[item] if val in corpus.lems]
379         wordlist = dict(list(zip(wordlist,wordlist)))
380         res = dict([[val, self.tgenlem[val]] for val in self.tgenlem if self.tgenlem[val][0] in wordlist])
381         win = ListLexFrame(self, ira, corpus, res, self.etoiles)
382         win.Show()
383
384     def OnMakeTgen(self, evt):
385         self.parent.tree.OnTgenEditor(self.getselectedwords())
386
387
388 class ListLexFrame ( wx.Frame ):
389
390     def __init__( self, parent, ira, corpus, data, columns ):
391         wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 500,300 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
392         self.SetSizeHints( wx.DefaultSize, wx.DefaultSize )
393         bSizer1 = wx.BoxSizer( wx.VERTICAL )
394         self.listlex = ListForSpec(self, ira, data, columns)
395         bSizer1.Add( self.listlex, 5, wx.ALL|wx.EXPAND, 5 )
396         m_sdbSizer1 = wx.StdDialogButtonSizer()
397         self.m_sdbSizer1OK = wx.Button( self, wx.ID_OK )
398         m_sdbSizer1.AddButton( self.m_sdbSizer1OK )
399         self.m_sdbSizer1Cancel = wx.Button( self, wx.ID_CANCEL )
400         m_sdbSizer1.AddButton( self.m_sdbSizer1Cancel )
401         m_sdbSizer1.Realize();
402         bSizer1.Add( m_sdbSizer1, 0, wx.EXPAND, 5 )
403         self.SetSizer( bSizer1 )
404         self.Layout()
405         self.Centre( wx.BOTH )
406
407     def __del__( self ):
408         pass