sgf-parser 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sgf_parser/__init__.py ADDED
@@ -0,0 +1 @@
1
+ from sgf_parser.parser import Parser
@@ -0,0 +1,44 @@
1
+ """
2
+ Datetime utilities for converting to and from datetime.datetime, json, naive and time zone aware
3
+ """
4
+
5
+ from datetime import datetime, time
6
+
7
+ import dateutil.parser
8
+
9
+
10
+ def convert_str_to_datetime(date_string: str | None) -> datetime | None:
11
+ """
12
+ Guess what datetime is in the string
13
+ """
14
+ if not date_string or not isinstance(date_string, str):
15
+ return None
16
+
17
+ try:
18
+ # The ISO 8601 format specifies that the time portion is separated from the date portion by a `T` character.
19
+ if len(date_string) > 8 and "T" in date_string or len(date_string) == 8:
20
+ return dateutil.parser.isoparse(date_string)
21
+ except ValueError:
22
+ pass
23
+
24
+ try:
25
+ return dateutil.parser.parse(date_string, parserinfo=dateutil.parser.parserinfo(yearfirst=True, dayfirst=True))
26
+ except ValueError:
27
+ pass
28
+
29
+ return None
30
+
31
+
32
+ def convert_str_to_time(time_string: str | None) -> time | None:
33
+ """
34
+ Guess what time is in the string
35
+ """
36
+ if not time_string:
37
+ return None
38
+
39
+ try:
40
+ return dateutil.parser.parse(f"1970-01-01 {time_string}").time()
41
+ except ValueError:
42
+ pass
43
+
44
+ return None
@@ -0,0 +1,12 @@
1
+ from sgf_parser.models.method_type import MethodType
2
+
3
+ from sgf_parser.models.types import StopCode, ParseState
4
+ from sgf_parser.models.method import Method, MethodData
5
+ from sgf_parser.models.method_cpt import MethodCPT, MethodCPTData
6
+ from sgf_parser.models.method_dp import MethodDP, MethodDPData
7
+ from sgf_parser.models.method_dt import MethodDT, MethodDTData
8
+ from sgf_parser.models.method_rp import MethodRP, MethodRPData
9
+ from sgf_parser.models.method_srs import MethodSRS, MethodSRSData
10
+ from sgf_parser.models.method_svt import MethodSVT, MethodSVTData
11
+ from sgf_parser.models.method_tot import MethodTOT, MethodTOTData
12
+ from sgf_parser.models.method_wst import MethodWST, MethodWSTData
@@ -0,0 +1,447 @@
1
+ import abc
2
+ import re
3
+ from datetime import datetime, time
4
+ from decimal import Decimal
5
+ from typing import Any
6
+
7
+ from pydantic import BaseModel, Field, AliasChoices, model_validator
8
+
9
+ from sgf_parser.datetime_parser import convert_str_to_datetime, convert_str_to_time
10
+ from sgf_parser.models import MethodType
11
+ from sgf_parser.models.types import FlushingVariant, HammeringVariant, RotationVariant
12
+
13
+
14
+ class MethodData(BaseModel, abc.ABC):
15
+ @classmethod
16
+ def _fix_malformed_data(cls, code: str) -> str | None:
17
+ """Wrong K codes as "4,0" will be converted to "40"."""
18
+ return re.sub("[^0-9]", "", code)
19
+
20
+ @classmethod
21
+ def _extract_comment_code(cls, data: dict[str, Any]) -> tuple[int, str | None]:
22
+ """
23
+ If more than one code, prioritize the codes in the following order:
24
+ Range 40-43 before any other code
25
+ Store the first code that matches the priority in `K` and move the rest to `T` as string
26
+ """
27
+ if ", " in data["K"]:
28
+ codes = data["K"].split(", ")
29
+ sorted_codes = sorted(
30
+ codes,
31
+ key=lambda code: "0"
32
+ if code in ("40", "41", "42", "43")
33
+ else (" " if code in ("90", "91", "92", "93", "94", "95", "96", "97", "98", "99") else code),
34
+ reverse=False,
35
+ )
36
+ code = sorted_codes[0]
37
+ rest = ", ".join(sorted_codes[1:]) if len(sorted_codes) > 1 else None
38
+ elif data["K"].isdecimal():
39
+ code = data["K"]
40
+ rest = None
41
+ else:
42
+ code = cls._fix_malformed_data(data["K"])
43
+ rest = None
44
+
45
+ return int(code), rest
46
+
47
+ @model_validator(mode="before")
48
+ @classmethod
49
+ def comment_code_format(cls, data: Any) -> Any:
50
+ """
51
+ The comment code we return should be an integer.
52
+ But there are string variants of the codes that we need to convert to integers.
53
+ Sometimes we get more than one code on a data row, then we need to prioritize what code to keep.
54
+ """
55
+ if isinstance(data, dict):
56
+ if "K" in data and data["K"] is not None:
57
+ # We want to interpret K as a stop code (with integer value)
58
+ # sometimes K is a string with e.g. "SAND", in that case we move it to T
59
+ K_is_digit = any(char.isdigit() for char in data["K"])
60
+
61
+ if not K_is_digit:
62
+ # move it to T (remarks column)
63
+ if "T" not in data:
64
+ data["T"] = data["K"]
65
+ else:
66
+ data["T"] = f"{data['K']}, {data['T']}"
67
+
68
+ del data["K"]
69
+
70
+ else:
71
+ # we identify the most important stop code, and move the rest to T
72
+ _code, _rest = cls._extract_comment_code(data)
73
+ data["K"] = _code
74
+ if _rest:
75
+ if "T" not in data:
76
+ data["T"] = _rest
77
+ else:
78
+ data["T"] = f"{_rest}, {data['T']}"
79
+
80
+ return data
81
+
82
+ # "K": "comment_code", # "comment_code"
83
+ comment_code: int | None = Field(None, alias="K")
84
+ remarks: str | None = Field(None, alias="T")
85
+
86
+ @model_validator(mode="before")
87
+ @classmethod
88
+ def penetration_rate_validator(cls, data: Any) -> Any:
89
+ """
90
+ If the penetration rate (B mm/s) is not set, but C is (s/0.2m) then convert C to B and set B.
91
+ """
92
+ if isinstance(data, dict):
93
+ if ("B" not in data or data["B"] is None) and "C" in data and data["C"] is not None:
94
+ # B is not set, but C is, convert C to B
95
+ try:
96
+ data["B"] = 200 / float(data["C"])
97
+ except (ZeroDivisionError, ValueError):
98
+ data["B"] = None
99
+
100
+ return data
101
+
102
+ @model_validator(mode="before")
103
+ @classmethod
104
+ def torque_validator(cls, data: Any) -> Any:
105
+ """
106
+ If the torque V (kNm) is not set, but AB is (Nm) then convert AB to V and set V.
107
+ """
108
+ if isinstance(data, dict):
109
+ if ("V" not in data or data["V"] is None) and "AB" in data and data["AB"] is not None:
110
+ try:
111
+ data["V"] = float(data["AB"]) / 1000
112
+ except ValueError:
113
+ data["V"] = None
114
+
115
+ return data
116
+
117
+ @model_validator(mode="before")
118
+ @classmethod
119
+ def ramming_validator(cls, data: Any) -> Any:
120
+ """
121
+ If the ramming S (blows/0.2m) is not set, but SA is (blows/0.1m) then convert SA to S and set S.
122
+ """
123
+ if isinstance(data, dict):
124
+ if ("S" not in data or data["S"] is None) and "SA" in data and data["SA"] is not None:
125
+ try:
126
+ data["S"] = float(data["SA"]) * 2
127
+ except ValueError:
128
+ data["S"] = None
129
+
130
+ return data
131
+
132
+ def __repr__(self):
133
+ return f"<{self.__class__.__name__} {self.depth}>"
134
+
135
+
136
+ # class Method(BaseModel, abc.ABC):
137
+ class Method(BaseModel):
138
+ _flushing_variant: FlushingVariant | None = None
139
+ _current_flushing_active_state: bool = False
140
+ _hammering_variant: HammeringVariant | None = None
141
+ _current_hammer_active_state: bool = False
142
+ _rotation_variant: RotationVariant | None = None
143
+ _current_increased_rotation_state: bool = False
144
+
145
+ def __init__(self, **kwargs):
146
+ super().__init__(**kwargs)
147
+
148
+ def post_processing(self):
149
+ pass
150
+
151
+ def detect_flushing_rule(self) -> FlushingVariant:
152
+ """
153
+ Call this with the method data before parsing the method data.
154
+
155
+ The result of calling this method will set the self.detected_flushing_variant to either use the "K" code if any
156
+ regulating the flushing are present, the "AR" (flushing on/off) code or the "I" (flushing pressure) code.
157
+ """
158
+ if self._flushing_variant:
159
+ return self._flushing_variant
160
+
161
+ if any(
162
+ [
163
+ row.comment_code in (72, 73, 76, 77)
164
+ or any(x in (72, 73, 76, 77) for x in self.extract_codes(row.remarks))
165
+ for row in self.method_data
166
+ ]
167
+ ):
168
+ self._flushing_variant = FlushingVariant.CODE_K
169
+ elif any([getattr(row, "flushing") is not None for row in self.method_data]):
170
+ self._flushing_variant = FlushingVariant.CODE_AR
171
+ else:
172
+ self._flushing_variant = FlushingVariant.CODE_I
173
+
174
+ return self._flushing_variant
175
+
176
+ @classmethod
177
+ def extract_codes(cls, remarks: str | None) -> tuple[int, ...]:
178
+ """
179
+ Extract any two-digit codes from the remarks string.
180
+
181
+ Must be on the format "
182
+ """
183
+ if not remarks:
184
+ return tuple()
185
+
186
+ result = re.findall(r"(?:^| )(\d\d)(?:,|$)", remarks)
187
+ return tuple(int(r) for r in result)
188
+
189
+ def is_flushing_active(
190
+ self,
191
+ data_row, #: "MethodCPTData" | "MethodTOTData" | "MethodRPData",
192
+ ) -> bool:
193
+ """
194
+ Indicate if flushing is active at given depth.
195
+
196
+ The following priority should be used to figure out if flushing is active:
197
+
198
+ 1. Check K (kode) regulating flushing in file, use only K codes
199
+ 2. If no K codes present in file, then check if "AR" code is present and has
200
+ a value (0 or 0.0 = off, 1 or 1.0 = on)
201
+ 3. If no "AR" code is present in the file, then check if "I" (flushing pressure) > 0.1
202
+ 4. Otherwise, return False
203
+
204
+ Codes used:
205
+ Kode 72 (flushing on)
206
+ Kode 73 (flushing off)
207
+ Kode 76 (hammer and flushing on)
208
+ Kode 77 (hammer and flushing off)
209
+ """
210
+ if self._flushing_variant == FlushingVariant.CODE_K:
211
+ if data_row.comment_code in (72, 76) or any(x in (72, 76) for x in self.extract_codes(data_row.remarks)):
212
+ self._current_flushing_active_state = True
213
+ # TODO: check remark for extra codes
214
+ elif data_row.comment_code in (73, 77) or any(x in (73, 77) for x in self.extract_codes(data_row.remarks)):
215
+ self._current_flushing_active_state = False
216
+
217
+ elif self._flushing_variant == FlushingVariant.CODE_AR:
218
+ if data_row.flushing is not None:
219
+ self._current_flushing_active_state = data_row.flushing
220
+
221
+ elif self._flushing_variant == FlushingVariant.CODE_I:
222
+ if data_row.flushing_pressure is not None:
223
+ if data_row.flushing_pressure > Decimal("0.1"):
224
+ self._current_flushing_active_state = True
225
+ else:
226
+ self._current_flushing_active_state = False
227
+
228
+ return self._current_flushing_active_state
229
+
230
+ def detect_hammering_rule(self) -> HammeringVariant | None:
231
+ """
232
+ Call this with the method data loaded before parsing the hammering in the method data.
233
+
234
+ The result of calling this method will set the self._hammering_variant to either use the "K" code if
235
+ any regulating the hammering are present, the "AP" (hammering on/off) code.
236
+ """
237
+ if self._hammering_variant:
238
+ return self._hammering_variant
239
+
240
+ if any(
241
+ [
242
+ row.comment_code in (74, 75, 76, 77)
243
+ or any(x in (74, 75, 76, 77) for x in self.extract_codes(row.remarks))
244
+ for row in self.method_data
245
+ ]
246
+ ):
247
+ self._hammering_variant = HammeringVariant.K
248
+ else:
249
+ self._hammering_variant = HammeringVariant.AP
250
+
251
+ return self._hammering_variant
252
+
253
+ def is_hammer_active(
254
+ self,
255
+ data_row, #: models.MethodCPTData| models.MethodTOTData| models.MethodRPData| models.MethodSRSData,
256
+ ) -> bool:
257
+ """
258
+ Indicate if hammer is active at given depth.
259
+
260
+ The following priority should be used to figure out if the hammer is active:
261
+
262
+ 1. Check K (kode)
263
+ 2. Check "AP" value (0 or 0.0 = off, 1 or 1.0 = on)
264
+ 3. Otherwise, return False
265
+
266
+ Codes used:
267
+ Kode 74 (hammer on)
268
+ Kode 75 (hammer off)
269
+ Kode 76 (hammer and flushing on)
270
+ Kode 77 (hammer and flushing off)
271
+ """
272
+ if self._hammering_variant == HammeringVariant.K:
273
+ if data_row.comment_code in (74, 76) or any(x in (74, 76) for x in self.extract_codes(data_row.remarks)):
274
+ self._current_hammer_active_state = True
275
+ return self._current_hammer_active_state
276
+ elif data_row.comment_code in (75, 77) or any(x in (75, 77) for x in self.extract_codes(data_row.remarks)):
277
+ self._current_hammer_active_state = False
278
+ return self._current_hammer_active_state
279
+
280
+ elif self._hammering_variant == HammeringVariant.AP:
281
+ if data_row.hammering is not None:
282
+ self._current_hammer_active_state = data_row.hammering
283
+ return self._current_hammer_active_state
284
+
285
+ return self._current_hammer_active_state
286
+
287
+ def detect_increased_rotation_rule(self) -> RotationVariant | None:
288
+ """
289
+ Call this with the method data before updating the increased rotation in the method data.
290
+
291
+ The result of calling this method will set the self._increased_rotation_variant to either use the
292
+ "K" code if any regulating the increased rotation are present, the "AQ" (increased rotation on/off) code
293
+ or the "R" (rotation rate) code.
294
+ """
295
+
296
+ if self._rotation_variant:
297
+ return self._rotation_variant
298
+
299
+ if any(
300
+ [
301
+ row.comment_code in (70, 71) or any(x in (70, 71) for x in self.extract_codes(row.remarks))
302
+ for row in self.method_data
303
+ ]
304
+ ):
305
+ self._rotation_variant = RotationVariant.K
306
+ elif any([row.increased_rotation_rate is not None for row in self.method_data]):
307
+ self._rotation_variant = RotationVariant.AQ
308
+ else:
309
+ self._rotation_variant = RotationVariant.R
310
+
311
+ return self._rotation_variant
312
+
313
+ def is_increased_rotation_active(
314
+ self,
315
+ data_row, #: models.MethodCPTData | models.MethodTOTData | models.MethodRPData,
316
+ ) -> bool:
317
+ """
318
+ Indicate if increased rotation speed is active at a given depth.
319
+
320
+ The following priority should be used to figure out if increased rotation speed is active:
321
+
322
+ 1. Check K (kode)
323
+ 2. Check "AQ" value (0 or 0.0 = off, 1 or 1.0 = on)
324
+ 3. If rotation (R) > 35 rpm set increased rotation
325
+ 4. Otherwise, return False
326
+
327
+ Codes used:
328
+ Kode 70 (increased rotation speed on)
329
+ Kode 71 (increased rotation speed off)
330
+ """
331
+ if self._rotation_variant == RotationVariant.K:
332
+ if data_row.comment_code == 70:
333
+ self._current_increased_rotation_state = True
334
+ elif data_row.comment_code == 71:
335
+ self._current_increased_rotation_state = False
336
+ elif self._rotation_variant == RotationVariant.AQ:
337
+ if data_row.increased_rotation_rate is not None:
338
+ self._current_increased_rotation_state = data_row.increased_rotation_rate
339
+ else:
340
+ if data_row.rotation_rate is not None:
341
+ if data_row.rotation_rate > 35:
342
+ self._current_increased_rotation_state = True
343
+ else:
344
+ self._current_increased_rotation_state = False
345
+
346
+ return self._current_increased_rotation_state
347
+
348
+ def flushing_update(self):
349
+ """
350
+ Update flushing
351
+
352
+ """
353
+ self._flushing_variant = self.detect_flushing_rule()
354
+
355
+ for data in self.method_data:
356
+ data.flushing = self.is_flushing_active(data)
357
+
358
+ def hammering_update(self):
359
+ """
360
+ Update hammering
361
+
362
+ """
363
+ self._hammering_variant = self.detect_hammering_rule()
364
+
365
+ for data in self.method_data:
366
+ data.hammering = self.is_hammer_active(data)
367
+
368
+ def rotation_update(self):
369
+ """
370
+ Update rotation
371
+
372
+ """
373
+ self._rotation_variant = self.detect_increased_rotation_rule()
374
+
375
+ for data in self.method_data:
376
+ data.increased_rotation_rate = self.is_increased_rotation_active(data)
377
+
378
+ @model_validator(mode="before")
379
+ @classmethod
380
+ def guess_date_format(cls, data: Any) -> Any:
381
+ if isinstance(data, dict):
382
+ if "HI" in data and data["HI"] is not None:
383
+ data["HI"] = convert_str_to_time(data["HI"])
384
+
385
+ if "KD" in data and data["KD"] is not None and "HD" not in data:
386
+ # If KD is present, but HD is not, set HD since it is the same as KD
387
+ data["HD"] = convert_str_to_datetime(data["KD"])
388
+
389
+ elif "HD" in data and data["HD"] is not None:
390
+ data["HD"] = convert_str_to_datetime(data["HD"])
391
+
392
+ if "HI" in data and data["HI"] is not None and "HD" in data and data["HD"] is not None:
393
+ data["HD"] = datetime.combine(data["HD"], data["HI"])
394
+
395
+ return data
396
+
397
+ method_type: MethodType
398
+ method_data_type: type[MethodData]
399
+
400
+ # name: str | None = None
401
+
402
+ location_name: str | None = Field(None, alias="KP")
403
+ project_number: str | None = Field(None, alias="HJ")
404
+ method_type_string: str | None = Field(None, alias="HM")
405
+
406
+ # HX, HY, HZ
407
+ point_x: float | None = Field(None, alias="HX")
408
+ point_y: float | None = Field(None, alias="HY")
409
+ point_z: float | None = Field(None, alias="HZ")
410
+
411
+ # "HD": "conducted_at", # Date
412
+ # # "KD": "conducted_at", # Date
413
+ conducted_at: datetime | None = Field(None, validation_alias=AliasChoices("HD", "KD"))
414
+ conducted_time: time | None = Field(None, alias="HI")
415
+ # "HC": "serial_number",
416
+ serial_number: str | None = Field(None, alias="HC")
417
+
418
+ # "HO": "predrilling_depth",
419
+ predrilling_depth: Decimal = Field(Decimal("0"), alias="HO")
420
+
421
+ # "HQ": "conducted_by",
422
+ conducted_by: str | None = Field(None, alias="HQ")
423
+
424
+ # "HN": "cone_reference",
425
+ cone_reference: str | None = Field(None, alias="HN")
426
+
427
+ # # "HG": "groundwater_level",
428
+ # "HP": "water_depth",
429
+
430
+ # "HT": "remarks",
431
+ remarks: str | None = Field(None, alias="HT")
432
+
433
+ # "MA": "cone_area_ratio", # same as header code IE
434
+ # "IE": "cone_area_ratio", # same as header code MA
435
+ cone_area_ratio: Decimal | None = Field(None, validation_alias=AliasChoices("IE", "MA"))
436
+
437
+ # "MB": "sleeve_area_ratio", # same as header code IF
438
+ # "IF": "sleeve_area_ratio", # same as header code MB
439
+ sleeve_area_ratio: Decimal | None = Field(None, validation_alias=AliasChoices("IF", "MB"))
440
+
441
+ # "IV": "vane_diameter", # Not in spec, but seen in example files
442
+ vane_diameter: Decimal | None = Field(None, alias="IV", description="Diameter of the vane used (mm).")
443
+
444
+ method_data: list[MethodData]
445
+
446
+ def __repr__(self):
447
+ return f"<{self.__class__.__name__} {self.method_type} method_data={self.method_data!r}>"