2013-10-22 18:42:52 +01:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
|
|
"""
|
|
|
|
***************************************************************************
|
|
|
|
SpatialJoin.py
|
|
|
|
---------------------
|
|
|
|
Date : October 2013
|
|
|
|
Copyright : (C) 2013 by Joshua Arnott
|
|
|
|
Email : josh at snorfalorpagus dot net
|
|
|
|
***************************************************************************
|
|
|
|
* *
|
|
|
|
* 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. *
|
|
|
|
* *
|
|
|
|
***************************************************************************
|
|
|
|
"""
|
2016-09-21 18:24:26 +02:00
|
|
|
from builtins import str
|
|
|
|
from builtins import zip
|
|
|
|
from builtins import range
|
2014-09-19 14:46:19 +03:00
|
|
|
|
2013-10-22 18:42:52 +01:00
|
|
|
__author__ = 'Joshua Arnott'
|
|
|
|
__date__ = 'October 2013'
|
|
|
|
__copyright__ = '(C) 2013, Joshua Arnott'
|
2016-01-25 15:42:11 +02:00
|
|
|
|
2013-10-22 18:42:52 +01:00
|
|
|
# This will get replaced with a git SHA1 when you do a git archive
|
2016-01-25 15:42:11 +02:00
|
|
|
|
2013-10-22 18:42:52 +01:00
|
|
|
__revision__ = '$Format:%H$'
|
|
|
|
|
2016-01-25 15:42:11 +02:00
|
|
|
import os
|
|
|
|
|
2016-04-22 10:38:48 +02:00
|
|
|
from qgis.PyQt.QtGui import QIcon
|
|
|
|
from qgis.PyQt.QtCore import QVariant
|
2016-01-25 15:42:11 +02:00
|
|
|
|
2017-06-23 14:34:38 +10:00
|
|
|
from qgis.core import QgsFields, QgsField, QgsFeatureSink, QgsFeature, QgsGeometry, NULL, QgsWkbTypes, QgsProcessingUtils
|
2014-09-19 14:46:19 +03:00
|
|
|
|
2017-06-06 13:41:42 +10:00
|
|
|
from processing.algs.qgis.QgisAlgorithm import QgisAlgorithm
|
2014-07-14 14:19:09 +02:00
|
|
|
from processing.core.parameters import ParameterVector
|
2015-09-29 14:24:17 +02:00
|
|
|
from processing.core.parameters import ParameterNumber
|
2014-07-14 14:19:09 +02:00
|
|
|
from processing.core.parameters import ParameterSelection
|
|
|
|
from processing.core.parameters import ParameterString
|
|
|
|
from processing.core.outputs import OutputVector
|
2017-05-02 14:47:58 +10:00
|
|
|
from processing.tools import vector
|
2013-10-22 18:42:52 +01:00
|
|
|
|
2016-01-25 15:42:11 +02:00
|
|
|
pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0]
|
|
|
|
|
2013-10-22 18:42:52 +01:00
|
|
|
|
2017-05-19 11:27:16 +10:00
|
|
|
class SpatialJoin(QgisAlgorithm):
|
2014-09-19 14:46:19 +03:00
|
|
|
TARGET = "TARGET"
|
|
|
|
JOIN = "JOIN"
|
2015-01-09 17:23:49 +01:00
|
|
|
PREDICATE = "PREDICATE"
|
2015-09-29 14:24:17 +02:00
|
|
|
PRECISION = 'PRECISION'
|
2013-10-22 18:42:52 +01:00
|
|
|
SUMMARY = "SUMMARY"
|
|
|
|
STATS = "STATS"
|
|
|
|
KEEP = "KEEP"
|
|
|
|
OUTPUT = "OUTPUT"
|
2014-04-06 12:27:51 +02:00
|
|
|
|
2017-03-29 10:42:42 +10:00
|
|
|
def icon(self):
|
2016-01-25 15:42:11 +02:00
|
|
|
return QIcon(os.path.join(pluginPath, 'images', 'ftools', 'join_location.png'))
|
|
|
|
|
2017-03-29 12:04:09 +10:00
|
|
|
def group(self):
|
|
|
|
return self.tr('Vector general tools')
|
|
|
|
|
2017-05-15 13:40:38 +10:00
|
|
|
def __init__(self):
|
|
|
|
super().__init__()
|
2016-11-05 20:22:02 +01:00
|
|
|
self.predicates = (
|
|
|
|
('intersects', self.tr('intersects')),
|
|
|
|
('contains', self.tr('contains')),
|
|
|
|
('equals', self.tr('equals')),
|
|
|
|
('touches', self.tr('touches')),
|
|
|
|
('overlaps', self.tr('overlaps')),
|
|
|
|
('within', self.tr('within')),
|
|
|
|
('crosses', self.tr('crosses')))
|
|
|
|
|
2015-08-31 16:59:11 +02:00
|
|
|
self.summarys = [
|
|
|
|
self.tr('Take attributes of the first located feature'),
|
|
|
|
self.tr('Take summary of intersecting features')
|
|
|
|
]
|
|
|
|
|
|
|
|
self.keeps = [
|
|
|
|
self.tr('Only keep matching records'),
|
|
|
|
self.tr('Keep all records (including non-matching target records)')
|
|
|
|
]
|
|
|
|
|
2014-09-19 14:46:19 +03:00
|
|
|
self.addParameter(ParameterVector(self.TARGET,
|
2016-08-23 19:33:42 +03:00
|
|
|
self.tr('Target vector layer')))
|
2014-09-19 14:46:19 +03:00
|
|
|
self.addParameter(ParameterVector(self.JOIN,
|
2016-08-23 19:33:42 +03:00
|
|
|
self.tr('Join vector layer')))
|
2016-11-05 20:22:02 +01:00
|
|
|
self.addParameter(ParameterSelection(self.PREDICATE,
|
|
|
|
self.tr('Geometric predicate'),
|
|
|
|
self.predicates,
|
|
|
|
multiple=True))
|
2015-09-29 14:24:17 +02:00
|
|
|
self.addParameter(ParameterNumber(self.PRECISION,
|
|
|
|
self.tr('Precision'),
|
|
|
|
0.0, None, 0.0))
|
2014-09-19 14:46:19 +03:00
|
|
|
self.addParameter(ParameterSelection(self.SUMMARY,
|
2015-08-31 16:59:11 +02:00
|
|
|
self.tr('Attribute summary'), self.summarys))
|
2014-09-19 14:46:19 +03:00
|
|
|
self.addParameter(ParameterString(self.STATS,
|
2015-08-22 14:29:41 +02:00
|
|
|
self.tr('Statistics for summary (comma separated)'),
|
|
|
|
'sum,mean,min,max,median', optional=True))
|
2014-09-19 14:46:19 +03:00
|
|
|
self.addParameter(ParameterSelection(self.KEEP,
|
2015-08-31 16:59:11 +02:00
|
|
|
self.tr('Joined table'), self.keeps))
|
2015-05-22 15:56:45 +02:00
|
|
|
self.addOutput(OutputVector(self.OUTPUT, self.tr('Joined layer')))
|
2013-10-22 18:42:52 +01:00
|
|
|
|
2017-05-15 13:40:38 +10:00
|
|
|
def name(self):
|
|
|
|
return 'joinattributesbylocation'
|
|
|
|
|
|
|
|
def displayName(self):
|
|
|
|
return self.tr('Join attributes by location')
|
|
|
|
|
2017-05-15 16:19:46 +10:00
|
|
|
def processAlgorithm(self, parameters, context, feedback):
|
2017-05-02 13:40:49 +10:00
|
|
|
target = QgsProcessingUtils.mapLayerFromString(self.getParameterValue(self.TARGET), context)
|
|
|
|
join = QgsProcessingUtils.mapLayerFromString(self.getParameterValue(self.JOIN), context)
|
2015-01-09 17:23:49 +01:00
|
|
|
predicates = self.getParameterValue(self.PREDICATE)
|
2015-09-29 14:24:17 +02:00
|
|
|
precision = self.getParameterValue(self.PRECISION)
|
2013-10-22 18:42:52 +01:00
|
|
|
|
|
|
|
summary = self.getParameterValue(self.SUMMARY) == 1
|
2014-12-11 12:43:35 +02:00
|
|
|
keep = self.getParameterValue(self.KEEP) == 1
|
2014-09-19 14:46:19 +03:00
|
|
|
|
|
|
|
sumList = self.getParameterValue(self.STATS).lower().split(',')
|
2014-04-06 12:27:51 +02:00
|
|
|
|
2016-08-04 07:33:49 +10:00
|
|
|
targetFields = target.fields()
|
|
|
|
joinFields = join.fields()
|
2014-04-06 12:27:51 +02:00
|
|
|
|
|
|
|
fieldList = QgsFields()
|
2014-09-19 14:46:19 +03:00
|
|
|
|
2013-10-22 18:42:52 +01:00
|
|
|
if not summary:
|
2014-09-19 14:46:19 +03:00
|
|
|
joinFields = vector.testForUniqueness(targetFields, joinFields)
|
2016-09-21 18:24:26 +02:00
|
|
|
seq = list(range(len(targetFields) + len(joinFields)))
|
2014-09-19 14:46:19 +03:00
|
|
|
targetFields.extend(joinFields)
|
2016-09-21 18:24:26 +02:00
|
|
|
targetFields = dict(list(zip(seq, targetFields)))
|
2013-10-22 18:42:52 +01:00
|
|
|
else:
|
|
|
|
numFields = {}
|
2016-09-21 18:24:26 +02:00
|
|
|
for j in range(len(joinFields)):
|
2016-06-24 15:09:40 +03:00
|
|
|
if joinFields[j].type() in [QVariant.Int, QVariant.Double, QVariant.LongLong, QVariant.UInt, QVariant.ULongLong]:
|
2013-10-22 18:42:52 +01:00
|
|
|
numFields[j] = []
|
|
|
|
for i in sumList:
|
2016-09-21 18:24:26 +02:00
|
|
|
field = QgsField(i + str(joinFields[j].name()), QVariant.Double, '', 24, 16)
|
2013-10-22 18:42:52 +01:00
|
|
|
fieldList.append(field)
|
2014-09-19 14:46:19 +03:00
|
|
|
field = QgsField('count', QVariant.Double, '', 24, 16)
|
2013-10-22 18:42:52 +01:00
|
|
|
fieldList.append(field)
|
2014-09-19 14:46:19 +03:00
|
|
|
joinFields = vector.testForUniqueness(targetFields, fieldList)
|
|
|
|
targetFields.extend(fieldList)
|
2016-09-21 18:24:26 +02:00
|
|
|
seq = list(range(len(targetFields)))
|
|
|
|
targetFields = dict(list(zip(seq, targetFields)))
|
2013-10-22 18:42:52 +01:00
|
|
|
|
|
|
|
fields = QgsFields()
|
2016-09-21 18:24:26 +02:00
|
|
|
for f in list(targetFields.values()):
|
2013-10-22 18:42:52 +01:00
|
|
|
fields.append(f)
|
2013-10-22 23:49:08 +01:00
|
|
|
|
2017-04-26 14:33:53 +10:00
|
|
|
writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fields, target.wkbType(), target.crs(), context)
|
2014-04-06 12:27:51 +02:00
|
|
|
|
2013-10-22 18:42:52 +01:00
|
|
|
outFeat = QgsFeature()
|
|
|
|
inFeatB = QgsFeature()
|
|
|
|
inGeom = QgsGeometry()
|
2014-04-06 12:27:51 +02:00
|
|
|
|
2017-05-02 13:39:36 +10:00
|
|
|
index = QgsProcessingUtils.createSpatialIndex(join, context)
|
2014-09-19 14:46:19 +03:00
|
|
|
|
2014-12-11 12:43:35 +02:00
|
|
|
mapP2 = dict()
|
2017-04-25 17:59:35 +10:00
|
|
|
features = QgsProcessingUtils.getFeatures(join, context)
|
2014-09-19 14:46:19 +03:00
|
|
|
for f in features:
|
|
|
|
mapP2[f.id()] = QgsFeature(f)
|
|
|
|
|
2017-04-25 17:59:35 +10:00
|
|
|
features = QgsProcessingUtils.getFeatures(target, context)
|
2017-06-23 13:49:32 +10:00
|
|
|
total = 100.0 / target.featureCount() if target.featureCount() else 0
|
2014-12-11 12:43:35 +02:00
|
|
|
for c, f in enumerate(features):
|
2014-09-19 14:46:19 +03:00
|
|
|
atMap1 = f.attributes()
|
2015-09-29 14:24:17 +02:00
|
|
|
outFeat.setGeometry(f.geometry())
|
|
|
|
inGeom = vector.snapToPrecision(f.geometry(), precision)
|
2013-10-22 18:42:52 +01:00
|
|
|
none = True
|
|
|
|
joinList = []
|
2016-08-04 09:10:08 +02:00
|
|
|
if inGeom.type() == QgsWkbTypes.PointGeometry:
|
2015-09-29 14:24:17 +02:00
|
|
|
bbox = inGeom.buffer(10, 2).boundingBox()
|
2013-10-22 18:42:52 +01:00
|
|
|
else:
|
2015-09-29 14:24:17 +02:00
|
|
|
bbox = inGeom.boundingBox()
|
2017-05-02 13:27:01 +10:00
|
|
|
bbox.grow(0.51 * precision)
|
|
|
|
joinList = index.intersects(bbox)
|
2015-09-29 14:24:17 +02:00
|
|
|
if len(joinList) > 0:
|
2013-10-22 18:42:52 +01:00
|
|
|
count = 0
|
|
|
|
for i in joinList:
|
2014-12-11 12:43:35 +02:00
|
|
|
inFeatB = mapP2[i]
|
2015-09-29 14:24:17 +02:00
|
|
|
inGeomB = vector.snapToPrecision(inFeatB.geometry(), precision)
|
2015-01-09 17:23:49 +01:00
|
|
|
|
|
|
|
res = False
|
|
|
|
for predicate in predicates:
|
2016-12-14 14:13:31 +01:00
|
|
|
res = getattr(inGeom, predicate)(inGeomB)
|
2015-01-09 17:23:49 +01:00
|
|
|
if res:
|
|
|
|
break
|
|
|
|
|
|
|
|
if res:
|
2014-12-11 12:43:35 +02:00
|
|
|
count = count + 1
|
2014-09-19 14:46:19 +03:00
|
|
|
none = False
|
2013-10-22 18:42:52 +01:00
|
|
|
atMap2 = inFeatB.attributes()
|
|
|
|
if not summary:
|
|
|
|
atMap = atMap1
|
|
|
|
atMap2 = atMap2
|
|
|
|
atMap.extend(atMap2)
|
2016-09-21 18:24:26 +02:00
|
|
|
atMap = dict(list(zip(seq, atMap)))
|
2013-10-22 18:42:52 +01:00
|
|
|
break
|
|
|
|
else:
|
2016-09-21 18:24:26 +02:00
|
|
|
for j in list(numFields.keys()):
|
2013-10-22 18:42:52 +01:00
|
|
|
numFields[j].append(atMap2[j])
|
2014-12-11 12:43:35 +02:00
|
|
|
|
2013-10-22 18:42:52 +01:00
|
|
|
if summary and not none:
|
|
|
|
atMap = atMap1
|
2016-09-21 18:24:26 +02:00
|
|
|
for j in list(numFields.keys()):
|
2013-10-22 18:42:52 +01:00
|
|
|
for k in sumList:
|
2014-09-19 14:46:19 +03:00
|
|
|
if k == 'sum':
|
2014-12-11 12:43:35 +02:00
|
|
|
atMap.append(sum(self._filterNull(numFields[j])))
|
2014-09-19 14:46:19 +03:00
|
|
|
elif k == 'mean':
|
|
|
|
try:
|
2015-01-09 17:23:49 +01:00
|
|
|
nn_count = sum(1 for _ in self._filterNull(numFields[j]))
|
2014-12-11 12:43:35 +02:00
|
|
|
atMap.append(sum(self._filterNull(numFields[j])) / nn_count)
|
2014-09-19 14:46:19 +03:00
|
|
|
except ZeroDivisionError:
|
|
|
|
atMap.append(NULL)
|
|
|
|
elif k == 'min':
|
|
|
|
try:
|
2014-12-11 12:43:35 +02:00
|
|
|
atMap.append(min(self._filterNull(numFields[j])))
|
2014-09-19 14:46:19 +03:00
|
|
|
except ValueError:
|
|
|
|
atMap.append(NULL)
|
|
|
|
elif k == 'median':
|
2014-12-11 12:43:35 +02:00
|
|
|
atMap.append(self._median(numFields[j]))
|
2014-09-19 14:46:19 +03:00
|
|
|
else:
|
|
|
|
try:
|
2014-12-11 12:43:35 +02:00
|
|
|
atMap.append(max(self._filterNull(numFields[j])))
|
2014-09-19 14:46:19 +03:00
|
|
|
except ValueError:
|
|
|
|
atMap.append(NULL)
|
|
|
|
|
2013-10-22 18:42:52 +01:00
|
|
|
numFields[j] = []
|
|
|
|
atMap.append(count)
|
2016-09-21 18:24:26 +02:00
|
|
|
atMap = dict(list(zip(seq, atMap)))
|
2013-10-22 18:42:52 +01:00
|
|
|
if none:
|
|
|
|
outFeat.setAttributes(atMap1)
|
|
|
|
else:
|
2016-09-21 18:24:26 +02:00
|
|
|
outFeat.setAttributes(list(atMap.values()))
|
2014-09-19 14:46:19 +03:00
|
|
|
|
2014-12-11 12:43:35 +02:00
|
|
|
if keep:
|
2017-06-23 14:34:38 +10:00
|
|
|
writer.addFeature(outFeat, QgsFeatureSink.FastInsert)
|
2014-12-11 12:43:35 +02:00
|
|
|
else:
|
2013-10-22 18:42:52 +01:00
|
|
|
if not none:
|
2017-06-23 14:34:38 +10:00
|
|
|
writer.addFeature(outFeat, QgsFeatureSink.FastInsert)
|
2013-10-26 18:19:52 +01:00
|
|
|
|
2017-01-06 20:04:00 +10:00
|
|
|
feedback.setProgress(int(c * total))
|
2014-09-19 14:46:19 +03:00
|
|
|
del writer
|
2013-10-26 18:19:52 +01:00
|
|
|
|
2014-12-11 12:43:35 +02:00
|
|
|
def _filterNull(self, values):
|
2014-09-19 14:46:19 +03:00
|
|
|
"""Takes an iterator of values and returns a new iterator
|
|
|
|
returning the same values but skipping any NULL values"""
|
2014-12-11 12:43:35 +02:00
|
|
|
return (v for v in values if v != NULL)
|
|
|
|
|
|
|
|
def _median(self, data):
|
|
|
|
count = len(data)
|
|
|
|
if count == 1:
|
|
|
|
return data[0]
|
|
|
|
data.sort()
|
|
|
|
|
|
|
|
median = 0
|
|
|
|
if count > 1:
|
2015-01-09 17:23:49 +01:00
|
|
|
if (count % 2) == 0:
|
|
|
|
median = 0.5 * ((data[count / 2 - 1]) + (data[count / 2]))
|
2013-10-26 18:19:52 +01:00
|
|
|
else:
|
2014-12-11 12:43:35 +02:00
|
|
|
median = data[(count + 1) / 2 - 1]
|
|
|
|
|
|
|
|
return median
|