class MainWindow(QMainWindow, Ui_MainWindow): launchSignal = pyqtSignal() def __init__(self, parent = None): QMainWindow.__init__(self, parent) self.setupUi(self) self.countdown = QTimer(); self.startTimer() self.countdown.timeout.connect(self.decrement) self.launchSignal.connect(self.launchButton.click) self.launchButton.clicked.connect(self.launch) self.rebootButton.clicked.connect(self.reboot) self.shutdownButton.clicked.connect(self.shutdown) self.tabWidget.currentChanged.connect(self.tabChange) self.calibrationWidget = CalibrationWidget() self.tabWidget.addTab(self.calibrationWidget,"Calibration") self.updateWidget = UpdateWidget() self.updateWidget.setStatusbar(self.statusbar) self.tabWidget.addTab(self.updateWidget,"Update") self.settingsWidget = SettingsWidget(self) self.settingsWidget.statusBar = self.statusbar self.tabWidget.addTab(self.settingsWidget,"Global Settings") self.statusbar.showMessage("Ready") def decrement(self): self.lcdNumber.display(self.lcdNumber.intValue() - 1) if self.lcdNumber.intValue() == 0: self.launchSignal.emit() self.countdown.stop() def startTimer(self): self.countdown.start(1000) self.lcdNumber.display(10) def tabChange(self,tab): self.countdown.stop() if self.tabWidget.tabText(tab) == 'Global Settings': self.settingsWidget.updateImage() self.settingsWidget.updateImage() def gameStop(self): self.statusbar.showMessage("Ready") self.startTimer() def launch(self): self.countdown.stop() self.statusbar.showMessage("Launching Simulation...") launcher = Launcher() launcher.finished.connect(self.gameStop) launcher.start() self.launcher = launcher def reboot(self): call(['gksudo','reboot']) def shutdown(self): call(['gksudo','halt'])
def __init__(self, parent = None): QMainWindow.__init__(self, parent) self.setupUi(self) self.countdown = QTimer(); self.startTimer() self.countdown.timeout.connect(self.decrement) self.launchSignal.connect(self.launchButton.click) self.launchButton.clicked.connect(self.launch) self.rebootButton.clicked.connect(self.reboot) self.shutdownButton.clicked.connect(self.shutdown) self.tabWidget.currentChanged.connect(self.tabChange) self.calibrationWidget = CalibrationWidget() self.tabWidget.addTab(self.calibrationWidget,"Calibration") self.settingsWidget = SettingsWidget(self) self.settingsWidget.statusBar = self.statusbar self.tabWidget.addTab(self.settingsWidget,"Global Settings") self.statusbar.showMessage("Ready")
def __init__(self, parent=None): super(Player, self).__init__(parent) self.setWindowTitle("SongScreen") self.setFocusPolicy(Qt.StrongFocus) self.colorDialog = None self.trackInfo = "" self.statusInfo = "" self.duration = 0 self.player = QMediaPlayer() self.playlist = QMediaPlaylist() self.player.setPlaylist(self.playlist) self.player.durationChanged.connect(self.durationChanged) self.player.positionChanged.connect(self.positionChanged) self.player.metaDataChanged.connect(self.metaDataChanged) # self.playlist.currentIndexChanged.connect(self.playlistPositionChanged) self.player.mediaStatusChanged.connect(self.statusChanged) self.player.bufferStatusChanged.connect(self.bufferingProgress) self.player.videoAvailableChanged.connect(self.videoAvailableChanged) self.player.error.connect(self.displayErrorMessage) # self.videoWidget = VideoWidget() # self.player.setVideoOutput(self.videoWidget) self.slider = MediaProgressWidget() # QSlider(Qt.Horizontal) self.markers = [] self.songtext_widget = SongTextWidget() self.songtext_widget.show() # self.playlistModel = PlaylistModel() # self.playlistModel.setPlaylist(self.playlist) # # self.playlistView = QListView() # self.playlistView.setModel(self.playlistModel) # self.playlistView.setCurrentIndex( # self.playlistModel.index(self.playlist.currentIndex(), 0)) # # self.playlistView.activated.connect(self.jump) self.slider.setRange(0, self.player.duration() / 1000) self.labelDuration = QLabel() self.slider.sliderMoved.connect(self.seek) # openButton = QPushButton("Open", clicked=self.open) controls = PlayerControlsWidget() controls.setState(self.player.state()) controls.setVolume(self.player.volume()) # controls.setMuted(controls.isMuted()) controls.play.connect(self.player.play) controls.pause.connect(self.player.pause) controls.stop.connect(self.stop_clicked) # controls.stop.connect(self.videoWidget.update) # controls.next.connect(self.playlist.next) # controls.previous.connect(self.previousClicked) controls.changeVolume.connect(self.player.setVolume) # controls.changeMuting.connect(self.player.setMuted) # controls.changeRate.connect(self.player.setPlaybackRate) self.player.stateChanged.connect(controls.setState) self.player.stateChanged.connect(self.setState) self.player.volumeChanged.connect(controls.setVolume) # self.player.mutedChanged.connect(controls.setMuted) # self.fullScreenButton = QPushButton("FullScreen") # self.fullScreenButton.setCheckable(True) # # self.colorButton = QPushButton("Color Options...") # self.colorButton.setEnabled(False) # self.colorButton.clicked.connect(self.showColorDialog) displayLayout = QHBoxLayout() # displayLayout.addWidget(self.videoWidget, 2) # displayLayout.addWidget(self.songtext_widget) # displayLayout.addWidget(self.playlistView) self.song_select_widget = SongSelectWidget() self.song_select_widget.song_selected.connect(self.load_song) self.screen_select_widget = ScreenSelectWidget() self.screen_select_widget.screen_selected.connect(self.display_lyrics_on_screen) self.screen_select_widget.active_screen = QApplication.desktop().screenNumber(self.songtext_widget) self.settings_button = QPushButton() self.settings_button.setText(self.tr("Settings...")) self.settings_button.clicked.connect(self.show_settings) sidebarLayout = QVBoxLayout() sidebarLayout.setContentsMargins(10, 1, 0, 1); sidebarLayout.addWidget(self.settings_button) sidebarLayout.addStretch(1); sidebarLayout.addWidget(self.screen_select_widget) displayLayout.addWidget(self.song_select_widget) displayLayout.addLayout(sidebarLayout) controlLayout = QHBoxLayout() controlLayout.setContentsMargins(0, 0, 0, 0) # controlLayout.addWidget(openButton) # controlLayout.addStretch(1) controlLayout.addWidget(controls) controlLayout.addStretch(1) controlLayout.addWidget(self.labelDuration) # controlLayout.addWidget(self.fullScreenButton) # controlLayout.addWidget(self.colorButton) layout = QVBoxLayout() layout.addLayout(displayLayout) hLayout = QHBoxLayout() hLayout.addWidget(self.slider) # hLayout.addWidget(self.labelDuration) layout.addLayout(hLayout) layout.addLayout(controlLayout) self.setLayout(layout) if not self.player.isAvailable(): QMessageBox.warning(self, "Service not available", "The QMediaPlayer object does not have a valid service.\n" "Please check the media service plugins are installed.") controls.setEnabled(False) self.playlistView.setEnabled(False) # openButton.setEnabled(False) self.colorButton.setEnabled(False) self.fullScreenButton.setEnabled(False) self.metaDataChanged() self._loading_audio = False self._finished_song = False self._lyrics_fading = False self._song_number = -1 self.settings = { 'font_size': 40, 'line_increment': 2, 'lyrics_language': '', } self._load_settings() self.settings_widget = SettingsWidget(self.settings, self.lyrics_path) self.settings_widget.font_size_changed.connect(self.songtext_widget.set_font_size) self.settings_widget.line_increment_changed.connect(self.songtext_widget.set_line_increment) self.settings_widget.language_changed.connect(self._language_changed) self.song_select_widget.reset(self.available_song_numbers)
class Player(QWidget): audio_path = "audio" lyrics_path = "lyrics" timings_path = os.path.join("lyrics", "timing") settings_path = "settings.json" fullScreenChanged = pyqtSignal(bool) def __init__(self, parent=None): super(Player, self).__init__(parent) self.setWindowTitle("SongScreen") self.setFocusPolicy(Qt.StrongFocus) self.colorDialog = None self.trackInfo = "" self.statusInfo = "" self.duration = 0 self.player = QMediaPlayer() self.playlist = QMediaPlaylist() self.player.setPlaylist(self.playlist) self.player.durationChanged.connect(self.durationChanged) self.player.positionChanged.connect(self.positionChanged) self.player.metaDataChanged.connect(self.metaDataChanged) # self.playlist.currentIndexChanged.connect(self.playlistPositionChanged) self.player.mediaStatusChanged.connect(self.statusChanged) self.player.bufferStatusChanged.connect(self.bufferingProgress) self.player.videoAvailableChanged.connect(self.videoAvailableChanged) self.player.error.connect(self.displayErrorMessage) # self.videoWidget = VideoWidget() # self.player.setVideoOutput(self.videoWidget) self.slider = MediaProgressWidget() # QSlider(Qt.Horizontal) self.markers = [] self.songtext_widget = SongTextWidget() self.songtext_widget.show() # self.playlistModel = PlaylistModel() # self.playlistModel.setPlaylist(self.playlist) # # self.playlistView = QListView() # self.playlistView.setModel(self.playlistModel) # self.playlistView.setCurrentIndex( # self.playlistModel.index(self.playlist.currentIndex(), 0)) # # self.playlistView.activated.connect(self.jump) self.slider.setRange(0, self.player.duration() / 1000) self.labelDuration = QLabel() self.slider.sliderMoved.connect(self.seek) # openButton = QPushButton("Open", clicked=self.open) controls = PlayerControlsWidget() controls.setState(self.player.state()) controls.setVolume(self.player.volume()) # controls.setMuted(controls.isMuted()) controls.play.connect(self.player.play) controls.pause.connect(self.player.pause) controls.stop.connect(self.stop_clicked) # controls.stop.connect(self.videoWidget.update) # controls.next.connect(self.playlist.next) # controls.previous.connect(self.previousClicked) controls.changeVolume.connect(self.player.setVolume) # controls.changeMuting.connect(self.player.setMuted) # controls.changeRate.connect(self.player.setPlaybackRate) self.player.stateChanged.connect(controls.setState) self.player.stateChanged.connect(self.setState) self.player.volumeChanged.connect(controls.setVolume) # self.player.mutedChanged.connect(controls.setMuted) # self.fullScreenButton = QPushButton("FullScreen") # self.fullScreenButton.setCheckable(True) # # self.colorButton = QPushButton("Color Options...") # self.colorButton.setEnabled(False) # self.colorButton.clicked.connect(self.showColorDialog) displayLayout = QHBoxLayout() # displayLayout.addWidget(self.videoWidget, 2) # displayLayout.addWidget(self.songtext_widget) # displayLayout.addWidget(self.playlistView) self.song_select_widget = SongSelectWidget() self.song_select_widget.song_selected.connect(self.load_song) self.screen_select_widget = ScreenSelectWidget() self.screen_select_widget.screen_selected.connect(self.display_lyrics_on_screen) self.screen_select_widget.active_screen = QApplication.desktop().screenNumber(self.songtext_widget) self.settings_button = QPushButton() self.settings_button.setText(self.tr("Settings...")) self.settings_button.clicked.connect(self.show_settings) sidebarLayout = QVBoxLayout() sidebarLayout.setContentsMargins(10, 1, 0, 1); sidebarLayout.addWidget(self.settings_button) sidebarLayout.addStretch(1); sidebarLayout.addWidget(self.screen_select_widget) displayLayout.addWidget(self.song_select_widget) displayLayout.addLayout(sidebarLayout) controlLayout = QHBoxLayout() controlLayout.setContentsMargins(0, 0, 0, 0) # controlLayout.addWidget(openButton) # controlLayout.addStretch(1) controlLayout.addWidget(controls) controlLayout.addStretch(1) controlLayout.addWidget(self.labelDuration) # controlLayout.addWidget(self.fullScreenButton) # controlLayout.addWidget(self.colorButton) layout = QVBoxLayout() layout.addLayout(displayLayout) hLayout = QHBoxLayout() hLayout.addWidget(self.slider) # hLayout.addWidget(self.labelDuration) layout.addLayout(hLayout) layout.addLayout(controlLayout) self.setLayout(layout) if not self.player.isAvailable(): QMessageBox.warning(self, "Service not available", "The QMediaPlayer object does not have a valid service.\n" "Please check the media service plugins are installed.") controls.setEnabled(False) self.playlistView.setEnabled(False) # openButton.setEnabled(False) self.colorButton.setEnabled(False) self.fullScreenButton.setEnabled(False) self.metaDataChanged() self._loading_audio = False self._finished_song = False self._lyrics_fading = False self._song_number = -1 self.settings = { 'font_size': 40, 'line_increment': 2, 'lyrics_language': '', } self._load_settings() self.settings_widget = SettingsWidget(self.settings, self.lyrics_path) self.settings_widget.font_size_changed.connect(self.songtext_widget.set_font_size) self.settings_widget.line_increment_changed.connect(self.songtext_widget.set_line_increment) self.settings_widget.language_changed.connect(self._language_changed) self.song_select_widget.reset(self.available_song_numbers) @property def lyrics_language_path(self): path = QStandardPaths.locate(QStandardPaths.AppDataLocation, self.lyrics_path, QStandardPaths.LocateDirectory) return os.path.join(path, self.settings['lyrics_language']) @property def available_song_numbers(self): audios = set( [int(os.path.splitext(filename)[0]) for filename in os.listdir(self.audio_path) if filename[0] != '.']) try: lyrics = set( [int(os.path.splitext(filename)[0]) for filename in os.listdir(self.lyrics_language_path) if filename[0] != '.'] ) except (ValueError, FileNotFoundError): lyrics = set() return sorted(list(audios.intersection(lyrics))) def show_settings(self): self.settings_widget.hide() self.settings_widget.show() def display_lyrics_on_screen(self, screen_number): desktop = QApplication.desktop() if screen_number >= desktop.screenCount(): screen_number = desktop.screenNumber(self) rect = desktop.availableGeometry(screen_number) for _ in range(3): if screen_number != desktop.screenNumber(self): self.songtext_widget.setWindowFlags(Qt.FramelessWindowHint) self.songtext_widget.hide() self.songtext_widget.move(rect.x(), rect.y()) self.songtext_widget.resize(rect.width(), rect.height()) self.songtext_widget.showFullScreen() else: self.songtext_widget.setWindowFlags(Qt.WindowTitleHint) self.songtext_widget.hide() self.songtext_widget.move(rect.x(), rect.y()) self.songtext_widget.resize(self.songtext_widget.minimumSize()) self.songtext_widget.show() self.screen_select_widget.active_screen = screen_number self.activateWindow() def load_song(self, song_number): if self._song_number == song_number: self.seek(0) else: if self._song_number > 0: self._save_timings() self._song_number = song_number self.slider.dirty = False self._load_audio() self._load_lyrics() # self.player.play() def _load_audio(self): filename = os.path.join(self.audio_path, "{:03}.mp3".format(self._song_number)) self.playlist.clear() fileInfo = QFileInfo(filename) if fileInfo.exists(): url = QUrl.fromLocalFile(fileInfo.absoluteFilePath()) if fileInfo.suffix().lower() == 'm3u': self.playlist.load(url) else: self.playlist.addMedia(QMediaContent(url)) self._loading_audio = True self.player.play() def _load_lyrics(self): with open(os.path.join(self.lyrics_language_path, "{}.json".format(self._song_number)), 'r') as f: song_markers = json.load(f) self.markers = [] for m in song_markers['markers']: marker = MediaMarker(self.slider, m['name']) marker.text = m['text'] marker.progress = 0.0 self.markers.append(marker) self.songtext_widget.title = "{} {}".format(self._song_number, song_markers['title']) self.songtext_widget.markers = self.markers self.songtext_widget.fade_in() try: with open(os.path.join(self.timings_path, "{}.json".format(self._song_number)), 'r') as f: timings = json.load(f) for m, t in zip(self.markers, timings): m.progress = t except FileNotFoundError: pass self.slider.markers = self.markers def _language_changed(self, _): available_song_numbers = self.available_song_numbers self.song_select_widget.reset(available_song_numbers) if self._song_number in available_song_numbers: self._load_lyrics() # def open(self): # fileNames, _ = QFileDialog.getOpenFileNames(self, "Open Files") # self.addToPlaylist(fileNames) # # def addToPlaylist(self, fileNames): # for name in fileNames: # fileInfo = QFileInfo(name) # if fileInfo.exists(): # url = QUrl.fromLocalFile(fileInfo.absoluteFilePath()) # if fileInfo.suffix().lower() == 'm3u': # self.playlist.load(url) # else: # self.playlist.addMedia(QMediaContent(url)) # else: # url = QUrl(name) # if url.isValid(): # self.playlist.addMedia(QMediaContent(url)) def durationChanged(self, duration): duration /= 1000 self.duration = duration self.slider.setMaximum(duration) if self._loading_audio: self._loading_audio = False line_total = 0 for marker in self.markers: line_total += marker.linecount - 1 silence_ratio = 5.0 / self.duration offset = 1.8 / line_total linecount = 0 for marker in self.markers: if marker.progress == 0.0: marker.progress = offset + (1 - offset) * (1 - silence_ratio) * linecount / line_total linecount += marker.linecount - 1 self.player.pause() @property def _should_fade_out(self): return self.player.position() / 1000 >= self.duration - 5 def positionChanged(self, progress): progress /= 1000 if not self.slider.isSliderDown(): self.slider.setValue(progress) self.updateDurationInfo(progress) if self.duration > 0: # if self.player.state() == QMediaPlayer.PlayingState: self.songtext_widget.progress = progress / self.duration if self._should_fade_out: self._fade_out_lyrics() def _fade_out_lyrics(self): if not self._lyrics_fading: self._lyrics_fading = True self.songtext_widget.fade_out() def metaDataChanged(self): if self.player.isMetaDataAvailable(): self.setTrackInfo("%s - %s" % ( self.player.metaData(QMediaMetaData.AlbumArtist), self.player.metaData(QMediaMetaData.Title))) def previousClicked(self): # Go to the previous track if we are within the first 5 seconds of # playback. Otherwise, seek to the beginning. if self.player.position() <= 5000: self.playlist.previous() else: self.player.setPosition(0) def jump(self, index): if index.isValid(): self.playlist.setCurrentIndex(index.row()) self.player.play() def seek(self, seconds): self.player.setPosition(seconds * 1000) def setState(self, status): if status == QMediaPlayer.StoppedState: self._finished_song = True elif status == QMediaPlayer.PlayingState: if self._finished_song or (self._lyrics_fading and not self._should_fade_out): self._finished_song = False self._lyrics_fading = False self.songtext_widget.fade_in() def stop_clicked(self): self.player.stop() self._fade_out_lyrics() def statusChanged(self, status): self.handleCursor(status) if status == QMediaPlayer.LoadingMedia: self.setStatusInfo("Loading...") elif status == QMediaPlayer.StalledMedia: self.setStatusInfo("Media Stalled") elif status == QMediaPlayer.EndOfMedia: QApplication.alert(self) elif status == QMediaPlayer.InvalidMedia: self.displayErrorMessage() else: self.setStatusInfo("") def handleCursor(self, status): if status in (QMediaPlayer.LoadingMedia, QMediaPlayer.BufferingMedia, QMediaPlayer.StalledMedia): self.setCursor(Qt.BusyCursor) else: self.unsetCursor() def bufferingProgress(self, progress): self.setStatusInfo("Buffering %d%" % progress) def videoAvailableChanged(self, available): if available: self.fullScreenButton.clicked.connect( self.videoWidget.setFullScreen) self.videoWidget.fullScreenChanged.connect( self.fullScreenButton.setChecked) if self.fullScreenButton.isChecked(): self.videoWidget.setFullScreen(True) else: self.fullScreenButton.clicked.disconnect( self.videoWidget.setFullScreen) self.videoWidget.fullScreenChanged.disconnect( self.fullScreenButton.setChecked) self.videoWidget.setFullScreen(False) self.colorButton.setEnabled(available) def setTrackInfo(self, info): self.trackInfo = info # if self.statusInfo != "": # self.setWindowTitle("%s | %s" % (self.trackInfo, self.statusInfo)) # else: # self.setWindowTitle(self.trackInfo) def setStatusInfo(self, info): self.statusInfo = info # if self.statusInfo != "": # self.setWindowTitle("%s | %s" % (self.trackInfo, self.statusInfo)) # else: # self.setWindowTitle(self.trackInfo) def displayErrorMessage(self): self.setStatusInfo(self.player.errorString()) def updateDurationInfo(self, currentInfo): duration = self.duration if currentInfo or duration: currentTime = QTime((currentInfo / 3600) % 60, (currentInfo / 60) % 60, currentInfo % 60, (currentInfo * 1000) % 1000) totalTime = QTime((duration / 3600) % 60, (duration / 60) % 60, duration % 60, (duration * 1000) % 1000); format = 'hh:mm:ss' if duration > 3600 else 'mm:ss' tStr = currentTime.toString(format) + " / " + totalTime.toString(format) else: tStr = "" self.labelDuration.setText(tStr) def showColorDialog(self): if self.colorDialog is None: brightnessSlider = QSlider(Qt.Horizontal) brightnessSlider.setRange(-100, 100) brightnessSlider.setValue(self.videoWidget.brightness()) brightnessSlider.sliderMoved.connect( self.videoWidget.setBrightness) self.videoWidget.brightnessChanged.connect( brightnessSlider.setValue) contrastSlider = QSlider(Qt.Horizontal) contrastSlider.setRange(-100, 100) contrastSlider.setValue(self.videoWidget.contrast()) contrastSlider.sliderMoved.connect(self.videoWidget.setContrast) self.videoWidget.contrastChanged.connect(contrastSlider.setValue) hueSlider = QSlider(Qt.Horizontal) hueSlider.setRange(-100, 100) hueSlider.setValue(self.videoWidget.hue()) hueSlider.sliderMoved.connect(self.videoWidget.setHue) self.videoWidget.hueChanged.connect(hueSlider.setValue) saturationSlider = QSlider(Qt.Horizontal) saturationSlider.setRange(-100, 100) saturationSlider.setValue(self.videoWidget.saturation()) saturationSlider.sliderMoved.connect( self.videoWidget.setSaturation) self.videoWidget.saturationChanged.connect( saturationSlider.setValue) layout = QFormLayout() layout.addRow("Brightness", brightnessSlider) layout.addRow("Contrast", contrastSlider) layout.addRow("Hue", hueSlider) layout.addRow("Saturation", saturationSlider) button = QPushButton("Close") layout.addRow(button) self.colorDialog = QDialog(self) self.colorDialog.setWindowTitle("Color Options") self.colorDialog.setLayout(layout) button.clicked.connect(self.colorDialog.close) self.colorDialog.show() def closeEvent(self, close_event): self._save_timings() self._save_settings() self.songtext_widget.close() self.settings_widget.close() def keyPressEvent(self, key_event): if key_event.key() == Qt.Key_Space: key_event.accept() if self.player.state() == QMediaPlayer.PlayingState: self.player.pause() elif self.player.state() in [QMediaPlayer.PausedState, QMediaPlayer.StoppedState]: self.player.play() elif key_event.key() == Qt.Key_M: key_event.accept() self.slider.set_closest_marker_to_current_progress() def _save_timings(self): if self.slider.dirty: with open(os.path.join(self.timings_path, "{}.json".format(self._song_number)), 'w') as f: json.dump([marker.progress for marker in self.markers], f, indent=2) def _save_settings(self): # TODO : refactor and use QSettings directly # with open(self.settings_path, 'w') as f: self.settings.update({ 'lyrics_screen': QApplication.desktop().screenNumber(self.songtext_widget), 'control_window_position': self.pos(), }) # json.dump(self.settings, f, indent=2) settings = QSettings("Maccesch", "SongScreen") for key, value in self.settings.items(): settings.setValue(key, value) def _load_settings(self): # try: # with open(self.settings_path, 'r') as f: # settings = json.load(f) settings = QSettings("Maccesch", "SongScreen") if settings.contains('lyrics_screen'): self.display_lyrics_on_screen(settings.value('lyrics_screen')) if settings.contains('control_window_position'): self.move(settings.value('control_window_position')) for key in settings.allKeys(): self.settings[key] = settings.value(key) # self.settings.update(settings) self.songtext_widget.set_font_size(self.settings['font_size']) self.songtext_widget.set_line_increment(self.settings['line_increment']) # except (FileNotFoundError, ValueError): # pass if not os.path.exists(self.lyrics_language_path) or not self.settings['lyrics_language']: languages = list( filter(lambda p: os.path.isdir(os.path.join(self.lyrics_path, p)) and p != "timings", os.listdir(self.lyrics_path)) ) self.settings['lyrics_language'] = languages[0] if languages else ""
def initUI(self): ''' Setting up Interface ''' mainWidget = QtGui.QSplitter(QtCore.Qt.Horizontal) self.fileMenu=FileSourceWidget(self) mainWidget.addWidget(self.fileMenu) tabsAndSettingsWidget=QtGui.QWidget(self) tabsAndSettingsLayout=QtGui.QHBoxLayout(tabsAndSettingsWidget) tabs = QtGui.QTabWidget(self) #### NOT THE BEST WAY TO IMPLEMENT THAT! self.lastCalcMultiple=False images=QtGui.QWidget(self) highlightColot = str('white')#tabs.palette().color(QtGui.QPalette.HighlightedText).name()) imagesLayout=QtGui.QVBoxLayout(images) tabs.addTab(images,"Results") self.figure = plt.figure(facecolor=highlightColot) self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas, self) imagesLayout.addWidget(self.canvas) imagesLayout.addWidget(self.toolbar) fastFRET=QtGui.QWidget(self) fastFRETLayout=QtGui.QVBoxLayout(fastFRET) tabs.addTab(fastFRET,"Raw signal") self.figure1 = plt.figure(facecolor=highlightColot) self.canvas1 = FigureCanvas(self.figure1) self.toolbar1 = NavigationToolbar(self.canvas1, self) fastFRETLayout.addWidget(self.canvas1) fastFRETLayout.addWidget(self.toolbar1) results=QtGui.QWidget(self) resultsLayout=QtGui.QVBoxLayout(results) tabs.addTab(results,"Export") self.tableWidget=TableWidget(self) resultsLayout.addWidget(self.tableWidget) self.logText = QtGui.QTextEdit() self.logText.setMaximumHeight(130) self.logText.setReadOnly(True) self.logText.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) self.logText.append("Welcome to Fretty 1.1! ") self.logger = Logger(self.logText) #self.errors = Logger(self.logText) sys.stdout = self.logger tabs_and_logger_widget=QtGui.QWidget(self) tabs_and_logger_layout=QtGui.QVBoxLayout(tabs_and_logger_widget) tabs_and_logger_layout.addWidget(tabs) tabs_and_logger_layout.addWidget(self.logText) tabsAndSettingsLayout.addWidget(tabs_and_logger_widget) self.settingsWidget=SettingsWidget(self) self.settings=self.settingsWidget.collectSettings() tabsAndSettingsLayout.addWidget(self.settingsWidget) mainWidget.addWidget(tabsAndSettingsWidget) self.setCentralWidget(mainWidget) self.setWindowTitle('FRETTY') self.assignConnections()
class MainWindow(QtGui.QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.initUI() self.show() def initUI(self): ''' Setting up Interface ''' mainWidget = QtGui.QSplitter(QtCore.Qt.Horizontal) self.fileMenu=FileSourceWidget(self) mainWidget.addWidget(self.fileMenu) tabsAndSettingsWidget=QtGui.QWidget(self) tabsAndSettingsLayout=QtGui.QHBoxLayout(tabsAndSettingsWidget) tabs = QtGui.QTabWidget(self) #### NOT THE BEST WAY TO IMPLEMENT THAT! self.lastCalcMultiple=False images=QtGui.QWidget(self) highlightColot = str('white')#tabs.palette().color(QtGui.QPalette.HighlightedText).name()) imagesLayout=QtGui.QVBoxLayout(images) tabs.addTab(images,"Results") self.figure = plt.figure(facecolor=highlightColot) self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas, self) imagesLayout.addWidget(self.canvas) imagesLayout.addWidget(self.toolbar) fastFRET=QtGui.QWidget(self) fastFRETLayout=QtGui.QVBoxLayout(fastFRET) tabs.addTab(fastFRET,"Raw signal") self.figure1 = plt.figure(facecolor=highlightColot) self.canvas1 = FigureCanvas(self.figure1) self.toolbar1 = NavigationToolbar(self.canvas1, self) fastFRETLayout.addWidget(self.canvas1) fastFRETLayout.addWidget(self.toolbar1) results=QtGui.QWidget(self) resultsLayout=QtGui.QVBoxLayout(results) tabs.addTab(results,"Export") self.tableWidget=TableWidget(self) resultsLayout.addWidget(self.tableWidget) self.logText = QtGui.QTextEdit() self.logText.setMaximumHeight(130) self.logText.setReadOnly(True) self.logText.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) self.logText.append("Welcome to Fretty 1.1! ") self.logger = Logger(self.logText) #self.errors = Logger(self.logText) sys.stdout = self.logger tabs_and_logger_widget=QtGui.QWidget(self) tabs_and_logger_layout=QtGui.QVBoxLayout(tabs_and_logger_widget) tabs_and_logger_layout.addWidget(tabs) tabs_and_logger_layout.addWidget(self.logText) tabsAndSettingsLayout.addWidget(tabs_and_logger_widget) self.settingsWidget=SettingsWidget(self) self.settings=self.settingsWidget.collectSettings() tabsAndSettingsLayout.addWidget(self.settingsWidget) mainWidget.addWidget(tabsAndSettingsWidget) self.setCentralWidget(mainWidget) self.setWindowTitle('FRETTY') self.assignConnections() def assignConnections(self): ''' Assigning connections ''' self.connect(self.fileMenu,QtCore.SIGNAL("updateFilePreview"),self.set_data) self.connect(self.fileMenu,QtCore.SIGNAL("updateUI"),self.repaint) self.connect(self.fileMenu,QtCore.SIGNAL("runCalculations"),self.plot_multiple_files) self.connect(self.settingsWidget,QtCore.SIGNAL("settingsUpdatedSignal"),self.apply_settings) def apply_settings(self,settings): self.settings=settings if self.lastCalcMultiple: try: self.plot_multiple_files() except IndexError: print "<font color=#FF0000>No files loaded.</font>" else: try: self.plot_single_file(self.calculate_single_file(self.data,self.settings,self.name)) except AttributeError: try: self.plot_multiple_files() except IndexError: print "<font color=#FF0000>No files loaded.</font>" def set_data(self,data,name): self.data=data self.name=name self.plot_single_file(self.calculate_single_file(self.data,self.settings,self.name)) self.lastCalcMultiple=False def plot_raw(self,data,settings,showplots=True): time=data.time cy3=data.donor cy5=data.acceptor timestep=data.timestep cy3_int=np.round(timestep*cy3*1000) cy5_int=np.round(timestep*cy5*1000) max=[cy3_int.max() if cy5_int.max()<=cy3_int.max() else cy5_int.max()][0] av_max=[np.average(cy3_int) if np.average(cy5_int)<=np.average(cy3_int) else np.average(cy5_int)][0] max=np.round(max/3) x=np.arange(0,max,1) cy3_hist=np.histogram(cy3_int,x,normed=True)[0] cy5_hist=np.histogram(cy5_int,x,normed=True)[0] x_axis=x[:-1] rawframe=np.vstack((x_axis,cy3_hist,cy5_hist)).T np.savetxt('data.txt',rawframe,header="#MHz Cy3 Cy5",fmt='%.3f',) m, sd1, = [5, 1] p = [m, sd1] # Initial guesses for leastsq plsq_cy3 = leastsq(res, p, args = (cy3_hist, x_axis)) plsq_cy5 = leastsq(res, p, args = (cy5_hist, x_axis)) cy3_est = norm(x_axis, plsq_cy3[0][0], plsq_cy3[0][1]) cy5_est = norm(x_axis, plsq_cy5[0][0], plsq_cy5[0][1]) x_axis=x_axis/(timestep*1000) cy3_guess=plsq_cy3[0]/(timestep*1000) cy5_guess=plsq_cy5[0]/(timestep*1000) if settings['backgrMetod']=='Auto (gauss)': cy3_bgrnd=cy3_guess[0] cy5_bgrnd=cy5_guess[0] elif settings['backgrMetod']=='Manual': cy3_bgrnd=settings['BD'] cy5_bgrnd=settings['BA'] if settings['threshMethod']=='Auto (gauss)': if settings['threshLogic']=='SUM': cy3_thld=(cy3_guess[1]+cy5_guess[1])*settings['CD'] cy5_thld=(cy3_guess[1]+cy5_guess[1])*settings['CD'] else: cy3_thld=cy3_guess[1]*settings['CD'] cy5_thld=cy5_guess[1]*settings['CA'] elif settings['threshMethod']=='Manual thresholds': cy3_thld=settings['TD'] cy5_thld=settings['TA'] elif settings['threshMethod']=='Select top events': cy3_thld=cy3[np.argpartition(cy3,-settings['ND'])[-settings['ND']:]].min()-cy3_bgrnd cy5_thld=cy5[np.argpartition(cy5,-settings['NA'])[-settings['NA']:]].min()-cy5_bgrnd #ms, cs , ws = fit_mixture(cy3.reshape(cy3.size,1),1) #gaus2=ws[0]*mlab.normpdf(x_axis,ms[0],cs[0]) self.figure1.clf() if showplots: gs = gridspec.GridSpec(2, 2) ax00 = self.figure1.add_subplot(gs[0,0]) ax00.plot(x_axis, cy3_hist,color='blue', label='Signal') #ax00.hist(cy3,np.arange(0,max,1/(timestep*1000)), label='Raw',normed=True) ax00.plot(x_axis, cy3_est,color='black', label='Fitted') ax00.axvline(cy3_bgrnd,color='red', label='Bkgnd',linewidth=3) ax00.axvline(cy3_bgrnd+cy3_thld,color='green', label='Thld',linewidth=3) #ax00.plot(x_axis,gaus2, linewidth=3) ax00.legend() ax00.set_title('Donor signal spectra') ax00.set_ylabel('Amount,%') ax00.set_xlabel('Count, kHz') scale=[cy3_thld+1 if 10*cy3_guess[1]<=cy3_thld else 10*cy3_guess[1]][0] ax00.set_xlim(0,np.round(cy3_guess[0]+scale)) ax01 = self.figure1.add_subplot(gs[0,1]) ax01.plot(x_axis, cy5_hist,color='blue', label='Raw') ax01.plot(x_axis, cy5_est,color='black', label='Fitted') ax01.axvline(cy5_bgrnd,color='red', label='Bkgnd',linewidth=3) ax01.axvline(cy5_bgrnd+cy5_thld,color='green', label='Thld',linewidth=3) ax01.legend() ax01.set_title('Acceptor signal spectra') ax01.set_ylabel('Amount,%') ax01.set_xlabel('Count, kHz') scale=[cy5_thld+1 if 10*cy5_guess[1]<=cy5_thld else 10*cy5_guess[1]][0] ax01.set_xlim(0,np.round(cy5_guess[0]+scale)) ax10 = self.figure1.add_subplot(gs[1,0]) ax10.plot(time,cy3,color='blue',linewidth=0.02,label='Signal') ax10.axhline(cy3_bgrnd,color='red', label='Bkgnd',linewidth=2) ax10.axhline(cy3_bgrnd+cy3_thld,color='green', label='Thld',linewidth=2) ax10.axhline(settings['UTD']-cy3_bgrnd,color='black', label='Up Thld',linewidth=2) ax10.legend() ax10.set_title('Donor signal') ax10.set_ylabel('Count, kHz') ax10.set_xlabel('Time, S') ax11 = self.figure1.add_subplot(gs[1,1]) ax11.plot(time,cy5,color='blue',linewidth=0.02,label='Signal') ax11.axhline(cy5_bgrnd,color='red', label='Bkgnd',linewidth=2) ax11.axhline(cy5_bgrnd+cy5_thld,color='green', label='Thld',linewidth=2) ax11.axhline(settings['UTA']-cy5_bgrnd,color='black', label='Up Thld',linewidth=2) ax11.legend() ax11.set_title('Acceptor signal') ax11.set_ylabel('Count, kHz') ax11.set_xlabel('Time, S') self.figure1.tight_layout() self.canvas1.draw() return cy3_bgrnd,cy3_thld,cy5_bgrnd,cy5_thld def plot_single_file(self,(result,settings,name,E)): self.figure.clf() ax = self.figure.add_subplot(111) # result=np.histogram(fret.proximity_ratio(gamma=gamma),np.arange(0,1.05,0.05),normed=True) axis=result[1][:-1]+(result[1][1]-result[1][0])/2.0 ax.plot(axis,result[0],linewidth=3, label='Eff') if (settings['nGausFit']!=0): ms, cs , ws = fit_mixture(E.reshape(E.size,1),settings['nGausFit']) gaus=np.zeros((settings['nGausFit'],axis.size)) for i in range(settings['nGausFit']): gaus[i]=ws[i]*mlab.normpdf(axis,ms[i],cs[i]) ax.plot(axis,gaus[i], linewidth=2, label='Fit ' + str(i) +', Pos '+str(np.round(ms[i],2))+', '+str(np.round(ws[i]*100,2))+'%') ax.plot(axis,gaus.sum(0), linewidth=2,linestyle='--') ax.set_title(os.path.basename(name)) ax.set_ylabel('Amount, %') ax.set_xlabel('FRET Eff') box = ax.get_position() ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9]) #ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.1),ncol=5) if (settings['nGausFit']==0): table=np.vstack((axis,np.round(result[0],4))).transpose() self.tableWidget.buildFromList(np.vstack((['FRET eff.','Amount'],table)),False) else: table=np.vstack((axis,np.round(result[0],4),gaus,gaus.sum(0))).transpose() header= ['FRET eff.','Amount'] [header.append('Fitted ' + str(i)) for i in range(1,settings['nGausFit']+1)] header.append('Fitted Sum') self.tableWidget.buildFromList(np.vstack((header,table)),False) self.tableWidget.addFromList(np.array([[' ']])) gausses= np.array([np.array(ms),np.array(cs).flatten(),np.array(ws)]).T gausses[:,2]*=100 gausses=np.hstack(( np.transpose([np.arange(1,gausses.shape[0]+1)]),gausses )) self.tableWidget.addFromList(np.vstack( ([['#','Position','Sigma','Area, %']],gausses) ).T) self.tableWidget.addFromList(np.array([[' ']])) self.tableWidget.addFromList(np.hstack(([['Settings'],['']],np.array([settings.keys(),[str(qstring) for qstring in settings.values()]])))) #print np.array([settings.keys(),[str(qstring) for qstring in settings.values()]]) self.canvas.draw()