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