Coverage for brodata/gld.py: 73%

270 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-06 14:37 +0000

1import csv 

2import logging 

3import time 

4from functools import partial 

5from io import StringIO 

6 

7import numpy as np 

8import pandas as pd 

9 

10from . import bro, util 

11 

12logger = logging.getLogger(__name__) 

13 

14 

15def get_objects_as_csv( 

16 bro_id, 

17 rapportagetype="volledig", 

18 observatietype=None, 

19 to_file=None, 

20 return_contents=True, 

21 **kwargs, 

22): 

23 """ 

24 Fetch a complete Groundwater Level Dossier (GLD) as a CSV (RFC 4180) file 

25 based on the provided BRO-ID. The data can be filtered by report type and 

26 observation type. 

27 

28 Parameters 

29 ---------- 

30 bro_id : str 

31 The BRO-ID of the Groundwater Level Dossier to fetch. It can also be a full url, 

32 which is used by the gm-services. When using a full url, the parameter 

33 `rapportagetype` needs to reflect the choice in the url, and the parameter 

34 `observatietype` is ignored. 

35 rapportagetype : str, optional 

36 Type of report. The valid values are: 

37 - "volledig" : Full report 

38 - "compact" : Compact report with readable timestamps 

39 - "compact_met_timestamps" : Compact report with Unix epoch timestamps 

40 Default is "volledig". 

41 observatietype : str, optional 

42 Type of observations. The valid values are: 

43 - "regulier_beoordeeld" : Regular measurement with full evaluation 

44 (observatietype = reguliere meting en mate beoordeling = volledig beoordeeld) 

45 - "regulier_voorlopig" : Regular measurement with preliminary evaluation 

46 (observatietype = reguliere meting en mate beoordeling = voorlopig) 

47 - "controle" : Control measurement 

48 (observatietype = controle meting) 

49 - "onbekend" : Unknown evaluation 

50 (observatietype = reguliere meting en mate beoordeling = onbekend) 

51 If None, all observation types will be returned. Default is None. 

52 to_file : str, optional 

53 If provided, the CSV data will be written to the specified file. 

54 If None, the function returns the CSV data as a DataFrame. Default is None. 

55 return_contents : bool, optional 

56 If True, the function returns the parsed CSV data as a DataFrame. If False, 

57 the function returns None after saving the CSV to the specified file (if 

58 `to_file` is provided). Default is True. 

59 **kwargs : additional keyword arguments 

60 Additional arguments passed to `read_gld_csv`. 

61 

62 Returns 

63 ------- 

64 pd.DataFrame or None 

65 If successful, returns a DataFrame containing the parsed CSV data. 

66 If `to_file` is provided, returns None after saving the CSV to the specified file. 

67 If the request fails or returns empty data, returns None. 

68 

69 Notes 

70 ----- 

71 The function sends a GET request to the Groundwater Level Dossier API 

72 and fetches the data in CSV format. The `rapportagetype` and `observatietype` 

73 parameters can be used to filter the data. 

74 """ 

75 if bro_id.startswith("http"): 

76 req = util.get_with_rate_limit(bro_id) 

77 else: 

78 url = f"{GroundwaterLevelDossier._rest_url}/objectsAsCsv/{bro_id}" 

79 params = { 

80 "rapportagetype": rapportagetype, 

81 } 

82 if observatietype is not None: 

83 params["observatietype"] = observatietype 

84 req = util.get_with_rate_limit(url, params=params) 

85 req = _check_request_status(req) 

86 if to_file is not None: 

87 with open(to_file, "w") as f: 

88 f.write(req.text) 

89 if not return_contents: 

90 return 

91 if req.text == "": 

92 return None 

93 else: 

94 df = read_gld_csv( 

95 StringIO(req.text), 

96 bro_id, 

97 rapportagetype=rapportagetype, 

98 observatietype=observatietype, 

99 **kwargs, 

100 ) 

101 return df 

102 

103 

104def _check_request_status(req): 

105 if req.status_code == 429: 

106 msg = "Too many requests. The BRO API has rate limits in place." 

107 logger.warning(msg) 

