windows
[iramuteq] / listlex.py
index 5d34a66..285745a 100644 (file)
@@ -16,28 +16,35 @@ import os
 import sys
 import  wx
 import  wx.lib.mixins.listctrl  as  listmix
-import cStringIO
 import tempfile
-from functions import exec_rcode, MessageImage
+from functions import exec_rcode, doconcorde
 from chemins import ffr
 from PrintRScript import barplot
-from dialog import SearchDial
+from dialog import SearchDial, message, BarGraphDialog, BarFrame
+from operator import itemgetter
 #---------------------------------------------------------------------------
 
-#class List(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
-#    def __init__(self, parent, ID, pos=wx.DefaultPosition,
-#                 size=wx.DefaultSize, style=0):
-#        wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
-#        listmix.ListCtrlAutoWidthMixin.__init__(self)
-
 class ListForSpec(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.ColumnSorterMixin):
-    def __init__(self, parent,gparent, dlist,first):
+    def __init__(self, parent,gparent, dlist = {}, first = [], usefirst = False, menu = True):
+    #def  __init__(self, parent) :
         wx.ListCtrl.__init__( self, parent, -1, style=wx.LC_REPORT|wx.LC_VIRTUAL|wx.LC_HRULES|wx.LC_VRULES)
         self.parent=parent
         self.gparent=gparent
         self.dlist=dlist
         self.first = first
-
+        self.tgen = False
+        self.tgenlem = False
+        if 'etoiles' in dir(self.gparent) and not usefirst :
+            self.etoiles = self.gparent.etoiles
+        else :
+            self.etoiles = []
+            for val in self.first :
+                if val.startswith(u'X.') :
+                    val = val.replace(u'X.', u'*')
+                self.etoiles.append(val)
+        self.menu = menu
+
+    #def start(self) :
         search_id = wx.NewId()
         self.parent.Bind(wx.EVT_MENU, self.onsearch, id = search_id)
         self.accel_tbl = wx.AcceleratorTable([(wx.ACCEL_CTRL, ord('F'), search_id)])
@@ -56,49 +63,67 @@ class ListForSpec(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.ColumnSor
         self.attr1.SetBackgroundColour((230, 230, 230))
         self.attr2 = wx.ListItemAttr()
         self.attr2.SetBackgroundColour("light blue")
+        self.attrselected = wx.ListItemAttr()
+        self.attrselected.SetBackgroundColour("red")
+        self.selected = {}
         
-        self.dlist = dlist 
+        i=0
+        for name in [u'formes'] + self.etoiles :
+            self.InsertColumn(i,name,wx.LIST_FORMAT_LEFT)
+            i+=1
+            
+        self.SetColumnWidth(0, 180)
 
+        for i in range(0,len(self.etoiles)):
+            self.SetColumnWidth(i + 1, self.checkcolumnwidth(len(self.etoiles[i]) * 10))
+        
+        self.itemDataMap = self.dlist
+        self.itemIndexMap = self.dlist.keys()
+        self.SetItemCount(len(self.dlist))
+        
+        #listmix.ListCtrlAutoWidthMixin.__init__(self)
+        listmix.ColumnSorterMixin.__init__(self, len(self.first) + 1)
+        self.SortListItems(1, 0)
+        
+#-----------------------------------------------------------------------------------------    
         self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected, self)
         
+        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED , self.OnPopupTwo, self)
         # for wxMSW
         self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightClick)
 
         # for wxGTK
         self.Bind(wx.EVT_RIGHT_UP, self.OnRightClick)
-        
-        
-        self.itemDataMap = dlist
-        self.itemIndexMap = dlist.keys()
-        self.SetItemCount(len(dlist))
-        
-        listmix.ListCtrlAutoWidthMixin.__init__(self)
-        listmix.ColumnSorterMixin.__init__(self, len(first))
-        self.SortListItems(1, False)
-        
-#-----------------------------------------------------------------------------------------    
-
-        i=0
-        for name in first :
-            self.InsertColumn(i,name,wx.LIST_FORMAT_LEFT)
-            i+=1
-            
-        self.SetColumnWidth(0, 180)
 
