Coverage for brodata/plot.py: 87%

218 statements  

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

1import logging 

2 

3import matplotlib.pyplot as plt 

4import numpy as np 

5import pandas as pd 

6from matplotlib.patches import Rectangle 

7 

8logger = logging.getLogger(__name__) 

9 

10 

11def cone_penetration_test( 

12 cpt, figsize=(10, 10), ax=None, linewidth=1.0, ylabel="Sondeertrajectlengte" 

13): 

14 """ 

15 Plot the results of a cone penetration test (CPT). 

16 

17 This function visualizes multiple CPT parameters (cone resistance, friction ratio, 

18 local friction, and inclination resultant) against the test depth or trajectory 

19 length. Each parameter is plotted on a separate x-axis, sharing the same y-axis. 

20 

21 Parameters 

22 ---------- 

23 cpt : pandas.DataFrame or object 

24 The CPT data as a DataFrame or an object with a 'conePenetrationTest' attribute 

25 containing the DataFrame. 

26 figsize : tuple, optional 

27 Size of the figure to create if `ax` is not provided. Default is (10, 10). 

28 ax : matplotlib.axes.Axes, optional 

29 Existing matplotlib Axes to plot on. If None, a new figure and axes are created. 

30 linewidth : float, optional 

31 Width of the plot lines. Default is 1.0. 

32 ylabel : str, optional 

33 Label for the y-axis. Default is "Sondeertrajectlengte". 

34 

35 Returns 

36 ------- 

37 list of matplotlib.axes.Axes 

38 List of axes objects for each parameter plotted. 

39 

40 Notes 

41 ----- 

42 - The y-axis is inverted to represent increasing depth downward. 

43 - Each parameter is plotted only if its column in the DataFrame is not entirely NaN. 

44 - The function supports plotting up to four parameters: 'coneResistance', 

45 'frictionRatio', 'localFriction', and 'inclinationResultant'. 

46 """ 

47 if hasattr(cpt, "conePenetrationTest"): 

48 df = cpt.conePenetrationTest 

49 else: 

50 df = cpt 

51 if ax is None: 

52 f, ax1 = plt.subplots(figsize=figsize) 

53 else: 

54 ax1 = ax 

55 ax1.set_ylabel(ylabel) 

56 ax1.invert_yaxis() 

57 

58 axes = [] 

59 

60 if not df["coneResistance"].isna().all(): 

61 ax1.plot(df["coneResistance"], df.index, color="b", linewidth=linewidth) 

62 ax1.set_xlim(0, df["coneResistance"].max() * 2) 

63 ax1.tick_params(axis="x", labelcolor="b") 

64 lab = ax1.set_xlabel("Conusweerstand MPa", color="b") 

65 lab.set_position((0.0, lab.get_position()[1])) 

66 lab.set_horizontalalignment("left") 

67 axes.append(ax1) 

68 

69 if not df["frictionRatio"].isna().all(): 

70 ax2 = ax1.twiny() 

71 ax2.xaxis.set_ticks_position("bottom") 

72 ax2.xaxis.set_label_position("bottom") 

73 ax2.plot(df["frictionRatio"], df.index, color="g", linewidth=linewidth) 

74 ax2.set_xlim(0, df["frictionRatio"].max() * 2) 

75 ax2.tick_params(axis="x", labelcolor="g") 

76 ax2.invert_xaxis() 

77 lab = ax2.set_xlabel("Wrijvingsgetal", color="g") 

78 lab.set_position((1.0, lab.get_position()[1])) 

79 lab.set_horizontalalignment("right") 

80 axes.append(ax2) 

81 

82 if not df["localFriction"].isna().all(): 

83 ax3 = ax1.twiny() 

84 ax3.plot( 

85 df["localFriction"], 

86 df.index, 

87 color="r", 

88 linestyle="--", 

89 linewidth=linewidth, 

90 ) 

91 ax3.set_xlim(0, df["localFriction"].max() * 2) 

92 ax3.tick_params(axis="x", labelcolor="r") 

93 lab = ax3.set_xlabel("Plaatselijke wrijving", color="r") 

94 lab.set_position((0.0, lab.get_position()[1])) 

95 lab.set_horizontalalignment("left") 

96 axes.append(ax3) 

97 

98 if not df["inclinationResultant"].isna().all(): 

99 ax4 = ax1.twiny() 

100 ax4.plot( 

101 df["inclinationResultant"], 

102 df.index, 

103 color="m", 

104 linestyle="--", 

105 linewidth=linewidth, 

106 ) 

107 

108 ax4.set_xlim(0, df["inclinationResultant"].max() * 2) 

109 ax4.tick_params(axis="x", labelcolor="m") 

110 ax4.invert_xaxis() 

111 lab = ax4.set_xlabel("Hellingsresultante", color="m") 

112 lab.set_position((1.0, lab.get_position()[1])) 

113 lab.set_horizontalalignment("right") 