108 # try 3 times with increasing wait time 

109 wait_times = [1, 2, 4] 

110 for wait_time in wait_times: 

111 logger.warning(f"Waiting for {wait_time} seconds before retrying...") 

112 time.sleep(wait_time) 

113 req = util.get_with_rate_limit(req.url) 

114 if req.status_code <= 200: 

115 break 

116 if req.status_code == 429: 

117 raise Exception(msg + " Please try again later.") 

118 if req.status_code > 200: 

119 json_data = req.json() 

120 if "errors" in json_data: 

121 msg = json_data["errors"][0]["message"] 

122 else: 

123 msg = "{}: {}".format(json_data["title"], json_data["description"]) 

124 raise Exception(msg) 

125 return req 

126 

127 

128def get_series_as_csv( 

129 bro_id, filter_on_status_quality_control=None, asISO8601=False, to_file=None 

130): 

131 """ 

132 Get groundwater level series as a CSV, with timestamps and corresponding measurements. 

133 

134 This function retrieves a table with measurements for different observation types 

135 (regulier_voorlopig, regulier_beoordeeld, controle en onbekend) as columns. It is 

136 intended for applications such as the graphical visualization of groundwater levels. 

137 

138 Parameters 

139 ---------- 

140 bro_id : str 

141 The BRO-ID of the Groundwater Level Dossier. 

142 filter_on_status_quality_control : str or list of str, optional 

143 One or more quality control statuses to filter the measurements by. 

144 Possible values are 'onbeslist', 'goedgekeurd', and 'afgekeurd'. 

145 The default is None. 

146 asISO8601 : bool, optional 

147 If True, timestamps are returned in ISO8601 format; otherwise, in Unix 

148 epoch format. The default is False. 

149 to_file : str, optional 

150 If provided, the CSV data will be written to this file path. The default 

151 is None. 

152 

153 Returns 

154 ------- 

155 pd.DataFrame or None 

156 A DataFrame containing the time series of measurements, with timestamps 

157 as the index. Returns None if no data is available. 

158 """ 

159 url = f"{GroundwaterLevelDossier._rest_url}/seriesAsCsv/{bro_id}" 

160 params = {} 

161 if filter_on_status_quality_control is not None: 

162 if not isinstance(filter_on_status_quality_control, str): 

163 filter_on_status_quality_control = ",".join( 

164 filter_on_status_quality_control 

165 ) 

166 params["filterOnStatusQualityControl"] = filter_on_status_quality_control 

167 if asISO8601: 

168 params["asISO8601"] = "" 

169 req = util.get_with_rate_limit(url, params=params) 

170 req = _check_request_status(req) 

171 if to_file is not None: 

172 with open(to_file, "w") as f: 

173 f.write(req.text) 

174 if req.text == "": 

175 return None 

176 else: 

177 df = pd.read_csv(StringIO(req.text)) 

178 if "Tijdstip" in df.columns: 

179 if asISO8601: 

180 df["Tijdstip"] = pd.to_datetime(df["Tijdstip"]) 

181 else: 

182 df["Tijdstip"] = pd.to_datetime(df["Tijdstip"], unit="ms") 

183 df = df.set_index("Tijdstip") 

184 return df 

185 

186 

187def read_gld_csv( 

188 fname, bro_id="gld", rapportagetype="volledig", observatietype=None, **kwargs 

189): 