-        for i in range(1,len(first)-1):
-            self.SetColumnWidth(i, len(first[i]) * 10)
+#-----------------------------------------------------------------------------------------    
+    def RefreshData(self, data):
+        self.itemDataMap = data
+        self.itemIndexMap = data.keys()
+        self.SetItemCount(len(data))
+        self.Refresh()
         
+    def checkcolumnwidth(self, width) :
+        if width < 80 :
+            return 80
+        else :
+            return width
+
     def OnGetItemText(self, item, col):
         index=self.itemIndexMap[item]
         s = self.itemDataMap[index][col]
         return s
 
     def OnGetItemAttr(self, item):
-        if item % 2 :
-            return self.attr1
+        if self.getColumnText(item, 0) not in self.selected :
+            if item % 2 :
+                return self.attr1
+            else :
+                return self.attr2
         else :
-            return self.attr2
-
+            return self.attrselected
+    
+    def GetItemByWord(self, word):
+        return [ val for val in self.dlist if self.dlist[val][0] == word ][0]
 
     # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
     def GetListCtrl(self):
@@ -107,8 +132,7 @@ class ListForSpec(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.ColumnSor
     # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
     def GetSortImages(self):
         return (self.sm_dn, self.sm_up)
-
-
+    
     def OnRightDown(self, event):
         x = event.GetX()
         y = event.GetY()
@@ -118,6 +142,12 @@ class ListForSpec(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.ColumnSor
             self.Select(item)
 
         event.Skip()
+    
+    def GetString(self, evt):
+        return self.getselectedwords()[0]
+    
+    def GetSelections(self):
+        return self.getselectedwords()
 
     def getColumnText(self, index, col):
         item = self.GetItem(index, col)
@@ -127,7 +157,14 @@ class ListForSpec(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.ColumnSor
         index=self.itemIndexMap[item]
         s = self.itemDataMap[index]
         return s
-
+    
+    def SortItems(self,sorter=cmp):
+        items = list(self.itemDataMap.keys())
+        items.sort(sorter)
+        self.itemIndexMap = items
+        # redraw the list
+        self.Refresh()
+    
     def OnItemSelected(self, event):
         self.currentItem = event.m_itemIndex
         event.Skip()
@@ -135,102 +172,158 @@ class ListForSpec(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.ColumnSor
     def onsearch(self, evt) :
         self.dial = SearchDial(self, self, 0, True)
         self.dial.CenterOnParent()
-        self.dial.ShowModal()
-        self.dial.Destroy()
+        self.dial.Show()
+        #self.dial.Destroy()
     
     def OnRightClick(self, event):
-
-        # only do this part the first time so the events are only bound once
-        if not hasattr(self, "popupID1"):
-            self.popupID1 = wx.NewId()
-            self.popupID2 = wx.NewId()
-            self.popupID3 = wx.NewId()
-            self.popup_Tgen_glob = wx.NewId()
-
-            self.Bind(wx.EVT_MENU, self.OnPopupOne, id=self.popupID1)
-            self.Bind(wx.EVT_MENU, self.OnPopupTwo, id=self.popupID2)
-            self.Bind(wx.EVT_MENU, self.OnPopupThree, id=self.popupID3)
-            self.Bind(wx.EVT_MENU, self.OnTgen_glob, id=self.popup_Tgen_glob)
-        # make a menu
-        menu = wx.Menu()
-        # add some items
-        menu.Append(self.popupID1, u"Formes associées")
-        menu.Append(self.popupID2, u"Concordancier")
-        menu.Append(self.popupID3, "Graphique")
-        #menu.Append(self.popup_Tgen_glob, "Tgen global")
-
-        self.PopupMenu(menu)
-        menu.Destroy()
-
+        if self.menu :
+            # only do this part the first time so the events are only bound once
+            if not hasattr(self, "popupID1"):
+                self.popupID1 = wx.NewId()
+                self.popupID2 = wx.NewId()
+                self.popupID3 = wx.NewId()
+                self.popup_Tgen_glob = wx.NewId()
+                self.onmaketgen = wx.NewId()
+                self.ID_stcaract = wx.NewId()
+                self.id_tgendetails = wx.NewId()
+
+                self.Bind(wx.EVT_MENU, self.OnPopupOne, id = self.popupID1)
+                self.Bind(wx.EVT_MENU, self.OnPopupTwo, id = self.popupID2)
+                self.Bind(wx.EVT_MENU, self.OnPopupThree, id = self.popupID3)
+                self.Bind(wx.EVT_MENU, self.OnTgen_glob, id = self.popup_Tgen_glob)
+                self.Bind(wx.EVT_MENU, self.OnMakeTgen, id = self.onmaketgen)
+                self.Bind(wx.EVT_MENU, self.OnTgenDetails, id = self.id_tgendetails)
+                #self.Bind(wx.EVT_MENU, self.onstcaract, id = self.ID_stcaract)
+            # make a menu
+            menu = wx.Menu()
+            # add some items
+            menu.Append(self.popupID1, _(u"Associated forms").decode('utf8'))
+            menu.Append(self.popupID2, _(u"Concordance").decode('utf8'))
+            menu.Append(self.popupID3, _(u"Graphic").decode('utf8'))
+            menu_stcaract = wx.Menu()
+            self.menuid = {}
+            if not self.tgen :
+                for i, et in enumerate(self.etoiles) :
+                    nid = wx.NewId()
+                    self.menuid[nid] = i
+                    menu_stcaract.Append(nid, et)
+                    self.Bind(wx.EVT_MENU, self.onstcaract, id = nid)
+                menu.AppendMenu(-1, _(u"Typical text segments").decode('utf8'), menu_stcaract)
+                menu.Append(self.onmaketgen, _(u"Make Tgen").decode('utf8'))
+            else :
+                menu.Append(self.id_tgendetails, _(u'Tgen details').decode('utf8'))
+            self.PopupMenu(menu)
+            menu.Destroy()
+
+    def getselectedwords(self) :
+        words = [self.getColumnText(self.GetFirstSelected(), 0)]
+        last = self.GetFirstSelected()
+        while self.GetNextSelected(last) != -1:
+            last = self.GetNextSelected(last)
+            words.append(self.getColumnText(last, 0))
+        return words
 
     def OnPopupOne(self, event):
         activenotebook = self.parent.nb.GetSelection()
         page = self.parent.nb.GetPage(activenotebook)
         corpus = page.corpus
-        word = self.getColumnText(self.GetFirstSelected(), 0)
+        word = self.getselectedwords()[0]
         lems = corpus.getlems()
         rep = []
         for forme in lems[word].formes :
-             rep.append([corpus.getforme(forme).forme, corpus.getforme(forme).freq])
-        win = message(self, -1, u"Formes associées", size=(300, 200), style=wx.DEFAULT_FRAME_STYLE)
-        win.html = '<html>\n' + '<br>'.join([' : '.join([str(val) for val in forme]) for forme in rep]) + '\n</html>'
-        win.HtmlPage.SetPage(win.html)
+            rep.append([corpus.getforme(forme).forme, corpus.getforme(forme).freq])
+        rep.sort(key = itemgetter(1), reverse = True)
+        items = dict([[i, '<font face="courier">' + '\t:\t'.join([str(val) for val in forme]) + '</font>'] for i, forme in enumerate(rep)])
+        win = message(self, items, _(u"Associated forms").decode('utf8'), (300, 200))
+        #win = message(self, u"Formes associées", (300, 200))
+        #win.html = '<html>\n' + '<br>'.join([' : '.join([str(val) for val in forme]) for forme in rep]) + '\n</html>'
+        #win.HtmlPage.SetPage(win.html)
         win.Show(True)
-
-    def OnPopupTwo(self, event):
+    
+    def onstcaract(self, evt) :
+        ind = self.menuid[evt.Id]
+        limite = 50
+        minind = 2
         activenotebook = self.parent.nb.GetSelection()
         page = self.parent.nb.GetPage(activenotebook)
         item=self.getColumnText(self.GetFirstSelected(), 0)
         corpus = page.corpus
-        win = message(self, -1, u"Concordancier", size=(600, 200),style = wx.DEFAULT_FRAME_STYLE)
-        avap=60
-        listmot = corpus.getlems()[item].formes       
-        uce_ok = corpus.getlemuces(item)
-        txt = '<h1>Concordancier</h1>'
-        res = corpus.getconcorde(uce_ok)
-        for uce in res :
-            ucetxt = ' '+uce[1]+' '
-            txt += ' '.join(corpus.ucis[corpus.getucefromid(uce[0]).uci].etoiles) + '<br>'
-            for forme in listmot :
-                forme = corpus.getforme(forme).forme
-                ucetxt = ucetxt.replace(' '+forme+' ', '<font color=red> ' + forme + ' </font>')
-            txt += ucetxt + '<br><br>'        
-        win.HtmlPage.SetPage(txt)
+        parametres = page.parametres
+        paneff = self.gparent.ListPanEff
+        panchi = self.gparent.ListPan
+        et = self.etoiles[ind]
+        uces = corpus.getucesfrometoile(et)
+        self.la = [panchi.dlist[i][0] for i in range(0, len(panchi.dlist)) if panchi.dlist[i][ind+1] >= minind ]
+        self.lchi = [panchi.dlist[i][ind+1] for i in range(0, len(panchi.dlist)) if panchi.dlist[i][ind+1] >= minind ]
+        if max(self.lchi) == float('inf') :
+            nchi = []
+            for val in self.lchi :
+                if val == float('inf') :
+                    nchi.append(0)
+                else :
+                    nchi.append(val)
+            nmax = max(nchi)
+            nchi = [val if val != float('inf') else nmax + 2 for val in self.lchi]
+            self.lchi = nchi
+        tab = corpus.make_pondtable_with_classe(uces, self.la)
+        tab.pop(0)
+        ntab = [round(sum([(self.lchi[i] * word) for i, word in enumerate(line) if word != 0]),2) for line in tab]
+        ntab2 = [[ntab[i], uces[i]] for i, val in enumerate(ntab) if ntab[i] != 0]
+        del ntab
+        ntab2.sort(reverse = True)
+        ntab2 = ntab2[:limite]
+        nuces = [val[1] for val in ntab2]
+        ucis_txt, ucestxt = doconcorde(corpus, nuces, self.la)
+        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))])
+        win = message(self, items, ' - '.join([_(u"Typical text segments").decode('utf8'), "%s" % self.first[ind]]), (900, 600))
+        win.Show(True)
+        
+    def OnPopupTwo(self, event):
+        if 'nb' in dir(self.parent) :
+            activenotebook = self.parent.nb.GetSelection()
+            page = self.parent.nb.GetPage(activenotebook)
+            corpus = page.corpus
+        else :
+            corpus = self.parent.parent.parent.corpus
+        ira = wx.GetApp().GetTopWindow()
+        item=self.getColumnText(self.GetFirstSelected(), 0)
+        if not self.tgen :
+            uce_ok = corpus.getlemuces(item)
+            wordlist = [item]
+        else :
+            uce_ok = corpus.gettgenst(self.tgens[item])
+            wordlist = [val for val in self.tgens[item] if val in corpus.lems]
+        ucis_txt, ucestxt = doconcorde(corpus, uce_ok, wordlist)
+        items = dict([[i, '<br><br>'.join([ucis_txt[i], ucestxt[i]])] for i in range(0,len(ucestxt))])
+        win = message(ira, items, ' - '.join([_(u"Concordance").decode('utf8'), "%s" % item]), (800, 500), uceids = uce_ok)
         win.Show(True)
 
