Skip to content

Commit 5c762ef

Browse files
committed
applied path for #6574
applied patch for multiple grass sessions added points in polygon weighted
1 parent 0b1ebaa commit 5c762ef

11 files changed

+280
-93
lines changed

python/plugins/sextante/ftools/FToolsAlgorithmProvider.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
* *
1717
***************************************************************************
1818
"""
19+
from sextante.ftools.PointsInPolygonWeighted import PointsInPolygonWeighted
1920

2021
__author__ = 'Victor Olaya'
2122
__date__ = 'August 2012'
@@ -76,7 +77,7 @@ class FToolsAlgorithmProvider(AlgorithmProvider):
7677

7778
def __init__(self):
7879
AlgorithmProvider.__init__(self)
79-
self.alglist = [SumLines(), PointsInPolygon(), BasicStatisticsStrings(),
80+
self.alglist = [SumLines(), PointsInPolygon(), PointsInPolygonWeighted(), BasicStatisticsStrings(),
8081
BasicStatisticsNumbers(), NearestNeighbourAnalysis(),
8182
MeanCoords(), LinesIntersection(), UniqueValues(), PointDistance(),
8283
# data management

python/plugins/sextante/ftools/FToolsUtils.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
FToolsUtils.py
66
---------------------
77
Date : September 2012
8-
Copyright : (C) 2012 by Victor Olaya
8+
Copyright : (C) 2012 by Carson Farmer, Victor Olaya
99
Email : volayaf at gmail dot com
1010
***************************************************************************
1111
* *
@@ -17,9 +17,9 @@
1717
***************************************************************************
1818
"""
1919

20-
__author__ = 'Victor Olaya'
20+
__author__ = 'Carson, Farmer, Victor Olaya'
2121
__date__ = 'September 2012'
22-
__copyright__ = '(C) 2012, Victor Olaya'
22+
__copyright__ = '(C) 2012, Carson Farmer, Victor Olaya'
2323
# This will get replaced with a git SHA1 when you do a git archive
2424
__revision__ = '$Format:%H$'
2525

python/plugins/sextante/ftools/PointsInPolygon.py