190 """ 

191 Read and process a Groundwater Level Dossier (GLD) CSV file. 

192 

193 This function reads a CSV file containing groundwater level observations, 

194 processes the data according to the specified report type (`rapportagetype`), 

195 and returns a DataFrame of the observations. The file is assumed to contain 

196 at least three columns: time, value, and qualifier. The 'time' column is parsed 

197 as datetime, and additional processing is applied to the data. 

198 

199 Parameters 

200 ---------- 

201 fname : str 

202 The path to the CSV file containing the groundwater level observations. 

203 bro_id : str 

204 The BRO-ID of the Groundwater Level Dossier being processed. Only used for 

205 logging-purposes. The default is "gld". 

206 rapportagetype : str, optional 

207 The report type. Can be one of: 

208 - 'volledig': as complete as possible 

209 - 'compact': simple format with time and value. 

210 - 'compact_met_timestamps': format with timestamps for each observation. 

211 Default is "volledig". 

212 observatietype : str, optional 

213 Type of observations. The valid values are: 

214 - "regulier_beoordeeld" : Regular measurement with full evaluation 

215 (observatietype = reguliere meting en mate beoordeling = volledig beoordeeld) 

216 - "regulier_voorlopig" : Regular measurement with preliminary evaluation 

217 (observatietype = reguliere meting en mate beoordeling = voorlopig) 

218 - "controle" : Control measurement 

219 (observatietype = controle meting) 

220 - "onbekend" : Unknown evaluation 

221 (observatietype = reguliere meting en mate beoordeling = onbekend) 

222 If None, all observation types will be returned. Default is None. 

223 **kwargs : additional keyword arguments 

224 Additional arguments passed to the `process_observations` function. 

225 

226 Returns 

227 ------- 

228 pd.DataFrame 

229 A DataFrame containing the processed observations with the following columns: 

230 - time: The observation time. 

231 - value: The observed groundwater level. 

232 - qualifier: The quality code of the observation. 

233 - censored_reason: Reason for censoring, if applicable. 

234 - censoring_limitvalue: Limit value for censoring, if applicable. 

235 - interpolation_type: The interpolation method used, if applicable. 

236 

237 Notes 

238 ----- 

239 The time column is parsed as a datetime index. If the report type is 

240 'compact_met_timestamps', the time values are converted from Unix epoch time 

241 (milliseconds) to a datetime format. 

242 """ 

243 names = [ 

244 "time", 

245 "value", 

246 "qualifier", 

247 "censored_reason", 

248 "censoring_limitvalue", 

249 "interpolation_type", 

250 ] 

251 if rapportagetype == "compact": 

252 parse_dates = ["time"] 

253 else: 

254 parse_dates = None 

255 if observatietype is None or rapportagetype == "volledig": 

256 # the csv contains multiple observation types, seperated by a header with 

257 # observation-type and status. 

258 if isinstance(fname, StringIO): 

259 lines = fname.readlines() 

260 else: 

261 with open(fname, "r") as f: 

262 lines = f.readlines() 

263 

264 # look for header lines 

265 headers = [] 

266 if rapportagetype == "volledig": 

267 # the line with metdata is proceeded by a line starting with "observatie ID" 

268 for i, line in enumerate(lines): 

269 if line.startswith('"observatie ID",'): 

270 headers.append(i + 1) 

271 header_length = 3 

272 else: 

273 # the line with metdata is proceeded by an empty line 

274 # but directly after the header, there can also be empty lines, that we skip 

275 data_lines = False 

276 for i, line in enumerate(lines): 

277 only_commas = all(c == "," for c in line.rstrip("\r\n")) 

278 last_line_was_header = len(headers) > 0 and headers[-1] == i - 1 

279 

280 if only_commas: 

281 if last_line_was_header: 

282 data_lines = True 

283 else: 

284 data_lines = False 

285 else: 

286 if not data_lines: 

287 headers.append(i) 

288 header_length = 2 

289 

290 rows = [] 

291 for i, header in enumerate(headers): 

292 line = lines[header] 

293 # split string by comma, but ignore commas between quotes 

294 reader = csv.reader(StringIO(line)) 

295 parts = next(reader) 

296 observation_type = parts[3] 

297 status = parts[4] 

298 

299 if i < len(headers) - 1: 

300 current_lines = lines[header + header_length : headers[i + 1] - 1] 

301 else: 

302 current_lines = lines[header + header_length :] 

303 for values in csv.reader(current_lines): 

304 if len(values) < 3: 

305 continue 

306 time_value, measurement_value, qualifier_value = values[:3] 

307 if time_value == "" and measurement_value == "" and qualifier_value == "": 

308 continue 

309 rows.append( 

310 ( 

311 time_value, 

312 measurement_value, 

313 qualifier_value, 

314 status, 

315 observation_type, 

316 ) 

317 ) 

