|
29 | 29 | import random
|
30 | 30 |
|
31 | 31 | from qgis.core import (QgsApplication)
|
| 32 | +from collections import defaultdict |
32 | 33 | from processing.core.GeoAlgorithm import GeoAlgorithm
|
33 | 34 | from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException
|
34 | 35 | from processing.core.parameters import ParameterSelection
|
@@ -106,38 +107,23 @@ def processAlgorithm(self, feedback):
|
106 | 107 | layer.fields().toList(), layer.wkbType(), layer.crs())
|
107 | 108 |
|
108 | 109 | selran = []
|
109 |
| - current = 0 |
110 | 110 | total = 100.0 / (featureCount * len(unique))
|
111 | 111 | features = vector.features(layer)
|
112 | 112 |
|
113 |
| - if not len(unique) == featureCount: |
114 |
| - for classValue in unique: |
115 |
| - classFeatures = [] |
116 |
| - for i, feature in enumerate(features): |
117 |
| - attrs = feature.attributes() |
118 |
| - if attrs[index] == classValue: |
119 |
| - classFeatures.append(i) |
120 |
| - current += 1 |
121 |
| - feedback.setProgress(int(current * total)) |
122 |
| - |
123 |
| - if method == 1: |
124 |
| - selValue = int(round(value * len(classFeatures), 0)) |
125 |
| - else: |
126 |
| - selValue = value |
127 |
| - |
128 |
| - if selValue >= len(classFeatures): |
129 |
| - selFeat = classFeatures |
130 |
| - else: |
131 |
| - selFeat = random.sample(classFeatures, selValue) |
132 |
| - |
133 |
| - selran.extend(selFeat) |
134 |
| - else: |
135 |
| - selran = list(range(featureCount)) |
| 113 | + classes = defaultdict(list) |
| 114 | + for i, feature in enumerate(features): |
| 115 | + attrs = feature.attributes() |
| 116 | + classes[attrs[index]].append(feature) |
| 117 | + feedback.setProgress(int(i * total)) |
| 118 | + |
| 119 | + for subset in classes.values(): |
| 120 | + selValue = value if method != 1 else int(round(value * len(subset), 0)) |
| 121 | + selran.extend(random.sample(subset, selValue)) |
| 122 | + |
136 | 123 |
|
137 | 124 | features = vector.features(layer)
|
138 | 125 | total = 100.0 / len(features)
|
139 |
| - for (i, feat) in enumerate(features): |
140 |
| - if i in selran: |
141 |
| - writer.addFeature(feat) |
| 126 | + for (i, feat) in enumerate(selran): |
| 127 | + writer.addFeature(feat) |
142 | 128 | feedback.setProgress(int(i * total))
|
143 | 129 | del writer
|
0 commit comments