Example #1
0
    def run(self):
        time = QTime()
        eventLoop = QEventLoop()

        self.m_bStop = False

#        log.debug("Запускаем поток")
        #if not self.initThread():
            #return
        while not self.m_bStop:
            self.m_nTactCounter += 1 # Добавить обнуление при переполнении

            time.start()
            eventLoop.processEvents()

            if not self.workThread():
                self.m_bStop = True
                return
            workTime = time.elapsed()
            if 0 <= workTime < self.m_nTact:
                self.msleep(self.m_nTact - workTime)
            else:
                self.msleep(0)

        eventLoop.processEvents()

        self.exitThread()
Example #2
0
    def __init__(self, db, sql, parent=None):
        self.db = db.connector

        t = QTime()
        t.start()
        c = self.db._execute(None, unicode(sql))
        self._secs = t.elapsed() / 1000.0
        del t

        self._affectedRows = 0
        data = []
        header = self.db._get_cursor_columns(c)
        if header is None:
            header = []

        try:
            if len(header) > 0:
                data = self.db._fetchall(c)
            self._affectedRows = c.rowcount
        except DbError:
            # nothing to fetch!
            data = []
            header = []

        BaseTableModel.__init__(self, header, data, parent)

        # commit before closing the cursor to make sure that the changes are stored
        self.db._commit()
        c.close()
        del c
Example #3
0
class MyApplication(QtGui.QApplication):
    def __init__(self, *args, **kwargs):
        super(MyApplication, self).__init__(*args, **kwargs)
        self.t = QTime()
        self.t.start()

        maxlen = 200
        self.data_x = deque(maxlen=maxlen)
        self.data_y = deque(maxlen=maxlen)

        self.win = pg.GraphicsWindow(title="Basic plotting examples")
        self.win.resize(1000, 600)

        tai = TimeAxisItem(orientation='bottom')
        self.plot = self.win.addPlot(
            title='Timed data',
            axisItems={'bottom': TimeAxisItem(orientation='bottom')})
        #self.plot.setYRange(0, 150)
        self.curve = self.plot.plot()

        self.tmr = QTimer()
        self.tmr.timeout.connect(self.update)
        self.tmr.start(100)

        self.y = 100

    def update(self):
        #self.data.append({'x': self.t.elapsed(), 'y': np.random.randint(0, 100)})
        x = now_timestamp()
        self.y = self.y + np.random.uniform(-1, 1)

        self.data_x.append(x)
        self.data_y.append(self.y)
        self.curve.setData(x=list(self.data_x), y=list(self.data_y))
Example #4
0
        def __init__(self, db, sql, parent=None):
                self.db = db.connector

                t = QTime()
                t.start()
                c = self.db._execute(None, unicode(sql))
                self._secs = t.elapsed() / 1000.0
                del t

                self._affectedRows = 0
                data = []
                header = self.db._get_cursor_columns(c)
                if header is None:
                        header = []

                try:
                        if len(header) > 0:
                                data = self.db._fetchall(c)
                        self._affectedRows = c.rowcount
                except DbError:
                        # nothing to fetch!
                        data = []
                        header = []

                BaseTableModel.__init__(self, header, data, parent)

                # commit before closing the cursor to make sure that the changes are stored
                self.db._commit()
                c.close()
                del c
Example #5
0
    def run(self):
        time = QTime()
        eventLoop = QEventLoop()

        self.m_bStop = False

        #        log.debug("Запускаем поток")
        #if not self.initThread():
        #return
        while not self.m_bStop:
            self.m_nTactCounter += 1  # Добавить обнуление при переполнении

            time.start()
            eventLoop.processEvents()

            if not self.workThread():
                self.m_bStop = True
                return
            workTime = time.elapsed()
            if 0 <= workTime < self.m_nTact:
                self.msleep(self.m_nTact - workTime)
            else:
                self.msleep(0)

        eventLoop.processEvents()

        self.exitThread()
Example #6
0
class MyApplication(QtGui.QApplication):
    def __init__(self, *args, **kwargs):
        super(MyApplication, self).__init__(*args, **kwargs)
        self.t = QTime()
        self.t.start()

        self.data = deque(maxlen=20)

        self.win = pg.GraphicsWindow(title="Basic plotting examples")
        self.win.resize(1000, 600)

        self.plot = self.win.addPlot(
            title='Timed data',
            axisItems={'bottom': TimeAxisItem(orientation='bottom')})
        self.curve = self.plot.plot()

        self.tmr = QTimer()
        self.tmr.timeout.connect(self.update)
        self.tmr.start(1000)

    def update(self):
        self.data.append({
            'x': self.t.elapsed() + 1323587062,
            'y': np.random.randint(0, 100)
        })
        x = [item['x'] for item in self.data]
        y = [item['y'] for item in self.data]
        self.curve.setData(x=x, y=y)
Example #7
0
class OpenAnt(QApplication):
    def __init__(self):
        QApplication.__init__(self, sys.argv)

        # Set the default background color to a darker grey.
        self.setPalette(
            QPalette(self.palette().button().color(), QColor(192, 192, 192)))

        self.window = MainWindow()
        self.window.show()
        self.window.start()
        self.window.setWindowTitle('OpenAnt')

        # Game timer, used in the gameloop FPS calculations.
        self.game_timer = QTime()
        self.game_timer.start()

        # Draw map, set view to ground.
        self.map = Map()
        Globals.view = self.map.generateMap()
        self.map.spawnAnts()

        # Start the main loop.
        self.gameLoop()

    def gameLoop(self):
        TICKS_PER_SECOND = 20
        SKIP_TICKS = 1000 / TICKS_PER_SECOND
        MAX_FRAMESKIP = 5

        next_game_tick = self.getTickCount()
        Globals.game_is_running = True
        while Globals.game_is_running:
            loops = 0
            while self.getTickCount(
            ) > next_game_tick and loops < MAX_FRAMESKIP:
                self.updateGame()
                next_game_tick += SKIP_TICKS
                loops += 1
            interpolation = float(self.getTickCount() + SKIP_TICKS -
                                  next_game_tick) / float(SKIP_TICKS)
            self.updateDisplay(interpolation)

    def updateDisplay(self, interpolation):

        #lerp away
        if not 'nolerp' in sys.argv:
            if self.map.yellowAnt.moving:
                self.map.yellowAnt.lerpMoveSimple(interpolation)

        Globals.glwidget.updateGL()
        self.processEvents()  # Let Qt process its events.

    def getTickCount(self):
        return self.game_timer.elapsed()

    def updateGame(self):
        self.map.update()
Example #8
0
class AutoSaver(QObject):
    """
    Class implementing the auto saver.
    """
    AUTOSAVE_IN = 1000 * 3
    MAXWAIT     = 1000 * 15
    
    def __init__(self, parent, save):
        """
        Constructor
        
        @param parent reference to the parent object (QObject)
        @param save slot to be called to perform the save operation
        """
        QObject.__init__(self, parent)
        
        if parent is None:
            raise RuntimeError("AutoSaver: parent must not be None.")
        
        self.__save = save
        
        self.__timer = QBasicTimer()
        self.__firstChange = QTime()
    
    def changeOccurred(self):
        """
        Public slot handling a change.
        """
        if self.__firstChange.isNull():
            self.__firstChange.start()
        
        if self.__firstChange.elapsed() > self.MAXWAIT:
            self.saveIfNeccessary()
        else:
            self.__timer.start(self.AUTOSAVE_IN, self)
    
    def timerEvent(self, evt):
        """
        Protected method handling timer events.
        
        @param evt reference to the timer event (QTimerEvent)
        """
        if evt.timerId() == self.__timer.timerId():
            self.saveIfNeccessary()
        else:
            QObject.timerEvent(self, evt)
    
    def saveIfNeccessary(self):
        """
        Public method to activate the save operation.
        """
        if not self.__timer.isActive():
            return
        
        self.__timer.stop()
        self.__firstChange = QTime()
        self.__save()
Example #9
0
class OpenAnt(QApplication):
    
    def __init__(self):
        QApplication.__init__(self, sys.argv)
        
        # Set the default background color to a darker grey.
        self.setPalette(QPalette(self.palette().button().color(), QColor(192, 192, 192)))
    
        self.window = MainWindow()
        self.window.show()
        self.window.start()
        self.window.setWindowTitle('OpenAnt')
        
        # Game timer, used in the gameloop FPS calculations.
        self.game_timer = QTime()
        self.game_timer.start()
        
        # Draw map, set view to ground.
        self.map = Map()
        Globals.view = self.map.generateMap()
        self.map.spawnAnts()
        
        # Start the main loop.
        self.gameLoop()
        
    def gameLoop(self):
        TICKS_PER_SECOND = 20
        SKIP_TICKS = 1000 / TICKS_PER_SECOND
        MAX_FRAMESKIP = 5
        
        next_game_tick = self.getTickCount()
        Globals.game_is_running = True
        while Globals.game_is_running:
            loops = 0
            while self.getTickCount() > next_game_tick and loops < MAX_FRAMESKIP:
                self.updateGame()
                next_game_tick += SKIP_TICKS
                loops += 1
            interpolation = float(self.getTickCount() + SKIP_TICKS - next_game_tick) / float(SKIP_TICKS)
            self.updateDisplay(interpolation)

    def updateDisplay(self, interpolation):
       
        #lerp away
        if not 'nolerp' in sys.argv:
            if self.map.yellowAnt.moving:
                self.map.yellowAnt.lerpMoveSimple(interpolation)

        Globals.glwidget.updateGL()
        self.processEvents() # Let Qt process its events.

    def getTickCount(self):
        return self.game_timer.elapsed()

    def updateGame(self):
        self.map.update()
Example #10
0
    def __init__(self, db, sql, parent=None):
        # create a virtual layer with non-geometry results
        q = QUrl.toPercentEncoding(sql)
        t = QTime()
        t.start()

        tf = QTemporaryFile()
        tf.open()
        tmp = tf.fileName()
        tf.close()

        p = QgsVectorLayer(
            "%s?query=%s" % (QUrl.fromLocalFile(tmp).toString(), q), "vv",
            "virtual")
        self._secs = t.elapsed() / 1000.0

        if not p.isValid():
            data = []
            header = []
            raise DbError(p.dataProvider().error().summary(), sql)
        else:
            header = [f.name() for f in p.fields()]
            has_geometry = False
            if p.geometryType() != QGis.WKBNoGeometry:
                gn = getQueryGeometryName(tmp)
                if gn:
                    has_geometry = True
                    header += [gn]

            data = []
            for f in p.getFeatures():
                a = f.attributes()
                if has_geometry:
                    if f.geometry():
                        a += [f.geometry().exportToWkt()]
                    else:
                        a += [None]
                data += [a]

        self._secs = 0
        self._affectedRows = len(data)

        BaseTableModel.__init__(self, header, data, parent)
Example #11
0
    def __init__(self, db, sql, parent=None):
        # create a virtual layer with non-geometry results
        q = QUrl.toPercentEncoding(sql)
        t = QTime()
        t.start()

        tf = QTemporaryFile()
        tf.open()
        tmp = tf.fileName()
        tf.close()

        p = QgsVectorLayer("%s?query=%s" % (QUrl.fromLocalFile(tmp).toString(), q), "vv", "virtual")
        self._secs = t.elapsed() / 1000.0

        if not p.isValid():
            data = []
            header = []
            raise DbError(p.dataProvider().error().summary(), sql)
        else:
            header = [f.name() for f in p.fields()]
            has_geometry = False
            if p.geometryType() != QGis.WKBNoGeometry:
                gn = getQueryGeometryName(tmp)
                if gn:
                    has_geometry = True
                    header += [gn]

            data = []
            for f in p.getFeatures():
                a = f.attributes()
                if has_geometry:
                    if f.geometry():
                        a += [f.geometry().exportToWkt()]
                    else:
                        a += [None]
                data += [a]

        self._secs = 0
        self._affectedRows = len(data)

        BaseTableModel.__init__(self, header, data, parent)
