2 # -*- coding: utf-8 -*-
3 #Author: Pierre Ratinaud
4 #Copyright (c) 2008-2012 Pierre Ratinaud
9 from ConfigParser import ConfigParser
10 from subprocess import Popen, call, PIPE
22 from shutil import copyfile
23 #from dialog import BugDialog
24 print 'TEST LOGGING funcion'
27 log = logging.getLogger('iramuteq')
30 indices_simi = [u'cooccurrence' ,'pourcentage de cooccurrence',u'Russel',u'Jaccard', 'Kulczynski1', 'Kulczynski2', 'Mountford', 'Fager', 'simple matching', 'Hamman', 'Faith', 'Tanimoto', 'Dice', 'Phi', 'Stiles', 'Michael', 'Mozley', 'Yule', 'Yule2', 'Ochiai', 'Simpson', 'Braun-Blanquet','Chi-squared', 'Phi-squared', 'Tschuprow', 'Cramer', 'Pearson', 'binomial']
34 def __init__(self, filein, syscoding = 'utf8') :
36 self.syscoding = syscoding
38 self.openedcorpus = {}
45 self.conf = DoConf(self.filein)
48 for i, section in enumerate(self.conf.conf.sections()) :
49 if self.conf.conf.has_option(section, 'corpus_name') :
50 self.corpora[section] = self.conf.getoptions(section)
51 self.order[len(self.order)] = section
53 self.analyses[section] = self.conf.getoptions(section)
54 self.ordera[len(self.ordera)] = section
56 for corpus in self.corpora :
57 self.history[corpus] = copy(self.corpora[corpus])
58 for analyse in self.analyses :
59 if self.analyses[analyse]['corpus'] in self.corpora :
60 if 'analyses' in self.history[self.analyses[analyse]['corpus']] :
61 self.history[self.analyses[analyse]['corpus']]['analyses'].append(self.analyses[analyse])
64 self.history[self.analyses[analyse]['corpus']]['analyses'] = [self.analyses[analyse]]
67 self.history[analyse] = self.analyses[analyse]
68 #for analyse in todel :
69 # del self.analyses[analyse]
72 sections = self.corpora.keys() + self.analyses.keys()
73 parametres = [self.corpora[key] for key in self.corpora.keys()] + [self.analyses[key] for key in self.analyses.keys()]
74 self.conf.makeoptions(sections, parametres)
75 log.info('write history')
77 def add(self, analyse) :
78 if 'corpus' in analyse :
79 acorpus_uuid = analyse['corpus']
80 if acorpus_uuid in self.corpora :
81 if 'analyses' in self.history[acorpus_uuid] :
82 self.history[acorpus_uuid]['analyses'].append(analyse)
84 self.history[acorpus_uuid]['analyses'] = [analyse]
85 self.analyses[analyse['uuid']] = analyse
87 self.analyses[analyse['uuid']] = analyse
88 elif 'corpus_name' in analyse :
89 self.history[analyse['uuid']] = analyse
90 self.corpora[analyse['uuid']] = analyse
93 def delete(self, uuid, corpus = False) :
95 del self.corpora[uuid]
96 self.conf.conf.remove_section(uuid)
97 for analyse in self.history[uuid].get('analyses', [False]) :
99 del self.analyses[analyse['uuid']]
100 self.conf.conf.remove_section(analyse['uuid'])
102 del self.analyses[uuid]
103 self.conf.conf.remove_section(uuid)
106 def addtab(self, analyse) :
107 self.opened[analyse['uuid']] = analyse
109 def rmtab(self, analyse) :
110 del self.opened[analyse['uuid']]
113 return str(self.history)
116 def __init__(self, configfile=None, diff = None, parametres = None) :
117 self.configfile = configfile
118 self.conf = ConfigParser()
119 if configfile is not None :
120 self.conf.readfp(codecs.open(configfile, 'r', 'utf8'))
122 if parametres is not None :
123 self.doparametres(parametres)
125 def doparametres(self, parametres) :
128 def getsections(self) :
129 return self.conf.sections()
131 def getoptions(self, section = None, diff = None):
134 section = self.conf.sections()[0]
135 for option in self.conf.options(section) :
136 if self.conf.get(section, option).isdigit() :
137 parametres[option] = int(self.conf.get(section, option))
138 elif self.conf.get(section, option) == 'False' :
139 parametres[option] = False
140 elif self.conf.get(section, option) == 'True' :
141 parametres[option] = True
142 elif self.conf.get(section, option).startswith('(') and self.conf.get(section, option).endswith(')') :
143 parametres[option] = ast.literal_eval(self.conf.get(section, option))
145 parametres[option] = self.conf.get(section, option)
146 if 'type' not in parametres :
147 parametres['type'] = section
150 def makeoptions(self, sections, parametres, outfile = None) :
151 for i, section in enumerate(sections) :
152 if not self.conf.has_section(section) :
153 self.conf.add_section(section)
154 for option in parametres[i] :
155 if isinstance(parametres[i][option], int) :
156 self.conf.set(section, option, `parametres[i][option]`)
157 elif isinstance(parametres[i][option], basestring) :
158 self.conf.set(section, option, parametres[i][option].encode('utf8'))
159 elif isinstance(parametres[i][option], wx.Colour) :
160 self.conf.set(section, option, str(parametres[i][option]))
162 self.conf.set(section, option, `parametres[i][option]`)
164 outfile = self.configfile
165 with codecs.open(outfile, 'w', 'utf8') as f :
168 def totext(self, parametres) :
170 for val in parametres :
171 if isinstance(parametres[val], int) :
172 txt.append(' \t\t: '.join([val, `parametres[val]`]))
174 txt.append(' \t\t: '.join([val, parametres[val]]))
175 return '\n'.join(txt)
178 def write_tab(tab, fileout) :
179 writer = csv.writer(open(fileout, 'wb'), delimiter=';', quoting = csv.QUOTE_NONNUMERIC)
180 writer.writerows(tab)
182 class BugDialog(wx.Dialog):
183 def __init__(self, *args, **kwds):
184 # begin wxGlade: MyDialog.__init__
185 kwds["style"] = wx.DEFAULT_DIALOG_STYLE
186 kwds["size"] = wx.Size(500, 200)
187 wx.Dialog.__init__(self, *args, **kwds)
188 self.text_ctrl_1 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE)
189 self.button_1 = wx.Button(self, wx.ID_OK, "")
191 self.__set_properties()
195 def __set_properties(self):
196 # begin wxGlade: MyDialog.__set_properties
198 self.SetMinSize(wx.Size(500, 200))
199 self.text_ctrl_1.SetMinSize(wx.Size(500, 200))
203 def __do_layout(self):
204 # begin wxGlade: MyDialog.__do_layout
205 sizer_1 = wx.BoxSizer(wx.VERTICAL)
206 sizer_1.Add(self.text_ctrl_1, 1, wx.EXPAND, 0)
207 sizer_1.Add(self.button_1, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
208 self.SetSizer(sizer_1)
213 def CreateIraFile(DictPathOut, clusternb, corpname='corpus_name', section = 'analyse'):
214 AnalyseConf = ConfigParser()
215 AnalyseConf.read(DictPathOut['ira'])
216 AnalyseConf.add_section(section)
217 date = datetime.datetime.now().ctime()
218 AnalyseConf.set(section, 'date', str(date))
219 AnalyseConf.set(section, 'clusternb', clusternb)
220 AnalyseConf.set(section, 'corpus_name', corpname)
222 fileout = open(DictPathOut['ira'], 'w')
223 AnalyseConf.write(fileout)
226 def sortedby(list, direct, *indices):
229 sortedby: sort a list of lists (e.g. a table) by one or more indices
230 (columns of the table) and return the sorted list
233 for list = [[2,3],[1,2],[3,1]]:
234 sortedby(list,1) will return [[3, 1], [1, 2], [2, 3]],
235 sortedby(list,0) will return [[1, 2], [2, 3], [3, 1]]
238 nlist = map(lambda x, indices=indices:
239 map(lambda i, x=x: x[i], indices) + [x],
244 nlist.sort(reverse=True)
245 return map(lambda l: l[-1], nlist)
247 def add_type(line, dictlem):
248 if line[4] in dictlem:
249 line.append(dictlem[line[4]])
254 def treat_line_alceste(i, line) :
255 if line[0] == '*' or line[0] == '*****' :
260 elif float(line[5].replace(',', '.')) < 0.0001:
262 elif float(line[5].replace(',', '.')) > 0.05:
263 line[5] = 'NS (%s)' % str(float(line[5].replace(',', '.')))[0:7]
265 line[5] = str(float(line[5].replace(',', '.')))[0:7]
266 return [i, int(line[0]), int(line[1]), float(line[2]), float(line[3]), line[6], line[4], line[5]]
268 def ReadProfileAsDico(parent, File, Alceste=False, encoding = sys.getdefaultencoding()):
269 #print 'lecture des profils : ReadProfileAsDico'
271 # print 'lecture du dictionnaire de type'
273 # for line in parent.corpus.lem_type_list :
274 # dictlem[line[0]] = line[1]
276 print 'lecture des profiles'
277 #encoding = sys.getdefaultencoding()
279 FileReader = codecs.open(File, 'r', encoding)
280 Filecontent = FileReader.readlines()
284 rows = [row.replace('\n', '').replace("'", '').replace('\"', '').replace(',', '.').replace('\r','').split(';') for row in Filecontent]
286 ClusterNb = rows[0][2]
288 clusters = [row[2] for row in rows if row[0] == u'**']
289 valclusters = [row[1:4] for row in rows if row[0] == u'****']
290 lp = [i for i, line in enumerate(rows) if line[0] == u'****']
291 prof = [rows[lp[i] + 1:lp[i+1] - 1] for i in range(0, len(lp)-1)] + [rows[lp[-1] + 1:len(rows)]]
293 prof = [[add_type(row, dictlem) for row in pr] for pr in prof]
294 prof = [[treat_line_alceste(i,line) for i, line in enumerate(pr)] for pr in prof]
296 prof = [[line + [''] for line in pr] for pr in prof]
297 prof = [[treat_line_alceste(i,line) for i, line in enumerate(pr)] for pr in prof]
298 for i, cluster in enumerate(clusters):
299 DictProfile[cluster] = [valclusters[i]] + prof[i]
302 def GetTxtProfile(dictprofile) :
304 for classe in range(0, len(dictprofile)) :
305 prof = dictprofile[str(classe + 1)]
307 proflist.append('\n'.join([' '.join(['classe %i' % (classe + 1), '-', '%s uce sur %s - %s%%' % (clinfo[0], clinfo[1], clinfo[2])]), '\n'.join(['%5s|%5s|%6s|%6s|%8s|%8s|%20s\t%10s' % tuple([str(val) for val in line]) for line in prof if len(line)==8])]))
308 return '\n\n'.join(proflist)
310 def formatExceptionInfo(maxTBlevel=5):
311 cla, exc, trbk = sys.exc_info()
312 excName = cla.__name__
314 excArgs = exc.__dict__["args"]
316 excArgs = "<no args>"
317 excTb = traceback.format_tb(trbk, maxTBlevel)
318 return (excName, excArgs, excTb)
321 #fonction des etudiants de l'iut
322 def decoupercharact(chaine, longueur, longueurOptimale, separateurs = None) :
324 on part du dernier caractère, et on recule jusqu'au début de la chaîne.
325 Si on trouve un '$', c'est fini.
326 Sinon, on cherche le meilleur candidat. C'est-Ã -dire le rapport poids/distance le plus important.
328 separateurs = [[u'.', 60.0], [u'?', 60.0], [u'!', 60.0], [u'£', 60], [u':', 50.0], [u';', 40.0], [u',', 10.0], [u' ', 0.1]]
329 trouve = False # si on a trouvé un bon séparateur
330 iDecoupe = 0 # indice du caractere ou il faut decouper
332 # on découpe la chaine pour avoir au maximum 240 caractères
333 longueur = min(longueur, len(chaine) - 1)
334 chaineTravail = chaine[:longueur + 1]
336 meilleur = ['', 0, 0] # type, poids et position du meilleur separateur
338 # on vérifie si on ne trouve pas un '$'
339 indice = chaineTravail.find(u'$')
344 # si on ne trouve rien, on cherche le meilleur séparateur
347 caractere = chaineTravail[nbCar]
348 distance = abs(longueurOptimale - nbCar) + 1
349 meilleureDistance = abs(longueurOptimale - meilleur[2]) + 1
351 # on vérifie si le caractére courant est une marque de ponctuation
352 for s in separateurs:
353 if caractere == s[0]:
354 # si c'est une ponctuation
356 if s[1] / distance > float(meilleur[1]) / meilleureDistance:
364 # et on termine la recherche
367 # on passe au caractère précédant
372 fin = chaine[iDecoupe + 1:]
373 retour = chaineTravail[:iDecoupe]
374 return len(retour) > 0, retour.split(), fin
375 # si on a rien trouvé
376 return False, chaine.split(), ''
378 def BugReport(parent):
379 for ch in parent.GetChildren():
380 if "<class 'wx._windows.ProgressDialog'>" == str(type(ch)):
382 dial = BugDialog(parent)
383 txt = u' !== BUG ==! \n'
384 txt += u'*************************************\n'
385 for line in formatExceptionInfo():
386 if type(line) == type([]):
388 txt += don.replace(' ', ' ')
391 if 'Rerror' in dir(parent) :
394 print formatExceptionInfo()
396 dial.text_ctrl_1.write(txt)
397 dial.CenterOnParent()
399 raise NameError('Bug')
401 def PlaySound(parent):
402 if parent.pref.getboolean('iramuteq', 'sound') :
404 if "gtk2" in wx.PlatformInfo:
405 error = Popen(['aplay','-q',os.path.join(parent.AppliPath,'son_fin.wav')])
407 sound = wx.Sound(os.path.join(parent.AppliPath, 'son_fin.wav'))
408 sound.Play(wx.SOUND_SYNC)
412 def ReadDicoAsDico(dicopath):
413 with codecs.open(dicopath, 'r', 'UTF8') as f:
414 content = f.readlines()
416 for line in content :
418 line = line.replace(u'\n', '').replace('"', '').split('\t')
419 dico[line[0]] = line[1:]
422 def ReadLexique(parent, lang = 'french'):
423 parent.lexique = ReadDicoAsDico(parent.DictPath.get(lang, 'french'))
425 def ReadList(filein, encoding = sys.getdefaultencoding()):
427 file = codecs.open(filein, 'r', encoding)
428 content = file.readlines()
430 first = content.pop(0)
431 first = first.replace('\n', '').replace('\r','').replace('\"', '').split(';')
435 line = line.replace('\n', '').replace('\r','').replace('\"', '').replace(',', '.')
436 line = line.split(';')
445 don = float('%.5f' % float(val))
451 def exec_rcode(rpath, rcode, wait = True, graph = False):
454 if sys.platform == 'darwin' :
456 macversion = platform.mac_ver()[0].split('.')
458 if int(macversion[1]) < 5 :
465 rpath = rpath.replace('\\','\\\\')
468 if sys.platform == 'win32':
469 error = call(["%s" % rpath, "--vanilla","--slave","-f", "%s" % rcode])
471 error = call([rpath, '--vanilla','--slave',"-f %s" % rcode])
474 if sys.platform == 'win32':
475 pid = Popen(["%s" % rpath, '--vanilla','--slave','-f', "%s" % rcode])
477 pid = Popen([rpath, '--vanilla','--slave',"-f %s" % rcode], stderr = PIPE)
481 if sys.platform == 'win32':
482 error = call(["%s" % rpath, '--vanilla','--slave','-f', "%s" % rcode])
483 elif sys.platform == 'darwin' and needX11:
484 os.environ['DISPLAY'] = ':0.0'
485 error = call([rpath, '--vanilla','--slave',"-f %s" % rcode])
487 error = call([rpath, '--vanilla','--slave',"-f %s" % rcode])
490 if sys.platform == 'win32':
491 pid = Popen(["%s" % rpath, '--vanilla','--slave','-f', "%s" % rcode])
492 elif sys.platform == 'darwin' and needX11:
493 os.environ['DISPLAY'] = ':0.0'
494 pid = Popen([rpath, '--vanilla','--slave',"-f %s" % rcode], stderr = PIPE)
496 pid = Popen([rpath, '--vanilla','--slave',"-f %s" % rcode], stderr = PIPE)
499 def check_Rresult(parent, pid) :
500 if isinstance(pid, Popen) :
501 if pid.returncode != 0 :
502 error = pid.communicate()
503 error = [str(error[0]), error[1]]
504 if error[1] is None :
506 parent.Rerror = '\n'.join([str(pid.returncode), '\n'.join(error)])
508 raise Exception('\n'.join(u'Erreur R', '\n'.join(error[1:])))
514 raise Exception(u'Erreur R')
518 def print_liste(filename,liste):
519 with open(filename,'w') as f :
521 f.write(';'.join(graph)+'\n')
523 def read_list_file(filename, encoding = sys.getdefaultencoding()):
524 with codecs.open(filename,'rU', encoding) as f :
525 content=f.readlines()
526 ncontent=[line.replace('\n','').split(';') for line in content if line.strip() != '']
529 class MessageImage(wx.Frame):
530 def __init__(self, *args, **kwds):
531 # begin wxGlade: MyFrame.__init__
532 kwds["style"] = wx.DEFAULT_FRAME_STYLE
533 wx.Frame.__init__(self, *args, **kwds)
534 #self.text_ctrl_1 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE)
535 self.imageFile = False
536 self.imagename = u"chi_classe.png"
537 self.HtmlPage = wx.html.HtmlWindow(self, -1)
538 if "gtk2" in wx.PlatformInfo:
539 self.HtmlPage.SetStandardFonts()
540 self.HtmlPage.SetFonts('Courier', 'Courier')
542 self.button_1 = wx.Button(self, -1, u"Fermer")
543 self.Bind(wx.EVT_BUTTON, self.OnCloseMe, self.button_1)
544 self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
548 def __do_layout(self):
549 # begin wxGlade: MyFrame.__do_layout
550 sizer_1 = wx.BoxSizer(wx.VERTICAL)
551 self.sizer_2 = wx.BoxSizer(wx.VERTICAL)
552 self.sizer_2.Add(self.HtmlPage, 1, wx.EXPAND | wx.ADJUST_MINSIZE, 0)
553 self.sizer_2.Add(self.button_1, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ADJUST_MINSIZE, 0)
554 sizer_1.Add(self.sizer_2, 1, wx.EXPAND, 0)
555 self.SetAutoLayout(True)
556 self.SetSizer(sizer_1)
559 def addsaveimage(self, imageFile) :
560 self.imageFile = imageFile
561 self.button_2 = wx.Button(self, -1, u"Enregistrer l'image...")
562 self.Bind(wx.EVT_BUTTON, self.OnSaveImage, self.button_2)
563 self.sizer_2.Add(self.button_2, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ADJUST_MINSIZE, 0)
566 def OnCloseMe(self, event):
569 def OnCloseWindow(self, event):
572 def OnSaveImage(self, event) :
574 self, message="Enregistrer sous...", defaultDir=os.getcwd(),
575 defaultFile= self.imagename, wildcard="png|*.png", style=wx.SAVE | wx.OVERWRITE_PROMPT
577 dlg.SetFilterIndex(2)
579 if dlg.ShowModal() == wx.ID_OK:
581 copyfile(self.imageFile, path)
584 def progressbar(self, maxi) :
585 if 'parent' in dir(self) :
589 return wx.ProgressDialog("Traitements",
590 "Veuillez patienter...",
593 style=wx.PD_APP_MODAL | wx.PD_AUTO_HIDE | wx.PD_ELAPSED_TIME | wx.PD_CAN_ABORT
597 def treat_var_mod(variables) :
599 for variable in variables :
600 if u'_' in variable :
601 forme = variable.split(u'_')
604 if not var in var_mod :
605 var_mod[var] = [variable]
607 if not mod in var_mod[var] :
608 var_mod[var].append(variable)