-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathutils.py
More file actions
99 lines (78 loc) · 2.57 KB
/
Copy pathutils.py
File metadata and controls
99 lines (78 loc) · 2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
"""
Util functions
"""
from __future__ import annotations
import logging
from typing import Optional
import numpy as np
LOGGER = logging.getLogger(__name__)
def _parse_coordinate(
value: Optional[str],
deg_len: int,
hemisphere_positive: str,
hemisphere_negative: str,
) -> float:
if value is None:
LOGGER.debug("Coordinate is None")
return np.nan
if not isinstance(value, str):
try:
value = str(value)
except (TypeError, ValueError):
LOGGER.debug("Coordinate has non-string, non-coercible type: %r", value)
return np.nan
value = value.strip()
expected_len = deg_len + 2 + 2 + 1
if len(value) < expected_len:
LOGGER.debug("Coordinate has invalid length: %r", value)
return np.nan
try:
degs = float(value[0:deg_len])
mins = float(value[deg_len:deg_len + 2])
secs = float(value[deg_len + 2:deg_len + 4])
hemisphere = value[deg_len + 4].lower()
except (TypeError, ValueError, IndexError):
LOGGER.debug("Coordinate has invalid numeric format: %r", value)
return np.nan
if hemisphere == hemisphere_negative:
factor = -1.0
elif hemisphere == hemisphere_positive:
factor = 1.0
else:
LOGGER.debug("Coordinate has invalid hemisphere: %r", value)
return np.nan
return factor * (degs + mins / 60 + secs / 3600)
def convert_lat(value: Optional[str]) -> float:
"""
Convert a latitude string in DMS format to decimal degrees.
Parameters
----------
value : Optional[str]
Latitude string encoded as DDMMSSN or DDMMSSS.
Returns
-------
float
Decimal degrees; returns numpy.nan for invalid inputs.
"""
return _parse_coordinate(value, deg_len=2, hemisphere_positive="n", hemisphere_negative="s")
def convert_lon(value: Optional[str]) -> float:
"""
Convert a longitude string in DMS format to decimal degrees.
Parameters
----------
value : Optional[str]
Longitude string encoded as DDDMMSSE or DDDMMSSW.
Returns
-------
float
Decimal degrees; returns numpy.nan for invalid inputs.
"""
return _parse_coordinate(value, deg_len=3, hemisphere_positive="e", hemisphere_negative="w")
def rename_categories(old_categories, codes_meaning):
new_categories = []
for cat in old_categories:
if str(int(cat)) in codes_meaning.index:
new_categories.append(codes_meaning.loc[str(int(cat)), 'meaning'])
else:
new_categories.append(cat)
return new_categories