matrix
[iramuteq] / ProfList.py
1 # -*- coding: utf-8 -*-
2
3 #----------------------------------------------------------------------------
4 # Name:         ListCtrl.py
5 # Author:       Pierre Ratinaud
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 import os
17 import sys
18 import  wx
19 import  wx.lib.mixins.listctrl  as  listmix
20 #from tabsimi import DoSimi
21 from listlex import ListForSpec
22 from chemins import ConstructPathOut, ffr
23 from dialog import PrefExport, PrefUCECarac, SearchDial, message
24 from tableau import Tableau
25 from search_tools import SearchFrame
26 import webbrowser
27 #import cStringIO
28 import tempfile
29 import codecs
30 from functions import exec_rcode, MessageImage, progressbar, treat_var_mod, doconcorde
31 from PrintRScript import barplot
32 from textclassechd import ClasseCHD
33 from shutil import copyfile
34 from operator import itemgetter
35
36 #---------------------------------------------------------------------------
37 class ProfListctrlPanel(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.ColumnSorterMixin):
38     def __init__(self, parent, gparent, profclasse, Alceste=False, cl=0):
39         wx.ListCtrl.__init__( self, parent, -1, style=wx.LC_REPORT|wx.LC_VIRTUAL|wx.LC_HRULES|wx.LC_VRULES)
40
41         self.parent = parent
42         self.Alceste = Alceste
43         self.Source = gparent
44         self.cl = cl
45         self.var_mod = {}
46
47         line1 = profclasse.pop(0)
48         classen = [line for line in profclasse if line[0] != '*' and line[0] != '*****']
49         try :
50             self.lenact = profclasse.index([u'*****', u'*', u'*', u'*', u'*', u'*', '', ''])
51             profclasse.pop(self.lenact)
52         except ValueError:
53             try :
54                 self.lenact = profclasse.index([u'*', u'*', u'*', u'*', u'*', u'*', '', ''])
55                 profclasse.pop(self.lenact)
56             except ValueError:
57                 self.lenact = len(profclasse)
58         try :
59             self.lensup = profclasse.index([u'*', u'*', u'*', u'*', u'*', u'*', '', ''])
60             self.lensup = self.lensup - self.lenact
61             profclasse.pop(self.lensup)
62         except ValueError: 
63             self.lensup = len(profclasse) - self.lenact
64         self.lenet = len(profclasse) - (self.lenact + self.lensup)
65 #        print self.lenact, self.lensup, self.lenet
66         for i,  line in enumerate(classen) :
67             line[0] = i
68         dictdata = dict(zip([i for i in range(0,len(classen))], classen))
69
70         if self.lenact != 0 :
71             self.la = [dictdata[i][6] for i in range(0, self.lenact)]
72             self.lchi = [dictdata[i][4] for i in range(0, self.lenact)]
73             self.lfreq = [dictdata[i][1] for i in range(0, self.lenact)]
74         else :
75             self.la = []
76             self.lchi = []
77             self.lfreq = []
78         self.tmpchi = None
79             
80         #adding some art
81         self.il = wx.ImageList(16, 16)
82         a={"sm_up":"GO_UP","sm_dn":"GO_DOWN","w_idx":"WARNING","e_idx":"ERROR","i_idx":"QUESTION"}
83         for k,v in a.items():
84             s="self.%s= self.il.Add(wx.ArtProvider_GetBitmap(wx.ART_%s,wx.ART_TOOLBAR,(16,16)))" % (k,v)
85             exec(s)
86         self.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
87
88         #adding some attributes (colourful background for each item rows)
89         self.attr1 = wx.ListItemAttr()
90         self.attr1.SetBackgroundColour((220, 220, 220))
91         self.attrsg = wx.ListItemAttr()
92         self.attrsg.SetBackgroundColour((230, 230, 230))
93         self.attr2 = wx.ListItemAttr()
94         self.attr2.SetBackgroundColour((190, 249, 236))
95         self.attr2s = wx.ListItemAttr()
96         self.attr2s.SetBackgroundColour((211, 252, 244))        
97         self.attr3 = wx.ListItemAttr()
98         self.attr3.SetBackgroundColour((245, 180, 180))
99         self.attr3s = wx.ListItemAttr()
100         self.attr3s.SetBackgroundColour((245, 190, 190))
101
102
103         self.InsertColumn(0, "num", wx.LIST_FORMAT_RIGHT)
104         self.InsertColumn(1, "eff. s.t.", wx.LIST_FORMAT_RIGHT)
105         self.InsertColumn(2, "eff. total", wx.LIST_FORMAT_RIGHT)
106         self.InsertColumn(3, "pourcentage", wx.LIST_FORMAT_RIGHT)
107         self.InsertColumn(4, "chi2", wx.LIST_FORMAT_RIGHT)
108         self.InsertColumn(5, "Type", wx.LIST_FORMAT_RIGHT)
109         self.InsertColumn(6, "forme", wx.LIST_FORMAT_RIGHT)
110         self.InsertColumn(7, "p", wx.LIST_FORMAT_RIGHT)
111         
112
113         self.SetColumnWidth(0, 60)
114         self.SetColumnWidth(1, 70)
115         self.SetColumnWidth(2, 80)
116         self.SetColumnWidth(3, 100)
117         self.SetColumnWidth(4, 70)
118         self.SetColumnWidth(5, 60)
119         self.SetColumnWidth(6, 140)
120         self.SetColumnWidth(7, wx.LIST_AUTOSIZE)
121
122         #These two should probably be passed to init more cleanly
123         #setting the numbers of items = number of elements in the dictionary
124         self.itemDataMap = dictdata
125         self.itemIndexMap = dictdata.keys()
126         self.SetItemCount(len(dictdata))
127         
128         #mixins
129         listmix.ListCtrlAutoWidthMixin.__init__(self)
130         listmix.ColumnSorterMixin.__init__(self, len(classen[0]))
131
132         #sort by genre (column 2), A->Z ascending order (1)
133         self.SortListItems(0, 1)
134
135         #events
136         #self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
137         self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnPopupTwo, self)
138         #self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnItemDeselected)
139         self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick)
140
141         # for wxMSW
142         self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightClick)
143
144         # for wxGTK
145         self.Bind(wx.EVT_RIGHT_UP, self.OnRightClick)
146
147         #for searching
148         search_id = wx.NewId()
149         searchall_id = wx.NewId()
150         concord_id = wx.NewId()
151         self.parent.Bind(wx.EVT_MENU, self.onsearch, id = search_id)
152         self.parent.Bind(wx.EVT_MENU, self.onsearchall, id = searchall_id)
153         self.accel_tbl = wx.AcceleratorTable([(wx.ACCEL_CTRL, ord('F'), search_id),
154                                               (wx.ACCEL_CTRL|wx.ACCEL_SHIFT, ord('F'), searchall_id)])
155         self.SetAcceleratorTable(self.accel_tbl)
156
157
158
159     def OnColClick(self,event):
160         event.Skip()
161
162     def OnItemSelected(self, event):
163         self.currentItem = event.m_itemIndex
164
165     def OnItemActivated(self, event):
166         self.currentItem = event.m_itemIndex
167
168     def getColumnText(self, index, col):
169         item = self.GetItem(index, col)
170         return item.GetText()
171
172     def OnItemDeselected(self, evt):
173         pass
174     #---------------------------------------------------
175     # These methods are callbacks for implementing the
176     # "virtualness" of the list...
177
178     def OnGetItemText(self, item, col):
179         index=self.itemIndexMap[item]
180         s = self.itemDataMap[index][col]
181         return s
182
183     def OnGetItemImage(self, item):
184         index=self.itemIndexMap[item]
185         genre=self.itemDataMap[index][2]
186
187         if genre=="Rock":
188             return self.w_idx
189         elif genre=="Jazz":
190             return self.e_idx
191         elif genre=="New Age":
192             return self.i_idx
193         else:
194             return -1
195
196     def OnGetItemAttr(self, item):
197         index=self.itemIndexMap[item]
198         if index < self.lenact :
199             if item % 2 :
200                 return self.attr1
201             else :
202                 return self.attrsg
203         elif index >= self.lenact and index < (self.lenact + self.lensup) :
204             if item % 2 :
205                 return self.attr2
206             else :
207                 return self.attr2s
208         elif index >= (self.lenact + self.lensup) :
209             if item % 2 :
210                 return self.attr3
211             else :
212                 return self.attr3s
213         else :
214             return None
215
216     #---------------------------------------------------
217     # Matt C, 2006/02/22
218     # Here's a better SortItems() method --
219     # the ColumnSorterMixin.__ColumnSorter() method already handles the ascending/descending,
220     # and it knows to sort on another column if the chosen columns have the same value.
221
222     def SortItems(self,sorter=cmp):
223         items = list(self.itemDataMap.keys())
224         items.sort(sorter)
225         self.itemIndexMap = items
226         
227         # redraw the list
228         self.Refresh()
229
230     # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
231     def GetListCtrl(self):
232         return self
233
234     # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
235     def GetSortImages(self):
236         return (self.sm_dn, self.sm_up)
237
238     def onsearch(self, evt) :
239         self.dial = SearchDial(self, self, 6, True)
240         self.dial.CenterOnParent()
241         self.dial.Show()
242         #self.dial.Destroy()
243
244     def onsearchall(self, evt) :
245         if 'FrameSearch' not in dir(self.Source) :
246             self.Source.FrameSearch = SearchFrame(self.parent, -1, u"Rechercher...", self.Source.corpus)
247         self.dial = SearchDial(self, self.Source.FrameSearch.liste, 1, False)
248         self.dial.CenterOnParent()
249         self.dial.Show()
250         #self.dial.Destroy()
251
252     def OnRightClick(self, event):
253
254         # only do this part the first time so the events are only bound once
255         if self.Alceste:
256             if not hasattr(self, "popupID1"):
257                 self.popupID1 = wx.NewId()
258                 self.popupID2 = wx.NewId()
259                 self.popupID3 = wx.NewId()
260                 self.popupID4 = wx.NewId()
261                 self.popupID5 = wx.NewId()
262                 self.popupID6 = wx.NewId()
263                 self.popupID7 = wx.NewId()
264                 self.popupID8 = wx.NewId()
265                 self.popupID9 = wx.NewId()
266                 #self.popupID10 = wx.NewId()
267                 self.popupIDgraph = wx.NewId()
268                 self.idseg = wx.NewId()
269                 self.iducecarac = wx.NewId()
270                 self.idtablex = wx.NewId()
271                 self.idchimod = wx.NewId()
272                 self.idwordgraph = wx.NewId()
273                 self.popup_proxe = wx.NewId()
274                 self.idlexdendro = wx.NewId()
275                 self.idcloud = wx.NewId()
276                 self.idexport = wx.NewId()
277                 self.idexporttropes = wx.NewId()
278                 self.idexportowledge = wx.NewId()
279             #    self.export_classes = wx.NewId()
280    
281                 self.Bind(wx.EVT_MENU, self.OnPopupOne, id=self.popupID1)
282                 self.Bind(wx.EVT_MENU, self.OnPopupTwo, id=self.popupID2)
283                 self.Bind(wx.EVT_MENU, self.OnPopupThree, id=self.popupID3)
284                 self.Bind(wx.EVT_MENU, self.OnPopupFour, id=self.popupID4)
285                 self.Bind(wx.EVT_MENU, self.OnPopupFive, id=self.popupID5)
286                 self.Bind(wx.EVT_MENU, self.OnPopupSix, id=self.popupID6)
287                 self.Bind(wx.EVT_MENU, self.OnPopupSeven, id=self.popupID7)
288                 self.Bind(wx.EVT_MENU, self.OnPopupHeight, id=self.popupID8)
289                 self.Bind(wx.EVT_MENU, self.OnPopupNine, id=self.popupID9)
290                 #self.Bind(wx.EVT_MENU, self.OnPopupSpec, id=self.popupID10)
291                 self.Bind(wx.EVT_MENU, self.on_graph, id=self.popupIDgraph)
292                 self.Bind(wx.EVT_MENU, self.on_segments, id=self.idseg)
293                 self.Bind(wx.EVT_MENU, self.on_uce_carac, id = self.iducecarac)
294                 self.Bind(wx.EVT_MENU, self.on_tablex, id = self.idtablex)
295                 self.Bind(wx.EVT_MENU, self.quest_var_mod, id = self.idchimod)
296                 self.Bind(wx.EVT_MENU, self.onwordgraph, id = self.idwordgraph)
297                 self.Bind(wx.EVT_MENU, self.onproxe, id = self.popup_proxe)
298                 self.Bind(wx.EVT_MENU, self.onlexdendro, id = self.idlexdendro)
299                 self.Bind(wx.EVT_MENU, self.oncloud, id = self.idcloud)
300                 self.Bind(wx.EVT_MENU, self.onexport, id = self.idexport)
301                 self.Bind(wx.EVT_MENU, self.onexporttropes, id = self.idexporttropes)
302                 self.Bind(wx.EVT_MENU, self.onexportowledge, id = self.idexportowledge)
303              #  self.Bind(wx.EVT_MENU, self.on_export_classes, id = self.export_classes)
304    #            self.Bind(wx.EVT_MENU, self.OnPopupThree, id=self.popupID3)
305     
306             # make a menu
307             menu = wx.Menu()
308             menu.Append(self.popupID1, u"Formes associées")
309             menu.Append(self.idtablex, u"Chi2 par classe")
310             menu.Append(self.idlexdendro, u"Chi2 par classe + dendro")
311             menu.Append(self.idchimod, u"Chi2 modalités de la variable")
312             menu.Append(self.idwordgraph, u"Graphe du mot")
313             #menu.Append(self.export_classes, u"Exporter le corpus...") 
314             
315             #menu.Append(self.popupID10, u"Spécificités")
316
317             menu_conc = wx.Menu()
318             menu_conc.Append(self.popupID2, u"dans les segments de texte de la classe")
319             menu_conc.Append(self.popupID3, u"dans les segments de texte classés")
320             menu_conc.Append(self.popupID4, u"dans tous les segments de texte")
321             menu.AppendMenu(-1, u"Concordancier", menu_conc) 
322             menu_cnrtl = wx.Menu()      
323             menu_cnrtl.Append(self.popupID5, u"Définition")
324             menu_cnrtl.Append(self.popupID6, u"Etymologie")
325             menu_cnrtl.Append(self.popupID7, u"Synonymie")
326             menu_cnrtl.Append(self.popupID8, u"Antonymie")
327             menu_cnrtl.Append(self.popupID9, u"Morphologie")
328             menu_cnrtl.Append(self.popup_proxe, u"Proxémie")
329             menu.AppendMenu(-1, u"Outils du CNRTL", menu_cnrtl)
330             menu.AppendSeparator()
331             menu.Append(self.popupIDgraph, u"Graphe de la classe")
332             menu.Append(self.idseg, u"Segments répétés")
333             menu.Append(self.iducecarac, u"Segments de texte caractéristiques")
334             menu.Append(self.idcloud, u"Nuage de la classe")
335             menu.Append(self.idexport, u'Exporter...')
336             menu.Append(self.idexporttropes, 'Exporter pour Tropes')
337             menu.Append(self.idexportowledge, 'Exporter pour Owledge')
338             #menu.Append(self.popupID2, u"Concordancier")
339     #        menu.Append(self.popupID3, "recharger")
340     
341             self.PopupMenu(menu)
342             menu.Destroy()
343         elif 'tableau' in dir(self.Source) :
344             if not hasattr(self, "pop1"):
345                 self.pop1 = wx.NewId()
346                 self.pop2 = wx.NewId()
347                 self.pop3 = wx.NewId()
348                 self.Bind(wx.EVT_MENU, self.quest_simi, id=self.pop1)
349                 self.Bind(wx.EVT_MENU, self.on_tablex, id=self.pop2)
350                 self.Bind(wx.EVT_MENU, self.quest_var_mod, id=self.pop3)
351
352             menu = wx.Menu()
353             menu.Append(self.pop2, u"Chi2 par classe")
354             menu.Append(self.pop3, u"Chi2 modalités de la variable")
355             menu.AppendSeparator()
356             menu.Append(self.pop1, u"Graph de la classe")
357             self.PopupMenu(menu)
358             menu.Destroy()
359
360     def oncloud(self, evt) :
361         if 'corpus' in dir(self.Source):
362             corpus = self.Source.corpus
363         prof = [[self.la[i], self.lchi[i], self.lfreq[i]] for i, val in enumerate(self.la)]
364         parametres = self.Source.parametres
365         parametres['clusterprof'] = prof
366         parametres['type'] = 'clustercloud'
367         parametres['prof'] = self.Source.pathout['actprof_classe_%i.csv' % self.cl]
368         del  parametres['uuid']
369         #if not os.path.exists(self.Source.pathout['actprof_classe_%i.csv' % self.lc]) :
370         #    with open(self.Source.pathout['actprof_classe_%i.csv' % self.lc], 'w') as f :
371         #        f.write('\n'.join(prof).encode(self.parent.syscoding))
372         self.parent.OnClusterCloud(self.Source.corpus, parametres = parametres)
373
374     def onexport(self, evt) :
375         if 'corpus' in dir(self.Source):
376             corpus = self.Source.corpus
377         if self.Source.parametres['classif_mode'] != 2 :
378             uci = False
379         else :
380             uci = True
381         corpus.export_classe(self.Source.pathout['classe_%i_export.txt' % self.cl], self.cl, uci = uci)
382         dial = wx.MessageDialog(self, self.Source.pathout['classe_%i_export.txt' % self.cl], u"Export", wx.OK|wx.ICON_INFORMATION)
383         dial.ShowModal()
384         dial.Destroy()
385         #if 'corpus' in dir(self.Source):
386         #    corpus = self.Source.corpus
387         #ClasseCHD(self.parent, corpus, self.cl)
388     
389     def onexporttropes(self, evt) :
390         if 'corpus' in dir(self.Source):
391             corpus = self.Source.corpus
392         if self.Source.parametres['classif_mode'] != 2 :
393             uci = False
394         else :
395             uci = True
396         fileout = self.Source.pathout['export_tropes_classe_%i.txt' % self.cl]
397         corpus.export_tropes(fileout, self.cl, uci = uci)
398     
399     def onexportowledge(self, evt):
400         if 'corpus' in dir(self.Source):
401             corpus = self.Source.corpus
402         if self.Source.parametres['classif_mode'] != 2 :
403             uci = False
404         else :
405             uci = True
406         repout = self.Source.pathout['export_owledge_classe_%i' % self.cl]
407         if not os.path.exists(repout) :
408             os.mkdir(repout)
409         corpus.export_owledge(repout, self.cl, uci = uci)        
410
411     def getselectedwords(self) :
412         words = [self.getColumnText(self.GetFirstSelected(), 6)]
413         last = self.GetFirstSelected()
414         while self.GetNextSelected(last) != -1:
415             last = self.GetNextSelected(last)
416             words.append(self.getColumnText(last, 6))
417         return words
418
419     def quest_var_mod(self, evt) :
420         if 'corpus' in dir(self.Source):
421             corpus = self.Source.corpus
422             if self.var_mod == {} :
423                 self.var_mod = self.Source.corpus.make_etoiles_dict()
424         else :
425             corpus = self.Source.tableau
426             if self.var_mod == {} :
427                 self.var_mod = treat_var_mod([val for val in corpus.actives] + [val for val in corpus.sups])
428         with codecs.open(self.Source.pathout['chisqtable'], 'r', corpus.parametres['syscoding']) as f :
429             chistable = [line.replace('\n','').replace('\r','').replace('"','').replace(',','.').split(';') for line in f]
430         title = chistable[0]
431         title.pop(0)
432         chistable.pop(0)
433         vchistable = [line[1:] for line in chistable]
434         fchistable = [line[0] for line in chistable]
435         word = self.getselectedwords()[0]
436         if len(word.split('_')) > 1 :
437             var = word.split('_')
438             #words = ['_'.join([var[0],word]) for word in self.var_mod[var[0]]]
439             words = [word for word in self.var_mod[var[0]]]
440             words.sort()
441             tableout = []
442             kwords = []
443             for word in words :
444                 if word in fchistable :
445                     tableout.append(vchistable[fchistable.index(word)])
446                     kwords.append(word)
447             tmpgraph = tempfile.mktemp(dir=self.Source.parent.TEMPDIR)
448             txt = barplot(tableout, kwords, title, self.Source.parent.RscriptsPath['Rgraph'], tmpgraph)
449             tmpscript = tempfile.mktemp(dir=self.Source.parent.TEMPDIR)
450             file = open(tmpscript,'w')
451             file.write(txt)
452             file.close()
453             exec_rcode(self.Source.parent.RPath, tmpscript, wait = True)
454             win = MessageImage(self,u"Graphique", size=(700, 500))
455             win.addsaveimage(tmpgraph)
456             txt = "<img src='%s'>" % tmpgraph
457             win.HtmlPage.SetPage(txt)
458             win.Show(True)
459         else :
460             dial = wx.MessageDialog(self, u"Ce n'est pas une forme du type variable_modalité", u"Problème", wx.OK | wx.ICON_WARNING)
461             dial.CenterOnParent()
462             dial.ShowModal()
463             dial.Destroy()
464
465     def quest_simi(self, evt) :
466         tableau = self.Source.tableau
467         tab = tableau.make_table_from_classe(self.cl, self.la)
468         pathout = ConstructPathOut(self.Source.pathout.dirout, 'simi_classe_%i' %self.cl)
469         if self.tmpchi is None :
470             self.tmpchi = os.path.join(pathout,'chi.csv')
471             with open(self.tmpchi, 'w') as f:
472                 f.write('\n'.join([str(val) for val in self.lchi]))
473         self.filename = os.path.join(pathout,'mat01.csv')
474         tableau.printtable(self.filename, tab)
475         del tab
476         paramsimi = {'coeff' : 0,
477                           'layout' : 2,
478                           'type_graph' : 1,
479                           'arbremax' : 1,
480                           'coeff_tv' : 1,
481                           'coeff_tv_nb' : 0,
482                           'tvprop' : 0,
483                           'tvmin' : 5,
484                           'tvmax' : 30,
485                           'coeff_te' : 1,
486                           'coeff_temin' : 1,
487                           'coeff_temax' : 10,
488                           'label_v': 1,
489                           'label_e': 1,
490                           'vcex' : 0,
491                           'vcexmin' : 10,
492                           'vcexmax' : 25,
493                           'cex' : 10,
494                           'cexfromchi' : True,
495                           'sfromchi': False,
496                           'seuil_ok' : 0,
497                           'seuil' : 1,
498                           'cols' : (255,0,0),
499                           'cola' : (200,200,200),
500                           'width' : 1000,
501                           'height' : 1000,
502                           'first' : True,
503                           'keep_coord' : True,
504                           'alpha' : 20,
505                           'film': False,
506                           'com' : 0,
507                           'communities' : 0,
508                           'halo' : 0,
509                           'tmpchi': self.tmpchi
510                           }
511         act = {}
512         tableau.chi = {}
513         tableau.lchi = self.lchi
514         tableau.parametres['fromprof'] = True
515         for i, val in enumerate(self.la) :
516             act[val] = [self.lfreq[i]]
517             tableau.chi[val] = [self.lchi[i]]
518         self.parent.SimiCluster(parametres = paramsimi, fromprof = ffr(self.filename), pathout = pathout, listactives = self.la, actives = act, tableau = tableau)
519
520     def onwordgraph(self, evt):
521         word = self.getColumnText(self.GetFirstSelected(), 6)
522         if self.tmpchi is None :
523             self.tmpchi = os.path.join(self.Source.parametres['pathout'],'chi_%i.csv' % self.cl)
524             with open(self.tmpchi, 'w') as f:
525                 f.write('\n'.join([str(val) for val in self.lchi]))
526         index = self.la.index(word)
527         parametres = {'type' : 'clustersimitxt', 
528                         'pathout' : self.Source.parametres['pathout'],
529                         'word' : index ,
530                         'lem' : self.Source.parametres['lem'],
531                         'tmpchi' : self.tmpchi}
532         #try :
533         self.parent.SimiFromCluster(self.parent, self.Source.corpus, self.la, self.lfreq, self.lchi, self.cl - 1, parametres = parametres, dlg = progressbar(self, 4))
534         #except :
535         #    print 'not acitve'
536
537     def on_graph(self, evt):
538         if self.tmpchi is None :
539             self.tmpchi = os.path.join(self.Source.parametres['pathout'],'chi_%i.csv' % self.cl)
540             with open(self.tmpchi, 'w') as f:
541                 f.write('\n'.join([str(val) for val in self.lchi]))
542         parametres = {'type' : 'clustersimitxt', 
543                         'pathout' : self.Source.parametres['pathout'],
544                         'lem' : self.Source.parametres['lem'],
545                         'tmpchi' : self.tmpchi}
546
547         self.parent.SimiFromCluster(self.parent, self.Source.corpus, self.la, self.lfreq, self.lchi, self.cl - 1, parametres = parametres, dlg = progressbar(self, 4))
548
549     def on_segments(self,evt) :
550         dlg = progressbar(self, 2)
551         corpus = self.Source.corpus
552         uces = corpus.lc[self.cl-1]
553         if self.Source.parametres['classif_mode'] != 2 :
554             uci = False
555         else :
556             uci = True
557         l = []
558         dlg.Update(1, u'Segments...')
559         for i in range(2,10) :
560             li = corpus.find_segments_in_classe(uces, i, 1000, uci = uci)
561             if li == [] :
562                 break
563             else :
564                 l += li
565         l.sort(reverse = True)
566         d = {}
567         dlg.Update(2, 'Tri...')
568         for i, line in enumerate(l) :
569             d[i] = [line[1],line[0], line[2]]
570         first = ['','','']
571         para={'dico': d,'fline':first}
572         dlg.Destroy()
573         win = wliste(self, -1, u"Segments répétés - Classe %i" % self.cl, d, first, size=(600, 500))
574         win.Show(True)
575
576     def on_uce_carac(self,evt) :
577         dial = PrefUCECarac(self, self.parent)
578         dial.CenterOnParent()
579         if dial.ShowModal() == wx.ID_OK :
580             limite = dial.spin_eff.GetValue()
581             atype = dial.radio_type.GetSelection()
582             dlg = progressbar(self,maxi = 4)
583             corpus = self.Source.corpus
584             uces = corpus.lc[self.cl-1]
585             if self.Source.parametres['classif_mode'] != 2 :
586                 uci = False
587             else :
588                 uci = True
589             tab = corpus.make_table_with_classe(uces, self.la, uci = uci)
590             tab.pop(0)
591             dlg.Update(2, u'score...')
592             if atype == 0 :
593                 ntab = [round(sum([self.lchi[i] for i, word in enumerate(line) if word == 1]),2) for line in tab]
594             else :
595                 ntab = [round(sum([self.lchi[i] for i, word in enumerate(line) if word == 1])/float(sum(line)),2) if sum(line)!=0 else 0 for line in tab]
596             ntab2 = [[ntab[i], uces[i]] for i, val in enumerate(ntab)]
597             del ntab
598             ntab2.sort(reverse = True)
599             ntab2 = ntab2[:limite]
600             nuces = [val[1] for val in ntab2]
601             dlg.Update(3, u'concordancier...')
602             ucis_txt, ucestxt = doconcorde(corpus, nuces, self.la, uci = uci)
603             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))])
604             dlg.Update(4, u'texte...')
605             win = message(self, items, u"Segments de texte caractéristiques - Classe %i" % self.cl, (750, 600))
606             #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>'
607             #win.HtmlPage.SetPage(win.html)
608             dlg.Destroy()
609             win.Show(True)
610     
611     def on_tablex(self, evt):
612         if 'corpus' in dir(self.Source):
613             corpus = self.Source.corpus
614         else :
615             corpus = self.Source.tableau
616         with codecs.open(self.Source.pathout['chisqtable'], 'r', corpus.parametres['syscoding']) as f :
617             chistable = [line.replace('\n','').replace('\r','').replace('"','').replace(',','.').split(';') for line in f]
618         title = chistable[0]
619         title.pop(0)
620         chistable.pop(0)
621         vchistable = [line[1:] for line in chistable]
622         fchistable = [line[0] for line in chistable]
623         words = self.getselectedwords()
624         tableout = [vchistable[fchistable.index(word)] for word in words]
625         tmpgraph = tempfile.mktemp(dir=self.Source.parent.TEMPDIR)
626         nbcl = len(title)
627         nbwords = len(words)
628         txt = barplot(tableout, words, title, self.Source.parent.RscriptsPath['Rgraph'], tmpgraph)
629         #print 'ATTENTION TEST R'
630         #txt = """
631         #sink('/Users/pierre/Desktop/qdfqsdfqsdfqsdf.txt')
632         #Sys.getlocale()
633         #sink()
634         #"""
635         tmpscript = tempfile.mktemp(dir=self.Source.parent.TEMPDIR)
636         file = open(tmpscript,'w')
637         file.write(txt)
638         file.close()
639         exec_rcode(self.Source.parent.RPath, tmpscript, wait = True)
640         w = 100 + (20 * nbwords) + (100 * nbcl)
641         h = 100 + (nbwords * 15)
642         if w > 1100 : w = 1100
643         if h > 800 : h = 800
644         if h < 450 : h = 450
645         win = MessageImage(self, u"Graphique", size=(w, h))
646         win.addsaveimage(tmpgraph)
647         txt = "<img src='%s'>" % tmpgraph
648         win.HtmlPage.SetPage(txt)
649         win.Show(True)
650
651     def onlexdendro(self, evt):
652         if 'corpus' in dir(self.Source):
653             corpus = self.Source.corpus
654         else :
655             corpus = self.Source.tableau
656         with codecs.open(self.Source.pathout['chisqtable'], 'r', corpus.parametres['syscoding']) as f :
657             chistable = [line.replace('\n','').replace('\r','').replace('"','').replace(',','.').split(';') for line in f]
658         title = chistable[0]
659         title.pop(0)
660         chistable.pop(0)
661         vchistable = [line[1:] for line in chistable]
662         fchistable = [line[0] for line in chistable]
663         words = self.getselectedwords()
664         tableout = [vchistable[fchistable.index(word)] for word in words]
665         tmpgraph = tempfile.mktemp(dir=self.Source.parent.TEMPDIR)
666         txttable = 'c(' + ','.join([','.join(line) for line in tableout]) + ')'
667         rownames = 'c("' + '","'.join(words) + '")'
668         colnames = 'c("' + '","'.join(title) + '")'
669         nbcl = len(title)
670         rownb = len(words)
671         txt = """
672         load("%s")
673         di <- matrix(data=%s, nrow=%i, byrow = TRUE)
674         rownames(di)<- %s
675         colnames(di) <- %s
676         library(ape)
677         source("%s")
678         height <- (30*ncol(di)) + (15*nrow(di))
679         height <- ifelse(height <= 400, 400, height)
680         width <- 500
681         open_file_graph("%s", width=width, height=height)
682         plot.dendro.lex(tree.cut1$tree.cl, di)
683         """ % (self.Source.pathout['Rdendro'], txttable, rownb, rownames, colnames, self.Source.parent.RscriptsPath['Rgraph'], ffr(tmpgraph))
684         tmpscript = tempfile.mktemp(dir=self.Source.parent.TEMPDIR)
685         file = open(tmpscript,'w')
686         file.write(txt)
687         file.close()
688         exec_rcode(self.Source.parent.RPath, tmpscript, wait = True)
689         win = MessageImage(self, u"Graphique", size=(700, 500))
690         win.addsaveimage(tmpgraph)
691         txt = "<img src='%s'>" % tmpgraph
692         win.HtmlPage.SetPage(txt)
693         win.Show(True)
694
695     def make_concord(self, uces, title, color = 'red') :
696         corpus = self.Source.corpus
697         ListWord = [self.getColumnText(self.GetFirstSelected(), 6)]
698         last = self.GetFirstSelected()
699         while self.GetNextSelected(last) != -1:
700             last = self.GetNextSelected(last)
701             ListWord.append(self.getColumnText(last, 6))
702         ucef = []
703         if self.Source.parametres['classif_mode'] != 2 :
704             for word in ListWord : 
705                 uci = False
706                 ucef += list(set(corpus.getlemuces(word)).intersection(uces))
707         else :
708             for word in ListWord : 
709                 ucef += list(set(corpus.getlemucis(word)).intersection(uces))            
710                 uci = True
711         ucis_txt, ucestxt = doconcorde(corpus, ucef, ListWord, uci = uci)
712         items = dict([[i, '<br><br>'.join([ucis_txt[i], ucestxt[i]])] for i in range(0,len(ucestxt))])
713         win = message(self, items, title, (800, 500))
714         #win = message(self, title, size=(750, 600))
715         #win.html = ('<html>\n<h1>%s</h1>' % ' '.join(ListWord)) + '<br>'.join(['<br>'.join([ucis_txt[i], ucestxt[i]]) for i in range(0,len(ucestxt))]) + '\n</html>'
716         #win.HtmlPage.SetPage(win.html)
717         return win
718
719     def OnPopupTwo(self, event):
720         if 'corpus' in dir(self.Source) :
721             corpus = self.Source.corpus
722             uces = corpus.lc[self.cl-1]
723             win = self.make_concord(uces, "Concordancier - Classe %i" % self.cl)
724             win.Show(True)
725     
726     def OnPopupThree(self, event):
727         corpus = self.Source.corpus
728         uces = [classe[i] for classe in corpus.lc for i in range(0,len(classe))]
729         win = self.make_concord(uces, "Concordancier - UCE classées")
730         win.Show(True)
731         
732     def OnPopupFour(self, event):
733         corpus = self.Source.corpus
734         uces = [classe[i] for classe in corpus.lc for i in range(0,len(classe))] + corpus.lc0
735         win = self.make_concord(uces, "Concordancier - Toutes les UCE")
736         win.Show(True)
737
738     def OnPopupFive(self, event):
739         word = self.getColumnText(self.GetFirstSelected(), 6)
740         lk = "http://www.cnrtl.fr/definition/" + word
741         webbrowser.open(lk)
742
743     def OnPopupSix(self, event):  
744         word = self.getColumnText(self.GetFirstSelected(), 6)
745         lk = "http://www.cnrtl.fr/etymologie/" + word
746         webbrowser.open(lk)
747         
748     def OnPopupSeven(self, event):        
749         word = self.getColumnText(self.GetFirstSelected(), 6)
750         lk = "http://www.cnrtl.fr/synonymie/" + word
751         webbrowser.open(lk)
752         
753     def OnPopupHeight(self, event):  
754         word = self.getColumnText(self.GetFirstSelected(), 6)
755         lk = "http://www.cnrtl.fr/antonymie/" + word
756         webbrowser.open(lk)
757         
758     def OnPopupNine(self, event):            
759         word = self.getColumnText(self.GetFirstSelected(), 6)
760         lk = "http://www.cnrtl.fr/morphologie/" + word
761         webbrowser.open(lk)
762
763     def onproxe(self, evt) :
764         word = self.getColumnText(self.GetFirstSelected(), 6)
765         lk = "http://www.cnrtl.fr/proxemie/" + word
766         webbrowser.open(lk)
767
768     def OnPopupOne(self, event):
769         corpus = self.Source.corpus
770         #print 'ATTENTION PRINT ET TABLE'
771         #corpus.make_et_table()
772         word = self.getColumnText(self.GetFirstSelected(), 6)
773         lems = corpus.getlems()
774         uces = corpus.lc[self.cl-1]
775         rep = []
776         #FIXME : donner aussi eff reel a la place de nb uce
777         for forme in lems[word].formes :
778             if self.Source.parametres['classif_mode'] != 2 :
779                 ucef = list(set(corpus.getworduces(forme)).intersection(uces))
780             else :
781                 ucef = list(set(corpus.getworducis(forme)).intersection(uces))
782             #ucef = [uce for uce in corpus.formes[forme][1] if uce in uces]
783             if ucef != [] :
784                 nb = len(ucef)
785                 rep.append([corpus.getforme(forme).forme, nb])
786         rep.sort(key = itemgetter(1), reverse = True)
787         #win = message(self, u"Formes associées", wx.Size(300, 200))
788         items = dict([[i, '\t:\t'.join([str(val) for val in forme])] for i, forme in enumerate(rep)])
789         win = message(self, items, u"Formes associées", (300, 200))
790         #win.html = '<html>\n' + '<br>'.join([' : '.join([str(val) for val in forme]) for forme in rep]) + '\n</html>'
791         #win.HtmlPage.SetPage(win.html)
792         win.Show(True)
793
794
795 class wliste(wx.Frame):
796     def __init__(self, parent, id, title, d, fline, size=(600, 500)):
797         wx.Frame.__init__(self, parent, id)
798         self.liste = ListForSpec(self, parent, d, fline, menu = False)
799         self.button_1 = wx.Button(self, -1, "Fermer")
800         self.Bind(wx.EVT_BUTTON, self.OnCloseMe, self.button_1)
801         self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
802         self.__do_layout()
803
804     def __do_layout(self):
805         sizer_1 = wx.BoxSizer(wx.VERTICAL)
806         sizer_2 = wx.BoxSizer(wx.VERTICAL)
807         sizer_2.Add(self.liste, 1, wx.EXPAND | wx.ADJUST_MINSIZE, 0)
808         sizer_2.Add(self.button_1, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ADJUST_MINSIZE, 0)
809         sizer_1.Add(sizer_2, 1, wx.EXPAND, 0)
810         self.SetAutoLayout(True)
811         self.SetSizer(sizer_1)
812         self.Layout()
813         
814     def OnCloseMe(self, event):
815         self.Close(True)
816
817     def OnCloseWindow(self, event):
818         self.Destroy()