...
[iramuteq] / analysetxt.py
1 # -*- coding: utf-8 -*-
2 #Author: Pierre Ratinaud
3 #from corpusNG import Corpus
4 import logging
5 from chemins import PathOut, ChdTxtPathOut
6 from functions import exec_rcode, check_Rresult, DoConf, print_liste
7 from time import time, sleep
8 from uuid import uuid4
9 import os
10 #ALCESTE
11 from PrintRScript import RchdTxt, AlcesteTxtProf
12 from OptionAlceste import OptionAlc 
13 from layout import PrintRapport
14 from openanalyse import OpenAnalyse
15 from time import time
16 ######################################
17 print '#######LOGGING TEST###########'
18 log = logging.getLogger('iramuteq.analyse')
19 #formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
20 #ch = logging.StreamHandler()
21 #ch.setFormatter(formatter)
22 #log.addHandler(ch)
23 #log.setLevel(logging.INFO)
24 #######################################
25
26 #def make_ucecl_from_R(filein) :
27 #    with open(filein, 'rU') as f :
28 #        c = f.readlines()
29 #    c.pop(0)
30 #    ucecl = []
31 #    for line in c :
32 #        line = line.replace('\n', '').replace('"', '').split(';')
33 #        ucecl.append([int(line[0]) - 1, int(line[1])])
34 #    classesl = [val[1] for val in ucecl]
35 #    clnb = max(classesl)
36 #    ucecl = sorted(ucecl, key=itemgetter(1))
37 #    ucecl = [[uce[0] for uce in ucecl if uce[1] == i] for i in range(clnb+1)]
38 #    return ucecl
39 #
40 #def make_lc(self, uces, classes, clnb) :    
41 #    self.lc = [[] for classe in range(0,clnb)]
42 #    for i in range(0,clnb):
43 #        self.lc[i] = [uce for j, uce in enumerate(uces) if i+1 == classes[j]]
44 #    self.lc0 = [uce for j, uce in enumerate(uces) if 0 == classes[j]]
45
46
47 class AnalyseText :
48     def __init__(self, ira, corpus, parametres = None, dlg = False) :
49         self.corpus = corpus
50         self.ira = ira
51         self.parent = ira
52         self.dlg = dlg
53         self.dialok = True
54         self.parametres = parametres
55         self.pathout = PathOut(corpus.parametres['originalpath'], analyse_type = parametres['type'], dirout = corpus.parametres['pathout'])
56         self.parametres = self.make_config(parametres)
57         log.info(self.pathout.dirout)
58         if self.parametres is not None :
59             self.keys = DoConf(self.ira.ConfigPath['key']).getoptions()
60             gramact = [k for k in keys if keys[k] == 1]
61             gramsup = [k for k in keys if keys[k] == 2]
62             #FIXME
63             if not 'lem' in self.parametres :
64                 self.parametres['lem'] = 1
65             self.parametres['pathout'] = self.pathout.mkdirout()
66             self.pathout = PathOut(dirout = self.parametres['pathout'])
67             self.pathout.createdir(self.parametres['pathout'])
68             self.parametres['corpus'] = self.corpus.parametres['uuid']
69             self.parametres['uuid'] = str(uuid4())
70             self.parametres['name'] = os.path.split(self.parametres['pathout'])[1]
71             self.parametres['type'] = parametres['type']
72             self.parametres['encoding'] = self.ira.syscoding
73             self.t1 = time()
74             #if self.corpus.lems is None :
75             self.corpus.make_lems(lem = self.parametres['lem'])
76             corpus.parse_active(gramact, gramsup)
77             self.doanalyse()
78             self.time = time() - self.t1
79             minutes, seconds = divmod(self.time, 60)
80             hours, minutes = divmod(minutes, 60)            
81             self.parametres['time'] = '%.0fh %.0fm %.0fs' % (hours, minutes, seconds)
82             self.parametres['ira'] = self.pathout['Analyse.ira']
83             DoConf().makeoptions([self.parametres['type']], [self.parametres], self.pathout['Analyse.ira'])
84             self.ira.history.add(self.parametres)
85             if dlg :
86                 dlg.Destroy()
87                 OpenAnalyse(self.parent, self.parametres['ira'])
88                 self.ira.tree.AddAnalyse(self.parametres)
89                 self.val = 5100
90         else :
91             if dlg :
92                 dlg.Destroy()
93             self.val = False
94
95     def doanalyse(self) :
96         pass
97
98     def make_config(self, config) :
99         if config is not None :
100             if not self.dlg : 
101                 return config
102             else :
103                 return self.preferences()
104
105     def readconfig(self, config) :
106         return config
107
108     def preferences(self) :
109         return {}
110
111     def printRscript(self) :
112         pass
113
114     def doR(self, Rscript, wait = False, dlg = None, message = '') :
115         log.info('R code...')
116         pid = exec_rcode(self.ira.RPath, Rscript, wait = wait)
117         while pid.poll() is None :
118             if dlg is not None :
119                 self.dlg.Pulse(message)
120                 sleep(0.2)
121             else :
122                 sleep(0.2)
123         check_Rresult(self.ira, pid)
124
125
126
127 class Alceste(AnalyseText) :
128     def doanalyse(self) :
129         #self.pathout = PathOut(self.corpus.parametres['filename'], 'alceste')
130         self.parametres['type'] = 'alceste'
131         self.pathout.basefiles(ChdTxtPathOut)
132         self.actives, lim = self.corpus.make_actives_nb(self.parametres['max_actives'], 1)
133         self.parametres['eff_min_forme'] = lim
134         self.parametres['nbactives'] = len(self.actives)
135         if self.parametres['classif_mode'] == 0 :
136             lenuc1, lenuc2 = self.corpus.make_and_write_sparse_matrix_from_uc(self.actives, self.parametres['tailleuc1'], self.parametres['tailleuc2'], self.pathout['TableUc1'], self.pathout['TableUc2'], self.pathout['listeuce1'], self.pathout['listeuce2'])
137             self.parametres['lenuc1'] = lenuc1
138             self.parametres['lenuc2'] = lenuc2
139         elif self.parametres['classif_mode'] == 1 :
140             self.corpus.make_and_write_sparse_matrix_from_uces(self.actives, self.pathout['TableUc1'], self.pathout['listeuce1'])
141         elif self.parametres['classif_mode'] == 2 :
142             self.corpus.make_and_write_sparse_matrix_from_uci(self.actives, self.pathout['TableUc1'], self.pathout['listeuce1'])
143         Rscript = self.printRscript()
144         self.doR(Rscript)
145         #self.lc = make_ucecl_from_R(self.pathout['uce'])
146         #self.lc0 = self.lc.pop(0)
147         self.corpus.make_ucecl_from_R(self.pathout['uce'])
148         self.corpus.make_and_write_profile(self.actives, self.corpus.lc, self.pathout['Contout'])
149         self.sup, lim = self.corpus.make_actives_nb(self.parametres['max_actives'], 2)
150         self.corpus.make_and_write_profile(self.sup, self.corpus.lc, self.pathout['ContSupOut'])
151         self.corpus.make_and_write_profile_et(self.corpus.lc, self.pathout['ContEtOut'])
152         self.clnb = len(self.corpus.lc)
153         self.parametres['clnb'] = self.clnb
154         Rscript = self.printRscript2()
155         self.doR(Rscript)
156         self.time = time() - self.t1
157         minutes, seconds = divmod(self.time, 60)
158         hours, minutes = divmod(minutes, 60)            
159         self.parametres['time'] = '%.0fh %.0fm %.0fs' % (hours, minutes, seconds)
160         self.print_graph_files()
161
162     def preferences(self) :
163         parametres = DoConf(self.parent.ConfigPath['alceste']).getoptions('ALCESTE')
164         parametres['corpus'] = self.corpus
165         parametres['pathout'] = self.pathout
166         self.dial = OptionAlc(self.parent, parametres)
167         self.dial.CenterOnParent()
168         self.dialok = self.dial.ShowModal()
169         if self.dialok == 5100 :
170             if self.dial.radio_1.GetSelection() == 0 :
171                 lem = 1
172             else :
173                 lem = 0
174             parametres['lem'] = lem
175             parametres['classif_mode'] = self.dial.radio_box_2.GetSelection()
176             parametres['tailleuc1'] = self.dial.spin_ctrl_1.GetValue()
177             parametres['tailleuc2'] = self.dial.spin_ctrl_2.GetValue()
178             parametres['mincl'] = self.dial.spin_ctrl_4.GetValue()
179             parametres['minforme'] = self.dial.spin_ctrl_5.GetValue()
180             parametres['nbcl_p1'] = self.dial.spin_nbcl.GetValue()
181             parametres['max_actives'] = self.dial.spin_max_actives.GetValue()
182             parametres['corpus'] = ''
183             parametres['pathout'] = self.pathout.dirout
184             for val in parametres :
185                 print val, parametres[val]
186             DoConf(self.parent.ConfigPath['alceste']).makeoptions(['ALCESTE'], [parametres])
187             self.dial.Destroy()
188             return parametres
189         else :
190             self.dial.Destroy()
191             return None
192
193     def printRscript(self) :
194         RchdTxt(self.pathout, self.parent.RscriptsPath, self.parametres['mincl'], self.parametres['classif_mode'], nbt = self.parametres['nbcl_p1'] - 1, libsvdc = self.parent.pref.getboolean('iramuteq','libsvdc'), libsvdc_path = self.parent.pref.get('iramuteq','libsvdc_path'), R_max_mem = False)
195         return self.pathout['Rchdtxt']
196
197     def printRscript2(self) :
198         AlcesteTxtProf(self.pathout, self.parent.RscriptsPath, self.clnb, 0.9)
199         return self.pathout['RTxtProfGraph']
200
201     def print_graph_files(self) :
202         afc_graph_list = [[os.path.basename(self.pathout['AFC2DL_OUT']), u'Variables actives - coordonnées - facteurs 1 / 2'],
203                       [os.path.basename(self.pathout['AFC2DSL_OUT']), u'variables supplémentaires - coordonnées - facteurs 1 / 2'],
204                       [os.path.basename(self.pathout['AFC2DEL_OUT']), u'Variables illustratives - Coordonnées - facteur 1 / 2'],
205                       [os.path.basename(self.pathout['AFC2DCL_OUT']), u'Classes - Coordonnées - facteur 1 / 2'],
206                       [os.path.basename(self.pathout['AFC2DCoul']), u'Variables actives - Corrélation - facteur 1 / 2'],
207                       [os.path.basename(self.pathout['AFC2DCoulSup']), u'Variables supplémentaires - Corrélation - facteur 1 / 2'],
208                       [os.path.basename(self.pathout['AFC2DCoulEt']), u'Variables illustratives - Corrélations - facteur 1 / 2'],
209                       [os.path.basename(self.pathout['AFC2DCoulCl']), u'Classes - Corrélations - facteurs 1 / 2'],]
210         chd_graph_list = [[os.path.basename(self.pathout['dendro1']), u'dendrogramme à partir de chd1']]
211         if self.parametres['classif_mode'] == 0 :
212             chd_graph_list.append([os.path.basename(self.pathout['dendro2']), u'dendrogramme à partir de chd2'])
213         chd_graph_list.append([os.path.basename(self.pathout['arbre1']), u'chd1'])
214         if self.parametres['classif_mode'] == 0 :
215             chd_graph_list.append([os.path.basename(self.pathout['arbre2']), u'chd2'])       
216         print_liste(self.pathout['liste_graph_afc'],afc_graph_list)
217         print_liste(self.pathout['liste_graph_chd'],chd_graph_list)
218         PrintRapport(self, self.corpus, self.parametres)
219
220
221 keys = {'art_def' : 2,
222         'pre' : 2,
223         'adj_dem' : 2,
224         'ono' : 2,
225         'pro_per' : 2,
226         'ver_sup' : 2,
227         'adv' : 1,
228         'ver' : 1,
229         'adj_ind' : 2,
230         'adj_pos' : 2,
231         'aux' : 2,
232         'adj_int' : 2,
233         'pro_ind' : 2,
234         'adj' : 1,
235         'pro_dem' : 2,
236         'nom' : 1,
237         'art_ind' : 2,
238         'pro_pos' : 2,
239         'nom_sup' : 2,
240         'adv_sup' : 2,
241         'adj_sup' : 2,
242         'adj_num' : 2,
243         'pro_rel' : 2,
244         'con' : 2,
245         'num' : 2,
246         'nr' : 1,
247         'sw' : 2,
248 }
249
250 gramact = [k for k in keys if keys[k] == 1]
251 gramsup = [k for k in keys if keys[k] == 2]
252
253 #corpus = Corpus('', {'filename': '/home/pierre/workspace/iramuteq/dev/testcorpus.txt','formesdb':'formes.db', 'ucesdb': 'uces.db', 'corpusdb' : 'corpus.db', 'syscoding' : 'utf-8'})
254 #corpus.read_corpus()
255 #corpus.parse_active(gramact, gramsup)
256 #Alceste(corpus).doanalyse()