Skip to content

Commit a7f9018

Browse files
committed
[processing] added native raster calculator algorithm
Conflicts: python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py
1 parent fcc3437 commit a7f9018

File tree

6 files changed

+689
-2
lines changed

6 files changed

+689
-2
lines changed

python/plugins/processing/algs/help/qgis.yaml

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -552,3 +552,18 @@ qgis:voronoipolygons: >
552552

553553
qgis:zonalstatistics:
554554

555+
qgis:rastercalculator: >
556+
This algorithm allows to perform algebraic operations using raster layers.
557+
558+
The resulting layer will have its values computed according to an expression. The expression can contain numerical values, operators and references to any of the layers in the current project. The following functions are also supported:
559+
560+
- sin(), cos(), tan(), atan2(), ln(), log10()
561+
562+
The extent and cellsize can be defined by the user. If the extent is not specified, the minimum extent that covers the input layers will be used. If the cellsize is not specified, the minimum cellsize of all input layers will be used.
563+
564+
The cellsize is assumed to be the same in both X and Y axes.
565+
566+
Layers are refered by their name as displayed in the layer list and the number of the band to use (based on 1), using the pattern 'layer_name@band number'. For instance, the first band from a layer named DEM will be referred as DEM@1.
567+
568+
When using the calculator in the batch interface or from the console, the files to use have to be specified. The corresponding layers are refered using the base name of the file (without the full path). For instance, is using a layer at path/to/my/rasterfile.tif, the first band of that layer will be refered as rasterfile.tif@1.
569+

python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,7 @@
178178
from .GeometryByExpression import GeometryByExpression
179179
from .SnapGeometries import SnapGeometriesToLayer
180180
from .PoleOfInaccessibility import PoleOfInaccessibility
181+
from .RasterCalculator import RasterCalculator
181182
from .CreateAttributeIndex import CreateAttributeIndex
182183
from .DropGeometry import DropGeometry
183184
from .BasicStatistics import BasicStatisticsForField
@@ -245,7 +246,7 @@ def __init__(self):
245246
RemoveNullGeometry(), ExtractByExpression(), ExtendLines(),
246247
ExtractSpecificNodes(), GeometryByExpression(), SnapGeometriesToLayer(),
247248
PoleOfInaccessibility(), CreateAttributeIndex(), DropGeometry(),
248-
BasicStatisticsForField()
249+
BasicStatisticsForField(), RasterCalculator()
249250
]
250251

