diff --git a/python/plugins/processing/algs/qgis/RandomExtractWithinSubsets.py b/python/plugins/processing/algs/qgis/RandomExtractWithinSubsets.py index 7ba41634ec7d..7afffe0411bf 100644 --- a/python/plugins/processing/algs/qgis/RandomExtractWithinSubsets.py +++ b/python/plugins/processing/algs/qgis/RandomExtractWithinSubsets.py @@ -125,8 +125,11 @@ def processAlgorithm(self, parameters, context, feedback): classes[attrs[index]].append(feature) feedback.setProgress(int(i * total)) - for subset in classes.values(): + for k, subset in classes.items(): selValue = value if method != 1 else int(round(value * len(subset), 0)) + if selValue > len(subset): + selValue = len(subset) + feedback.reportError(self.tr('Subset "{}" is smaller than requested number of features.'.format(k))) selran.extend(random.sample(subset, selValue)) total = 100.0 / featureCount if featureCount else 1 diff --git a/python/plugins/processing/algs/qgis/RandomSelectionWithinSubsets.py b/python/plugins/processing/algs/qgis/RandomSelectionWithinSubsets.py index 9281da0545b3..4321f1d586db 100644 --- a/python/plugins/processing/algs/qgis/RandomSelectionWithinSubsets.py +++ b/python/plugins/processing/algs/qgis/RandomSelectionWithinSubsets.py @@ -133,11 +133,14 @@ def processAlgorithm(self, parameters, context, feedback): feedback.setProgress(int(i * total)) selran = [] - for subset in classes.values(): + for k, subset in classes.items(): if feedback.isCanceled(): break selValue = value if method != 1 else int(round(value * len(subset), 0)) + if selValue > len(subset): + selValue = len(subset) + feedback.reportError(self.tr('Subset "{}" is smaller than requested number of features.'.format(k))) selran.extend(random.sample(subset, selValue)) layer.selectByIds(selran) diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index 6db7255abd07..239e17459576 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -3923,6 +3923,21 @@ tests: name: points_weighted.gml compare: false + - algorithm: qgis:randomextractwithinsubsets + name: Random extract within subset (subset smaller than number) + params: + FIELD: id2 + INPUT: + name: points.gml + type: vector + METHOD: 0 + NUMBER: 3 + results: + OUTPUT: + type: vector + name: points.gml + compare: false + - algorithm: qgis:heatmapkerneldensityestimation name: Heatmap (Kernel density estimation) params: @@ -5355,6 +5370,7 @@ tests: compare: fields: fid: skip + - algorithm: native:difference name: Test Difference B - A (basic) params: