...
[iramuteq] / textaslexico.py
1 # -*- coding: utf-8 -*-
2 #Author: Pierre Ratinaud
3 #Copyright (c) 2008-2011 Pierre Ratinaud
4 #Lisense: GNU/GPL
5
6 from chemins import ConstructPathOut, StatTxtPathOut
7 #from corpus import Corpus
8 from analysetxt import AnalyseText
9 import wx
10 import os
11 import sys
12 from listlex import *
13 from functions import exec_rcode, progressbar, check_Rresult, CreateIraFile, print_liste, treat_var_mod, write_tab, DoConf
14 from dialog import OptLexi, StatDialog #LexDialog
15 from openanalyse import OpenAnalyse
16 import tempfile
17 from ConfigParser import RawConfigParser
18 from guifunct import getPage, getCorpus
19 from time import sleep
20 import logging
21
22 log = logging.getLogger('iramuteq.spec')
23
24 class Lexico(AnalyseText) :
25     def doanalyse(self) :
26         pathout = self.pathout.dirout
27         self.dictpathout = StatTxtPathOut(pathout)
28         self.parametres['ira'] = self.dictpathout['ira']
29         self.make_lexico()
30         if self.dlg :
31             try :
32                 self.dlg.Destroy()
33             except :
34                 pass
35 #    def __init__(self, parent, cmd = False):
36 #        self.parent = parent
37 #        self.cmd = False
38 #        self.ConfigPath = parent.ConfigPath
39 #        self.DictPath = parent.DictPath
40 #        self.KeyConf = RawConfigParser()
41 #        self.KeyConf.read(self.ConfigPath['key'])
42 #
43 #        page = getPage(self.parent)
44 #        if page is not None :
45 #            self.corpus = getCorpus(page)
46 #            if self.corpus is not None :
47 #                pathout = ConstructPathOut(self.corpus.parametre['openpath'], 'lexico')
48 #                self.dictpathout = StatTxtPathOut(pathout)
49 #                self.val = wx.ID_OK
50 #                #print self.corpus.lems
51 #                self.make_lexico()
52 #
53 #        else :
54 #            self.corpus = Corpus(parent)
55 #            self.corpus.content = self.parent.content
56 #            self.corpus.parametre['encodage'] = parent.corpus_encodage
57 #            self.corpus.parametre['lang'] = parent.corpus_lang
58 #            self.corpus.parametre['filename'] = parent.filename
59 #            dial = StatDialog(self, self.parent)
60 #            dial.check_uce.SetValue(True)
61 #            dial.check_uce.Enable(False)
62 #            dial.OnCheckUce(wx.EVT_MENU)
63 #            self.val = dial.ShowModal()           
64 ##            dial = LexDialog(self.parent)
65 ##            dial.CenterOnParent()
66 ##            res = dial.ShowModal()
67 #            if self.val == wx.ID_OK : 
68 #                #if dial.m_radioBox2.GetSelection() == 0 : self.corpus.parametre['lem'] = True
69 #                if dial.radio_lem.GetSelection() == 0 : self.corpus.parametre['lem'] = True
70 #                else : self.corpus.parametre['lem'] = False
71 #                #if dial.m_radioBox21.GetSelection() == 0 : self.corpus.parametre['expressions'] = True
72 #                if dial.exp.GetSelection() == 0 : self.corpus.parametre['expressions'] = True
73 #                else : self.corpus.parametre['expressions'] = False
74 #                self.make_uce = dial.check_uce.GetValue()
75 #                self.corpus.parametre['nbforme_uce'] = dial.spin_ctrl_4.GetValue()
76 #                self.corpus.parametre['max_actives'] = dial.spin_max_actives.GetValue()
77 #                self.corpus.parametre['eff_min_uce'] = self.corpus.parametre['nbforme_uce']
78 #                dial.Destroy()
79 #                pathout = ConstructPathOut(self.corpus.parametre['filename'], 'lexico')
80 #                self.dictpathout = StatTxtPathOut(pathout)
81 #                self.make_corpus()
82 #                #print self.corpus.ucis
83 #                self.make_lexico()
84 #
85 #    def make_corpus(self) :
86 #        print 'make corpus'
87 #        if not self.cmd :
88 #            dlg = progressbar(self, maxi = 6)
89 #        self.corpus.supplementaires = [option for option in self.KeyConf.options('KEYS') if self.KeyConf.get('KEYS', option) == "2"]
90 #        self.corpus.typeactive = [option for option in self.KeyConf.options('KEYS') if self.KeyConf.get('KEYS', option) == "1"]
91 #        ucis_txt, ucis_paras_txt = self.corpus.start_analyse(self.parent, dlg = dlg, cmd = self.cmd)
92 #        del ucis_txt
93 #    
94 #        if not self.cmd :
95 #            dlg.Update(5, '%i ucis - Construction des uces' % len(ucis_paras_txt))
96 #        self.corpus.make_ucis_paras_uces(ucis_paras_txt, make_uce = self.make_uce)
97 #        del ucis_paras_txt
98 #
99 #        if self.corpus.para_coords != [[] for val in self.corpus.para_coords] :
100 #            self.corpus.parametre['para'] = True
101 #        else :
102 #            self.corpus.parametre['para'] = False
103 #        self.corpus.make_etoiles(self.corpus.para_coords)
104 #
105 #        print 'len(ucis_paras_uces)', len(self.corpus.ucis_paras_uces)
106 #    
107 #        if not self.cmd :
108 #            dlg.Update(6, u'Dictionnaires')
109 #        uces, orderuces = self.corpus.make_forms_and_uces()
110 #        self.corpus.make_lems(self.parent.lexique)
111 ##        if not self.corpus.parametre['lem'] :
112 ##            formes = self.corpus.formes
113 ##        else :
114 ##            formes = self.corpus.make_lem_eff()
115 #        if not self.cmd :
116 #            dlg.Destroy()
117    
118     def DoR(self):
119         nbligne = 5
120         colonne = 1
121         txt = """
122         source("%s")
123         source("%s")
124         """ % (self.parent.RscriptsPath['chdfunct'], self.parent.RscriptsPath['Rgraph'])
125         txt += """
126         dmf<-read.csv2("%s",row.names=1)
127         """ % self.dictpathout['tableafcm']
128         txt += """
129         dmt<-read.csv2("%s",row.names=1)
130         """ % self.dictpathout['tabletypem']
131         if self.parametres['indice'] == 'hypergeo' :
132             txt += """
133             outf <- make.spec.hypergeo(dmf)
134             outt <- make.spec.hypergeo(dmt)
135             """
136         elif self.parametres['indice'] == 'chi2' :
137             txt += """
138             outf<-AsLexico2(dmf)
139             outt<-AsLexico2(dmt)
140             """
141
142         txt += """
143         specf<-outf[[1]]
144         spect<-outt[[1]]
145         write.csv2(specf,file="%s")
146         """ % self.dictpathout['tablespecf']
147         txt += """
148         write.csv2(spect,file="%s")
149         """ % self.dictpathout['tablespect']
150         txt += """
151         write.csv2(outf[[3]],file="%s")
152         """ % self.dictpathout['eff_relatif_forme']
153         txt += """
154         write.csv2(outt[[3]],file="%s")
155         """ % self.dictpathout['eff_relatif_type']
156         if self.parametres['clnb'] > 2 :
157             txt += """
158             library(ca)
159             nd <- ncol(specf) - 1
160             if (nd > 6) nd <- 6
161             slf <- rowSums(dmf)
162             if (min(slf) == 0) {
163                 dmfp<-dmf[-which(slf==0),]
164                 specfp <- specf[-which(slf==0),]
165             } else { 
166                 dmfp <- dmf
167                 specfp <- specf
168                 }
169             afcf <- ca(dmfp, nd = nd)
170             slt <- rowSums(dmt)
171             if (min(slt) == 0) {
172                 dmtp<-dmt[-which(slt==0),]
173                 spectp <- spect[-which(slt==0),]
174             } else { 
175                 dmtp <- dmt
176                 spectp <- spect
177                 }
178             afct <- ca(dmtp, nd = nd)
179             open_file_graph("%s", widt = 1000, height=1000)
180             plot(afcf, what=c('all','none'), labels=c(1,1))
181             open_file_graph("%s", widt = 1000, height=1000)
182             plot(afcf, what=c('none','all'), labels=c(1,1))
183             open_file_graph("%s", widt = 1000, height=1000)
184             plot(afct, what=c('all','none'), labels=c(1,1))
185             open_file_graph("%s", widt = 1000, height=1000)
186             plot(afct, what=c('none','all'), labels=c(1,1))
187             afcf <- AddCorrelationOk(afcf)
188             afct <- AddCorrelationOk(afct)
189             afcf <- summary.ca.dm(afcf)
190             afct <- summary.ca.dm(afct)
191             afcf_table <- create_afc_table(afcf)
192             afct_table <- create_afc_table(afct)
193             write.csv2(afcf_table$facteur, file = "%s")
194             write.csv2(afcf_table$colonne, file = "%s")
195             write.csv2(afcf_table$ligne, file = "%s")
196             write.csv2(afct_table$facteur, file = "%s")
197             write.csv2(afct_table$colonne, file = "%s")
198             write.csv2(afct_table$ligne, file = "%s")
199             debsup <- NULL
200             debet <- NULL
201             clnb <-  ncol(specf)
202             """ % (self.dictpathout['afcf_row'], self.dictpathout['afcf_col'], self.dictpathout['afct_row'], self.dictpathout['afct_col'], self.dictpathout['afcf_facteur_csv'], self.dictpathout['afcf_col_csv'], self.dictpathout['afcf_row_csv'], self.dictpathout['afct_facteur_csv'], self.dictpathout['afct_col_csv'], self.dictpathout['afct_row_csv'])
203
204         txt += """
205         save.image("%s")
206         """ % self.dictpathout['RData']
207         tmpfile = tempfile.mktemp(dir=self.parent.TEMPDIR)
208         tmpscript = open(tmpfile, 'w')
209         tmpscript.write(txt)
210         tmpscript.close()
211         pid = exec_rcode(self.parent.RPath, tmpfile, wait = False)
212         while pid.poll() == None :
213             sleep(0.2)
214         check_Rresult(self.parent, pid)
215
216     def preferences(self) :
217         listet = self.corpus.make_etoiles()
218         listet.sort()
219         variables = treat_var_mod(listet)
220         var = [v for v in variables]
221         dial = OptLexi(self.parent)
222         dial.listet = listet
223         dial.variables = var
224         for et in var :
225             dial.list_box_1.Append(et)
226         dial.CenterOnParent()
227         self.dialok = dial.ShowModal()
228         if self.dialok == wx.ID_OK :
229             if dial.choice.GetSelection() == 1 :
230                 ListEt = [listet[i] for i in dial.list_box_1.GetSelections()]
231             else :
232                 ListEt = variables[var[dial.list_box_1.GetSelections()[0]]]
233             self.listet = ListEt
234             self.parametres['mineff'] = dial.spin.GetValue()
235             if dial.choice_indice.GetSelection() == 0 :
236                 self.parametres['indice'] = 'hypergeo'
237             else :
238                 self.parametres['indice'] = 'chi2'
239             self.parametres['clnb'] = len(ListEt)
240             if dial.checklem.GetValue() :
241                 self.parametres['lem'] = 1 
242             else :
243                 self.parametres['lem'] = 0
244             dial.Destroy()
245             return self.parametres
246         else :
247             dial.Destroy()
248             return None
249
250     def make_lexico(self) :
251 #        listet = self.corpus.make_etoiles()
252 #        listet.sort()
253 #        variables = treat_var_mod(listet)
254 #        var = [v for v in variables]
255 #        if self.dlg :
256 #            dial = OptLexi(self.parent)
257 #            dial.listet = listet
258 #            dial.variables = var
259 #            for et in var :
260 #                dial.list_box_1.Append(et)
261 #            dial.CenterOnParent()
262 #            val = dial.ShowModal()
263 #            if val == wx.ID_OK :
264 #                if dial.choice.GetSelection() == 1 :
265 #                    ListEt = [listet[i] for i in dial.list_box_1.GetSelections()]
266 #                else :
267 #                    ListEt = variables[var[dial.list_box_1.GetSelections()[0]]]
268 #                mineff = dial.spin.GetValue()
269 #                if dial.choice_indice.GetSelection() == 0 :
270 #                    indice = 'hypergeo'
271 #                else :
272 #                    indice = 'chi2'
273 #                self.parametres = {'indice' : indice}
274 #                dial.Destroy()
275 #            else :
276 #                dial.Destroy()
277 #        else :
278         mineff = self.parametres['mineff']
279         #dlg = progressbar(self, maxi = 3)
280         tabout = self.corpus.make_lexitable(mineff, self.listet)
281         log.warning('Fmax a 200')
282         Fmax = [line for line in tabout[1:] if sum(line[1:]) > 199]
283         formesmax = [line[0] for line in Fmax]
284         Fmax = [line[1:] for line in Fmax]
285         summax = [sum(col) for col in zip(*Fmax)]
286         tabout.append(['Fmax'] + summax)
287         tabout = [line for line in tabout if line[0] not in formesmax]
288         log.warning('ATTENTION : hapax par etoile')
289         tabout.append(['hapax'] + self.corpus.gethapaxbyet(self.listet))
290         write_tab(tabout, self.dictpathout['tableafcm'])
291         
292         #log.warning('ATTENTION : gethapaxuces')
293         #self.corpus.gethapaxuces()
294
295         tabout = self.corpus.make_efftype_from_etoiles(self.listet)
296         write_tab(tabout, self.dictpathout['tabletypem'])
297         #dlg.Update(2, u'R...')
298         self.DoR()
299         #dlg.Update(3, u'Chargement...')
300         afcf_graph_list = [[os.path.basename(self.dictpathout['afcf_row']), u'lignes'],\
301                             [os.path.basename(self.dictpathout['afcf_col']), u'colonnes']]
302         afct_graph_list = [[os.path.basename(self.dictpathout['afct_row']), u'lignes'],\
303                             [os.path.basename(self.dictpathout['afct_col']), u'colonnes']]
304         print_liste(self.dictpathout['liste_graph_afcf'],afcf_graph_list)
305         print_liste(self.dictpathout['liste_graph_afct'],afct_graph_list)
306         #CreateIraFile(self.dictpathout, 0, corpname = os.path.basename(self.corpus.parametre['filename']), section = 'lexico')
307         DoConf().makeoptions(['spec'],[self.parametres], self.dictpathout['ira'])
308             #OpenAnalyse(self.parent, self.dictpathout['ira']) 
309             #dolayout(self)
310             #dlg.Destroy()