sgf-parser 0.0.1a1__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,9 @@
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_rp import MethodRP, MethodRPData
7
+ from sgf_parser.models.method_srs import MethodSRS, MethodSRSData
8
+ from sgf_parser.models.method_svt import MethodSVT, MethodSVTData
9
+ from sgf_parser.models.method_tot import MethodTOT, MethodTOTData
@@ -0,0 +1,386 @@
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
+ return re.sub("[^0-9]", "", code)
18
+
19
+ @classmethod
20
+ def _extract_comment_code(cls, data: dict[str, Any]) -> tuple[int, str | None]:
21
+ """
22
+ If more than one code, prioritize the codes in the following order:
23
+ Range 40-43 before any other code
24
+ Store the first code that matches the priority in `K` and move the rest to `T` as string
25
+ """
26
+ if ", " in data["K"]:
27
+ codes = data["K"].split(", ")
28
+ sorted_codes = sorted(
29
+ codes,
30
+ key=lambda code: "0"
31
+ if code in ("40", "41", "42", "43")
32
+ else (" " if code in ("90", "91", "92", "93", "94", "95", "96", "97", "98", "99") else code),
33
+ reverse=False,
34
+ )
35
+ code = sorted_codes[0]
36
+ rest = ", ".join(sorted_codes[1:]) if len(sorted_codes) > 1 else None
37
+ elif data["K"].isdecimal():
38
+ code = data["K"]
39
+ rest = None
40
+ else:
41
+ code = cls._fix_malformed_data(data["K"])
42
+ rest = None
43
+
44
+ return int(code), rest
45
+
46
+ @model_validator(mode="before")
47
+ @classmethod
48
+ def comment_code_format(cls, data: Any) -> Any:
49
+ """
50
+ The comment code we return should be an integer.
51
+ But there are string variants of the codes that we need to convert to integers.
52
+ Sometimes we get more than one code on a data row, then we need to prioritize what code to keep.
53
+ """
54
+ if isinstance(data, dict):
55
+ # Detect string variants of the comment code and convert them to integers
56
+ if "K" in data and data["K"] is not None:
57
+ _code, _rest = cls._extract_comment_code(data)
58
+ data["K"] = _code
59
+ if _rest:
60
+ if data["T"]:
61
+ data["T"] = f"{_rest}, {data['T']}"
62
+ else:
63
+ data["T"] = _rest
64
+
65
+ return data
66
+
67
+ # "K": "comment_code", # "comment_code"
68
+ comment_code: int | None = Field(None, alias="K")
69
+ remarks: str | None = Field(None, alias="T")
70
+
71
+ def __repr__(self):
72
+ return f"<{self.__class__.__name__} {self.depth}>"
73
+
74
+
75
+ # class Method(BaseModel, abc.ABC):
76
+ class Method(BaseModel):
77
+ _flushing_variant: FlushingVariant | None = None
78
+ _current_flushing_active_state: bool = False
79
+ _hammering_variant: HammeringVariant | None = None
80
+ _current_hammer_active_state: bool = False
81
+ _rotation_variant: RotationVariant | None = None
82
+ _current_increased_rotation_state: bool = False
83
+
84
+ def __init__(self, **kwargs):
85
+ super().__init__(**kwargs)
86
+
87
+ def post_processing(self):
88
+ pass
89
+
90
+ def detect_flushing_rule(self) -> FlushingVariant:
91
+ """
92
+ Call this with the method data before parsing the method data.
93
+
94
+ The result of calling this method will set the self.detected_flushing_variant to either use the "K" code if any
95
+ regulating the flushing are present, the "AR" (flushing on/off) code or the "I" (flushing pressure) code.
96
+ """
97
+ if self._flushing_variant:
98
+ return self._flushing_variant
99
+
100
+ if any(
101
+ [
102
+ row.comment_code in (72, 73, 76, 77)
103
+ or any(x in (72, 73, 76, 77) for x in self.extract_codes(row.remarks))
104
+ for row in self.method_data
105
+ ]
106
+ ):
107
+ self._flushing_variant = FlushingVariant.CODE_K
108
+ elif any([getattr(row, "flushing") is not None for row in self.method_data]):
109
+ self._flushing_variant = FlushingVariant.CODE_AR
110
+ else:
111
+ self._flushing_variant = FlushingVariant.CODE_I
112
+
113
+ return self._flushing_variant
114
+
115
+ @classmethod
116
+ def extract_codes(cls, remarks: str | None) -> tuple[int, ...]:
117
+ """
118
+ Extract any two-digit codes from the remarks string.
119
+
120
+ Must be on the format "
121
+ """
122
+ if not remarks:
123
+ return tuple()
124
+
125
+ result = re.findall(r"(?:^| )(\d\d)(?:,|$)", remarks)
126
+ return tuple(int(r) for r in result)
127
+
128
+ def is_flushing_active(
129
+ self,
130
+ data_row, #: "MethodCPTData" | "MethodTOTData" | "MethodRPData",
131
+ ) -> bool:
132
+ """
133
+ Indicate if flushing is active at given depth.
134
+
135
+ The following priority should be used to figure out if flushing is active:
136
+
137
+ 1. Check K (kode) regulating flushing in file, use only K codes
138
+ 2. If no K codes present in file, then check if "AR" code is present and has
139
+ a value (0 or 0.0 = off, 1 or 1.0 = on)
140
+ 3. If no "AR" code is present in the file, then check if "I" (flushing pressure) > 0.1
141
+ 4. Otherwise, return False
142
+
143
+ Codes used:
144
+ Kode 72 (flushing on)
145
+ Kode 73 (flushing off)
146
+ Kode 76 (hammer and flushing on)
147
+ Kode 77 (hammer and flushing off)
148
+ """
149
+ if self._flushing_variant == FlushingVariant.CODE_K:
150
+ if data_row.comment_code in (72, 76) or any(x in (72, 76) for x in self.extract_codes(data_row.remarks)):
151
+ self._current_flushing_active_state = True
152
+ # TODO: check remark for extra codes
153
+ elif data_row.comment_code in (73, 77) or any(x in (73, 77) for x in self.extract_codes(data_row.remarks)):
154
+ self._current_flushing_active_state = False
155
+
156
+ elif self._flushing_variant == FlushingVariant.CODE_AR:
157
+ if data_row.flushing is not None:
158
+ self._current_flushing_active_state = data_row.flushing
159
+
160
+ elif self._flushing_variant == FlushingVariant.CODE_I:
161
+ if data_row.flushing_pressure is not None:
162
+ if data_row.flushing_pressure > Decimal("0.1"):
163
+ self._current_flushing_active_state = True
164
+ else:
165
+ self._current_flushing_active_state = False
166
+
167
+ return self._current_flushing_active_state
168
+
169
+ def detect_hammering_rule(self) -> HammeringVariant | None:
170
+ """
171
+ Call this with the method data loaded before parsing the hammering in the method data.
172
+
173
+ The result of calling this method will set the self._hammering_variant to either use the "K" code if
174
+ any regulating the hammering are present, the "AP" (hammering on/off) code.
175
+ """
176
+ if self._hammering_variant:
177
+ return self._hammering_variant
178
+
179
+ if any(
180
+ [
181
+ row.comment_code in (74, 75, 76, 77)
182
+ or any(x in (74, 75, 76, 77) for x in self.extract_codes(row.remarks))
183
+ for row in self.method_data
184
+ ]
185
+ ):
186
+ self._hammering_variant = HammeringVariant.K
187
+ else:
188
+ self._hammering_variant = HammeringVariant.AP
189
+
190
+ return self._hammering_variant
191
+
192
+ def is_hammer_active(
193
+ self,
194
+ data_row, #: models.MethodCPTData| models.MethodTOTData| models.MethodRPData| models.MethodSRSData,
195
+ ) -> bool:
196
+ """
197
+ Indicate if hammer is active at given depth.
198
+
199
+ The following priority should be used to figure out if the hammer is active:
200
+
201
+ 1. Check K (kode)
202
+ 2. Check "AP" value (0 or 0.0 = off, 1 or 1.0 = on)
203
+ 3. Otherwise, return False
204
+
205
+ Codes used:
206
+ Kode 74 (hammer on)
207
+ Kode 75 (hammer off)
208
+ Kode 76 (hammer and flushing on)
209
+ Kode 77 (hammer and flushing off)
210
+ """
211
+ if self._hammering_variant == HammeringVariant.K:
212
+ if data_row.comment_code in (74, 76) or any(x in (74, 76) for x in self.extract_codes(data_row.remarks)):
213
+ self._current_hammer_active_state = True
214
+ return self._current_hammer_active_state
215
+ elif data_row.comment_code in (75, 77) or any(x in (75, 77) for x in self.extract_codes(data_row.remarks)):
216
+ self._current_hammer_active_state = False
217
+ return self._current_hammer_active_state
218
+
219
+ elif self._hammering_variant == HammeringVariant.AP:
220
+ if data_row.hammering is not None:
221
+ self._current_hammer_active_state = data_row.hammering
222
+ return self._current_hammer_active_state
223
+
224
+ return self._current_hammer_active_state
225
+
226
+ def detect_increased_rotation_rule(self) -> RotationVariant | None:
227
+ """
228
+ Call this with the method data before updating the increased rotation in the method data.
229
+
230
+ The result of calling this method will set the self._increased_rotation_variant to either use the
231
+ "K" code if any regulating the increased rotation are present, the "AQ" (increased rotation on/off) code
232
+ or the "R" (rotation rate) code.
233
+ """
234
+
235
+ if self._rotation_variant:
236
+ return self._rotation_variant
237
+
238
+ if any(
239
+ [
240
+ row.comment_code in (70, 71) or any(x in (70, 71) for x in self.extract_codes(row.remarks))
241
+ for row in self.method_data
242
+ ]
243
+ ):
244
+ self._rotation_variant = RotationVariant.K
245
+ elif any([row.increased_rotation_rate is not None for row in self.method_data]):
246
+ self._rotation_variant = RotationVariant.AQ
247
+ else:
248
+ self._rotation_variant = RotationVariant.R
249
+
250
+ return self._rotation_variant
251
+
252
+ def is_increased_rotation_active(
253
+ self,
254
+ data_row, #: models.MethodCPTData | models.MethodTOTData | models.MethodRPData,
255
+ ) -> bool:
256
+ """
257
+ Indicate if increased rotation speed is active at a given depth.
258
+
259
+ The following priority should be used to figure out if increased rotation speed is active:
260
+
261
+ 1. Check K (kode)
262
+ 2. Check "AQ" value (0 or 0.0 = off, 1 or 1.0 = on)
263
+ 3. If rotation (R) > 35 rpm set increased rotation
264
+ 4. Otherwise, return False
265
+
266
+ Codes used:
267
+ Kode 70 (increased rotation speed on)
268
+ Kode 71 (increased rotation speed off)
269
+ """
270
+ if self._rotation_variant == RotationVariant.K:
271
+ if data_row.comment_code == 70:
272
+ self._current_increased_rotation_state = True
273
+ elif data_row.comment_code == 71:
274
+ self._current_increased_rotation_state = False
275
+ elif self._rotation_variant == RotationVariant.AQ:
276
+ if data_row.increased_rotation_rate is not None:
277
+ self._current_increased_rotation_state = data_row.increased_rotation_rate
278
+ else:
279
+ if data_row.rotation_rate is not None:
280
+ if data_row.rotation_rate > 35:
281
+ self._current_increased_rotation_state = True
282
+ else:
283
+ self._current_increased_rotation_state = False
284
+
285
+ return self._current_increased_rotation_state
286
+
287
+ def flushing_update(self):
288
+ """
289
+ Update flushing
290
+
291
+ """
292
+ self._flushing_variant = self.detect_flushing_rule()
293
+
294
+ for data in self.method_data:
295
+ data.flushing = self.is_flushing_active(data)
296
+
297
+ def hammering_update(self):
298
+ """
299
+ Update hammering
300
+
301
+ """
302
+ self._hammering_variant = self.detect_hammering_rule()
303
+
304
+ for data in self.method_data:
305
+ data.hammering = self.is_hammer_active(data)
306
+
307
+ def rotation_update(self):
308
+ """
309
+ Update rotation
310
+
311
+ """
312
+ self._rotation_variant = self.detect_increased_rotation_rule()
313
+
314
+ for data in self.method_data:
315
+ data.increased_rotation_rate = self.is_increased_rotation_active(data)
316
+
317
+ @model_validator(mode="before")
318
+ @classmethod
319
+ def guess_date_format(cls, data: Any) -> Any:
320
+ if isinstance(data, dict):
321
+ if "HI" in data and data["HI"] is not None:
322
+ data["HI"] = convert_str_to_time(data["HI"])
323
+
324
+ if "KD" in data and data["KD"] is not None and "HD" not in data:
325
+ # If KD is present, but HD is not, set HD since it is the same as KD
326
+ data["HD"] = convert_str_to_datetime(data["KD"])
327
+
328
+ elif "HD" in data and data["HD"] is not None:
329
+ data["HD"] = convert_str_to_datetime(data["HD"])
330
+
331
+ if "HI" in data and data["HI"] is not None and "HD" in data and data["HD"] is not None:
332
+ data["HD"] = datetime.combine(data["HD"], data["HI"])
333
+
334
+ return data
335
+
336
+ method_type: MethodType
337
+ method_data_type: type[MethodData]
338
+
339
+ # name: str | None = None
340
+
341
+ location_name: str | None = Field(None, alias="KP")
342
+ project_number: str | None = Field(None, alias="HJ")
343
+ method_type_string: str | None = Field(None, alias="HM")
344
+
345
+ # HX, HY, HZ
346
+ point_x: float | None = Field(None, alias="HX")
347
+ point_y: float | None = Field(None, alias="HY")
348
+ point_z: float | None = Field(None, alias="HZ")
349
+
350
+ # "HD": "conducted_at", # Date
351
+ # # "KD": "conducted_at", # Date
352
+ conducted_at: datetime | None = Field(None, validation_alias=AliasChoices("HD", "KD"))
353
+ conducted_time: time | None = Field(None, alias="HI")
354
+ # "HC": "serial_number",
355
+ serial_number: str | None = Field(None, alias="HC")
356
+
357
+ # "HO": "predrilling_depth",
358
+ predrilling_depth: Decimal = Field(0, alias="HO")
359
+
360
+ # "HQ": "conducted_by",
361
+ conducted_by: str | None = Field(None, alias="HQ")
362
+
363
+ # "HN": "cone_reference",
364
+ cone_reference: str | None = Field(None, alias="HN")
365
+
366
+ # # "HG": "groundwater_level",
367
+ # "HP": "water_depth",
368
+
369
+ # "HT": "remarks",
370
+ remarks: str | None = Field(None, alias="HT")
371
+
372
+ # "MA": "cone_area_ratio", # same as header code IE
373
+ # "IE": "cone_area_ratio", # same as header code MA
374
+ cone_area_ratio: Decimal | None = Field(None, validation_alias=AliasChoices("IE", "MA"))
375
+
376
+ # "MB": "sleeve_area_ratio", # same as header code IF
377
+ # "IF": "sleeve_area_ratio", # same as header code MB
378
+ sleeve_area_ratio: Decimal | None = Field(None, validation_alias=AliasChoices("IF", "MB"))
379
+
380
+ # "IV": "vane_diameter", # Not in spec, but seen in example files
381
+ vane_diameter: Decimal | None = Field(None, alias="IV", description="Diameter of the vane used (mm).")
382
+
383
+ method_data: list[MethodData]
384
+
385
+ def __repr__(self):
386
+ return f"<{self.__class__.__name__} {self.method_type} method_data={self.method_data!r}>"