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
7 #----------------------------------------------------------------------------
8 #comes from ListCtrl.py from the demo tool of wxPython:
9 # Author: Robin Dunn & Gary Dumer
12 # Copyright: (c) 1998 by Total Control Software
13 # Licence: wxWindows license
14 #----------------------------------------------------------------------------
16 #------------------------------------
17 # import des modules python
18 #------------------------------------
22 from operator import itemgetter
27 #------------------------------------
28 # import des modules wx
29 #------------------------------------
31 import wx.lib.mixins.listctrl as listmix
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
42 class ListForSpec(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.ColumnSorterMixin):
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)
52 if 'etoiles' in dir(self.gparent) and not usefirst :
53 self.etoiles = self.gparent.etoiles
56 for val in self.first :
57 if val.startswith('X.') :
58 val = val.replace('X.', '*')
59 self.etoiles.append(val)
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)
71 self.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
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")
81 for name in ['formes'] + self.etoiles :
82 self.InsertColumn(i,name,wx.LIST_FORMAT_LEFT)
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)
96 self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightClick)
98 self.Bind(wx.EVT_RIGHT_UP, self.OnRightClick)
99 #-----------------------------------------------------------------------------------------
101 def OnGetItemColumnImage(self, item, col):
104 def OnGetItemImage(self, item):
107 def RefreshData(self, data):
108 self.itemDataMap = data
109 self.itemIndexMap = list(data.keys())
110 self.SetItemCount(len(data))
113 def checkcolumnwidth(self, width) :
119 def OnGetItemText(self, item, col):
120 index=self.itemIndexMap[item]
121 s = self.itemDataMap[index][col]
122 if isinstance(s, (int, float)):
125 return s #modification pour python 3
127 def OnGetItemAttr(self, item):
128 index=self.itemIndexMap[item]
129 if self.IsSelected(index) == False :
135 return self.attrselected
137 def GetItemByWord(self, word):
138 return [ val for val in self.dlist if self.dlist[val][0] == word ][0]
140 # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
141 def GetListCtrl(self):
144 # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
145 def GetSortImages(self):
146 return (self.sm_dn, self.sm_up)
148 def OnRightDown(self, event):
151 item, flags = self.HitTest((x, y))
152 if flags & wx.LIST_HITTEST_ONITEM:
156 def GetString(self, evt):
157 return self.getselectedwords()[0]
159 def GetSelections(self):
160 return self.getselectedwords()
162 def getColumnText(self, index, col):
163 item = self.GetItem(index, col)
164 return item.GetText()
166 def GetItemData(self, item) :
167 index=self.itemIndexMap[item]
168 s = self.itemDataMap[index]
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
180 def OnItemSelected(self, event):
181 self.currentItem = event.GetIndex() #event.m_itemIndex
184 def onsearch(self, evt) :
185 self.dial = SearchDial(self, self, 0, True)
186 self.dial.CenterOnParent()
190 def OnRightClick(self, event):
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)
212 menu.Append(self.popupID1, _("Associated forms"))
213 menu.Append(self.popupID2, _("Concordance"))
214 menu.Append(self.popupID3, _("Graphic"))
215 menu_stcaract = wx.Menu()
218 for i, et in enumerate(self.etoiles) :
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"))
226 menu.Append(self.id_tgendetails, _('Tgen details'))
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))
238 def OnPopupOne(self, event):
239 activenotebook = self.parent.nb.GetSelection()
240 page = self.parent.nb.GetPage(activenotebook)
242 word = self.getselectedwords()[0]
243 lems = corpus.getlems()
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)
255 def onstcaract(self, evt) :
256 ind = self.menuid[evt.Id]
259 activenotebook = self.parent.nb.GetSelection()
260 page = self.parent.nb.GetPage(activenotebook)
261 item=self.getColumnText(self.GetFirstSelected(), 0)
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') :
272 for val in self.lchi :
273 if val == float('inf') :
278 nchi = [val if val != float('inf') else nmax + 2 for val in self.lchi]
280 tab = corpus.make_pondtable_with_classe(uces, self.la)
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]
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))
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)
299 corpus = self.parent.parent.parent.corpus
300 ira = wx.GetApp().GetTopWindow()
301 item=self.getColumnText(self.GetFirstSelected(), 0)
303 uce_ok = corpus.getlemuces(item)
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)
313 def getinf(self, txt) :
314 if txt == float('Inf') :
316 elif txt == float('-Inf') :
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)
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)
333 def OnTgen_glob(self, evt) :
334 activenotebook = self.parent.nb.GetSelection()
335 page = self.parent.nb.GetPage(activenotebook)
337 # préparation du script R
338 tmpgraph = tempfile.mktemp(dir=self.parent.TEMPDIR)
341 """ % corpus.dictpathout['RData']
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))
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),]
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 :
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)
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)
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)
384 def OnMakeTgen(self, evt):
385 self.parent.tree.OnTgenEditor(self.getselectedwords())
388 class ListLexFrame ( wx.Frame ):
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 )
405 self.Centre( wx.BOTH )