Skip to content

Commit

Permalink
[processing] [FEATURE] SplitWithLines
Browse files Browse the repository at this point in the history
Rename algorithm SplitLinesWithLines to SplitWithLines
Accept polygon as input, too
Use only selected lines to split with (if processing is set to use selection only)
Issue log message if trying to split multi geometries
Update help
  • Loading branch information
Bernhard Ströbl authored and nyalldawson committed Nov 23, 2016
1 parent 986acab commit 0e2ef06
Show file tree
Hide file tree
Showing 6 changed files with 302 additions and 7 deletions.
5 changes: 2 additions & 3 deletions python/plugins/processing/algs/help/qgis.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -495,9 +495,8 @@ qgis:snapgeometriestolayer: >
qgis:snappointstogrid: >
This algorithm modifies the position of points in a vector layer, so they fall in the coordinates of a grid.


qgis:splitlineswithlines: >
This algorithm splits the lines in a line layer using the lines in another line layer to define the breaking points. Intersection between geometries in both layers are considered as split points.
qgis:splitwithlines: >
This algorithm splits the lines or polygons in one layer using the lines in another layer to define the breaking points. Intersection between geometries in both layers are considered as split points.

qgis:splitvectorlayer: >
This algorithm takes a vector layer and an attribute and generates a set of vector layers in an output folder. Each of the layers created in that folder contains all features from the input layer with the same value for the specified attribute.
Expand Down
3 changes: 2 additions & 1 deletion python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@
from .SelectByExpression import SelectByExpression
from .SelectByAttributeSum import SelectByAttributeSum
from .HypsometricCurves import HypsometricCurves
from .SplitWithLines import SplitWithLines
from .SplitLinesWithLines import SplitLinesWithLines
from .FieldsMapper import FieldsMapper
from .Datasources2Vrt import Datasources2Vrt
Expand Down Expand Up @@ -226,7 +227,7 @@ def __init__(self):
PostGISExecuteSQL(), ImportIntoPostGIS(),
SetVectorStyle(), SetRasterStyle(),
SelectByExpression(), HypsometricCurves(),
SplitLinesWithLines(), CreateConstantRaster(),
SplitWithLines(), SplitLinesWithLines(), CreateConstantRaster(),
FieldsMapper(), SelectByAttributeSum(), Datasources2Vrt(),
CheckValidity(), OrientedMinimumBoundingBox(), Smooth(),
ReverseLineDirection(), SpatialIndex(), DefineProjection(),
Expand Down
11 changes: 8 additions & 3 deletions python/plugins/processing/algs/qgis/SplitLinesWithLines.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@

"""
***************************************************************************
SplitLines.py
SplitLinesWithLines.py
DEPRECATED, replaced by SplitWithLines.py
---------------------
Date : November 2014
Revised : February 2016
Revised : November 2016
Copyright : (C) 2014 by Bernhard Ströbl
Email : bernhard dot stroebl at jena dot de
***************************************************************************
Expand All @@ -17,7 +18,6 @@
* *
***************************************************************************
"""
from builtins import next

__author__ = 'Bernhard Ströbl'
__date__ = 'November 2014'
Expand All @@ -43,6 +43,11 @@ class SplitLinesWithLines(GeoAlgorithm):

OUTPUT = 'OUTPUT'

def __init__(self):
GeoAlgorithm.__init__(self)
# this algorithm is deprecated - use SplitWithLines instead
self.showInToolbox = False

def defineCharacteristics(self):
self.name, self.i18n_name = self.trAlgorithm('Split lines with lines')
self.group, self.i18n_group = self.trAlgorithm('Vector overlay tools')
Expand Down
187 changes: 187 additions & 0 deletions python/plugins/processing/algs/qgis/SplitWithLines.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
# -*- coding: utf-8 -*-

