Coverage for brodata/bro.py: 79%
604 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 logging
2import os
3import types
4from abc import ABC, abstractmethod
5from io import StringIO
6from xml.etree import ElementTree
7from zipfile import ZipFile
9import geopandas as gpd
10import numpy as np
11import pandas as pd
12import requests
13import shapely
14from pyproj import Transformer
15from shapely.geometry import MultiPolygon, Point, Polygon
17from . import gml, util
19logger = logging.getLogger(__name__)
22# %%
23def _get_bro_ids_of_bronhouder(cl, bronhouder):
24 """
25 Retrieve list of BRO (Basisregistratie Ondergrond) IDs for a given bronhouder.
27 This function sends a GET request to the REST API to fetch the BRO IDs associated
28 with the specified bronhouder. If the request is unsuccessful, it logs an error
29 message.
31 Parameters
32 ----------
33 bronhouder : str
34 The identifier for the bronhouder to retrieve the associated BRO IDs.
36 Returns
37 -------
38 list or None
39 A list of BRO IDs if the request is successful. Returns `None` if the request
40 fails.
41 """
42 url = f"{cl._rest_url}/bro-ids?"
43 params = {"bronhouder": bronhouder}
44 req = util.get_with_rate_limit(url, params=params)
45 if req.status_code > 200:
46 logger.error(req.json()["errors"][0]["message"])
47 return
48 bro_ids = req.json()["broIds"]
49 return bro_ids
52def _get_characteristics(
53 cl,
54 extent=None,
55 tmin=None,
56 tmax=None,
57 x=None,
58 y=None,
59 radius=1000.0,
60 epsg=28992,
61 to_file=None,
62 redownload=False,
63 use_all_corners_of_extent=True,
64 timeout=5,
65 zipfile=None,
66):
67 """
68 Get characteristics of a set of registered objects for a given object class.
70 The maximum number of objects that can be retrieved is 2000 for a single request.
72 Parameters
73 ----------
74 extent : list, tuple, shapely.geometry.Polygon or shapely.geometry.MultiPolygon, optional
75 Download the characteristics within extent ([xmin, xmax, ymin, ymax]) or
76 within the bounds of a polygon. The default is None.
77 tmin : str or pd.Timestamp, optional
78 The minimum registrationPeriod of the requested characteristics. The default is
79 None.
80 tmax : str or pd.Timestamp, optional
81 The maximum registrationPeriod of the requested characteristics. The default is
82 None.
83 x : float, optional
84 The x-coordinate of the center of the circle in which the characteristics are
85 requested. The default is None.
86 y : float, optional
87 The y-coordinate of the center of the circle in which the characteristics are
88 requested. The default is None.
89 radius : float, optional
90 The radius in meters of the center of the circle in which the characteristics
91 are requested. The default is 1000.0.
92 epsg : str, optional
93 The coordinate reference system of the specified extent, x or y, and of the
94 resulting GeoDataFrame. The default is 28992, which is the Dutch RD-system.
95 to_file : str, optional
96 When not None, save the characteristics to a file with a name as specified in
97 to_file. The defaults None.
98 redownload : bool, optional
99 When the downloaded file exists in to_file, read from this file when redownload
100 is False. If redownload is True, download the data again from the BRO-servers.
101 The default is False.
102 use_all_corners_of_extent : bool, optional
103 Because the extent by default is given in epsg 28992, some locations along the
104 border of a requested extent will not be returned in the result. To solve this
105 issue, when use_all_corners_of_extent is True, all four corners of the extent
106 are used to calculate the minimum and maximum lan and lon values. The default is
107 True.
108 timeout : int or float, optional
109 A number indicating how many seconds to wait for the client to make a connection
110 and/or send a response. The default is 5.
111 zipfile : zipfile.ZipFile, optional
112 A zipfile-object. When not None, zipfile is used to read previously downloaded
113 data from. The default is None.
115 Returns
116 -------
117 gpd.GeoDataFrame
118 A GeoDataFrame contraining the characteristics.
120 Notes
121 -----
122 Haalt de karakteristieken op van een set van registratie objecten, gegeven een
123 kenmerkenverzameling (kenset).
125 De karakteristieken geven een samenvatting van een object zodat een verdere selectie
126 gemaakt kan worden. Het past in een tweetrapsbenadering, waarbij de eerste stap
127 bestaat uit het ophalen van de karakteristieken en de 2e stap uit het ophalen van de
128 gewenste registratie objecten. Het resultaat van deze operatie is gemaximaliseerd op
129 2000.
130 """
131 if zipfile is None and (
132 redownload or to_file is None or not os.path.isfile(to_file)
133 ):
134 url = f"{cl._rest_url}/characteristics/searches?"
136 data = {}
137 if tmin is not None or tmax is not None:
138 data["registrationPeriod"] = {}
139 if tmin is not None:
140 beginDate = pd.to_datetime(tmin).strftime("%Y-%m-%d")
141 data["registrationPeriod"]["beginDate"] = beginDate
142 if tmax is not None:
143 endDate = pd.to_datetime(tmax).strftime("%Y-%m-%d")
144 data["registrationPeriod"]["endDate"] = endDate
145 if (x is None or y is None) and extent is None:
146 raise (Exception("Please specify either extent or x, y and radius"))
148 transformer = Transformer.from_crs(epsg, 4326)
149 data["area"] = {}
150 if x is not None and y is not None:
151 lat, lon = transformer.transform(x, y)
152 data["area"]["enclosingCircle"] = {
153 "center": {"lat": lat, "lon": lon},
154 "radius": radius / 1000,
155 }
156 if extent is not None:
157 if isinstance(extent, (Polygon, MultiPolygon)):
158 xmin, ymin, xmax, ymax = extent.bounds
159 else:
160 xmin, xmax, ymin, ymax = extent
162 lat_ll, lon_ll = transformer.transform(xmin, ymin)
163 lat_ur, lon_ur = transformer.transform(xmax, ymax)
164 if use_all_corners_of_extent:
165 lat_ul, lon_ul = transformer.transform(xmin, ymax)
166 lat_lr, lon_lr = transformer.transform(xmax, ymin)
167 lat_ll = min(lat_ll, lat_lr)
168 lon_ll = min(lon_ll, lon_ul)
169 lat_ur = max(lat_ul, lat_ur)
170 lon_ur = max(lon_lr, lon_ur)
172 data["area"]["boundingBox"] = {
173 "lowerCorner": {"lat": lat_ll, "lon": lon_ll},
174 "upperCorner": {"lat": lat_ur, "lon": lon_ur},
175 }
176 req = util.post_with_rate_limit(url, json=data, timeout=timeout)
177 if req.status_code > 200:
178 root = ElementTree.fromstring(req.text)
179 FileOrUrl._check_for_rejection(root)
180 # if reading of the rejection message failed, raise a more general error
181 raise (Exception((f"Retieving data from {url} failed")))
183 if to_file is not None:
184 with open(to_file, "w") as f:
185 f.write(req.text)
187 # read results
188 tree = ElementTree.fromstring(req.text)
189 else:
190 if zipfile is not None:
191 with zipfile.open(to_file) as f:
192 tree = ElementTree.parse(f).getroot()
193 else:
194 tree = ElementTree.parse(to_file).getroot()
196 ns = {"xmlns": cl._xmlns}
197 data = []
198 for gmw in tree.findall(f".//xmlns:{cl._char}", ns):
199 d = {}
200 for key in gmw.attrib:
201 d[key.split("}", 1)[1]] = gmw.attrib[key]
202 for child in gmw:
203 key = util._get_tag(child)
204 if len(child) == 0:
205 d[key] = child.text
206 elif key == "standardizedLocation" or key == "deliveredLocation":
207 d[key] = FileOrUrl._read_geometry(child)
208 elif key.endswith(("Date", "Overview")) or key in ["startTime", "endTime"]:
209 d[key] = child[0].text
210 elif key in ["diameterRange", "screenPositionRange"]:
211 for grandchild in child:
212 key = util._get_tag(grandchild)
213 d[key] = grandchild.text
214 elif key == "licence":
215 for grandchild in child:
216 key2 = grandchild.tag.split("}", 1)[1]
217 for greatgrandchild in grandchild:
218 key3 = greatgrandchild.tag.split("}", 1)[1]
219 if key3 == "identificationLicence":
220 d[key] = greatgrandchild.text
221 else:
222 logger.warning(f"Unknown key: {key2}")
223 elif key == "realisedInstallation":
224 for grandchild in child:
225 key2 = grandchild.tag.split("}", 1)[1]
226 for greatgrandchild in grandchild:
227 key3 = greatgrandchild.tag.split("}", 1)[1]
228 if key3 == "installationFunction":
229 d[key] = greatgrandchild.text
230 else:
231 logger.warning(f"Unknown key: {key2}")
233 else:
234 logger.warning(f"Unknown key: {key}")
235 data.append(d)
237 gdf = objects_to_gdf(data)
238 if zipfile is not None and extent is not None and isinstance(gdf, gpd.GeoDataFrame):
239 if isinstance(extent, (Polygon, MultiPolygon)):
240 gdf = gdf[gdf.intersects(extent)]
241 else:
242 gdf = gdf.cx[extent[0] : extent[1], extent[2] : extent[3]]
243 return gdf
246def _get_data_in_extent(
247 bro_cl,
248 extent=None,
249 timeout=5,
250 silent=False,
251 to_path=None,
252 to_zip=None,
253 redownload=False,
254 geometry=None,
255 to_gdf=True,
256 index="broId",
257 continue_on_error=False,
258 progress_callback=None,
259):
260 """
261 Retrieve data within a specified extent for a certain bro-class.
263 Parameters
264 ----------
265 bro_cl : class
266 brodata class.
267 extent : str or object, optional
268 Spatial extent to query. If a string, interpreted as a zip file path.
269 timeout : int, default=5
270 Timeout in seconds for data retrieval requests.
271 silent : bool, default=False
272 If True, disables progress bars and reduces logging output.
273 to_path : str, optional
274 Directory path to save downloaded files.
275 to_zip : str, optional
276 Path to a zip file to read from or save data to.
277 redownload : bool, default=False
278 If True, forces redownload of data even if files exist.
279 geometry : str or object, optional
280 Geometry specification for the output GeoDataFrame.
281 to_gdf : bool, default=True
282 If True, converts the output to a GeoDataFrame.
283 index : str, default="broId"
284 Column name to use as index in the output GeoDataFrame.
285 continue_on_error : bool, default=False
286 If True, continues processing other items if an error occurs.
287 progress_callback : function, optional
288 A callback function that takes two arguments (current, total) to report
289 progress. If None, no progress reporting is done. Defaults to None.
291 Returns
292 -------
293 gdf : GeoDataFrame
294 GeoDataFrame containing the retrieved data objects, indexed by the specified
295 column.
297 Raises
298 ------
299 Exception
300 If invalid arguments are provided or data retrieval fails (unless
301 continue_on_error is True).
303 Notes
304 -----
305 - If `extent` is a string, it is treated as a zip file path and `to_zip` must not
306 be provided.
307 - Data can be read from or saved to zip archives or directories, depending on the
308 provided arguments.
309 - Progress is displayed unless `silent` is True.
310 """
311 if isinstance(extent, str):
312 if to_zip is not None:
313 raise (Exception("When extent is a string, do not supply to_zip"))
314 to_zip = extent
315 extent = None
316 redownload = False
317 zipfile = None
318 _files = None
319 if to_zip is not None:
320 if not redownload and os.path.isfile(to_zip):
321 logger.info(f"Reading data from {to_zip}")
322 zipfile = ZipFile(to_zip)
323 else:
324 if to_path is None:
325 to_path = os.path.splitext(to_zip)[0]
326 remove_path_again = not os.path.isdir(to_path)
327 _files = []
329 # get gwm characteristics
330 logger.info(f"Getting characteristics in extent: {extent}")
331 to_file = None
332 if zipfile is not None or to_path is not None:
333 to_file = "characteristics.xml"
334 if zipfile is None:
335 to_file = os.path.join(to_path, to_file)
336 if _files is not None:
337 _files.append(to_file)
338 if to_path is not None and not os.path.isdir(to_path):
339 os.makedirs(to_path)
341 char = _get_characteristics(
342 bro_cl, extent=extent, to_file=to_file, redownload=redownload, zipfile=zipfile
343 )
345 data = _get_data_for_bro_ids(
346 bro_cl,
347 char.index,
348 timeout=timeout,
349 silent=silent,
350 to_path=to_path,
351 zipfile=zipfile,
352 redownload=redownload,
353 continue_on_error=continue_on_error,
354 progress_callback=progress_callback,
355 _files=_files,
356 )
357 if zipfile is not None:
358 zipfile.close()
359 if zipfile is None and to_zip is not None:
360 util._save_data_to_zip(to_zip, _files, remove_path_again, to_path)
362 gdf = objects_to_gdf(data, geometry, to_gdf, index)
364 return gdf
367def _get_data_for_bro_ids(
368 bro_cl,
369 bro_ids,
370 timeout=5,
371 silent=False,
372 to_path=None,
373 zipfile=None,
374 redownload=False,
375 continue_on_error=False,
376 desc=None,
377 progress_callback=None,
378 _files=None,
379):
380 """
381 Retrieve data for a list of specified bro_ids for a certain bro-class.
383 Parameters
384 ----------
385 bro_cl : class
386 brodata class.
387 bro_ids : list of strings
388 A list of bro-ids to donnload data for.
389 timeout : int, default=5
390 Timeout in seconds for data retrieval requests.
391 silent : bool, default=False
392 If True, disables progress bars and reduces logging output.
393 to_path : str, optional
394 Directory path to save downloaded files.
395 zipfile : zipfile.ZipFile, optional
396 A zipfile-object. When not None, zipfile is used to read previously downloaded
397 data from. The default is None.
398 redownload : bool, default=False
399 If True, forces redownload of data even if files exist.
400 continue_on_error : bool, default=False
401 If True, continues processing other items if an error occurs.
402 desc : str, optional
403 Description for the progress bar. The default is None.
404 progress_callback : function, optional
405 A callback function that takes two arguments (current, total) to report
406 progress. If None, no progress reporting is done. Defaults to None.
408 Returns
409 -------
410 data : dictionary
411 A dictionary with the bro-ids as keys, and the data as values.
413 Raises
414 ------
415 Exception
416 If invalid arguments are provided or data retrieval fails (unless
417 continue_on_error is True).
419 Notes
420 -----
421 - Data can be read from or saved to zip archives or directories, depending on the
422 provided arguments.
423 - Progress is displayed unless `silent` is True.
424 """
425 data = {}
426 if isinstance(bro_ids, str):
427 bro_ids = [bro_ids]
428 total = len(bro_ids)
429 for i, bro_id in util.tqdm(
430 enumerate(bro_ids), total=total, disable=silent, desc=desc
431 ):
432 if progress_callback is not None:
433 progress_callback(i, total)
434 if zipfile is not None:
435 fname = f"{bro_id}.xml"
436 data[bro_id] = bro_cl(fname, zipfile=zipfile)
437 continue
438 to_file = None
439 if to_path is not None:
440 to_file = os.path.join(to_path, f"{bro_id}.xml")
441 if _files is not None:
442 _files.append(to_file)
443 if not redownload and os.path.isfile(to_file):
444 data[bro_id] = bro_cl(to_file)
445 continue
446 kwargs = {"to_file": to_file, "timeout": timeout}
447 if continue_on_error:
448 try:
449 data[bro_id] = bro_cl.from_bro_id(bro_id, **kwargs)
450 except Exception as e:
451 logger.error("Error retrieving %s: %s", bro_id, e)
452 else:
453 data[bro_id] = bro_cl.from_bro_id(bro_id, **kwargs)
455 return data
458def objects_to_gdf(
459 data,
460 geometry=None,
461 to_gdf=True,
462 index="broId",
463 from_crs=None,
464 to_crs=28992,
465):
466 if not to_gdf:
467 return data
468 if isinstance(data, list):
469 df = pd.DataFrame(data)
470 else:
471 df = pd.DataFrame([data[key].to_dict() for key in data])
473 if index is not None and not df.empty:
474 if isinstance(index, str):
475 if index in df.columns:
476 df = df.set_index(index)
477 elif np.all([x in df.columns for x in index]):
478 # we assume index is an iterable (list), to form a MultiIndex
479 df = df.set_index(index)
480 if geometry is None:
481 if "deliveredLocation" in df:
482 geometry = "deliveredLocation"
483 if from_crs is None:
484 from_crs = 28992
485 elif "standardizedLocation" in df:
486 geometry = "standardizedLocation"
487 if from_crs is None:
488 from_crs = 4258
489 else:
490 return df
491 gdf = gpd.GeoDataFrame(df, geometry=geometry, crs=from_crs)
492 if to_crs is not None and from_crs is not None and to_crs != from_crs:
493 gdf = gdf.to_crs(to_crs)
494 return gdf
497class FileOrUrl(ABC):
498 """
499 A class for parsing and handling XML data from files, URLs, or zipped files.
501 Supports fetching XML data from local files or remote URLs. It also handles
502 rejection checks and extracts data into object attributes. Data is parsed
503 recursively and can be converted to a dictionary.
505 Attributes:
506 Instance variables are dynamically set based on the XML content.
508 Methods:
509 __init__(url_or_file, zipfile=None, timeout=5, to_file=None, **kwargs):
510 Parses XML from a URL, file, or zipped file, and initializes the object.
512 from_bro_id(bro_id, **kwargs):
513 Fetches XML data from a REST service based on a given 'bro_id'.
515 to_dict():
516 Converts instance attributes to a dictionary, excluding methods and
517 private attributes.
518 """
520 def __init__(
521 self,
522 url_or_file,
523 zipfile=None,
524 timeout=5,
525 to_file=None,
526 redownload=True,
527 max_retries=2,
528 **kwargs,
529 ):
530 # CSV
531 if url_or_file.endswith(".csv"):
532 if zipfile is not None:
533 self._read_csv(StringIO(zipfile.read(url_or_file)), **kwargs)
534 else:
535 self._read_csv(url_or_file, **kwargs)
536 # XML or URL
537 else:
538 if zipfile is not None:
539 root = ElementTree.fromstring(zipfile.read(url_or_file))
540 elif url_or_file.startswith("http"):
541 if redownload or to_file is None or not os.path.isfile(to_file):
542 params = {}
543 if "tmin" in kwargs and kwargs["tmin"] is not None:
544 tmin = kwargs.pop("tmin")
545 tmin = pd.to_datetime(tmin).strftime("%Y-%m-%d")
546 params["observationPeriodBeginDate"] = tmin
547 if "tmax" in kwargs and kwargs["tmax"] is not None:
548 tmax = kwargs.pop("tmax")
549 tmax = pd.to_datetime(tmax).strftime("%Y-%m-%d")
550 params["observationPeriodEndDate"] = tmax
551 if max_retries > 1:
552 adapter = requests.adapters.HTTPAdapter(max_retries=max_retries)
553 session = requests.Session()
554 session.mount("https://", adapter)
555 util.wait_for_rate_limit(url_or_file)
556 req = session.get(url_or_file, params=params, timeout=timeout)
557 else:
558 req = util.get_with_rate_limit(
559 url_or_file, params=params, timeout=timeout
560 )
561 if not req.ok:
562 if req.reason == "Bad Request":
563 root = ElementTree.fromstring(req.text)
564 FileOrUrl._check_for_rejection(root)
565 raise Exception(f"Retrieving data from {url_or_file} failed")
566 if to_file is not None:
567 with open(to_file, "w") as f:
568 f.write(req.text)
569 root = ElementTree.fromstring(req.text)
570 FileOrUrl._check_for_rejection(root)
571 else:
572 tree = ElementTree.parse(to_file)
573 root = tree.getroot()
574 else:
575 tree = ElementTree.parse(url_or_file)
576 root = tree.getroot()
578 self._read_contents(root, **kwargs)
580 def __repr__(self):
581 # retrieve properties if they exist
582 propdict = {"broId": "broId"}
583 props = {}
584 for key in propdict:
585 if hasattr(self, key):
586 props[propdict[key]] = getattr(self, key)
587 if hasattr(self, "deliveredLocation"):
588 if isinstance(self.deliveredLocation, Point):
589 props["x"] = self.deliveredLocation.x
590 props["y"] = self.deliveredLocation.y
591 name = util._format_repr(self, props)
592 return name
594 @abstractmethod
595 def _read_contents(self, tree, **kwargs):
596 """Each subclass must overload _read_contents to parse XML result."""
598 def _read_csv(self, *args, **kwargs):
599 raise NotImplementedError(
600 f"Class {self.__class__.__name__} does not support reading from CSV files."
601 )
603 @classmethod
604 def from_bro_id(cls, bro_id, **kwargs):
605 if not hasattr(cls, "_rest_url"):
606 raise (NotImplementedError(f"No rest-service defined for {cls.__name__}"))
608 return cls(f"{cls._rest_url}/objects/{bro_id}", **kwargs)
610 def to_dict(self):
611 d = {}
612 for attrib in dir(self):
613 if attrib.startswith("_"):
614 continue
615 value = getattr(self, attrib)
616 if type(value) is types.MethodType:
617 continue
618 d[attrib] = value
619 return d
621 @staticmethod
622 def _check_for_rejection(tree):
623 ns = {"brocom": "http://www.broservices.nl/xsd/brocommon/3"}
624 response_type = tree.find("brocom:responseType", ns)
625 if response_type is not None and response_type.text == "rejection":
626 criterionError = tree.find("brocom:criterionError", ns)
627 if criterionError is None:
628 rejection_reason = tree.find("brocom:rejectionReason", ns)
629 if rejection_reason is None:
630 msg = "Unknown rejection reason"
631 else:
632 msg = rejection_reason.text
633 else:
634 specification = criterionError.find("brocom:specification", ns)
635 if specification is None:
636 msg = "Unknown specification"
637 else:
638 msg = specification.text
639 raise (ValueError(msg))
641 @staticmethod
642 def _get_tag(node):
643 return util._get_tag(node)
645 def _get_main_object(self, tree, object_name=None, ns=None):
646 if object_name is None:
647 object_name = self._object_name
648 if ns is None:
649 ns = {"xmlns": self._xmlns}
650 if isinstance(object_name, list):
651 for name in object_name:
652 objects = tree.findall(f".//xmlns:{name}", ns)
653 if objects:
654 break
655 else:
656 objects = tree.findall(f".//xmlns:{object_name}", ns)
657 if len(objects) > 1:
658 raise (Exception(f"Only one {object_name} supported"))
659 elif len(objects) == 0:
660 raise (Exception(f"No {object_name} found"))
661 return objects[0]
663 def _warn_unknown_tag(self, tag, parent=None):
664 class_name = self.__class__.__name__
665 bro_id = getattr(self, "broId", "")
666 util._warn_unknown_tag(tag, parent, class_name, bro_id)
668 def _raise_assumed_single(self, key):
669 raise ValueError(
670 f"Assumed there is only one {key} in {self.__class__.__name__} {getattr(self, 'broId', '')}"
671 )
673 def _check_single_child_with_tag(self, node, tag):
674 return len(node) == 1 and self._get_tag(node[0]) == tag
676 def _read_children_of_children(self, node, d=None, to_float=None, to_int=None):
677 if to_float is not None and isinstance(to_float, str):
678 to_float = [to_float]
679 if to_int is not None and isinstance(to_int, str):
680 to_int = [to_int]
681 if len(node) == 0:
682 key = node.tag.split("}", 1)[1]
683 if d is None:
684 setattr(self, key, FileOrUrl._parse_text(node, key, to_float, to_int))
685 else:
686 d[key] = FileOrUrl._parse_text(node, key, to_float, to_int)
687 else:
688 for child in node:
689 self._read_children_of_children(
690 child, d=d, to_float=to_float, to_int=to_int
691 )
693 @staticmethod
694 def _parse_text(node, key, to_float=None, to_int=None):
695 if to_float is not None and key in to_float:
696 return FileOrUrl._parse_float(node)
697 if to_int is not None and key in to_int:
698 return int(node.text)
699 return node.text
701 @staticmethod
702 def _parse_float(node):
703 if node.text is None:
704 return np.nan
705 return float(node.text)
707 def _read_delivered_location(self, node):
708 for child in node:
709 key = self._get_tag(child)
710 if key == "location":
711 setattr(self, "deliveredLocation", self._read_geometry(child))
712 elif key == "horizontalPositioningDate":
713 setattr(self, key, self._read_date(child))
714 elif key == "horizontalPositioningMethod":
715 setattr(self, key, child.text)
716 elif key == "horizontalPositioningOperator":
717 setattr(self, key, self._read_operator(child))
718 else:
719 self._warn_unknown_tag(key)
721 def _read_operator(self, node):
722 d = {}
723 for child in node:
724 key = self._get_tag(child)
725 if key in [
726 "chamberOfCommerceNumber",
727 "europeanCompanyRegistrationNumber",
728 ]:
729 d[key] = child.text
730 else:
731 self._warn_unknown_tag(key)
732 return d
734 def _read_standardized_location(self, node):
735 for child in node:
736 key = self._get_tag(child)
737 if key == "location":
738 setattr(self, "standardizedLocation", self._read_geometry(child))
739 elif key == "coordinateTransformation":
740 setattr(self, key, child.text)
741 else:
742 self._warn_unknown_tag(key)
744 def _read_delivered_vertical_position(self, node, d=None):
745 for child in node:
746 key = self._get_tag(child)
747 if key == "verticalPositioningDate":
748 value = self._read_date(child)
749 elif key == "offset":
750 if child.text is None:
751 value = np.nan
752 else:
753 value = float(child.text)
754 elif key == "verticalPositioningOperator":
755 value = self._read_operator(child)
756 else:
757 value = child.text
759 if d is None:
760 setattr(self, key, value)
761 else:
762 d[key] = value
764 def _read_lifespan(self, node, d=None):
765 for child in node:
766 key = self._get_tag(child)
767 if key in ["startDate", "startTime", "endTime"]:
768 if d is None:
769 setattr(self, key, self._read_date(child))
770 else:
771 d[key] = self._read_date(child)
772 else:
773 self._warn_unknown_tag(key)
775 def _read_validity_period(self, node, d=None):
776 for child in node:
777 key = self._get_tag(child)
778 if key in ["startValidity", "endValidity"]:
779 if d is None:
780 setattr(self, key, self._read_date(child))
781 else:
782 d[key] = self._read_date(child)
783 else:
784 self._warn_unknown_tag(key)
786 @staticmethod
787 def _read_geometry(node):
788 assert len(node) == 1
789 tag = node[0].tag.split("}")[-1]
790 if tag == "pos":
791 x, y = tuple(map(float, node[0].text.strip().split()))
792 if FileOrUrl._is_epsg_4258(node):
793 x, y = y, x
794 return Point(x, y)
795 geometry = gml.parse_geometry(node[0])
796 if FileOrUrl._is_epsg_4258(node[0]):
797 geometry = shapely.transform(
798 geometry, lambda x, y: (y, x), interleaved=False
799 )
800 return geometry
802 @staticmethod
803 def _is_epsg_4258(node):
804 srsName = "urn:ogc:def:crs:EPSG::4258"
805 return "srsName" in node.attrib and node.attrib["srsName"] == srsName
807 @staticmethod
808 def _read_date(node):
809 ns = {"brocom": "http://www.broservices.nl/xsd/brocommon/3.0"}
810 date = node.find("brocom:date", ns)
811 if date is None:
812 date = node.find("brocom:yearMonth", ns)
813 if date is None:
814 date = node.find("brocom:year", ns)
815 if date is None:
816 return pd.NaT
817 return pd.to_datetime(date.text)
819 @staticmethod
820 def _read_time_instant(node):
821 ns = {"gml": "http://www.opengis.net/gml/3.2"}
822 time_instant = node.find("gml:TimeInstant", ns)
823 time_position = time_instant.find("gml:timePosition", ns)
824 return pd.to_datetime(time_position.text)
826 def _read_data_array(self, node):
827 values = None
828 for child in node:
829 key = self._get_tag(child)
830 if key == "encoding":
831 ns = {"swe": "http://www.opengis.net/swe/2.0"}
832 text_encoding = child.find("swe:TextEncoding", ns)
833 encoding = text_encoding.attrib.copy()
834 elif key in ["elementCount", "elementType"]:
835 pass
836 elif key == "values":
837 values = pd.read_csv(
838 StringIO(child.text),
839 header=None,
840 decimal=encoding["decimalSeparator"],
841 sep=encoding["tokenSeparator"],
842 lineterminator=encoding["blockSeparator"],
843 na_values=-999999,
844 )
845 else:
846 self._warn_unknown_tag(key)
847 return values
849 def _read_descriptive_borehole_log(self, node):
850 d = {}
851 for child in node:
852 key = self._get_tag(child)
853 if key in [
854 "descriptionQuality",
855 "describedSamplesQuality",
856 "continuouslySampled",
857 "descriptionLocation",
858 "describedMaterial",
859 "sampleMoistness",
860 "boreholeLogChecked",
861 ]:
862 d[key] = child.text
863 elif key == "layer":
864 if key not in d:
865 d[key] = []
866 if self._check_single_child_with_tag(child, "Layer"):
867 child = child[0]
868 layer = {}
869 for grandchild in child:
870 key2 = self._get_tag(grandchild)
871 if key2 in ["upperBoundary", "lowerBoundary"]:
872 layer[key2] = self._parse_float(grandchild)
873 elif key2 in [
874 "upperBoundaryDetermination",
875 "lowerBoundaryDetermination",
876 "anthropogenic",
877 "activityType",
878 "specialMaterial",
879 "slant",
880 "internalStructureIntact",
881 "bedded",
882 "compositeLayer",
883 "bedding",
884 "rooted",
885 "identification",
886 "structure",
887 ]:
888 layer[key2] = grandchild.text
889 elif key2 == "soil":
890 self._read_soil(grandchild, layer)
891 elif key2 == "rock":
892 self._read_rock(grandchild, layer)
893 elif key2 == "soilType":
894 for greatgrandchild in grandchild:
895 key2 = self._get_tag(greatgrandchild)
896 if key2 in ["soilName", "sandMedianClass"]:
897 layer[key2] = greatgrandchild.text
898 elif key2 == "particularConstituent":
899 for greatgrandchild in grandchild:
900 key2 = self._get_tag(greatgrandchild)
901 if key2 in ["ConstituentType"]:
902 layer[key2] = greatgrandchild.text
903 else:
904 self._warn_unknown_tag(key2)
905 d[key].append(layer)
906 else:
907 self._warn_unknown_tag(key)
908 if "layer" in d:
909 d["layer"] = pd.DataFrame(d["layer"])
910 return d
912 def _read_soil(self, node, d):
913 for child in node:
914 key = self._get_tag(child)
915 if key in [
916 "geotechnicalSoilName",
917 "soilNameNEN5104",
918 "gravelContentClassNEN5104",
919 "organicMatterContentClassNEN5104",
920 "colour",
921 "mottled",
922 "interbedding",
923 "carbonateContentClass",
924 "organicMatterContentClass",
925 "crossBedding",
926 "gradedBedding",
927 "mixed",
928 "mixingType",
929 "gravelMedianClass",
930 "fineGravelContentClass",
931 "mediumCoarseGravelContentClass",
932 "veryCoarseGravelContentClass",
933 "sandMedianClass",
934 "sandSortingNEN5104",
935 "peatType",
936 "organicSoilTexture",
937 "fineSoilConsistency",
938 "organicSoilConsistency",
939 "peatTensileStrength",
940 "geotechnicalDepositionalCharacteristic",
941 "depositionalAge",
942 "classificationLoamBased",
943 "pedologicalSoilName",
944 "structureType",
945 "estimatedDensity",
946 "ripeningClass",
947 "vertic",
948 "containsShellMatter",
949 "containsGravel",
950 "gravelContentClass",
951 "chunk",
952 "moistness",
953 "shellMatterContentClassArchive",
954 ]:
955 d[key] = child.text
956 elif key in ["estimatedOrganicMatterContent", "estimatedClayContent"]:
957 d[key] = float(child.text)
958 elif key in ["tertiaryConstituent", "dispersedInhomogeneity"]:
959 if key not in d:
960 d[key] = []
961 d[key].append(child.text)
962 elif key == "grainshape":
963 for grandchild in child:
964 key = self._get_tag(grandchild)
965 if key in ["sizeFraction", "angularity", "sphericity"]:
966 d[key] = grandchild.text
967 else:
968 self._warn_unknown_tag(key)
969 elif key == "incompleteFractionSpecification":
970 for grandchild in child:
971 key = self._get_tag(grandchild)
972 if key in ["estimatedOrganicMatterContent", "estimatedClayContent"]:
973 d[key] = float(grandchild.text)
974 else:
975 self._warn_unknown_tag(key)
976 elif key == "stain":
977 for grandchild in child:
978 key = self._get_tag(grandchild)
979 if key in ["stainColour", "mottlingDensity", "evenlyMottled"]:
980 d[key] = grandchild.text
981 else:
982 self._warn_unknown_tag(key)
983 elif key == "soilAggregate":
984 for grandchild in child:
985 key = self._get_tag(grandchild)
986 if key in [
987 "aggregateShape",
988 "angularity",
989 "roughness",
990 "aggregateLengthClass",
991 "poreAbundanceClass",
992 "horizontallyAligned",
993 "disintegrating",
994 ]:
995 d[key] = grandchild.text
996 else:
997 self._warn_unknown_tag(key)
998 elif key == "fractionDistribution":
999 for grandchild in child:
1000 key = self._get_tag(grandchild)
1001 if key in [
1002 "estimatedGravelContent",
1003 "estimatedShellMatterContent",
1004 "estimatedOrganicMatterContent",
1005 "estimatedFineFractionContent",
1006 ]:
1007 d[key] = float(grandchild.text)
1008 elif key == "fineFractionDistribution":
1009 for greatgrandchild in grandchild:
1010 key = self._get_tag(greatgrandchild)
1011 if key in [
1012 "estimatedClayContent",
1013 "estimatedSiltContent",
1014 "estimatedSandContent",
1015 ]:
1016 d[key] = float(greatgrandchild.text)
1017 else:
1018 self._warn_unknown_tag(key)
1019 else:
1020 self._warn_unknown_tag(key)
1021 elif key == "munsellColour":
1022 for grandchild in child:
1023 key = self._get_tag(grandchild)
1024 if key in ["munsellHue", "munsellValue", "munsellChroma"]:
1025 d[key] = grandchild.text
1026 else:
1027 self._warn_unknown_tag(key)
1028 elif key == "sandFraction":
1029 for grandchild in child:
1030 key = self._get_tag(grandchild)
1031 if key in ["sandMedianClass", "sandSorting"]:
1032 d[key] = grandchild.text
1033 else:
1034 self._warn_unknown_tag(key)
1035 elif key == "peatFraction":
1036 for grandchild in child:
1037 key = self._get_tag(grandchild)
1038 if key == "peatConstituent":
1039 for greatgrandchild in grandchild:
1040 key = self._get_tag(greatgrandchild)
1041 if key in ["plantRemainType", "archiveClass"]:
1042 d[key] = greatgrandchild.text
1043 else:
1044 self._warn_unknown_tag(key)
1045 else:
1046 self._warn_unknown_tag(key)
1047 else:
1048 self._warn_unknown_tag(key)
1050 def _read_rock(self, node, d):
1051 for child in node:
1052 key = self._get_tag(child)
1053 if key in [
1054 "rockType",
1055 "cementType",
1056 "colour",
1057 "carbonateContentClass",
1058 "crossBedding",
1059 "gradedBedding",
1060 "voidsPresent",
1061 "voidDistribution",
1062 "stability",
1063 "strengthClass",
1064 "weathered",
1065 ]:
1066 d[key] = child.text
1067 elif key in ["tertiaryRockConstituent", "dispersedInhomogeneity"]:
1068 if key not in d:
1069 d[key] = []
1070 d[key].append(child.text)
1071 elif key == "weatheringDegree":
1072 for grandchild in child:
1073 key = self._get_tag(grandchild)
1074 if key in ["discolouration", "disintegration", "decomposition"]:
1075 d[key] = grandchild.text
1076 else:
1077 self._warn_unknown_tag(key)
1078 else:
1079 self._warn_unknown_tag(key)
1082def get_bronhouders(index="kvk", **kwargs):
1083 """
1084 Get the name, kvk-number and the identifier of bronhouders (data owners).
1086 Parameters
1087 ----------
1088 index : string, optional
1089 The column to set as the index of the resulting DataFrame. The default is "kvk".
1090 **kwargs : dict
1091 Kwargs are passed onto pandas.read_json().
1093 Returns
1094 -------
1095 df : pd.DataFrame
1096 A Pandas DataFrame, with one row per bronhouder.
1098 """
1099 url = "https://bromonitor.nl/api/rapporten/bronhouders"
1100 df = pd.read_json(url, **kwargs)
1101 if index is not None:
1102 df = df.set_index(index)
1103 return df
1106def get_brondocumenten_per_bronhouder(index=("kvk", "type"), timeout=5, **kwargs):
1107 """
1108 Get the number of documents per bronhouder (data owner).
1110 Parameters
1111 ----------
1112 index : str, tuple or list, optional
1113 The column(s) to set as the index of the resulting DataFrame. The default is
1114 "kvk" and "type".
1115 timeout : int or float, optional
1116 A number indicating how many seconds to wait for the client to make a connection
1117 and/or send a response. The default is 5.
1118 **kwargs : dict
1119 Kwargs are passed onto pandas.DataFrame().
1121 Returns
1122 -------
1123 df : pd.DataFrame
1124 A Pandas DataFrame, with one row per combination of bronhouder and data-type.
1126 """
1127 url = "https://bromonitor.nl/api/rapporten/brondocumenten-per-bronhouder"
1128 r = util.get_with_rate_limit(url, timeout=timeout)
1129 if not r.ok:
1130 raise (Exception("Download of brondocumenten per bronhouder failed"))
1131 df = pd.DataFrame(r.json()["data"], **kwargs)
1132 if "key" in df.columns:
1133 df = pd.concat((pd.DataFrame(list(df["key"])), df.drop(columns="key")), axis=1)
1134 if index is not None:
1135 if isinstance(index, tuple):
1136 index = list(index)
1137 df = df.set_index(index)
1138 return df
1141def get_kvk_df(fn_bronhouder_kvk=None):
1142 """
1143 Read manually saved table of KVK and Organisatienaam to DataFrame.
1145 from https://basisregistratieondergrond.nl/service-contact/formulieren/aangemeld-bro/
1146 :param fn_bronhouder_kvk: str, filename of the file with bronhouder and kvk numbers
1147 :return: pandas DataFrame with kvk as index and column 'Organisatienaam' and 'Bronhouder'
1148 """
1149 if fn_bronhouder_kvk is None:
1150 fn_bronhouder_kvk = os.path.join(
1151 os.path.dirname(__file__), "data", "bronhouder_kvk.txt"
1152 )
1154 df_bron_kvk = pd.read_csv(
1155 fn_bronhouder_kvk,
1156 sep=";", # is a dummy value, data will be split later on the last | sign
1157 dtype=str,
1158 header=None,
1159 names=["all_data"],
1160 skipinitialspace=True,
1161 comment="#",
1162 )
1164 # split column all_data into bronhouder and kvk, using last | sign; both as string type
1165 # mind that index has string type, as that is format provided in brodata downloads
1166 df_bron_kvk[["Organisatienaam", "KVK-nummer"]] = (
1167 df_bron_kvk["all_data"].str.rsplit("|", n=1, expand=True).astype(str)
1168 )
1169 df_bron_kvk = df_bron_kvk.drop(columns=["all_data"])
1171 # add column Bronhouder, value is True when (B) in kvk
1172 df_bron_kvk["Bronhouder"] = False
1174 bronhouder_pattern = r"[(B)|(B)]"
1175 df_bron_kvk.loc[
1176 df_bron_kvk["KVK-nummer"].str.contains(bronhouder_pattern, regex=True),
1177 "Bronhouder",
1178 ] = True
1179 # clean up kvk
1180 df_bron_kvk["KVK-nummer"] = (
1181 df_bron_kvk["KVK-nummer"]
1182 .str.replace(bronhouder_pattern, "", regex=True)
1183 .str.strip()
1184 )
1186 # remove leading and trailing whitespace from all columns
1187 df_bron_kvk = df_bron_kvk.map(lambda x: x.strip() if isinstance(x, str) else x)
1189 # make kvk index
1190 df_bron_kvk = df_bron_kvk.set_index("KVK-nummer")
1192 return df_bron_kvk