-1
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,6 @@ def getIcon(self):
5555
def defineCharacteristics(self):
5656
self.name = "Count points in polygon"
5757
self.group = "Analysis tools"
58-
5958
self.addParameter(ParameterVector(self.POLYGONS, "Polygons", ParameterVector.VECTOR_TYPE_POLYGON))
6059
self.addParameter(ParameterVector(self.POINTS, "Points", ParameterVector.VECTOR_TYPE_POINT))
6160
self.addParameter(ParameterString(self.FIELD, "Count field name", "NUMPOINTS"))
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
# -*- coding: utf-8 -*-
2+
3+
"""
4+
***************************************************************************
5+
PointsInPolygon.py
6+
---------------------
7+
Date : August 2012
8+
Copyright : (C) 2012 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 sextante.parameters.ParameterTableField import ParameterTableField
20+
21+
__author__ = 'Victor Olaya'
22+
__date__ = 'August 2012'
23+
__copyright__ = '(C) 2012, Victor Olaya'
24+
# This will get replaced with a git SHA1 when you do a git archive
25+
__revision__ = '$Format:%H$'
26+
27+
import os.path
28+
29+
from PyQt4 import QtGui
30+
from PyQt4.QtCore import *
31+
32+
from qgis.core import *
33+
34+
from sextante.core.GeoAlgorithm import GeoAlgorithm
35+
from sextante.core.QGisLayers import QGisLayers
36+
from sextante.core.SextanteLog import SextanteLog
37+
38+
from sextante.parameters.ParameterVector import ParameterVector
39+
from sextante.parameters.ParameterString import ParameterString
40+
41+
from sextante.outputs.OutputVector import OutputVector
42+
43+
from sextante.ftools import FToolsUtils as utils
44+
45+
46+
class PointsInPolygonWeighted(GeoAlgorithm):
47+
48+
POLYGONS = "POLYGONS"
49+
POINTS = "POINTS"
50+
OUTPUT = "OUTPUT"
51+
FIELD = "FIELD"
52+
WEIGHT = "WEIGHT"
53+
54+
def getIcon(self):
55+
return QtGui.QIcon(os.path.dirname(__file__) + "/icons/sum_points.png")
56+
57+
def defineCharacteristics(self):
58+
self.name = "Count points in polygon(weighted)"
59+
self.group = "Analysis tools"
60+
61+
self.addParameter(ParameterVector(self.POLYGONS, "Polygons", ParameterVector.VECTOR_TYPE_POLYGON))
62+
self.addParameter(ParameterVector(self.POINTS, "Points", ParameterVector.VECTOR_TYPE_POINT))
63+
self.addParameter(ParameterTableField(self.WEIGHT, "Weight field", self.POINTS))
64+
self.addParameter(ParameterString(self.FIELD, "Count field name", "NUMPOINTS"))
65+
66+
self.addOutput(OutputVector(self.OUTPUT, "Result"))
67+
68+
def processAlgorithm(self, progress):
69+
polyLayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.POLYGONS))
70+
pointLayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.POINTS))
71+
fieldName = self.getParameterValue(self.FIELD)
72+
fieldidx = pointLayer.dataProvider().fieldNameIndex(self.getParameterValue(self.WEIGHT))
73+
74+
polyProvider = polyLayer.dataProvider()
75+
pointProvider = pointLayer.dataProvider()
76+
if polyProvider.crs() != pointProvider.crs():
77+
SextanteLog.addToLog(SextanteLog.LOG_WARNING,
78+
"CRS warning: Input layers have non-matching CRS. This may cause unexpected results.")
79+
80+
idxCount, fieldList = utils.findOrCreateField(polyLayer, polyLayer.pendingFields(), fieldName)
81+
82+
writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fieldList,
83+
polyProvider.geometryType(), polyProvider.crs())
84+
85+
spatialIndex = utils.createSpatialIndex(pointProvider)
86+
87+
pointProvider.rewind()
88+
pointProvider.select()
89+
90+
allAttrs = polyLayer.pendingAllAttributesList()
91+
polyLayer.select(allAttrs)
92+
93+
ftPoly = QgsFeature()
94+
ftPoint = QgsFeature()
95+
outFeat = QgsFeature()
96+
geom = QgsGeometry()
97+
98+
current = 0
99+
total = 100.0 / float(polyProvider.featureCount())
100+
hasIntersections = False
101+
102+
while polyLayer.nextFeature(ftPoly):
103+
geom = ftPoly.geometry()
104+
atMap = ftPoly.attributeMap()
105+
106+
count = 0
107+
hasIntersections = False
108+
points = spatialIndex.intersects(geom.boundingBox())
109+
if len(points) > 0:
110+
hasIntersections = True
111+
112+
if hasIntersections:
113+
for i in points:
114+
pointLayer.featureAtId(int(i), ftPoint, True, False)
115+
tmpGeom = QgsGeometry(ftPoint.geometry())
116+
if geom.contains(tmpGeom):
117+
try:
118+
weight = float(ftPoint.attributeMap()[fieldidx])
119+
except:
120+
weight = 1
121+
count += weight
122+
123+
outFeat.setGeometry(geom)
124+
outFeat.setAttributeMap(atMap)
125+
outFeat.addAttribute(idxCount, QVariant(count))
126+
writer.addFeature(outFeat)
127+
128+
current += 1
129+
progress.setPercentage(int(current * total))
130+
131+
del writer

python/plugins/sextante/ftools/ftools_utils.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
ftools_utils.py
66
---------------------
77
Date : August 2012
8-
Copyright : (C) 2012 by Victor Olaya
8+
Copyright : (C) 2012 by Carson Farmer, Victor Olaya
99
Email : volayaf at gmail dot com
1010
***************************************************************************
1111
* *
@@ -17,9 +17,9 @@
1717
***************************************************************************
1818
"""
1919

20-
__author__ = 'Victor Olaya'
20+
__author__ = 'Carson Farmer, Victor Olaya'
2121
__date__ = 'August 2012'
22-
__copyright__ = '(C) 2012, Victor Olaya'
22+
__copyright__ = '(C) 2012, Carson Farmer, Victor Olaya'
2323
# This will get replaced with a git SHA1 when you do a git archive
2424
__revision__ = '$Format:%H$'
2525

python/plugins/sextante/grass/GrassAlgorithm.py

+42-11
Original file line numberDiff line numberDiff line change
@@ -163,11 +163,18 @@ def processAlgorithm(self, progress):
163163
commands = []
164164
self.exportedLayers = {}
165165

