QGIS/python/plugins/processing/algs/qgis/RasterSampling.py

198 lines
6.4 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
"""
***************************************************************************
RasterSampling.py
-----------------------
Date : July 2018
Copyright : (C) 2018 by Matteo Ghetta
Email : matteo dot ghetta at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
__author__ = 'Matteo Ghetta'
__date__ = 'July 2018'
__copyright__ = '(C) 2018, Matteo Ghetta'
import os
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtCore import QVariant
from qgis.core import (NULL,
QgsApplication,
QgsField,
QgsFeatureSink,
QgsRaster,
QgsPointXY,
QgsProcessing,
2018-07-12 09:27:56 +02:00
QgsProcessingParameterRasterLayer,
2018-07-12 10:27:03 +02:00
QgsProcessingParameterString,
QgsProcessingParameterDefinition,
2018-07-12 11:30:48 +02:00
QgsCoordinateTransform,
QgsFields,
QgsProcessingUtils,
QgsProcessingException,
QgsProcessingParameterFeatureSource,
QgsProcessingParameterFeatureSink)
from processing.algs.qgis.QgisAlgorithm import QgisAlgorithm
class RasterSampling(QgisAlgorithm):
INPUT = 'INPUT'
RASTERCOPY = 'RASTERCOPY'
2018-07-12 10:27:03 +02:00
COLUMN_PREFIX = 'COLUMN_PREFIX'
OUTPUT = 'OUTPUT'
def name(self):
return 'rastersampling'
def displayName(self):
2018-07-16 21:12:49 +10:00
return self.tr('Sample raster values')
def group(self):
return self.tr('Raster analysis')
def groupId(self):
return 'rasteranalysis'
def __init__(self):
super().__init__()
def initAlgorithm(self, config=None):
self.addParameter(
QgsProcessingParameterFeatureSource(
self.INPUT,
self.tr('Input Point Layer'),
[QgsProcessing.TypeVectorPoint]
)
)
self.addParameter(
2018-07-12 09:27:56 +02:00
QgsProcessingParameterRasterLayer(
self.RASTERCOPY,
self.tr('Raster Layer to sample'),
)
)
columnPrefix = QgsProcessingParameterString(
self.COLUMN_PREFIX,
self.tr('Output column prefix'), 'rvalue'
2018-07-12 10:27:03 +02:00
)
columnPrefix.setFlags(columnPrefix.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
self.addParameter(columnPrefix)
2018-07-12 10:27:03 +02:00
self.addParameter(
QgsProcessingParameterFeatureSink(
self.OUTPUT,
self.tr('Sampled Points')
)
)
def processAlgorithm(self, parameters, context, feedback):
source = self.parameterAsSource(
parameters,
self.INPUT,
context
)
sampled_raster = self.parameterAsRasterLayer(
parameters,
self.RASTERCOPY,
context
)
2018-07-12 10:27:03 +02:00
columnPrefix = self.parameterAsString(
parameters,
self.COLUMN_PREFIX,
context
)
if source is None:
raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT))
source_fields = source.fields()
raster_fields = QgsFields()
# append field to vector as columnPrefix_bandCount
for b in range(sampled_raster.bandCount()):
2018-07-12 09:27:56 +02:00
raster_fields.append(QgsField(
2018-07-12 10:27:03 +02:00
columnPrefix + str('_{}'.format(b + 1)), QVariant.Double
2018-07-12 10:00:53 +02:00
)
2018-07-12 09:27:56 +02:00
)
# combine all the vector fields
out_fields = QgsProcessingUtils.combineFields(source_fields, raster_fields)
(sink, dest_id) = self.parameterAsSink(
parameters,
self.OUTPUT,
context,
out_fields,
source.wkbType(),
source.sourceCrs()
)
if sink is None:
raise QgsProcessingException(self.invalidSinkError(parameters, self.OUTPUT))
total = 100.0 / source.featureCount() if source.featureCount() else 0
features = source.getFeatures()
2018-07-12 11:30:48 +02:00
# create the coordinates transformation context
ct = QgsCoordinateTransform(source.sourceCrs(), sampled_raster.crs(), context.transformContext())
for n, i in enumerate(source.getFeatures()):
2018-07-16 08:01:02 +02:00
attrs = i.attributes()
if i.geometry().isMultipart() and i.geometry().constGet().partCount() > 1:
sink.addFeature(i, QgsFeatureSink.FastInsert)
feedback.setProgress(int(n * total))
feedback.reportError(self.tr('Impossible to sample data of multipart feature {}.').format(i.id()))
continue
2018-07-12 09:52:41 +02:00
2018-07-12 11:30:48 +02:00
# get the feature geometry as point
point = QgsPointXY()
if i.geometry().isMultipart():
point = i.geometry().asMultiPoint()[0]
else:
point = i.geometry().asPoint()
2018-07-12 11:30:48 +02:00
# reproject to raster crs
try:
point = ct.transform(point)
except QgsCsException:
2018-07-12 12:45:18 +02:00
for b in range(sampled_raster.bandCount()):
2018-07-16 08:01:02 +02:00
attrs.append(None)
i.setAttributes(attrs)
sink.addFeature(i, QgsFeatureSink.FastInsert)
feedback.setProgress(int(n * total))
2018-07-12 11:30:48 +02:00
feedback.reportError(self.tr('Could not reproject feature {} to raster CRS').format(i.id()))
2018-07-16 08:01:02 +02:00
continue
for b in range(sampled_raster.bandCount()):
value, ok = sampled_raster.dataProvider().sample(point, b + 1)
if ok:
attrs.append(value)
else:
attrs.append(NULL)
2018-07-12 09:27:56 +02:00
i.setAttributes(attrs)
sink.addFeature(i, QgsFeatureSink.FastInsert)
feedback.setProgress(int(n * total))
return {self.OUTPUT: dest_id}