first import
[iramuteq] / textstat.py
1 #!/bin/env python
2 # -*- coding: utf-8 -*-
3 #Author: Pierre Ratinaud
4 #Copyright (c) 2008-2009 Pierre Ratinaud
5 #Lisense: GNU/GPL
6
7 #from chemins import ConstructPathOut, StatTxtPathOut, ffr
8 from chemins import PathOut
9 from analysetxt import AnalyseText
10 #from corpus import Corpus
11 from guifunct import getPage, getCorpus
12 from ConfigParser import RawConfigParser
13 from functions import sortedby, progressbar, CreateIraFile, exec_rcode, check_Rresult, DoConf
14 from dialog import StatDialog
15 from openanalyse import OpenAnalyse
16 #from ttparser import * 
17 import tempfile
18 from time import sleep
19 import wx
20 import os
21
22 print 'TEST LOGGING'
23 import logging
24
25 logger = logging.getLogger('iramuteq.textstat')
26
27
28
29 class Stat(AnalyseText) :
30     def doanalyse(self) :
31         self.make_stats()
32
33     def preferences(self) :
34         dial = StatDialog(self, self.parent)
35         dial.CenterOnParent()
36         val = dial.ShowModal()
37         if val == 5100 :
38             if dial.radio_lem.GetSelection() == 0 :
39                 lem = 1
40             else :
41                 lem = 0            
42             self.parametres['lem'] = lem
43             dial.Destroy()
44             return self.parametres
45         else :
46             dial.Destroy()
47             return None
48
49     def make_stats(self):
50         if self.dlg :
51             if not 'dlg' in dir(self) :
52                 self.dlg = progressbar(self, 7)
53         #if not self.lem :
54         #    formes = self.corpus.formes
55         #else :
56         #    self.corpus.make_lems()
57         formes = self.corpus.lems
58         tot = [[forme, formes[forme].freq, formes[forme].gram] for forme in formes if formes[forme].freq > 1]
59         tot = sortedby(tot, 2,1)
60         tot = [[i, val] for i, val in enumerate(tot)]
61         hapax = [[forme, formes[forme].freq, formes[forme].gram] for forme in formes if formes[forme].freq == 1]
62         hapax = sortedby(hapax, 1, 1)
63         hapax = [[i, val] for i, val in enumerate(hapax)]
64         act = [[forme, formes[forme].freq, formes[forme].gram] for forme in formes if formes[forme].act == 1]
65         act = sortedby(act, 2, 1)
66         act = [[i, val] for i, val in enumerate(act)]
67         supp = [[forme, formes[forme].freq, formes[forme].gram] for forme in formes if formes[forme].act == 2]        
68         supp = sortedby(supp, 2, 1)
69
70         supp = [[i, val] for i, val in enumerate(supp)]
71         #self.corpus.pathout = self.dictpathout
72         #self.corpus.make_type_tot()
73
74         self.result = {u'total' : dict(tot), u'formes_actives' : dict(act), u'formes_supplĂ©mentaires' : dict(supp), u'hapax' : dict(hapax), u'glob' : ''}
75         occurrences = sum([val[1][1] for val in tot]) + len(hapax)
76         phapax = (float(len(hapax)) / float(occurrences)) * 100
77         phapax_forme = (float(len(hapax)) / (float(len(formes)))) * 100
78         moy_occu_mot = float(occurrences) / float(len(formes))
79         txt = 'Globale\n'
80         txt += 'nombre d\'uci : %i\n' % len(self.corpus.ucis)
81         txt += 'nombre d\'occurrences : %i\n' % occurrences
82         txt += 'nombre de formes : %i\n' % (len(formes))
83         txt += 'moyenne d\'occurrences par forme : %.2f\n' % moy_occu_mot
84         txt += 'nombre d\'hapax : %i (%.2f%% des occurrences - %.2f%% des formes)\n' % (len(hapax), phapax, phapax_forme)
85         print float(occurrences), float(len(self.corpus.ucis))
86         txt += 'moyenne d\'occurrences par uci : %.2f' % (float(occurrences)/float(len(self.corpus.ucis)))
87         if self.dlg :
88              self.dlg.Update(7, u'Ecriture...')
89         self.result['glob'] = txt
90         self.print_result()
91         # for Zipf grap
92         txt = """
93         source("%s")
94         tot <- read.csv2("%s", header = FALSE, row.names = 1)
95         hapax <- read.csv2("%s", header = FALSE, row.names = 1)
96         tot <- rbind(tot, hapax)
97         open_file_graph("%s", width = 400, height = 400)
98         plot(log(tot[,1]), log = 'x', xlab='log(rangs)', ylab = 'log(frequences)', col = 'red', pch=16)
99         dev.off()
100         """ % (self.parent.RscriptsPath['Rgraph'], self.pathout['total.csv'], self.pathout['hapax.csv'], self.pathout['zipf.png'])
101         tmpscript = tempfile.mktemp(dir=self.parent.TEMPDIR)
102         with open(tmpscript, 'w') as f :
103             f.write(txt)
104         pid = exec_rcode(self.parent.RPath, tmpscript, wait = False)
105         while pid.poll() == None :
106             sleep(0.2)
107         check_Rresult(self.parent, pid)
108         #CreateIraFile(self.dictpathout, 0, corpname = os.path.basename(self.corpus.parametre['filename']), section = 'stat')
109         if self.dlg :
110             #OpenAnalyse(self.parent, self.pathout['Analyse.ira'])
111             #self.DoLayout(self.parent)
112             self.dlg.Destroy()
113
114     def print_result(self) :
115         for key in self.result :
116             if key != 'glob' :
117                 dico = self.result[key]
118                 toprint = [[dico[val][0],`dico[val][1]`, dico[val][2]] for val in dico]
119                 #toprint = [[line[0], `line[1]`] for line in self.result[key]]
120                 with open(self.pathout['%s.csv' % key], 'w') as f :
121                     f.write('\n'.join([';'.join([val for val in ligne]) for ligne in toprint]).encode(self.parent.syscoding))
122             else :
123                 with open(self.pathout['%s.txt' % 'glob'], 'w') as f :
124                     f.write(self.result['glob'].encode(self.parent.syscoding))
125             self.parametres['pathout'] = self.pathout['Analyse.ira']
126             DoConf().makeoptions(['stat'],[self.parametres], self.pathout['Analyse.ira'])
127
128
129 #class Stat():
130 #    def __init__(self, parent, corpus, cmd = False, lem = True, exp = True):
131 #####################################################################   
132 #        logger.info('start text stat')
133 #        self.conf = None
134 #        self.parent = parent
135 #        self.type = 'alceste'
136 #        self.cmd = cmd
137 #        self.ConfigPath = parent.ConfigPath
138 #        self.DictPath = parent.DictPath
139 #        self.KeyConf = RawConfigParser()
140 #        self.KeyConf.read(self.ConfigPath['key'])
141 #        page = getPage(self.parent)
142 #        if page is not None :
143 #            self.corpus = getCorpus(page)
144 #            if self.corpus is not None :
145 #                self.pathout = ConstructPathOut(self.corpus.parametre['openpath'], 'Stat')
146 #                self.dictpathout = StatTxtPathOut(self.pathout)
147 #                self.val = wx.ID_OK
148 #        else :
149 #            self.corpus = Corpus(parent)
150 #            self.corpus.parametre['encodage'] = parent.corpus_encodage
151 #            self.corpus.parametre['lang'] = parent.corpus_lang
152 #            self.corpus.parametre['filename'] = parent.filename
153 #            self.pathout = ConstructPathOut(self.corpus.parametre['filename'], 'Stat')
154 #            self.dictpathout = StatTxtPathOut(self.pathout)
155 #            self.corpus.dictpathout = self.dictpathout
156 #            if not self.cmd :
157 #                dial = StatDialog(self,parent)
158 #                dial.CenterOnParent()
159 #                self.val = dial.ShowModal()
160 #            else :
161 #                self.val = wx.ID_OK
162 #            if self.val == wx.ID_OK :
163 #                if not self.cmd :
164 #                    if dial.radio_lem.GetSelection() == 0 : lem = True
165 #                    else : lem = False
166 #                    if dial.exp.GetSelection() == 0 : exp = True
167 #                    else : exp = False
168 #                    self.make_uce = dial.check_uce.GetValue()
169 #                    self.corpus.parametre['nbforme_uce'] = dial.spin_ctrl_4.GetValue()
170 #                    self.corpus.parametre['max_actives'] = dial.spin_max_actives.GetValue()
171 #                    self.corpus.parametre['eff_min_uce'] = self.corpus.parametre['nbforme_uce']
172 #                else :
173 #                    lem = True
174 #                    exp = True
175 #                    self.make_uce = False
176 #                    self.corpus.parametre['nbforme_uce'] = None
177 #                    self.corpus.parametre['eff_min_uce'] = None
178 #                self.corpus.parametre['lem'] = lem
179 #                self.corpus.parametre['expressions'] = exp
180 #                self.corpus.supplementaires = [option for option in self.KeyConf.options('KEYS') if self.KeyConf.get('KEYS', option) == "2"]
181 #                self.corpus.typeactive = [option for option in self.KeyConf.options('KEYS') if self.KeyConf.get('KEYS', option) == "1"]
182 #                self.make_corpus()
183 #
184 #        if self.val == wx.ID_OK :
185 #            if 'supplementaires' not in dir(self.corpus) :
186 #                print 'supplementaire'
187 #                self.corpus.supplementaires = [option for option in self.KeyConf.options('KEYS') if self.KeyConf.get('KEYS', option) == "2"]
188 #                print self.corpus.supplementaires
189 #            else :
190 #                print 'corpus supplementaires'
191 #                print self.corpus.supplementaires
192 #            if 'typeactive' not in dir(self.corpus) :
193 #                self.corpus.typeactive = [option for option in self.KeyConf.options('KEYS') if self.KeyConf.get('KEYS', option) == "1"]
194 #            self.make_stats()
195 #
196 #    def make_corpus(self) :
197 #        if not self.cmd :
198 #            self.dlg = progressbar(self, 7)
199 #        else :
200 #            self.dlg = None
201 #        self.corpus.content = self.parent.content
202 #        #print 'ATTENTION : FROM TT'
203 #        #prepare_for_treetagger(self.corpus, self.parent)
204 #        #get_ucis_from_tt(self.corpus)
205 #        #qsdfqsdf
206 #        ucis_txt, ucis_paras_txt = self.corpus.start_analyse(self.parent, dlg = self.dlg, cmd = self.cmd, fromtt = False)
207 #        #self.corpus.make_et_table()
208 #        #self.corpus.make_len_uce(self.corpus.get_tot_occ_from_ucis_txt(ucis_txt))
209 ##        print 'ATTTTTENTION CHECK_DOUBLON'
210 ##        self.corpus.check_double(ucis_txt)
211 #        del ucis_txt
212 #        
213 #        if not self.cmd :
214 #            self.dlg.Update(5, '%i UCI...' % len(ucis_paras_txt))
215 #        self.corpus.make_ucis_paras_uces(ucis_paras_txt, make_uce = self.make_uce)
216 #        del ucis_paras_txt
217 #
218 ##        print 'ATTENTION EFF PAR UCI'
219 ##        effuci = [[`i`, `len(uce)`] for i, uci in enumerate(self.corpus.ucis_paras_uces) for para in uci for uce in para]
220 ##        with open('/home/pierre/fac/identite/taille_uci.csv', 'w') as f :
221 ##            f.write('\n'.join([';'.join(val) for val in effuci]))
222 ##        print effuci[0:30]
223 ##        print max(effuci), min(effuci), float(sum(effuci))/float(len(effuci))
224 ##        qsdfqsdfqsd
225 #
226 #
227 #        if self.corpus.para_coords != [[] for val in self.corpus.para_coords] :
228 #            self.corpus.parametre['para'] = True
229 #        else :
230 #            self.corpus.parametre['para'] = False
231 #        self.corpus.make_etoiles(self.corpus.para_coords)
232 #
233 #        print 'len(ucis_paras_uces', len(self.corpus.ucis_paras_uces)
234 #        
235 #        if not self.cmd :
236 #            self.dlg.Update(6, u'Dictionnaires')
237 #        uces, orderuces = self.corpus.make_forms_and_uces()
238 #        self.corpus.make_lems(self.parent.lexique)
239 #
240 #    def make_stats(self):
241 #        if not self.cmd :
242 #            if not 'dlg' in dir(self) :
243 #                self.dlg = progressbar(self, 7)
244 #        if not self.corpus.parametre['lem'] :
245 #            formes = self.corpus.formes
246 #        else :
247 #            formes = self.corpus.make_lem_eff()
248 #        tot = [[forme, formes[forme][0], formes[forme][2]] for forme in formes if formes[forme][0] > 1]
249 #        tot = sortedby(tot, 2,1)
250 #        tot = [[i, val] for i, val in enumerate(tot)]
251 #        hapax = [[forme, formes[forme][0], formes[forme][2]] for forme in formes if formes[forme][0] == 1]
252 #        hapax = sortedby(hapax, 1, 1)
253 #        hapax = [[i, val] for i, val in enumerate(hapax)]
254 #        act = [[forme, formes[forme][0], formes[forme][2]] for forme in formes if formes[forme][2] in self.corpus.typeactive]
255 #        act = sortedby(act, 2, 1)
256 #        act = [[i, val] for i, val in enumerate(act)]
257 #        supp = [[forme, formes[forme][0], formes[forme][2]] for forme in formes if formes[forme][2] in self.corpus.supplementaires]
258 #        supp = sortedby(supp, 2, 1)
259 #        supp = [[i, val] for i, val in enumerate(supp)]
260 #        self.corpus.dictpathout = self.dictpathout
261 #        #self.corpus.make_type_tot()
262 #
263 #        self.result = {u'total' : dict(tot), u'formes_actives' : dict(act), u'formes_supplĂ©mentaires' : dict(supp), u'hapax' : dict(hapax), u'glob' : ''}
264 #        occurrences = sum([val[1][1] for val in tot]) + len(hapax)
265 #        phapax = (float(len(hapax)) / float(occurrences)) * 100
266 #        phapax_forme = (float(len(hapax)) / (float(len(formes)) + len(hapax))) * 100
267 #        moy_occu_mot = float(occurrences) / float(len(formes))
268 #        txt = 'Globale\n'
269 #        txt += 'nombre d\'uci : %i\n' % len(self.corpus.ucis)
270 #        txt += 'nombre d\'occurrences : %i\n' % occurrences
271 #        txt += 'nombre de formes : %i\n' % (len(formes) + len(hapax))
272 #        txt += 'moyenne d\'occurrences par forme : %.2f\n' % moy_occu_mot
273 #        txt += 'nombre d\'hapax : %i (%.2f%% des occurrences - %.2f%% des formes)\n' % (len(hapax), phapax, phapax_forme)
274 #        print float(occurrences), float(len(self.corpus.ucis))
275 #        txt += 'moyenne d\'occurrences par uci : %.2f' % (float(occurrences)/float(len(self.corpus.ucis)))
276 #        if not self.cmd :
277 #             self.dlg.Update(7, u'Ecriture...')
278 #        self.result['glob'] = txt
279 #        self.print_result()
280 #        # for Zipf grap
281 #        txt = """
282 #        source("%s")
283 #        tot <- read.csv2("%s", header = FALSE, row.names = 1)
284 #        hapax <- read.csv2("%s", header = FALSE, row.names = 1)
285 #        tot <- rbind(tot, hapax)
286 #        open_file_graph("%s", width = 400, height = 400)
287 #        plot(log(tot[,1]), log = 'x', xlab='log(rangs)', ylab = 'log(frequences)', col = 'red', pch=16)
288 #        dev.off()
289 #        """ % (self.parent.RscriptsPath['Rgraph'], ffr(os.path.join(self.pathout, 'total.csv')), ffr(os.path.join(self.pathout, 'hapax.csv')), self.dictpathout['zipf'])
290 #        tmpscript = tempfile.mktemp(dir=self.parent.TEMPDIR)
291 #        with open(tmpscript, 'w') as f :
292 #            f.write(txt)
293 #        pid = exec_rcode(self.parent.RPath, tmpscript, wait = False)
294 #        while pid.poll() == None :
295 #            sleep(0.2)
296 #        check_Rresult(self.parent, pid)
297 #        self.corpus.save_corpus(self.dictpathout['db'])
298 #        CreateIraFile(self.dictpathout, 0, corpname = os.path.basename(self.corpus.parametre['filename']), section = 'stat')
299 #        if not self.cmd :
300 #            OpenAnalyse(self.parent, self.dictpathout['ira'])
301 #            #self.DoLayout(self.parent)
302 #            self.dlg.Destroy()
303 #
304 #    def print_result(self) :
305 #        for key in self.result :
306 #            if key != 'glob' :
307 #                dico = self.result[key]
308 #                toprint = [[dico[val][0],`dico[val][1]`, dico[val][2]] for val in dico]
309 #                #toprint = [[line[0], `line[1]`] for line in self.result[key]]
310 #                output = open(os.path.join(self.pathout,'%s.csv' % key), 'w')
311 #                output.write('\n'.join([';'.join([val for val in ligne]) for ligne in toprint]))
312 #                output.close()
313 #            else :
314 #                output = open(os.path.join(self.pathout,'%s.txt' % 'glob'), 'w')
315 #                output.write(self.result['glob'])
316 #                output.close()