166+
# if GRASS session has been created outside of this algorithm then get the list of layers loaded in GRASS
167+
# otherwise start a new session
168+
existingSession = GrassUtils.sessionRunning
169+
if existingSession:
170+
self.exportedLayers = GrassUtils.getSessionLayers()
171+
else:
172+
GrassUtils.startGrassSession()
173+
174+
166175
#self.calculateRegion()
167176
region = str(self.getParameterValue(self.GRASS_REGION_EXTENT_PARAMETER))
168177
regionCoords = region.split(",")
169-
GrassUtils.createTempMapset();
170-
171178
command = "g.region"
172179
command += " n=" + str(regionCoords[3])
173180
command +=" s=" + str(regionCoords[2])
@@ -178,19 +185,26 @@ def processAlgorithm(self, progress):
178185
else:
179186
command +=" res=" + str(self.getParameterValue(self.GRASS_REGION_CELLSIZE_PARAMETER));
180187
commands.append(command)
181-
188+
182189
#1: Export layer to grass mapset
183190
for param in self.parameters:
184191
if isinstance(param, ParameterRaster):
185192
if param.value == None:
186193
continue
187194
value = param.value
188-
commands.append(self.exportRasterLayer(value))
195+
# check if the layer hasn't already been exported in, for example, previous GRASS calls in this session
196+
if value in self.exportedLayers.keys():
197+
continue
198+
else:
199+
commands.append(self.exportRasterLayer(value))
189200
if isinstance(param, ParameterVector):
190201
if param.value == None:
191202
continue
192203
value = param.value
193-
commands.append(self.exportVectorLayer(value))
204+
if value in self.exportedLayers.keys():
205+
continue
206+
else:
207+
commands.append(self.exportVectorLayer(value))
194208
if isinstance(param, ParameterTable):
195209
pass
196210
if isinstance(param, ParameterMultipleInput):
@@ -201,15 +215,21 @@ def processAlgorithm(self, progress):
201215
continue
202216
if param.datatype == ParameterMultipleInput.TYPE_RASTER:
203217
for layer in layers:
204-
commands.append(self.exportRasterLayer(layer))
218+
if layer in self.exportedLayers.keys():
219+
continue
220+
else:
221+
commands.append(self.exportRasterLayer(layer))
205222
elif param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
206223
for layer in layers:
207-
commands.append(self.exportVectorLayer(layer))
224+
if layer in self.exportedLayers.keys():
225+
continue
226+
else:
227+
commands.append(self.exportVectorLayer(layer))
208228

209229
#2: set parameters and outputs
210230
command = self.grassName
211231
for param in self.parameters:
212-
if param.value == None:
232+
if param.value == None or param.value == "":
213233
continue
214234
if param.name == self.GRASS_REGION_CELLSIZE_PARAMETER or param.name == self.GRASS_REGION_EXTENT_PARAMETER:
215235
continue
@@ -238,7 +258,9 @@ def processAlgorithm(self, progress):
238258
if isinstance(out, OutputFile):
239259
command+=(" " + out.name + "=\"" + out.value + "\"");
240260
else:
241-
command+=(" " + out.name + "=" + out.name);
261+
command += (" " + out.name)
262+
out.name += ("_"+str(len(self.exportedLayers))) # make sure output is unique within a session
263+
command += ("=" + out.name)
242264

243265
command += " --overwrite"
244266
commands.append(command)
@@ -254,14 +276,17 @@ def processAlgorithm(self, progress):
254276
command += out.name
255277
command += " output=\"" + filename + "\""
256278
commands.append(command)
279+
# add output file to exported layers, to indicate that they are present in GRASS
280+
self.exportedLayers[filename]= out.name
257281
if isinstance(out, OutputVector):
258282
command = "v.out.ogr -ce input=" + out.name
259283
command += " dsn=\"" + os.path.dirname(out.value) + "\""
260284
command += " format=ESRI_Shapefile"
261285
command += " olayer=" + os.path.basename(out.value)[:-4]
262286
command += " type=auto"
263287
commands.append(command)
264-
288+
self.exportedLayers[filename]= out.name
289+
265290
#4 Run GRASS
266291
loglines = []
267292
loglines.append("GRASS execution commands")
@@ -271,7 +296,12 @@ def processAlgorithm(self, progress):
271296
if SextanteConfig.getSetting(GrassUtils.GRASS_LOG_COMMANDS):
272297
SextanteLog.addToLog(SextanteLog.LOG_INFO, loglines)
273298
GrassUtils.executeGrass(commands, progress);
274-
299+
# if the session has been created outside of this algorithm, add the new GRASS layers to it
300+
# otherwise finish the session
301+
if existingSession:
302+
GrassUtils.addSessionLayers(self.exportedLayers)
303+
else:
304+
GrassUtils.endGrassSession()
275305