114 axes.append(ax4) 

115 

116 if ax is None: 

117 f.tight_layout(pad=0.0) 

118 

119 return axes 

120 

121 

122lithology_colors = { 

123 "ballast": (200 / 255, 200 / 255, 200 / 255), # checked at B38D4055 

124 "baggert": (144 / 255, 144 / 255, 144 / 255), # checked at B60C5217 

125 "baksteen": (200 / 255, 200 / 255, 200 / 255), # checked at B31H2923 

126 "beton": (200 / 255, 200 / 255, 200 / 255), # same as baksteen, checked at B31H2925 

127 "bruinkool": (140 / 255, 92 / 255, 54 / 255), # checked at B51G2426 

128 "detritus": (157 / 255, 78 / 255, 64 / 255), # checked at B44A0733 

129 "glauconietzand": (204 / 255, 1, 153 / 255), # checked at B49E1446 

130 "grind": (216 / 255, 163 / 255, 32 / 255), 

131 "hout": (157 / 255, 78 / 255, 64 / 255), 

132 "ijzeroer": (242 / 255, 128 / 255, 13 / 255), # checked at B49E1446 

133 "kalksteen": (140 / 255, 180 / 255, 1), # checked at B44B0062 

134 "klei": (0, 146 / 255, 0), 

135 "leem": (194 / 255, 207 / 255, 92 / 255), 

136 "mergel ": (140 / 255, 180 / 255, 1), # checked at B60C0656 

137 "mijnsteen": (200 / 255, 200 / 255, 200 / 255), # checked at B60C3651 

138 "moeraskalk": (204 / 255, 102 / 255, 1), # checked at B31D1237 

139 "oer": (200 / 255, 200 / 255, 200 / 255), 

140 "puin": (200 / 255, 200 / 255, 200 / 255), # same as beton 

141 "slurrie": (144 / 255, 144 / 255, 144 / 255), # same as slib, checked at B25A3512 

142 "stenen": (216 / 255, 163 / 255, 32 / 255), 

143 "stigmaria": ( 

144 144 / 255, 

145 144 / 255, 

146 144 / 255, 

147 ), # same as baggert , checked at B60C5003 

148 "veen": (157 / 255, 78 / 255, 64 / 255), 

149 "zand": (1, 1, 0), 

150 "zand fijn": (1, 1, 0), # same as zand 

151 "zand midden": (243 / 255, 225 / 255, 6 / 255), 

152 "zand grof": (231 / 255, 195 / 255, 22 / 255), 

153 "sideriet": (242 / 255, 128 / 255, 13 / 255), # checked at B51D2864 

154 "slib": (144 / 255, 144 / 255, 144 / 255), 

155 "schalie": (156 / 255, 158 / 255, 99 / 255), # checked at B60C4442 

156 "schelpen": (95 / 255, 95 / 255, 1), 

157 "sterkGrindigZand": ( 

158 231 / 255, 

159 195 / 255, 

160 22 / 255, 

161 ), # same as zand grove categorie 

162 "steenkool": (58 / 255, 37 / 255, 22 / 255), # checked at B60C4442 

163 "vast gesteente": (97 / 255, 97 / 255, 97 / 255), # checked at B60C5112 

164 "wegverhardingsmateriaal": ( 

165 200 / 255, 

166 200 / 255, 

167 200 / 255, 

168 ), # same as puin, checked at B25D3298 

169 "zwakZandigeKlei": (0, 146 / 255, 0), # same as klei 

170 "gyttja": (157 / 255, 78 / 255, 64 / 255), # same as hout, checked at B02G0307 

171 "zandsteen": (200 / 255, 171 / 255, 55 / 255), # checked at B44B0119 

172 "niet benoemd": (1, 1, 1), 

173 "geen monster": (1, 1, 1), 

174} 

175 

176sand_class_fine = [ 

177 "fijne categorie (O)", 

178 "zeer fijn (O)", 

179 "uiterst fijn (O)", 

180 "zeer fijn", 

181 "uiterst fijn", 

182] 

183 

184sand_class_medium = [ 

185 "matig fijn", 

186 "matig fijn (O)", 

187 "matig grof", 

188 "matig grof (O)", 

189 "midden categorie (O)", 

190] 

191 

192sand_class_course = [ 

193 "grove categorie (O)", 

194 "zeer grof", 

195 "zeer grof (O)", 

196 "uiterst grof", 

197 "uiterst grof (O)", 

198] 

199 

200 

201def get_lithology_color( 

202 hoofdgrondsoort, 

203 zandmediaanklasse=None, 

204 drilling=None, 

205 colors=None, 

206): 

