"""Build a QGIS project that animates the A417 groundwater readings with the Temporal Controller. Part 9 of the TechnicalGIS series "AGS data in GIS". Run groundwater_monitoring.py first, then run this with the QGIS Python launcher, for example on Windows: "C:\\Program Files\\QGIS 3.40.12\\bin\\python-qgis-ltr.bat" qgis_groundwater.py It writes output/a417_groundwater.qgz (open it in QGIS Desktop and press play on the Temporal Controller) and renders two frames of the animation side by side as output/05-qgis-temporal-frames.png. Tested with QGIS 3.40.12-Bratislava. Data: A417 Missing Link ground investigation (BGS deposited data item 173984), Open Government Licence v3.0, contains British Geological Survey materials © UKRI 2026. Environment Agency LIDAR Composite DTM (Open Government Licence v3). """ from pathlib import Path from qgis.core import ( Qgis, QgsApplication, QgsClassificationRange, QgsCoordinateReferenceSystem, QgsDateTimeRange, QgsGraduatedSymbolRenderer, QgsHillshadeRenderer, QgsLineSymbol, QgsMapRendererParallelJob, QgsMapSettings, QgsMarkerSymbol, QgsPalLayerSettings, QgsProject, QgsRasterDataProvider, QgsRasterLayer, QgsRectangle, QgsSingleSymbolRenderer, QgsRendererRange, QgsTextBufferSettings, QgsTextFormat, QgsUnitTypes, QgsVectorLayer, QgsVectorLayerSimpleLabeling, ) from qgis.PyQt.QtCore import QDate, QDateTime, QPoint, QRect, QSize, Qt, QTime from qgis.PyQt.QtGui import QColor, QFont, QImage, QPainter HERE = Path(__file__).parent OUT = HERE / "output" DTM = HERE / "data" / "ea_dtm_391600_212800_4000m_5m.tif" GPKG = OUT / "a417_groundwater.gpkg" CREDIT = ("Contains Environment Agency information © Environment Agency and database right; " "BGS © UKRI (OGL v3)") # Change from each pipe's own median level, in metres: falling water in orange, rising water in blue. CLASSES = [(-99, -2, "#b35806", "more than 2 m below"), (-2, -0.5, "#f1a340", "0.5 to 2 m below"), (-0.5, 0.5, "#f7f7f7", "within 0.5 m"), (0.5, 2, "#67a9cf", "0.5 to 2 m above"), (2, 99, "#2166ac", "more than 2 m above")] FRAMES = [("September 2020", QDate(2020, 9, 1), QDate(2020, 10, 1)), ("February 2021", QDate(2021, 2, 1), QDate(2021, 3, 1))] def text_format(size, bold=False): fmt = QgsTextFormat() font = QFont("Arial") font.setBold(bold) fmt.setFont(font) fmt.setSize(size) buffer = QgsTextBufferSettings() buffer.setEnabled(True) buffer.setSize(0.8) buffer.setColor(QColor("white")) fmt.setBuffer(buffer) return fmt def main() -> None: qgs = QgsApplication([], False) qgs.initQgis() print("QGIS", Qgis.version()) project = QgsProject.instance() project.setCrs(QgsCoordinateReferenceSystem("EPSG:27700")) dtm = QgsRasterLayer(str(DTM), "LIDAR DTM (hillshade)") dtm.setRenderer(QgsHillshadeRenderer(dtm.dataProvider(), 1, 315, 45)) dtm.dataProvider().setZoomedInResamplingMethod(QgsRasterDataProvider.ResamplingMethod.Bilinear) dtm.setOpacity(0.7) contours = QgsVectorLayer(f"{GPKG}|layername=limestone_contours", "Birdlip Limestone groundwater (m OD)", "ogr") pipes = QgsVectorLayer(f"{GPKG}|layername=standpipes", "Standpipes", "ogr") # Dry and out-of-step readings are filtered in the layer source, so they never draw. readings = QgsVectorLayer(f'{GPKG}|layername=readings|subset="dry" = 0 AND "spike" = 0', "Water level readings", "ogr") for layer in [dtm, contours, pipes, readings]: print(f"{layer.name()}: valid={layer.isValid()}" + (f", {layer.featureCount()} features" if isinstance(layer, QgsVectorLayer) else "")) contours.setRenderer(QgsSingleSymbolRenderer( QgsLineSymbol.createSimple({"color": "#08306b", "width": "0.4"}))) label = QgsPalLayerSettings() label.fieldName = "format_number(\"level\", 0)" label.isExpression = True label.placement = Qgis.LabelPlacement.Line label.setFormat(text_format(6.5)) contours.setLabeling(QgsVectorLayerSimpleLabeling(label)) contours.setLabelsEnabled(True) pipes.setRenderer(QgsSingleSymbolRenderer(QgsMarkerSymbol.createSimple( {"name": "circle", "color": "0,0,0,0", "outline_color": "#333333", "outline_width": "0.3", "size": "4.2"}))) # Readings: one point per dip, coloured by the change from the pipe's median. ranges = [] for lo, hi, colour, name in CLASSES: symbol = QgsMarkerSymbol.createSimple({"name": "circle", "color": colour, "outline_color": "#222222", "outline_width": "0.25", "size": "3.2"}) ranges.append(QgsRendererRange(QgsClassificationRange(name, lo, hi), symbol)) readings.setRenderer(QgsGraduatedSymbolRenderer("change", ranges)) # The temporal settings the Temporal Controller uses: each reading is an instant, so with monthly steps # every frame shows the dips made in that month. temporal = readings.temporalProperties() temporal.setIsActive(True) temporal.setMode(Qgis.VectorTemporalMode.FeatureDateTimeInstantFromField) temporal.setStartField("time") navigation = project.timeSettings() navigation.setTemporalRange(QgsDateTimeRange(QDateTime(QDate(2019, 1, 1), QTime(0, 0)), QDateTime(QDate(2021, 8, 1), QTime(0, 0)))) navigation.setTimeStep(1) navigation.setTimeStepUnit(QgsUnitTypes.TemporalUnit.TemporalMonths) navigation.setFramesPerSecond(2) project.addMapLayers([dtm, contours, pipes, readings], False) root = project.layerTreeRoot() for layer in [readings, pipes, contours, dtm]: # first in the tree draws on top root.addLayer(layer) dtm.serverProperties().setAttribution("© Environment Agency, Open Government Licence v3") for layer in [contours, pipes, readings]: layer.serverProperties().setAttribution( "Contains British Geological Survey materials © UKRI, Open Government Licence v3") project.writeEntry("CopyrightLabel", "/Enabled", True) project.writeEntry("CopyrightLabel", "/Label", CREDIT) project.write(str(OUT / "a417_groundwater.qgz")) print("saved output/a417_groundwater.qgz with temporal readings, monthly steps") # Render two frames of the animation, the dry late summer of 2020 and the wet February of 2021. size = QSize(900, 1100) frames = [] for title, start, end in FRAMES: settings = QgsMapSettings() settings.setLayers([readings, pipes, contours, dtm]) settings.setDestinationCrs(project.crs()) settings.setExtent(QgsRectangle(392_000, 213_000, 395_000, 216_700)) settings.setOutputSize(size) settings.setOutputDpi(150) settings.setBackgroundColor(QColor("white")) settings.setIsTemporal(True) settings.setTemporalRange(QgsDateTimeRange(QDateTime(start, QTime(0, 0)), QDateTime(end, QTime(0, 0)), True, False)) job = QgsMapRendererParallelJob(settings) job.start() job.waitForFinished() shown = [f["change"] for f in readings.getFeatures() if start <= f["time"].date() < end] below, above = sum(c <= -0.5 for c in shown), sum(c >= 0.5 for c in shown) print(f"{title}: {len(shown)} readings in the frame, {below} more than 0.5 m below the pipe's median and " f"{above} more than 0.5 m above; scale 1:{settings.scale():,.0f}; render errors: {len(job.errors())}") frames.append((title, job.renderedImage(), len(shown))) gap, legend_h = 20, 70 image = QImage(size.width() * 2 + gap, size.height() + legend_h, QImage.Format_ARGB32) image.fill(QColor("white")) painter = QPainter(image) painter.setRenderHint(QPainter.Antialiasing) for i, (title, frame, shown) in enumerate(frames): x = i * (size.width() + gap) painter.drawImage(x, 0, frame) painter.setPen(QColor("#999999")) painter.drawRect(x, 0, size.width() - 1, size.height() - 1) painter.setFont(QFont("Arial", 11, QFont.Bold)) box = QRect(x + 10, 10, 420, 34) painter.fillRect(box, QColor(255, 255, 255, 225)) painter.setPen(QColor("#111111")) painter.drawText(box.adjusted(8, 0, 0, 0), Qt.AlignVCenter | Qt.AlignLeft, f"{title}: {shown} readings") painter.setFont(QFont("Arial", 8)) x, y = 12, size.height() + 14 painter.setPen(QColor("#111111")) painter.drawText(x, y + 12, "Water level against the pipe's own median:") x += painter.fontMetrics().horizontalAdvance("Water level against the pipe's own median:") + 16 for lo, hi, colour, name in CLASSES: painter.setBrush(QColor(colour)) painter.setPen(QColor("#222222")) painter.drawEllipse(QPoint(x + 6, y + 8), 6, 6) painter.drawText(x + 18, y + 12, name) x += painter.fontMetrics().horizontalAdvance(name) + 40 painter.setPen(QColor("#555555")) painter.drawText(12, y + 40, CREDIT + ". Open circles: every standpipe. Lines: Birdlip Limestone " "groundwater contours (m OD).") painter.end() image.save(str(OUT / "05-qgis-temporal-frames.png")) print(f"rendered 05-qgis-temporal-frames.png, {image.width()} x {image.height()} px") project.clear() qgs.exitQgis() if __name__ == "__main__": main()