318 if rows: 

319 df = pd.DataFrame( 

320 rows, 

321 columns=["time", "value", "qualifier", "status", "observation_type"], 

322 ).set_index("time") 

323 df["value"] = pd.to_numeric(df["value"], errors="coerce") 

324 else: 

325 df = _get_empty_observation_df() 

326 else: 

327 df = pd.read_csv( 

328 fname, 

329 names=names, 

330 index_col="time", 

331 parse_dates=parse_dates, 

332 usecols=[0, 1, 2], 

333 ) 

334 if observatietype == "regulier_beoordeeld": 

335 df["status"] = "volledigBeoordeeld" 

336 df["observation_type"] = "reguliereMeting" 

337 elif observatietype == "regulier_voorlopig": 

338 df["status"] = "voorlopig" 

339 df["observation_type"] = "reguliereMeting" 

340 elif observatietype == "controle": 

341 df["status"] = np.nan 

342 df["observation_type"] = "controleMeting" 

343 elif observatietype == "onbekend": 

344 df["status"] = "onbekend" 

345 df["observation_type"] = "reguliereMeting" 

346 if rapportagetype == "compact_met_timestamps": 

347 df.index = pd.to_datetime(df.index, unit="ms") 

348 # remove empty indices 

349 mask = df.index.isna() & df.isna().all(axis=1) 

350 if mask.any(): 

351 df = df[~mask] 

352 df = process_observations(df, bro_id, **kwargs) 

353 return df 

354 

355 

356def get_observations_summary(bro_id): 

357 """ 

358 Fetch a summary of a Groundwater Level Dossier (GLD) in JSON format based on 

359 the provided BRO-ID. The summary includes details about the groundwater level 

360 observations, such as observation ID, start and end dates. 

361 

362 Parameters 

363 ---------- 

364 bro_id : str 

365 The BRO-ID of the Groundwater Level Dossier to fetch the summary for. 

366 

367 Raises 

368 ------ 

369 Exception 

370 If the request to the API fails or the status code is greater than 200, 

371 an exception will be raised with the error message returned by the API. 

372 

373 Returns 

374 ------- 

375 pd.DataFrame 

376 A DataFrame containing the summary of the groundwater level observations. 

377 The DataFrame will be indexed by the `observationId` and include 

378 `startDate` and `endDate` columns, converted to `datetime` format. 

379 

380 Notes 

381 ----- 

382 The function sends a GET request to the REST API and processes the returned 

383 JSON data into a DataFrame. If the response contains valid `startDate` or 

384 `endDate` fields, they will be converted to `datetime` format using the 

385 `pd.to_datetime` function. 

386 """ 

387 url = GroundwaterLevelDossier._rest_url 

388 url = "{}/objects/{}/observationsSummary".format(url, bro_id) 

389 req = util.get_with_rate_limit(url) 

390 req = _check_request_status(req) 

391 df = pd.DataFrame(req.json()) 

392 if "observationId" in df.columns: 

393 df = df.set_index("observationId") 

394 if "startDate" in df.columns: 

395 df["startDate"] = pd.to_datetime(df["startDate"], dayfirst=True) 

396 if "endDate" in df.columns: 

397 df["endDate"] = pd.to_datetime(df["endDate"], dayfirst=True) 

398 return df 

399 

400 

401class GroundwaterLevelDossier(bro.FileOrUrl): 

402 """ 

403 Class to represent a Groundwater Level Dossier (GLD) from the BRO. 

404 

405 Attributes 

406 ---------- 

407 observation : pd.DataFrame 

408 DataFrame containing groundwater level observations with time and value 

409 columns. The data is processed and filtered based on the provided arguments. 

410 

411 tubeNumber : int 

412 The tube number associated with the observation. 

413 

414 groundwaterMonitoringWell : str 

415 The BRO-ID of the groundwater monitoring well. 

416 """ 

417 

418 _rest_url = "https://publiek.broservices.nl/gm/gld/v1" 

419 

420 def _read_contents(self, tree, status=None, observation_type=None, **kwargs): 

