Skip to content
Snippets Groups Projects
main.py 46.8 KiB
Newer Older
  • Learn to ignore specific revisions
  •     def showMapViewDefinition(self, mapViewDefinition):
            assert mapViewDefinition in self.mapViewsDefinitions
    
            assert isinstance(mapViewDefinition, MapView)
            l = self.scrollAreaContent.layout()
    
            for d in self.recentMapViewDefinitions():
                d.ui.setVisible(False)
                l.removeWidget(d.ui)
    
            l.insertWidget(l.count() - 1, mapViewDefinition.ui)
            mapViewDefinition.ui.setVisible(True)
    
        def recentMapViewDefinitions(self):
    
            return [ui.mapViewDefinition() for ui in parent.findChildren(MapViewDefinitionUI)]
    
    
        def setMapViewVisibility(self, bandView, isVisible):
    
            assert isinstance(bandView, MapView)
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
    
    
    
        def __len__(self):
    
            return len(self.mapViewsDefinitions)
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
    
        def __iter__(self):
    
            return iter(self.mapViewsDefinitions)
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
    
        def __getitem__(self, key):
    
            return self.mapViewsDefinitions[key]
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
    
    
        def __contains__(self, mapView):
            return mapView in self.mapViewsDefinitions
    
    class TimeSeriesViewer:
    
    unknown's avatar
    unknown committed
    
        def __init__(self, iface):
            """Constructor.
    
            :param iface: An interface instance that will be passed to this class
                which provides the hook by which you can manipulate the QGIS
                application at run time.
            :type iface: QgsInterface
            """
            # Save reference to the QGIS interface
    
            from timeseriesviewer.ui.widgets import TimeSeriesViewerUI
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
    
    
            self.ui = TimeSeriesViewerUI(parent=iface)
    
                timeseriesviewer.QGIS_TSV_BRIDGE = QgisTsvBridge(iface, self.ui)
    
    
            #init empty time series
            self.TS = TimeSeries()
            self.hasInitialCenterPoint = False
    
            self.TS.sigTimeSeriesDatesAdded.connect(self.datesAdded)
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
    
    
            #self.ICP = D.scrollAreaSubsetContent.layout()
            #D.scrollAreaMapViews.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)
            #self.BVP = self.ui.scrollAreaMapViews.layout()
    
            D.dockNavigation.connectTimeSeries(self.TS)
            D.dockTimeSeries.connectTimeSeries(self.TS)
    
            self.spatialTemporalVis = SpatialTemporalVisualization(self)
            self.spatialTemporalVis.sigLoadingStarted.connect(self.ui.dockRendering.addStartedWork)
            self.spatialTemporalVis.sigLoadingFinished.connect(self.ui.dockRendering.addFinishedWork)
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
    
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
    
    
    unknown's avatar
    unknown committed
            self.ValidatorPxX = QIntValidator(0,99999)
            self.ValidatorPxY = QIntValidator(0,99999)
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
    
            #connect actions with logic
    
            #D.btn_showPxCoordinate.clicked.connect(lambda: self.showSubsetsStart())
    
            #connect actions with logic
    
            D.actionSelectCenter.triggered.connect(lambda : self.spatialTemporalVis.activateMapTool('selectCenter'))
            D.actionSelectArea.triggered.connect(lambda : self.spatialTemporalVis.activateMapTool('selectArea'))
    
            D.actionZoomMaxExtent.triggered.connect(lambda : self.zoomTo('maxExtent'))
            D.actionZoomPixelScale.triggered.connect(lambda: self.zoomTo('pixelScale'))
    
            D.actionZoomIn.triggered.connect(lambda: self.spatialTemporalVis.activateMapTool('zoomIn'))
            D.actionZoomOut.triggered.connect(lambda: self.spatialTemporalVis.activateMapTool('zoomOut'))
            D.actionPan.triggered.connect(lambda: self.spatialTemporalVis.activateMapTool('pan'))
            D.actionAddMapView.triggered.connect(self.spatialTemporalVis.createMapView)
    
            D.actionAddTSD.triggered.connect(lambda : self.ua_addTSImages())
            D.actionRemoveTSD.triggered.connect(lambda: self.TS.removeDates(self.ui.dockTimeSeries.selectedTimeSeriesDates()))
            D.actionRedraw.triggered.connect(self.spatialTemporalVis.redraw)
    
            D.actionClearTS.triggered.connect(self.clearTimeSeries)
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
            D.actionSaveTS.triggered.connect(self.ua_saveTSFile)
            D.actionAddTSExample.triggered.connect(self.ua_loadExampleTS)
    
    
            #connect buttons with actions
    
            D.actionAbout.triggered.connect(lambda: AboutDialogUI(self.ui).exec_())
            D.actionSettings.triggered.connect(lambda : PropertyDialogUI(self.ui).exec_())
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
            D.actionFirstTSD.triggered.connect(lambda: self.setDOISliderValue('first'))
            D.actionLastTSD.triggered.connect(lambda: self.setDOISliderValue('last'))
            D.actionNextTSD.triggered.connect(lambda: self.setDOISliderValue('next'))
            D.actionPreviousTSD.triggered.connect(lambda: self.setDOISliderValue('previous'))
    
    
    
            D.dockRendering.actionSetSubsetSize.triggered.connect(lambda : self.spatialTemporalVis.setSubsetSize(
                                                    D.dockRendering.subsetSize()))
            D.actionSetExtent.triggered.connect(lambda: self.spatialTemporalVis.setSpatialExtent(self.ui.spatialExtent()))
    
            self.canvasCrs = QgsCoordinateReferenceSystem()
    
        def loadImageFiles(self, files):
            assert isinstance(files, list)
            self.TS.addFiles(files)
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
    
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
    
    
        def loadTimeSeries(self, path=None, n_max=None):
            if path is None or path is False:
                path = QFileDialog.getOpenFileName(self.ui, 'Open Time Series file', '')
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
    
    
            if os.path.exists(path):
                M = self.ui.dockTimeSeries.tableView_TimeSeries.model()
                M.beginResetModel()
                self.clearTimeSeries()
                self.TS.loadFromFile(path, n_max=n_max)
                M.endResetModel()
    
        def zoomTo(self, key):
            if key == 'maxExtent':
                ext = self.TS.getMaxSpatialExtent(self.ui.dockNavigation.crs())
                self.spatialTemporalVis.setSpatialExtent(ext)
            elif key == 'pixelScale':
                s = ""
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
    
    
    
        def icon(self):
            return TimeSeriesViewer.icon()
    
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
        def timeseriesChanged(self):
    
                    extent = self.TS.getMaxSpatialExtent()
                    self.spatialTemporalVis.setSubsetSize(self.ui.dockRendering.subsetSize())
                    self.spatialTemporalVis.setSpatialExtent(extent)
    
                if len(self.spatialTemporalVis.MVC) == 0:
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
                    # add two empty band-views by default
    
                    self.spatialTemporalVis.createMapView()
                    self.spatialTemporalVis.createMapView()
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
    
    
            path = QFileDialog.getSaveFileName(self.ui, caption='Save Time Series file')
    
            if path is not None:
                self.TS.saveToFile(path)
    
    
        def ua_loadExampleTS(self):
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
            from timeseriesviewer import PATH_EXAMPLE_TIMESERIES
            if not os.path.exists(PATH_EXAMPLE_TIMESERIES):
    
                QMessageBox.information(self.ui, 'File not found', '{} - this file describes an exemplary time series.'.format(path_example))
    
    unknown's avatar
    unknown committed
        def ua_selectByRectangle(self):
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
            if self.RectangleMapTool is not None:
    
    unknown's avatar
    unknown committed
    
        def ua_selectByCoordinate(self):
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
            if self.PointMapTool is not None:
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
        #todo: define as qt slot
    
        def setSpatialSubset(self, spatialExtent):
            #keep specified CRS but translate extent
            oldExtent = self.ui.spatialExtent()
    
            self.ui.setSpatialExtent(extent)
    
            self.spatialTemporalVis.setSpatialExtent(extent)
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
        def qgs_handleMouseDown(self, pt, btn):
    
    unknown's avatar
    unknown committed
    
    
        def ua_TSprogress(self, v_min, v, v_max):
            assert v_min <= v and v <= v_max
    
            if v_min < v_max:
    
                if P.minimum() != v_min or P.maximum() != v_max:
                    P.setRange(v_min, v_max)
                else:
                    s = ""
    
                P.setValue(v)
    
    unknown's avatar
    unknown committed
    
    
        def datesAdded(self, dates):
            assert isinstance(dates, list)
    
            self.ui.dockTimeSeries.tableView_TimeSeries.resizeColumnsToContents()
    
    unknown's avatar
    unknown committed
    
    
        # noinspection PyMethodMayBeStatic
        def tr(self, message):
            """Get the translation for a string using Qt translation API.
    
            We implement this ourselves since we do not inherit QObject.
    
            :param message: String for translation.
            :type message: str, QString
    
            :returns: Translated version of message.
            :rtype: QString
            """
            # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
            return QCoreApplication.translate('EnMAPBox', message)
    
    
    
    
    
    
        def ua_addTSD_to_QGIS(self, TSD, bands):
    
    unknown's avatar
    unknown committed
        def unload(self):
    
            """Removes the plugin menu item and icon """
            self.iface.removeToolBarIcon(self.action)
    
    unknown's avatar
    unknown committed
    
        def run(self):
    
    unknown's avatar
    unknown committed
    
    
    
        def scrollToDate(self, date_of_interest):
    
            HBar = self.ui.scrollArea_imageChips.horizontalScrollBar()
    
            TSDs = list(self.CHIPWIDGETS.keys())
            if len(TSDs) == 0:
    
                return
    
            #get date INDEX that is closest to requested date
    
            if type(date_of_interest) is str:
                date_of_interest = np.datetime64(date_of_interest)
    
    
            if type(date_of_interest) is np.datetime64:
                i_doi = TSDs.index(sorted(TSDs, key=lambda TSD: abs(date_of_interest - TSD.getDate()))[0])
            else:
                i_doi = date_of_interest
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
            step = int(float(HBar.maximum()) / (len(TSDs)+1))
            HBar.setSingleStep(step)
            HBar.setPageStep(step*5)
            HBar.setValue(i_doi * step)
    
        def showSubset(self, renderJob, pixmap):
    
            assert isinstance(renderJob, RenderJob)
            chipLabel = self.CHIPWIDGETS[renderJob.TSD][renderJob.destinationId]
            chipLabel.setPixmap(pixmap)
            chipLabel.setFixedSize(pixmap.size())
            chipLabel.update()
            s = ""
    
        def ua_collect_date(self, ICL, event):
    
            if self.ui.rb_labeling_activate.isChecked():
                txt = self.ui.tb_labeling_text.toPlainText()
    
                reg = re.compile('\d{4}-\d{2}-\d{2}', re.I | re.MULTILINE)
                dates = set([np.datetime64(m) for m in reg.findall(txt)])
                doi = ICL.TSD.getDate()
    
    
                if event.button() == Qt.LeftButton:
    
                    dates.add(doi)
    
                elif event.button() == Qt.MiddleButton and doi in dates:
                    dates.remove(doi)
    
    
                dates = sorted(list(dates))
                txt = ' '.join([d.astype(str) for d in dates])
    
                self.ui.tb_labeling_text.setText(txt)
    
    unknown's avatar
    unknown committed
    
        def clearLayoutWidgets(self, L):
            if L is not None:
                while L.count():
                    w = L.takeAt(0)
    
                    if w.widget():
                        w.widget().deleteLater()
    
    unknown's avatar
    unknown committed
                    #if w is not None:
                    #    w.widget().deleteLater()
    
    unknown's avatar
    unknown committed
    
        def ua_addTSImages(self, files=None):
            if files is None:
                files = QFileDialog.getOpenFileNames()
    
            if files:
                self.TS.addFiles(files)
    
    
        def clearTimeSeries(self):
    
    unknown's avatar
    unknown committed
            #remove views
    
    
            M = self.ui.dockTimeSeries.tableView_TimeSeries.model()
    
    unknown's avatar
    unknown committed
            M.beginResetModel()
            self.TS.clear()
            M.endResetModel()
    
    
        def getSelectedTSDs(self):
    
            TV = self.ui.tableView_TimeSeries
    
            return [TVM.getTimeSeriesDatumFromIndex(idx) for idx in TV.selectionModel().selectedRows()]
    
    def disconnect_signal(signal):
        while True:
            try:
                signal.disconnect()
            except TypeError:
                break
    
    unknown's avatar
    unknown committed
    
    
    
    unknown's avatar
    unknown committed
        from scipy.misc import toimage
        toimage(data).show()
    
    
    unknown's avatar
    unknown committed
    def run_tests():
    
        if False:
    
            pathImg = r'O:\SenseCarbonProcessing\BJ_NOC\01_RasterData\00_VRTs\02_Cutted\2014-07-26_LC82270652014207LGN00_BOA.vrt'
            pathMsk = r'O:\SenseCarbonProcessing\BJ_NOC\01_RasterData\00_VRTs\02_Cutted\2014-07-26_LC82270652014207LGN00_Msk.vrt'
    
    
            if False:
                TSD = TimeSeriesDatum(pathImg)
                TSD.setMask(pathMsk)
    
    unknown's avatar
    unknown committed
    
    
                c = [670949.883,-786288.771]
    
                w_x = w_y = 1000 #1km box
                srs = TSD.getSpatialReference()
                ring = ogr.Geometry(ogr.wkbLinearRing)
                import itertools
                for x,y in itertools.product([1000, -1000], repeat=2):
                    ring.AddPoint(c[0]+x, c[1]+y)
                ring.AssignSpatialReference(srs)
                bb = ogr.Geometry(ogr.wkbPolygon)
                bb.AddGeometry(ring)
                bb.AssignSpatialReference(srs)
    
    unknown's avatar
    unknown committed
    
    
    
    
            def getChip3d_OLD(chips, r,g,b, range_r, range_g, range_b):
    
                nl, ns = chips[r].shape
                a3d = np.ndarray((3,nl,ns), dtype='float')
    
                rgb_idx = [r,g,b]
                ranges = [range_r, range_g, range_b]
    
                for i, rgb_i in enumerate(rgb_idx):
                    range = ranges[i]
                    data = chips[rgb_i].astype('float')
                    data -= range[0]
                    data *= 255./range[1]
                    a3d[i,:] = data
    
                np.clip(a3d, 0, 255, out=a3d)
    
                return a3d.astype('uint8')
    
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
            app  = QApplication([])
            main = PictureTest()
    
    unknown's avatar
    unknown committed
            main.show()
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
    
    
    unknown's avatar
    unknown committed
            range_r = [0,500]
            range_g = [0,500]
            range_b = [0,500]
    
            bands = [3,2,1]
    
            #chipData = TSD.readSpatialChip(bb,bands=bands )
    
    unknown's avatar
    unknown committed
    
    
            #main.addNumpy(getChip3d(chipData, bands, (range_r, range_g, range_b)))
    
    unknown's avatar
    unknown committed
            app.exec_()
            exit(0)
    
        if False:
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
            dirSrcLS = r'O:\SenseCarbonProcessing\BJ_NOC\01_RasterData\00_VRTs\02_Cutted'
            filesImgLS = file_search(dirSrcLS, '2014*_BOA.vrt')
            filesMsk = file_search(dirSrcLS, '2014*_Msk.vrt')
            TS = TimeSeries(imageFiles=filesImgLS, maskFiles=filesMsk)
    
    unknown's avatar
    unknown committed
    
            print(TS)
            exit(0)
    
    
    
    unknown's avatar
    unknown committed
        if True:
    
    unknown's avatar
    unknown committed
            import PyQt4.Qt
    
            app=PyQt4.Qt.QApplication([])
    
            S = TimeSeriesViewer(None)
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
            S.run()
    
            if True:
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
                dirSrcLS = r'\\141.20.140.107\NAS_Processing\SenseCarbonProcessing\BJ_NOC\01_RasterData\02_CuttedVRT'
    
                dirSrcRE = r'\\141.20.140.91\SAN_RSDBrazil\RapidEye\3A_VRTs'
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
                filesImgLS = file_search(dirSrcLS, '20*_BOA.vrt')
    
                filesImgRE = file_search(dirSrcRE, '*.vrt', recursive=True)
    
                #filesMsk = file_search(dirSrc, '2014*_Msk.vrt')
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
                S.ua_addTSImages(files=filesImgLS[0:2])
                S.ua_addTSImages(files=filesImgRE[0:2])
    
                #S.ua_addTSImages(files=filesImgLS)
                #S.ua_addTSImages(files=filesImgRE)
    
                #S.ua_loadExampleTS()
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
                #S.ua_addTSMasks(files=filesMsk)
    
            #S.ua_addView(bands=[4,5,3])
    
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
    
        if False:
            import qgis.core
    
            # supply path to where is your qgis installed
    
    
            #QgsApplication.setPrefixPath("/Applications/QGIS_2.12.app/Contents/MacOS/QGIS", True)
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
    
            # load providers
            QgsApplication.initQgis()
    
            a = QgsApplication([], True)
    
    
            S = TimeSeriesViewer(a)
    
    unknown's avatar
    unknown committed
            S.run()
    
    unknown's avatar
    unknown committed
            if True:
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
                dirSrcLS = r'O:\SenseCarbonProcessing\BJ_NOC\01_RasterData\00_VRTs\02_Cutted'
                filesImgLS = file_search(dirSrcLS, '2014*_BOA.vrt')
                filesMsk = file_search(dirSrcLS, '2014*_Msk.vrt')
                S.ua_addTSImages(files=filesImgLS)
    
                S.ua_addTSMasks(files=filesMsk)
    
    unknown's avatar
    unknown committed
    
            #S.ua_addView(bands=[4,5,3])
    
            a.exec_()
    
    unknown's avatar
    unknown committed
        print('Tests done')
        exit(0)
    
    
    
    if __name__ == '__main__':
    
    unknown's avatar
    unknown committed
        run_tests()
    
    
        newExtent = model.convertSpatialExten(exten, crs)
    
        ext = SpatialExtent()
    
    
    unknown's avatar
    unknown committed
        print('Done')