forked from NaturalGIS/naturalgis_postgis_geoprocessing
/
selectbypolygon.py
192 lines (167 loc) · 11.4 KB
/
selectbypolygon.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# -*- coding: utf-8 -*-
"""
***************************************************************************
selectbypolygon.py
---------------------
Date : January 2015
Copyright : (C) 2015 by Giovanni Manghi
Email : giovanni dot manghi at naturalgis dot pt
***************************************************************************
* *
* 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__ = 'Giovanni Manghi'
__date__ = 'January 2015'
__copyright__ = '(C) 2015, Giovanni Manghi'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import os
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from processing.core.parameters import ParameterVector
from processing.core.parameters import ParameterString
from processing.core.parameters import ParameterNumber
from processing.core.parameters import ParameterBoolean
from processing.core.parameters import ParameterTableField
from processing.core.outputs import OutputVector
from processing.core.outputs import OutputHTML
from processing.tools.system import *
from processing.tools import dataobjects
from processing.core.GeoAlgorithm import GeoAlgorithm
from processing.algs.gdal.GdalUtils import GdalUtils
from processing.tools.vector import ogrConnectionString, ogrLayerName
class selectbypolygon(GeoAlgorithm):
INPUT_LAYER_A = 'INPUT_LAYER_A'
INPUT_LAYER_B = 'INPUT_LAYER_B'
FIELDS_B = 'FIELDS_B'
TABLE = 'TABLE'
SCHEMA = 'SCHEMA'
SINGLE = 'SINGLE'
KEEP = 'KEEP'
KEEPC = 'KEEPC'
OPTIONS = 'OPTIONS'
OUTPUT = 'OUTPUT'
def getIcon(self):
return QIcon(os.path.dirname(__file__) + '/icons/postgis.png')
def defineCharacteristics(self):
self.name = 'Select by polygons (select by location)'
self.group = 'Vector geoprocessing'
self.addParameter(ParameterVector(self.INPUT_LAYER_A, 'Polygon layer used for the selection',
[ParameterVector.VECTOR_TYPE_POLYGON], False))
self.addParameter(ParameterVector(self.INPUT_LAYER_B, 'Select features from',
[ParameterVector.VECTOR_TYPE_ANY], False))
self.addParameter(ParameterString(self.FIELDS_B, 'Attributes to keep (comma separated list). Aliasing permitted.',
'', optional=False))
self.addParameter(ParameterBoolean(self.SINGLE,
'Force output as singlepart', True))
self.addParameter(ParameterBoolean(self.KEEPC,
'Select only lines and polygons inside of selection layer (not used when selecting points)', False))
self.addParameter(ParameterBoolean(self.KEEP,
'Select also features just touching the selection layer', False))
self.addParameter(ParameterString(self.SCHEMA, 'Output schema',
'public', optional=False))
self.addParameter(ParameterString(self.TABLE, 'Output table name',
'select', optional=False))
self.addParameter(ParameterString(self.OPTIONS, 'Additional creation options (see ogr2ogr manual)',
'', optional=True))
self.addOutput(OutputHTML(self.OUTPUT, 'Output log'))
def processAlgorithm(self, progress):
inLayerA = self.getParameterValue(self.INPUT_LAYER_A)
ogrLayerA = ogrConnectionString(inLayerA)[1:-1]
layernameA = ogrLayerName(inLayerA)
inLayerB = self.getParameterValue(self.INPUT_LAYER_B)
ogrLayerB = ogrConnectionString(inLayerB)[1:-1]
layernameB = ogrLayerName(inLayerB)
fieldsB = unicode(self.getParameterValue(self.FIELDS_B))
dsUriA = QgsDataSourceURI(self.getParameterValue(self.INPUT_LAYER_A))
geomColumnA = dsUriA.geometryColumn()
dsUriB = QgsDataSourceURI(self.getParameterValue(self.INPUT_LAYER_B))
geomColumnB = dsUriB.geometryColumn()
layerB = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_LAYER_B))
geomTypeB = layerB.geometryType()
wkbTypeB = layerB.wkbType()
sridB = layerB.crs().postgisSrid()
schema = unicode(self.getParameterValue(self.SCHEMA))
table = unicode(self.getParameterValue(self.TABLE))
single = self.getParameterValue(self.SINGLE)
keep = self.getParameterValue(self.KEEP)
keepc = self.getParameterValue(self.KEEPC)
if len(fieldsB) > 0:
fieldstringB = fieldsB.replace(",", ", g2.")
fieldstringB = ", g2." + fieldstringB
else:
fieldstringB = ""
if geomTypeB == 0:
type = "POINT"
elif geomTypeB == 1:
type = "LINESTRING"
else:
type = "POLYGON"
if single:
multistring = "-nlt " + type
caststring = type
st_function = "ST_Dump"
castgeom = ".geom"
else:
multistring = "-nlt MULTI" + type
caststring = "MULTI" + type
st_function = "ST_Multi"
castgeom = ""
if geomTypeB == 0:
if keep:
sqlstring = "-sql \"SELECT (" + st_function + "(g2." + geomColumnB + "))" + castgeom + "::geometry(" + caststring + "," + str(sridB) + ") AS geom" + fieldstringB + " FROM " + layernameA + " AS g1, " + layernameB + " AS g2 WHERE ST_Intersects(g1." + geomColumnA + ",g2." + geomColumnB + ") is true\" -nln " + schema + "." + table + " -lco FID=gid " + multistring + " -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES"
else:
sqlstring = "-sql \"WITH temp_table AS (SELECT ST_Union(" + geomColumnA + ") AS geom FROM " + layernameA + ") SELECT (" + st_function + "(g2." + geomColumnB + "))" + castgeom + "::geometry(" + caststring + "," + str(sridB) + ") AS geom" + fieldstringB + " FROM temp_table AS g1, " + layernameB + " AS g2 WHERE ST_Contains(g1." + geomColumnA + ",g2." + geomColumnB + ") is true\" -nln " + schema + "." + table + " -lco FID=gid " + multistring + " -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES -a_srs EPSG:" + str(sridB) + ""
elif geomTypeB == 1:
if keepc:
if keep:
sqlstring = "-sql \"SELECT (" + st_function + "(g2." + geomColumnB + "))" + castgeom + "::geometry(" + caststring + "," + str(sridB) + ") AS geom" + fieldstringB + " FROM " + layernameA + " AS g1, " + layernameB + " AS g2 WHERE ST_Contains(g1." + geomColumnA + ",g2." + geomColumnB + ") is true\" -nln " + schema + "." + table + " -lco FID=gid " + multistring + " -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES"
else:
sqlstring = "-sql \"SELECT (" + st_function + "(g2." + geomColumnB + "))" + castgeom + "::geometry(" + caststring + "," + str(sridB) + ") AS geom" + fieldstringB + " FROM " + layernameA + " AS g1, " + layernameB + " AS g2 WHERE ST_ContainsProperly(g1." + geomColumnA + ",g2." + geomColumnB + ") is true\" -nln " + schema + "." + table + " -lco FID=gid " + multistring + " -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES"
else:
if keep:
sqlstring = "-sql \"SELECT (" + st_function + "(g2." + geomColumnB + "))" + castgeom + "::geometry(" + caststring + "," + str(sridB) + ") AS geom" + fieldstringB + " FROM " + layernameA + " AS g1, " + layernameB + " AS g2 WHERE ST_Intersects(g1." + geomColumnA + ",g2." + geomColumnB + ") is true\" -nln " + schema + "." + table + " -lco FID=gid " + multistring + " -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES"
else:
sqlstring = "-sql \"SELECT (" + st_function + "(g2." + geomColumnB + "))" + castgeom + "::geometry(" + caststring + "," + str(sridB) + ") AS geom" + fieldstringB + " FROM " + layernameA + " AS g1, " + layernameB + " AS g2 WHERE ST_Intersects(g1." + geomColumnA + ",g2." + geomColumnB + ") is true AND ST_Touches(g1." + geomColumnA + ",g2." + geomColumnB + ") is false\" -nln " + schema + "." + table + " -lco FID=gid " + multistring + " -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES"
else:
if keepc:
if keep:
sqlstring = "-sql \"SELECT (" + st_function + "(g2." + geomColumnB + "))" + castgeom + "::geometry(" + caststring + "," + str(sridB) + ") AS geom" + fieldstringB + " FROM " + layernameA + " AS g1, " + layernameB + " AS g2 WHERE ST_Contains(g1." + geomColumnA + ",g2." + geomColumnB + ") is true\" -nln " + schema + "." + table + " -lco FID=gid " + multistring + " -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES"
else:
sqlstring = "-sql \"SELECT (" + st_function + "(g2." + geomColumnB + "))" + castgeom + "::geometry(" + caststring + "," + str(sridB) + ") AS geom" + fieldstringB + " FROM " + layernameA + " AS g1, " + layernameB + " AS g2 WHERE ST_ContainsProperly(g1." + geomColumnA + ",g2." + geomColumnB + ") is true\" -nln " + schema + "." + table + " -lco FID=gid " + multistring + " -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES"
else:
if keep:
sqlstring = "-sql \"SELECT (" + st_function + "(g2." + geomColumnB + "))" + castgeom + "::geometry(" + caststring + "," + str(sridB) + ") AS geom" + fieldstringB + " FROM " + layernameA + " AS g1, " + layernameB + " AS g2 WHERE ST_Intersects(g1." + geomColumnA + ",g2." + geomColumnB + ") is true OR ST_Contains(g2." + geomColumnB + ",g1." + geomColumnA + ") is true\" -nln " + schema + "." + table + " -lco FID=gid " + multistring + " -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES"
else:
sqlstring = "-sql \"SELECT (" + st_function + "(g2." + geomColumnB + "))" + castgeom + "::geometry(" + caststring + "," + str(sridB) + ") AS geom" + fieldstringB + " FROM " + layernameA + " AS g1, " + layernameB + " AS g2 WHERE ST_Contains(g1." + geomColumnA + ",g2." + geomColumnB + ") is true OR ST_Overlaps(g1." + geomColumnA + ",g2." + geomColumnB + ") is true OR ST_Contains(g2." + geomColumnB+ ",g1." + geomColumnA + ") is true\" -nln " + schema + "." + table + " -lco FID=gid " + multistring + " -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES"
options = unicode(self.getParameterValue(self.OPTIONS))
arguments = []
arguments.append('-f')
arguments.append('PostgreSQL')
arguments.append(ogrLayerA)
arguments.append(ogrLayerA)
arguments.append(sqlstring)
arguments.append('-overwrite')
if len(options) > 0:
arguments.append(options)
print geomTypeB
commands = []
if isWindows():
commands = ['cmd.exe', '/C ', 'ogr2ogr.exe',
GdalUtils.escapeAndJoin(arguments)]
else:
commands = ['ogr2ogr', GdalUtils.escapeAndJoin(arguments)]
GdalUtils.runGdal(commands, progress)
output = self.getOutputValue(self.OUTPUT)
f = open(output, 'w')
f.write('<pre>')
for s in GdalUtils.getConsoleOutput()[1:]:
f.write(unicode(s))
f.write('</pre>')
f.close()