421 """ 

422 Parse data to populate the Groundwater Level Dossier attributes. 

423 

424 This method reads and processes the XML contents, extracting relevant 

425 groundwater monitoring information such as the groundwater monitoring well, 

426 tube number, and observations. It also processes the observations into a 

427 DataFrame, which is filtered and transformed based on the provided arguments. 

428 

429 Parameters 

430 ---------- 

431 tree : xml.etree.ElementTree 

432 The XML tree to parse and extract data from. 

433 

434 **kwargs : keyword arguments 

435 Additional parameters passed to the `process_observations` function to 

436 filter and transform the observations. 

437 

438 Raises 

439 ------ 

440 Exception 

441 If more than one or no GLD element is found in the XML tree. 

442 

443 Notes 

444 ----- 

445 The method expects the XML structure to adhere to the specified namespaces 

446 and element tags. It processes observation values, timestamps, and qualifiers 

447 into a pandas DataFrame. 

448 

449 The observation data is stored in the `observation` attribute and can be 

450 accessed as a DataFrame. 

451 """ 

452 ns = { 

453 "xmlns": "http://www.broservices.nl/xsd/dsgld/1.0", 

454 "gldcommon": "http://www.broservices.nl/xsd/gldcommon/1.0", 

455 "waterml": "http://www.opengis.net/waterml/2.0", 

456 "swe": "http://www.opengis.net/swe/2.0", 

457 "om": "http://www.opengis.net/om/2.0", 

458 "xlink": "http://www.w3.org/1999/xlink", 

459 } 

460 

461 def _direct_child(element, local_name): 

462 if element is None: 

463 return None 

464 for child_element in element: 

465 if child_element.tag.rsplit("}", 1)[-1] == local_name: 

466 return child_element 

467 return None 

468 

469 def _nested_text(element, *local_names): 

470 current = element 

471 for local_name in local_names: 

472 current = _direct_child(current, local_name) 

473 if current is None: 

474 return None 

475 return current.text 

476 

477 gld = self._get_main_object(tree, "GLD_O", ns) 

478 observation_rows = [] 

479 for key in gld.attrib: 

480 setattr(self, key.split("}", 1)[1], gld.attrib[key]) 

481 for child in gld: 

482 key = self._get_tag(child) 

483 if len(child) == 0: 

484 setattr(self, key, child.text) 

485 elif key == "monitoringPoint": 

486 well = child.find("gldcommon:GroundwaterMonitoringTube", ns) 

487 gmw_id = well.find("gldcommon:broId", ns).text 

488 self.groundwaterMonitoringWell = gmw_id 

489 tube_nr = int(well.find("gldcommon:tubeNumber", ns).text) 

490 self.tubeNumber = tube_nr 

491 elif key in ["registrationHistory"]: 

492 self._read_children_of_children(child) 

493 elif key == "groundwaterMonitoringNet": 

494 for grandchild in child: 

495 key2 = grandchild.tag.split("}", 1)[1] 

496 if key2 == "GroundwaterMonitoringNet": 

497 setattr(self, key, grandchild[0].text) 

498 else: 

499 logger.warning(f"Unknown key: {key2}") 

500 elif key == "observation": 

501 # get observation_metadata 

502 om_observation = _direct_child(child, "OM_Observation") 

503 if om_observation is None: 

504 continue 

505 metadata = _direct_child(om_observation, "metadata") 

506 observation_metadata = _direct_child(metadata, "ObservationMetadata") 

507 

508 # get status 

509 water_ml_status = _direct_child(observation_metadata, "status") 

510 if water_ml_status is None: 

511 status_value = None 

512 else: 

513 status_value = water_ml_status.attrib[ 

514 f"{{{ns['xlink']}}}href" 

515 ].rsplit(":", 1)[-1] 

516 if status is not None and status != status_value: 

517 continue 

518 

519 # get observation_type 

520 parameter = _direct_child(observation_metadata, "parameter") 

521 named_value = _direct_child(parameter, "NamedValue") 

522 name = _direct_child(named_value, "name") 

523 assert ( 

524 name.attrib[f"{{{ns['xlink']}}}href"] 

525 == "urn:bro:gld:ObservationMetadata:observationType" 

526 ) 