207 """ 

208 Return the RGB color and label for a given lithology (hoofdgrondsoort). 

209 

210 Parameters 

211 ---------- 

212 hoofdgrondsoort : str or any 

213 The main soil type (lithology) to get the color for. If not a string (e.g., 

214 NaN), a default color is used. 

215 zandmediaanklasse : str, optional 

216 The sand median class, used for further classification if hoofdgrondsoort is 

217 "zand". 

218 drilling : any, optional 

219 Optional drilling identifier, used for logging warnings. 

220 colors : dict, optional 

221 Dictionary mapping lithology names to RGB color tuples (0-1). If None, uses 

222 the default `lithology_colors`. 

223 

224 Returns 

225 ------- 

226 color : tuple of float 

227 The RGB color as a tuple of floats in the range [0, 1]. 

228 label : str 

229 The label for the lithology, possibly more specific for sand classes. 

230 

231 Notes 

232 ----- 

233 - If the hoofdgrondsoort is not recognized, a warning is logged and a default white 

234 color is returned. 

235 - For "zand", the zandmediaanklasse determines the specific sand color and label. 

236 - If colors is not provided, the function uses a default color mapping. 

237 """ 

238 if colors is None: 

239 colors = lithology_colors 

240 label = None 

241 if not isinstance(hoofdgrondsoort, str): 

242 # hoofdgrondsoort is nan 

243 color = colors["niet benoemd"] 

244 label = str(hoofdgrondsoort) 

245 elif hoofdgrondsoort in colors: 

246 if hoofdgrondsoort == "zand": 

247 if zandmediaanklasse in sand_class_fine: 

248 color = colors["zand fijn"] 

249 label = "Zand fijne categorie" 

250 elif zandmediaanklasse in sand_class_medium: 

251 label = "Zand midden categorie" 

252 color = colors["zand midden"] 

253 elif zandmediaanklasse in sand_class_course: 

254 color = colors["zand grof"] 

255 label = "Zand grove categorie" 

256 else: 

257 if not ( 

258 pd.isna(zandmediaanklasse) 

259 or zandmediaanklasse in ["zandmediaan onduidelijk"] 

260 ): 

261 msg = f"Unknown zandmediaanklasse: {zandmediaanklasse}" 

262 if drilling is not None: 

263 msg = f"{msg} in drilling {drilling}" 

264 logger.warning(msg) 

265 # for zandmediaanklasse is None or something other than mentioned above 

266 color = colors[hoofdgrondsoort] 

267 else: 

268 color = colors[hoofdgrondsoort] 

269 else: 

270 msg = f"No color defined for hoofdgrondsoort {hoofdgrondsoort}" 

271 if drilling is not None: 

272 msg = f"{msg} in drilling {drilling}" 

273 logger.warning(msg) 

274 color = (1.0, 1.0, 1.0) 

275 

276 if isinstance(color, (tuple, list, np.ndarray)) and np.any([x > 1 for x in color]): 

277 logger.warning( 

278 f"Color {color} specified as as integers between 0 and 255. " 

279 "Please specify rgb-values as floats between 0 and 1." 

280 ) 

281 color = tuple(x / 255 for x in color) 

282 

283 if label is None: 

284 label = hoofdgrondsoort.capitalize() 

285 return color, label 

286 

287 

288def lithology( 

289 df, 

290 top, 

291 bot, 

292 kind, 

293 sand_class=None, 

294 ax=None, 

295 x=0.5, 

296 z=0.0, 

297 solid_capstyle="butt", 

298 linewidth=6, 

299 drilling=None, 

300 colors=None, 

301 **kwargs, 

302): 

303 """ 

304 Plot lithology intervals from a DataFrame as vertical lines or filled spans. 

305 

306 Parameters 

307 ---------- 

308 df : pandas.DataFrame 

309 DataFrame containing lithology data. 

310 top : str 

311 Column name in `df` representing the top depth of each interval. 

312 bot : str 

313 Column name in `df` representing the bottom depth of each interval. 

314 kind : str 

315 Column name in `df` specifying the lithology type for color mapping. 

316 sand_class : str, optional 

317 Column name in `df` specifying sand class for color mapping (default: None). 

318 ax : matplotlib.axes.Axes, optional 

319 Matplotlib axis to plot on. If None, uses current axis (default: None). 

320 x : float, optional 

321 X-coordinate for vertical lines (default: 0.5). If None or not finite, uses 

322 filled spans. 

323 z : float, optional 

324 Reference depth for vertical positioning (default: 0.0). 

325 solid_capstyle : str, optional 

326 Cap style for vertical lines (default: "butt"). 

327 linewidth : float, optional 

328 Line width for plotting (default: 6). 

329 drilling : any, optional 

330 Additional drilling information for color mapping (default: None). 

331 colors : dict, optional 

332 Custom color mapping for lithologies (default: None). 

333 **kwargs 

334 Additional keyword arguments passed to matplotlib plotting functions. 

335 

336 Returns 

337 ------- 

338 list 

339 List of matplotlib artist objects corresponding to the plotted lithology 

340 intervals. 

341 

342 Notes 

343 ----- 

344 - If `x` is provided and finite, plots vertical lines at `x`. 

345 - If `x` is None or not finite, plots filled horizontal spans between `z_top` and 

346 `z_bot`. 

347 - Uses `get_lithology_color` to determine color and label for each interval. 

348 """ 

