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