527 value = _direct_child(named_value, "value") 

528 observation_type_value = value.text 

529 if ( 

530 observation_type is not None 

531 and observation_type != observation_type_value 

532 ): 

533 continue 

534 

535 for measurement in child.iterfind(".//{*}MeasurementTVP"): 

536 time_text = _nested_text(measurement, "time") 

537 measurement_value = _nested_text(measurement, "value") 

538 if measurement_value is None: 

539 value_float = np.nan 

540 else: 

541 value_float = float(measurement_value) 

542 qualifier_value = _nested_text( 

543 measurement, 

544 "metadata", 

545 "TVPMeasurementMetadata", 

546 "qualifier", 

547 "Category", 

548 "value", 

549 ) 

550 observation_rows.append( 

551 ( 

552 time_text, 

553 value_float, 

554 qualifier_value, 

555 status_value, 

556 observation_type_value, 

557 ) 

558 ) 

559 else: 

560 self._warn_unknown_tag(key) 

561 if observation_rows: 

562 self.observation = pd.DataFrame( 

563 observation_rows, 

564 columns=["time", "value", "qualifier", "status", "observation_type"], 

565 ).set_index("time") 

566 self.observation = process_observations( 

567 self.observation, self.broId, **kwargs 

568 ) 

569 else: 

570 self.observation = _get_empty_observation_df() 

571 

572 

573def process_observations( 

574 df, 

575 bro_id="gld", 

576 to_wintertime=True, 

577 qualifier=None, 

578 tmin=None, 

579 tmax=None, 

580 sort=True, 

581 drop_duplicates=True, 

582): 

583 """ 

584 Process groundwater level observations. 

585 

586 This function processes a DataFrame containing groundwater level observations, 

587 applying the following operations based on the provided parameters: 

588 - Conversion to Dutch winter time (optional). 

589 - Filtering observations based on the qualifier. 

590 - Dropping duplicate observations (optional). 

591 - Sorting the observations by time (optional). 

592 

593 Parameters 

594 ---------- 

595 df : pd.DataFrame 

596 DataFrame containing the groundwater level observations, with a time 

597 index and columns such as "value", "qualifier", etc. 

598 bro_id : str 

599 The BRO-ID of the Groundwater Level Dossier being processed. Only used for 

600 logging-purposes. The default is "gld". 

601 to_wintertime : bool, optional 

602 If True, the observation times are converted to Dutch winter time by 

603 removing any time zone information and adding one hour. If to_wintertime is 

604 False, observation times are kept in CET/CEST. Default is True. 

605 qualifier : str or list of str, optional 

606 If provided, the observations are filtered based on their "qualifier" 

607 column. Only rows with the specified qualifier(s) will be kept. 

608 tmin : str or datetime, optional 

609 The minimum time for filtering observations. Defaults to None. 

610 tmax : str or datetime, optional 

611 The maximum time for filtering observations. Defaults to None. 

612 sort : bool, optional 

613 If True, the DataFrame will be sorted, see `sort_observations`. Default is 

614 True. 

615 drop_duplicates : bool, optional 

616 If True, any duplicate observation times will be dropped, keeping only 

617 the first occurrence. Default is True. 

618 

619 Returns 

620 ------- 

621 pd.DataFrame 

622 A DataFrame containing the processed observations, with duplicate rows 

623 (if any) removed, the time index sorted, and filtered by qualifier if 

624 applicable. 

625 

626 """ 

627 df.index = pd.to_datetime(df.index, utc=True) 

628 if to_wintertime: 

629 # remove time zone information by transforming to dutch winter time 

630 df.index = df.index.tz_localize(None) + pd.Timedelta(1, unit="h") 

631 else: 

632 df.index = df.index.tz_convert("CET") 

633 

634 if qualifier is not None: 

635 if isinstance(qualifier, str): 

636 df = df[df["qualifier"] == qualifier] 

637 else: 

638 df = df[df["qualifier"].isin(qualifier)] 

639 

640 if tmin is not None: 

