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