Example #12
0
class ScrollCounter(QThread):
    scrollMeasureSignal = pyqtSignal(int, int)
    scrollStartSignal = pyqtSignal()
    scrollStopSignal = pyqtSignal()

    def __init__(self):
        QThread.__init__(self)
        self.running = False
        self.scrollingTimer = QTimer()
        self.scrollingTimer.setSingleShot(True)
        self.scrollingTimer.timeout.connect(self.scrollEventStop)
        self.time = QTime()
        self.counter = 0

    def run(self):
        self.running = True
        while self.running:
            QThread.usleep(100)
            if self.scrollingTimer.isActive():
                self.scrollMeasureSignal.emit(self.time.elapsed(),
                                              self.counter)
        self.running = False

    def stop(self):
        self.running = False

    def scrollEvent(self):
        if not self.scrollingTimer.isActive():
            self.counter = 1
            self.time.start()
            self.scrollStartSignal.emit()
        else:
            self.counter += 1
        self.scrollingTimer.start(200)

    def scrollEventStop(self):
        self.scrollMeasureSignal.emit(self.time.elapsed(), self.counter)
        self.counter = 0
        self.scrollStopSignal.emit()
    def __evaluate(self, query):
        """

        :type query: str
        :return: bool
        """
        t = QTime()
        t.start()

        qDebug("\n(VFK) SQL: {}\n".format(query))
        self.setQuery(query, QSqlDatabase.database(self.__mConnectionName))

        while self.canFetchMore():
            self.fetchMore()

        if t.elapsed() > 500:
            qDebug("\n(VFK) Time elapsed: {} ms\n".format(t.elapsed()))

        if self.lastError().isValid():
            qDebug('\n(VFK) SQL ERROR: {}'.format(self.lastError().text()))
            return False

        return True
    def __evaluate(self, query):
        """

        :type query: str
        :return: bool
        """
        t = QTime()
        t.start()

        qDebug("\n(VFK) SQL: {}\n".format(query))
        self.setQuery(query, QSqlDatabase.database(self.__mConnectionName))

        while self.canFetchMore():
            self.fetchMore()

        if t.elapsed() > 500:
            qDebug("\n(VFK) Time elapsed: {} ms\n".format(t.elapsed()))

        if self.lastError().isValid():
            #qDebug('\n(VFK) SQL ERROR: {}'.format(self.lastError().text()))
            return False

        return True
Example #15
0
class Plot( Qwt.QwtPlot):
    def __init__(self,parent=None):
        Qwt.QwtPlot.__init__(self, parent)
        self.d_time = QTime()
        self.d_curves = []
        self.setAutoReplot( False )
        self.setTitle( "Animated Curves" )

        # hide all axes
        for axis in range(Qwt.QwtPlot.axisCnt):
            self.enableAxis( axis, False )

        #self.plotLayout.setCanvasMargin( 10 )

        self.d_curves.append(Curve1())
        self.d_curves.append(Curve2())
        self.d_curves.append(Curve3())
        self.d_curves.append(Curve4())

        self.updateCurves()

        for i in range(len(self.d_curves)):
            self.d_curves[i].attach( self )
        self.d_time.start()
        self.startTimer( 40 )

    def timerEvent( self, event ):
        self.updateCurves()
        self.replot()

    def updateCurves(self):
        speed = 2 * 3.14159 / 25000.0 # a cycle every 25 seconds

        phase = self.d_time.elapsed() * speed
        for i in range(len(self.d_curves)):
            self.d_curves[i].updateSamples( phase )
Example #16
0
	def importALKIS(self):
		if os.environ.has_key('CPL_DEBUG'):
			self.log( u"Debug-Ausgaben aktiv." )

		files = []
		for i in range(self.lstFiles.count()):
			files.append( self.lstFiles.item(i).text() )

		s = QSettings( "norBIT", "norGIS-ALKIS-Import" )
		s.setValue( "service", self.leSERVICE.text() )
		s.setValue( "host", self.leHOST.text() )
		s.setValue( "port", self.lePORT.text() )
		s.setValue( "dbname", self.leDBNAME.text() )
		s.setValue( "uid", self.leUID.text() )
		s.setValue( "pwd", self.lePWD.text() )
		s.setValue( "gt", self.leGT.text() )
		s.setValue( "files", files )
		s.setValue( "skipfailures", self.cbxSkipFailures.isChecked()==True )
		s.setValue( "usecopy", self.cbxUseCopy.isChecked()==True )

		self.fnbruch = self.cbFnbruch.currentIndex()==0
		s.setValue( "fnbruch", self.fnbruch )

		self.epsg = int( self.cbEPSG.itemData( self.cbEPSG.currentIndex() ) )
		s.setValue( "epsg", self.epsg)

		self.running = True
		self.canceled = False

		self.pbStart.setText( "Abbruch" )
		self.pbStart.clicked.disconnect(self.run)
		self.pbStart.clicked.connect(self.cancel)

		self.pbAdd.setDisabled(True)
		self.pbAddDir.setDisabled(True)
		self.pbRemove.setDisabled(True)
		self.pbLoad.setDisabled(True)
		self.pbSave.setDisabled(True)

		self.lstFiles.itemSelectionChanged.disconnect(self.selChanged)

		QApplication.setOverrideCursor( Qt.WaitCursor )

		while True:
			t0 = QTime()
			t0.start()

			self.loadRe()

			self.lstFiles.clearSelection()

			conn = self.connectDb()
			if conn is None:
				break

			self.log( "Import-Version: 7f82ac2" )

			self.db.exec_( "SET application_name='ALKIS-Import - Frontend'" )
			self.db.exec_( "SET client_min_messages TO notice" )

			qry = self.db.exec_( "SELECT version()" )

			if not qry or not qry.next():
				self.log(u"Konnte PostgreSQL-Version nicht bestimmen!")
				break

			self.log( "Datenbank-Version: %s" % qry.value(0) )

			m = re.search( "PostgreSQL (\d+)\.(\d+)", qry.value(0) )
			if not m:
				self.log(u"PostgreSQL-Version nicht im erwarteten Format")
				break

			if int(m.group(1)) < 8 or ( int(m.group(1))==8 and int(m.group(2))<3 ):
				self.log(u"Mindestens PostgreSQL 8.3 erforderlich")
				break

			qry = self.db.exec_( "SELECT postgis_version()" )
			if not qry or not qry.next():
				self.log(u"Konnte PostGIS-Version nicht bestimmen!")
				break

			self.log( "PostGIS-Version: %s" % qry.value(0) )

			qry = self.db.exec_( "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='public' AND table_name='alkis_importlog'" )
			if not qry or not qry.next():
				self.log( u"Konnte Existenz von Protokolltabelle nicht überprüfen." )
				break

			if int( qry.value(0) ) == 0:
				qry = self.db.exec_( "CREATE TABLE alkis_importlog(n SERIAL PRIMARY KEY, ts timestamp default now(), msg text)" )
				if not qry:
					self.log( u"Konnte Protokolltabelle nicht anlegen [%s]" % qry.lastError().text() )
					break
			elif self.cbxClearProtocol.isChecked():
				qry = self.db.exec_( "TRUNCATE alkis_importlog" )
				if not qry:
					self.log( u"Konnte Protokolltabelle nicht leeren [%s]" % qry.lastError().text() )
					break
				self.cbxClearProtocol.setChecked( False )
				self.log( u"Protokolltabelle gelöscht." )

			qry = self.db.exec_( "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='public' AND table_name='ax_flurstueck'" )
			if not qry or not qry.next():
				self.log( u"Konnte Existenz des ALKIS-Schema nicht überprüfen." )
				break

			if not self.cbxCreate.isChecked():
				if int( qry.value(0) ) == 0:
					self.cbxCreate.setChecked( True )
					self.log( u"Keine ALKIS-Daten vorhanden - Datenbestand muß angelegt werden." )
					break

				if not qry.exec_( "SELECT find_srid('','ax_flurstueck','wkb_geometry')" ) or not qry.next():
					self.log( u"Konnte Koordinatensystem der vorhandenen Datenbank nicht bestimmen." )
					break

				self.epsg = int( qry.value(0) )

			self.logqry = QSqlQuery(self.db)
			if not self.logqry.prepare( "INSERT INTO alkis_importlog(msg) VALUES (?)" ):
				self.log( u"Konnte Protokollierungsanweisung nicht vorbereiten [%s]" % qry.lastError().text() )
				self.logqry = None
				break

			self.ogr2ogr = which("ogr2ogr")
			if not self.ogr2ogr:
				self.ogr2ogr = which("ogr2ogr.exe")

			if not self.ogr2ogr:
				self.log(u"ogr2ogr nicht gefunden!")
				break

			n = self.lwProtocol.count() - 1

			if not self.runProcess([self.ogr2ogr, "--version"]):
				self.log(u"Konnte ogr2ogr-Version nicht abfragen!")
				break

			for i in range(n, self.lwProtocol.count()):
				m = re.search( "GDAL (\d+)\.(\d+)", self.lwProtocol.item( i ).text() )
				if m:
					break

			if not m:
				self.log(u"GDAL-Version nicht gefunden")
				break

			convertToLinear = int(m.group(1)) > 1

			if not self.runProcess([self.ogr2ogr, "--utility_version"]):
				self.log(u"Konnte ogr2ogr-Bibliotheksversion nicht abfragen!")
				break

			self.psql = which("psql")
			if not self.psql:
				self.psql = which("psql.exe")

			if not self.psql:
				self.log(u"psql nicht gefunden!")
				break

			if not self.runProcess([self.psql, "--version"]):
				self.log(u"Konnte psql-Version nicht abfragen!")
				break

			try:
				self.status( u"Bestimme Gesamtgröße des Imports..." )

				self.pbProgress.setVisible( True )
				self.pbProgress.setRange( 0, self.lstFiles.count() )

				sizes={}

				ts = 0
				for i in range(self.lstFiles.count()):
					self.pbProgress.setValue( i )
					item = self.lstFiles.item(i)
					fn = unicode( item.text() )

					if fn[-4:].lower() == ".xml":
						s = os.path.getsize(fn)
						sizes[ fn ] = s

					elif fn[-4:].lower() == ".zip":
						l = -8 if fn[-8:].lower() == ".xml.zip" else -4
						self.status( u"%s wird abgefragt..." % fn )
						app.processEvents()

						f = zipfile.ZipFile(fn, "r")
						il = f.infolist()
						if len(il) <> 1:
							raise ProcessError(u"ZIP-Archiv %s enthält mehr als eine Datei!" % fn)
						s = il[0].file_size
						sizes[ fn[:l] + ".xml" ] = s

					elif fn[-7:].lower() == ".xml.gz":
						self.status( u"%s wird abgefragt..." % fn )

						f = gzip.open(fn)
						s = 0
						while True:
							chunk = f.read( 1024*1024 )
							if not chunk:
								break
							s = s + len( chunk )
						f.close()
						sizes[ fn[:-3] ] = s

					ts += s

					if self.canceled:
						break

				if self.canceled:
					break

				self.pbProgress.setVisible( False )

				self.log( u"Gesamtgröße des Imports: %s" % self.memunits(ts) )

				self.pbProgress.setRange( 0, 10000 )
				self.pbProgress.setValue( 0 )

				self.status( u"Kompatibilitätsfunktionen werden importiert..." )
				if not self.runSQLScript( conn, "alkis-compat.sql" ):
					self.log( u"Import der Kompatibilitätsfunktionen schlug fehl." )
					break

				self.log( u"Kompatibilitätsfunktionen importiert." )

				if self.cbxCreate.isChecked():
					self.status( u"Datenbestand wird angelegt..." )
					if not self.runSQLScript( conn, "alkis-schema.sql" ):
						self.log( u"Anlegen des Datenbestands schlug fehl." )
						break
					self.log( u"Datenbestand angelegt." )

					self.status( u"Präsentationstabellen werden erzeugt..." )
					if not self.runSQLScript( conn, "alkis-po-tables.sql" ):
						self.log( u"Anlegen der Präsentationstabellen schlug fehl." )
						break
					self.log( u"Präsentationstabellen angelegt." )

					self.cbxCreate.setChecked( False )
				else:
					self.status( u"Datenbankschema wird geprüft..." )
					if not self.runSQLScript( conn, "alkis-update.sql" ):
						self.log( u"Schemaprüfung schlug fehl." )
						break

				self.status( u"Signaturen werden importiert..." )
				if not self.runSQLScript( conn, "alkis-signaturen.sql" ):
					self.log( u"Import der Signaturen schlug fehl." )
					break
				self.log( u"Signaturen importiert." )

				ok = True

				self.pbProgress.setVisible( True )

				s = 0
				for i in range(self.lstFiles.count()):
					if self.canceled:
						self.log( "Import abgebrochen." )
						break

					item = self.lstFiles.item(i)
					self.lstFiles.setCurrentItem( item )

					fn = unicode( item.text() )

					src = ""
					if fn[-7:] == ".xml.gz":
						src = fn[:-3]
						size = sizes[ src ]

						self.status( u"%s wird extrahiert." % fn )
						app.processEvents()

						src = os.path.join( tempfile.gettempdir(), os.path.basename(src) )

						f_in = gzip.open(fn)
						f_out = open(src, "wb")
						while True:
							chunk = f_in.read( 1024*1024 )
							if not chunk:
								break

							f_out.write( chunk )

						f_out.close()
						f_in.close()

						self.logDb( u"%s wurde entpackt." % fn )

					elif fn[-4:] == ".zip":
						src = fn[:-4] + ".xml"
						size = sizes[ src ]

						self.status( u"%s wird extrahiert." % fn )
						app.processEvents()

						src = os.path.join( tempfile.gettempdir(), os.path.basename(src) )

						zipf = zipfile.ZipFile(fn, "r")
						f_in = zipf.open( zipf.infolist()[0].filename )
						f_out = open(src, "wb")
						while True:
							chunk = f_in.read( 1024*1024 )
							if not chunk:
								break

							f_out.write( chunk )
						f_out.close()
						f_in.close()
						zipf.close()

						self.logDb( u"%s wurde entpackt." % fn )

					else:
						src = fn
						size = sizes[ fn ]

					try:
						os.unlink( src[:-4] + ".gfs" )
					except OSError, e:
						pass

					#if size==623 or size==712:
					#	item.setSelected( True )
					#	self.log( u"Kurze Datei %s übersprungen." % fn )
					#	continue

					if self.epsg==131466 or self.epsg==131467 or self.epsg==131468:
						srs = "+init=custom:%d" % self.epsg
						os.putenv( "PROJ_LIB", "." )
					else:
						srs = "EPSG:%d" % self.epsg

					args = [self.ogr2ogr,
						"-f", "PostgreSQL",
						"-append",
						"-update",
						"PG:%s" % conn,
						"-a_srs", srs,
						"-gt", self.leGT.text()
						]

					if self.cbxSkipFailures.isChecked():
						args.append("-skipfailures")

					if self.cbxUseCopy.isChecked():
						args.extend( ["--config", "PG_USE_COPY", "YES" ] )

					if convertToLinear:
						args.extend( ["-nlt", "CONVERT_TO_LINEAR" ] )

					args.append(src)

					self.status( u"%s mit %s wird importiert..." % (fn, self.memunits(size) ) )

					t1 = QTime()
					t1.start()

					ok = self.runProcess(args)

					elapsed = t1.elapsed()

					if elapsed>0:
						throughput = " (%s/s)" % self.memunits( size * 1000 / elapsed )
					else:
						throughput = ""

					self.log( u"%s mit %s in %s importiert%s" % (
							fn,
							self.memunits( size ),
							self.timeunits( elapsed ),
							throughput
						) )

					item.setSelected( ok )
					if src <> fn and os.path.exists(src):
						os.unlink( src )

					s = s + size
					self.pbProgress.setValue( 10000 * s / ts )

					remaining_data = ts - s
					remaining_time = remaining_data * t0.elapsed() / s

					self.alive.setText( "Noch %s in etwa %s\nETA: %s -" % (
								self.memunits( remaining_data ),
								self.timeunits( remaining_time ),
								QDateTime.currentDateTime().addMSecs( remaining_time ).toString( Qt.ISODate )
							) )

					app.processEvents()

					if not ok:
						self.status( u"Fehler bei %s." % fn )
						break

				self.pbProgress.setValue( 10000 )
				self.pbProgress.setVisible( False )

				if ok and self.lstFiles.count()>0:
					self.log( u"Alle NAS-Dateien importiert." )

				if ok:
					self.status( u"Ableitungsregeln werden verarbeitet..." )
					ok = self.runSQLScript( conn, "alkis-ableitungsregeln.sql" )
					if ok:
						self.log( u"Ableitungsregeln verarbeitet." )

				if ok:
					for f in glob.glob("postprocessing.d/*.sql"):
						self.status( u"Nachverarbeitungsskript %s wird gestartet..." % f )
						ok = self.runSQLScript( conn, f )
						if ok:
							self.log( u"Nachverarbeitungsskript %s ausgeführt." % f )

				if ok:
					self.status( u"VACUUM..." )
					ok = self.db.exec_( "VACUUM" )
					if ok:
						self.log( u"VACUUM abgeschlossen." )

				if ok:
					self.log( u"Import nach %s erfolgreich beendet." % self.timeunits( t0.elapsed() ) )
				else:
					self.log( u"Import nach %s abgebrochen." % self.timeunits( t0.elapsed() ) )

			except Exception, e:
				exc_type, exc_value, exc_traceback = sys.exc_info()
				err = u"\n> ".join( traceback.format_exception( exc_type, exc_value, exc_traceback ) )
				if sys.stdout:
					print err
				self.log( u"Abbruch nach Fehler\n> %s" % unicode(err) )