+    def getinf(self, txt) :
+        if txt == float('Inf') :
+            return 'Inf'
+        elif txt == float('-Inf') :
+            return '-Inf'
+        else :
+            return `txt`
+
     def OnPopupThree(self, event) :
-        print self.GetFirstSelected()
         datas = [self.GetItemData(self.GetFirstSelected())]
-        print datas
         last = self.GetFirstSelected()
         while self.GetNextSelected(last) != -1:
             last = self.GetNextSelected(last)
             data = self.GetItemData(last)
             datas += [data]
-        colnames = self.first[1:]
-        table = [[str(val) for val in line[1:]] for line in datas]
+        colnames = self.first
+        table = [[self.getinf(val) for val in line[1:]] for line in datas]
         rownames = [val[0] for val in datas]
-        tmpgraph = tempfile.mktemp(dir=self.parent.TEMPDIR)
-
-        txt = barplot(table, rownames, colnames, self.parent.RscriptsPath['Rgraph'], tmpgraph)
-
-        tmpscript = tempfile.mktemp(dir=self.parent.TEMPDIR)
-        file = open(tmpscript,'w')
-        file.write(txt)
-        file.close()
-        exec_rcode(self.parent.RPath, tmpscript, wait = True)
-        win = MessageImage(self, -1, u"Graphique", size=(700, 500),style = wx.DEFAULT_FRAME_STYLE)
-        win.addsaveimage(tmpgraph)
-        txt = "<img src='%s'>" % tmpgraph
-        win.HtmlPage.SetPage(txt)
-        win.Show(True)
+        BarFrame(self.parent, table, colnames, rownames)
 
     def OnTgen_glob(self, evt) :
         activenotebook = self.parent.nb.GetSelection()
         page = self.parent.nb.GetPage(activenotebook)
         corpus = page.corpus
 