349 h = [] 

350 if not isinstance(df, pd.DataFrame): 

351 return h 

352 if ax is None: 

353 ax = plt.gca() 

354 for index in df.index: 

355 z_top = z - df.at[index, top] 

356 z_bot = z - df.at[index, bot] 

357 zandmediaanklasse = None if sand_class is None else df.at[index, sand_class] 

358 color, label = get_lithology_color( 

359 df.at[index, kind], zandmediaanklasse, drilling=drilling, colors=colors 

360 ) 

361 if x is not None and np.isfinite(x): 

362 h.append( 

363 ax.plot( 

364 [x, x], 

365 [z_bot, z_top], 

366 color=color, 

367 label=label, 

368 linewidth=linewidth, 

369 solid_capstyle=solid_capstyle, 

370 **kwargs, 

371 ) 

372 ) 

373 else: 

374 h.append( 

375 ax.axhspan( 

376 z_bot, 

377 z_top, 

378 facecolor=color, 

379 label=label, 

380 linewidth=linewidth, 

381 **kwargs, 

382 ) 

383 ) 

384 return h 

385 

386 

387def lithology_along_line( 

388 gdf, line, kind, ax=None, legend=True, max_distance=None, **kwargs 

389): 

390 """ 

391 Plot lithological drillings along a cross-sectional line. 

392 

393 This function visualizes subsurface lithology data from borehole records 

394 in a 2D cross-section view, based on their proximity to a specified line. 

395 It supports both 'dino' and 'bro' formatted datasets. 

396 

397 Parameters 

398 ---------- 

399 gdf : geopandas.GeoDataFrame 

400 GeoDataFrame containing borehole data. This typically includes geometry and 

401 lithology-related columns. Can be retrieved using, for example, 

402 `brodata.dino.get_boormonsterprofiel`. 

403 line : shapely.geometry.LineString or list of tuple[float, float] 

404 The cross-sectional line along which to plot the lithologies. Determines the 

405 x-coordinates of the lithology logs. If `max_distance` is set, only boreholes 

406 within this distance from the line will be included. 

407 kind : str 

408 Specifies the data source format. Must be either 'dino' or 'bro'. 

409 ax : matplotlib.axes.Axes, optional 

410 The matplotlib axes object to plot on. If None, uses the current axes. 

411 legend : bool, optional 

412 Whether to include a legend for the lithology classes. Default is True. 

413 max_distance : float, optional 

414 Maximum distance (in the same units as the GeoDataFrame's CRS) from the line 

415 within which boreholes are included in the cross-section. If None, includes all. 

416 **kwargs : 

417 Additional keyword arguments passed to either `dino_lithology` or 

418 `bro_lithology`. 

419 

420 Returns 

421 ------- 

422 ax : matplotlib.axes.Axes 

423 The matplotlib axes object containing the lithology cross-section plot. 

424 

425 Raises 

426 ------ 

427 Exception 

428 If `kind` is not 'dino' or 'bro'. 

429 """ 

430 from shapely.geometry import LineString 

431 

432 ax = plt.gca() if ax is None else ax 

433 

434 line = LineString(line) if not isinstance(line, LineString) else line 

435 

436 if max_distance is not None: 

437 gdf = gdf[gdf.distance(line) < max_distance] 

438 

439 # calculate length along line 

440 s = pd.Series([line.project(point) for point in gdf.geometry], gdf.index) 

441 

442 for index in gdf.index: 

443 if kind == "dino": 

444 dino_lithology( 

445 gdf.at[index, "lithologie_lagen"], 

446 z=gdf.at[index, "Maaiveldhoogte (m tov NAP)"], 

447 x=s[index], 

448 drilling=index, 

449 ax=ax, 

450 **kwargs, 

451 ) 

452 elif kind == "bro": 

453 if len(gdf.at[index, "descriptiveBoreholeLog"]) > 0: 

454 msg = ( 

455 f"More than 1 descriptiveBoreholeLog for {index}. " 

456 "Only plotting the first one." 

457 ) 

458 logger.warning(msg) 

459 df = gdf.at[index, "descriptiveBoreholeLog"][0]["layer"] 

460 bro_lithology(df, x=s[index], drilling=index, ax=ax, **kwargs) 

461 else: 

462 raise (Exception(f"Unknown kind: {kind}")) 

463 

464 if legend: # add a legend 

465 add_lithology_legend(ax=ax) 

466 

467 return ax 

468 

469 

470def add_lithology_legend(ax, **kwargs): 