276306
def exportVectorLayer(self, orgFilename):
277307
#only export to an intermediate shp if the layer is not file-based.
@@ -319,3 +349,4 @@ def getTempFilename(self):
319349

320350
def commandLineName(self):
321351
return "grass:" + self.name[:self.name.find(" ")]
352+

python/plugins/sextante/grass/GrassAlgorithmProvider.py

-18
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,6 @@
3232
from sextante.grass.GrassUtils import GrassUtils
3333
from sextante.grass.GrassAlgorithm import GrassAlgorithm
3434
from sextante.core.SextanteUtils import SextanteUtils
35-
from sextante.grass.DefineGrassRegionAction import DefineGrassRegionAction
36-
from sextante.grass.DefineGrassRegionFromLayerAction import DefineGrassRegionFromLayerAction
3735

3836
class GrassAlgorithmProvider(AlgorithmProvider):
3937

@@ -52,31 +50,15 @@ def initializeSettings(self):
5250
SextanteConfig.addSetting(Setting(self.getDescription(), GrassUtils.GRASS_WIN_SHELL, "Msys folder", GrassUtils.grassWinShell()))
5351
SextanteConfig.addSetting(Setting(self.getDescription(), GrassUtils.GRASS_LOG_COMMANDS, "Log execution commands", False))
5452
SextanteConfig.addSetting(Setting(self.getDescription(), GrassUtils.GRASS_LOG_CONSOLE, "Log console output", False))
55-
#SextanteConfig.addSetting(Setting(self.getDescription(), GrassUtils.GRASS_AUTO_REGION, "Use min covering region", True))
5653
SextanteConfig.addSetting(Setting(self.getDescription(), GrassUtils.GRASS_LATLON, "Coordinates are lat/lon", False))
57-
#=======================================================================
58-
# SextanteConfig.addSetting(Setting(self.getDescription(), GrassUtils.GRASS_REGION_XMIN, "GRASS Region min x", 0))
59-
# SextanteConfig.addSetting(Setting(self.getDescription(), GrassUtils.GRASS_REGION_YMIN, "GRASS Region min y", 0))
60-
# SextanteConfig.addSetting(Setting(self.getDescription(), GrassUtils.GRASS_REGION_XMAX, "GRASS Region max x", 1000))
61-
# SextanteConfig.addSetting(Setting(self.getDescription(), GrassUtils.GRASS_REGION_YMAX, "GRASS Region max y", 1000))
62-
# SextanteConfig.addSetting(Setting(self.getDescription(), GrassUtils.GRASS_REGION_CELLSIZE, "GRASS Region cellsize", 100))
63-
#=======================================================================
6454
SextanteConfig.addSetting(Setting(self.getDescription(), GrassUtils.GRASS_HELP_FOLDER, "GRASS help folder", GrassUtils.grassHelpPath()))
6555

6656
def unload(self):
6757
AlgorithmProvider.unload(self)
6858
if SextanteUtils.isWindows() or SextanteUtils.isMac():
6959
SextanteConfig.removeSetting(GrassUtils.GRASS_FOLDER)
7060
SextanteConfig.removeSetting(GrassUtils.GRASS_WIN_SHELL)
71-
#SextanteConfig.removeSetting(GrassUtils.GRASS_AUTO_REGION)
7261
SextanteConfig.removeSetting(GrassUtils.GRASS_LATLON)
73-
#=======================================================================
74-
# SextanteConfig.removeSetting(GrassUtils.GRASS_REGION_XMIN)
75-
# SextanteConfig.removeSetting(GrassUtils.GRASS_REGION_YMIN)
76-
# SextanteConfig.removeSetting(GrassUtils.GRASS_REGION_XMAX)
77-
# SextanteConfig.removeSetting(GrassUtils.GRASS_REGION_YMAX)
78-
# SextanteConfig.removeSetting(GrassUtils.GRASS_REGION_CELLSIZE)
79-
#=======================================================================
8062
SextanteConfig.removeSetting(GrassUtils.GRASS_HELP_FOLDER)
8163
SextanteConfig.removeSetting(GrassUtils.GRASS_LOG_COMMANDS)
8264
SextanteConfig.removeSetting(GrassUtils.GRASS_LOG_CONSOLE)

0 commit comments

Comments
 (0)