251252
if hasMatplotlib:
Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
# -*- coding: utf-8 -*-
2+
3+
"""
4+
***************************************************************************
5+
RasterLayerCalculator.py
6+
---------------------
7+
Date : November 2016
8+
Copyright : (C) 2016 by Victor Olaya
9+
Email : volayaf at gmail dot com
10+
***************************************************************************
11+
* *
12+
* This program is free software; you can redistribute it and/or modify *
13+
* it under the terms of the GNU General Public License as published by *
14+
* the Free Software Foundation; either version 2 of the License, or *
15+
* (at your option) any later version. *
16+
* *
17+
***************************************************************************
18+
"""
19+
from processing.modeler.ModelerAlgorithm import ValueFromInput, ValueFromOutput
20+
import os
21+
22+
23+
__author__ = 'Victor Olaya'
24+
__date__ = 'November 2016'
25+
__copyright__ = '(C) 2016, Victor Olaya'
26+
27+
# This will get replaced with a git SHA1 when you do a git archive
28+
29+
__revision__ = '$Format:%H$'
30+
31+
import math
32+
from processing.core.GeoAlgorithm import GeoAlgorithm
33+
from processing.core.parameters import ParameterMultipleInput, ParameterExtent, ParameterString, ParameterRaster, ParameterNumber
34+
from processing.core.outputs import OutputRaster
35+
from processing.tools import dataobjects
36+
from processing.algs.gdal.GdalUtils import GdalUtils
37+
from qgis.core import QgsRectangle
38+
from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry
39+
from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException
40+
from processing.algs.qgis.ui.RasterCalculatorWidgets import LayersListWidgetWrapper, ExpressionWidgetWrapper
41+
42+
class RasterCalculator(GeoAlgorithm):
43+
44+
LAYERS = 'LAYERS'
45+
EXTENT = 'EXTENT'
46+
CELLSIZE = 'CELLSIZE'
47+
EXPRESSION = 'EXPRESSION'
48+
OUTPUT = 'OUTPUT'
49+
50+
def defineCharacteristics(self):
51+
self.name, self.i18n_name = self.trAlgorithm('Raster calculator')
52+
self.group, self.i18n_group = self.trAlgorithm('Raster')
53+
54+
self.addParameter(ParameterMultipleInput(self.LAYERS,
55+
self.tr('Input layers'),
56+
datatype=dataobjects.TYPE_RASTER,
57+
optional=True,
58+
metadata = {'widget_wrapper': LayersListWidgetWrapper}))
59+
class ParameterExpression(ParameterString):
60+
def evaluateForModeler(self, value, model):
61+
#print value
62+
for i in list(model.inputs.values()):
63+
param = i.param
64+
if isinstance(param, ParameterRaster):
65+
new = "%s@" % os.path.basename(param.value)
66+
old = "%s@" % param.name
67+
value = value.replace(old, new)
68+
69+
for alg in list(model.algs.values()):
70+
for out in alg.algorithm.outputs:
71+
print out, out.value
72+
if isinstance(out, OutputRaster):
73+
if out.value:
74+
new = "%s@" % os.path.basename(out.value)
75+
old = "%s:%s@" % (alg.name, out.name)
76+
value = value.replace(old, new)
77+
return value
78+
79+
self.addParameter(ParameterExpression(self.EXPRESSION, self.tr('Expression'),
80+
multiline=True,
81+
metadata = {'widget_wrapper': ExpressionWidgetWrapper}))
82+
self.addParameter(ParameterNumber(self.CELLSIZE,
83+
self.tr('Cellsize (use 0 or empty to set it automatically)'),
84+
minValue=0.0, default=0.0, optional=True))
85+
self.addParameter(ParameterExtent(self.EXTENT,
86+
self.tr('Output extent'),
87+
optional=True))
88+
self.addOutput(OutputRaster(self.OUTPUT, self.tr('Output')))
89+
90+
91+
def processAlgorithm(self, progress):
92+
expression = self.getParameterValue(self.EXPRESSION)
93+
layersValue = self.getParameterValue(self.LAYERS)
94+
layersDict = {}
95+
if layersValue:
96+
layers = [dataobjects.getObjectFromUri(f) for f in layersValue.split(";")]
97+
layersDict = {os.path.basename(lyr.source()): lyr for lyr in layers}
98+
99+
for lyr in dataobjects.getRasterLayers():
100+
name = lyr.name()
101+
if (name + "@") in expression:
102+
layersDict[name] = lyr
103+
104+
entries = []
105+
for name, lyr in layersDict.iteritems():
106+
for n in xrange(lyr.bandCount()):
107+
entry = QgsRasterCalculatorEntry()
108+
entry.ref = '%s@%i' % (name, n + 1)
109+
entry.raster = lyr
110+
entry.bandNumber = n + 1
111+
entries.append(entry)
112+
113+
output = self.getOutputValue(self.OUTPUT)
114+
extentValue = self.getParameterValue(self.EXTENT)
115+
116+
if extentValue:
117+
extent = extentValue.split(',')
118+
bbox = QgsRectangle(float(extent[0]), float(extent[2]),
119+
float(extent[1]), float(extent[3]))
120+
else:
121+
if layersDict:
122+
bbox = layersDict.values()[0].extent()
123+
for lyr in layersDict.values():
124+
bbox.combineExtentWith(lyr.extent())
125+
else:
126+
raise GeoAlgorithmExecutionException(self.tr("No layers selected"))
127+
def _cellsize(layer):
128+
return (layer.extent().xMaximum() - layer.extent().xMinimum()) / layer.width()
129+
cellsize = self.getParameterValue(self.CELLSIZE) or min([_cellsize(lyr) for lyr in layersDict.values()])
130+
width = math.floor((bbox.xMaximum() - bbox.xMinimum()) / cellsize)
131+
height = math.floor((bbox.yMaximum() - bbox.yMinimum()) / cellsize)
132+
driverName = GdalUtils.getFormatShortNameFromFilename(output)
133+
calc = QgsRasterCalculator(expression,
134+
output,
135+
driverName,
136+
bbox,
137+
width,
138+
height,
139+
entries)
140+
141+
res = calc.processCalculation()
142+
if res == QgsRasterCalculator.ParserError:
143+
raise GeoAlgorithmExecutionException(self.tr("Error parsing formula"))
144+
145+
def processBeforeAddingToModeler(self, algorithm, model):
146+
values = []
147+
expression = algorithm.params[self.EXPRESSION]
148+
for i in list(model.inputs.values()):
149+
param = i.param
150+
if isinstance(param, ParameterRaster) and "%s@" % param.name in expression:
151+
values.append(ValueFromInput(param.name))
152+
153+
if algorithm.name:
154+
dependent = model.getDependentAlgorithms(algorithm.name)
155+
else:
156+
dependent = []
157+
for alg in list(model.algs.values()):
158+
if alg.name not in dependent:
159+
for out in alg.algorithm.outputs:
160+
if (isinstance(out, OutputRaster)
161+
and "%s:%s@" % (alg.name, out.name) in expression):
162+
values.append(ValueFromOutput(alg.name, out.name))
163+
164+
algorithm.params[self.LAYERS] = values

0 commit comments

Comments
 (0)