471 """ 

472 Add a custom legend to a matplotlib Axes for lithology categories. 

473 

474 ax : matplotlib.axes.Axes 

475 The matplotlib Axes object to which the legend will be added. 

476 **kwargs : dict, optional 

477 Additional keyword arguments passed to `ax.legend()` (e.g., loc, fontsize). 

478 

479 Returns 

480 ------- 

481 matplotlib.legend.Legend 

482 The legend object added to the axes. 

483 

484 Notes 

485 ----- 

486 The function reorders legend entries so that common lithology categories appear in a 

487 preferred order: 

488 - "Veen", "Klei", "Leem", "Zand fijne categorie", "Zand midden categorie", 

489 "Zand grove categorie", "Zand", "Grind" 

490 These are placed at the top of the legend, while "Niet benoemd" and "Geen monster" 

491 are placed at the bottom. 

492 Duplicate labels are removed, keeping only the first occurrence. 

493 

494 """ 

495 handles, labels = ax.get_legend_handles_labels() 

496 labels, index = np.unique(np.array(labels), return_index=True) 

497 boven = np.array( 

498 [ 

499 "Veen", 

500 "Klei", 

501 "Leem", 

502 "Zand fijne categorie", 

503 "Zand midden categorie", 

504 "Zand grove categorie", 

505 "Zand", 

506 "Grind", 

507 ] 

508 ) 

509 for lab in boven: 

510 if lab in labels: 

511 mask = labels == lab 

512 labels = np.hstack((labels[mask], labels[~mask])) 

513 index = np.hstack((index[mask], index[~mask])) 

514 onder = np.array(["Niet benoemd", "Geen monster"]) 

515 for lab in onder: 

516 if lab in labels: 

517 mask = labels == lab 

518 labels = np.hstack((labels[~mask], labels[mask])) 

519 index = np.hstack((index[~mask], index[mask])) 

520 return ax.legend(np.array(handles)[index], labels, **kwargs) 

521 

522 

523def dino_lithology(df, **kwargs): 

524 """ 

525 Plot lithology information from a DataFrame containing lithology data from DINO. 

526 

527 Parameters 

528 ---------- 

529 df : pandas.DataFrame 

530 The input DataFrame containing lithology data. 

531 **kwargs 

532 Additional keyword arguments passed to the underlying `lithology` function. 

533 

534 Returns 

535 ------- 

536 list 

537 List of matplotlib artist objects corresponding to the plotted lithology 

538 intervals. 

539 

540 Notes 

541 ----- 

542 This function is a wrapper around the `lithology` function, mapping the DataFrame 

543 columns: 

544 - 'Bovenkant laag (m beneden maaiveld)' as top 

545 - 'Onderkant laag (m beneden maaiveld)' as bot 

546 - 'Hoofdgrondsoort' as kind 

547 - 'Zandmediaanklasse' as sand_class 

548 """ 

549 return lithology( 

550 df, 

551 top="Bovenkant laag (m beneden maaiveld)", 

552 bot="Onderkant laag (m beneden maaiveld)", 

553 kind="Hoofdgrondsoort", 

554 sand_class="Zandmediaanklasse", 

555 **kwargs, 

556 ) 

557 

558 

559def bro_lithology(df, **kwargs): 

560 """ 

561 Plot lithology information from a DataFrame containing lithology data from BRO. 

562 

563 Parameters 

564 ---------- 

565 df : pandas.DataFrame 

566 The input DataFrame containing lithology data. 

567 **kwargs 

568 Additional keyword arguments passed to the underlying `lithology` function. 

569 

570 Returns 

571 ------- 

572 list 

573 List of matplotlib artist objects corresponding to the plotted lithology 

574 intervals. 

575 

576 Notes 

577 ----- 

578 This function is a wrapper around the `lithology` function, mapping the DataFrame 

579 columns: 

580 - 'upperBoundary' as the top, 

581 - 'lowerBoundary' as the bot, 

582 - 'geotechnicalSoilName' as kind. 

583 """ 

584 return lithology( 

585 df, 

586 top="upperBoundary", 

587 bot="lowerBoundary", 

588 kind="geotechnicalSoilName", 

589 **kwargs, 

590 ) 

591 

592 

593def get_dino_lithology_colors(): 

594 """ 

595 Retrieve the standard color mapping for DINO lithology types. 

596 

597 Returns 

598 ------- 

599 dict 

600 A dictionary mapping lithology type names to their corresponding color values 

601 used for visualization in plots and maps. 

602 """ 

603 return lithology_colors 

604 

605 

606def get_bro_lithology_properties(): 

607 """ 

608 Retrieve a comprehensive legend dictionary for BRO (Basisregistratie Ondergrond) lithology properties. 

609 This function defines visual properties (colors and hatching patterns) for various soil and rock types 

610 used in geological mapping, including: 

611 - Primary lithologies (veen, klei, leem, zand, grind, silt) 

612 - Unspecified categories (nietBepaald, grondNietGespecificeerd) 

613 - Complex composite lithologies with width-based proportions for mixed soil types 

614 

615 Returns 

616 ------- 

617 dict: A dictionary mapping lithology type names (str) to their visual properties (dict or list of dict). 

618 Each property dict contains: 

619 - "color": tuple of RGB values (normalized to 0-1 range) 

620 - "hatch": str, optional pattern for visualization ("-", "/", "\\", ".", "o", "|") 

621 - "width": float, optional proportion value used for composite lithologies 

622 """ 