641 df = df.loc[df.index >= pd.Timestamp(tmin)] 

642 

643 if tmax is not None: 

644 df = df.loc[df.index <= pd.Timestamp(tmax)] 

645 

646 if sort: 

647 df = sort_observations(df) 

648 

649 if drop_duplicates: 

650 df = drop_duplicate_observations(df, bro_id=bro_id, sort=sort) 

651 

652 return df 

653 

654 

655def sort_observations(df): 

656 """ 

657 Sort observations in a DataFrame by multiple criteria. Applies a multi-level sort 

658 to the input DataFrame, prioritizing the following criteria in order: 

659 1. By the DataFrame's DatetimeIndex in ascending order 

660 2. By status (if present): volledigBeoordeeld before voorlopig before onbekend 

661 3. By observation_type (if present): reguliereMeting before controleMeting 

662 

663 Parameters 

664 ---------- 

665 df : pandas.DataFrame 

666 DataFrame with optional 'observation_type' and 'status' columns, 

667 and a DatetimeIndex. 

668 

669 Returns 

670 ------- 

671 pandas.DataFrame 

672 Sorted DataFrame with the same structure as input. 

673 """ 

674 if "observation_type" in df.columns: 

675 # make sure measurements with observation_type set to reguliereMeting are first 

676 sort_dict = {"reguliereMeting": 0, "controleMeting": 1} 

677 df = df.sort_values( 

678 "observation_type", key=lambda x: x.map(sort_dict), kind="mergesort" 

679 ) 

680 

681 if "status" in df.columns: 

682 # make sure measurements with status set to volledigBeoordeeld are first 

683 sort_dict = {"volledigBeoordeeld": 0, "voorlopig": 1, "onbekend": 2} 

684 df = df.sort_values("status", key=lambda x: x.map(sort_dict), kind="mergesort") 

685 

686 # sort based on DatetimeIndex 

687 df = df.sort_index(kind="mergesort") 

688 

689 return df 

690 

691 

692def drop_duplicate_observations(df, bro_id="gld", keep="first", sort=True): 

693 """ 

694 Remove duplicate observations from a DataFrame based on its index. 

695 

696 Parameters 

697 ---------- 

698 df : pd.DataFrame 

699 The DataFrame to process. 

700 bro_id : str, optional 

701 Identifier for the dataset, used in warning messages. Default is "gld". 

702 keep : {'first', 'last', False}, optional 

703 Which duplicates to mark: 

704 - 'first' : Mark duplicates as True except for the first occurrence. 

705 - 'last' : Mark duplicates as True except for the last occurrence. 

706 - False : Mark all duplicates as True. 

707 Default is 'first'. 

708 

709 Returns 

710 ------- 

711 pd.DataFrame 

712 DataFrame with duplicate index values removed, keeping only the rows 

713 specified by the `keep` parameter. 

714 

715 Warnings 

716 -------- 

717 Logs a warning message if duplicates are found, indicating the number and 

718 total count of duplicates before removal. 

719 """ 

720 if df.index.has_duplicates: 

721 duplicates = df.index.duplicated(keep=keep) 

722 message = "{} contains {} duplicates (of {}). Keeping only first values" 

723 message = message.format(bro_id, duplicates.sum(), len(df.index)) 

724 if sort: 

725 message = f"{message} (sorted for importance)" 

726 message = f"{message}." 

727 logger.warning(message) 

728 df = df[~duplicates] 

729 return df 

730 

731 

732def _get_empty_observation_df(): 

733 columns = ["time", "value", "qualifier", "status", "observation_type"] 

734 return pd.DataFrame(columns=columns).set_index("time") 

735 

736 

737cl = GroundwaterLevelDossier 

738 

739get_bro_ids_of_bronhouder = partial(bro._get_bro_ids_of_bronhouder, cl) 

740get_bro_ids_of_bronhouder.__doc__ = bro._get_bro_ids_of_bronhouder.__doc__ 

741 

742get_data_for_bro_ids = partial(bro._get_data_for_bro_ids, cl) 

743get_data_for_bro_ids.__doc__ = bro._get_data_for_bro_ids.__doc__