Example #17
0
class Window(QtGui.QMainWindow):
    def __init__(self):
        super(Window,self).__init__()
        self.setGeometry(50,50,500,300)
        self.setWindowTitle("Respiratory analysis")
        self.ser=serial.Serial('COM35',4800)
        self.menu()
        self.home()
    def menu(self):
        #--------------------Complete Menus------------------
        mainMenu=self.menuBar()
        mainMenu.setStatusTip('Select Options from main menu')
        fileMenu=mainMenu.addMenu('&File')
        fileMenu.setStatusTip('Select Options from File Menu')
        windowMenu=mainMenu.addMenu('&Plot')
        windowMenu.setStatusTip('Select Options from Window Menu')
        connectionMenu=mainMenu.addMenu('&Connection')
        connectionMenu.setStatusTip('Select Options from Connection Menu')
        helpMenu=mainMenu.addMenu('&Help')
        helpMenu.setStatusTip('Select for help')
        #----------------File Menus--------------------------------------
        #--------------Exit Action---------------------------------------
        exitAction=QtGui.QAction("&Exit",self)
        exitAction.setShortcut("Ctrl + Q")
        exitAction.setStatusTip("Leave the Application")
        exitAction.triggered.connect(self.close_application)
        fileMenu.addAction(exitAction)
        #---------------------------------------------------
        #----------------------------------------------------------------
        #-----------------Plot Menus-----------------------------------
        #----------------------------------------------------------------
        zoomin=QtGui.QAction('&Zoom In',self)
        zoomin.setStatusTip("Click to Zoom In")
        zoomin.setShortcut("Ctrl + =")
        zoomin.triggered.connect(self.zoom_in)
        windowMenu.addAction(zoomin)
        zoomout=QtGui.QAction('&Zoom Out',self)
        zoomout.setStatusTip("Click to Zoom Out")
        zoomout.setShortcut("Ctrl + -")
        zoomout.triggered.connect(self.zoom_out)
        windowMenu.addAction(zoomout)
        #----------------------------------------------------------------
        #----------------------------------------------------------------
        #----------------Connection Menus--------------------------------
        #----------------COM Ports---------------------------------------
        comMenu=connectionMenu.addMenu('&COM Ports')
        com=list(serial.tools.list_ports.comports())
        for i in range(len(com)):
            comAction=QtGui.QAction('&'+com[i][0],self)
            comAction.setStatusTip("Click to connect to "+com[i][0]+" Port")
            comAction.triggered.connect(self.establish_conn)
            comMenu.addAction(comAction)
        self.statusBar()
    def establish_conn(self,name):
        print(name)
    def zoom_in(self):
        self.ylow=self.ylow+100
        self.yhigh=self.yhigh-100
        self.p1.setYRange(self.ylow,self.yhigh)
    def zoom_out(self):
        self.ylow=self.ylow-100
        self.yhigh=self.yhigh+100
        self.p1.setYRange(self.ylow,self.yhigh)
    def home(self):
        self.splitter1=QtGui.QSplitter(Qt.Vertical,self)
        self.splitter2=QtGui.QSplitter(Qt.Vertical,self)
        self.wid=QtGui.QWidget()
        self.setCentralWidget(self.wid)
        self.hbox=QtGui.QHBoxLayout()
        self.vbox=QtGui.QVBoxLayout()
        self.wid.setLayout(self.hbox)
        self.hbox.addLayout(self.vbox)
        self.resize(1000,800)
        self.data1=deque(maxlen=1000)
        self.data=[]
        self.t=QTime()
        self.t.start()
        self.timer1=QtCore.QTimer()
        self.timer1.timeout.connect(self.update)
        self.timer2=QtCore.QTimer()
        self.timer2.timeout.connect(self.read_data)
        self.timer3=QtCore.QTimer()
        self.timer3.timeout.connect(self.stats)
        for i in range(2000):
            self.data1.append({'x':self.t.elapsed(),'y': 0})
        #----------------Left pane--------------------------
        #----------------Adding Plot------------------------
        self.p1=pg.PlotWidget(name="Raw",title="Respiration Plot",labels={'left':("Thoracic Circumference in (cm)"),'bottom':("Time Elapsed (mm:ss)")},enableMenu=True,axisItems={'bottom': TimeAxisItem(orientation='bottom')})
        self.p1.addLegend(offset=(450,30))
        self.p1.showGrid(x=True,y=True,alpha=0.5)
        self.p1.setMouseEnabled(x=True,y=True)
        self.curve=self.p1.plot(pen='y',name="Raw Respiration Data")
        self.curve1=self.p1.plot(pen='r',name="Filtered Respiration DAta")
        self.ylow=600
        self.yhigh=800
        self.p1.setYRange(self.ylow,self.yhigh)
        #----------------------------------------------------
        self.statistics=QtGui.QGroupBox()
        self.statistics.setTitle("Statistics")
        self.stlabel1=QtGui.QLabel("Mean Value\t\t\t:",self.statistics)
        self.stlabel1.move(5,40)
        self.stlabel2=QtGui.QLabel("Variance\t\t\t\t:",self.statistics)
        self.stlabel2.move(280,40)
        self.stlabel3=QtGui.QLabel("Respiration Rate (per min)\t\t:",self.statistics)
        self.stlabel3.move(5,70)
        self.stlabel4=QtGui.QLabel("Average Breath Duration (mins)\t:",self.statistics)
        self.stlabel4.move(280,70)
        self.stlabel5=QtGui.QLabel("Variance in Breath Duration (mins)\t:",self.statistics)
        self.stlabel5.move(5,100)
        self.stlabel6=QtGui.QLabel("Statistical Dispersion\t\t:",self.statistics)
        self.stlabel6.move(280,100)
        self.stlabel7=QtGui.QLabel("Average Normalized Tidal Volume\t:",self.statistics)
        self.stlabel7.move(5,130)
        self.stlabel8=QtGui.QLabel("Variance in Normalized Tidal Volume\t:",self.statistics)
        self.stlabel8.move(280,130)
        self.stlabel9=QtGui.QLabel("Average Respiration Width\t\t:",self.statistics)
        self.stlabel9.move(5,160)
        self.stlabel10=QtGui.QLabel("Variance in Respiration Width\t\t:",self.statistics)
        self.stlabel10.move(280,160)
        self.stlabelmean=QtGui.QLabel("0",self.statistics)
        self.stlabelmean.move(205,40)
        self.stlabelmean.resize(200,20)
        self.stlabelvariance=QtGui.QLabel("0",self.statistics)
        self.stlabelvariance.move(485,40)
        self.stlabelvariance.resize(200,20)
        self.stlabelrrate=QtGui.QLabel("0",self.statistics)
        self.stlabelrrate.move(205,70)
        self.stlabelrrate.resize(200,20)
        self.stlabelabd=QtGui.QLabel("0",self.statistics)
        self.stlabelabd.move(485,70)
        self.stlabelabd.resize(200,20)
        self.stlabelvbd=QtGui.QLabel("0",self.statistics)
        self.stlabelvbd.move(205,100)
        self.stlabelvbd.resize(200,20)
        self.stlabelsd=QtGui.QLabel("0",self.statistics)
        self.stlabelsd.move(485,100)
        self.stlabelsd.resize(200,20)
        self.stlabelatv=QtGui.QLabel("0",self.statistics)
        self.stlabelatv.move(205,130)
        self.stlabelatv.resize(200,20)
        self.stlabelvtv=QtGui.QLabel("0",self.statistics)
        self.stlabelvtv.move(485,130)
        self.stlabelvtv.resize(200,20)
        self.stlabelarw=QtGui.QLabel("0",self.statistics)
        self.stlabelarw.move(205,160)
        self.stlabelarw.resize(200,20)
        self.stlabelvrw=QtGui.QLabel("0",self.statistics)
        self.stlabelvrw.move(485,160)
        self.stlabelvrw.resize(200,20)
        #----------------------------------------------------
        self.apneagb=QtGui.QGroupBox()
        self.apneagb.setTitle("Apnea")
        self.apnealabel1=QtGui.QLabel("Apnea Event Detected",self.apneagb)
        self.apnealabel1.resize(150,20)
        self.apnealabel1.move(30,30)
        self.apnealabel2=QtGui.QLabel("No",self.apneagb)
        self.apnealabel2.resize(150,20)
        self.apnealabel2.move(80,50)
        self.apnealabel3=QtGui.QLabel("Total Apnea Events",self.apneagb)
        self.apnealabel3.resize(150,20)
        self.apnealabel3.move(30,70)
        self.apnealabel4=QtGui.QLabel("0",self.apneagb)
        self.apnealabel4.resize(150,20)
        self.apnealabel4.move(80,90)
        #----------------Plot GroupBox---------------------------
        self.groupBox=QtGui.QGroupBox()
        self.groupBox.setTitle("Plot")
        self.label3=QtGui.QLabel("Y-Low  :",self.groupBox)
        self.label3.move(5,20)
        self.label4=QtGui.QLabel("Y-High :",self.groupBox)
        self.label4.move(150,20)
        self.slider3=QtGui.QSlider(self.groupBox)
        self.slider3.setOrientation(QtCore.Qt.Horizontal)
        self.slider3.move(50,20)
        self.slider3.valueChanged[int].connect(self.setylow)
        self.slider4=QtGui.QSlider(self.groupBox)
        self.slider4.setOrientation(QtCore.Qt.Horizontal)
        self.slider4.move(195,20)
        self.slider4.valueChanged[int].connect(self.setyhigh)
        self.pb1=QtGui.QPushButton("Resume",self.groupBox)
        self.pb1.move(60,50)
        self.pb1.clicked.connect(self.plot_resume)
        self.pb2=QtGui.QPushButton("Pause",self.groupBox)
        self.pb2.move(150,50)
        self.pb2.clicked.connect(self.plot_pause)
        #--------------------------------------------------------------
        #---------------Signal-Processing-GroupBox---------------------
        self.sp=QtGui.QGroupBox()
        self.sptab=QtGui.QTabWidget(self.sp)
        self.sptab.setGeometry(QtCore.QRect(10,20,270,120))
        self.tab1=QtGui.QWidget()
        self.sp.setTitle("Signal Processing")
        self.splabel2=QtGui.QLabel("Normalized Cutoff Frequency\t:\tHz",self.tab1)
        self.splabel2.move(5,10)
        self.l1=QtGui.QLineEdit(self.tab1)
        self.l1.setGeometry(QtCore.QRect(160,10,31,20))
        self.splabel3=QtGui.QLabel("Order of Filter\t\t:\tHz",self.tab1)
        self.splabel3.move(5,35)
        self.l2=QtGui.QLineEdit(self.tab1)
        self.l2.setGeometry(QtCore.QRect(160,35,31,20))
        self.sb1=QtGui.QPushButton("Apply",self.tab1)
        self.sb1.move(40,60)
        self.sb1.clicked.connect(self.low_pass)
        self.sptab.addTab(self.tab1,"Low Pass Filter")
        self.tab2=QtGui.QWidget()
        self.splabel7=QtGui.QLabel("Window Size:	    samples",self.tab2)
        self.splabel7.move(5,10)
        self.l5=QtGui.QLineEdit(self.tab2)
        self.l5.setGeometry(QtCore.QRect(75,10,31,20))
        self.sb2=QtGui.QPushButton("Apply",self.tab2)
        self.sb2.move(30,40)
        self.sb2.clicked.connect(self.moving_average)
        self.sb3=QtGui.QPushButton("Remove",self.tab1)
        self.sb3.move(120,60)
        self.sb3.clicked.connect(self.remove_lowpass)
        self.sb4=QtGui.QPushButton("Remove",self.tab2)
        self.sb4.move(130,40)
        self.sptab.addTab(self.tab2,"Moving Average")
        #--------------------------------------------------------------
        #--------------Pneumonia Detection-----------------------------
        self.pneumonia=QtGui.QGroupBox()
        self.pneumonia.setTitle("Pneumonia Detection")
        self.plabel1=QtGui.QLabel("Enter the Age :	        yrs",self.pneumonia)
        self.plabel1.move(70,25)
        self.pl1=QtGui.QLineEdit(self.pneumonia)
        self.pl1.setGeometry(QtCore.QRect(150,25,35,20))
        self.pb1=QtGui.QPushButton("Detect",self.pneumonia)
        self.pb1.move(115,50)
        self.pb1.clicked.connect(self.detect_pneumonia)
        self.plabel2=QtGui.QLabel("Symptoms of Pneumonia :",self.pneumonia)
        self.plabel2.move(70,85)
        self.plabelpneumonia=QtGui.QLabel("No",self.pneumonia)
        self.plabelpneumonia.move(200,85)
        #--------------------------------------------------------------
        #--------------Database Connection-----------------------------
        self.databaseg=QtGui.QGroupBox()
        self.databaseg.setTitle("Dashboard")
        self.dlabel1=QtGui.QLabel("Name\t\t:",self.databaseg)
        self.dlabel1.move(5,15)
        self.dText1=QtGui.QLineEdit(self.databaseg)
        self.dText1.move(120,15)
        self.dlabel2=QtGui.QLabel("Date of Birth\t:",self.databaseg)
        self.dlabel2.move(5,45)
        self.dateEdit=QtGui.QDateEdit(self.databaseg)
        self.dateEdit.setGeometry(QtCore.QRect(120,40,133,22))
        self.dlabel3=QtGui.QLabel("Start Saving to\t:",self.databaseg)
        self.dlabel3.move(5,152)
        self.dlabel4=QtGui.QLabel("Respiration plot\t:",self.databaseg)
        self.dlabel4.move(5,80)
        self.dpb1=QtGui.QCheckBox("Local",self.databaseg)
        self.dpb1.move(120,152)
        self.dpb2=QtGui.QCheckBox("Cloud",self.databaseg)
        self.dpb2.move(200,152)
        self.dpb6=QtGui.QPushButton("Start",self.databaseg)
        self.dpb6.move(120,180)
        self.dpb6.clicked.connect(self.database_startsaving)
        self.dpb3=QtGui.QPushButton("Stop",self.databaseg)
        self.dpb3.move(200,180)
        self.dpb3.clicked.connect(self.database_stopsaving)
        self.dpb4=QtGui.QPushButton("Start",self.databaseg)
        self.dpb4.move(120,75)
        self.dpb4.clicked.connect(self.database_startplot)
        self.dpb5=QtGui.QPushButton("Stop",self.databaseg)
        self.dpb5.move(200,75)
        self.dpb5.clicked.connect(self.database_stopplot)
        self.dlabel5=QtGui.QLabel("Tools\t\t:",self.databaseg)
        self.dlabel5.move(5,115)
        self.dpb7=QtGui.QPushButton("Calibrate",self.databaseg)
        self.dpb7.move(120,112)
        self.dpb7.clicked.connect(self.database_calibrate)
        self.dpb8=QtGui.QPushButton("Analyze",self.databaseg)
        self.dpb8.move(200,112)
        self.dpb8.clicked.connect(self.database_analyze)
        #------------------------------------------------------
        #---------------------Arranging Splitters---------------
        self.vbox2=QtGui.QVBoxLayout()
        self.splitter3=QtGui.QSplitter(self)
        self.splitter4=QtGui.QSplitter(self)
        self.splitter1.addWidget(self.p1)
        self.splitter4.addWidget(self.statistics)
        self.splitter4.addWidget(self.apneagb)
        self.splitter1.addWidget(self.splitter4)
        self.vbox.addWidget(self.splitter3)
        self.splitter2.addWidget(self.groupBox)
        self.splitter2.addWidget(self.databaseg)
        self.splitter2.addWidget(self.sp)
        self.splitter2.addWidget(self.pneumonia)
        self.splitter3.addWidget(self.splitter1)
        self.splitter3.addWidget(self.splitter2)
        self.splitter2.setSizes([80,200,200,160])
        self.splitter3.setSizes([1000,420])
        self.splitter1.setSizes([500,260])
        self.splitter4.setSizes([100,10])
        self.lowpass_flag=0
        #-------------------------------------------------------
        self.show()

    def setylow(self,value):
        self.ylow=value*1024/100
        self.p1.setYRange(self.ylow,self.yhigh)
    def setyhigh(self,value):
        self.yhigh=value*1024/100
        self.p1.setYRange(self.ylow,self.yhigh)
    def update(self):
            x=[item['x'] for item in self.data1]
            y=[item['y'] for item in self.data1]
            if(self.lowpass_flag==1):
                y1=self.butter_lowpass_filter(y,self.cutoff,10,self.order)
                self.curve1.setData(x=x,y=y1)
            self.curve.setData(x=x,y=y)
            
    def plot_resume(self):
        self.timer1.start(100)
    def plot_pause(self):
        self.timer1.stop()
    def low_pass(self):
        self.lowpass_flag=1
        self.cutoff=float(self.l1.text())
        self.order=float(self.l2.text())
    def remove_lowpass(self):
        self.lowpass_flag=0
        self.curve1.clear()
    def moving_average(self):
        print("Clicked Moving Average")
    def detect_pneumonia(self):
        print("Detect Pneumonia Clicked")
    def database_local(self):
        print("Database Local")
    def database_cloud(self):
        print("Database Cloud")
    def database_startplot(self):
        self.t.restart()
        self.timer1.start(50)
        self.timer2.start(4)
        self.timer3.start(30000)
    def database_stopplot(self):
        self.timer1.stop()
        self.timer2.stop()
        self.timer3.stop()
    def database_startsaving(self):
        print("Database start saving")
    def database_stopsaving(self):
        print("Database stop saving")
    def database_calibrate(self):
        print("Database calibrate")
    def database_analyze(self):
        print("Database Analyze")
    def read_data(self):
        #data=np.random.randint(600,700)
        data=int(self.ser.readline()[0:4])
        self.data.append(data)
        self.data1.append({'x':self.t.elapsed(),'y':data})
    def stats(self):
        resp_rate=[]
        total_tidal_volume=[]
        self.data2=self.butter_lowpass_filter(self.data,0.7,len(self.data)/30,6)
        self.data2=np.array(self.data2)
        self.mean=np.mean(self.data2)
        self.stlabelmean.setText(str(round(self.mean,2)))
        self.variance=np.var(self.data2)
        self.stlabelvariance.setText(str(round(self.variance,2)))
        new_data=self.data2-self.mean
        zero_crossings=np.where(np.diff(np.sign(new_data)))[0]
        self.respirationrate=(zero_crossings.size)
        self.stlabelrrate.setText(str(round(self.respirationrate,2)))
        local_maxima=argrelextrema(self.data2,np.greater)[0]
        local_minima=argrelextrema(self.data2,np.less)[0]
        tenp=np.percentile(self.data2,10)
        nintyp=np.percentile(self.data2,90)
        diff_local_maxima=np.diff(local_maxima)
        self.average_breath_duration=np.mean(diff_local_maxima)
        self.stlabelabd.setText(str(round(self.average_breath_duration*0.5/len(self.data2),2)))
        self.var_breath_duration=np.var(diff_local_maxima)
        self.stlabelvbd.setText(str(round(self.var_breath_duration*0.5/len(self.data2),2)))
        self.dispersion=nintyp-tenp
        self.stlabelsd.setText(str(round(self.dispersion,2)))
        tidal_volume=[]
        for i in range(local_minima.size-1):
            maxima=np.where(np.logical_and(local_maxima>=local_minima[i],local_maxima<=local_minima[i+1]))[0]
            if(maxima.size>0):
                volume=self.data2[local_maxima[maxima[0]]]-((self.data2[local_minima[i]]+self.data2[local_minima[i+1]])/2)
                tidal_volume.append(volume)
        self.average_tidal_volume=np.mean(tidal_volume)
        self.variant_tidal_volume=np.var(tidal_volume)
        self.stlabelatv.setText(str(round(self.average_tidal_volume,2)))
        self.stlabelvtv.setText(str(round(self.variant_tidal_volume,2)))
        intdata1=[self.data2[x] for x in local_maxima]
        intdata2=[self.data2[x] for x in local_minima]
        f1=interp1d(local_maxima,intdata1,kind='cubic')
        f2=interp1d(local_minima,intdata2,kind='cubic')
        xmin=max(local_maxima[0],local_minima[0])
        xmax=min(local_maxima[len(local_maxima)-1],local_minima[len(local_minima)-1])
        xnew=np.linspace(xmin,xmax)
        width=f1(xnew)-f2(xnew)
        self.average_width=np.mean(width)
        self.var_width=np.var(width)
        self.stlabelarw.setText(str(round(self.average_width,2)))
        self.stlabelvrw.setText(str(round(self.var_width,2)))
        print(self.mean)
        self.data.clear()
    def butter_lowpass(self,cutoff,fs,order=5):
        nyq=0.5*fs
        normal_cutoff=cutoff/nyq
        b,a=butter(order,normal_cutoff,btype='low',analog=False)
        return b,a
    def butter_lowpass_filter(self,data,cutoff,fs,order=5):
        b,a=self.butter_lowpass(cutoff,fs,order=order)
        y=lfilter(b,a,data)
        return y
    def close_application(self):
         sys.exit()