623 legend = { 

624 "veen": {"color": (153 / 255, 76 / 255, 58 / 255), "hatch": "-"}, 

625 "klei": {"color": (0, 150 / 255, 8 / 255), "hatch": "/"}, 

626 "leem": {"color": (219 / 255, 219 / 255, 219 / 255), "hatch": "\\"}, 

627 "zand": {"color": (254 / 255, 254 / 255, 8 / 255), "hatch": "."}, 

628 "grind": {"color": (243 / 255, 192 / 255, 39 / 255), "hatch": "o"}, 

629 "silt": {"color": (219 / 255, 219 / 255, 219 / 255), "hatch": "|"}, 

630 "nietBepaald": {"color": (112 / 255, 48 / 255, 160 / 255)}, 

631 "grondNietGespecificeerd": {"color": (1, 1, 1)}, 

632 } 

633 

634 legend = legend | { 

635 "mineraalarmVeen": legend["veen"], 

636 "zwakZandigVeen": [ 

637 {"width": 50 / 60} | legend["veen"], 

638 {"width": 10 / 60} | legend["zand"], 

639 ], 

640 "sterkZandigVeen": [ 

641 {"width": 41 / 60} | legend["veen"], 

642 {"width": 19 / 60} | legend["zand"], 

643 ], 

644 "zwakKleiigVeen": [ # not checked at broloket 

645 {"width": 50 / 60} | legend["veen"], 

646 {"width": 10 / 60} | legend["klei"], 

647 ], 

648 "sterkKleiigVeen": [ 

649 {"width": 41 / 60} | legend["veen"], 

650 {"width": 19 / 60} | legend["klei"], 

651 ], 

652 "kleiigVeen": [ 

653 {"width": 42 / 60} | legend["veen"], 

654 {"width": 18 / 60} | legend["klei"], 

655 ], 

656 "veenNietGespecificeerd": [ 

657 {"width": (39 / 60)} | legend["veen"], 

658 {"width": (21 / 60)} | legend["grondNietGespecificeerd"], 

659 ], 

660 "zwakZandigSilt": [ 

661 {"width": 48 / 60} | legend["silt"], 

662 {"width": 12 / 60} | legend["zand"], 

663 ], 

664 "zwakGrindigeKlei": [ 

665 {"width": 48 / 60} | legend["klei"], 

666 {"width": 12 / 60} | legend["grind"], 

667 ], 

668 "zwakZandigeKlei": [ 

669 {"width": 48 / 60} | legend["klei"], 

670 {"width": 12 / 60} | legend["zand"], 

671 ], 

672 "zwakZandigeKleiMetGrind": [ 

673 {"width": 48 / 60} | legend["klei"], 

674 {"width": 12 / 60} | legend["zand"], 

675 ], 

676 "matigZandigeKlei": [ 

677 {"width": 41 / 60} | legend["klei"], 

678 {"width": 19 / 60} | legend["zand"], 

679 ], 

680 "sterkZandigeKlei": [ 

681 {"width": 30 / 60} | legend["klei"], 

682 {"width": 30 / 60} | legend["zand"], 

683 ], 

684 "sterkZandigeKleiMetGrind": [ 

685 {"width": 36 / 60} | legend["klei"], 

686 {"width": 24 / 60} | legend["leem"], # with a hatch 

687 ], 

688 "zwakSiltigeKlei": [ 

689 {"width": 48 / 60} | legend["klei"], 

690 {"width": 12 / 60} | legend["leem"], # with a hatch 

691 ], 

692 "matigSiltigeKlei": [ 

693 {"width": 39 / 60} | legend["klei"], 

694 {"width": 21 / 60} | legend["leem"], # with a hatch 

695 ], 

696 "sterkSiltigeKlei": [ 

697 {"width": 30 / 60} | legend["klei"], 

698 {"width": 30 / 60} | legend["leem"], # with a hatch 

699 ], 

700 "uiterstSiltigeKlei": [ 

701 {"width": 26 / 60} | legend["klei"], 

702 {"width": 34 / 60} | {"color": legend["silt"]["color"]}, # without a hatch 

703 ], 

704 "zwakZandigeLeem": [ 

705 {"width": 50 / 60} | legend["leem"], 

706 {"width": 10 / 60} | legend["zand"], 

707 ], 

708 "sterkZandigeLeem": [ 

709 {"width": 30 / 60} | legend["leem"], 

710 {"width": 30 / 60} | legend["zand"], 

711 ], 

712 "zwakGrindigZand": [ 

713 {"width": 48 / 60} | legend["zand"], 

714 {"width": 12 / 60} | legend["grind"], 

715 ], 

716 "sterkGrindigZand": [ 

717 {"width": 36 / 60} | legend["zand"], 

718 {"width": 24 / 60} | legend["grind"], 

719 ], 

720 "zwakSiltigZand": [ 

721 {"width": 50 / 60} | legend["zand"], 

722 {"width": 10 / 60} | legend["leem"], 

723 ], 

724 "matigSiltigZand": [ 

725 {"width": 39 / 60} | legend["zand"], 

726 {"width": 21 / 60} | legend["leem"], 

727 ], 

728 "sterkSiltigZand": [ 

729 {"width": 30 / 60} | legend["zand"], 

730 {"width": 30 / 60} | legend["leem"], 

731 ], 

732 "uiterstSiltigZand": [ 

733 {"width": 24 / 60} | legend["zand"], 

734 {"width": 36 / 60} | legend["silt"], 

735 ], 

736 "siltigZandMetGrind": [ 

737 {"width": 42 / 60} | legend["zand"], 

738 {"width": 18 / 60} | legend["silt"], 

739 ], 

740 "kleiigZand": [ 

741 {"width": 50 / 60} | legend["zand"], 

742 {"width": 10 / 60} | legend["klei"], 

743 ], 

744 "kleiigZandMetGrind": [ 

745 {"width": 42 / 60} | legend["zand"], 

746 {"width": 18 / 60} | legend["klei"], 

747 ], 

748 "siltigZand": [ 

749 {"width": 42 / 60} | legend["zand"], 

750 {"width": 18 / 60} | legend["silt"], 

751 ], 

752 "zwakZandigGrind": [ 

753 {"width": 48 / 60} | legend["grind"], 

754 {"width": 12 / 60} | legend["zand"], 

755 ], 

756 "sterkZandigGrind": [ 

757 {"width": 36 / 60} | legend["grind"], 

758 {"width": 24 / 60} | legend["zand"], 

759 ], 

760 "zandNietGespecificeerd": [ 

761 {"width": (24 / 60)} | legend["zand"], 

762 {"width": (36 / 60)} | legend["grondNietGespecificeerd"], 

763 ], 

764 } 

