Skip to content
Snippets Groups Projects
profilevisualization.py 42 KiB
Newer Older
        self.ui.progressInfo.setText(t)

    def requestUpdate(self, *args):
        self.updateRequested = True
        #next time

    def updatePersistentWidgets(self):
        model = self.TV.model()
        if model:
            colExpression = model.columnames.index('y-value')
            colStyle = model.columnames.index('style')
            for row in range(model.rowCount()):
                idxExpr = model.createIndex(row, colExpression)
                idxStyle = model.createIndex(row, colStyle)
                #self.TV.closePersistentEditor(idxExpr)
                #self.TV.closePersistentEditor(idxStyle)
                self.TV.openPersistentEditor(idxExpr)
                self.TV.openPersistentEditor(idxStyle)

                #self.TV.openPersistentEditor(model.createIndex(start, colStyle))
            s = ""

    def onRowsInserted(self, parent, start, end):
        model = self.TV.model()
        if model:
            colExpression = model.columnames.index('y-value')
            colStyle = model.columnames.index('style')
            while start <= end:
                idxExpr = model.createIndex(start, colExpression)
                idxStyle = model.createIndex(start, colStyle)
                self.TV.openPersistentEditor(idxExpr)
                self.TV.openPersistentEditor(idxStyle)
                start += 1
                #self.TV.openPersistentEditor(model.createIndex(start, colStyle))
            s = ""

    def onObservationClicked(self, plotDataItem, points):
        for p in points:
            tsd = p.data()
            print(tsd)
        s =""

    def clear(self):
        #first remove from pixelCollection
        self.pxCollection.clearPixels()
        self.plotData2D.clear()
        self.plotData3D.clear()
        pi = self.plot2D.getPlotItem()
        plotItems = pi.listDataItems()
        for p in plotItems:
            p.clear()
            p.update()

        if len(self.TS) > 0:
            rng = [self.TS[0].date, self.TS[-1].date]
            rng = [date2num(d) for d in rng]
            self.plot2D.getPlotItem().setRange(xRange=rng)
        QApplication.processEvents()
        if self.plot3D:
            pass

    def loadCoordinate(self, spatialPoint):
        if not isinstance(self.plotSettingsModel, PlotSettingsModel):
            return False

        if not self.pixelLoader.isReadyToLoad():
            return False

        assert isinstance(spatialPoint, SpatialPoint)
        assert isinstance(self.TS, TimeSeries)

        LUT_bandIndices = dict()
        for sensor in self.TS.Sensors:
            LUT_bandIndices[sensor] = self.plotSettingsModel.requiredBands(sensor)

        paths = []
        bandIndices = []
        for tsd in self.TS:
            if tsd.isVisible():
                paths.append(tsd.pathImg)
                bandIndices.append(LUT_bandIndices[tsd.sensor])

        aGoodDefault = 2 if len(self.TS) > 25 else 1
        self.pixelLoader.setNumberOfProcesses(SETTINGS.value('profileloader_threads', aGoodDefault))
        self.pixelLoader.startLoading(paths, spatialPoint, bandIndices=bandIndices)

        self.ui.setWindowTitle('{} | {} {}'.format(self.ui.baseTitle, str(spatialPoint.toString()), spatialPoint.crs().authid()))


    def setVisibility(self, sensorPlotStyle):
        assert isinstance(sensorPlotStyle, SensorPlotStyle)
        self.setVisibility2D(sensorPlotStyle)
    def setVisibility2D(self, sensorPlotStyle):
        assert isinstance(sensorPlotStyle, SensorPlotStyle)
        p = self.plotData2D[sensorPlotStyle.sensor()]
        p.setSymbol(sensorPlotStyle.markerSymbol)
        p.setSymbolSize(sensorPlotStyle.markerSize)
        p.setSymbolBrush(sensorPlotStyle.markerBrush)
        p.setSymbolPen(sensorPlotStyle.markerPen)
        p.setPen(sensorPlotStyle.linePen)
        p.setVisible(sensorPlotStyle.isVisible())
        p.update()
        self.plot2D.update()
    def addData(self, sensorView = None):

        if sensorView is None:
            for sv in self.plotSettingsModel.items:
            assert isinstance(sensorView, SensorPlotStyle)
    @QtCore.pyqtSlot()
    def updatePlot(self):
        if isinstance(self.plotSettingsModel, PlotSettingsModel) and self.updateRequested:
            self.setData()
            self.updateRequested = False

    def setData(self, sensorView = None):
        self.updateLock = True
        if sensorView is None:
            for sv in self.plotSettingsModel.mSensorPlotSettings:
                self.setData(sv)
        else:
            assert isinstance(sensorView, SensorPlotStyle)
            self.setData2D(sensorView)

        self.updateLock = False

    def removeSensor(self, sensor):
        s = ""
        self.plotSettingsModel.removeSensor(sensor)

        if sensor in self.plotData2D.keys():
            #remove from settings model
            self.plotSettingsModel.removeSensor(sensor)
            self.plotData2D.pop(sensor)
            self.pxCollection.removeSensor(sensor)
            # remove from px layer dictionary
            #self.sensorPxLayers.pop(sensor)
            #todo: remove from plot
            s = ""

    def setData2D(self, sensorView):
        assert isinstance(sensorView, SensorPlotStyle)
        if sensorView.sensor() not in self.plotData2D.keys():
            plotDataItem = self.plot2D.plot(name=sensorView.sensor().name(), pen=None, symbol='o', symbolPen=None)
            plotDataItem.sigPointsClicked.connect(self.onObservationClicked)

            self.plotData2D[sensorView.sensor()] = plotDataItem
            self.setVisibility2D(sensorView)
        plotDataItem = self.plotData2D[sensorView.sensor()]
        plotDataItem.setToolTip('Values {}'.format(sensorView.sensor().name()))
        #https://github.com/pyqtgraph/pyqtgraph/blob/5195d9dd6308caee87e043e859e7e553b9887453/examples/customPlot.py
        tsds, values = self.pxCollection.dateValues(sensorView.sensor(), sensorView.expression())
        if len(tsds) > 0:
            dates = np.asarray([date2num(tsd.date) for tsd in tsds])
            tsds = np.asarray(tsds)
            values = np.asarray(values)
            i = np.argsort(dates)
            plotDataItem.appendData()
            plotDataItem.setData(x=dates[i], y=values[i], data=tsds[i])
            self.setVisibility2D(sensorView)
    def setData3D(self, *arg):