Example #18
0
class Game(QObject):
    """Container to hold one new or loaded game instance"""
    FRAME_RATE = 25 # Frame rate in frames per second.
    
    def __init__(self):
        """Game Instance responsible For all non visual work"""
        
        # Keep track of how long we have been playing.
        self.gameTime = None
        self.frameTimer = QTimer()
        
        # Manage Character
        self.character = None
        
        # Manage Game Progression
        self.story = Story(self.FRAME_RATE)
        
        # Manage World
        self.places = Places()
        
        # Store player's name
        self.playerName = ""
        
        # Store scores from previous play
        self.scoreList = []
        self.topTen = True
        
    def new(self):
        """Load new game from file"""
        debug("newgame...loading clues")
        self.story.loadClues()
        debug("newgame...loading charcter")
        self.character = Character((0,0), "Character", "Character")
        debug("newgame...loading places")
        self.places.loadLoc()
        debug("end of load")
        self.places.addLoc(self.character)
        self.story.currClue = self.story._clueList.pop()
        #self.frameTimer = QTimer() # Create Frame Timer
        self.gameTime = QTime()
        self.launch()
        
    def load(self,filename):
        """Load existing game from file"""
        
        debug("loadgame...read data from saved file")
        debug("loadgame...loading clues")
        self.story.loadClues()
        
        savedData = open(filename)    
        nextLine = savedData.readline()
        # Parsing saved file
        while (nextLine):
            line = nextLine.split()
            if (len(line) == 5 and self.loadIsValid(line)):
                x = int(line[0])
                y = int(line[1])
                numClues = int(line[2])+1
                self.story._clueList =  self.story._clueList[:numClues]
                self.story.score = int(line[3])
                self.playerName = line[4]
            nextLine = savedData.readline()       
        savedData.close()
        self.story.currClue = self.story._clueList.pop()
        
        debug("loadgame...loading initial character and places")
        self.character = Character((x,y), "Character", "Character")
        self.places.loadLoc()
        
        debug("end of load")
        self.places.addLoc(self.character)
        # FIXME if QTime and QTimer should be stored in certain way
        self.gameTime = QTime()
        #self.frameTimer = QTimer() # Create Frame Timer
        self.launch()
      
    def loadIsValid(self,obj):
        """Check that the input from saved file is valid"""         
        posx = obj[0]
        posy = obj[1]
        numClue = obj[2]
        score = obj[3]
        try:
            int(posx) and int(posy) and int(numClue) and int(score)
        except:
            debug("Invalid position input in save file")
            return False
        return True
    
    def loadScores(self, filename = "saves/player.score"):
        """load the 10 highest score from file"""
        scoreData = open(filename)    
        nextLine = scoreData.readline()
        # Parsing saved file
        while (nextLine):
            prevScore = nextLine.strip().split(";")
            if (len(prevScore) == 2):
                loadedName = prevScore[0]
                loadedScore = int(prevScore[1])
                self.scoreList.append((loadedName, loadedScore))
            nextLine = scoreData.readline()       
        scoreData.close()
        self.addCurrScoreToList()
    
    def addCurrScoreToList(self):
        """save player's score into top 10 list if the player make it"""
        listLen = len(self.scoreList)
        lowestScore = 0
        
        if (listLen > 0):
            lowestScore = self.scoreList[-1][1]
        if (self.story.score <= lowestScore and listLen > 9):
            debug("player's score is not high enough to write to file")
            self.topTen = False
            return
        elif listLen < 10:
            debug("Player score append to scoreList")
            self.scoreList.append((self.playerName, self.story.score))
        else:
            debug("Pop the bad score, and add in player score to file")
            self.scoreList.pop()
            self.scoreList.append((self.playerName, self.story.score))
        # sorted previous player by score
        self.scoreList = sorted(self.scoreList, \
                                key = itemgetter(1), reverse = True) 
        
    def writeScoreToFile(self, filename = "saves/player.score"):
        """Save the 10 highest score to file.."""
        text = ""
        if (len(self.scoreList)<=10):
            scoreFile = open(filename, "w")
            while (self.scoreList):
                scores = self.scoreList.pop()
                text = text + scores[0] + ";" + `scores[1]` + "\n"
            scoreFile.write(text)
            scoreFile.close()
        else:
            print "Error: Too many scores to be stored in scoreList"
            return    
        
    def save(self, filename):
        """Save to file"""
        fname = open(filename, "w")
        score = `self.story.score`
        numClues = `len(self.story._clueList)`
        charX, charY = self.character.getCenter()
        name = self.playerName
        toWriteList = '\t' + `charX` + '\t' + `charY` + '\t' \
                       + numClues + '\t'+ score + '\t'+ name
        fname.write(toWriteList)     
        fname.close()
            
    def endGame(self):
        """Make things tidy for another game instance"""
        # Signal that we have won the game and should
        None
    
    def launch(self):
        """Start sending signals to the game using Timers"""
        self.gameTime.start()
        self.frameTimer.start(ONE_SECOND/self.FRAME_RATE)
        self.frameTimer.timeout.connect(self.story.frameTime)
        
    def keyPress(self, event):
        """Recieve events from keyboard, pass to update character movement"""
        key = event.key()
        self.character.keyPress(key)
        
    def keyRelease(self, event):
        """Recieve events from keyboard, pass to update character movement"""
        key = event.key()
        self.character.keyRelease(key)
