Skip to content
Snippets Groups Projects
sensecarbon_tsv.py 47.7 KiB
Newer Older
  • Learn to ignore specific revisions
  • Benjamin Jakimow's avatar
    Benjamin Jakimow committed
            if type(geometry) is QgsRectangle:
                center = geometry.center()
                x = center.x()
                y = center.y()
    
                dx = geometry.xMaximum() - geometry.xMinimum()
                dy = geometry.yMaximum() - geometry.yMinimum()
    
            if type(geometry) is QgsPoint:
                x = geometry.x()
                y = geometry.y()
    
            if self.TS.srs is not None and not self.TS.srs.IsSame(canvas_srs):
                print('Convert canvas coordinates to time series SRS')
                g = ogr.Geometry(ogr.wkbPoint)
                g.AddPoint(x,y)
                g.AssignSpatialReference(canvas_srs)
                g.TransformTo(self.TS.srs)
                x = g.GetX()
                y = g.GetY()
    
    
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
            D.doubleSpinBox_subset_size_x.setValue(dx)
            D.doubleSpinBox_subset_size_y.setValue(dy)
            D.spinBox_coordinate_x.setValue(x)
            D.spinBox_coordinate_y.setValue(y)
    
        def qgs_handleMouseDown(self, pt, btn):
    
            print('MOUSE DOWN')
            print(pt)
            print(btn)
    
    
    unknown's avatar
    unknown committed
    
    
        def ua_TSprogress(self, v_min, v, v_max):
            assert v_min <= v and v <= v_max
            P = self.dlg.progressBar
            if P.minimum() != v_min or P.maximum() != v_max:
                P.setRange(v_min, v_max)
            P.setValue(v)
    
        def ua_datumAdded(self):
            cb_centerdate = self.dlg.cb_centerdate
            cb_centerdate.clear()
            if len(self.TS) > 0:
                if self.dlg.spinBox_coordinate_x.value() == 0.0 and \
                   self.dlg.spinBox_coordinate_y.value() == 0.0:
                    xmin, ymin, xmax, ymax = self.TS.getMaxExtent()
                    self.dlg.spinBox_coordinate_x.setRange(xmin, xmax)
                    self.dlg.spinBox_coordinate_y.setRange(ymin, ymax)
                    self.dlg.spinBox_coordinate_x.setValue(0.5*(xmin+xmax))
                    self.dlg.spinBox_coordinate_y.setValue(0.5*(ymin+ymax))
                    s =""
    
                    for date in self.TS.getDates():
                        cb_centerdate.addItem(date.astype('str'), date)
                s = ""
            self.dlg.tableView_TimeSeries.resizeColumnsToContents()
    
        def check_enabled(self):
            D = self.dlg
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
            hasTS = len(self.TS) > 0 or DEBUG
    
    unknown's avatar
    unknown committed
            hasTSV = len(self.VIEWS) > 0
            hasQGIS = qgis_available
    
            D.tabWidget_viewsettings.setEnabled(hasTS)
            D.btn_showPxCoordinate.setEnabled(hasTS and hasTSV)
            D.btn_selectByCoordinate.setEnabled(hasQGIS)
            D.btn_selectByRectangle.setEnabled(hasQGIS)
    
    
    
    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 add_action(
            self,
            icon_path,
            text,
            callback,
            enabled_flag=True,
            add_to_menu=True,
            add_to_toolbar=True,
            status_tip=None,
            whats_this=None,
            parent=None):
            """Add a toolbar icon to the toolbar.
    
            :param icon_path: Path to the icon for this action. Can be a resource
                path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
            :type icon_path: str
    
            :param text: Text that should be shown in menu items for this action.
            :type text: str
    
            :param callback: Function to be called when the action is triggered.
            :type callback: function
    
            :param enabled_flag: A flag indicating if the action should be enabled
                by default. Defaults to True.
            :type enabled_flag: bool
    
            :param add_to_menu: Flag indicating whether the action should also
                be added to the menu. Defaults to True.
            :type add_to_menu: bool
    
            :param add_to_toolbar: Flag indicating whether the action should also
                be added to the toolbar. Defaults to True.
            :type add_to_toolbar: bool
    
            :param status_tip: Optional text to show in a popup when mouse pointer
                hovers over the action.
            :type status_tip: str
    
            :param parent: Parent widget for the new action. Defaults None.
            :type parent: QWidget
    
            :param whats_this: Optional text to show in the status bar when the
                mouse pointer hovers over the action.
    
            :returns: The action that was created. Note that the action is also
                added to self.actions list.
            :rtype: QAction
            """
    
            icon = QIcon(icon_path)
            action = QAction(icon, text, parent)
            action.triggered.connect(callback)
            action.setEnabled(enabled_flag)
    
            if status_tip is not None:
                action.setStatusTip(status_tip)
    
            if whats_this is not None:
                action.setWhatsThis(whats_this)
    
            if add_to_toolbar:
                self.toolbar.addAction(action)
    
            if add_to_menu:
                self.iface.addPluginToMenu(
                    self.menu,
                    action)
    
            self.actions.append(action)
    
            return action
    
        def initGui(self):
            """Create the menu entries and toolbar icons inside the QGIS GUI."""
    
    
    unknown's avatar
    unknown committed
            self.icon_path = ':/plugins/SenseCarbon/icon.png'
    
    unknown's avatar
    unknown committed
            self.add_action(
                self.icon_path,
    
    unknown's avatar
    unknown committed
                text=self.tr(u'SenseCarbon Time Series Viewer'),
    
    unknown's avatar
    unknown committed
                callback=self.run,
                parent=self.iface.mainWindow())
    
    
        def unload(self):
            """Removes the plugin menu item and icon from QGIS GUI."""
            for action in self.actions:
                self.iface.removePluginMenu(
    
    unknown's avatar
    unknown committed
                    self.tr(u'&SenseCarbon Time Series Viewer'),
    
    unknown's avatar
    unknown committed
                    action)
                self.iface.removeToolBarIcon(action)
            # remove the toolbar
            del self.toolbar
    
        def run(self):
            """Run method that performs all the real work"""
    
            #self.dlg.setWindowIcon(QIcon(self.icon_path))
            # show the GUI
            self.dlg.show()
    
            if DEBUG:
                pass
    
        def ua_showPxCoordinate_start(self):
    
    unknown's avatar
    unknown committed
    
            if len(self.TS) == 0:
                return
    
    unknown's avatar
    unknown committed
            D = self.dlg
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
            dx = D.doubleSpinBox_subset_size_x.value() * 0.5
    
    unknown's avatar
    unknown committed
            dy = D.doubleSpinBox_subset_size_y.value() * 0.5
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
    
            cx = D.spinBox_coordinate_x.value()
            cy = D.spinBox_coordinate_y.value()
    
    unknown's avatar
    unknown committed
    
    
    
            ring = ogr.Geometry(ogr.wkbLinearRing)
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
            ring.AddPoint(cx - dx, cy + dy)
            ring.AddPoint(cx + dx, cy + dy)
            ring.AddPoint(cx + dx, cy - dy)
            ring.AddPoint(cx - dx, cy - dy)
    
    unknown's avatar
    unknown committed
    
            bb = ogr.Geometry(ogr.wkbPolygon)
            bb.AddGeometry(ring)
            bbWkt = bb.ExportToWkt()
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
            srsWkt = None
            if self.TS.srs:
                bb.AssignSpatialReference(self.TS.srs)
    
                srsWkt = bb.GetSpatialReference().ExportToWkt()
    
    unknown's avatar
    unknown committed
    
    
            self.ImageChipBuffer.setBoundingBox(bb)
    
            D = self.dlg
    
    unknown's avatar
    unknown committed
            ratio = dx / dy
            size_px = D.spinBox_chipsize_max.value()
            if ratio > 1: #x is largest side
                size_x = size_px
                size_y = int(size_px / ratio)
            else: #y is largest
                size_y = size_px
                size_x = int(size_px * ratio)
            #size_x = D.spinBox_chipsize_x.value()
            #size_y = D.spinBox_chipsize_y.value()
    
    unknown's avatar
    unknown committed
    
            ScrollArea = D.scrollArea
            #S.setWidgetResizable(False)
            #remove widgets
    
    
    unknown's avatar
    unknown committed
            #get the dates of interes
            dates_of_interest = list()
            if D.rb_showEntireTS.isChecked():
                dates_of_interest = self.TS.getDates()
            elif D.rb_showSelectedDates.isChecked():
                dates_of_interest = self.getSelectedDates()
            elif D.rb_showTimeWindow.isChecked():
                TSD = D.cb_timeWindow_doi.itemData(D.cb_timeWindow_doi.currentIndex())
                s = ""
                allDates = self.TS.getDates()
                i_doi = allDates.index(TSD)
                i0 = max([0, i_doi-D.sb_ndates_before.value()])
                ie = min([i_doi + D.sb_ndates_after.value(), len(allDates)])
                dates_of_interest = allDates[i0:ie]
    
    
    
    unknown's avatar
    unknown committed
            if self.CPV is None:
                ScrollArea.setLayout(QHBoxLayout())
                self.CPV = ScrollArea.layout()
            else:
    
    unknown's avatar
    unknown committed
                diff = set(dates_of_interest)
    
    unknown's avatar
    unknown committed
                diff = diff.symmetric_difference(self.CHIPWIDGETS.keys())
    
    unknown's avatar
    unknown committed
    
            self.clearLayoutWidgets(self.CPV)
            self.CHIPWIDGETS.clear()
    
            if False:
    
    unknown's avatar
    unknown committed
                if len(diff) != 0:
                    self.clearLayoutWidgets(self.CPV)
    
    unknown's avatar
    unknown committed
                    self.CHIPWIDGETS.clear()
    
    unknown's avatar
    unknown committed
                else:
                    for date, viewList in self.CHIPWIDGETS.items():
                        for imageLabel in viewList:
                            imageLabel.clear()
    
            #initialize image labels
    
    
    unknown's avatar
    unknown committed
            for i, date in enumerate(dates_of_interest):
    
    unknown's avatar
    unknown committed
    
                #LV = QVBoxLayout()
                #LV.setSizeConstraint(QLayout.SetNoConstraint)
                TSD = self.TS.data[date]
                textLabel = QLabel('{}'.format(date.astype(str)))
                textLabel.setToolTip(str(TSD))
                #textLabel.setMinimumWidth(size_x)
                #textLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
                self.CPV.addWidget(textLabel, 0, i)
                viewList = list()
                for j, view in enumerate(self.VIEWS):
    
    unknown's avatar
    unknown committed
                    imageLabel = QLabel()
    
    unknown's avatar
    unknown committed
                    imageLabel.setFrameShape(QFrame.StyledPanel)
                    imageLabel.setMinimumSize(size_x, size_y)
    
    unknown's avatar
    unknown committed
                    imageLabel.setMaximumSize(size_x+1, size_y+1)
                    imageLabel.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
    
    unknown's avatar
    unknown committed
                    viewList.append(imageLabel)
                    self.CPV.addWidget(imageLabel,j+1, i)
                self.CHIPWIDGETS[date] = viewList
    
            #LH.addSpacerItem(Spacer(size_x, size_y))
            ScrollArea.show()
    
            #fill image labels
            missing_dates = set()
            missing_bands = set()
            for i, date in enumerate(self.TS.getDates()):
                required_bands = set()
                for j, view in enumerate(self.VIEWS):
                    required_bands = required_bands.union(set(view.getBands()))
    
                missing = self.ImageChipBuffer.getMissingBands(date, required_bands)
                if len(missing) == 0:
                    self.ua_showPxCoordinate_addChips(None, date=date)
                else:
                    missing_dates.add(date)
                    missing_bands = missing_bands.union(missing)
    
            if len(missing_dates) > 0:
                self.TS.getSpatialChips_parallel(bbWkt, srsWkt, dates=list(missing_dates), bands=list(missing_bands))
    
        def ua_showPxCoordinate_addChips(self, results, date=None):
    
            if results is not None:
                date, chipData = results
                self.ImageChipBuffer.addDataCube(date, chipData)
    
            viewList = self.CHIPWIDGETS.get(date)
    
    unknown's avatar
    unknown committed
            if viewList:
                for j, view in enumerate(self.VIEWS):
    
                    imageLabel = viewList[j]
    
    unknown's avatar
    unknown committed
                    imageLabel.clear()
                    #imageLabel.setScaledContents(True)
    
    
                    rgb = self.ImageChipBuffer.getChipRGB(date, view)
                    rgb2 = rgb.transpose([1,2,0]).copy('C')
                    qImg = qimage2ndarray.array2qimage(rgb2)
                    #img = QImage(rgb2.data, nl, ns, QImage.Format_RGB888)
    
                    pxMap = QPixmap.fromImage(qImg)
    
    unknown's avatar
    unknown committed
                    pxMap = pxMap.scaled(imageLabel.size(), Qt.KeepAspectRatio)
    
    unknown's avatar
    unknown committed
                    imageLabel.setPixmap(pxMap)
    
    unknown's avatar
    unknown committed
                    #imageLabel.update()
                    imageLabel.adjustSize()
    
    unknown's avatar
    unknown committed
    
                    s = ""
                    pass
    
    unknown's avatar
    unknown committed
                self.CPV.layout().update()
    
    unknown's avatar
    unknown committed
            s = ""
    
            pass
    
        def clearLayoutWidgets(self, L):
            if L is not None:
                while L.count():
                    w = L.takeAt(0)
                    w.widget().deleteLater()
                    #if w is not None:
                    #    w.widget().deleteLater()
    
        def ua_addTSImages(self, files=None):
            if files is None:
                files = QFileDialog.getOpenFileNames()
    
            if files:
                M = self.dlg.tableView_TimeSeries.model()
                M.beginResetModel()
                self.TS.addFiles(files)
                M.endResetModel()
    
                nb = self.TS.nb
                if len(self.VIEWS) == 0 and nb > 0:
                    if nb < 3:
                        bands = [1,1,1]
                    else:
                        self.ua_addView([3,2,1])
                        if nb >= 5:
                            self.ua_addView([4,5,3])
    
    
            self.check_enabled()
    
    
        def ua_addTSMasks(self, files=None):
    
            if files is None:
                files = QFileDialog.getOpenFileNames()
    
            l = len(files)
            if l > 0:
                M = self.dlg.tableView_TimeSeries.model()
                M.beginResetModel()
    
    unknown's avatar
    unknown committed
                self.TS.addMasks(files, raise_errors=False)
    
    unknown's avatar
    unknown committed
                M.endResetModel()
    
            self.check_enabled()
    
    
        def setViewNames(self):
            for i, w in enumerate(self.VIEWS):
                w.setTitle('View {}'.format(i+1))
            self.check_enabled()
    
    
    
        def ua_addView(self, bands = [3,2,1]):
            import imagechipviewsettings_widget
    
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
            if len(self.TS.bandnames) > 0:
    
                w = imagechipviewsettings_widget.ImageChipViewSettings(self.TS, parent=self.dlg)
                w.setMaximumSize(w.size())
    
    unknown's avatar
    unknown committed
                #w.setMinimumSize(w.size())
                w.setSizePolicy(QSizePolicy.Fixed,QSizePolicy.MinimumExpanding)
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
                w.setBands(bands)
                w.removeView.connect(lambda : self.ua_removeView(w))
    
    unknown's avatar
    unknown committed
    
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
                L = self.dlg.scrollArea_viewsWidget.layout()
                L.addWidget(w)
                self.dlg.scrollArea_views.show()
    
    unknown's avatar
    unknown committed
                self.VIEWS.append(w)
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
                self.setViewNames()
                self.check_enabled()
    
    unknown's avatar
    unknown committed
    
    
    unknown's avatar
    unknown committed
        def ua_removeTS(self):
            #remove views
    
            M = self.dlg.tableView_TimeSeries.model()
            M.beginResetModel()
            self.TS.clear()
            M.endResetModel()
            self.check_enabled()
    
    
    unknown's avatar
    unknown committed
        def ua_removeTSD(self, dates):
            if dates is None:
    
    unknown's avatar
    unknown committed
                dates = self.getSelectedDates()
    
    
    unknown's avatar
    unknown committed
            M = self.dlg.tableView_TimeSeries.model()
            M.beginResetModel()
    
    unknown's avatar
    unknown committed
            self.TS.removeDates(dates)
    
    unknown's avatar
    unknown committed
            M.endResetModel()
    
    unknown's avatar
    unknown committed
            self.check_enabled()
    
    unknown's avatar
    unknown committed
    
    
        def ua_removeView(self,w):
            self.VIEWS.remove(w)
            L = self.dlg.scrollArea_viewsWidget.layout()
            L.removeWidget(w)
            w.deleteLater()
            self.setViewNames()
    
        def getSelectedDates(self):
            TV = self.dlg.tableView_TimeSeries
            TVM = TV.model()
    
            return [TVM.getTimeSeriesDatumFromIndex(idx).getDate() for idx in TV.selectionModel().selectedRows()]
    
    
    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'
            TSD = TimeSeriesDatum(pathImg)
            TSD.setMask(pathMsk)
    
            print(TSD)
    
            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)
    
    
    
    
            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')
    
            app=QApplication([])
            main=PictureTest()
            main.show()
            range_r = [0,500]
            range_g = [0,500]
            range_b = [0,500]
    
            bands = [3,2,1]
            chipData = TSD.readSpatialChip(bb,bands=bands )
    
            main.addNumpy(getChip3d(chipData, bands, (range_r, range_g, range_b)))
            app.exec_()
            exit(0)
    
        if False:
            dirSrc = r'O:\SenseCarbonProcessing\BJ_NOC\01_RasterData\00_VRTs\02_Cutted'
            filesImg = file_search(dirSrc, '2014*_BOA.vrt')
            filesMsk = file_search(dirSrc, '2014*_Msk.vrt')
            TS = TimeSeries(imageFiles=filesImg, maskFiles=filesMsk)
    
            print(TS)
            exit(0)
    
    
    
    unknown's avatar
    unknown committed
        if True:
    
    unknown's avatar
    unknown committed
            import PyQt4.Qt
            a = PyQt4.Qt.QApplication([])
    
    unknown's avatar
    unknown committed
            S = SenseCarbon_TSV(None)
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
            S.run()
    
            if True:
                dirSrc = r'O:\SenseCarbonProcessing\BJ_NOC\01_RasterData\00_VRTs\02_Cutted'
                filesImg = file_search(dirSrc, '2014*_BOA.vrt')
    
                #filesMsk = file_search(dirSrc, '2014*_Msk.vrt')
                #S.ua_addTSImages(files=filesImg[0:1])
    
                #S.ua_addTSImages(files=filesImg)
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
                #S.ua_addTSMasks(files=filesMsk)
    
            #S.ua_addView(bands=[4,5,3])
    
            a.exec_()
    
        if False:
            import qgis.core
    
            # supply path to where is your qgis installed
    
            QgsApplication.setPrefixPath("/Applications/QGIS_2.12.app/Contents/MacOS/QGIS", True)
    
            # load providers
            QgsApplication.initQgis()
    
            a = QgsApplication([], True)
    
    
    unknown's avatar
    unknown committed
            S = SenseCarbon_TSV(a)
            S.run()
    
    unknown's avatar
    unknown committed
            if True:
    
    Benjamin Jakimow's avatar
    Benjamin Jakimow committed
                dirSrc = r'O:\SenseCarbonProcessing\BJ_NOC\01_RasterData\00_VRTs\02_Cutted'
                filesImg = file_search(dirSrc, '2014*_BOA.vrt')
                filesMsk = file_search(dirSrc, '2014*_Msk.vrt')
                S.ua_addTSImages(files=filesImg)
    
    unknown's avatar
    unknown committed
                #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__':
    
        run_tests()
    
        print('Done')