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
24 #from dialog import BugDialog
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 = {}
46 d = shelve.open(self.filein)
47 self.history = d.get('history', [])
48 self.matrix = d.get('matrix', [])
49 self.ordercorpus = dict([[corpus['uuid'], i] for i, corpus in enumerate(self.history)])
50 self.corpus = dict([[corpus['uuid'], corpus] for corpus in self.history])
51 self.analyses = dict([[analyse['uuid'], analyse] for corpus in self.history for analyse in corpus.get('analyses', [])])
52 self.matrixanalyse = dict([[mat['uuid'], mat] for mat in self.matrix])
56 d = shelve.open(self.filein)
57 d['history'] = self.history
58 d['matrix'] = self.matrix
61 def add(self, analyse) :
62 log.info('add to history %s' % analyse.get('corpus_name', 'pas un corpus'))
63 tosave = {'uuid' : analyse['uuid'], 'ira': analyse['ira'], 'type' : analyse['type']}
64 if analyse.get('corpus', False) :
65 if analyse['uuid'] in self.analyses :
67 tosave['corpus'] = analyse['corpus']
68 tosave['name'] = analyse['name']
69 acorpus_uuid = analyse['corpus']
70 if acorpus_uuid in self.corpus :
71 if 'analyses' in self.history[self.ordercorpus[acorpus_uuid]] :
72 self.history[self.ordercorpus[acorpus_uuid]]['analyses'].append(tosave)
74 self.history[self.ordercorpus[acorpus_uuid]]['analyses'] = [tosave]
76 self.orph.append(tosave)
78 tosave['corpus_name'] = analyse['corpus_name']
79 self.history.append(tosave)
83 def addMatrix(self, analyse) :
84 tosave = {'uuid' : analyse['uuid'], 'ira': analyse['ira'], 'type' : analyse['type']}
85 tosave['name'] = analyse['name']
86 self.matrix.append(tosave)
90 def addmultiple(self, analyses) :
91 for analyse in analyses :
92 tosave = {'uuid' : analyse['uuid'], 'ira': analyse['ira'], 'type' : analyse['type']}
93 corpus = analyse['uuid']
94 tosave['corpus'] = corpus
95 tosave['name'] = analyse['name']
96 if corpus in self.corpus :
97 if 'analyses' in self.history[self.ordercorpus[corpus]] :
98 self.history[self.ordercorpus[corpus]]['analyses'].append(tosave)
100 self.history[self.ordercorpus[corpus]]['analyses'] = [tosave]
104 def delete(self, analyse, corpus = False) :
106 self.history.pop(self.ordercorpus[analyse['uuid']])
107 if analyse['uuid'] in self.openedcorpus :
108 del self.openedcorpus[analyse['uuid']]
109 elif analyse['uuid'] in self.analyses :
110 todel = [i for i, ana in enumerate(self.corpus[analyse['corpus']]['analyses']) if ana['uuid'] == analyse['uuid']][0]
111 self.history[self.ordercorpus[analyse['corpus']]]['analyses'].pop(todel)
112 elif analyse['uuid'] in self.matrixanalyse :
113 self.matrix = [mat for mat in self.matrix if mat['uuid'] != analyse['uuid']]
117 def addtab(self, analyse) :
118 self.opened[analyse['uuid']] = analyse
120 def rmtab(self, analyse) :
121 del self.opened[analyse['uuid']]
124 return str(self.history)
127 def __init__(self, configfile=None, diff = None, parametres = None) :
128 self.configfile = configfile
129 self.conf = ConfigParser()
130 if configfile is not None :
131 self.conf.readfp(codecs.open(configfile, 'r', 'utf8'))
133 if parametres is not None :
134 self.doparametres(parametres)
136 def doparametres(self, parametres) :
139 def getsections(self) :
140 return self.conf.sections()
142 def getoptions(self, section = None, diff = None):
145 section = self.conf.sections()[0]
146 for option in self.conf.options(section) :
147 if self.conf.get(section, option).isdigit() :
148 parametres[option] = int(self.conf.get(section, option))
149 elif self.conf.get(section, option) == 'False' :
150 parametres[option] = False
151 elif self.conf.get(section, option) == 'True' :
152 parametres[option] = True
153 elif self.conf.get(section, option).startswith('(') and self.conf.get(section, option).endswith(')') :
154 parametres[option] = ast.literal_eval(self.conf.get(section, option))
155 elif self.conf.get(section, option).startswith('[') and self.conf.get(section, option).endswith(']') :
156 parametres[option] = ast.literal_eval(self.conf.get(section, option))
158 parametres[option] = self.conf.get(section, option)
159 if 'type' not in parametres :
160 parametres['type'] = section
163 def makeoptions(self, sections, parametres, outfile = None) :
165 for i, section in enumerate(sections) :
166 txt += '[%s]\n' % section
167 if not self.conf.has_section(section) :
168 self.conf.add_section(section)
169 for option in parametres[i] :
170 if isinstance(parametres[i][option], int) :
171 self.conf.set(section, option, `parametres[i][option]`)
172 txt += '%s = %i\n' % (option, parametres[i][option])
173 elif isinstance(parametres[i][option], basestring) :
174 self.conf.set(section, option, parametres[i][option].encode('utf8'))
175 txt += '%s = %s\n' % (option, parametres[i][option])
176 elif isinstance(parametres[i][option], wx.Colour) :
177 self.conf.set(section, option, str(parametres[i][option]))
178 txt += '%s = %s\n' % (option, str(parametres[i][option]))
179 elif option == 'analyses' :
182 self.conf.set(section, option, `parametres[i][option]`)
183 txt += '%s = %s\n' % (option, `parametres[i][option]`)
185 outfile = self.configfile
186 with codecs.open(outfile, 'w', 'utf8') as f :
190 def totext(self, parametres) :
193 for val in parametres :
194 if isinstance(parametres[val], int) :
195 txt.append(' \t\t: '.join([val, `parametres[val]`]))
196 elif isinstance(parametres[val], basestring) :
197 txt.append(' \t\t: '.join([val, parametres[val]]))
198 elif val in ['listet', 'stars'] :
201 txt.append(' \t\t: '.join([val, `parametres[val]`]))
202 return '\n'.join(txt)
205 def write_tab(tab, fileout) :
206 writer = csv.writer(open(fileout, 'wb'), delimiter=';', quoting = csv.QUOTE_NONNUMERIC)
207 writer.writerows(tab)
209 class BugDialog(wx.Dialog):
210 def __init__(self, *args, **kwds):
211 # begin wxGlade: MyDialog.__init__
212 kwds["style"] = wx.DEFAULT_DIALOG_STYLE
213 kwds["size"] = wx.Size(500, 200)
214 wx.Dialog.__init__(self, *args, **kwds)
215 self.text_ctrl_1 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE)
216 self.button_1 = wx.Button(self, wx.ID_OK, "")
218 self.__set_properties()
222 def __set_properties(self):
223 # begin wxGlade: MyDialog.__set_properties
225 self.SetMinSize(wx.Size(500, 200))
226 self.text_ctrl_1.SetMinSize(wx.Size(500, 200))
230 def __do_layout(self):
231 # begin wxGlade: MyDialog.__do_layout
232 sizer_1 = wx.BoxSizer(wx.VERTICAL)
233 sizer_1.Add(self.text_ctrl_1, 1, wx.EXPAND, 0)
234 sizer_1.Add(self.button_1, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
235 self.SetSizer(sizer_1)
240 def CreateIraFile(DictPathOut, clusternb, corpname='corpus_name', section = 'analyse'):
241 AnalyseConf = ConfigParser()
242 AnalyseConf.read(DictPathOut['ira'])
243 AnalyseConf.add_section(section)
244 date = datetime.datetime.now().ctime()
245 AnalyseConf.set(section, 'date', str(date))
246 AnalyseConf.set(section, 'clusternb', clusternb)
247 AnalyseConf.set(section, 'corpus_name', corpname)
249 fileout = open(DictPathOut['ira'], 'w')
250 AnalyseConf.write(fileout)
253 def sortedby(list, direct, *indices):
256 sortedby: sort a list of lists (e.g. a table) by one or more indices
257 (columns of the table) and return the sorted list
260 for list = [[2,3],[1,2],[3,1]]:
261 sortedby(list,1) will return [[3, 1], [1, 2], [2, 3]],
262 sortedby(list,0) will return [[1, 2], [2, 3], [3, 1]]
265 nlist = map(lambda x, indices=indices:
266 map(lambda i, x=x: x[i], indices) + [x],
271 nlist.sort(reverse=True)
272 return map(lambda l: l[-1], nlist)
274 def add_type(line, dictlem):
275 if line[4] in dictlem:
276 line.append(dictlem[line[4]])
281 def treat_line_alceste(i, line) :
282 if line[0] == '*' or line[0] == '*****' :
287 elif float(line[5].replace(',', '.')) < 0.0001:
289 elif float(line[5].replace(',', '.')) > 0.05:
290 line[5] = 'NS (%s)' % str(float(line[5].replace(',', '.')))[0:7]
292 line[5] = str(float(line[5].replace(',', '.')))[0:7]
293 return [i, int(line[0]), int(line[1]), float(line[2]), float(line[3]), line[6], line[4], line[5]]
295 def ReadProfileAsDico(File, Alceste=False, encoding = sys.getdefaultencoding()):
296 #print 'lecture des profils : ReadProfileAsDico'
298 # print 'lecture du dictionnaire de type'
300 # for line in parent.corpus.lem_type_list :
301 # dictlem[line[0]] = line[1]
303 print 'lecture des profiles'
304 #encoding = sys.getdefaultencoding()
305 FileReader = codecs.open(File, 'r', encoding)
306 Filecontent = FileReader.readlines()
310 rows = [row.replace('\n', '').replace("'", '').replace('\"', '').replace(',', '.').replace('\r','').split(';') for row in Filecontent]
312 ClusterNb = rows[0][2]
314 clusters = [row[2] for row in rows if row[0] == u'**']
315 valclusters = [row[1:4] for row in rows if row[0] == u'****']
316 lp = [i for i, line in enumerate(rows) if line[0] == u'****']
317 prof = [rows[lp[i] + 1:lp[i+1] - 1] for i in range(0, len(lp)-1)] + [rows[lp[-1] + 1:len(rows)]]
319 prof = [[add_type(row, dictlem) for row in pr] for pr in prof]
320 prof = [[treat_line_alceste(i,line) for i, line in enumerate(pr)] for pr in prof]
322 prof = [[line + [''] for line in pr] for pr in prof]
323 prof = [[treat_line_alceste(i,line) for i, line in enumerate(pr)] for pr in prof]
324 for i, cluster in enumerate(clusters):
325 DictProfile[cluster] = [valclusters[i]] + prof[i]
328 def GetTxtProfile(dictprofile, cluster_size) :
330 for classe in range(0, len(dictprofile)) :
331 prof = dictprofile[str(classe + 1)]
332 clinfo = cluster_size[classe]
333 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])]))
334 return '\n\n'.join(proflist)
336 def formatExceptionInfo(maxTBlevel=5):
337 cla, exc, trbk = sys.exc_info()
338 excName = cla.__name__
340 excArgs = exc.args[0]
342 excArgs = "<no args>"
343 excTb = traceback.format_tb(trbk, maxTBlevel)
344 return (excName, excArgs, excTb)
347 #fonction des etudiants de l'iut
348 def decoupercharact(chaine, longueur, longueurOptimale, separateurs = None) :
350 on part du dernier caractère, et on recule jusqu'au début de la chaîne.
351 Si on trouve un '$', c'est fini.
352 Sinon, on cherche le meilleur candidat. C'est-Ă -dire le rapport poids/distance le plus important.
354 separateurs = [[u'.', 60.0], [u'?', 60.0], [u'!', 60.0], [u'ÂŁ$ÂŁ', 60], [u':', 50.0], [u';', 40.0], [u',', 10.0], [u' ', 0.1]]
355 trouve = False # si on a trouvé un bon séparateur
356 iDecoupe = 0 # indice du caractere ou il faut decouper
358 # on découpe la chaine pour avoir au maximum 240 caractères
359 longueur = min(longueur, len(chaine) - 1)
360 chaineTravail = chaine[:longueur + 1]
362 meilleur = ['', 0, 0] # type, poids et position du meilleur separateur
364 # on vérifie si on ne trouve pas un '$'
365 indice = chaineTravail.find(u'$')
370 # si on ne trouve rien, on cherche le meilleur séparateur
373 caractere = chaineTravail[nbCar]
374 distance = abs(longueurOptimale - nbCar) + 1
375 meilleureDistance = abs(longueurOptimale - meilleur[2]) + 1
377 # on vérifie si le caractére courant est une marque de ponctuation
378 for s in separateurs:
379 if caractere == s[0]:
380 # si c'est une ponctuation
382 if s[1] / distance > float(meilleur[1]) / meilleureDistance:
390 # et on termine la recherche
393 # on passe au caractère précédant
398 fin = chaine[iDecoupe + 1:]
399 retour = chaineTravail[:iDecoupe]
400 return len(retour) > 0, retour.split(), fin
401 # si on a rien trouvé
402 return False, chaine.split(), ''
404 def BugReport(parent, error = None):
405 for ch in parent.GetChildren():
406 if "<class 'wx._windows.ProgressDialog'>" == str(type(ch)):
408 excName, exc, excTb = formatExceptionInfo()
409 if excName == 'Exception' :
412 txt = u' !== BUG ==! \n'
413 txt += u'*************************************\n'
414 txt += '\n'.join(excTb).replace(' ', ' ')
415 txt += excName + '\n'
418 dial = BugDialog(parent)
419 if 'Rerror' in dir(parent) :
423 dial.text_ctrl_1.write(txt)
424 dial.CenterOnParent()
428 def PlaySound(parent):
429 if parent.pref.getboolean('iramuteq', 'sound') :
431 if "gtk2" in wx.PlatformInfo:
432 error = Popen(['aplay','-q',os.path.join(parent.AppliPath,'son_fin.wav')])
434 sound = wx.Sound(os.path.join(parent.AppliPath, 'son_fin.wav'))
435 sound.Play(wx.SOUND_SYNC)
439 def ReadDicoAsDico(dicopath):
440 with codecs.open(dicopath, 'r', 'UTF8') as f:
441 content = f.readlines()
443 for line in content :
445 line = line.replace(u'\n', '').replace('"', '').split('\t')
446 dico[line[0]] = line[1:]
449 def ReadLexique(parent, lang = 'french', filein = None):
452 parent.lexique = ReadDicoAsDico(parent.DictPath.get(lang, 'french'))
454 parent.lexique = ReadDicoAsDico(filein)
458 def ReadList(filein, encoding = sys.getdefaultencoding()):
460 file = codecs.open(filein, 'r', encoding)
461 content = file.readlines()
463 first = content.pop(0)
464 first = first.replace('\n', '').replace('\r','').replace('\"', '').split(';')
468 line = line.replace('\n', '').replace('\r','').replace('\"', '').replace(',', '.')
469 line = line.split(';')
478 don = float('%.5f' % float(val))
484 def exec_RCMD(rpath, command) :
485 log.info('R CMD INSTALL %s' % command)
486 rpath = rpath.replace('\\','\\\\')
487 error = call(["%s" % rpath, 'CMD', 'INSTALL', "%s" % command])
490 def exec_rcode(rpath, rcode, wait = True, graph = False):
491 log.info("R Script : %s" % rcode)
493 if sys.platform == 'darwin' :
495 macversion = platform.mac_ver()[0].split('.')
497 if int(macversion[1]) < 5 :
504 rpath = rpath.replace('\\','\\\\')
507 if sys.platform == 'win32':
508 error = call(["%s" % rpath, "--vanilla","--slave","-f", "%s" % rcode])
510 error = call([rpath, '--vanilla','--slave',"-f %s" % rcode])
513 if sys.platform == 'win32':
514 pid = Popen(["%s" % rpath, '--vanilla','--slave','-f', "%s" % rcode])
516 pid = Popen([rpath, '--vanilla','--slave',"-f %s" % rcode], stderr = PIPE)
520 if sys.platform == 'win32':
521 error = call(["%s" % rpath, '--vanilla','--slave','-f', "%s" % rcode])
522 elif sys.platform == 'darwin' and needX11:
523 os.environ['DISPLAY'] = ':0.0'
524 error = call([rpath, '--vanilla','--slave',"-f %s" % rcode])
526 error = call([rpath, '--vanilla','--slave',"-f %s" % rcode])
529 if sys.platform == 'win32':
530 pid = Popen(["%s" % rpath, '--vanilla','--slave','-f', "%s" % rcode])
531 elif sys.platform == 'darwin' and needX11:
532 os.environ['DISPLAY'] = ':0.0'
533 pid = Popen([rpath, '--vanilla','--slave',"-f %s" % rcode], stderr = PIPE)
535 pid = Popen([rpath, '--vanilla','--slave',"-f %s" % rcode], stderr = PIPE)
538 def check_Rresult(parent, pid) :
539 if isinstance(pid, Popen) :
540 if pid.returncode != 0 :
541 error = pid.communicate()
543 error = [str(error[0]), error[1]]
544 if error[1] is None :
546 parent.Rerror = '\n'.join([str(pid.returncode), '\n'.join(error)])
548 raise Exception('\n'.join([u'Erreur R', '\n'.join(error[1:])]))
557 raise Exception(u'Erreur R')
564 def print_liste(filename,liste):
565 with open(filename,'w') as f :
567 f.write(';'.join(graph)+'\n')
569 def read_list_file(filename, encoding = sys.getdefaultencoding()):
570 with codecs.open(filename,'rU', encoding) as f :
571 content=f.readlines()
572 ncontent=[line.replace('\n','').split(';') for line in content if line.strip() != '']
575 class MessageImage(wx.Frame):
576 def __init__(self, parent,title, size):
577 wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = title, pos = wx.DefaultPosition, size = size, style = wx.DEFAULT_FRAME_STYLE )
578 self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
579 self.imageFile = False
580 self.imagename = u"chi_classe.png"
581 self.HtmlPage = wx.html.HtmlWindow(self, -1)
582 self.HtmlPage.SetMinSize(size)
583 if "gtk2" in wx.PlatformInfo:
584 self.HtmlPage.SetStandardFonts()
585 self.HtmlPage.SetFonts('Courier', 'Courier')
587 self.button_1 = wx.Button(self, wx.ID_CANCEL)
588 self.button_2 = wx.Button(self, wx.ID_SAVE)
589 self.Bind(wx.EVT_BUTTON, self.OnCloseMe, self.button_1)
590 self.Bind(wx.EVT_BUTTON, self.OnSaveImage, self.button_2)
594 self.sizer_1 = wx.BoxSizer(wx.VERTICAL)
595 self.sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
596 self.sizer_1.Add(self.HtmlPage, 2, wx.EXPAND, 0)
598 self.m_sdbSizer1 = wx.StdDialogButtonSizer()
599 self.m_sdbSizer1.AddButton( self.button_2 )
600 self.m_sdbSizer1.AddButton( self.button_1 )
601 self.m_sdbSizer1.Realize()
602 self.sizer_1.Add(self.m_sdbSizer1, 0, wx.EXPAND, 5)
603 self.SetSizer(self.sizer_1)
605 self.sizer_1.Fit( self )
607 def addsaveimage(self, imageFile) :
608 self.imageFile = imageFile
610 def OnCloseMe(self, event):
613 def OnSaveImage(self, event) :
615 self, message="Enregistrer sous...", defaultDir=os.getcwd(),
616 defaultFile= self.imagename, wildcard="png|*.png", style=wx.SAVE | wx.OVERWRITE_PROMPT
618 dlg.SetFilterIndex(2)
620 if dlg.ShowModal() == wx.ID_OK:
622 copyfile(self.imageFile, path)
625 def progressbar(self, maxi) :
626 if 'parent' in dir(self) :
630 return wx.ProgressDialog("Traitements",
631 "Veuillez patienter...",
634 style=wx.PD_APP_MODAL | wx.PD_AUTO_HIDE | wx.PD_ELAPSED_TIME | wx.PD_CAN_ABORT
638 def treat_var_mod(variables) :
640 for variable in variables :
641 if u'_' in variable :
642 forme = variable.split(u'_')
645 if not var in var_mod :
646 var_mod[var] = [variable]
648 if not mod in var_mod[var] :
649 var_mod[var].append(variable)