765 return legend 

766 

767 

768def bro_lithology_advanced( 

769 df, 

770 soil_name_column="geotechnicalSoilName", 

771 z=0.0, 

772 x=0.5, 

773 width=0.1, 

774 lithology_properties=None, 

775 ax=None, 

776 hatch_factor=2, 

777 hatch_color=(0.0, 0.0, 0.0, 0.2), 

778 hatch_linewidth=2, 

779 bro_id=None, 

780): 

781 """ 

782 Plot advanced lithology data from a BRO (Basisregistratie Ondergrond) dataframe. 

783 This function visualizes soil layers with customizable colors, patterns, and 

784 hatching, creating a detailed stratigraphic column representation. 

785 

786 Parameters 

787 ---------- 

788 df : pandas.DataFrame 

789 DataFrame containing borehole lithology data with columns for soil names and 

790 depth boundaries. 

791 soil_name_column : str, optional 

792 Name of the column containing soil classifications. Default is 

793 "geotechnicalSoilName". Other options include "soilNameNEN5104", 

794 "standardSoilName" or "soilName" depending on data source. 

795 z : float, optional 

796 Base depth (z-coordinate) for the plot in meters. Default is 0.0. 

797 x : float, optional 

798 Horizontal x-coordinate position for the lithology column. Default is 0.5. 

799 width : float, optional 

800 Base width of the lithology column. Default is 0.1. 

801 lithology_properties : dict, optional 

802 Dictionary mapping soil names to their visual properties (color, hatch pattern, 

803 width). If None, properties are loaded from get_bro_lithology_properties(). 

804 Default is None. 

805 ax : matplotlib.axes.Axes, optional 

806 Matplotlib axes object to plot on. If None, uses current axes. Default is None. 

807 hatch_factor : float, optional 

808 Scaling factor for hatch pattern density. Default is 2. 

809 hatch_color : tuple, optional 

810 RGBA color tuple for hatch patterns. Default is (0.0, 0.0, 0.0, 0.2) (semi- 

811 transparent black). 

812 hatch_linewidth : float, optional 

813 Line width for hatch patterns in points. Default is 2. 

814 bro_id : str or int, optional 

815 BRO identifier for logging purposes. Used in warning messages. Default is None. 

816 

817 Returns 

818 ------- 

819 list 

820 List of matplotlib Rectangle patch handles for the plotted soil layers. 

821 

822 Raises 

823 ------ 

824 ValueError 

825 If the specified soil_name_column is not present in the dataframe. 

826 

827 Notes 

828 ----- 

829 - Soil names with NaN values are mapped to "grondNietGespecificeerd" (unspecified ground). 

830 - Unsupported soil names generate warning messages but do not halt execution. 

831 - Lithology properties can be overridden per layer using the lithology_properties dictionary. 

832 """ 

