GeoDonkey for QGIS 1.12

This commit is contained in:
GeoDonkey committed 2026-12-01 19:59:12 +01:00
commit 20ab32da30
63 files changed
+11157

No files matched your search

View File
Whitespace-only changes.
+183
View File
@@ -0,0 +1,183 @@
from __future__ import annotations
import collections
from typing import Any, Dict, Optional, Sequence, Tuple
from qgis.core import (
QgsCoordinateReferenceSystem,
QgsCoordinateTransform,
QgsFeature,
QgsFeatureSink,
QgsFields,
QgsGeometry,
QgsPointXY,
QgsProcessingAlgorithm,
QgsProcessingException,
QgsProcessingLayerPostProcessorInterface,
)
from .. import auth, config, geojson, layers, settings
from ..client import ApiClient
from ..compat import field, icon
from ..errors import GeoDonkeyError
from ..i18n import tr
from ..net import QgisTransport
from ..results import Field, Row
WGS84 = "EPSG:4326"
def wgs84() -> QgsCoordinateReferenceSystem:
return QgsCoordinateReferenceSystem(WGS84)
def build_fields(spec: Sequence[Field]) -> QgsFields:
fields = QgsFields()
for name, kind in spec:
fields.append(field(name, kind))
return fields
_KEEP = collections.deque(maxlen=64)
class Styler(QgsProcessingLayerPostProcessorInterface):
def __init__(self, rule) -> None:
super().__init__()
self._rule = rule
def postProcessLayer(self, layer, context, feedback) -> None: # noqa: N802
layers.apply_style(layer, self._rule)
class GeoDonkeyAlgorithm(QgsProcessingAlgorithm):
ICON = "geodonkey.svg"
GROUP = "GeoDonkey"
GROUP_ID = "geodonkey"
COST_KEY = ""
def group(self) -> str:
return tr(self.GROUP)
def groupId(self) -> str: # noqa: N802
return self.GROUP_ID
def icon(self):
return icon(self.ICON)
def price(self) -> int:
return config.COIN_COSTS.get(self.COST_KEY, 0)
def cost_note(self) -> str:
return tr(
"<p><b>Every run costs {coins} DonkeyCoins</b> once the {free} free "
"calls of the current hour are used up. The API key is taken from "
"the plugin settings (Web ▸ GeoDonkey ▸ GeoDonkey settings); "
"without a key only the free calls are available.</p>"
).format(coins=self.price(), free=config.FREE_CALLS_PER_HOUR)
def client(self, feedback) -> ApiClient:
api = ApiClient(transport=QgisTransport(),
base_url=settings.api_url(),
token=auth.load_token(),
language=settings.language())
if not api.token:
feedback.pushWarning(tr(
"No API key stored – only the free calls of this hour are available. "
"Add a key under Web ▸ GeoDonkey ▸ GeoDonkey settings."))
return api
@staticmethod
def fail(exc: GeoDonkeyError, feedback) -> None:
if exc.detail:
feedback.pushDebugInfo(exc.detail)
raise QgsProcessingException(exc.message)
@staticmethod
def report(api: ApiClient, feedback) -> None:
charged = api.usage.charged
if charged:
feedback.pushInfo(tr("Charged: {coins} DC · balance {balance} DC").format(
coins=charged, balance=api.usage.balance))
elif api.usage.free_remaining is not None:
feedback.pushInfo(tr("Free call · {count} left this hour").format(
count=api.usage.free_remaining))
def wgs84_point(self, parameters, name: str, context) -> Tuple[float, float]:
point = self.parameterAsPoint(parameters, name, context, wgs84())
return (point.x(), point.y())
@staticmethod
def source_points(source, context, feedback) -> Tuple[list, list]:
transform = QgsCoordinateTransform(source.sourceCrs(), wgs84(),
context.transformContext())
coordinates = []
features = []
skipped = 0
for feature in source.getFeatures():
if feedback.isCanceled():
break
geometry = feature.geometry()
if geometry is None or geometry.isEmpty():
skipped += 1
continue
point = geometry.centroid().asPoint() if geometry.isMultipart() \
else geometry.asPoint()
moved = transform.transform(QgsPointXY(point))
coordinates.append((moved.x(), moved.y()))
features.append(feature)
if skipped:
feedback.pushWarning(tr(
"{count} features without geometry were skipped.").format(count=skipped))
return coordinates, features
def make_sink(self, parameters, context, name: str, spec: Sequence[Field],
wkb, crs: Optional[QgsCoordinateReferenceSystem] = None):
return self.parameterAsSink(parameters, name, context,
build_fields(spec), wkb,
crs if crs is not None else wgs84())
def style(self, context, dest_id: Any, rule) -> bool:
if not dest_id or rule is None:
return False
try:
if not context.willLoadLayerOnCompletion(dest_id):
return False
details = context.layerToLoadOnCompletionDetails(dest_id)
except (AttributeError, TypeError):
return False
if details is None:
return False
processor = Styler(rule)
_KEEP.append(processor)
details.setPostProcessor(processor)
return True
@staticmethod
def write(sink, spec: Sequence[Field], rows: Sequence[Row], feedback) -> int:
if sink is None:
return 0
fields = build_fields(spec)
written = 0
for row in rows:
if feedback.isCanceled():
break
out = QgsFeature(fields)
wkt = geojson.to_wkt(row.get("geometry"))
if wkt:
out.setGeometry(QgsGeometry.fromWkt(wkt))
attrs = row.get("attrs") or {}
out.setAttributes([attrs.get(name) for name, _kind in spec])
sink.addFeature(out, QgsFeatureSink.Flag.FastInsert)
written += 1
return written
def attribution(meta: Dict[str, Any], feedback) -> None:
text = geojson.attribution(meta)
if not text:
sources = meta.get("attributions")
if isinstance(sources, (list, tuple)) and sources:
text = ", ".join(str(entry) for entry in sources)
if text:
feedback.pushInfo(str(text))
@@ -0,0 +1,170 @@
from __future__ import annotations
from typing import Any, Dict, List
from qgis.core import (
QgsFeature,
QgsFeatureSink,
QgsFields,
QgsProcessing,
QgsProcessingException,
QgsProcessingParameterFeatureSink,
QgsProcessingParameterFeatureSource,
)
from .. import config, points, results, style
from ..compat import field
from ..errors import GeoDonkeyError
from ..i18n import tr
from .base import GeoDonkeyAlgorithm
OUTSIDE = "outside"
class ElevationPointsAlgorithm(GeoDonkeyAlgorithm):
ICON = "elevation.svg"
GROUP = "Elevation"
GROUP_ID = "elevation"
COST_KEY = "elevation_points"
INPUT = "INPUT"
OUTPUT = "OUTPUT"
def createInstance(self): # noqa: N802
return ElevationPointsAlgorithm()
def name(self) -> str:
return "elevationpoints"
def displayName(self) -> str: # noqa: N802
return tr("Add elevation to points")
def shortHelpString(self) -> str: # noqa: N802
return tr(
"<p>Looks up the elevation above sea level for every point of a "
"layer and writes it into three new fields: <code>elevation</code>, "
"<code>ele_source</code> and <code>ele_state</code>. Geometry and "
"existing fields are kept unchanged.</p>"
"<p>Layers with more than {max_points} points are split into "
"several calls automatically. That does not cost extra: the price "
"follows the number of points, not the number of calls.</p>"
"<p><b>Elevation data is available for Germany only.</b> Points "
"outside keep their place in the layer, get an empty elevation and "
"<code>{outside}</code> in <code>ele_state</code> – a single point "
"abroad does not abort the run.</p>"
"<p><b>The price follows the quantity:</b> {coins} DonkeyCoins per "
"started {batch} points, once the {free} free calls of the current "
"hour are used up.</p>"
"<p>Elevation data by the surveying authorities of the German "
"federal states; the exact source of every point is in "
"<code>ele_source</code>.</p>"
).format(max_points=config.ELEVATION_MAX_POINTS,
batch=config.ELEVATION_BILLING_BATCH,
coins=config.COIN_COSTS.get("elevation_points", 2),
free=config.FREE_CALLS_PER_HOUR, outside=OUTSIDE)
def initAlgorithm(self, configuration=None): # noqa: N802
self.addParameter(QgsProcessingParameterFeatureSource(
self.INPUT, tr("Point layer"),
types=[QgsProcessing.SourceType.TypeVectorPoint]))
self.addParameter(QgsProcessingParameterFeatureSink(
self.OUTPUT, tr("Points with elevation"),
type=QgsProcessing.SourceType.TypeVectorPoint))
def processAlgorithm(self, parameters, context, feedback): # noqa: N802
source = self.parameterAsSource(parameters, self.INPUT, context)
if source is None:
raise QgsProcessingException(tr("The input layer could not be read."))
coordinates, features = self.source_points(source, context, feedback)
if not coordinates:
raise QgsProcessingException(tr("The layer contains no usable points."))
inside, outside = points.split_germany(coordinates)
if outside:
feedback.pushWarning(tr(
"{count} points lie outside Germany and get no elevation.").format(
count=len(outside)))
if not inside:
raise QgsProcessingException(points.germany_message())
values = self._lookup(coordinates, inside, feedback)
if feedback.isCanceled():
return {}
out_fields = self._fields(source.fields())
sink, dest = self.parameterAsSink(
parameters, self.OUTPUT, context, out_fields,
source.wkbType(), source.sourceCrs())
if sink is None:
raise QgsProcessingException(tr("The output could not be created."))
known = 0
for feature, extra in zip(features, values):
if feedback.isCanceled():
return {}
out = QgsFeature(out_fields)
out.setGeometry(feature.geometry())
out.setAttributes(list(feature.attributes()) + [
extra.get("elevation"), extra.get("ele_source"),
extra.get("ele_state")])
sink.addFeature(out, QgsFeatureSink.Flag.FastInsert)
if extra.get("elevation") is not None:
known += 1
feedback.pushInfo(tr("{known} of {count} points have an elevation.").format(
known=known, count=len(features)))
self.style(context, dest, style.elevation_plan())
feedback.setProgress(100)
result: Dict[str, Any] = {self.OUTPUT: dest}
return result
def _lookup(self, coordinates, inside: List[int], feedback) -> List[Dict[str, Any]]:
wanted = set(inside)
values: List[Dict[str, Any]] = [
{"elevation": None, "ele_source": None,
"ele_state": None if index in wanted else OUTSIDE}
for index in range(len(coordinates))
]
api = self.client(feedback)
batches = list(points.chunks(inside, config.ELEVATION_MAX_POINTS))
for number, batch in enumerate(batches):
if feedback.isCanceled():
return values
feedback.pushInfo(tr("Batch {number} of {total} · {count} points").format(
number=number + 1, total=len(batches), count=len(batch)))
try:
payload = api.elevation_points([coordinates[i] for i in batch],
feedback=feedback)
except GeoDonkeyError as exc:
self.fail(exc, feedback)
self.report(api, feedback)
answers = results.elevation_values(payload)
if len(answers) != len(batch):
raise QgsProcessingException(tr(
"The service returned {got} elevations for {sent} points."
).format(got=len(answers), sent=len(batch)))
for position, index in enumerate(batch):
values[index] = answers[position]
feedback.setProgress(10 + 80.0 * (number + 1) / len(batches))
return values
@staticmethod
def _fields(source_fields: QgsFields) -> QgsFields:
out = QgsFields()
taken = set()
for existing in source_fields:
out.append(existing)
taken.add(existing.name())
for name, kind in results.ELEVATION_FIELDS:
unique = name
suffix = 2
while unique in taken:
unique = "%s_%d" % (name, suffix)
suffix += 1
taken.add(unique)
out.append(field(unique, kind))
return out
@@ -0,0 +1,149 @@
from __future__ import annotations
from typing import Any, Dict
from qgis.core import (
QgsProcessing,
QgsProcessingException,
QgsProcessingParameterFeatureSink,
QgsProcessingParameterNumber,
QgsProcessingParameterPoint,
QgsWkbTypes,
)
from .. import config, results, style
from ..errors import GeoDonkeyError
from ..i18n import tr
from .base import GeoDonkeyAlgorithm, attribution
class ElevationProfileAlgorithm(GeoDonkeyAlgorithm):
ICON = "profile.svg"
GROUP = "Elevation"
GROUP_ID = "elevation"
COST_KEY = "elevation_profile"
START = "START"
END = "END"
MAX_POINTS = "MAX_POINTS"
STEP = "STEP"
OUTPUT = "OUTPUT"
OUTPUT_SEGMENTS = "OUTPUT_SEGMENTS"
def createInstance(self): # noqa: N802
return ElevationProfileAlgorithm()
def name(self) -> str:
return "elevationprofile"
def displayName(self) -> str: # noqa: N802
return tr("Elevation profile")
def shortHelpString(self) -> str: # noqa: N802
return tr(
"<p>Samples the terrain along the straight line between two points "
"and returns one point per sample, carrying the distance from the "
"start and the elevation above sea level.</p>"
"<p>The service places the samples on the centres of its elevation "
"tiles. <b>Maximum points</b> is the upper limit (at most "
"{max_points}), <b>Minimum spacing</b> the smallest distance "
"between two samples (at least {min_step} m).</p>"
"<p>Samples without elevation data keep their place in the list "
"and have an empty <code>elevation</code>. Dropping them would "
"tear the distance axis apart.</p>"
"<p><b>Elevation data is available for Germany only.</b> Points "
"outside are rejected before the call is sent.</p>"
"<p><b>The price follows the quantity:</b> {coins} DonkeyCoins per "
"started {batch} points of <i>Maximum points</i> – {max_points} "
"points therefore cost {full} DC, once the {free} free calls of "
"the current hour are used up.</p>"
"<p>Elevation data by the surveying authorities of the German "
"federal states; the exact source of every sample is in the field "
"<code>source</code>.</p>"
).format(max_points=config.ELEVATION_MAX_POINTS,
min_step=config.ELEVATION_MIN_STEP_METRES,
batch=config.ELEVATION_BILLING_BATCH,
coins=config.COIN_COSTS.get("elevation_profile", 2),
full=config.elevation_coins(config.ELEVATION_MAX_POINTS),
free=config.FREE_CALLS_PER_HOUR)
def initAlgorithm(self, configuration=None): # noqa: N802
self.addParameter(QgsProcessingParameterPoint(
self.START, tr("Start point")))
self.addParameter(QgsProcessingParameterPoint(
self.END, tr("End point")))
self.addParameter(QgsProcessingParameterNumber(
self.MAX_POINTS, tr("Maximum points"),
type=QgsProcessingParameterNumber.Type.Integer,
minValue=2, maxValue=config.ELEVATION_MAX_POINTS,
defaultValue=config.ELEVATION_MAX_POINTS))
self.addParameter(QgsProcessingParameterNumber(
self.STEP, tr("Minimum spacing (metres)"),
type=QgsProcessingParameterNumber.Type.Double,
minValue=config.ELEVATION_MIN_STEP_METRES,
defaultValue=config.ELEVATION_DEFAULT_STEP_METRES))
self.addParameter(QgsProcessingParameterFeatureSink(
self.OUTPUT, tr("Elevation profile"),
type=QgsProcessing.SourceType.TypeVectorPoint))
self.addParameter(QgsProcessingParameterFeatureSink(
self.OUTPUT_SEGMENTS, tr("Sections by gradient (optional)"),
type=QgsProcessing.SourceType.TypeVectorLine,
optional=True, createByDefault=False))
def processAlgorithm(self, parameters, context, feedback): # noqa: N802
start = self.wgs84_point(parameters, self.START, context)
end = self.wgs84_point(parameters, self.END, context)
max_points = self.parameterAsInt(parameters, self.MAX_POINTS, context)
step = self.parameterAsDouble(parameters, self.STEP, context)
api = self.client(feedback)
feedback.pushInfo(tr("Up to {count} points · {coins} DC").format(
count=max_points,
coins=config.elevation_coins(max_points, "elevation_profile")))
feedback.setProgress(5)
try:
payload = api.elevation_profile(start, end, max_points=max_points,
step=step, feedback=feedback)
except GeoDonkeyError as exc:
self.fail(exc, feedback)
if feedback.isCanceled():
return {}
feedback.setProgress(60)
self.report(api, feedback)
rows = results.profile_rows(payload)
feedback.pushInfo(results.profile_summary(payload))
attribution(results.metadata(payload), feedback)
covered = results.metadata(payload).get("covered")
if covered is not None and rows and covered < len(rows):
feedback.pushWarning(tr(
"{missing} of {count} points have no elevation data.").format(
missing=len(rows) - int(covered), count=len(rows)))
sink, dest = self.make_sink(parameters, context, self.OUTPUT,
results.PROFILE_FIELDS, QgsWkbTypes.Type.Point)
if sink is None:
raise QgsProcessingException(tr("The output could not be created."))
self.write(sink, results.PROFILE_FIELDS, rows, feedback)
self.style(context, dest, style.profile_point_plan())
out: Dict[str, Any] = {self.OUTPUT: dest}
feedback.setProgress(85)
if parameters.get(self.OUTPUT_SEGMENTS):
sink, dest = self.make_sink(parameters, context, self.OUTPUT_SEGMENTS,
results.PROFILE_SEGMENT_FIELDS,
QgsWkbTypes.Type.LineString)
if sink is not None:
self.write(sink, results.PROFILE_SEGMENT_FIELDS,
results.profile_segment_rows(payload), feedback)
self.style(context, dest, style.profile_segment_plan())
out[self.OUTPUT_SEGMENTS] = dest
feedback.setProgress(100)
return out
+129
View File
@@ -0,0 +1,129 @@
from __future__ import annotations
from typing import Any, Dict
from qgis.core import (
QgsProcessing,
QgsProcessingException,
QgsProcessingParameterEnum,
QgsProcessingParameterFeatureSink,
QgsProcessingParameterPoint,
QgsProcessingParameterString,
QgsWkbTypes,
)
from .. import config, results, style
from ..errors import GeoDonkeyError
from ..i18n import tr
from .base import GeoDonkeyAlgorithm, attribution
MEASURE_MINUTES = 0
MEASURE_KILOMETRES = 1
class IsochroneAlgorithm(GeoDonkeyAlgorithm):
ICON = "isochrone.svg"
GROUP = "Routing"
GROUP_ID = "routing"
COST_KEY = "isochrone"
POINT = "POINT"
MODE = "MODE"
MEASURE = "MEASURE"
VALUES = "VALUES"
OUTPUT = "OUTPUT"
def createInstance(self): # noqa: N802
return IsochroneAlgorithm()
def name(self) -> str:
return "isochrone"
def displayName(self) -> str: # noqa: N802
return tr("Isochrone (reachable area)")
def shortHelpString(self) -> str: # noqa: N802
return tr(
"<p>Calculates the area that can be reached from a point within a "
"given travel time or distance, using the road network – not a "
"circle around the point.</p>"
"<p><b>Contours</b> is a comma separated list, for example "
"<code>5,10,15</code>. Up to {rings} rings are calculated in a "
"single call and cost the same as one: travel time from {min_min} "
"to {max_min} minutes, distance from {min_km} to {max_km} "
"kilometres.</p>"
"<p>The rings are returned from the largest to the smallest, so "
"that drawing them in that order keeps all of them visible. The "
"field <code>label</code> holds the ring as readable text, for "
"example <code>10 min</code>.</p>"
"<p>Data © OpenStreetMap contributors, ODbL.</p>"
).format(rings=config.ISOCHRONE_MAX_RINGS,
min_min=int(config.ISOCHRONE_MIN_MINUTES),
max_min=int(config.ISOCHRONE_MAX_MINUTES),
min_km=config.ISOCHRONE_MIN_KILOMETRES,
max_km=int(config.ISOCHRONE_MAX_KILOMETRES)) + self.cost_note()
def initAlgorithm(self, configuration=None): # noqa: N802
self.addParameter(QgsProcessingParameterPoint(
self.POINT, tr("Start point")))
self.addParameter(QgsProcessingParameterEnum(
self.MODE, tr("Travel mode"),
options=[tr("Walking"), tr("Driving"), tr("Cycling")],
defaultValue=0))
self.addParameter(QgsProcessingParameterEnum(
self.MEASURE, tr("Measure"),
options=[tr("Travel time (minutes)"), tr("Distance (kilometres)")],
defaultValue=MEASURE_MINUTES))
self.addParameter(QgsProcessingParameterString(
self.VALUES, tr("Contours (comma separated)"),
defaultValue=config.ISOCHRONE_DEFAULT_MINUTES))
self.addParameter(QgsProcessingParameterFeatureSink(
self.OUTPUT, tr("Reachable area"),
type=QgsProcessing.SourceType.TypeVectorPolygon))
def processAlgorithm(self, parameters, context, feedback): # noqa: N802
lon, lat = self.wgs84_point(parameters, self.POINT, context)
mode = config.TRAVEL_MODES[self.parameterAsEnum(parameters, self.MODE, context)]
measure = self.parameterAsEnum(parameters, self.MEASURE, context)
values = (self.parameterAsString(parameters, self.VALUES, context) or "").strip()
api = self.client(feedback)
feedback.setProgress(5)
try:
if measure == MEASURE_KILOMETRES:
payload = api.isochrone(lon, lat, mode=mode, kilometres=values,
feedback=feedback)
else:
payload = api.isochrone(lon, lat, mode=mode, minutes=values,
feedback=feedback)
except GeoDonkeyError as exc:
self.fail(exc, feedback)
if feedback.isCanceled():
return {}
feedback.setProgress(60)
self.report(api, feedback)
rows = results.isochrone_rows(payload)
if not rows:
feedback.pushWarning(tr("No reachable area was returned for this point."))
attribution(results.metadata(payload), feedback)
sink, dest = self.make_sink(parameters, context, self.OUTPUT,
results.ISOCHRONE_FIELDS,
QgsWkbTypes.Type.MultiPolygon)
if sink is None:
raise QgsProcessingException(tr("The output could not be created."))
written = self.write(sink, results.ISOCHRONE_FIELDS, rows, feedback)
self.style(context, dest, style.isochrone_plan(
[row.get("attrs") or {} for row in rows]))
feedback.pushInfo(tr("{count} rings written.").format(count=written))
feedback.setProgress(100)
out: Dict[str, Any] = {self.OUTPUT: dest}
return out
@@ -0,0 +1,209 @@
from __future__ import annotations
from typing import Any, Dict
from qgis.core import (
QgsProcessing,
QgsProcessingException,
QgsProcessingParameterBoolean,
QgsProcessingParameterFeatureSink,
QgsProcessingParameterNumber,
QgsProcessingParameterPoint,
QgsWkbTypes,
)
from .. import config, results, style
from ..errors import GeoDonkeyError
from ..i18n import tr
from .base import GeoDonkeyAlgorithm, attribution
class LineOfSightAlgorithm(GeoDonkeyAlgorithm):
ICON = "lineofsight.svg"
GROUP = "Elevation"
GROUP_ID = "elevation"
COST_KEY = "line_of_sight"
FROM = "FROM"
TO = "TO"
HEIGHT_A = "HEIGHT_A"
HEIGHT_B = "HEIGHT_B"
CURVATURE = "CURVATURE"
K = "K"
STEP = "STEP"
MAX_POINTS = "MAX_POINTS"
OUTPUT_LINE = "OUTPUT_LINE"
OUTPUT_OBSTACLES = "OUTPUT_OBSTACLES"
OUTPUT_SAMPLES = "OUTPUT_SAMPLES"
OUTPUT_SEGMENTS = "OUTPUT_SEGMENTS"
def createInstance(self): # noqa: N802
return LineOfSightAlgorithm()
def name(self) -> str:
return "lineofsight"
def displayName(self) -> str: # noqa: N802
return tr("Line of sight")
def shortHelpString(self) -> str: # noqa: N802
return tr(
"<p>Checks whether there is a clear line of sight between two "
"points, using the terrain model including earth curvature and "
"atmospheric refraction.</p>"
"<p><b>Height above ground</b> is the height of the eye, the mast "
"or the roof edge at each end, from 0 to {max_height} m. If the "
"sight is blocked, the fields <code>raise_a</code> and "
"<code>raise_b</code> say how much higher one end would have to "
"be.</p>"
"<p>Three outputs: the <b>sight line</b> with the result in its "
"attributes, the <b>obstacles</b> as points at the spot where the "
"terrain rises highest above the ray, and optionally <b>every "
"sample</b> with terrain, ray and clearance – the basis for a "
"profile chart of your own.</p>"
"<p><b>Refraction factor k</b> is {k_default} for the standard "
"atmosphere. <code>k = 1</code> applies earth curvature without "
"refraction; switching curvature off applies neither.</p>"
"<p><b>Elevation data is available for Germany only.</b></p>"
"<p><b>Up to {free_metres} m of straight-line distance a run is "
"free</b>, above that it costs {coins} DonkeyCoins. This endpoint "
"has its own allowance of {free_calls} calls per hour, replacing "
"the shared one – after that it requires an API key, as the only "
"tool in this plugin.</p>"
"<p>Elevation data by the surveying authorities of the German "
"federal states.</p>"
).format(max_height=int(config.LOS_MAX_HEIGHT_METRES),
k_default=round(config.LOS_REFRACTION_K, 3),
free_metres=int(config.LOS_FREE_METRES),
coins=config.COIN_COSTS.get("line_of_sight", 2),
free_calls=config.ENDPOINT_FREE_CALLS.get("line_of_sight", 5))
def initAlgorithm(self, configuration=None): # noqa: N802
self.addParameter(QgsProcessingParameterPoint(
self.FROM, tr("Observer point")))
self.addParameter(QgsProcessingParameterPoint(
self.TO, tr("Target point")))
self.addParameter(QgsProcessingParameterNumber(
self.HEIGHT_A, tr("Height above ground at the observer (metres)"),
type=QgsProcessingParameterNumber.Type.Double,
minValue=0.0, maxValue=config.LOS_MAX_HEIGHT_METRES,
defaultValue=config.LOS_DEFAULT_HEIGHT_METRES))
self.addParameter(QgsProcessingParameterNumber(
self.HEIGHT_B, tr("Height above ground at the target (metres)"),
type=QgsProcessingParameterNumber.Type.Double,
minValue=0.0, maxValue=config.LOS_MAX_HEIGHT_METRES,
defaultValue=config.LOS_DEFAULT_HEIGHT_METRES))
self.addParameter(QgsProcessingParameterBoolean(
self.CURVATURE, tr("Account for earth curvature"), defaultValue=True))
self.addParameter(QgsProcessingParameterNumber(
self.K, tr("Refraction factor k"),
type=QgsProcessingParameterNumber.Type.Double,
minValue=0.1, maxValue=10.0,
defaultValue=config.LOS_REFRACTION_K))
self.addParameter(QgsProcessingParameterNumber(
self.STEP, tr("Minimum spacing (metres)"),
type=QgsProcessingParameterNumber.Type.Double,
minValue=config.ELEVATION_MIN_STEP_METRES,
defaultValue=config.ELEVATION_DEFAULT_STEP_METRES))
self.addParameter(QgsProcessingParameterNumber(
self.MAX_POINTS, tr("Maximum samples"),
type=QgsProcessingParameterNumber.Type.Integer,
minValue=2, maxValue=config.ELEVATION_MAX_POINTS,
defaultValue=config.ELEVATION_MAX_POINTS))
self.addParameter(QgsProcessingParameterFeatureSink(
self.OUTPUT_LINE, tr("Sight line"),
type=QgsProcessing.SourceType.TypeVectorLine))
self.addParameter(QgsProcessingParameterFeatureSink(
self.OUTPUT_OBSTACLES, tr("Obstacles"),
type=QgsProcessing.SourceType.TypeVectorPoint))
self.addParameter(QgsProcessingParameterFeatureSink(
self.OUTPUT_SEGMENTS, tr("Sections by visibility (optional)"),
type=QgsProcessing.SourceType.TypeVectorLine,
optional=True, createByDefault=False))
self.addParameter(QgsProcessingParameterFeatureSink(
self.OUTPUT_SAMPLES, tr("Samples (optional)"),
type=QgsProcessing.SourceType.TypeVectorPoint,
optional=True, createByDefault=False))
def processAlgorithm(self, parameters, context, feedback): # noqa: N802
start = self.wgs84_point(parameters, self.FROM, context)
end = self.wgs84_point(parameters, self.TO, context)
height_a = self.parameterAsDouble(parameters, self.HEIGHT_A, context)
height_b = self.parameterAsDouble(parameters, self.HEIGHT_B, context)
curvature = self.parameterAsBool(parameters, self.CURVATURE, context)
k = self.parameterAsDouble(parameters, self.K, context)
step = self.parameterAsDouble(parameters, self.STEP, context)
max_points = self.parameterAsInt(parameters, self.MAX_POINTS, context)
wants_segments = bool(parameters.get(self.OUTPUT_SEGMENTS))
wants_samples = bool(parameters.get(self.OUTPUT_SAMPLES)) or wants_segments
api = self.client(feedback)
feedback.setProgress(5)
try:
payload = api.line_of_sight(start, end, height_a=height_a,
height_b=height_b, curvature=curvature,
k=k, step=step, max_points=max_points,
samples=wants_samples, feedback=feedback)
except GeoDonkeyError as exc:
self.fail(exc, feedback)
if feedback.isCanceled():
return {}
feedback.setProgress(60)
self.report(api, feedback)
line_rows, obstacle_rows, sample_rows = results.sight_rows(payload, start, end)
feedback.pushInfo(results.sight_summary(payload))
attribution(results.metadata(payload), feedback)
out: Dict[str, Any] = {}
sink, dest = self.make_sink(parameters, context, self.OUTPUT_LINE,
results.SIGHT_FIELDS,
QgsWkbTypes.Type.LineString)
if sink is None:
raise QgsProcessingException(tr("The output could not be created."))
self.write(sink, results.SIGHT_FIELDS, line_rows, feedback)
self.style(context, dest, style.sight_segment_plan())
out[self.OUTPUT_LINE] = dest
feedback.setProgress(70)
sink, dest = self.make_sink(parameters, context, self.OUTPUT_OBSTACLES,
results.OBSTACLE_FIELDS, QgsWkbTypes.Type.Point)
if sink is not None:
self.write(sink, results.OBSTACLE_FIELDS, obstacle_rows, feedback)
self.style(context, dest, style.sight_obstacle_plan())
out[self.OUTPUT_OBSTACLES] = dest
feedback.setProgress(80)
if wants_segments:
sink, dest = self.make_sink(parameters, context, self.OUTPUT_SEGMENTS,
results.SIGHT_SEGMENT_FIELDS,
QgsWkbTypes.Type.LineString)
if sink is not None:
self.write(sink, results.SIGHT_SEGMENT_FIELDS,
results.sight_segment_rows(payload, start, end), feedback)
self.style(context, dest, style.sight_segment_plan())
out[self.OUTPUT_SEGMENTS] = dest
feedback.setProgress(90)
if parameters.get(self.OUTPUT_SAMPLES):
sink, dest = self.make_sink(parameters, context, self.OUTPUT_SAMPLES,
results.SAMPLE_FIELDS, QgsWkbTypes.Type.Point)
if sink is not None:
self.write(sink, results.SAMPLE_FIELDS, sample_rows, feedback)
out[self.OUTPUT_SAMPLES] = dest
feedback.setProgress(100)
return out
+215
View File
@@ -0,0 +1,215 @@
from __future__ import annotations
from typing import Any, Dict, Mapping
from qgis.core import (
QgsCoordinateReferenceSystem,
QgsFeature,
QgsFeatureSink,
QgsFields,
QgsProcessing,
QgsProcessingException,
QgsProcessingParameterEnum,
QgsProcessingParameterExtent,
QgsProcessingParameterFeatureSink,
QgsProcessingParameterNumber,
QgsProcessingParameterString,
QgsVectorLayer,
QgsWkbTypes,
)
from qgis.PyQt.QtCore import QVariant
from .. import area as area_mod
from .. import config, geojson, layers, style
from ..client import split_collection
from ..compat import string_field
from ..errors import GeoDonkeyError
from ..i18n import tr
from .base import GeoDonkeyAlgorithm
MODE_WORDS = 0
MODE_TAGS = 1
MODE_QUERY = 2
SINKS = (
("OUTPUT_POINTS", "Point", QgsWkbTypes.Type.Point, "Points"),
("OUTPUT_LINES", "Line", QgsWkbTypes.Type.MultiLineString, "Lines"),
("OUTPUT_POLYGONS", "Polygon", QgsWkbTypes.Type.MultiPolygon, "Areas"),
)
def output_fields() -> QgsFields:
fields = QgsFields()
for name, _kind in geojson.PROCESSING_FIELDS:
fields.append(string_field(name))
return fields
class DonkeyOsmAlgorithm(GeoDonkeyAlgorithm):
ICON = "osm.svg"
GROUP = "OpenStreetMap"
GROUP_ID = "openstreetmap"
COST_KEY = "osm"
MODE = "MODE"
QUERY = "QUERY"
EXTENT = "EXTENT"
TYPES = "TYPES"
LIMIT = "LIMIT"
def createInstance(self): # noqa: N802
return DonkeyOsmAlgorithm()
def name(self) -> str:
return "donkeyosm"
def displayName(self) -> str: # noqa: N802
return tr("DonkeyOSM query")
def shortHelpString(self) -> str: # noqa: N802
return tr(
"<p>Queries OpenStreetMap data through the DonkeyOSM service of "
"geodonkey.com and returns it as three layers: points, lines and "
"areas.</p>"
"<p><b>Search mode</b> decides how the query text is read: as "
"everyday words, as a comma separated list of OSM tags "
"(<code>shop=bakery,amenity=cafe</code>), or as a DonkeyOSM line "
"query (one selection per line).</p>"
"<p><b>Every run costs {coins} DonkeyCoins</b> once the free calls "
"of the current hour are used up. The API key is taken from the "
"plugin settings.</p>"
"<p>All outputs share the same five fields: <code>osm_type</code>, "
"<code>osm_id</code>, <code>osm_url</code>, <code>name</code> and "
"<code>tags</code>. <code>tags</code> holds the complete OSM tags "
"as JSON text, so the schema stays the same no matter what the "
"query finds.</p>"
"<p>Data © OpenStreetMap contributors, ODbL.</p>"
).format(coins=config.COIN_COSTS.get("osm", 3))
def initAlgorithm(self, configuration=None): # noqa: N802
self.addParameter(QgsProcessingParameterEnum(
self.MODE, tr("Search mode"),
options=[tr("Plain language"), tr("OSM tags"), tr("Custom line query")],
defaultValue=MODE_WORDS))
self.addParameter(QgsProcessingParameterString(
self.QUERY, tr("Query"), multiLine=True))
self.addParameter(QgsProcessingParameterExtent(
self.EXTENT, tr("Area")))
self.addParameter(QgsProcessingParameterString(
self.TYPES, tr("OSM element types (node, way, relation)"),
defaultValue="", optional=True))
self.addParameter(QgsProcessingParameterNumber(
self.LIMIT, tr("Maximum objects"),
type=QgsProcessingParameterNumber.Type.Integer,
minValue=1, maxValue=config.OSM_LIMIT_PRO,
defaultValue=config.OSM_LIMIT_DEFAULT))
for key, _group, _wkb, label in SINKS:
self.addParameter(QgsProcessingParameterFeatureSink(
key, tr(label), type=QgsProcessing.SourceType.TypeVectorAnyGeometry,
optional=True, createByDefault=True))
def processAlgorithm(self, parameters, context, feedback): # noqa: N802
mode = self.parameterAsEnum(parameters, self.MODE, context)
text = (self.parameterAsString(parameters, self.QUERY, context) or "").strip()
types = (self.parameterAsString(parameters, self.TYPES, context) or "").strip()
limit = self.parameterAsInt(parameters, self.LIMIT, context)
if not text:
raise QgsProcessingException(tr("The query is empty."))
rect = self.parameterAsExtent(parameters, self.EXTENT, context,
QgsCoordinateReferenceSystem("EPSG:4326"))
if rect.isEmpty():
raise QgsProcessingException(tr("The area is empty."))
try:
area = area_mod.bbox_param(rect.xMinimum(), rect.yMinimum(),
rect.xMaximum(), rect.yMaximum())
except GeoDonkeyError as exc:
raise QgsProcessingException(exc.message)
client = self.client(feedback)
feedback.pushInfo(tr("Area: {area}").format(area=area_mod.describe(area)))
feedback.setProgress(5)
try:
if mode == MODE_QUERY:
payload = client.osm_query(text, area, limit=limit, feedback=feedback)
elif mode == MODE_TAGS:
payload = client.osm_search(area, tags=text, types=types,
limit=limit, feedback=feedback)
else:
payload = client.osm_search(area, words=text, types=types,
limit=limit, feedback=feedback)
except GeoDonkeyError as exc:
self.fail(exc, feedback)
if feedback.isCanceled():
return {}
feedback.setProgress(50)
collection, meta = split_collection(payload)
self.report(client, feedback)
if meta.get("truncated"):
feedback.pushWarning(tr(
"The limit of {limit} was reached – the result is incomplete.").format(
limit=meta.get("limit") or limit))
feedback.pushInfo(geojson.attribution(meta, config.DEFAULT_ATTRIBUTION))
buckets, without = geojson.split_by_geometry(collection)
if without:
feedback.pushInfo(tr("{count} objects without geometry were skipped.").format(
count=without))
results: Dict[str, Any] = {}
for index, (key, group, wkb, _label) in enumerate(SINKS):
if feedback.isCanceled():
return results
sink, dest = self.parameterAsSink(
parameters, key, context, output_fields(), wkb,
QgsCoordinateReferenceSystem("EPSG:4326"))
if sink is None:
continue
part = buckets.get(group)
if part:
self._fill(sink, part, group, feedback)
self.style(context, dest, style.osm_plan(group))
results[key] = dest
feedback.setProgress(50 + (index + 1) * 15)
return results
@staticmethod
def _fill(sink: QgsFeatureSink, part: Mapping[str, Any], group: str,
feedback) -> None:
folder = layers.result_folder()
path = geojson.write_collection(folder, "processing-%s" % group.lower(), part)
layer = QgsVectorLayer(geojson.ogr_uri(path, group, flatten=False),
"donkeyosm", "ogr")
if not layer.isValid():
raise QgsProcessingException(
tr("QGIS could not read the result file: {path}").format(path=path))
names = [field.name() for field in layer.fields()]
for feature in layer.getFeatures():
if feedback.isCanceled():
return
raw = {name: _plain(feature[name]) for name in names}
row = geojson.processing_row({"properties": raw})
out = QgsFeature(output_fields())
out.setGeometry(feature.geometry())
out.setAttributes([row[name] for name, _kind in geojson.PROCESSING_FIELDS])
sink.addFeature(out, QgsFeatureSink.Flag.FastInsert)
def _plain(value):
if value is None:
return None
if isinstance(value, QVariant):
return None if value.isNull() else value.value()
return value
+42
View File
@@ -0,0 +1,42 @@
from __future__ import annotations
from qgis.core import QgsProcessingProvider
from ..compat import icon
from ..i18n import tr
from .elevation_points_algorithm import ElevationPointsAlgorithm
from .elevation_profile_algorithm import ElevationProfileAlgorithm
from .isochrone_algorithm import IsochroneAlgorithm
from .line_of_sight_algorithm import LineOfSightAlgorithm
from .osm_algorithm import DonkeyOsmAlgorithm
from .route_algorithm import RouteAlgorithm
ALGORITHMS = (
DonkeyOsmAlgorithm,
IsochroneAlgorithm,
RouteAlgorithm,
ElevationProfileAlgorithm,
ElevationPointsAlgorithm,
LineOfSightAlgorithm,
)
class GeoDonkeyProvider(QgsProcessingProvider):
def loadAlgorithms(self) -> None: # noqa: N802
for algorithm in ALGORITHMS:
self.addAlgorithm(algorithm())
def id(self) -> str: # noqa: A003
return "geodonkey"
def name(self) -> str:
return "GeoDonkey"
def longName(self) -> str: # noqa: N802
return tr("GeoDonkey – OpenStreetMap, routing, elevation and map styles")
def icon(self):
return icon("geodonkey.svg")
def versionInfo(self) -> str: # noqa: N802
return "1.12"
+181
View File
@@ -0,0 +1,181 @@
from __future__ import annotations
from typing import Any, Dict, List, Tuple
from qgis.core import (
QgsProcessing,
QgsProcessingException,
QgsProcessingParameterBoolean,
QgsProcessingParameterEnum,
QgsProcessingParameterFeatureSink,
QgsProcessingParameterFeatureSource,
QgsProcessingParameterPoint,
QgsWkbTypes,
)
from .. import config, results, settings, style
from ..errors import GeoDonkeyError
from ..i18n import tr
from .base import GeoDonkeyAlgorithm, attribution
LANGUAGE_OPTIONS = ("", ) + tuple(config.ROUTE_LANGUAGES)
class RouteAlgorithm(GeoDonkeyAlgorithm):
ICON = "route.svg"
GROUP = "Routing"
GROUP_ID = "routing"
COST_KEY = "route"
START = "START"
END = "END"
VIA = "VIA"
MODE = "MODE"
OPTIMIZE = "OPTIMIZE"
STEPS = "STEPS"
LANGUAGE = "LANGUAGE"
OUTPUT_ROUTE = "OUTPUT_ROUTE"
OUTPUT_POINTS = "OUTPUT_POINTS"
def createInstance(self): # noqa: N802
return RouteAlgorithm()
def name(self) -> str:
return "route"
def displayName(self) -> str: # noqa: N802
return tr("Route")
def shortHelpString(self) -> str: # noqa: N802
return tr(
"<p>Calculates a route from the start through any stopovers to the "
"destination and returns two layers: the driven legs as lines and "
"the stops as points.</p>"
"<p><b>Stopovers</b> is an optional point layer. Its features are "
"visited in the order of the layer. Start, stopovers and "
"destination together may be at most {max_points} points.</p>"
"<p><b>Optimise stopover order</b> searches for the shortest "
"order of the stopovers; start and destination stay where they "
"are. The field <code>stop</code> then holds the driven order and "
"<code>input</code> the order as entered.</p>"
"<p><b>Turn-by-turn directions</b> adds the instructions of each "
"leg to the field <code>directions</code>.</p>"
"<p>Maximum total length: {walking} km walking, {cycling} km "
"cycling, {driving} km driving.</p>"
"<p>Data © OpenStreetMap contributors, ODbL.</p>"
"<p><b>A run costs {plain} DonkeyCoins, {optimized} with optimised "
"stopover order</b>, once the {free} free calls of the current "
"hour are used up. The API key is taken from the plugin settings "
"(Web ▸ GeoDonkey ▸ GeoDonkey settings).</p>"
).format(max_points=config.ROUTE_MAX_POINTS,
walking=int(config.ROUTE_MAX_KILOMETRES["walking"]),
cycling=int(config.ROUTE_MAX_KILOMETRES["cycling"]),
driving=int(config.ROUTE_MAX_KILOMETRES["driving"]),
plain=config.COIN_COSTS.get("route", 2),
optimized=config.COIN_COSTS.get("route_optimized", 3),
free=config.FREE_CALLS_PER_HOUR)
def initAlgorithm(self, configuration=None): # noqa: N802
self.addParameter(QgsProcessingParameterPoint(
self.START, tr("Start")))
self.addParameter(QgsProcessingParameterPoint(
self.END, tr("Destination")))
self.addParameter(QgsProcessingParameterFeatureSource(
self.VIA, tr("Stopovers (optional point layer)"),
types=[QgsProcessing.SourceType.TypeVectorPoint], optional=True))
self.addParameter(QgsProcessingParameterEnum(
self.MODE, tr("Travel mode"),
options=[tr("Walking"), tr("Driving"), tr("Cycling")],
defaultValue=1))
self.addParameter(QgsProcessingParameterBoolean(
self.OPTIMIZE, tr("Optimise stopover order"), defaultValue=False))
self.addParameter(QgsProcessingParameterBoolean(
self.STEPS, tr("Turn-by-turn directions"), defaultValue=False))
self.addParameter(QgsProcessingParameterEnum(
self.LANGUAGE, tr("Language of the directions"),
options=[tr("Follow QGIS"), tr("German"), tr("English"),
tr("French"), tr("Spanish")],
defaultValue=0))
self.addParameter(QgsProcessingParameterFeatureSink(
self.OUTPUT_ROUTE, tr("Route"),
type=QgsProcessing.SourceType.TypeVectorLine))
self.addParameter(QgsProcessingParameterFeatureSink(
self.OUTPUT_POINTS, tr("Stops"),
type=QgsProcessing.SourceType.TypeVectorPoint))
def processAlgorithm(self, parameters, context, feedback): # noqa: N802
stops = self._stops(parameters, context, feedback)
mode = config.TRAVEL_MODES[self.parameterAsEnum(parameters, self.MODE, context)]
optimize = self.parameterAsBool(parameters, self.OPTIMIZE, context)
steps = self.parameterAsBool(parameters, self.STEPS, context)
language = LANGUAGE_OPTIONS[
self.parameterAsEnum(parameters, self.LANGUAGE, context)]
if not language:
language = settings.language()
api = self.client(feedback)
feedback.pushInfo(tr("{count} points · {mode}").format(
count=len(stops), mode=mode))
feedback.setProgress(5)
try:
payload = api.route(stops, mode=mode, optimize=optimize, steps=steps,
language=language, feedback=feedback)
except GeoDonkeyError as exc:
self.fail(exc, feedback)
if feedback.isCanceled():
return {}
feedback.setProgress(60)
self.report(api, feedback)
legs, points_rows = results.route_rows(payload)
feedback.pushInfo(results.route_summary(payload))
attribution(results.metadata(payload), feedback)
out: Dict[str, Any] = {}
sink, dest = self.make_sink(parameters, context, self.OUTPUT_ROUTE,
results.ROUTE_LEG_FIELDS,
QgsWkbTypes.Type.MultiLineString)
if sink is None:
raise QgsProcessingException(tr("The output could not be created."))
self.write(sink, results.ROUTE_LEG_FIELDS, legs, feedback)
self.style(context, dest, style.route_leg_plan(
[row.get("attrs") or {} for row in legs]))
out[self.OUTPUT_ROUTE] = dest
feedback.setProgress(80)
sink, dest = self.make_sink(parameters, context, self.OUTPUT_POINTS,
results.ROUTE_STOP_FIELDS,
QgsWkbTypes.Type.Point)
if sink is not None:
self.write(sink, results.ROUTE_STOP_FIELDS, points_rows, feedback)
self.style(context, dest, style.route_stop_plan(
[row.get("attrs") or {} for row in points_rows]))
out[self.OUTPUT_POINTS] = dest
feedback.setProgress(100)
return out
def _stops(self, parameters, context, feedback) -> List[Tuple[float, float]]:
start = self.wgs84_point(parameters, self.START, context)
end = self.wgs84_point(parameters, self.END, context)
via: List[Tuple[float, float]] = []
source = self.parameterAsSource(parameters, self.VIA, context)
if source is not None:
via, _features = self.source_points(source, context, feedback)
stops = [start] + via + [end]
if len(stops) > config.ROUTE_MAX_POINTS:
raise QgsProcessingException(tr(
"{count} points given, at most {limit} are allowed.").format(
count=len(stops), limit=config.ROUTE_MAX_POINTS))
return stops