installation textometrieR
[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.val = False
56         self.pathout = PathOut(corpus.parametres['originalpath'], analyse_type = parametres['type'], dirout = corpus.parametres['pathout'])
57         self.parametres = self.make_config(parametres)
58         log.info(self.pathout.dirout)
59         if self.parametres is not None :
60             self.keys = DoConf(self.ira.ConfigPath['key']).getoptions()
61             gramact = [k for k in keys if keys[k] == 1]
62             gramsup = [k for k in keys if keys[k] == 2]
63             #FIXME
64             if not 'lem' in self.parametres :
65                 self.parametres['lem'] = 1
66             self.parametres['pathout'] = self.pathout.mkdirout()
67             self.pathout = PathOut(dirout = self.parametres['pathout'])
68             self.pathout.createdir(self.parametres['pathout'])
69             self.parametres['corpus'] = self.corpus.parametres['uuid']
70             self.parametres['uuid'] = str(uuid4())
71             self.parametres['name'] = os.path.split(self.parametres['pathout'])[1]
72             self.parametres['type'] = parametres['type']
73             self.parametres['encoding'] = self.ira.syscoding
74             self.t1 = time()
75             #if self.corpus.lems is None :
76             self.corpus.make_lems(lem = self.parametres['lem'])
77             corpus.parse_active(gramact, gramsup)
78             result_analyse = self.doanalyse()
79             if result_analyse is None :
80                  self.time = time() - self.t1
81                  minutes, seconds = divmod(self.time, 60)
82                  hours, minutes = divmod(minutes, 60)            
83                  self.parametres['time'] = '%.0fh %.0fm %.0fs' % (hours, minutes, seconds)
84                  self.parametres['ira'] = self.pathout['Analyse.ira']
85                  DoConf().makeoptions([self.parametres['type']], [self.parametres], self.pathout['Analyse.ira'])
86                  self.ira.history.add(self.parametres)
87                  if dlg :
88                      dlg.Destroy()
89                      OpenAnalyse(self.parent, self.parametres['ira'])
90                      self.ira.tree.AddAnalyse(self.parametres)
91                      self.val = 5100
92             else :
93                  self.val = False
94                  if dlg :
95                      dlg.Destroy()
96         else :
97             if dlg :
98                 dlg.Destroy()
99             self.val = False
100
101     def doanalyse(self) :
102         pass
103
104     def make_config(self, config) :
105         if config is not None :
106             if not self.dlg : 
107                 return config
108             else :
109                 return self.preferences()
110
111     def readconfig(self, config) :
112         return config
113
114     def preferences(self) :
115         return {}
116
117     def printRscript(self) :
118         pass
119
120     def doR(self, Rscript, wait = False, dlg = None, message = '') :
121         log.info('R code...')
122         pid = exec_rcode(self.ira.RPath, Rscript, wait = wait)
123         while pid.poll() is None :
124             if dlg is not None :
125                 self.dlg.Pulse(message)
126                 sleep(0.2)
127             else :
128                 sleep(0.2)
129         return check_Rresult(self.ira, pid)
130
131
132
133 class Alceste(AnalyseText) :
134     def doanalyse(self) :
135         #self.pathout = PathOut(self.corpus.parametres['filename'], 'alceste')
136         self.parametres['type'] = 'alceste'
137         self.pathout.basefiles(ChdTxtPathOut)
138         self.actives, lim = self.corpus.make_actives_nb(self.parametres['max_actives'], 1)
139         self.parametres['eff_min_forme'] = lim
140         self.parametres['nbactives'] = len(self.actives)
141         if self.parametres['classif_mode'] == 0 :
142             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'])
143             self.parametres['lenuc1'] = lenuc1
144             self.parametres['lenuc2'] = lenuc2
145         elif self.parametres['classif_mode'] == 1 :
146             self.corpus.make_and_write_sparse_matrix_from_uces(self.actives, self.pathout['TableUc1'], self.pathout['listeuce1'])
147         elif self.parametres['classif_mode'] == 2 :
148             self.corpus.make_and_write_sparse_matrix_from_uci(self.actives, self.pathout['TableUc1'], self.pathout['listeuce1'])
149         Rscript = self.printRscript()
150         self.doR(Rscript)
151         #self.lc = make_ucecl_from_R(self.pathout['uce'])
152         #self.lc0 = self.lc.pop(0)
153         self.corpus.make_ucecl_from_R(self.pathout['uce'])
154         self.corpus.make_and_write_profile(self.actives, self.corpus.lc, self.pathout['Contout'])
155         self.sup, lim = self.corpus.make_actives_nb(self.parametres['max_actives'], 2)
156         self.corpus.make_and_write_profile(self.sup, self.corpus.lc, self.pathout['ContSupOut'])
157         self.corpus.make_and_write_profile_et(self.corpus.lc, self.pathout['ContEtOut'])
158         self.clnb = len(self.corpus.lc)
159         self.parametres['clnb'] = self.clnb
160         Rscript = self.printRscript2()
161         self.doR(Rscript)
162         self.time = time() - self.t1
163         minutes, seconds = divmod(self.time, 60)
164         hours, minutes = divmod(minutes, 60)            
165         self.parametres['time'] = '%.0fh %.0fm %.0fs' % (hours, minutes, seconds)
166         self.print_graph_files()
167
168     def preferences(self) :
169         parametres = DoConf(self.parent.ConfigPath['alceste']).getoptions('ALCESTE')
170         parametres['corpus'] = self.corpus
171         parametres['pathout'] = self.pathout
172         self.dial = OptionAlc(self.parent, parametres)
173         self.dial.CenterOnParent()
174         self.dialok = self.dial.ShowModal()
175         if self.dialok == 5100 :
176             if self.dial.radio_1.GetSelection() == 0 :
177                 lem = 1
178             else :
179                 lem = 0
180             parametres['lem'] = lem
181             parametres['classif_mode'] = self.dial.radio_box_2.GetSelection()
182             parametres['tailleuc1'] = self.dial.spin_ctrl_1.GetValue()
183             parametres['tailleuc2'] = self.dial.spin_ctrl_2.GetValue()
184             parametres['mincl'] = self.dial.spin_ctrl_4.GetValue()
185             parametres['minforme'] = self.dial.spin_ctrl_5.GetValue()
186             parametres['nbcl_p1'] = self.dial.spin_nbcl.GetValue()
187             parametres['max_actives'] = self.dial.spin_max_actives.GetValue()
188             parametres['corpus'] = ''
189             parametres['pathout'] = self.pathout.dirout
190             for val in parametres :
191                 print val, parametres[val]
192             DoConf(self.parent.ConfigPath['alceste']).makeoptions(['ALCESTE'], [parametres])
193             self.dial.Destroy()
194             return parametres
195         else :
196             self.dial.Destroy()
197             return None
198
199     def printRscript(self) :
200         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)
201         return self.pathout['Rchdtxt']
202
203     def printRscript2(self) :
204         AlcesteTxtProf(self.pathout, self.parent.RscriptsPath, self.clnb, 0.9)
205         return self.pathout['RTxtProfGraph']
206
207     def print_graph_files(self) :
208         mess_afc = u"La position des points n'est peut être pas exacte"
209         afc_graph_list = [[os.path.basename(self.pathout['AFC2DL_OUT']), u'Variables actives - coordonnées - 30 points par classes - facteurs 1 / 2 - %s' % mess_afc],
210                       [os.path.basename(self.pathout['AFC2DSL_OUT']), u'variables supplémentaires - coordonnées - 30 points par classes - facteurs 1 / 2 - %s' % mess_afc],
211                       [os.path.basename(self.pathout['AFC2DEL_OUT']), u'Variables illustratives - Coordonnées - 30 points par classes - facteur 1 / 2 - %s' % mess_afc],
212                       [os.path.basename(self.pathout['AFC2DCL_OUT']), u'Classes - Coordonnées - facteur 1 / 2']]
213                       #[os.path.basename(self.pathout['AFC2DCoul']), u'Variables actives - Corrélation - facteur 1 / 2'],
214                       #[os.path.basename(self.pathout['AFC2DCoulSup']), u'Variables supplémentaires - Corrélation - facteur 1 / 2'],
215                       #[os.path.basename(self.pathout['AFC2DCoulEt']), u'Variables illustratives - Corrélations - facteur 1 / 2'],
216                       #[os.path.basename(self.pathout['AFC2DCoulCl']), u'Classes - Corrélations - facteurs 1 / 2'],]
217         chd_graph_list = [[os.path.basename(self.pathout['dendro1']), u'dendrogramme à partir de chd1']]
218         if self.parametres['classif_mode'] == 0 :
219             chd_graph_list.append([os.path.basename(self.pathout['dendro2']), u'dendrogramme à partir de chd2'])
220         chd_graph_list.append([os.path.basename(self.pathout['arbre1']), u'chd1'])
221         if self.parametres['classif_mode'] == 0 :
222             chd_graph_list.append([os.path.basename(self.pathout['arbre2']), u'chd2'])       
223         print_liste(self.pathout['liste_graph_afc'],afc_graph_list)
224         print_liste(self.pathout['liste_graph_chd'],chd_graph_list)
225         PrintRapport(self, self.corpus, self.parametres)
226
227
228 keys = {'art_def' : 2,
229         'pre' : 2,
230         'adj_dem' : 2,
231         'ono' : 2,
232         'pro_per' : 2,
233         'ver_sup' : 2,
234         'adv' : 1,
235         'ver' : 1,
236         'adj_ind' : 2,
237         'adj_pos' : 2,
238         'aux' : 2,
239         'adj_int' : 2,
240         'pro_ind' : 2,
241         'adj' : 1,
242         'pro_dem' : 2,
243         'nom' : 1,
244         'art_ind' : 2,
245         'pro_pos' : 2,
246         'nom_sup' : 2,
247         'adv_sup' : 2,
248         'adj_sup' : 2,
249         'adj_num' : 2,
250         'pro_rel' : 2,
251         'con' : 2,
252         'num' : 2,
253         'nr' : 1,
254         'sw' : 2,
255 }
256
257 gramact = [k for k in keys if keys[k] == 1]
258 gramsup = [k for k in keys if keys[k] == 2]
259
260 #corpus = Corpus('', {'filename': '/home/pierre/workspace/iramuteq/dev/testcorpus.txt','formesdb':'formes.db', 'ucesdb': 'uces.db', 'corpusdb' : 'corpus.db', 'syscoding' : 'utf-8'})
261 #corpus.read_corpus()
262 #corpus.parse_active(gramact, gramsup)
263 #Alceste(corpus).doanalyse()