"""
***************************************************************************
SplitWithLines.py
---------------------
Date : November 2014
Revised : November 2016
Copyright : (C) 2014 by Bernhard Ströbl
Email : bernhard dot stroebl at jena dot de
***************************************************************************
* *
* 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__ = 'Bernhard Ströbl'
__date__ = 'November 2014'
__copyright__ = '(C) 2014, Bernhard Ströbl'

# This will get replaced with a git SHA1 when you do a git archive

__revision__ = '$Format:%H$'

from qgis.core import QgsFeatureRequest, QgsFeature, QgsGeometry, QgsSpatialIndex, QgsWkbTypes, QgsMessageLog
from processing.core.GeoAlgorithm import GeoAlgorithm
from processing.core.parameters import ParameterVector
from processing.core.outputs import OutputVector
from processing.core.ProcessingLog import ProcessingLog
from processing.tools import dataobjects
from processing.tools import vector


class SplitWithLines(GeoAlgorithm):

INPUT_A = 'INPUT_A'
INPUT_B = 'INPUT_B'

OUTPUT = 'OUTPUT'

def defineCharacteristics(self):
self.name, self.i18n_name = self.trAlgorithm('Split with lines')
self.group, self.i18n_group = self.trAlgorithm('Vector overlay tools')
self.addParameter(ParameterVector(self.INPUT_A,
self.tr('Input layer, single geometries only'), [dataobjects.TYPE_VECTOR_POLYGON,
dataobjects.TYPE_VECTOR_LINE]))
self.addParameter(ParameterVector(self.INPUT_B,
self.tr('Split layer'), [dataobjects.TYPE_VECTOR_LINE]))

self.addOutput(OutputVector(self.OUTPUT, self.tr('Split')))

def processAlgorithm(self, progress):
layerA = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_A))
splitLayer = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_B))

sameLayer = self.getParameterValue(self.INPUT_A) == self.getParameterValue(self.INPUT_B)
fieldList = layerA.fields()

writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fieldList,
layerA.wkbType(), layerA.crs())

spatialIndex = QgsSpatialIndex()
splitGeoms = {}
request = QgsFeatureRequest()
request.setSubsetOfAttributes([])

for aSplitFeature in vector.features(splitLayer, request):
splitGeoms[aSplitFeature.id()] = aSplitFeature.geometry()
spatialIndex.insertFeature(aSplitFeature)
# honor the case that user has selection on split layer and has setting "use selection"

outFeat = QgsFeature()
features = vector.features(layerA)

if len(features) == 0:
total = 100
else:
total = 100.0 / float(len(features))

multiGeoms = 0 # how many multi geometries were encountered

for current, inFeatA in enumerate(features):
inGeom = inFeatA.geometry()

if inGeom.isMultipart():
multiGeoms += 1
# MultiGeometries are not allowed because the result of a splitted part cannot be clearly defined:
# 1) add both new parts as new features
# 2) store one part as a new feature and the other one as part of the multi geometry
# 2a) which part should be which, seems arbitrary
else:
attrsA = inFeatA.attributes()
outFeat.setAttributes(attrsA)
inGeoms = [inGeom]
lines = spatialIndex.intersects(inGeom.boundingBox())

if len(lines) > 0: # has intersection of bounding boxes
splittingLines = []

for i in lines:
try:
splitGeom = splitGeoms[i]
except:
continue

# check if trying to self-intersect
if sameLayer:
if inFeatA.id() == i:
continue

engine = QgsGeometry.createGeometryEngine(inGeom.geometry())
engine.prepareGeometry()

if engine.intersects(splitGeom.geometry()):
splittingLines.append(splitGeom)

if len(splittingLines) > 0:
for splitGeom in splittingLines:
splitterPList = None
outGeoms = []

while len(inGeoms) > 0:
inGeom = inGeoms.pop()
engine = QgsGeometry.createGeometryEngine(inGeom.geometry())
engine.prepareGeometry()
inPoints = vector.extractPoints(inGeom)

if engine.intersects(splitGeom.geometry()):
if splitterPList == None:
splitterPList = vector.extractPoints(splitGeom)

try:
result, newGeometries, topoTestPoints = inGeom.splitGeometry(splitterPList, False)
except:
ProcessingLog.addToLog(ProcessingLog.LOG_WARNING,
self.tr('Geometry exception while splitting'))
result = 1

# splitGeometry: If there are several intersections
# between geometry and splitLine, only the first one is considered.
if result == 0: # split occurred

if inPoints == vector.extractPoints(inGeom):
# bug in splitGeometry: sometimes it returns 0 but
# the geometry is unchanged
QgsMessageLog.logMessage("appending")
outGeoms.append(inGeom)
else:
inGeoms.append(inGeom)

for aNewGeom in newGeometries:
inGeoms.append(aNewGeom)
else:
QgsMessageLog.logMessage("appending else")
outGeoms.append(inGeom)
else:
outGeoms.append(inGeom)

inGeoms = outGeoms

for aGeom in inGeoms:
passed = True

if QgsWkbTypes.geometryType( aGeom.wkbType() ) == QgsWkbTypes.LineGeometry \
and not QgsWkbTypes.isMultiType( aGeom.wkbType() ):
passed = len(aGeom.asPolyline()) > 2

if not passed:
passed = (len(aGeom.asPolyline()) == 2 and
aGeom.asPolyline()[0] != aGeom.asPolyline()[1])
# sometimes splitting results in lines of zero length

if passed:
outFeat.setGeometry(aGeom)
writer.addFeature(outFeat)

progress.setPercentage(int(current * total))

if multiGeoms > 0:
ProcessingLog.addToLog(ProcessingLog.LOG_INFO,
self.tr('Feature geometry error: %s input features ignored due to multi-geometry.') % str(multiGeoms))

del writer
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<GMLFeatureClassList>
<GMLFeatureClass>
<Name>polys_split_with_lines</Name>
<ElementPath>polys_split_with_lines</ElementPath>
<!--POLYGON-->
<GeometryType>3</GeometryType>
<SRSName>GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]</SRSName>
<DatasetSpecificInfo>
<FeatureCount>7</FeatureCount>
<ExtentXMin>-1.00000</ExtentXMin>
<ExtentXMax>10.00000</ExtentXMax>
<ExtentYMin>-3.00000</ExtentYMin>
<ExtentYMax>6.00000</ExtentYMax>
</DatasetSpecificInfo>
<PropertyDefn>
<Name>fid</Name>
<ElementPath>fid</ElementPath>
<Type>String</Type>
<Width>7</Width>
</PropertyDefn>
<PropertyDefn>
<Name>name</Name>
<ElementPath>name</ElementPath>
<Type>String</Type>
<Width>5</Width>
</PropertyDefn>
<PropertyDefn>
<Name>intval</Name>
<ElementPath>intval</ElementPath>
<Type>Integer</Type>
</PropertyDefn>
<PropertyDefn>
<Name>floatval</Name>
<ElementPath>floatval</ElementPath>
<Type>Real</Type>
</PropertyDefn>
</GMLFeatureClass>
</GMLFeatureClassList>
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?xml version="1.0" encoding="utf-8" ?>
<ogr:FeatureCollection
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=""
xmlns:ogr="http://ogr.maptools.org/"
xmlns:gml="http://www.opengis.net/gml">
<gml:boundedBy>
<gml:Box>
<gml:coord><gml:X>-1</gml:X><gml:Y>-3</gml:Y></gml:coord>
<gml:coord><gml:X>10</gml:X><gml:Y>6</gml:Y></gml:coord>
</gml:Box>
</gml:boundedBy>

<gml:featureMember>
<ogr:polys_split_with_lines fid="polys.0">
<ogr:geometryProperty><gml:Polygon srsName="EPSG:4326"><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>-1,-1 -1,3 3,3 3,2 2,2 2,-1 -1,-1</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></ogr:geometryProperty>
<ogr:name>aaaaa</ogr:name>
<ogr:intval>33</ogr:intval>
<ogr:floatval>44.123456</ogr:floatval>
</ogr:polys_split_with_lines>
</gml:featureMember>
<gml:featureMember>
<ogr:polys_split_with_lines fid="polys.1">
<ogr:geometryProperty><gml:Polygon srsName="EPSG:4326"><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>5,5 6,4 4,4 5,5</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></ogr:geometryProperty>
<ogr:name>Aaaaa</ogr:name>
<ogr:intval>-33</ogr:intval>
<ogr:floatval>0</ogr:floatval>
</ogr:polys_split_with_lines>
</gml:featureMember>
<gml:featureMember>
<ogr:polys_split_with_lines fid="polys.2">
<ogr:geometryProperty><gml:Polygon srsName="EPSG:4326"><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>2,5 2,6 3,6 3,5 2,5</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></ogr:geometryProperty>
<ogr:name>bbaaa</ogr:name>
<ogr:floatval>0.123</ogr:floatval>
</ogr:polys_split_with_lines>
</gml:featureMember>
<gml:featureMember>
<ogr:polys_split_with_lines fid="polys.3">
<ogr:geometryProperty><gml:Polygon srsName="EPSG:4326"><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>6,-3 7,-2 9,-2 9,0 10,1 10,-3 6,-3</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></ogr:geometryProperty>
<ogr:name>ASDF</ogr:name>
<ogr:intval>0</ogr:intval>
</ogr:polys_split_with_lines>
</gml:featureMember>
<gml:featureMember>
<ogr:polys_split_with_lines fid="polys.3">
<ogr:geometryProperty><gml:Polygon srsName="EPSG:4326"><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>7,-2 6,-3 6,1 10,1 9,0 7,0 7,-2</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></ogr:geometryProperty>
<ogr:name>ASDF</ogr:name>
<ogr:intval>0</ogr:intval>
</ogr:polys_split_with_lines>
</gml:featureMember>
<gml:featureMember>
<ogr:polys_split_with_lines fid="polys.4">
<ogr:intval>120</ogr:intval>
<ogr:floatval>-100291.43213</ogr:floatval>
</ogr:polys_split_with_lines>
</gml:featureMember>
<gml:featureMember>
<ogr:polys_split_with_lines fid="polys.5">
<ogr:geometryProperty><gml:Polygon srsName="EPSG:4326"><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>3,2 6,1 6,-3 2,-1 2,2 3,2</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></ogr:geometryProperty>
<ogr:name>elim</ogr:name>
<ogr:intval>2</ogr:intval>
<ogr:floatval>3.33</ogr:floatval>
</ogr:polys_split_with_lines>
</gml:featureMember>
</ogr:FeatureCollection>

0 comments on commit 0e2ef06

Please sign in to comment.