Coverage for brodata/gm.py: 67%
221 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-06 14:37 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-06 14:37 +0000
1import json
2import logging
3import os
4import urllib.request
5from zipfile import ZipFile
7import geopandas as gpd
8import pandas as pd
9import requests
10from shapely.geometry import MultiPolygon, Polygon
12from . import gar, gld, gmw, util
14base_url = "https://api.pdok.nl/bzk/bro-gminsamenhang-karakteristieken/ogc/v1"
16logger = logging.getLogger(__name__)
19def conformance():
20 url = f"{base_url}/conformance"
21 r = requests.get(url, params={"f": "json"})
22 if not r.ok:
23 raise Exception(f"Retrieving data from {url} failed")
24 return r.json()
27def collections():
28 url = f"{base_url}/collections"
29 r = requests.get(url, params={"f": "json"})
30 if not r.ok:
31 raise Exception(f"Retrieving data from {url} failed")
32 return r.json()
35def gm_gld_collection():
36 url = f"{base_url}/collections/gm_gld"
37 r = requests.get(url, params={"f": "json"})
38 if not r.ok:
39 raise Exception(f"Retrieving data from {url} failed")
40 return r.json()
43def _gm_items(
44 url,
45 extent=None,
46 crs="http://www.opengis.net/def/crs/EPSG/0/28992",
47 limit=1000,
48 time_columns=None,
49 to_file=None,
50 zipfile=None,
51 redownload=False,
52 **kwargs,
53):
54 """
55 Fetches and parses geospatial features from a GeoJSON endpoint, with optional
56 filtering, pagination support, and time column localization.
58 Retrieves data from a remote URL, a local file, or within a zip archive. Supports
59 bounding box filtering, CRS specification, and conversion of datetime columns to
60 Dutch winter time (UTC+1).
62 Parameters
63 ----------
64 url : str
65 The base URL to request the GeoJSON data from.
66 extent : list, tuple, shapely.geometry.Polygon or shapely.geometry.MultiPolygon, optional
67 The spatial extent ([xmin, xmax, ymin, ymax]) or polygon geometry to filter the data.
68 When a polygon is provided, its bounding box is used for the spatial query.
69 crs : string, optional
70 The coordinate reference system of the requested extent and the geometries in
71 the response. Possible values are:
72 http://www.opengis.net/def/crs/OGC/1.3/CRS84
73 http://www.opengis.net/def/crs/EPSG/0/28992
74 http://www.opengis.net/def/crs/EPSG/0/3857
75 http://www.opengis.net/def/crs/EPSG/0/4258
76 The default is "http://www.opengis.net/def/crs/EPSG/0/28992".
77 limit : int, optional
78 Limits the number of items that are presented in the response document. The
79 maximum allowed value is 1000. The default is 1000.
80 time_columns : list of str, optional
81 Names of columns containing datetime values to convert to Dutch winter time.
82 If None, columns ending with '_time' are automatically selected.
83 to_file : str, optional
84 Path to save the downloaded GeoJSON file. If the file exists and
85 `redownload` is False, it will be reused.
86 zipfile : ZipFile, optional
87 A `zipfile.ZipFile` object from which to read the `to_file` if provided.
88 redownload : bool, optional
89 If True, forces redownload of the data even if `to_file` exists.
90 **kwargs : dict
91 Additional query parameters to include in the request.
93 Returns
94 -------
95 gdf : geopandas.GeoDataFrame
96 A GeoDataFrame containing the parsed geospatial features.
98 """
99 if zipfile is not None:
100 with zipfile.open(to_file) as f:
101 json_data = json.load(f)
102 elif redownload or to_file is None or not os.path.isfile(to_file):
103 params = {"f": "json", "crs": crs, "limit": limit}
104 if extent is not None:
105 if isinstance(extent, (Polygon, MultiPolygon)):
106 xmin, ymin, xmax, ymax = extent.bounds
107 else:
108 xmin, xmax, ymin, ymax = extent
109 bbox = f"{xmin},{ymin},{xmax},{ymax}"
110 params["bbox-crs"] = crs
111 params["bbox"] = bbox
113 for key in kwargs:
114 params[key] = kwargs[key]
115 r = requests.get(url, params=params)
117 if not r.ok:
118 detail = r.json()["detail"]
119 raise Exception(f"Retrieving data from {url} failed: {detail}")
120 if to_file is not None:
121 with open(to_file, "w") as f:
122 f.write(r.text)
123 json_data = r.json()
124 else:
125 with open(to_file) as f:
126 json_data = json.load(f)
127 if len(json_data["features"]) == 0:
128 msg = "No data found"
129 if extent is not None:
130 msg = "%s for extent=%s" % (msg, extent)
131 msg = "%s on %s" % (msg, url)
132 logger.warning(msg)
133 return
134 gdf = gpd.GeoDataFrame.from_features(json_data["features"], crs=crs)
135 url = _get_next_url(json_data)
136 if url is not None:
137 gdfs = [gdf]
138 while url is not None:
139 r = requests.get(url)
140 if not r.ok:
141 raise Exception(f"Retrieving data from {url} failed")
142 json_data = r.json()
143 gdfs.append(gpd.GeoDataFrame.from_features(json_data["features"], crs=crs))
144 url = _get_next_url(json_data)
145 gdf = pd.concat(gdfs, ignore_index=True)
146 if time_columns is None:
147 time_columns = gdf.columns[gdf.columns.str.endswith("_time")]
148 one_hour = pd.Timedelta(1, "hour")
149 for column in time_columns:
150 # transform date to dutch winter time
151 gdf[column] = (
152 pd.to_datetime(gdf[column], utc=True).dt.tz_localize(None) + one_hour
153 )
154 # Filter results to polygon if polygon extent was provided
155 if extent is not None and isinstance(extent, (Polygon, MultiPolygon)):
156 gdf = gdf[gdf.intersects(extent)]
157 return gdf
160def _get_next_url(json_data):
161 links = pd.DataFrame(json_data["links"])
162 next_mask = links["rel"] == "next"
163 if next_mask.any():
164 if next_mask.sum() > 1:
165 raise (ValueError("More than 1 'next' page"))
166 url = links.loc[next_mask, "href"].iloc[0]
167 return url
168 else:
169 return None
172def gar_items(*args, **kwargs):
173 url = f"{base_url}/collections/gm_gar/items"
175 gdf = _gm_items(url, *args, **kwargs)
176 return gdf
179def gld_items(*args, tmin=None, tmax=None, **kwargs):
180 url = f"{base_url}/collections/gm_gld/items"
182 gdf = _gm_items(url, *args, **kwargs)
184 return gdf
187def gmn_items(*args, **kwargs):
188 url = f"{base_url}/collections/gm_gmn/items"
190 gdf = _gm_items(url, *args, **kwargs)
192 return gdf
195def gmn_measuringpoint_items(*args, **kwargs):
196 url = f"{base_url}/collections/gm_gmn_measuringpoint/items"
198 gdf = _gm_items(url, *args, **kwargs)
200 return gdf
203def gmn_reference_items(*args, **kwargs):
204 url = f"{base_url}/collections/gm_gmn_reference/items"
206 gdf = _gm_items(url, *args, **kwargs)
208 return gdf
211def gmw_items(*args, **kwargs):
212 url = f"{base_url}/collections/gm_gmw/items"
214 gdf = _gm_items(url, *args, **kwargs)
216 return gdf
219def gmw_monitoringtube_items(*args, **kwargs):
220 url = f"{base_url}/collections/gm_gmw_monitoringtube/items"
222 gdf = _gm_items(url, *args, **kwargs)
224 return gdf
227def get_data_in_extent(
228 extent,
229 kind="gld",
230 tmin=None,
231 tmax=None,
232 silent=False,
233 combine=True,
234 index=None,
235 as_csv=False,
236 status=None,
237 observation_type=None,
238 qualifier=None,
239 to_path=None,
240 to_zip=None,
241 redownload=False,
242 continue_on_error=False,
243 sort=True,
244 drop_duplicates=True,
245 progress_callback=None,
246):
247 """
248 Retrieve metadata and observations within a specified spatial extent.
250 This function fetches monitoring well characteristics and groundwater observations
251 within the given spatial extent. It can combine the data for specific observation
252 types and return either individual dataframes or a combined dataframe.
254 Parameters
255 ----------
256 extent : object
257 The spatial extent ([xmin, xmax, ymin, ymax]) to filter the data.
258 kind : str, optional
259 The type of observations to retrieve. Valid values are {'gld', 'gar'} for
260 groundwater level dossier or groundwater analysis report. When kind is None, no
261 observations are downloaded. Defaults to 'gld'.
262 tmin : str or datetime, optional
263 The minimum time for filtering observations. Defaults to None.
264 tmax : str or datetime, optional
265 The maximum time for filtering observations. Defaults to None.
266 silent : bool, optional
267 If True, suppresses progress logging. Defaults to False.
268 combine : bool, optional
269 If True, combines the tube properties, and observations into a single
270 dataframe. Defaults to True.
271 index : str, optional
272 The column to use for indexing in the resulting dataframe. If None, the index
273 will be set to a MultiIndex of the columns "gmw_bro_id" and "tube_number".
274 Defaults to None.
275 as_csv : bool, optional
276 If True, the measurement data is requested as CSV files instead of XML files
277 (only supported for 'gld'). Defaults to False.
278 status : str, optional
279 A status string for additional filtering. Possible values are
280 "volledigBeoordeeld", "voorlopig" and "onbekend" Only valid if `kind` is 'gld'.
281 Defaults to None.
282 observation_type : str, optional
283 An observation type string for additional filtering. Possible values are
284 "reguliereMeting" and "controleMeting". Only valid if `kind` is 'gld'. Defaults
285 to None.
286 qualifier : str or list of str, optional
287 A string or list of strings used to filter the observations. Only valid if
288 `kind` is 'gld'. Defaults to None.
289 to_path : str, optional
290 If not None, save the downloaded files in the directory named to_path. The
291 default is None.
292 to_zip : str, optional
293 If not None, save the downloaded files in a zip-file named to_zip. The default
294 is None.
295 redownload : bool, optional
296 When downloaded files exist in to_path or to_zip, read from these files when
297 redownload is False. If redownload is True, download the data again from the
298 BRO-servers. The default is False.
299 continue_on_error : bool, optional
300 If True, continue after an error occurs during downloading or processing of
301 individual observation data. Defaults to False.
302 sort : bool, optional
303 If True, sort the observations. Only used if `kind` is 'gld'. Defaults to True.
304 drop_duplicates : bool, optional
305 If True, drop duplicate observations based on their timestamp. Only used if
306 `kind` is 'gld'. Defaults to True.
307 progress_callback : function, optional
308 A callback function that takes two arguments (current, total) to report
309 progress. If None, no progress reporting is done. Defaults to None.
311 Returns
312 -------
313 gdf : pd.DataFrame
314 A dataframe containing tube properties and metadata within the specified extent.
316 obs_df : pd.DataFrame, optional
317 A dataframe containing the observations for the specified wells. Returned only if
318 `combine` is False.
319 """
321 if isinstance(extent, str):
322 if to_zip is not None:
323 raise (Exception("When extent is a string, do not supply to_zip"))
324 to_zip = extent
325 if not os.path.isfile(to_zip):
326 raise (FileExistsError(f"The file {to_zip} is not present"))
327 extent = None
328 redownload = False
330 zipfile = None
331 _files = None
332 if to_zip is not None:
333 if not redownload and os.path.isfile(to_zip):
334 logger.info("Reading data from %s", to_zip)
335 zipfile = ZipFile(to_zip)
336 else:
337 if to_path is None:
338 to_path = os.path.splitext(to_zip)[0]
339 remove_path_again = not os.path.isdir(to_path)
340 _files = []
342 if to_path is not None and not os.path.isdir(to_path):
343 os.makedirs(to_path)
345 to_file = util._get_to_file("gm_gmw_monitoringtube.json", zipfile, to_path, _files)
346 tubes = gmw_monitoringtube_items(
347 extent, to_file=to_file, redownload=redownload, zipfile=zipfile
348 )
350 if tubes is None:
351 return tubes
353 if index is None:
354 index = ["gmw_bro_id", "tube_number"]
355 tubes = tubes.set_index(index)
357 if kind is None:
358 return tubes
360 obs_df = get_observations(
361 extent,
362 tubes=tubes,
363 kind=kind,
364 tmin=tmin,
365 tmax=tmax,
366 silent=silent,
367 as_csv=as_csv,
368 status=status,
369 observation_type=observation_type,
370 qualifier=qualifier,
371 to_path=to_path,
372 redownload=redownload,
373 continue_on_error=continue_on_error,
374 sort=sort,
375 drop_duplicates=drop_duplicates,
376 progress_callback=progress_callback,
377 zipfile=zipfile,
378 _files=_files,
379 )
380 # set the index of obs_df to the same index as tubes, so that they can be easily combined later on
381 obs_df = obs_df.reset_index().set_index(["groundwaterMonitoringWell", "tubeNumber"])
383 if zipfile is not None:
384 zipfile.close()
385 if zipfile is None and to_zip is not None:
386 util._save_data_to_zip(to_zip, _files, remove_path_again, to_path)
388 # only keep tubes with active measurements
389 mask = tubes.index.isin(obs_df.index)
390 tubes = tubes[mask]
392 if combine and kind in ["gld", "gar"]:
393 tubes = gmw.add_observations_to_tubes(
394 tubes, obs_df, kind=kind, sort=sort, drop_duplicates=drop_duplicates
395 )
396 return tubes
397 else:
398 return tubes, obs_df
401def get_observations(
402 extent,
403 tubes=None,
404 kind="gld",
405 tmin=None,
406 tmax=None,
407 silent=False,
408 as_csv=False,
409 status=None,
410 observation_type=None,
411 qualifier=None,
412 to_path=None,
413 redownload=False,
414 continue_on_error=False,
415 sort=True,
416 drop_duplicates=True,
417 progress_callback=None,
418 zipfile=None,
419 _files=None,
420):
421 """
422 Retrieve observations for monitoring wells within a specified spatial extent.
424 Parameters
425 ----------
426 extent : object
427 The spatial extent ([xmin, xmax, ymin, ymax]) to filter the data.
428 tubes : gpd.GeoDataFrame, optional
429 A GeoDataFrame containing monitoring tube properties. If provided, the
430 observations will be filtered to only include those associated with the
431 tubes in this GeoDataFrame. If None, all observations within the extent are
432 returned.
433 kind : str, optional
434 The type of observations to retrieve. Valid values are {'gld', 'gar'} for
435 groundwater level dossier or groundwater analysis report. Defaults to 'gld'.
436 tmin : str or datetime, optional
437 The minimum time for filtering observations. Defaults to None.
438 tmax : str or datetime, optional
439 The maximum time for filtering observations. Defaults to None.
440 silent : bool, optional
441 If True, suppresses progress logging. Defaults to False.
442 as_csv : bool, optional
443 If True, the measurement data is requested as CSV files instead of XML files
444 (only supported for 'gld'). Defaults to False.
445 status : str, optional
446 A status string for additional filtering. Possible values are
447 "volledigBeoordeeld", "voorlopig" and "onbekend" Only valid if `kind` is 'gld'.
448 Defaults to None.
449 observation_type : str, optional
450 An observation type string for additional filtering. Possible values are
451 "reguliereMeting" and "controleMeting". Only valid if `kind` is 'gld'. Defaults
452 to None.
453 qualifier : str or list of str, optional
454 A string or list of strings used to filter the observations. Only valid if
455 `kind` is 'gld'. Defaults to None.
456 to_path : str, optional
457 If not None, save the downloaded files in the directory named to_path. The
458 default is None.
459 redownload : bool, optional
460 When downloaded files exist in to_path or to_zip, read from these files when
461 redownload is False. If redownload is True, download the data again from the
462 BRO-servers. The default is False.
463 continue_on_error : bool, optional
464 If True, continue after an error occurs during downloading or processing of
465 individual observation data. Defaults to False.
466 sort : bool, optional
467 If True, sort the observations. Only used if `kind` is 'gld'. Defaults to True.
468 drop_duplicates : bool, optional
469 If True, drop duplicate observations based on their timestamp. Only used if
470 `kind` is 'gld'. Defaults to True.
471 progress_callback : function, optional
472 A callback function that takes two arguments (current, total) to report
473 progress. If None, no progress reporting is done. Defaults to None.
474 zipfile : ZipFile, optional
475 A `zipfile.ZipFile` object from which to read the `to_file` if provided.
476 _files : list, optional
477 A list of file paths to read the `to_file` if provided.
479 Returns
480 -------
481 obs_df : pd.DataFrame
482 A dataframe containing the observations for the specified wells, where each row
483 corresponds to an individual observation. The index is the BRO-id
484 of the observation-objects.
486 Raises
487 ------
488 ValueError
489 If the specified `kind` is not supported, or if `as_csv=True` and `kind` is not
490 'gld', or if `qualifier` is provided for a kind other than 'gld'.
491 """
492 if kind == "gar":
493 to_file = util._get_to_file("gm_gar.json", zipfile, to_path, _files)
494 meas_gdf = gar_items(
495 extent, to_file=to_file, redownload=redownload, zipfile=zipfile
496 )
497 if tmin is not None:
498 meas_gdf = meas_gdf[meas_gdf["sampling_date_time"] >= tmin]
500 if tmax is not None:
501 meas_gdf = meas_gdf[meas_gdf["sampling_date_time"] <= tmax]
502 meas_cl = gar.GroundwaterAnalysisReport
503 elif kind == "gld":
504 to_file = util._get_to_file("gm_gld.json", zipfile, to_path, _files)
505 meas_gdf = gld_items(
506 extent, to_file=to_file, redownload=redownload, zipfile=zipfile
507 )
508 if tmin is not None:
509 meas_gdf = meas_gdf[meas_gdf["research_last_date"] >= tmin]
511 if tmax is not None:
512 meas_gdf = meas_gdf[meas_gdf["research_first_date"] <= tmax]
513 meas_cl = gld.GroundwaterLevelDossier
514 else:
515 raise (ValueError(f"kind='{kind}' not supported"))
517 if tubes is not None:
518 # only download measurements for tubes that are present in the tubes-gdf
519 tube_pk = tubes["gm_gmw_monitoringtube_pk"].values
520 meas_gdf = meas_gdf[meas_gdf["gm_gmw_monitoringtube_fk"].isin(tube_pk)]
522 gld_kwargs = gmw._get_gld_kwargs(
523 kind, tmin, tmax, qualifier, status, observation_type, sort, drop_duplicates
524 )
526 meas_gdf = meas_gdf.set_index("bro_id")
527 measurement_objects = []
528 if zipfile is None:
529 desc = f"Downloading {kind}-observations"
530 else:
531 desc = f"Reading {kind}-observations from {zipfile.filename}"
532 if as_csv and kind != "gld":
533 raise (ValueError("as_csv=True is only supported for kind=='gld'"))
534 if qualifier is not None and kind != "gld":
535 raise (ValueError("A qualifier is only supported for kind=='gld'"))
536 datcol = gmw._get_data_column(kind)
537 for bro_id in util.tqdm(meas_gdf.index, disable=silent, desc=desc):
538 obsdata = gmw._download_observations_for_bro_id(
539 bro_id,
540 meas_cl,
541 as_csv,
542 zipfile,
543 to_path,
544 _files,
545 gld_kwargs,
546 redownload=redownload,
547 continue_on_error=continue_on_error,
548 )
550 if as_csv:
551 meas_dict = {"broId": bro_id, datcol: obsdata}
552 else:
553 meas_dict = obsdata.to_dict()
554 meas_dict["gm_gmw_monitoringtube_fk"] = meas_gdf.at[
555 bro_id, "gm_gmw_monitoringtube_fk"
556 ]
557 measurement_objects.append(meas_dict)
559 if progress_callback is not None:
560 progress_callback(len(measurement_objects), len(meas_gdf.index))
561 if len(measurement_objects) == 0:
562 return None
563 obs_df = pd.DataFrame(measurement_objects).set_index("broId")
565 if as_csv and tubes is not None:
566 # obs_df does not contain the gmw-id or the tube-number
567 # so we need to add these columns to the dataframe
568 tube_pk = tubes.reset_index().set_index("gm_gmw_monitoringtube_pk")
569 fk = obs_df["gm_gmw_monitoringtube_fk"].values
570 obs_df["groundwaterMonitoringWell"] = tube_pk["gmw_bro_id"].loc[fk].values
571 obs_df["tubeNumber"] = tube_pk["tube_number"].loc[fk].values
572 return obs_df
575def get_kenset_geopackage(to_file=None, layer=None, redownload=False, index="bro_id"):
576 """
577 Download or read data from a geopackage-file for the whole of the Netherlands.
579 Parameters
580 ----------
581 to_file : str, optional
582 Path to save the downloaded GeoPackage file (with the extension `.gpkg`). If the
583 file exists and `redownload` is False, it will be reused. The default is None.
584 layer : str, optional
585 The layer within the geopackage. Possible values are 'gm_gmw',
586 'gm_gmw_monitoringtube', 'gm_gld', 'gm_gar', 'gm_gmn', 'gm_gmn_measuringpoint'
587 and 'gm_gmn_reference'. The default is None, which reads data from the layer
588 "gm_gmw", and displays a warning that shows the available layers.
589 redownload : bool, optional
590 If True, forces redownload of the data even if `to_file` exists. The default is
591 False.
592 index : str, optional
593 The column to use for indexing in the resulting GeoDataFrame. The default is
594 "bro_id".
596 Returns
597 -------
598 gdf : gpd.GeoDataFrame
599 A GeoDataFrame containing the resulting objects.
601 """
602 url = "https://service.pdok.nl/bzk/bro-gminsamenhang-karakteristieken/atom/downloads/brogmkenset.gpkg"
603 if to_file is not None:
604 if redownload or not os.path.isfile(to_file):
605 urllib.request.urlretrieve(url, to_file)
606 url = to_file
607 gdf = gpd.read_file(url, layer=layer, fid_as_index=True)
608 if index in gdf.columns:
609 gdf = gdf.set_index(index)
610 return gdf