def main(): #SETTINGS best_n_words = 10000 logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) settings = Settings.Settings() results_dir = settings.results_directory + GwData.FOLDER #TOKENIZE data = GwData.GwData() tokenized_docs = WordTokenizer.tokenize(data.documents, min_word_count = 5) term_freq = TermFrequency.TermFrequency(tokenized_docs) #NLTK Decision Tree list_of_dicts = Converter.vector_space_to_dict_list(term_freq.matrix, term_freq.id2Word, Converter.to_binary) labels = data.causal_per_document causal_count = sum(labels) relative_word_frequency = DocumentFrequency.document_frequency_ratio(list_of_dicts, labels, lambda l: l == 1) condensed_data = extract_best_n_words(relative_word_frequency, best_n_words, list_of_dicts) labelled_data = zip(condensed_data, labels) td_size = int(0.75 * len(labelled_data)) training_data = labelled_data[:td_size] validation_data = labelled_data[td_size:] dt = nltk.DecisionTreeClassifier.train(training_data) #RESULTS classifications = [dt.classify(rcd) for rcd,lbl in validation_data] results = ResultsHelper.rfp(labels[td_size:], classifications) results += "Num Words Used : " + str(best_n_words) + "\n" results += "\n" error = dt.error(labelled_data) results += "ERROR: : " + str(error * 100) + "%\n" results += "\n" results += "PSEUDOCODE:\n" results += dt.pseudocode(depth = 1000) + "\n" print results #DUMP TO FILE fName = results_dir + "Causal_Relation_DT.txt" handle = open(fName, mode = "w+") handle.write(results) handle.close() #binary_matrix = term_freq.binary_matrix() #decision_tree = tree.DecisionTreeClassifier(criterion = 'entropy') #decision_tree.fit(binary_matrix, labels) # Test with CL1 labels raw_input("Press Enter to quit")
def convert(self, latex_input): logging.debug(latex_input) latex_input = self.handle_custom_commands(latex_input) logging.debug(latex_input) mathml_string = l2m.latex_to_mathml(latex_input, name_space = True) print(mathml_string) #mathml_string = etree.tostring(mathml_tree) logging.debug(mathml_string) mathml_tree = etree.fromstring(mathml_string) omml_tree = self.transform(mathml_tree) print(self.transform.error_log) return omml_tree.getroot()
def on_Convert(self, *args): #Apre la finestra di dialogo con le impostazioni dlgCon = ConverterDialog(self.mainWindow, self.prefs) dlgCon.show() if not dlgCon.response == gtk.RESPONSE_OK: return sorgente = "file" #Carica la lista dei file selezionati if not bool(int(self.prefs.get_option("save-all-tracks"))): # Solo i file selezionati self.selconv = self.Selection(self.FileTable) else: # Tutti i file self.FileTable.tvSelection.select_all() self.selconv = self.Selection(self.FileTable) self.FileTable.tvSelection.unselect_all() if self.selconv: # Inizializza la coda request_queue = Queue.Queue() n = 0 for sel in self.selconv: n += 1 af = sel[0] it = sel[1] # Status bar if af.get_tag("title") != "Unknown title" and af.get_tag("artist") != "Unknown artist": self.msg = af.get_tag("artist") + " - " + af.get_tag("title") elif af.get_uri(): self.msg = af.get_filepath() self.set_status("Converting " + self.msg + " (file " + str(n) + "/" + str(len(self.selconv)) + ")") # Riempie la coda caricando le preferenze request_queue.put([n, sel]) self.init = time.time() self.progConvert.show() # Riempita la coda, lancia il thread dell'encoder self.encoder_thread = Converter(self, self.prefs, sorgente, request_queue) self.encoder_thread.start() # Svuota la coda per fermare il thread for sel in self.selconv: request_queue.put(None) self.FileTable.tvSelection.unselect_all()
def download(self): print "Start downloading " + self.url #download youtube info if self.get_youtube_info()==False: return False signature = self.download_stream_info["sig"] url = self.download_stream_info["url"] download_url = "%s&signature=%s" % (url, signature) if self.output_file_name=="FF": dmn = Download( download_url, self.title) self.output_file_name = self.title else: dmn = Download( download_url, self.output_file_name) dmn.download() print "\nConverting:\n" ofile = "result_"+self.output_file_name+"."+self.ofe print ofile con = Converter( self.output_file_name, ofile) con.ffmpeg_converter(self.audio_codec,self.video_codec) return True
def main(): #SETTINGS logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) settings = Settings.Settings() results_dir = settings.results_directory + GwData.FOLDER #TOKENIZE data = GwData.GwData() tokenized_docs = WordTokenizer.tokenize(data.documents, min_word_count = 5) term_freq = TermFrequency.TermFrequency(tokenized_docs) #tfidf = TfIdf.TfIdf(tokenized_docs) #NLTK Decision Tree list_of_dicts = Converter.vector_space_to_dict_list(term_freq.distance_matrix, term_freq.id2Word, Converter.to_binary) #list_of_dicts = Converter.vector_space_to_dict_list(tfidf.matrix, tfidf.id2Word) labels = data.causal_per_document labelled_data = zip(list_of_dicts, labels) td_size = int(0.75 * len(labelled_data)) training_data = labelled_data[:td_size] validation_data = labelled_data[td_size:] me = nltk.MaxentClassifier.train(training_data, algorithm = "GIS") #RESULTS classifications = [me.classify(rcd) for rcd,lbl in validation_data] results = ResultsHelper.rfp(labels[td_size:], classifications) print results #print "EXPLAIN:\n" #me.explain(condensed_data[0], 100) #DUMP TO FILE fName = results_dir + "Causal_Relation_MaxEnt.txt" handle = open(fName, mode = "w+") handle.write(results) handle.close() #binary_matrix = term_freq.binary_matrix() #decision_tree = tree.DecisionTreeClassifier(criterion = 'entropy') #decision_tree.fit(binary_matrix, labels) # Test with CL1 labels raw_input("Press Enter to quit")
def appendStats(raw_output, clf, score, k, timeFit, timePredict): _timeFitLin = clf.time_fit_lin # SS_MSMS _timeFitGauss = clf.time_fit_gauss # MM:SS _timeFitOver = clf.time_overhead # MSMS # _timeTotal = _timeFitLin + _timeFitGauss + _timeFitOver _timeTotal = timeFit _score = score _error = round((1 - _score) * 100, 2) _timePredict = timePredict ## SS_MSMS gauss_stat = str(clf.n_gauss) + " (" + str( round((float(clf.n_gauss) / float(clf.n_gauss + clf.n_lin) * 100), 2)) + "%);" lin_stat = str(clf.n_lin) + " \t(" + str( round((float(clf.n_lin) / float(clf.n_gauss + clf.n_lin) * 100), 2)) + "%);" lin_c = Converter.toPowerOfTen(clf.lin_svc.C) + ";" gauss_c = Converter.toPowerOfTen(clf.gauss_svc.C) + ";" gauss_gamma = Converter.toPowerOfTen(clf.gauss_svc.gamma) + ";" try: n_gaussSVs = str(clf.gauss_svc.n_support_[0] + clf.gauss_svc.n_support_[1]) + ";" except AttributeError: n_gaussSVs = "0;" # Bring Time data in readable format # _timeFit = Conversions.secondsToHourMin(_timeTotal) _timeFitLin = Converter.secondsToSecMilsec(_timeFitLin) _timeFitGauss = Converter.secondsToMinSec(_timeFitGauss) _timeFitOver = Converter.secondsToMilsec(_timeFitOver) _timePredict = Converter.secondsToSecMilsec(_timePredict) raw_output[0].append(gauss_stat) raw_output[1].append(lin_stat) raw_output[2].append(lin_c) raw_output[3].append(gauss_c) raw_output[4].append(gauss_gamma) raw_output[5].append(n_gaussSVs) raw_output[6].append(str(_timeTotal).replace(".", ",") + "s;") raw_output[7].append(_timeFitGauss + ";") raw_output[8].append(_timeFitLin + ";") raw_output[9].append(_timeFitOver + ";") raw_output[10].append(_timePredict + ";") raw_output[11].append(str(_error) + "%;") raw_output[12].append(str(k) + ";") return raw_output
def main(): playlist = Playlist("/home/klaxa/Music/test.m3u") converter = Converter() converter.encode(playlist.tracks[0]) converter.encode(playlist.tracks[0])
class classXAudioCopy: # Costruttore della classe classXAudioCopy def __init__(self): # Collega il file XML self.builderXAC = Gtk.Builder() self.builderXAC.add_from_file(GLADE) # Collega i segnali self.builderXAC.connect_signals(self) # Carica la finestra principale "mainWindow" self.mainWindow = self.builderXAC.get_object("mainWindow") self.mainWindow.set_title(WINDOW_TITLE) self.mainWindow.connect("destroy", lambda on_quit: Gtk.main_quit()) # Carica la statusbar self.status = self.builderXAC.get_object("statusbar") # Collega il menu contestuale self.popupmenu = self.builderXAC.get_object("popupmenu") # Carica la tabella per la lista dei file (TreeView) self.FileTable = FileTable(self.builderXAC) # Visualizza la finestra principale mainWindow self.mainWindow.show() self.set_status() # Toglie il focus al pulsante cmdOpenFile (TODO: scoprire perché ce l'ha) self.mainWindow.set_focus(None) # Carica la barra con i tag e la nasconde all'avvio self.TagBar = TagBar(self.builderXAC) self.TagBar.hide() # Aggancia alcuni pulsanti e menu (per renderli sensibili o insensibili) self.cmdCD = self.builderXAC.get_object("cmdCD") self.menuCD = self.builderXAC.get_object("menuCD") self.cmdOpenFile = self.builderXAC.get_object("cmdOpenFile") self.menuOpenFile = self.builderXAC.get_object("menuOpenFile") self.cmdOpenFolder = self.builderXAC.get_object("cmdOpenFolder") self.menuOpenFolder = self.builderXAC.get_object("menuOpenFolder") self.cmdPlay = self.builderXAC.get_object("cmdPlay") self.menuPlay = self.builderXAC.get_object("menuPlay") self.menuPause = self.builderXAC.get_object("menuPause") self.popPlay = self.builderXAC.get_object("popPlay") self.popPause = self.builderXAC.get_object("popPause") self.cmdStop = self.builderXAC.get_object("cmdStop") self.menuStop = self.builderXAC.get_object("menuStop") self.popStop = self.builderXAC.get_object("popStop") self.cmdNext = self.builderXAC.get_object("cmdNext") self.menuNext = self.builderXAC.get_object("menuNext") self.cmdPrev = self.builderXAC.get_object("cmdPrev") self.menuPrev = self.builderXAC.get_object("menuPrev") self.cmdRewind = self.builderXAC.get_object("cmdRewind") self.cmdForward = self.builderXAC.get_object("cmdForward") self.labelTime = self.builderXAC.get_object("labelTime") self.scaleTime = self.builderXAC.get_object("scaleTime") self.volumebutton = self.builderXAC.get_object("volumebutton") self.volumebutton.set_value(0.5) self.cmdRemove = self.builderXAC.get_object("cmdRemove") self.menuRemove = self.builderXAC.get_object("menuRemove") self.cmdPurge = self.builderXAC.get_object("cmdPurge") self.menuPurge = self.builderXAC.get_object("menuPurge") self.menuSelectAll = self.builderXAC.get_object("menuSelectAll") self.menuUnselectAll = self.builderXAC.get_object("menuUnselectAll") self.cmdRip = self.builderXAC.get_object("cmdRip") self.menuRip = self.builderXAC.get_object("menuRip") self.cmdConvert = self.builderXAC.get_object("cmdConvert") self.menuConvert = self.builderXAC.get_object("menuConvert") self.menuProperty = self.builderXAC.get_object("menuProperty") self.menuModify = self.builderXAC.get_object("menuModify") self.menuPlaylist = self.builderXAC.get_object("menuPlaylist") self.popProperty = self.builderXAC.get_object("popProperty") self.popTagger = self.builderXAC.get_object("popTagger") # Rende insensibili alcuni menu e pulsanti all'avvio self.set_sensitive(False) self.cmdRip.set_sensitive(False) self.cmdConvert.set_sensitive(False) # Carica la progressbar per la conversione e la nasconde all'avvio self.progConvert = self.builderXAC.get_object("progressbar") self.progConvert.hide() # Crea l'oggetto lista dei file self.audioFileList = FileList() # Istanza del player audio self.player = Player(None, self) self.player.set_volume(self.volumebutton.get_value()) self.player_bus = self.player.bus self.player_bus.connect("message::eos", self.on_endPlay) self.player_bus.connect("message::error", self.on_endError) # Carica le preferenze self.prefs = Preferences() # Funzione che attiva la finestra principale def main(self): Gtk.main() # Funzione che modifica la barra di stato def set_status(self, text=None): self.status.show() con_id = self.status.get_context_id("SB") if not text: text = "Ready" self.mainWindow.set_title(WINDOW_TITLE) self.status.push(con_id, text) #print text while Gtk.events_pending(): Gtk.main_iteration() # Funzione che rende sensibili/insensibili alcuni menu e pulsanti def set_sensitive(self, sensitive): cmd = [ self.cmdPlay, self.menuPlay, self.popPlay, self.menuPause, self.popPause, self.cmdNext, self.menuNext, self.cmdPrev, self.menuPrev, self.cmdRemove, self.menuRemove, self.cmdPurge, self.menuPurge, self.cmdRewind, self.cmdForward, self.cmdConvert, self.menuConvert, self.menuSelectAll, self.menuUnselectAll, self.menuProperty, self.menuModify, self.popProperty, self.popTagger, self.menuPlaylist, self.TagBar ] if sensitive: for c in cmd: c.set_sensitive(True) elif not sensitive: for c in cmd: c.set_sensitive(False) self.menuRip.set_sensitive(False) self.cmdRip.set_sensitive(False) self.cmdStop.set_sensitive(False) self.menuStop.set_sensitive(False) self.popStop.set_sensitive(False) self.scaleTime.set_sensitive(False) # Evento per l'uscita dal programma def on_Quit(self, *args): print "Bye..." Gtk.main_quit() # Evento per l"apertura di un file def on_OpenFile(self, *args): self.set_status("Adding files...") # Oggetto di classe FileChooser (False se apre un file) FC = FileChooser(False) self.AddFileList(FC) try: self.player.stop() except: pass self.cmdPlay.set_stock_id("gtk-media-play") # Evento per l"apertura di una cartella def on_OpenFolder(self, *args): self.set_status("Adding forder...") # Oggetto di classe FileChooser (True se apre una cartella) FC = FileChooser(True) self.AddFileList(FC) try: self.player.stop() except: pass self.cmdPlay.set_stock_id("gtk-media-play") # Evento che apre la finetra informazioni def on_About(self, *args): # Oggetto di classe AboutDialog self.About = AboutDialog() # Evento che rimuove gli elementi della tabella slezionati def on_Remove(self, *args): self.FileTable.remove() self.on_Stop() self.cmdPlay.set_stock_id("gtk-media-play") self.mainWindow.set_title(WINDOW_TITLE) if len(self.audioFileList.filelist) == 0: self.set_sensitive(False) self.cmdConvert.set_sensitive(False) self.cmdStop.set_sensitive(False) self.menuStop.set_sensitive(False) else: self.set_sensitive(True) self.cmdConvert.set_sensitive(True) # Evento che pulisce la tabella def on_Purge(self, *args): self.set_status("Purge list...") self.FileTable.purge() self.audioFileList.purge() self.TagBar.purge() self.TagBar.hide() self.cmdOpenFile.set_sensitive(True) self.cmdOpenFolder.set_sensitive(True) self.set_status() self.on_Stop() self.cmdPlay.set_stock_id("gtk-media-play") self.mainWindow.set_title(WINDOW_TITLE) self.set_sensitive(False) self.cmdConvert.set_sensitive(False) self.cmdRip.set_sensitive(False) self.progConvert.hide() # Evento che apre la finestra preferenze def on_Preferences(self, *args): dlgPrefs = PreferencesDialog(self.mainWindow, self.prefs) dlgPrefs.show() # Evento per la riproduzione di un file def on_Play(self, *args): print self.cmdPlay.get_stock_id() self.cmdStop.set_sensitive(True) self.menuStop.set_sensitive(True) self.popStop.set_sensitive(True) self.scaleTime.set_sensitive(True) # Se il pulsante indica "play", riproduce la selezione if self.cmdPlay.get_stock_id() == "gtk-media-play": # Se il player è pronto, inizia la riproduzione if self.player.state == "ready": #Carica la lista dei file selezionati self.selplay = self.Selection(self.FileTable) # Riproduce solo il primo file della lista caricata try: sel = self.selplay[0] except IndexError: sel = None self.playing_song = sel if sel: af = sel[0] it = sel[1] if not self.file_exists(af): return self.FileTable.tvSelection.unselect_all() self.FileTable.tvSelection.select_iter(it) print "Riproduzione di: ", af.get_uri() self.player.play(af) if af.get_tag("title") != "Unknown title" and af.get_tag("artist") != "Unknown artist": msg = af.get_tag("artist") + " - " + af.get_tag("title") elif af.get_uri(): msg = af.get_filepath() self.set_status("Playing " + msg) self.mainWindow.set_title(msg) self.scaleTime.set_range(0, 1) self.scaleTime.set_value(0) # Se è in pausa, riprende la riproduzione elif self.player.state == "paused": self.player.carry_on() if self.player.state == "playing": self.cmdPlay.set_stock_id("gtk-media-pause") # Se il pulsante indica "pause", mette in pausa elif self.cmdPlay.get_stock_id() == "gtk-media-pause": if self.player.state == "playing": self.player.pause() if self.player.state == "paused": self.cmdPlay.set_stock_id("gtk-media-play") # Thread per l'avanzamento del tempo di riproduzione def play_thread(self): # From http://pygstdocs.berlios.de/pygst-tutorial/seeking.html print "PLAY_THREAD" play_thread_id = self.player.play_thread_id print play_thread_id print self.player.play_thread_id Gtk.gdk.threads_enter() self.labelTime.set_text("00:00 / 00:00") Gtk.gdk.threads_leave() while play_thread_id == self.player.play_thread_id: try: time.sleep(0.2) if self.player.duration == -1: continue Gtk.gdk.threads_enter() self.labelTime.set_text("00:00 / " + self.player.duration_str) Gtk.gdk.threads_leave() print "OK 1" break except: print "QUERY_IN_CORSO" pass time.sleep(0.2) while play_thread_id == self.player.play_thread_id: pos_int = self.player.player.query_position(gst.FORMAT_TIME, None)[0] pos_str = self.player.convert_ns(pos_int) if play_thread_id == self.player.play_thread_id: Gtk.gdk.threads_enter() self.labelTime.set_text(pos_str + " / " + self.player.duration_str) self.scaleTime.set_value(float(pos_int)/float(self.player.duration)) Gtk.gdk.threads_leave() time.sleep(0.5) # Evento che avanza la barra del tempo def on_adjust_bounds(self, *args): print "adjust-bound" self.player.change_position(self.scaleTime.get_value()) # Evento per la modifica del volume def volume_changed(self, *args): try: self.player.set_volume(self.volumebutton.get_value()) except: pass # Richiamato quando termina la riproduzione di un brano def on_endPlay(self, player_bus, message): print "Esecuzione terminata" self.set_status() self.mainWindow.set_title(WINDOW_TITLE) self.cmdStop.set_sensitive(False) self.menuStop.set_sensitive(False) self.popStop.set_sensitive(False) self.scaleTime.set_sensitive(False) self.labelTime.set_text("00:00 / 00:00") # Passa al brano successivo try: print "Brano successivo" self.on_Next() except: pass #self.scaleTime.set_value(1) def on_endError(self, player_bus, message): err, debug = message.parse_error() print "Error: %s" % err, debug self.set_status() self.mainWindow.set_title(WINDOW_TITLE) self.cmdStop.set_sensitive(False) self.menuStop.set_sensitive(False) self.popStop.set_sensitive(False) self.scaleTime.set_sensitive(False) self.labelTime.set_text("00:00 / 00:00") #self.scaleTime.set_value(0) # Evento per il menu pausa (serve per distinguere l'azione # da quello del pulsante play/pause) def on_menuPause(self, *args): if self.cmdPlay.get_stock_id() == "gtk-media-pause": self.on_Play() # Evento per il menu play (serve per distinguere l'azione # da quello del pulsante play/pause) def on_menuPlay(self, *args): if self.cmdPlay.get_stock_id() == "gtk-media-play": self.on_Play() else: if self.playing_song == self.Selection(self.FileTable): self.on_Play() self.on_Play() else: self.on_Stop() self.on_Play() # Evento per il doppio click su una riga della tabella # e riproduce la canzone clickata def on_row_activated(self, *args): print "RIGA ATTIVATA" try: self.player.stop() self.cmdPlay.set_stock_id("gtk-media-play") except: pass self.on_Play() # Evento per il click sulla tabella dei file def on_row_clicked(self, widget, event): # Apre il menù contestuale if event.button == 3: print "TASTO DESTRO" if self.Selection(self.FileTable): x = int(event.x) y = int(event.y) time = event.time pthinfo = widget.get_path_at_pos(x, y) if pthinfo is not None: path, col, cellx, celly = pthinfo widget.grab_focus() widget.set_cursor( path, col, 0) self.popupmenu.popup( None, None, None, event.button, time) return True if event.button == 1: print "TASTO SINISTRO" if event.type == Gtk.gdk.BUTTON_PRESS: print "SINGOLO CLICK" elif event.type == Gtk.gdk._2BUTTON_PRESS: print "DOPPIO CLICK" elif event.type == Gtk.gdk._3BUTTON_PRESS: print "TRIPLO CLICK" # Evento per la selezione di una riga della tabella def on_row_selected(self, *args): print "RIGA SELEZIONATA" model, pathlist = self.FileTable.tvSelection.get_selected_rows() if pathlist: rowpath = pathlist[0] it = self.FileTable.listStore.get_iter(rowpath) for af in self.audioFileList.filelist: if str(af.pointer) == model.get_string_from_iter(it): print "SELEZIONATO IL FILE: ", af.get_filepath() # Evento che ferma la riproduzione def on_Stop(self, *args): try: self.player.stop() except: pass self.cmdPlay.set_stock_id("gtk-media-play") self.set_status() self.mainWindow.set_title(WINDOW_TITLE) self.cmdStop.set_sensitive(False) self.menuStop.set_sensitive(False) self.popStop.set_sensitive(False) self.scaleTime.set_value(0) self.scaleTime.set_sensitive(False) self.labelTime.set_text("00:00 / 00:00") # Evento che passa a riprodurre la canzone successiva def on_Next(self, *args): model, pathlist = self.FileTable.tvSelection.get_selected_rows() rowpath = pathlist[0] self.FileTable.tvSelection.unselect_all() self.on_Stop() #self.FileTable.tvSelection.select_path(rowpath) it = self.FileTable.listStore.get_iter(rowpath) root_it = self.FileTable.listStore.get_iter_root() next_it = self.FileTable.listStore.iter_next(it) if next_it: self.FileTable.tvSelection.select_iter(next_it) print "on_Next Successivo" else: try: self.FileTable.tvSelection.select_iter(root_it) print "on_Next Primo della lista" except: pass self.cmdPlay.set_stock_id("gtk-media-play") self.labelTime.set_text("00:00 / 00:00") self.on_Play() # Evento che passa a riprodurre la canzone precedente def on_Prev(self, *args): selection = [] model, pathlist = self.FileTable.tvSelection.get_selected_rows() rowpath = pathlist[0] self.FileTable.tvSelection.unselect_all() self.on_Stop() prev_pointer = 0 prev_it = None curr_it = self.FileTable.listStore.get_iter(rowpath) for af in self.audioFileList.filelist: if str(af.pointer) == model.get_string_from_iter(curr_it): prev_pointer = af.pointer - 1 print "af.pointer: ", af.pointer print "prev_pointer: ", prev_pointer if prev_pointer > -1: self.FileTable.tvSelection.select_all() model, pathlist = self.FileTable.tvSelection.get_selected_rows() if pathlist: iterlist = [] for rowpath in pathlist: try: iterlist.append(model.get_iter(rowpath)) except ValueError: pass for it in iterlist: if str(prev_pointer) == model.get_string_from_iter(it): prev_it = it if prev_it: self.FileTable.tvSelection.unselect_all() self.FileTable.tvSelection.select_iter(prev_it) else: try: self.FileTable.tvSelection.select_iter(self.FileTable.listStore.get_iter_root()) except: pass self.cmdPlay.set_stock_id("gtk-media-play") self.labelTime.set_text("00:00 / 00:00") self.on_Play() # Evento per l'avanzamento veloce def on_Forward(self, *args): self.player.forward() # Evento per il riavvolgimento veloce def on_Rewind(self, *args): self.player.rewind() # Evento che apre un CD_Audio e carica i tag da freeDB # se il server è disponibile def on_CD(self, *args): self.set_status("Adding Audio CD...") self.TagBar.purge() self.CDdata = None try: self.audioCD = CDDBReader() except: self.set_status("Insert an Audio CD into the drive...") self.cmdOpenFile.set_sensitive(True) self.cmdOpenFolder.set_sensitive(True) self.dlg = WarningDialog(self.mainWindow, NAME + " - Warning", "No disc into the drive. Please insert one...") return if self.audioCD.is_audio_cd: self.audioFileList.purge() self.FileTable.purge() self.TagBar.show() self.cmdPlay.set_stock_id("gtk-media-play") self.on_Stop() if self.audioCD.query_status == 409: self.set_status("No connection to the internet is current available or no server response...") self.dlg = WarningDialog(self.mainWindow, NAME + " - Warning","No connection to the internet is current available or no server response...") self.TagBar.entry_tag("Unknow album", "Unknow artist", "Unknow year", "Unknow genre") for i in range(self.audioCD.disc_id[1]): n = "%.02d" %(i + 1) af = AudioFile("cdda://" + n, n) af.set_tag("track_number", n) af.set_tag("title", "Track " + n) #af.frame = self.audioCD.disc_id[i+2] af.set_filename("Track " + n) print af.get_tags_as_dict() self.audioFileList.append(af) self.set_status("Append " + af.get_filename() + "/" + str(self.audioCD.disc_id[1])) else: if type(self.audioCD.query_info).__name__ == "list": print "E'UNA LISTA" cds = [] for cd in self.audioCD.query_info: cds.append([cd["disc_id"], cd["category"], cd["title"]]) self.CDDBSelection = CDDBSelection(self.mainWindow, cds) selected_cd = int(self.CDDBSelection.selected_cd) self.audioCD.get_CDDB_tag(self.audioCD.query_status, self.audioCD.query_info[selected_cd]) else: self.audioCD.get_CDDB_tag(self.audioCD.query_status, self.audioCD.query_info) self.TagBar.entry_tag(self.audioCD.album, self.audioCD.artist, self.audioCD.year, self.audioCD.cddb_genre) self.CDdata = {"album": self.audioCD.album, "artist": self.audioCD.artist, "year": self.audioCD.year, "genre": self.audioCD.cddb_genre } for song in self.audioCD.song_list: af = AudioFile("cdda://" + str("%.02d" %(song["track_number"])), song["track_number"]) af.set_tag("track_number", "%.02d" %(song["track_number"])) af.set_tag("title", song["title"]) af.set_tag("artist", self.audioCD.artist) af.set_tag("album", self.audioCD.album) af.set_tag("year", self.audioCD.year) af.set_tag("genre", self.audioCD.cddb_genre) af.set_filename("Track " + str("%.02d" %(song["track_number"]))) print af.get_tags_as_dict() self.audioFileList.append(af) self.set_status("Append " + af.get_filename() + "/" + str(self.audioCD.disc_id[1])) # Scrive i file nella tabella self.FileTable.append(self.audioFileList) self.set_status() self.audioCD = None self.set_sensitive(True) self.cmdRip.set_sensitive(True) self.cmdOpenFile.set_sensitive(False) self.menuOpenFile.set_sensitive(False) self.cmdOpenFolder.set_sensitive(False) self.menuOpenFolder.set_sensitive(False) self.cmdConvert.set_sensitive(False) self.menuConvert.set_sensitive(False) else: self.audioCD = None return # Evento che cambia i dati del CD su modifica utente def on_entry_changed(self, *args): print "CHANGED" self.CDdata = {"album": self.TagBar.entryAlbum.get_text(), "artist": self.TagBar.entryArtist.get_text(), "year": self.TagBar.entryYear.get_text(), "genre": self.TagBar.entryGenre.get_text() } for af in self.audioFileList.filelist: af.set_tag("album", self.CDdata["album"]) af.set_tag("artist", self.CDdata["artist"]) af.set_tag("year", self.CDdata["year"]) af.set_tag("genre", self.CDdata["genre"]) self.FileTable.purge() self.FileTable.append(self.audioFileList) # Evento che apre la finestra di scelta per il ripping del CD def on_Rip(self, *args): try: from morituri.rip import main as Ripper except: self.dlg = WarningDialog(self.mainWindow, NAME + " - Warning",'''Morituri is not available. Please try 'apt-get install morituri' or visit http://thomas.apestaart.org/morituri/trac/wiki''') return #Apre la finestra di dialogo con le impostazioni dlgRip = RipDialog(self.mainWindow, self.prefs) dlgRip.show() if not dlgRip.response == Gtk.ResponseType.OK: return else: self.set_status("Ripping Audio CD ...") # Posizione temporanea import tempfile tempdir = tempfile.mkdtemp() # Ripping del CD audio in una directory temporanea # Argomenti da passare: # rip_args = ['cd', 'rip', '--output-directory=' + tempdir, '--track-template=%t - %n', '--profile=wav'] # In morituri waveenc non funziona. Bisogna lasciare l'uscita di default in flac rip_args = ['cd', 'rip', '--output-directory=' + tempdir, '--track-template=%t - %n'] try: # Avvia l'estrazione ret = Ripper.main(rip_args) ret = 0 except: self.dlg = WarningDialog(self.mainWindow, NAME + " - Warning", "Task exception. Morituri don't work.") ret = -1 self.set_status() return if ret == 0: self.set_status("Ripping completed...") # Carica i file da convertire walk = os.walk(tempdir) convert_filelist = [] for dirpath, subdir, filenames in walk: for f in filenames: if f[-5:] == ".flac": f = os.path.join(dirpath, f) convert_filelist.append(AudioFile("file://" + f)) #Carica la lista dei file selezionati if not bool(int(self.prefs.get_option("save-all-tracks"))): # Solo i file selezionati self.selconv = self.Selection(self.FileTable) else: # Tutti i file self.FileTable.tvSelection.select_all() self.selconv = self.Selection(self.FileTable) self.FileTable.tvSelection.unselect_all() if self.selconv: temp_format = self.prefs.get_option("output-format") # Inizializza la coda request_queue = Queue.Queue() n = 0 for sel in self.selconv: n += 1 af = sel[0] it = sel[1] for convert_file in convert_filelist: if af.get_tag("track_number") == convert_file.get_filename()[0:2]: convert_file.set_tags_as_dict(af.get_tags_as_dict()) # Salva non compressi if not bool(int(self.prefs.get_option("rip-compressed"))) or self.prefs.get_option("output-format") == "wav": self.prefs.set_option("output-format", "wav") request_queue.put([n, (convert_file, it)]) self.set_status("Now save uncompressed files...") elif bool(int(self.prefs.get_option("rip-compressed"))): request_queue.put([n, (convert_file, it)]) self.set_status("Now save compressed files...") self.init = time.time() self.progConvert.show() # Riempita la coda, lancia il thread dell'encoder self.encoder_thread = Converter(self, self.prefs, request_queue) self.encoder_thread.start() # Svuota la coda per fermare il thread for sel in self.selconv: request_queue.put(None) self.FileTable.tvSelection.unselect_all() self.set_status("Done...") # Evento per la conversione dei file audio def on_Convert(self, *args): #Apre la finestra di dialogo con le impostazioni dlgCon = ConverterDialog(self.mainWindow, self.prefs) dlgCon.show() if not dlgCon.response == Gtk.ResponseType.OK: return #Carica la lista dei file selezionati if not bool(int(self.prefs.get_option("save-all-tracks"))): # Solo i file selezionati self.selconv = self.Selection(self.FileTable) else: # Tutti i file self.FileTable.tvSelection.select_all() self.selconv = self.Selection(self.FileTable) self.FileTable.tvSelection.unselect_all() if self.selconv: # Inizializza la coda request_queue = Queue.Queue() n = 0 for sel in self.selconv: n += 1 af = sel[0] it = sel[1] # Status bar if af.get_tag("title") != "Unknown title" and af.get_tag("artist") != "Unknown artist": self.msg = af.get_tag("artist") + " - " + af.get_tag("title") elif af.get_uri(): self.msg = af.get_filepath() self.set_status("Converting " + self.msg + " (file " + str(n) + "/" + str(len(self.selconv)) + ")") # Riempie la coda caricando le preferenze request_queue.put([n, sel]) self.init = time.time() self.progConvert.show() # Riempita la coda, lancia il thread dell'encoder self.encoder_thread = Converter(self, self.prefs, request_queue) self.encoder_thread.start() # Svuota la coda per fermare il thread for sel in self.selconv: request_queue.put(None) self.FileTable.tvSelection.unselect_all() # Aggiorna la progressbar durante la conversione def on_ProgressBar(self): self.progConvert.set_fraction(self.encoder_thread.amount_completed) if self.encoder_thread.work_complete: self.progConvert.set_fraction(1) if self.encoder_thread.queue_complete: if bool(int(self.prefs.get_option("playlist"))): self.write_playlist(self.encoder_thread.savepath, self.encoder_thread.playlistname, self.encoder_thread.listsongs) self.progConvert.set_text("Complete!") print "Complete!" self.set_status("Done in " + str(round(time.time() - self.init, 2)) + " seconds") self.progConvert.set_fraction(1) else: self.progConvert.set_text("%d%%" % (self.encoder_thread.amount_completed * 100)) self.set_status("Converting " + self.encoder_thread.msg + \ " (file " + str(self.encoder_thread.n) + "/" + str(len(self.selconv)) + ")" + \ " - " + ("%f" % (round(time.time() - self.init, 2)))[:4] + " seconds") return not self.encoder_thread.work_complete # Crea la playlist dei brani convertiti def write_playlist(self, savepath, playlistname, listsongs): playlist = open(savepath + "/" + playlistname + ".m3u", "wb") playlist.writelines(listsongs) playlist.close() # Seleziona tutte le righe def on_SelectAll(self, *args): self.FileTable.tvSelection.select_all() # Deseleziona tutte le righe def on_UnselectAll(self, *args): self.FileTable.tvSelection.unselect_all() # Proprietà della canzone def on_Property(self, *args): #Carica la lista dei file selezionati self.selplay = self.Selection(self.FileTable) # Riproduce solo il primo file della lista caricata try: sel = self.selplay[0] except IndexError: sel = None self.playing_song = sel if sel: af = sel[0] it = sel[1] self.FileTable.tvSelection.unselect_all() self.FileTable.tvSelection.select_iter(it) dlgprop = PropertyDialog(self, self.mainWindow, sel) dlgprop.show() # Modifica i tag def on_Tagger(self, *args): #Carica la lista dei file selezionati self.selplay = self.Selection(self.FileTable) # Riproduce solo il primo file della lista caricata try: sel = self.selplay[0] except IndexError: sel = None if sel: af = sel[0] it = sel[1] self.FileTable.tvSelection.unselect_all() self.FileTable.tvSelection.select_iter(it) dlgtag = TaggerDialog(self, self.mainWindow, sel) dlgtag.show() if not dlgtag.response == Gtk.ResponseType.OK: return if dlgtag.save_tags: if dlgtag.save_tags_all: for af in self.audioFileList.filelist: af.write_metadata() if dlgtag.id3v2: af.write_ID3v2() else: selection = self.Selection(self.FileTable) sel = selection[0] sel[0].write_metadata() if dlgtag.id3v2: sel[0].write_ID3v2() i = self.audioFileList.filelist.index(sel[0]) self.audioFileList.remove(sel[0].get_uri()) self.audioFileList.filelist.insert(i, AudioFile(sel[0].get_uri())) elif dlgtag.remove_tags: if dlgtag.remove_tags_all: for af in self.audioFileList.filelist: af.remove_metadata() else: selection = self.Selection(self.FileTable) sel = selection[0] sel[0].remove_metadata() i = self.audioFileList.filelist.index(sel[0]) self.audioFileList.remove(sel[0].get_uri()) self.audioFileList.filelist.insert(i, AudioFile(sel[0].get_uri())) self.FileTable.purge() self.FileTable.append(self.audioFileList) # Crea una playlist def on_Playlist(self, *args): dlgpl = PlaylistDialog(self, self.mainWindow) dlgpl.show() if not dlgpl.response == Gtk.ResponseType.OK: return # Restituisce una lista di file audio selezionati def Selection(self, FileTable): selection = [] model, pathlist = FileTable.tvSelection.get_selected_rows() print "pathlist: ", pathlist if not pathlist: print "not" try: pathlist = [(0,)] print "pathlist: ", pathlist except: pass if pathlist: print "pathlist: ", pathlist iterlist = [] for rowpath in pathlist: print "rowpath: ", rowpath try: iterlist.append(model.get_iter(rowpath)) except ValueError: pass print "iterlist: ", iterlist for it in iterlist: print "riga da riprodurre", model.get_string_from_iter(it) for af in self.audioFileList.filelist: print "af.pointer: ", af.pointer print "model.get_string_from_iter(iter): ", model.get_string_from_iter(it) if str(af.pointer) == model.get_string_from_iter(it): print "sono uguali" selection.append((af, it)) print "Selection: ", selection else: print "non sono uguali" return selection # Funzione che apre il selettore file e carica i file scelti def AddFileList(self, FileChooser): # Imposta la cartella corrente try: if os.path.exists(self.prefs.get_option("last-used-folder")): FileChooser.set_current_folder(self.prefs.get_option("last-used-folder")) else: FileChooser.set_current_folder(os.path.expandvars("$HOME")) # Eccezione nel caso in cui non sia definita. # In tal caso la cartella corrente viene settata sulla HOME. except: FileChooser.set_current_folder(os.path.expandvars("$HOME")) # Seleziona la risposta response = FileChooser.run() if response == Gtk.ResponseType.OK: if FileChooser.is_folder: # Se il percorso restituito è una cartella # crea una lista con i file audio presenti nella cartella # e nelle sue sottocartelle. walk = os.walk(FileChooser.get_current_folder()) # Restituisce una lista con tutti i file walk_filelist = [] for dirpath, subdir, filenames in walk: print "dirpath: ", dirpath print "dirnames: ", subdir for f in filenames: f = os.path.join(dirpath, f) walk_filelist.append(f) print "listone: ", walk_filelist # Aggiunge l'uri completo ad ogni file furi = [] for f in walk_filelist: for ext in fileext: if f[-4:] == ext: furi.append("file://" + str(f)) for l in furi: print "fpathList: ", l self.audioFileList.add_list(furi) else: # Se il percorso restituito è un file o un elenco di file filenames = [] print FileChooser.get_filenames()[0] if FileChooser.get_filenames(): for f in FileChooser.get_filenames(): print "f ", FileChooser.get_filenames() # Se il percorso restituito è una plaulist "*.m3u" if f[-4:] == ".m3u": plist = open(f, "rb").readlines() for finlist in plist: if not "#EXT" in finlist: print re.compile("\n").sub("", finlist) print "PERCORSO FILE IN PLAYLIST", "file://" + FileChooser.get_current_folder() + "/" + re.compile("\n").sub("", finlist) filenames.append("file://" + FileChooser.get_current_folder() + "/" + re.compile("\n").sub("", finlist)) else: filenames.append("file://" + f) print filenames self.audioFileList.add_list(filenames) print "LISTA APPESA ", self.audioFileList.filelist # Scrive i file nella tabella self.FileTable.append(self.audioFileList) elif response == Gtk.ResponseType.CANCEL: print 'Closed, no files selected' self.prefs.set_option("last-used-folder", FileChooser.get_current_folder()) FileChooser.hide() FileChooser.destroy() self.set_status() if not self.audioFileList.filelist: print "LISTA VUOTA" self.set_sensitive(False) self.cmdConvert.set_sensitive(False) else: self.set_sensitive(True) self.cmdConvert.set_sensitive(True) # Funzione che verifica se il file audio esiste def file_exists(self, af): if os.path.exists(af.get_filepath()): return True elif af.get_uri()[:7] == "cdda://": return True else: dlg = WarningDialog(self.mainWindow, NAME + " - Warning", "The file " + af.get_filepath() + " does not exist in the specified path. Perhaps it was deleted.") return False
# - zipper (array) - import Converter as C import Post as P import Generator as G import Transform as T m1 = G.cylinder((0, 0, 0), 1, 5, 0., 360., 10., (50, 50, 1)) m1 = C.initVars(m1, 'cellN', 1.) # Set cellN = 2 (interpolated points) to boundary s = T.subzone(m1, (1, m1[3], 1), (m1[2], m1[3], m1[4])) s = C.initVars(s, 'cellN', 2) m1 = T.patch(m1, s, (1, m1[3], 1)) s = T.subzone(m1, (1, 1, 1), (m1[2], 1, m1[4])) s = C.initVars(s, 'cellN', 2) m1 = T.patch(m1, s, (1, 1, 1)) ni = 30 nj = 40 m2 = G.cart((0, 0, 0), (10. / (ni - 1), 10. / (nj - 1), -1), (ni, nj, 1)) m2 = C.initVars(m2, 'cellN', 1.) array = P.zipper([m1, m2], []) C.convertArrays2File([array], 'out.plt')
# One way to import module is using import file name import Converter print(Converter.convert("Hello :)")) # another to import module with specific functions only from Converter import convert print(convert("haha :P"))
# - perturbate (array) - import Generator as G import Transform as T import Converter as C a = G.cart((0, 0, 0), (1, 1, 1), (10, 10, 1)) a = T.perturbate(a, 0.1) C.convertArrays2File([a], "out.plt")
# - projectDir (array) - import Geom as D import Converter as C import Generator as G import Transform as T import KCore.test as test # Structure a = D.sphere((0, 0, 0), 1., 20) a = C.initVars(a, 'F', 1) b = G.cart((1.1, -0.1, -0.1), (0.1, 0.1, 0.1), (1, 5, 5)) b = C.initVars(b, 'F', 1) c = T.projectDir([b], [a], (-1., 0, 0), oriented=1) test.testA([a, b] + c, 1) c = T.projectDir([b], [a], (1., 0, 0), oriented=1) test.testA([a, b] + c, 2)
def streamSurf(arrays, b, vector, N=2000, dir=1): b = Converter.convertArray2Hexa(b) if (b[3] != 'BAR'): raise TypeError("streamSurf: b must be a BAR.") coord = b[1] return post.compStreamSurf(arrays, b, vector, dir, N)
# - patch (array) - import Transform as T import Generator as G import Converter as C import numpy c1 = G.cart((0, 0, 0), (0.01, 0.01, 1), (201, 101, 1)) c2 = G.cart((0, 0, 0), (0.01, 0.01, 1), (51, 81, 1)) c2 = T.rotate(c2, (0, 0, 0), (0, 0, 1), 0.2) c3 = G.cart((0.0, 1., 0), (0.01, 0.01, 1), (101, 1, 1)) c3 = T.rotate(c3, (0, 0, 0), (0, 0, 1), 0.3) # patch a region at given position a = T.patch(c1, c2, position=(1, 1, 1)) # patch some nodes nodes = numpy.arange(20100, 20201, dtype=numpy.int32) b = T.patch(c1, c3, nodes=nodes) C.convertArrays2File([a, b], 'out.plt')
# - reorder - # Reordonne le bloc selectionne # 's' sauvegarde le fichier import Converter as C import CPlot import Transform as T import time a = C.convertFile2Arrays('fontaine.plt') CPlot.display(a, mode=1, displayBB=0) bool = 0 while (bool == 0): l = -1 CPlot.display(a) while (l == -1): l = CPlot.getSelectedZone() s = CPlot.getKeyboard() if (s == "s"): C.convertArrays2File(a, 'out.plt') import sys sys.exit() time.sleep(0.1) # Reorder suivant le type de zone z = a[l - 1] if (len(z) == 5): # structure ni = z[2] nj = z[3] nk = z[4] if (ni == 1):
# - polyline (array) - import Geom as D import Converter as C a = D.polyline([(0.,0.,0.),(1.,1.,0.),(2.,0.,0.)]) C.convertArrays2File(a, "out.plt")
# - convertFile2Arrays (binary png) - import Converter as C a = C.convertFile2Arrays('Data/test.png', 'bin_png') C.convertArrays2File(a, 'out.plt', 'bin_tp')
# - computeExtraVariable (array) - import Generator as G import Converter as C import Post as P import Transform as T import KCore.test as test a = G.cart((0, 0, 0), (1, 1, 1), (10, 10, 10)) a = C.initVars(a, 'Density', 1.) a = C.initVars(a, 'MomentumX', 1.) a = C.initVars(a, 'MomentumY', 0.) a = C.initVars(a, 'MomentumZ', 0.) a = C.initVars(a, 'EnergyStagnationDensity', 1.) v = P.computeExtraVariable(a, 'Vorticity') m = P.computeExtraVariable(a, 'VorticityMagnitude') q = P.computeExtraVariable(a, 'QCriterion') tau = P.computeExtraVariable(a, 'ShearStress') a = C.node2Center(a) a = C.addVars([a, v, m, q, tau]) test.testA([a], 1) wall = T.subzone(a, (1, 1, 1), (9, 9, 1)) skinFriction = P.computeExtraVariable(wall, 'SkinFriction') wall = C.addVars([wall, skinFriction]) test.testA([wall], 2)
# - setHoleInterpolatedPts (array) - import Converter as C import Connector as X import Generator as G def sphere(x, y, z): if x * x + y * y + z * z < 0.5**2: return 0. else: return 1. a = G.cart((-1., -1., -1.), (0.1, 0.1, 0.1), (20, 20, 20)) celln = C.node2Center(a) celln = C.initVars(celln, 'cellN', sphere, ['x', 'y', 'z']) celln = X.setHoleInterpolatedPoints(celln, depth=1) C.convertArrays2File([celln], 'out.plt')
# - gapfixer (array) - import Generator as G import Converter as C import Geom as D import KCore.test as test a = D.circle( (0,0,0), 1, N=100 ) a = C.convertArray2Tetra(a); a = G.close(a) b = G.cart((-2.,-2.,0.), (0.1,0.1,1.), (50,50,1)) a1 = G.gapfixer(a, b) test.testA([a1],1) hp = D.point((0.5, 0.5, 0.)) a2 = G.gapfixer(a, b, hp, refine=0) test.testA([a2],2)
# - boolean reorientExternalFaces (array) - import Generator as G import Converter as C import Intersector as XOR a = G.cartHexa((0., 0., 0.), (0.1, 0.1, 0.2), (10, 10, 10)) a = C.convertArray2NGon(a) a = XOR.reorientExternalFaces(a) C.convertArrays2File([a], 'out.plt')
# - integMomentNorm (array) - import Generator as G import Converter as C import Transform as T import Post as P from numpy import * import math res1 = math.pi * 10. res1c = (math.pi - math.pi / 25.) * 10. res2 = 2. res2c = 1.62 # Lit le fichier et le met dans arrays a = G.cylinder((0., 0., 0.), 0.5, 1., 360., 0., 10., (50, 2, 30)) a2 = T.subzone(a, (1, 1, 1), (50, 1, 30)) C.convertArrays2File([a], "new.plt", "bin_tp") # integMoment node2center, nj = 1 ni = a[2] - 1 nj = a[3] - 1 nk = a[4] - 1 dens = ones((1, ni * nj * nk), float64) densa = ['t', dens, ni, nj, nk] res = P.integMomentNorm([a2], [densa], [], (0., 0., 5.)) ## if math.fabs(res[0]-res1) > 1.e-1: ## print "pb in integMomentNodeCenter, nj=1" print(res, res1) del res # integMoment, nj = 1
# - display (array) - import Generator as G import CPlot import Converter as C def F(x, y): return x * x + y * y a = G.cart((0, 0, 0), (1, 1, 1), (18, 28, 1)) a = C.initVars(a, 'F', F, ['x', 'y']) CPlot.display(a, mode=3, scalarField=0, dim=2, displayIsoLegend=1)
# - center2Node (array) - import Converter as C import Generator as G import KCore.test as test def F(x, y): return 2 * x + y # Non structure TETRA ni = 30 nj = 40 nk = 12 a = G.cartTetra((0, 0, 0), (10. / (ni - 1), 10. / (nj - 1), 1), (ni, nj, nk)) a = C.initVars(a, 'ro', F, ['x', 'y']) ac = C.node2Center(a) an = C.center2Node(ac) test.testA([an], 1) # Test sur une liste ni = 10 nj = 15 nk = 2 b = G.cartTetra((0, 0, 0), (10. / (ni - 1), 10. / (nj - 1), 1), (ni, nj, nk)) b = C.initVars(b, 'ro', F, ['x', 'y']) bc = C.node2Center(b) B = C.center2Node([ac, bc]) test.testA(B, 2) # Non structure TRI
def streamLine(arrays, X0, vector, N=2000, dir=2): """Compute a streamline starting from (x0,y0,z0) given a list of arrays containing 'vector' information. Usage: streamLine(arrays, (x0,y0,z0), vector, N, dir)""" # get an (unstructured) array containing all 2D-surface arrays surf = [] for a in arrays: elt = 'None' ni = 2 nj = 2 nk = 2 if (len(a) == 5): # structure ni = a[2] nj = a[3] nk = a[4] else: elt = a[3] mult = (ni - 1) * (nj - 1) * (nk - 1) add = (ni - 1) * (nj - 1) + (ni - 1) * (nk - 1) + (nj - 1) * (nk - 1) if ((mult == 0) and (add != 0)) or (elt == 'QUAD') or (elt == 'TRI'): a = Converter.convertArray2Tetra(a) surf.append(a) if surf != []: try: import Transform, Generator except: raise ImportError( "streamLine: requires Transform and Generator modules.") surf = Transform.join(surf) surf = Generator.close(surf) # grow 2D arrays if surf != []: tol = 1. inl, modified = growOfEps__(arrays, tol, nlayers=2, planarity=False) arrays = inl if (dir == +1): return post.compStreamLine(arrays, surf, X0, vector, 1., N) elif (dir == -1): return post.compStreamLine(arrays, surf, X0, vector, -1., N) else: try: a = post.compStreamLine(arrays, surf, X0, vector, 1., N) except: a = 0 try: b = post.compStreamLine(arrays, surf, X0, vector, -1., N) except: b = 0 if (a != 0 and b != 0): try: import Transform except: return a b = Transform.reorder(b, (-1, 2, 3)) c = Transform.join(b, a) return c elif (b == 0 and a != 0): return a elif (a == 0 and b != 0): return b else: raise
# - setDoublyDefinedBC (array) - import Converter as C import Connector as X import Generator as G a = G.cart((0, 0, 0), (1, 1, 1), (10, 10, 10)) b = G.cart((2.5, 2.5, -2.5), (0.5, 0.5, 0.5), (10, 10, 30)) celln = C.array('cellN', a[2] - 1, a[3] - 1, a[4] - 1) celln = C.initVars(celln, 'cellN', 1) indmax = celln[2] * celln[3] for ind in xrange(indmax): celln[1][0][ind] = 2 cellnb = C.array('cellN', b[2] - 1, b[3] - 1, b[4] - 1) cellnb = C.initVars(cellnb, 'cellN', 1) celln = X.setDoublyDefinedBC(a, celln, [b], [cellnb], [1, a[2], 1, a[3], 1, 1], depth=1) ac = C.node2Center(a) ac = C.addVars([ac, celln]) C.convertArrays2File([ac], 'out.plt')
def computeIndicatorField(octreeHexa, indicVal, nbTargetPts=-1, bodies=[], refineFinestLevel=1, coarsenCoarsestLevel=1): """Compute the indicator -1, 0 or 1 for each element of the HEXA octree with respect to the indicatorValue field located at element centers. The bodies fix the indicator to 0 in the vicinity of bodies. nbTargetPts controls the number of points after adaptation. If refineFinestLevel=1, the finest levels are refined. If coarsenCoarsestLevel=1, the coarsest levels are coarsened wherever possible. Returns the indicator field. Usage: computeIndicatorField(octreeHexa, indicVal, nbTargetPts, bodies, refinestLevel, coarsenCoarsestLevel)""" try: import Generator as G except: raise ImportError("computeIndicatorField: requires Generator module.") npts = octreeHexa[1][0].shape[0] if (nbTargetPts == -1): nbTargetPts = npts valName = indicVal[0] nelts = indicVal[2] indicVal[1] = numpy.absolute(indicVal[1]) indicator = Converter.initVars(indicVal, 'indicator', 0.) indicator = Converter.extractVars(indicator, ['indicator']) if bodies != []: bodies = Converter.convertArray2Tetra(bodies) indicator = post.enforceIndicatorNearBodies(indicator, octreeHexa, bodies) if (refineFinestLevel == 0): indicator = post.enforceIndicatorForFinestLevel(indicator, octreeHexa) if (coarsenCoarsestLevel == 1): indicator = post.enforceIndicatorForCoarsestLevel( indicator, octreeHexa) valMin = Converter.getMinValue(indicVal, valName) epsInf = valMin / 4. valMax = Converter.getMaxValue(indicVal, valName) epsSup = valMax * 4. # calcul de l'indicateur : tous les pts sont raffines (low) indicator1 = computeIndicatorFieldForBounds(indicator, indicVal, epsInf / 4., 4. * epsInf) res = G.adaptOctree(octreeHexa, indicator1) nptsfin = len(res[1][0]) print 'Number of points for low bound value %g is %d (targetPts=%d)' % ( epsInf, nptsfin, nbTargetPts) if (nptsfin < nbTargetPts): return indicator1, epsInf / 4., epsInf * 4. # calcul de l'indicateur : ts les pts sont deraffines indicator1 = computeIndicatorFieldForBounds(indicator, indicVal, \ epsSup/4., epsSup*4.) res = G.adaptOctree(octreeHexa, indicator1) nptsfin = len(res[1][0]) print 'Number of points for high bound value %g is %d (targetPts=%d)' % ( epsSup, nptsfin, nbTargetPts) if (nptsfin > nbTargetPts): #print 'Warning: computeIndicator: the number of final points cannot be lower than the target.' return indicator1, epsSup / 4., epsSup * 4. # dichotomie count = 0 Delta = nbTargetPts diffmax = 1.e-8 * nbTargetPts / max(Delta, 1e-6) diff = diffmax + 1. while (count < 100 and Delta > 0.02 * nbTargetPts and diff > diffmax): eps = 0.5 * (epsInf + epsSup) #print 'epsInf =', epsInf, ' | epsSup = ', epsSup indicator1 = computeIndicatorFieldForBounds(indicator, indicVal, eps / 4., 4. * eps) res = G.adaptOctree(octreeHexa, indicator1) nptsfin = len(res[1][0]) if (nptsfin > nbTargetPts): epsInf = eps else: epsSup = eps Delta = abs(nbTargetPts - nptsfin) diffmax = 1.e-8 * nbTargetPts / max(Delta, 1e-6) diff = abs(epsSup - epsInf) count += 1 print 'Number of points for bound value %g is %d (targetPts=%d)' % ( eps, nptsfin, nbTargetPts) return indicator1, eps / 4., eps * 4.
# - convertFile2Arrays (fmt v3d) - # - convertArrays2File (fmt v3d) - import Converter as C # Lit le fichier in.plt dans arrays arrays = C.convertFile2Arrays("infmt.v3d", "fmt_v3d") # Sauvegarde la liste au format fmt_v3d C.convertArrays2File(arrays, "outfmt.v3d", "fmt_v3d")
# - snapSharpEdges (array) - import Generator as G import Converter as C import Geom as D # polylines with sharp angles s = D.polyline([(0.2, 0, 0), (1, 1, 0), (2.5, 1, 0), (0.2, 0, 0)]) # Regular cartesian grid h = 0.1 ni = 30 nj = 20 nk = 1 b = G.cart((-0.5, -0.5, 0), (h, h, 1.), (ni, nj, nk)) b = G.snapSharpEdges(b, [s], h) C.convertArrays2File([b, s], 'out.plt')
# - convexify any concave polygon in the mesh (array) - import Intersector as XOR import Converter as C import KCore.test as test M1 = C.convertFile2Arrays('boolNG_M1.tp') M1 = C.convertArray2NGon(M1[0]) M2 = C.convertFile2Arrays('boolNG_M2.tp') M2 = C.convertArray2NGon(M2[0]) tol = -0.5e-3 m = XOR.booleanMinus(M1, M2, tol, preserve_right=1, solid_right=1, agg_mode=1) #C.convertArrays2File([m], 'i.plt') m = XOR.agglomerateNonStarCells(m) test.testA(m, 1)
#!/usr/bin/env python # coding: utf-8 r"""bezier (array)""" import Geom as D import Converter as C import Generator as G # Bezier 1D pts = D.polyline([(0., 0., 0.), (0., 1., 0.), (2., 1., 0.), (2., 0., 0.), (4., -1., 0.), (5., 6., 0.)]) # With a specified number of points a = D.bezier(pts, N=100) # With a specified point density b = D.bezier(pts, density=10.) C.convertArrays2File([pts, a, b], 'out.plt') # Bezier 2D ni = 2 nj = 3 a = G.cart((0, 0, 0), (1, 1, 1), (ni, nj, 1)) C.setValue(a, (1, 1, 1), [1., 1., 2.]) C.setValue(a, (1, 2, 1), [1., 2., 4.]) C.setValue(a, (1, 3, 1), [1., 3., 2.]) C.setValue(a, (2, 1, 1), [2., 1., 2.]) C.setValue(a, (2, 2, 1), [2., 2., 5.]) C.setValue(a, (2, 3, 1), [2., 3., 2.]) b = D.bezier(a, density=10.) C.convertArrays2File([a] + [b], 'out2.plt')
def train(): #SETTINGS best_n_words = 10000 logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) settings = Settings.Settings() results_dir = settings.results_directory + "Chicago/Files" #TOKENIZE xs = SentenceData.SentenceData() tokenizer = WordTokenizer.WordTokenizer(min_word_count = 5) tokenized_docs = tokenizer.tokenize(xs.documents) term_freq = TermFrequency.TermFrequency(tokenized_docs) #NLTK Decision Tree list_of_dicts = Converter.vector_space_to_dict_list(term_freq.distance_matrix, term_freq.id2Word, to_binary) #Number of unique documents unique_doc_count = len(xs.documents) for smCode in xs.sm_codes[1:]: # Skip the first (A code) try: print "{0} - Processing smCode: {1}".format(str(datetime.datetime.now()), smCode) labels = xs.labels_for(smCode) num_docs_for_code = len(xs.sentences_for_code(smCode)) print "#Docs for code: {0}".format(num_docs_for_code) relative_word_frequency = DocumentFrequency.document_frequency_ratio(list_of_dicts, labels, lambda l: l == 1) condensed_data = extract_best_n_words(relative_word_frequency, best_n_words, list_of_dicts) training_data = zip(condensed_data, labels) dt = nltk.DecisionTreeClassifier.train(training_data) results = "Num Words Used: " + str(best_n_words) + "\n" results += smCode + "\n\n" results += "PSEUDOCODE:\n" results += dt.pseudocode(depth = 1000) + "\n" error = dt.error(training_data) results += "ERROR: " + str(error * 100) + "%\n\n" pct_docs_for_code = num_docs_for_code / float(unique_doc_count) * 100.0 results += "Docs for code: {0}%\n".format(pct_docs_for_code) fName = results_dir + smCode + ".txt" handle = open(fName, mode = "w+") handle.write(results) handle.close() print results except IOError as e: print str(e) #binary_matrix = term_freq.binary_matrix() #decision_tree = tree.DecisionTreeClassifier(criterion = 'entropy') #decision_tree.fit(binary_matrix, labels) # Test with CL1 labels raw_input("Press Enter to quit")
def on_Rip(self, *args): try: from morituri.rip import main as Ripper except: self.dlg = WarningDialog(self.mainWindow, NAME + " - Warning",'''Morituri is not available. Please try 'apt-get install morituri' or visit http://thomas.apestaart.org/morituri/trac/wiki''') return #Apre la finestra di dialogo con le impostazioni dlgRip = RipDialog(self.mainWindow, self.prefs) dlgRip.show() if not dlgRip.response == Gtk.ResponseType.OK: return else: self.set_status("Ripping Audio CD ...") # Posizione temporanea import tempfile tempdir = tempfile.mkdtemp() # Ripping del CD audio in una directory temporanea # Argomenti da passare: # rip_args = ['cd', 'rip', '--output-directory=' + tempdir, '--track-template=%t - %n', '--profile=wav'] # In morituri waveenc non funziona. Bisogna lasciare l'uscita di default in flac rip_args = ['cd', 'rip', '--output-directory=' + tempdir, '--track-template=%t - %n'] try: # Avvia l'estrazione ret = Ripper.main(rip_args) ret = 0 except: self.dlg = WarningDialog(self.mainWindow, NAME + " - Warning", "Task exception. Morituri don't work.") ret = -1 self.set_status() return if ret == 0: self.set_status("Ripping completed...") # Carica i file da convertire walk = os.walk(tempdir) convert_filelist = [] for dirpath, subdir, filenames in walk: for f in filenames: if f[-5:] == ".flac": f = os.path.join(dirpath, f) convert_filelist.append(AudioFile("file://" + f)) #Carica la lista dei file selezionati if not bool(int(self.prefs.get_option("save-all-tracks"))): # Solo i file selezionati self.selconv = self.Selection(self.FileTable) else: # Tutti i file self.FileTable.tvSelection.select_all() self.selconv = self.Selection(self.FileTable) self.FileTable.tvSelection.unselect_all() if self.selconv: temp_format = self.prefs.get_option("output-format") # Inizializza la coda request_queue = Queue.Queue() n = 0 for sel in self.selconv: n += 1 af = sel[0] it = sel[1] for convert_file in convert_filelist: if af.get_tag("track_number") == convert_file.get_filename()[0:2]: convert_file.set_tags_as_dict(af.get_tags_as_dict()) # Salva non compressi if not bool(int(self.prefs.get_option("rip-compressed"))) or self.prefs.get_option("output-format") == "wav": self.prefs.set_option("output-format", "wav") request_queue.put([n, (convert_file, it)]) self.set_status("Now save uncompressed files...") elif bool(int(self.prefs.get_option("rip-compressed"))): request_queue.put([n, (convert_file, it)]) self.set_status("Now save compressed files...") self.init = time.time() self.progConvert.show() # Riempita la coda, lancia il thread dell'encoder self.encoder_thread = Converter(self, self.prefs, request_queue) self.encoder_thread.start() # Svuota la coda per fermare il thread for sel in self.selconv: request_queue.put(None) self.FileTable.tvSelection.unselect_all() self.set_status("Done...")
# - getInCircleMap (array) - import Geom as D import Generator as G import Converter as C a = D.sphere((0, 0, 0), 1, 50) a = C.convertArray2Tetra(a) n = G.getInCircleMap(a) n = C.center2Node(n) n = C.addVars([a, n]) C.convertArrays2File([n], "out.plt")
def train(): #SETTINGS cv_folds = 10 logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) settings = Settings.Settings() results_dir = settings.results_directory + GwData.FOLDER #TOKENIZE xs = GwData.GwData() tokenized_docs = WordTokenizer.tokenize(xs.documents, min_word_count = 5) tfidf = TfIdf.TfIdf(tokenized_docs) lsa = Lsa.Lsa(tfidf, 300) #NLTK SVM linear kernel xs = Converter.vector_space_to_dict_list(lsa.distance_matrix, lsa.id2Word, fn_dict_creator = lambda : defaultdict(float)) total_recall, total_precision, total_f1, total_accuracy = 0.0, 0.0, 0.0, 0.0 all_results = "" processed_code_count = 0 def create_maxent(xs, ys): td = zip(xs, ys) return nltk.MaxentClassifier.train(td, algorithm='GIS', trace = 2, max_iter = 10) def classify(me, xs): return me.batch_classify(xs) #MIN_CODE_COUNT = 5 MIN_CODE_COUNT = 1 codes = [c for c in xs.sm_codes # Exclude pure vague codes if c != "v" and # Exclude doc codes. Need whole doc to classify them not c.startswith("s")] for code in codes: code_count = xs.sm_code_count[code] if code_count <= MIN_CODE_COUNT: continue processed_code_count += 1 labels = xs.labels_for(code) recall, precision, f1_score, accuracy = cross_validation_score_generic(xs, labels, create_maxent, classify, cv_folds, class_value = 1.0) results = "Code: {0} Count: {1}, Recall: {2}, Precision: {3}, F1: {4}\n".format(code.ljust(10), code_count, recall, precision, f1_score) all_results += results total_recall += recall total_precision += precision total_f1 += f1_score total_accuracy += accuracy print results, #num_codes = len(xs.sm_codes) num_codes = processed_code_count result = "AGGREGATE\n\t Recall: {0}, Precision: {1}, F1: {2}, Accuracy {3}\n".format(total_recall / num_codes, total_precision / num_codes, total_f1 / num_codes, total_accuracy / num_codes) all_results += result print result #DUMP TO FILE fName = results_dir + "Code_Classify_MaxEnt.txt" handle = open(fName, mode = "w+") handle.write(all_results) handle.close() raw_input("Press Enter to quit")
# Variables a calculer # -------------------- vars = [ 'Pressure', 'VelocityX', 'VelocityZ', 'VelocityMagnitude', 'Temperature', 'Entropy', 'Enthalpy', 'Mach', 'ViscosityMolecular', 'PressureStagnation', 'TemperatureStagnation' ] # test sur un array avec variables conservatives # ---------------------------------------------- ni = 30 nj = 40 m = G.cart((0, 0, 0), (10. / (ni - 1), 10. / (nj - 1), 1), (ni, nj, 2)) c1 = C.array('ro,rou,rov,row,roE', ni, nj, 2) c1 = C.initVars(c1, 'ro', 1.5) c1 = C.initVars(c1, 'rou', 2.) c1 = C.initVars(c1, 'rov', 3.) c1 = C.initVars(c1, 'row', 6.) c1 = C.initVars(c1, 'roE', 1.e5) a1 = C.addVars([m, c1]) P._computeVariables2(a1, vars, rgp=12.5) test.testA([a1], 1) # test sur un array avec variables primitives # ------------------------------------------- c2 = C.array('ro,u,v,w,T', ni, nj, 2) c2 = C.initVars(c2, 'ro', 1.) c2 = C.initVars(c2, 'u', 1.)
# - extractVars (array) - import Generator as G import Converter as C a = G.cart((0,0,0), (1,1,1), (10,10,10)) a = C.initVars(a, 'F=2.') # Var defined by a string r = C.extractVars(a, 'F') # Vars defined by a list r = C.extractVars(a, ['x','y']) C.convertArrays2File(r, 'out.plt')
# - coarsen (array) - import Post as P import Converter as C import Generator as G import Transform as T # coarsen all cells of a square ni = 21 nj = 21 nk = 11 hi = 2. / (ni - 1) hj = 2. / (nj - 1) hk = 1. / (nk - 1) m = G.cart((0., 0., 0.), (hi, hj, hk), (ni, nj, nk)) hi = hi / 2 hj = hj / 2 hk = hk / 2 m2 = G.cart((0., 0., 0.), (hi, hj, hk), (ni, nj, nk)) m2 = T.subzone(m2, (3, 3, 6), (m[2] - 2, m[3] - 2, 6)) m2 = T.translate(m2, (0.75, 0.75, 0.25)) m2 = T.perturbate(m2, 0.51) tri = G.delaunay(m2) npts = tri[2].shape[1] indic = C.array('indic', npts, 1, 1) indic = C.initVars(indic, 'indic', 1) sol = P.coarsen(tri, indic, argqual=0.25, tol=1.e6) C.convertArrays2File([tri, sol], 'out.plt')
# - projectAllDirs (array) - import Geom as D import Converter as C import Generator as G import Transform as T import KCore.test as test # Structure a = D.sphere((0, 0, 0), 1., 20) a = C.initVars(a, 'F', 1) b = G.cart((1.1, -0.1, -0.1), (0.1, 0.1, 0.1), (1, 5, 5)) n = G.getNormalMap(b) n = C.center2Node(n) C._addVars([b, n]) b = C.initVars(b, 'F', 1) c = T.projectAllDirs([b], [a], ['sx', 'sy', 'sz']) test.testA(c, 1) # Non structure a = D.sphere((0, 0, 0), 1., 20) a = C.initVars(a, 'F', 1) b = G.cartTetra((1.1, -0.1, -0.1), (0.1, 0.1, 0.1), (1, 5, 5)) n = G.getNormalMap(b) n = C.center2Node(n) C._addVars([b, n]) b = C.initVars(b, 'F', 1) c = T.projectAllDirs([b], [a], ['sx', 'sy', 'sz']) test.testA(c, 2) a = C.convertArray2Tetra(a) b = G.cartTetra((1.1, -0.1, -0.1), (0.1, 0.1, 0.1), (1, 5, 5))
# - maximizeBlankedCells (array) - import Converter as C import Connector as X import Generator as G def F(x,y): if (x+y<1): return 1 else: return 2 Ni = 50; Nj = 50 a = G.cart((0,0,0),(1./(Ni-1),1./(Nj-1),1),(Ni,Nj,1)) a = C.initVars(a, 'cellN', F, ['x','y']) a = X.maximizeBlankedCells(a, 2) C.convertArrays2File([a], 'out.plt')
# - polyC1Mesher (array) - import Converter as C import Generator.PolyC1 as GP import Generator as G import Transform as T # Read geometry from svg file a = C.convertFile2Arrays('Data/curve.svg', density=1)[0] a = T.homothety(a, (0, 0, 0), 0.01) a = T.reorder(a, (1, 2, 3)) h = 0.2 hp = 0.001 density = 10. splitCrit = 2. m = GP.polyC1Mesher(a, h, hp, density, splitCrit) for i in m[0]: v = G.getVolumeMap(i) min = C.getMinValue(v, 'vol') if min <= 0: print('negative volume detected.') C.convertArrays2File(m[0], 'out.plt')
def get_binary_data(self, distance_matrix, id2word): # Get binary data return Converter.vector_space_to_dict_list(distance_matrix, id2word, Converter.to_binary)