-        tmpgraph = tempfile.mktemp(dir=self.gparent.parent.TEMPDIR)
+        tmpgraph = tempfile.mktemp(dir=self.parent.TEMPDIR)
         intxt = """
         load("%s")
         """ % corpus.dictpathout['RData']
@@ -248,56 +341,63 @@ class ListForSpec(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.ColumnSor
         spec.Tgen.glob <- spec.Tgen.glob[[1]][((nrow(Tgen.table)-ncol(Tgen.table))+1):nrow(Tgen.table),]
         di <- spec.Tgen.glob
         """
-        txt = barplot('', '', '', self.gparent.parent.RscriptsPath['Rgraph'], tmpgraph, intxt = intxt) 
-        tmpscript = tempfile.mktemp(dir=self.gparent.parent.TEMPDIR)
+        txt = barplot('', '', '', self.parent.RscriptsPath['Rgraph'], tmpgraph, intxt = intxt) 
+        tmpscript = tempfile.mktemp(dir=self.parent.TEMPDIR)
         with open(tmpscript, 'w') as f :
             f.write(txt)
-        exec_rcode(self.gparent.parent.RPath, tmpscript, wait = True)
-        win = MessageImage(self, -1, u"Graphique", size=(700, 500),style = wx.DEFAULT_FRAME_STYLE)
+        exec_rcode(self.parent.RPath, tmpscript, wait = True)
+        win = MessageImage(self, -1, _(u"Graphic").decode('utf8'), size=(700, 500),style = wx.DEFAULT_FRAME_STYLE)
         win.addsaveimage(tmpgraph)
         txt = "<img src='%s'>" % tmpgraph
         win.HtmlPage.SetPage(txt)
         win.Show(True)
+    
+    def OnTgenDetails(self, evt):
+        if 'nb' in dir(self.parent) :
+            activenotebook = self.parent.nb.GetSelection()
+            page = self.parent.nb.GetPage(activenotebook)
+            corpus = page.corpus
+        else :
+            corpus = self.parent.parent.parent.corpus
+        ira = wx.GetApp().GetTopWindow()
+        item=self.getColumnText(self.GetFirstSelected(), 0)
+        wordlist = [val for val in self.tgens[item] if val in corpus.lems]
+        wordlist = dict(zip(wordlist,wordlist))
+        res = dict([[val, self.tgenlem[val]] for val in self.tgenlem if self.tgenlem[val][0] in wordlist])
+        win = ListLexFrame(self, ira, corpus, res, self.etoiles)
+        win.Show()
+        
+    
+    def OnMakeTgen(self, evt):
+        self.parent.tree.OnTgenEditor(self.getselectedwords())
 
-    def SortItems(self,sorter=cmp):
-        items = list(self.itemDataMap.keys())
-        items.sort(sorter)
-        self.itemIndexMap = items
-        # redraw the list
-        self.Refresh()
-
-class message(wx.Frame):
-    def __init__(self, *args, **kwds):
-        # begin wxGlade: MyFrame.__init__
-        kwds["style"] = wx.DEFAULT_FRAME_STYLE
-        wx.Frame.__init__(self, *args, **kwds)
-        #self.text_ctrl_1 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE)
-        self.HtmlPage=wx.html.HtmlWindow(self, -1)
-        if "gtk2" in wx.PlatformInfo:
-            self.HtmlPage.SetStandardFonts()
-        self.HtmlPage.SetFonts('Courier','Courier')
+class ListLexFrame ( wx.Frame ):
+    
+    def __init__( self, parent, ira, corpus, data, columns ):
+        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 )
         
+        self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
         
-        self.button_1 = wx.Button(self, -1, "Fermer")
-        self.Bind(wx.EVT_BUTTON, self.OnCloseMe, self.button_1)
-        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
-        self.__do_layout()
-        # end wxGlade
-
-    def __do_layout(self):
-        # begin wxGlade: MyFrame.__do_layout
-        sizer_1 = wx.BoxSizer(wx.VERTICAL)
-        sizer_2 = wx.BoxSizer(wx.VERTICAL)
-        sizer_2.Add(self.HtmlPage, 1, wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-        sizer_2.Add(self.button_1, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ADJUST_MINSIZE, 0)
-        sizer_1.Add(sizer_2, 1, wx.EXPAND, 0)
-        self.SetAutoLayout(True)
-        self.SetSizer(sizer_1)
+        bSizer1 = wx.BoxSizer( wx.VERTICAL )
+        
+        
+        self.listlex = ListForSpec(self, ira, data, columns)
+        bSizer1.Add( self.listlex, 5, wx.ALL|wx.EXPAND, 5 )
+        
+        m_sdbSizer1 = wx.StdDialogButtonSizer()
+        self.m_sdbSizer1OK = wx.Button( self, wx.ID_OK )
+        m_sdbSizer1.AddButton( self.m_sdbSizer1OK )
+        self.m_sdbSizer1Cancel = wx.Button( self, wx.ID_CANCEL )
+        m_sdbSizer1.AddButton( self.m_sdbSizer1Cancel )
+        m_sdbSizer1.Realize();
+        
+        bSizer1.Add( m_sdbSizer1, 0, wx.EXPAND, 5 )
+        
+        
+        self.SetSizer( bSizer1 )
         self.Layout()
-        # end wxGlade
         
-    def OnCloseMe(self, event):
-        self.Close(True)
-
-    def OnCloseWindow(self, event):
-        self.Destroy()
+        self.Centre( wx.BOTH )
+    
+    def __del__( self ):
+        pass