def examplePixelLoader():

    # prepare QGIS environment
    if sys.platform == 'darwin':
        PATH_QGS = r'/Applications/QGIS.app/Contents/MacOS'
        os.environ['GDAL_DATA'] = r'/usr/local/Cellar/gdal/1.11.3_1/share'
    else:
        # assume OSGeo4W startup
        PATH_QGS = os.environ['QGIS_PREFIX_PATH']
    assert os.path.exists(PATH_QGS)

    qgsApp = QgsApplication([], True)
    QApplication.addLibraryPath(r'/Applications/QGIS.app/Contents/PlugIns')
    QApplication.addLibraryPath(r'/Applications/QGIS.app/Contents/PlugIns/qgis')
    qgsApp.setPrefixPath(PATH_QGS, True)
    qgsApp.initQgis()


    gb = QGroupBox()
    gb.setTitle('Sandbox')

    PL = PixelLoader()
    PL.setNumberOfThreads(2)

    if False:
        files = ['observationcloud/testdata/2014-07-26_LC82270652014207LGN00_BOA.bsq',
                 'observationcloud/testdata/2014-08-03_LE72270652014215CUB00_BOA.bsq'
                 ]
    else:
        from timeseriesviewer.utils import file_search
        searchDir = r'H:\LandsatData\Landsat_NovoProgresso'
        files = file_search(searchDir, '*227065*band4.img', recursive=True)
        #files = files[0:3]

    lyr = QgsRasterLayer(files[0])
    coord = lyr.extent().center()
    crs = lyr.crs()

    l = QVBoxLayout()

    btnStart = QPushButton()
    btnStop = QPushButton()
    prog = QProgressBar()
    tboxResults = QPlainTextEdit()
    tboxResults.setMaximumHeight(300)
    tboxThreads = QPlainTextEdit()
    tboxThreads.setMaximumHeight(200)
    label = QLabel()
    label.setText('Progress')

    def showProgress(n,m,md):
        prog.setMinimum(0)
        prog.setMaximum(m)
        prog.setValue(n)

        info = []
        for k, v in md.items():
            info.append('{} = {}'.format(k,str(v)))
        tboxResults.setPlainText('\n'.join(info))
        #tboxThreads.setPlainText(PL.threadInfo())
        qgsApp.processEvents()

    PL.sigPixelLoaded.connect(showProgress)
    btnStart.setText('Start loading')
    btnStart.clicked.connect(lambda : PL.startLoading(files, coord, crs))
    btnStop.setText('Cancel')
    btnStop.clicked.connect(lambda: PL.cancelLoading())
    lh = QHBoxLayout()
    lh.addWidget(btnStart)
    lh.addWidget(btnStop)
    l.addLayout(lh)
    l.addWidget(prog)
    l.addWidget(tboxThreads)
    l.addWidget(tboxResults)

    gb.setLayout(l)
    gb.show()
    #rs.setBackgroundStyle('background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #222, stop:1 #333);')
    #rs.handle.setStyleSheet('background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #282, stop:1 #393);')
    qgsApp.exec_()
    qgsApp.exitQgis()

if __name__ == '__main__':
    import site, sys
Benjamin Jakimow's avatar
Benjamin Jakimow committed
    from timeseriesviewer import sandbox
    qgsApp = sandbox.initQgisEnvironment()
    d1 = np.datetime64('2012-05-23')
    d2 = np.datetime64('2012-05-24')
    n1 = date2num(d1)
    n2 = date2num(d2)
    assert d1 == num2date(n1)
    assert d2 == num2date(n2)
    delta = n2-n1

    ui = ProfileViewDockUI()
    ui.show()
Benjamin Jakimow's avatar
Benjamin Jakimow committed
    if True:
        SViz = SpectralTemporalVisualization(ui)
        SViz.connectTimeSeries(TS)

        from example.Images import Img_2014_01_15_LC82270652014015LGN00_BOA
        TS.addFiles([Img_2014_01_15_LC82270652014015LGN00_BOA])
Benjamin Jakimow's avatar
Benjamin Jakimow committed
        ext = TS.getMaxSpatialExtent()
        cp = SpatialPoint(ext.crs(),ext.center())
        SViz.loadCoordinate(cp)
Benjamin Jakimow's avatar
Benjamin Jakimow committed
    qgsApp.exec_()
    qgsApp.exitQgis()