Example #19
0
class PollingKeyboardMonitor(AbstractKeyboardMonitor):
    """
    Monitor the keyboard for state changes by constantly polling the keyboard.
    """

    #: default polling interval
    DEFAULT_POLLDELAY = 200
    #: size of the X11 keymap array
    _KEYMAP_SIZE = 32

    def __init__(self, parent=None):
        AbstractKeyboardMonitor.__init__(self, parent)
        self._keyboard_was_active = False
        self._old_keymap = array(b'B', b'\0' * 32)
        self._keyboard_timer = QTimer(self)
        self._keyboard_timer.timeout.connect(self._check_keyboard_activity)
        self._keyboard_timer.setInterval(self.DEFAULT_POLLDELAY)
        self._activity = QTime()
        self._keys_to_ignore = self.IGNORE_NO_KEYS
        self._keymap_mask = self._setup_mask()
        self._idle_time = self.DEFAULT_IDLETIME

    @property
    def is_running(self):
        return self._keyboard_timer.isActive()

    def start(self):
        self._keyboard_timer.start()
        self.started.emit()

    def stop(self):
        AbstractKeyboardMonitor.stop(self)
        self._keyboard_timer.stop()
        self.stopped.emit()

    @property
    def keys_to_ignore(self):
        return self._keys_to_ignore

    @keys_to_ignore.setter
    def keys_to_ignore(self, value):
        if not (self.IGNORE_NO_KEYS <= value <= self.IGNORE_MODIFIER_COMBOS):
            raise ValueError('unknown constant for keys_to_ignore')
        self._keys_to_ignore = value
        self._keymap_mask = self._setup_mask()

    @property
    def idle_time(self):
        return self._idle_time / 1000

    @idle_time.setter
    def idle_time(self, value):
        self._idle_time = int(value * 1000)

    def _setup_mask(self):
        mask = array(b'B', b'\xff' * 32)
        if self._keys_to_ignore >= self.IGNORE_MODIFIER_KEYS:
            modifier_mappings = xlib.get_modifier_mapping(self.display)
            for modifier_keys in modifier_mappings:
                for keycode in modifier_keys:
                    mask[keycode // 8] &= ~(1 << (keycode % 8))
        return mask

    @property
    def keyboard_active(self):
        is_active = False

        _, raw_keymap = xlib.query_keymap(self.display)
        keymap = array(b'B', raw_keymap)

        is_active = keymap != self._old_keymap
        for new_state, old_state, mask in izip(keymap, self._old_keymap,
                                               self._keymap_mask):
            is_active = new_state & ~old_state & mask
            if is_active:
                break

        if self._keys_to_ignore == self.IGNORE_MODIFIER_COMBOS:
            for state, mask in izip(keymap, self._keymap_mask):
                if state & ~mask:
                    is_active = False
                    break

        self._old_keymap = keymap
        return is_active

    def _check_keyboard_activity(self):
        if self.keyboard_active:
            self._activity.start()
            if not self._keyboard_was_active:
                self._keyboard_was_active = True
                self.typingStarted.emit()
        elif self._activity.elapsed() > self._idle_time and \
                 self._keyboard_was_active:
            self._keyboard_was_active = False
            self.typingStopped.emit()
Example #20
0
    def importALKIS(self):
        if self.cbxDebug.isChecked():
            self.log(u"Debug-Ausgaben aktiv.")
            os.putenv("CPL_DEBUG", "ON")
        else:
            os.unsetenv("CPL_DEBUG")

        files = []
        for i in range(self.lstFiles.count()):
            files.append(self.lstFiles.item(i).text())

        s = QSettings("norBIT", "norGIS-ALKIS-Import")
        s.setValue("service", self.leSERVICE.text())
        s.setValue("host", self.leHOST.text())
        s.setValue("port", self.lePORT.text())
        s.setValue("dbname", self.leDBNAME.text())
        s.setValue("uid", self.leUID.text())
        s.setValue("pwd", self.lePWD.text())
        s.setValue("files", files)
        s.setValue("skipfailures", self.cbxSkipFailures.isChecked() == True)
        s.setValue("debug", self.cbxDebug.isChecked() == True)

        self.fnbruch = self.cbFnbruch.currentIndex() == 0
        s.setValue("fnbruch", self.fnbruch)

        self.epsg = int(self.cbEPSG.itemData(self.cbEPSG.currentIndex()))
        s.setValue("epsg", self.epsg)

        self.running = True
        self.canceled = False

        self.pbStart.setText("Abbruch")
        self.pbStart.clicked.disconnect(self.run)
        self.pbStart.clicked.connect(self.cancel)

        self.pbAdd.setDisabled(True)
        self.pbAddDir.setDisabled(True)
        self.pbRemove.setDisabled(True)
        self.pbLoad.setDisabled(True)
        self.pbSave.setDisabled(True)

        self.lstFiles.itemSelectionChanged.disconnect(self.selChanged)

        QApplication.setOverrideCursor(Qt.WaitCursor)

        while True:
            t0 = QTime()
            t0.start()

            self.loadRe()

            self.lstFiles.clearSelection()

            conn = self.connectDb()
            if conn is None:
                break

            qry = self.db.exec_(
                "SET application_name='ALKIS-Import - Frontend")

            qry = self.db.exec_("SELECT version()")

            if not qry or not qry.next():
                self.log(u"Konnte PostgreSQL-Version nicht bestimmen!")
                break

            self.log("Datenbank-Version: %s" % qry.value(0))

            m = re.search("PostgreSQL (\d+)\.(\d+)\.", qry.value(0))
            if not m:
                self.log(u"PostgreSQL-Version nicht im erwarteten Format")
                break

            if int(m.group(1)) < 8 or (int(m.group(1)) == 8
                                       and int(m.group(2)) < 3):
                self.log(u"Mindestens PostgreSQL 8.3 erforderlich")
                break

            qry = self.db.exec_("SELECT postgis_version()")
            if not qry or not qry.next():
                self.log(u"Konnte PostGIS-Version nicht bestimmen!")
                break

            self.log("PostGIS-Version: %s" % qry.value(0))

            qry = self.db.exec_(
                "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='public' AND table_name='alkis_importlog'"
            )
            if not qry or not qry.next():
                self.log(
                    u"Konnte Existenz von Protokolltabelle nicht überprüfen.")
                break

            if int(qry.value(0)) == 0:
                qry = self.db.exec_(
                    "CREATE TABLE alkis_importlog(n SERIAL PRIMARY KEY, ts timestamp default now(), msg text)"
                )
                if not qry:
                    self.log(u"Konnte Protokolltabelle nicht anlegen [%s]" %
                             qry.lastError().text())
                    break
            elif self.cbxClearProtocol.isChecked():
                qry = self.db.exec_("TRUNCATE alkis_importlog")
                if not qry:
                    self.log(u"Konnte Protokolltabelle nicht leeren [%s]" %
                             qry.lastError().text())
                    break
                self.cbxClearProtocol.setChecked(False)
                self.log(u"Protokolltabelle gelöscht.")

            qry = self.db.exec_(
                "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='public' AND table_name='alkis_beziehungen'"
            )
            if not qry or not qry.next():
                self.log(u"Konnte Existenz des ALKIS-Schema nicht überprüfen.")
                break

            if not self.cbxCreate.isChecked() and int(qry.value(0)) == 0:
                self.cbxCreate.setChecked(True)
                self.log(
                    u"Keine ALKIS-Daten vorhanden - Datenbank muß angelegt werden."
                )
                break

            self.logqry = QSqlQuery(self.db)
            if not self.logqry.prepare(
                    "INSERT INTO alkis_importlog(msg) VALUES (?)"):
                self.log(
                    u"Konnte Protokollierungsanweisung nicht vorbereiten [%s]"
                    % qry.lastError().text())
                self.logqry = None
                break

            self.ogr2ogr = which("ogr2ogr")
            if not self.ogr2ogr:
                self.ogr2ogr = which("ogr2ogr.exe")

            if not self.ogr2ogr:
                self.log(u"ogr2ogr nicht gefunden!")
                break

            if not self.runProcess([self.ogr2ogr, "--version"]):
                self.log(u"Konnte ogr2ogr-Version nicht abfragen!")
                break

            if not self.runProcess([self.ogr2ogr, "--utility_version"]):
                self.log(u"Konnte ogr2ogr-Bibliotheksversion nicht abfragen!")
                break

            self.psql = which("psql")
            if not self.psql:
                self.psql = which("psql.exe")

            if not self.psql:
                self.log(u"psql nicht gefunden!")
                break

            if not self.runProcess([self.psql, "--version"]):
                self.log(u"Konnte psql-Version nicht abfragen!")
                break

            try:
                self.status(u"Bestimme Gesamtgröße des Imports...")

                self.pbProgress.setRange(0, self.lstFiles.count())

                sizes = {}

                ts = 0
                for i in range(self.lstFiles.count()):
                    self.pbProgress.setValue(i)
                    item = self.lstFiles.item(i)
                    fn = unicode(item.text())

                    if fn[-4:] == ".xml":
                        s = os.path.getsize(fn)
                        sizes[fn] = s

                    elif fn[-4:] == ".zip":
                        l = -8 if fn[-8:] == ".xml.zip" else -4
                        self.status(u"%s wird abgefragt..." % fn)
                        app.processEvents()

                        f = zipfile.ZipFile(fn, "r")
                        il = f.infolist()
                        if len(il) <> 1:
                            raise ProcessError(
                                u"ZIP-Archiv %s enthält mehr als eine Datei!" %
                                fn)
                        s = il[0].file_size
                        sizes[fn[:l] + ".xml"] = s

                    elif fn[-7:] == ".xml.gz":
                        self.status(u"%s wird abgefragt..." % fn)

                        f = gzip.open(fn)
                        s = 0
                        while True:
                            chunk = f.read(1024 * 1024)
                            if not chunk:
                                break
                            s = s + len(chunk)
                        f.close()
                        sizes[fn[:-3]] = s

                    ts += s

                    if self.canceled:
                        break

                if self.canceled:
                    break

                self.log(u"Gesamtgröße des Imports: %s" % self.memunits(ts))

                self.pbProgress.setRange(0, 10000)
                self.pbProgress.setValue(0)

                if self.cbxCreate.isChecked():
                    self.status(u"Datenbank wird angelegt...")
                    if not self.runSQLScript(conn, "alkis-schema.sql"):
                        self.log(u"Anlegen des Datenbestands schlug fehl.")
                        break
                    self.cbxCreate.setChecked(False)
                    self.log(u"Datenbank angelegt.")

                ok = True

                s = 0
                for i in range(self.lstFiles.count()):
                    if self.canceled:
                        self.log("Import abgebrochen.")
                        break

                    item = self.lstFiles.item(i)
                    self.lstFiles.setCurrentItem(item)

                    fn = unicode(item.text())

                    src = ""
                    if fn[-7:] == ".xml.gz":
                        src = fn[:-3]
                        size = sizes[src]

                        self.status(u"%s wird extrahiert." % fn)
                        app.processEvents()

                        src = os.path.join(tempfile.gettempdir(),
                                           os.path.basename(src))

                        f_in = gzip.open(fn)
                        f_out = open(src, "wb")
                        while True:
                            chunk = f_in.read(1024 * 1024)
                            if not chunk:
                                break

                            f_out.write(chunk)

                        f_out.close()
                        f_in.close()

                        self.logDb(u"%s wurde entpackt." % fn)

                    elif fn[-4:] == ".zip":
                        src = fn[:-4] + ".xml"
                        size = sizes[src]

                        self.status(u"%s wird extrahiert." % fn)
                        app.processEvents()

                        src = os.path.join(tempfile.gettempdir(),
                                           os.path.basename(src))

                        zipf = zipfile.ZipFile(fn, "r")
                        f_in = zipf.open(zipf.infolist()[0].filename)
                        f_out = open(src, "wb")
                        while True:
                            chunk = f_in.read(1024 * 1024)
                            if not chunk:
                                break

                            f_out.write(chunk)
                        f_out.close()
                        f_in.close()
                        zipf.close()

                        self.logDb(u"%s wurde entpackt." % fn)

                    else:
                        src = fn
                        size = sizes[fn]

                    try:
                        os.unlink(src[:-4] + ".gfs")
                    except OSError, e:
                        pass

                    #if size==623 or size==712:
                    #	item.setSelected( True )
                    #	self.log( u"Kurze Datei %s übersprungen." % fn )
                    #	continue

                    if self.epsg == 131466 or self.epsg == 131467 or self.epsg == 131468:
                        srs = "+init=custom:%d" % self.epsg
                        os.putenv("PROJ_LIB", ".")
                    else:
                        srs = "EPSG:%d" % self.epsg

                    args = [
                        self.ogr2ogr, "-f", "PostgreSQL", "-append", "-update",
                        "PG:%s" % conn, "-a_srs", srs
                    ]

                    if self.cbxSkipFailures.isChecked():
                        args.append("-skipfailures")

                    args.append(src)

                    self.status(u"%s mit %s wird importiert..." %
                                (fn, self.memunits(size)))

                    t1 = QTime()
                    t1.start()

                    ok = self.runProcess(args)

                    elapsed = t1.elapsed()

                    if elapsed > 0:
                        throughput = " (%s/s)" % self.memunits(
                            size * 1000 / elapsed)
                    else:
                        throughput = ""

                    self.log(u"%s mit %s in %s importiert%s" %
                             (fn, self.memunits(size), self.timeunits(elapsed),
                              throughput))

                    item.setSelected(ok)
                    if src <> fn and os.path.exists(src):
                        os.unlink(src)

                    s = s + size
                    self.pbProgress.setValue(10000 * s / ts)

                    remaining_data = ts - s
                    remaining_time = remaining_data * t0.elapsed() / s

                    self.alive.setText(
                        "Noch %s in etwa %s\nETA: %s -" %
                        (self.memunits(remaining_data),
                         self.timeunits(remaining_time),
                         QDateTime.currentDateTime().addMSecs(
                             remaining_time).toString(Qt.ISODate)))

                    app.processEvents()

                    if not ok:
                        self.status(u"Fehler bei %s." % fn)
                        break

                self.pbProgress.setValue(10000)

                if ok and self.lstFiles.count() > 0:
                    self.log(u"Alle NAS-Dateien importiert.")

                if ok:
                    self.status(
                        u"Kompatibilitätsfunktionen werden importiert...")
                    ok = self.runSQLScript(conn, "alkis-compat.sql")
                    if ok:
                        self.log(u"Kompatibilitätsfunktionen importiert.")

                if ok:
                    self.status(u"Signaturen werden importiert...")
                    ok = self.runSQLScript(conn, "alkis-signaturen.sql")
                    if ok:
                        self.log(u"Signaturen importiert.")

                if ok:
                    self.status(u"Ableitungsregeln werden verarbeitet...")
                    ok = self.runSQLScript(conn, "alkis-ableitungsregeln.sql")
                    if ok:
                        self.log(u"Ableitungsregeln verarbeitet.")

                if ok:
                    for f in glob.glob("postprocessing.d/*.sql"):
                        self.status(
                            u"Nachverarbeitungsskript %s wird gestartet..." %
                            f)
                        ok = self.runSQLScript(conn, f)
                        if ok:
                            self.log(
                                u"Nachverarbeitungsskript %s ausgeführt." % f)

                if ok:
                    self.status(u"VACUUM...")
                    ok = self.db.exec_("VACUUM")
                    if ok:
                        self.log(u"VACUUM abgeschlossen.")

                if ok:
                    self.log(u"Import nach %s erfolgreich beendet." %
                             self.timeunits(t0.elapsed()))
                else:
                    self.log(u"Import nach %s abgebrochen." %
                             self.timeunits(t0.elapsed()))

            except Exception, e:
                exc_type, exc_value, exc_traceback = sys.exc_info()
                err = u"\n> ".join(
                    traceback.format_exception(exc_type, exc_value,
                                               exc_traceback))
                if sys.stdout:
                    print err
                self.log(u"Abbruch nach Fehler\n> %s" % unicode(err))
Example #21
0
class Window(QtGui.QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle("Respiratory analysis")
        self.ser = serial.Serial('COM35', 4800)
        self.menu()
        self.home()

    def menu(self):
        #--------------------Complete Menus------------------
        mainMenu = self.menuBar()
        mainMenu.setStatusTip('Select Options from main menu')
        fileMenu = mainMenu.addMenu('&File')
        fileMenu.setStatusTip('Select Options from File Menu')
        windowMenu = mainMenu.addMenu('&Plot')
        windowMenu.setStatusTip('Select Options from Window Menu')
        connectionMenu = mainMenu.addMenu('&Connection')
        connectionMenu.setStatusTip('Select Options from Connection Menu')
        helpMenu = mainMenu.addMenu('&Help')
        helpMenu.setStatusTip('Select for help')
        #----------------File Menus--------------------------------------
        #--------------Exit Action---------------------------------------
        exitAction = QtGui.QAction("&Exit", self)
        exitAction.setShortcut("Ctrl + Q")
        exitAction.setStatusTip("Leave the Application")
        exitAction.triggered.connect(self.close_application)
        fileMenu.addAction(exitAction)
        #---------------------------------------------------
        #----------------------------------------------------------------
        #-----------------Plot Menus-----------------------------------
        #----------------------------------------------------------------
        zoomin = QtGui.QAction('&Zoom In', self)
        zoomin.setStatusTip("Click to Zoom In")
        zoomin.setShortcut("Ctrl + =")
        zoomin.triggered.connect(self.zoom_in)
        windowMenu.addAction(zoomin)
        zoomout = QtGui.QAction('&Zoom Out', self)
        zoomout.setStatusTip("Click to Zoom Out")
        zoomout.setShortcut("Ctrl + -")
        zoomout.triggered.connect(self.zoom_out)
        windowMenu.addAction(zoomout)
        #----------------------------------------------------------------
        #----------------------------------------------------------------
        #----------------Connection Menus--------------------------------
        #----------------COM Ports---------------------------------------
        comMenu = connectionMenu.addMenu('&COM Ports')
        com = list(serial.tools.list_ports.comports())
        for i in range(len(com)):
            comAction = QtGui.QAction('&' + com[i][0], self)
            comAction.setStatusTip("Click to connect to " + com[i][0] +
                                   " Port")
            comAction.triggered.connect(self.establish_conn)
            comMenu.addAction(comAction)
        self.statusBar()

    def establish_conn(self, name):
        print(name)

    def zoom_in(self):
        self.ylow = self.ylow + 100
        self.yhigh = self.yhigh - 100
        self.p1.setYRange(self.ylow, self.yhigh)

    def zoom_out(self):
        self.ylow = self.ylow - 100
        self.yhigh = self.yhigh + 100
        self.p1.setYRange(self.ylow, self.yhigh)

    def home(self):
        self.splitter1 = QtGui.QSplitter(Qt.Vertical, self)
        self.splitter2 = QtGui.QSplitter(Qt.Vertical, self)
        self.wid = QtGui.QWidget()
        self.setCentralWidget(self.wid)
        self.hbox = QtGui.QHBoxLayout()
        self.vbox = QtGui.QVBoxLayout()
        self.wid.setLayout(self.hbox)
        self.hbox.addLayout(self.vbox)
        self.resize(1000, 800)
        self.data1 = deque(maxlen=1000)
        self.data = []
        self.t = QTime()
        self.t.start()
        self.timer1 = QtCore.QTimer()
        self.timer1.timeout.connect(self.update)
        self.timer2 = QtCore.QTimer()
        self.timer2.timeout.connect(self.read_data)
        self.timer3 = QtCore.QTimer()
        self.timer3.timeout.connect(self.stats)
        for i in range(2000):
            self.data1.append({'x': self.t.elapsed(), 'y': 0})
        #----------------Left pane--------------------------
        #----------------Adding Plot------------------------
        self.p1 = pg.PlotWidget(
            name="Raw",
            title="Respiration Plot",
            labels={
                'left': ("Thoracic Circumference in (cm)"),
                'bottom': ("Time Elapsed (mm:ss)")
            },
            enableMenu=True,
            axisItems={'bottom': TimeAxisItem(orientation='bottom')})
        self.p1.addLegend(offset=(450, 30))
        self.p1.showGrid(x=True, y=True, alpha=0.5)
        self.p1.setMouseEnabled(x=True, y=True)
        self.curve = self.p1.plot(pen='y', name="Raw Respiration Data")
        self.curve1 = self.p1.plot(pen='r', name="Filtered Respiration DAta")
        self.ylow = 600
        self.yhigh = 800
        self.p1.setYRange(self.ylow, self.yhigh)
        #----------------------------------------------------
        self.statistics = QtGui.QGroupBox()
        self.statistics.setTitle("Statistics")
        self.stlabel1 = QtGui.QLabel("Mean Value\t\t\t:", self.statistics)
        self.stlabel1.move(5, 40)
        self.stlabel2 = QtGui.QLabel("Variance\t\t\t\t:", self.statistics)
        self.stlabel2.move(280, 40)
        self.stlabel3 = QtGui.QLabel("Respiration Rate (per min)\t\t:",
                                     self.statistics)
        self.stlabel3.move(5, 70)
        self.stlabel4 = QtGui.QLabel("Average Breath Duration (mins)\t:",
                                     self.statistics)
        self.stlabel4.move(280, 70)
        self.stlabel5 = QtGui.QLabel("Variance in Breath Duration (mins)\t:",
                                     self.statistics)
        self.stlabel5.move(5, 100)
        self.stlabel6 = QtGui.QLabel("Statistical Dispersion\t\t:",
                                     self.statistics)
        self.stlabel6.move(280, 100)
        self.stlabel7 = QtGui.QLabel("Average Normalized Tidal Volume\t:",
                                     self.statistics)
        self.stlabel7.move(5, 130)
        self.stlabel8 = QtGui.QLabel("Variance in Normalized Tidal Volume\t:",
                                     self.statistics)
        self.stlabel8.move(280, 130)
        self.stlabel9 = QtGui.QLabel("Average Respiration Width\t\t:",
                                     self.statistics)
        self.stlabel9.move(5, 160)
        self.stlabel10 = QtGui.QLabel("Variance in Respiration Width\t\t:",
                                      self.statistics)
        self.stlabel10.move(280, 160)
        self.stlabelmean = QtGui.QLabel("0", self.statistics)
        self.stlabelmean.move(205, 40)
        self.stlabelmean.resize(200, 20)
        self.stlabelvariance = QtGui.QLabel("0", self.statistics)
        self.stlabelvariance.move(485, 40)
        self.stlabelvariance.resize(200, 20)
        self.stlabelrrate = QtGui.QLabel("0", self.statistics)
        self.stlabelrrate.move(205, 70)
        self.stlabelrrate.resize(200, 20)
        self.stlabelabd = QtGui.QLabel("0", self.statistics)
        self.stlabelabd.move(485, 70)
        self.stlabelabd.resize(200, 20)
        self.stlabelvbd = QtGui.QLabel("0", self.statistics)
        self.stlabelvbd.move(205, 100)
        self.stlabelvbd.resize(200, 20)
        self.stlabelsd = QtGui.QLabel("0", self.statistics)
        self.stlabelsd.move(485, 100)
        self.stlabelsd.resize(200, 20)
        self.stlabelatv = QtGui.QLabel("0", self.statistics)
        self.stlabelatv.move(205, 130)
        self.stlabelatv.resize(200, 20)
        self.stlabelvtv = QtGui.QLabel("0", self.statistics)
        self.stlabelvtv.move(485, 130)
        self.stlabelvtv.resize(200, 20)
        self.stlabelarw = QtGui.QLabel("0", self.statistics)
        self.stlabelarw.move(205, 160)
        self.stlabelarw.resize(200, 20)
        self.stlabelvrw = QtGui.QLabel("0", self.statistics)
        self.stlabelvrw.move(485, 160)
        self.stlabelvrw.resize(200, 20)
        #----------------------------------------------------
        self.apneagb = QtGui.QGroupBox()
        self.apneagb.setTitle("Apnea")
        self.apnealabel1 = QtGui.QLabel("Apnea Event Detected", self.apneagb)
        self.apnealabel1.resize(150, 20)
        self.apnealabel1.move(30, 30)
        self.apnealabel2 = QtGui.QLabel("No", self.apneagb)
        self.apnealabel2.resize(150, 20)
        self.apnealabel2.move(80, 50)
        self.apnealabel3 = QtGui.QLabel("Total Apnea Events", self.apneagb)
        self.apnealabel3.resize(150, 20)
        self.apnealabel3.move(30, 70)
        self.apnealabel4 = QtGui.QLabel("0", self.apneagb)
        self.apnealabel4.resize(150, 20)
        self.apnealabel4.move(80, 90)
        #----------------Plot GroupBox---------------------------
        self.groupBox = QtGui.QGroupBox()
        self.groupBox.setTitle("Plot")
        self.label3 = QtGui.QLabel("Y-Low  :", self.groupBox)
        self.label3.move(5, 20)
        self.label4 = QtGui.QLabel("Y-High :", self.groupBox)
        self.label4.move(150, 20)
        self.slider3 = QtGui.QSlider(self.groupBox)
        self.slider3.setOrientation(QtCore.Qt.Horizontal)
        self.slider3.move(50, 20)
        self.slider3.valueChanged[int].connect(self.setylow)
        self.slider4 = QtGui.QSlider(self.groupBox)
        self.slider4.setOrientation(QtCore.Qt.Horizontal)
        self.slider4.move(195, 20)
        self.slider4.valueChanged[int].connect(self.setyhigh)
        self.pb1 = QtGui.QPushButton("Resume", self.groupBox)
        self.pb1.move(60, 50)
        self.pb1.clicked.connect(self.plot_resume)
        self.pb2 = QtGui.QPushButton("Pause", self.groupBox)
        self.pb2.move(150, 50)
        self.pb2.clicked.connect(self.plot_pause)
        #--------------------------------------------------------------
        #---------------Signal-Processing-GroupBox---------------------
        self.sp = QtGui.QGroupBox()
        self.sptab = QtGui.QTabWidget(self.sp)
        self.sptab.setGeometry(QtCore.QRect(10, 20, 270, 120))
        self.tab1 = QtGui.QWidget()
        self.sp.setTitle("Signal Processing")
        self.splabel2 = QtGui.QLabel("Normalized Cutoff Frequency\t:\tHz",
                                     self.tab1)
        self.splabel2.move(5, 10)
        self.l1 = QtGui.QLineEdit(self.tab1)
        self.l1.setGeometry(QtCore.QRect(160, 10, 31, 20))
        self.splabel3 = QtGui.QLabel("Order of Filter\t\t:\tHz", self.tab1)
        self.splabel3.move(5, 35)
        self.l2 = QtGui.QLineEdit(self.tab1)
        self.l2.setGeometry(QtCore.QRect(160, 35, 31, 20))
        self.sb1 = QtGui.QPushButton("Apply", self.tab1)
        self.sb1.move(40, 60)
        self.sb1.clicked.connect(self.low_pass)
        self.sptab.addTab(self.tab1, "Low Pass Filter")
        self.tab2 = QtGui.QWidget()
        self.splabel7 = QtGui.QLabel("Window Size:	    samples", self.tab2)
        self.splabel7.move(5, 10)
        self.l5 = QtGui.QLineEdit(self.tab2)
        self.l5.setGeometry(QtCore.QRect(75, 10, 31, 20))
        self.sb2 = QtGui.QPushButton("Apply", self.tab2)
        self.sb2.move(30, 40)
        self.sb2.clicked.connect(self.moving_average)
        self.sb3 = QtGui.QPushButton("Remove", self.tab1)
        self.sb3.move(120, 60)
        self.sb3.clicked.connect(self.remove_lowpass)
        self.sb4 = QtGui.QPushButton("Remove", self.tab2)
        self.sb4.move(130, 40)
        self.sptab.addTab(self.tab2, "Moving Average")
        #--------------------------------------------------------------
        #--------------Pneumonia Detection-----------------------------
        self.pneumonia = QtGui.QGroupBox()
        self.pneumonia.setTitle("Pneumonia Detection")
        self.plabel1 = QtGui.QLabel("Enter the Age :	        yrs",
                                    self.pneumonia)
        self.plabel1.move(70, 25)
        self.pl1 = QtGui.QLineEdit(self.pneumonia)
        self.pl1.setGeometry(QtCore.QRect(150, 25, 35, 20))
        self.pb1 = QtGui.QPushButton("Detect", self.pneumonia)
        self.pb1.move(115, 50)
        self.pb1.clicked.connect(self.detect_pneumonia)
        self.plabel2 = QtGui.QLabel("Symptoms of Pneumonia :", self.pneumonia)
        self.plabel2.move(70, 85)
        self.plabelpneumonia = QtGui.QLabel("No", self.pneumonia)
        self.plabelpneumonia.move(200, 85)
        #--------------------------------------------------------------
        #--------------Database Connection-----------------------------
        self.databaseg = QtGui.QGroupBox()
        self.databaseg.setTitle("Dashboard")
        self.dlabel1 = QtGui.QLabel("Name\t\t:", self.databaseg)
        self.dlabel1.move(5, 15)
        self.dText1 = QtGui.QLineEdit(self.databaseg)
        self.dText1.move(120, 15)
        self.dlabel2 = QtGui.QLabel("Date of Birth\t:", self.databaseg)
        self.dlabel2.move(5, 45)
        self.dateEdit = QtGui.QDateEdit(self.databaseg)
        self.dateEdit.setGeometry(QtCore.QRect(120, 40, 133, 22))
        self.dlabel3 = QtGui.QLabel("Start Saving to\t:", self.databaseg)
        self.dlabel3.move(5, 152)
        self.dlabel4 = QtGui.QLabel("Respiration plot\t:", self.databaseg)
        self.dlabel4.move(5, 80)
        self.dpb1 = QtGui.QCheckBox("Local", self.databaseg)
        self.dpb1.move(120, 152)
        self.dpb2 = QtGui.QCheckBox("Cloud", self.databaseg)
        self.dpb2.move(200, 152)
        self.dpb6 = QtGui.QPushButton("Start", self.databaseg)
        self.dpb6.move(120, 180)
        self.dpb6.clicked.connect(self.database_startsaving)
        self.dpb3 = QtGui.QPushButton("Stop", self.databaseg)
        self.dpb3.move(200, 180)
        self.dpb3.clicked.connect(self.database_stopsaving)
        self.dpb4 = QtGui.QPushButton("Start", self.databaseg)
        self.dpb4.move(120, 75)
        self.dpb4.clicked.connect(self.database_startplot)
        self.dpb5 = QtGui.QPushButton("Stop", self.databaseg)
        self.dpb5.move(200, 75)
        self.dpb5.clicked.connect(self.database_stopplot)
        self.dlabel5 = QtGui.QLabel("Tools\t\t:", self.databaseg)
        self.dlabel5.move(5, 115)
        self.dpb7 = QtGui.QPushButton("Calibrate", self.databaseg)
        self.dpb7.move(120, 112)
        self.dpb7.clicked.connect(self.database_calibrate)
        self.dpb8 = QtGui.QPushButton("Analyze", self.databaseg)
        self.dpb8.move(200, 112)
        self.dpb8.clicked.connect(self.database_analyze)
        #------------------------------------------------------
        #---------------------Arranging Splitters---------------
        self.vbox2 = QtGui.QVBoxLayout()
        self.splitter3 = QtGui.QSplitter(self)
        self.splitter4 = QtGui.QSplitter(self)
        self.splitter1.addWidget(self.p1)
        self.splitter4.addWidget(self.statistics)
        self.splitter4.addWidget(self.apneagb)
        self.splitter1.addWidget(self.splitter4)
        self.vbox.addWidget(self.splitter3)
        self.splitter2.addWidget(self.groupBox)
        self.splitter2.addWidget(self.databaseg)
        self.splitter2.addWidget(self.sp)
        self.splitter2.addWidget(self.pneumonia)
        self.splitter3.addWidget(self.splitter1)
        self.splitter3.addWidget(self.splitter2)
        self.splitter2.setSizes([80, 200, 200, 160])
        self.splitter3.setSizes([1000, 420])
        self.splitter1.setSizes([500, 260])
        self.splitter4.setSizes([100, 10])
        self.lowpass_flag = 0
        #-------------------------------------------------------
        self.show()

    def setylow(self, value):
        self.ylow = value * 1024 / 100
        self.p1.setYRange(self.ylow, self.yhigh)

    def setyhigh(self, value):
        self.yhigh = value * 1024 / 100
        self.p1.setYRange(self.ylow, self.yhigh)

    def update(self):
        x = [item['x'] for item in self.data1]
        y = [item['y'] for item in self.data1]
        if (self.lowpass_flag == 1):
            y1 = self.butter_lowpass_filter(y, self.cutoff, 10, self.order)
            self.curve1.setData(x=x, y=y1)
        self.curve.setData(x=x, y=y)

    def plot_resume(self):
        self.timer1.start(100)

    def plot_pause(self):
        self.timer1.stop()

    def low_pass(self):
        self.lowpass_flag = 1
        self.cutoff = float(self.l1.text())
        self.order = float(self.l2.text())

    def remove_lowpass(self):
        self.lowpass_flag = 0
        self.curve1.clear()

    def moving_average(self):
        print("Clicked Moving Average")

    def detect_pneumonia(self):
        print("Detect Pneumonia Clicked")

    def database_local(self):
        print("Database Local")

    def database_cloud(self):
        print("Database Cloud")

    def database_startplot(self):
        self.t.restart()
        self.timer1.start(50)
        self.timer2.start(4)
        self.timer3.start(30000)

    def database_stopplot(self):
        self.timer1.stop()
        self.timer2.stop()
        self.timer3.stop()

    def database_startsaving(self):
        print("Database start saving")

    def database_stopsaving(self):
        print("Database stop saving")

    def database_calibrate(self):
        print("Database calibrate")

    def database_analyze(self):
        print("Database Analyze")

    def read_data(self):
        #data=np.random.randint(600,700)
        data = int(self.ser.readline()[0:4])
        self.data.append(data)
        self.data1.append({'x': self.t.elapsed(), 'y': data})

    def stats(self):
        resp_rate = []
        total_tidal_volume = []
        self.data2 = self.butter_lowpass_filter(self.data, 0.7,
                                                len(self.data) / 30, 6)
        self.data2 = np.array(self.data2)
        self.mean = np.mean(self.data2)
        self.stlabelmean.setText(str(round(self.mean, 2)))
        self.variance = np.var(self.data2)
        self.stlabelvariance.setText(str(round(self.variance, 2)))
        new_data = self.data2 - self.mean
        zero_crossings = np.where(np.diff(np.sign(new_data)))[0]
        self.respirationrate = (zero_crossings.size)
        self.stlabelrrate.setText(str(round(self.respirationrate, 2)))
        local_maxima = argrelextrema(self.data2, np.greater)[0]
        local_minima = argrelextrema(self.data2, np.less)[0]
        tenp = np.percentile(self.data2, 10)
        nintyp = np.percentile(self.data2, 90)
        diff_local_maxima = np.diff(local_maxima)
        self.average_breath_duration = np.mean(diff_local_maxima)
        self.stlabelabd.setText(
            str(round(self.average_breath_duration * 0.5 / len(self.data2),
                      2)))
        self.var_breath_duration = np.var(diff_local_maxima)
        self.stlabelvbd.setText(
            str(round(self.var_breath_duration * 0.5 / len(self.data2), 2)))
        self.dispersion = nintyp - tenp
        self.stlabelsd.setText(str(round(self.dispersion, 2)))
        tidal_volume = []
        for i in range(local_minima.size - 1):
            maxima = np.where(
                np.logical_and(local_maxima >= local_minima[i],
                               local_maxima <= local_minima[i + 1]))[0]
            if (maxima.size > 0):
                volume = self.data2[local_maxima[maxima[0]]] - (
                    (self.data2[local_minima[i]] +
                     self.data2[local_minima[i + 1]]) / 2)
                tidal_volume.append(volume)
        self.average_tidal_volume = np.mean(tidal_volume)
        self.variant_tidal_volume = np.var(tidal_volume)
        self.stlabelatv.setText(str(round(self.average_tidal_volume, 2)))
        self.stlabelvtv.setText(str(round(self.variant_tidal_volume, 2)))
        intdata1 = [self.data2[x] for x in local_maxima]
        intdata2 = [self.data2[x] for x in local_minima]
        f1 = interp1d(local_maxima, intdata1, kind='cubic')
        f2 = interp1d(local_minima, intdata2, kind='cubic')
        xmin = max(local_maxima[0], local_minima[0])
        xmax = min(local_maxima[len(local_maxima) - 1],
                   local_minima[len(local_minima) - 1])
        xnew = np.linspace(xmin, xmax)
        width = f1(xnew) - f2(xnew)
        self.average_width = np.mean(width)
        self.var_width = np.var(width)
        self.stlabelarw.setText(str(round(self.average_width, 2)))
        self.stlabelvrw.setText(str(round(self.var_width, 2)))
        print(self.mean)
        self.data.clear()

    def butter_lowpass(self, cutoff, fs, order=5):
        nyq = 0.5 * fs
        normal_cutoff = cutoff / nyq
        b, a = butter(order, normal_cutoff, btype='low', analog=False)
        return b, a

    def butter_lowpass_filter(self, data, cutoff, fs, order=5):
        b, a = self.butter_lowpass(cutoff, fs, order=order)
        y = lfilter(b, a, data)
        return y

    def close_application(self):
        sys.exit()
Example #22
0
class Game(QObject):
    """Container to hold one new or loaded game instance"""
    FRAME_RATE = 25 # Frame rate in frames per second.
    
    def __init__(self):
        """Game Instance responsible For all non visual work"""
        
        # Keep track of how long we have been playing.
        self.gameTime = None
        self.frameTimer = QTimer()
        
        # Manage Character
        self.character = None
        
        # Manage Game Progression
        self.story = Story(self.FRAME_RATE)
        
        # Manage World
        self.places = Places()

    def new(self):
        """Load new game from file"""
        debug("newgame...loading clues")
        self.story.loadClues()
        debug("newgame...loading charcter")
        self.character = Character((0,0), "Character", "Character")
        debug("newgame...loading places")
        self.places.loadLoc()
        debug("end of load")
        self.places.addLoc(self.character)
        self.story.currClue = self.story._clueList.pop()
        #self.frameTimer = QTimer() # Create Frame Timer
        self.gameTime = QTime()
        self.launch()
        
        
    def load(self,filename):
        """Load existing game from file"""
        
        debug("loadgame...read data from saved file")
        debug("loadgame...loading clues")
        self.story.loadClues()
        
        savedData = open(filename)    
        nextLine = savedData.readline()
        # Parsing saved file
        while (nextLine):
            line = nextLine.split()
            if (len(line) == 4 and self.loadIsValid(line)):
                x = int(line[0])
                y = int(line[1])
                numClues = int(line[2])+1
                self.story._clueList =  self.story._clueList[:numClues]
                self.story.score = int(line[3])
                debug("x: " + `x` + " y: " + `y` + " numCLue: " + `len(self.story._clueList)` + \
                      " score is: " + `int(line[3])`)
            nextLine = savedData.readline()       
        savedData.close()
        self.story.currClue = self.story._clueList.pop()
        
        debug("loadgame...loading initial character and places")
        self.character = Character((x,y), "Character", "Character")
        self.places.loadLoc()
        
        debug("end of load")
        self.places.addLoc(self.character)
        # FIXME if QTime and QTimer should be stored in certain way
        self.gameTime = QTime()
        #self.frameTimer = QTimer() # Create Frame Timer
        self.launch()
    
    def loadIsValid(self,obj):
        """Check that the input from saved file is valid"""         
        posx = obj[0]
        posy = obj[1]
        numClue = obj[2]
        score = obj[3]
        try:
            int(posx) and int(posy) and int(numClue) and int(score)
        except:
            debug("Invalid position input in save file")
            return False
        return True
    
    def save(self, filename):
        """Save to file"""
        fname = open(filename, "w")
        score = `self.story.score`
        numClues = `len(self.story._clueList)`
        charX, charY = self.character.getCenter()
        toWriteList = '\t' + `charX` + '\t' + `charY` + '\t' + \
                        numClues + '\t' + score
        fname.write(toWriteList)     
        fname.close()
    
    def endGame(self):
        """Make things tidy for another game instance"""
        # Signal that we have won the game and should
        None
    
    def launch(self):
        """Start sending signals to the game using Timers"""
        self.gameTime.start()
        self.frameTimer.start(ONE_SECOND/self.FRAME_RATE)
        self.frameTimer.timeout.connect(self.story.frameTime)
        
    def keyPress(self, event):
        key = event.key()
        self.character.keyPress(key)
        
    def keyRelease(self, event):
        key = event.key()
        self.character.keyRelease(key)
Example #23
0
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg
from PyQt4.QtCore import QTime, QTimer
from collections import deque
 
t = QTime()
t.start()
data = deque(maxlen=20)
 
class TimeAxisItem(pg.AxisItem):
    def __init__(self, *args, **kwargs):
        super(TimeAxisItem, self).__init__(*args, **kwargs)
 
    def tickStrings(self, values, scale, spacing):
        # PySide's QTime() initialiser fails miserably and dismisses args/kwargs
        return [QTime().addMSecs(value).toString('mm:ss') for value in values]
 
 
 
 
app = QtGui.QApplication([])
 
win = pg.GraphicsWindow(title="Basic plotting examples")
win.resize(1000,600)
 
plot = win.addPlot(title='Timed data', axisItems={'bottom': TimeAxisItem(orientation='bottom')})
curve = plot.plot()
 
def update():
    global plot, curve, data
Example #24
0
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg
from PyQt4.QtCore import QTime, QTimer
from collections import deque

t = QTime()
t.start()
data = deque(maxlen=20)


class TimeAxisItem(pg.AxisItem):
    def __init__(self, *args, **kwargs):
        super(TimeAxisItem, self).__init__(*args, **kwargs)

    def tickStrings(self, values, scale, spacing):
        # PySide's QTime() initialiser fails miserably and dismisses args/kwargs
        return [QTime().addMSecs(value).toString('mm:ss') for value in values]


app = QtGui.QApplication([])

win = pg.GraphicsWindow(title="Basic plotting examples")
win.resize(1000, 600)

plot = win.addPlot(title='Timed data',
                   axisItems={'bottom': TimeAxisItem(orientation='bottom')})
curve = plot.plot()


def update():