Coverage for brodata/cpt.py: 81%
105 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 tempfile
3from functools import partial
5import pandas as pd
7from . import bro
9logger = logging.getLogger(__name__)
12class ConePenetrationTest(bro.FileOrUrl):
13 """Class to represent a Cone Penetration Test (CPT) from the BRO."""
15 _rest_url = "https://publiek.broservices.nl/sr/cpt/v1"
16 _xmlns = "http://www.broservices.nl/xsd/dscpt/1.1"
17 _char = "CPT_C"
19 def _read_contents(self, tree):
20 ns = {
21 "brocom": "http://www.broservices.nl/xsd/brocommon/3.0",
22 "gml": "http://www.opengis.net/gml/3.2",
23 "cptcommon": "http://www.broservices.nl/xsd/cptcommon/1.1",
24 "xmlns": self._xmlns,
25 }
26 cpt = self._get_main_object(tree, "CPT_O", ns)
27 for key in cpt.attrib:
28 setattr(self, key.split("}", 1)[1], cpt.attrib[key])
29 for child in cpt:
30 key = self._get_tag(child)
31 if len(child) == 0:
32 setattr(self, key, child.text)
33 elif key == "standardizedLocation":
34 self._read_standardized_location(child)
35 elif key == "deliveredLocation":
36 self._read_delivered_location(child)
37 elif key in ["researchReportDate"]:
38 setattr(self, key, self._read_date(child))
39 elif key in ["deliveredVerticalPosition", "registrationHistory"]:
40 self._read_children_of_children(child)
41 elif key in ["conePenetrometerSurvey"]:
42 for grandchild in child:
43 key = self._get_tag(grandchild)
44 if len(grandchild) == 0:
45 setattr(self, key, grandchild.text)
46 elif key in [
47 "finalProcessingDate",
48 "trajectory",
49 "conePenetrometer",
50 "procedure",
51 ]:
52 self._read_children_of_children(grandchild)
53 elif key == "parameters":
54 self._read_parameters(grandchild)
55 elif key == "conePenetrationTest" or key == "dissipationTest":
56 self._read_cone_penetration_test(grandchild, key)
57 else:
58 self._warn_unknown_tag(key)
59 elif key == "additionalInvestigation":
60 self._read_additional_investigation(child)
61 else:
62 self._warn_unknown_tag(key)
63 if hasattr(self, "conePenetrationTest") and hasattr(self, "parameters"):
64 self.conePenetrationTest.columns = self.parameters.index
65 if "penetrationLength" in self.conePenetrationTest.columns:
66 self.conePenetrationTest = self.conePenetrationTest.set_index(
67 "penetrationLength"
68 )
70 def _read_parameters(self, node):
71 self.parameters = pd.Series()
72 for child in node:
73 key = self._get_tag(child)
74 self.parameters[key] = child.text
76 def _read_cone_penetration_test(self, node, name):
77 for child in node:
78 key = self._get_tag(child)
79 if key in ["phenomenonTime", "resultTime"]:
80 setattr(self, f"{name}_{key}", self._read_time_instant(child))
81 elif key in [
82 "procedure",
83 "observedProperty",
84 "featureOfInterest",
85 "penetrationLength",
86 ]:
87 self._read_children_of_children(child)
88 elif key in ["cptResult", "disResult"]:
89 setattr(self, name, self._read_data_array(child))
90 else:
91 self._warn_unknown_tag(key)
93 def _read_additional_investigation(self, node):
94 for child in node:
95 key = self._get_tag(child)
96 if len(child) == 0:
97 setattr(self, key, child.text)
98 elif key == "removedLayer":
99 if not hasattr(self, key):
100 self.removedLayer = []
101 d = {}
102 self._read_children_of_children(
103 child,
104 d=d,
105 to_float=["upperBoundary", "lowerBoundary"],
106 to_int="sequenceNumber",
107 )
108 self.removedLayer.append(d)
109 if hasattr(self, "removedLayer"):
110 self.removedLayer = pd.DataFrame(self.removedLayer)
111 if "sequenceNumber" in self.removedLayer.columns:
112 self.removedLayer = self.removedLayer.set_index("sequenceNumber")
115def get_graph_types(timeout=5):
116 """
117 Get the graph types that can be generated for CPT by the REST API of the BRO.
119 Parameters
120 ----------
121 timeout : int or float, optional
122 A number indicating how many seconds to wait for the client to make a connection
123 and/or send a response. The default is 5.
125 Returns
126 -------
127 pd.DataFrame
128 A Pandas DataFrame that contains the supported graph types, with the columns
129 'name' and 'description'. The index of this DataFrame contains the strings that
130 can be used for the graphType-argument in nlmod.cpt.graph().
132 """
133 url = "https://publiek.broservices.nl/sr/cpt/v1/result/graph/types"
134 r = bro.util.get_with_rate_limit(url)
135 supported_graphs = r.json()["supportedGraphs"]
136 assert len(supported_graphs) == 1
137 return pd.DataFrame(supported_graphs[0]["graphs"]).set_index("graphType")
140def graph(
141 xml_file, graphType="cptCombinedLength", to_file=None, timeout=5, return_fname=False
142):
143 """
144 Generate a svg-graph of a cpt-file (ConePenetrationTest).
146 Parameters
147 ----------
148 xml_file : str
149 The filename of the xml-file to generate a graphical representation of.
150 graphType : str, optional
151 The type of graph. Run `brodata.cpt.get_graph_types()` to view available graph
152 types. The default is "cptCombinedLength".
153 to_file : str, optional
154 The filename to save the svg-file to. The default is None.
155 timeout : int or float, optional
156 A number indicating how many seconds to wait for the client to make a connection
157 and/or send a response. The default is 5.
158 return_fname : bool, optional
159 If True, Return the filename of the svg-file. The default is False.
161 Returns
162 -------
163 IPython.display.SVG or str
164 A graphical representation of the svg-file or the filename of the svg-file.
166 """
167 url = "https://publiek.broservices.nl/sr/cpt/v1/result/graph/dispatch"
169 params = {"graphType": graphType}
170 with open(xml_file, "rb") as data:
171 r = bro.util.post_with_rate_limit(
172 url, data=data, timeout=timeout, params=params
173 )
174 r.raise_for_status()
175 if to_file is None:
176 to_file = tempfile.NamedTemporaryFile(suffix=".svg").name
177 with open(to_file, "w", encoding="utf-8") as f:
178 f.write(r.text)
179 if return_fname:
180 return to_file
181 else:
182 from IPython.display import SVG
184 return SVG(to_file)
187cl = ConePenetrationTest
189get_bro_ids_of_bronhouder = partial(bro._get_bro_ids_of_bronhouder, cl=cl)
190get_bro_ids_of_bronhouder.__doc__ = bro._get_bro_ids_of_bronhouder.__doc__
192get_data_for_bro_ids = partial(bro._get_data_for_bro_ids, cl)
193get_data_for_bro_ids.__doc__ = bro._get_data_for_bro_ids.__doc__
195get_characteristics = partial(bro._get_characteristics, cl)
196get_characteristics.__doc__ = bro._get_characteristics.__doc__
198get_data_in_extent = partial(bro._get_data_in_extent, cl)
199get_data_in_extent.__doc__ = bro._get_data_in_extent.__doc__