|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +""" |
| 4 | +*************************************************************************** |
| 5 | + TopoColors.py |
| 6 | + -------------- |
| 7 | + Date : February 2017 |
| 8 | + Copyright : (C) 2017 by Nyall Dawson |
| 9 | + Email : nyall dot dawson 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 | + |
| 20 | +__author__ = 'Nyall Dawson' |
| 21 | +__date__ = 'February 2017' |
| 22 | +__copyright__ = '(C) 2017, Nyall Dawson' |
| 23 | + |
| 24 | +# This will get replaced with a git SHA1 when you do a git archive323 |
| 25 | + |
| 26 | +__revision__ = '$Format:%H$' |
| 27 | + |
| 28 | +import os |
| 29 | +import operator |
| 30 | +from collections import defaultdict, deque |
| 31 | + |
| 32 | +from qgis.core import (QgsField, |
| 33 | + QgsGeometry, |
| 34 | + QgsSpatialIndex, |
| 35 | + NULL) |
| 36 | + |
| 37 | +from qgis.PyQt.QtCore import (QVariant) |
| 38 | + |
| 39 | +from processing.core.GeoAlgorithm import GeoAlgorithm |
| 40 | +from processing.core.parameters import ParameterVector |
| 41 | +from processing.core.outputs import OutputVector |
| 42 | +from processing.tools import dataobjects, vector |
| 43 | + |
| 44 | +pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0] |
| 45 | + |
| 46 | + |
| 47 | +class TopoColor(GeoAlgorithm): |
| 48 | + INPUT_LAYER = 'INPUT_LAYER' |
| 49 | + OUTPUT_LAYER = 'OUTPUT_LAYER' |
| 50 | + |
| 51 | + def defineCharacteristics(self): |
| 52 | + self.name, self.i18n_name = self.trAlgorithm('Topological coloring') |
| 53 | + self.group, self.i18n_group = self.trAlgorithm('Cartographic tools') |
| 54 | + self.tags = self.tr('topocolor,colors,graph,adjacent,assign') |
| 55 | + |
| 56 | + self.addParameter(ParameterVector(self.INPUT_LAYER, |
| 57 | + self.tr('Input layer'), [dataobjects.TYPE_VECTOR_POLYGON])) |
| 58 | + |
| 59 | + self.addOutput(OutputVector(self.OUTPUT_LAYER, self.tr('Colored'), datatype=[dataobjects.TYPE_VECTOR_POLYGON])) |
| 60 | + |
| 61 | + def processAlgorithm(self, feedback): |
| 62 | + layer = dataobjects.getObjectFromUri( |
| 63 | + self.getParameterValue(self.INPUT_LAYER)) |
| 64 | + |
| 65 | + fields = layer.fields() |
| 66 | + fields.append(QgsField('color_id', QVariant.Int)) |
| 67 | + |
| 68 | + writer = self.getOutputFromName( |
| 69 | + self.OUTPUT_LAYER).getVectorWriter( |
| 70 | + fields, |
| 71 | + layer.wkbType(), |
| 72 | + layer.crs()) |
| 73 | + |
| 74 | + # use a deque so we can drop features as we write them |
| 75 | + # it's a bit friendlier on memory usage |
| 76 | + features = deque(f for f in vector.features(layer)) |
| 77 | + |
| 78 | + topology, id_graph = self.compute_graph(features, feedback) |
| 79 | + feature_colors = ColoringAlgorithm.balanced(topology, feedback) |
| 80 | + |
| 81 | + max_colors = max(feature_colors.values()) |
| 82 | + feedback.pushInfo(self.tr('{} colors required').format(max_colors)) |
| 83 | + |
| 84 | + total = 20.0 / len(features) |
| 85 | + current = 0 |
| 86 | + while features: |
| 87 | + input_feature = features.popleft() |
| 88 | + output_feature = input_feature |
| 89 | + attributes = input_feature.attributes() |
| 90 | + if input_feature.id() in feature_colors: |
| 91 | + attributes.append(feature_colors[input_feature.id()]) |
| 92 | + else: |
| 93 | + attributes.append(NULL) |
| 94 | + output_feature.setAttributes(attributes) |
| 95 | + |
| 96 | + writer.addFeature(output_feature) |
| 97 | + current += 1 |
| 98 | + feedback.setProgress(80 + int(current * total)) |
| 99 | + |
| 100 | + del writer |
| 101 | + |
| 102 | + @staticmethod |
| 103 | + def compute_graph(features, feedback, create_id_graph=False): |
| 104 | + """ compute topology from a layer/field """ |
| 105 | + s = Graph(sort_graph=False) |
| 106 | + id_graph = None |
| 107 | + if create_id_graph: |
| 108 | + id_graph = Graph(sort_graph=True) |
| 109 | + |
| 110 | + # skip features without geometry |
| 111 | + features_with_geometry = dict((f.id(), f) for f in features if f.hasGeometry()) |
| 112 | + |
| 113 | + total = 70.0 / len(features_with_geometry) |
| 114 | + index = QgsSpatialIndex() |
| 115 | + |
| 116 | + i = 0 |
| 117 | + for feature_id, f in features_with_geometry.items(): |
| 118 | + engine = QgsGeometry.createGeometryEngine(f.geometry().geometry()) |
| 119 | + engine.prepareGeometry() |
| 120 | + |
| 121 | + feature_bounds = f.geometry().boundingBox() |
| 122 | + # grow bounds a little so we get touching features |
| 123 | + feature_bounds.grow(feature_bounds.width() * 0.01) |
| 124 | + intersections = index.intersects(feature_bounds) |
| 125 | + for l2 in intersections: |
| 126 | + f2 = features_with_geometry[l2] |
| 127 | + if engine.intersects(f2.geometry().geometry()): |
| 128 | + s.add_edge(f.id(), f2.id()) |
| 129 | + s.add_edge(f2.id(), f.id()) |
| 130 | + if id_graph: |
| 131 | + id_graph.add_edge(f.id(), f2.id()) |
| 132 | + |
| 133 | + index.insertFeature(f) |
| 134 | + i += 1 |
| 135 | + feedback.setProgress(int(i * total)) |
| 136 | + |
| 137 | + for feature_id, f in features_with_geometry.items(): |
| 138 | + if not feature_id in s.node_edge: |
| 139 | + s.add_edge(feature_id, None) |
| 140 | + |
| 141 | + return s, id_graph |
| 142 | + |
| 143 | + |
| 144 | +class ColoringAlgorithm: |
| 145 | + |
| 146 | + @staticmethod |
| 147 | + def balanced(graph, feedback): |
| 148 | + feature_colors = {} |
| 149 | + # start with 4 colors in pool |
| 150 | + color_pool = set(range(1, 5)) |
| 151 | + |
| 152 | + # calculate count of neighbours |
| 153 | + neighbour_count = defaultdict(int) |
| 154 | + for feature_id, neighbours in graph.node_edge.items(): |
| 155 | + neighbour_count[feature_id] += len(neighbours) |
| 156 | + |
| 157 | + # sort features by neighbour count - we want to handle those with more neighbours first |
| 158 | + sorted_by_count = [feature_id for feature_id in sorted(neighbour_count.items(), |
| 159 | + key=operator.itemgetter(1), |
| 160 | + reverse=True)] |
| 161 | + # counts for each color already assigned |
| 162 | + color_counts = defaultdict(int) |
| 163 | + for c in color_pool: |
| 164 | + color_counts[c] = 0 |
| 165 | + |
| 166 | + total = 10.0 / len(sorted_by_count) |
| 167 | + i = 0 |
| 168 | + |
| 169 | + for (feature_id, n) in sorted_by_count: |
| 170 | + # first work out which already assigned colors are adjacent to this feature |
| 171 | + adjacent_colors = set() |
| 172 | + for neighbour in graph.node_edge[feature_id]: |
| 173 | + if neighbour in feature_colors: |
| 174 | + adjacent_colors.add(feature_colors[neighbour]) |
| 175 | + |
| 176 | + # from the existing colors, work out which are available (ie non-adjacent) |
| 177 | + available_colors = color_pool.difference(adjacent_colors) |
| 178 | + |
| 179 | + if len(available_colors) == 0: |
| 180 | + # no existing colors available for this feature, so add new color to pool |
| 181 | + feature_color = len(color_pool) + 1 |
| 182 | + color_pool.add(feature_color) |
| 183 | + else: |
| 184 | + # choose least used available color |
| 185 | + counts = [(c, v) for c, v in color_counts.items() if c in available_colors] |
| 186 | + feature_color = sorted(counts, key=operator.itemgetter(1))[0][0] |
| 187 | + feature_colors[feature_id] = feature_color |
| 188 | + color_counts[feature_color] += 1 |
| 189 | + |
| 190 | + i += 1 |
| 191 | + feedback.setProgress(70 + int(i * total)) |
| 192 | + |
| 193 | + return feature_colors |
| 194 | + |
| 195 | + |
| 196 | +class Graph: |
| 197 | + |
| 198 | + def __init__(self, sort_graph=True): |
| 199 | + self.sort_graph = sort_graph |
| 200 | + self.node_edge = {} |
| 201 | + |
| 202 | + def add_edge(self, i, j): |
| 203 | + ij = [i, j] |
| 204 | + if self.sort_graph: |
| 205 | + ij.sort() |
| 206 | + (i, j) = ij |
| 207 | + if i in self.node_edge: |
| 208 | + self.node_edge[i].add(j) |
| 209 | + else: |
| 210 | + self.node_edge[i] = {j} |
| 211 | + |
| 212 | + def make_full(self): |
| 213 | + g = Graph(sort_graph=False) |
| 214 | + for k in self.node_edge.keys(): |
| 215 | + for v in self.node_edge[k]: |
| 216 | + g.add_edge(v, k) |
| 217 | + g.add_edge(k, v) |
| 218 | + return g |
0 commit comments