833 # TODO: create a legend. See https://stackoverflow.com/questions/55501860/how-to-put-multiple-colormap-patches-in-a-matplotlib-legend 

834 ax = plt.gca() if ax is None else ax 

835 

836 if lithology_properties is None: 

837 lithology_properties = get_bro_lithology_properties() 

838 

839 if soil_name_column not in df.columns: 

840 raise (ValueError(f"Column {soil_name_column} not present in df")) 

841 

842 handles = [] 

843 for index in df.index: 

844 # soil_name_column = "geotechnicalSoilName" for GeotechnicalBoreholeResearch 

845 # soil_name_column = "soilNameNEN5104" for GeologicalBoreholeResearch 

846 # soil_name_column = "standardSoilName" for PedologicalBoreholeResearch 

847 # soil_name_column = "soilName" for DescriptiveBoreholeLog in SiteAssessmentData 

848 sn = df.at[index, soil_name_column] 

849 # sn can be nan 

850 if pd.isna(sn): 

851 sn = "grondNietGespecificeerd" 

852 left = x - width / 2 

853 if sn not in lithology_properties: 

854 msg = f"SoilName {sn} not supported" 

855 if bro_id is not None: 

856 msg = f"{msg} (found at broId {bro_id})" 

857 logger.warning(f"{msg}. Please add {sn} to lithology_properties.") 

858 continue 

859 ps = lithology_properties[sn] 

860 if isinstance(ps, dict): 

861 ps = [ps] 

862 for p in ps: 

863 xy = (left, z - df.at[index, "upperBoundary"]) 

864 w = p["width"] * width if "width" in p else width 

865 h = df.at[index, "upperBoundary"] - df.at[index, "lowerBoundary"] 

866 hatch = p["hatch"] * hatch_factor if "hatch" in p else None 

867 h = ax.add_patch( 

868 Rectangle(xy, w, h, facecolor=p["color"], hatch=hatch, edgecolor="k") 

869 ) 

870 h._hatch_color = hatch_color 

871 h._hatch_linewidth = hatch_linewidth 

872 left = left + w 

873 handles.append(h) 

874 return handles 

875 

876 

877def descriptive_borehole_log( 

878 bhr, 

879 attr="descriptiveBoreholeLog", 

880 soil_name_column="geotechnicalSoilName", 

881 figsize=None, 

882 width=0.2, 

883 ylabel=None, 

884 nap=True, 

885): 

886 """ 

887 Generate a descriptive borehole log visualization. 

888 

889 Parameters 

890 ---------- 

891 bhr : object 

892 Borehole object containing descriptive log data, offset, and bored interval information. 

893 soil_name_column : str, optional 

894 Name of the column containing soil classifications. Default is 

895 "geotechnicalSoilName". Other options include "soilNameNEN5104", 

896 "standardSoilName" or "soilName" depending on data source. 

897 figsize : tuple, optional 

898 Figure size as (width, height) in inches. If None, uses matplotlib default. 

899 width : float, default=0.2 

900 Width of each borehole column in the plot. 

901 ylabel : str, optional 

902 Label for the y-axis. If None, defaults to "z (m t.o.v. NAP)" if nap=True, 

903 or "z (m t.o.v. maaiveld)" if nap=False. 

904 nap : bool, default=True 

905 If True, use NAP (Normaal Amsterdams Peil) reference level for depth. 

906 If False, use ground level (maaiveld) as reference. 

907 

908 Returns 

909 ------- 

910 f : matplotlib.figure.Figure 

911 The generated figure object. 

912 ax : matplotlib.axes.Axes 

913 The axes object containing the plot. 

914 """ 

915 if nap: 

916 z = bhr.offset 

917 else: 

918 z = 0.0 

919 

920 if ylabel is None: 

921 if nap: 

922 ylabel = "z (m t.o.v. NAP)" 

923 else: 

924 ylabel = "z (m t.o.v. maaiveld)" 

925 

926 f, ax = plt.subplots(figsize=figsize, layout="constrained") 

927 xticks = [] 

928 xticklabels = [] 

929 df = getattr(bhr, attr) 

930 if not isinstance(df, list): 

931 df = [df] 

932 for x, bl in enumerate(df): 

933 df = bl["layer"] 

934 bro_lithology_advanced( 

935 df, x=x, width=width, z=z, ax=ax, soil_name_column=soil_name_column 

936 ) 

937 xticks.append(x) 

938 xticklabels.append(bl["descriptionQuality"]) 

939 ax.set_xlim(-0.5, x + 0.5) 

940 ax.set_ylim(z - bhr.boredInterval["endDepth"].max(), z) 

941 ax.set_xticks(xticks) 

942 ax.set_xticklabels(xticklabels) 

943 ax.set_ylabel(ylabel) 

944 ax.set_axisbelow(True) 

945 ax.grid() 

946 return f, ax