-
Notifications
You must be signed in to change notification settings - Fork 0
/
dms.py
285 lines (236 loc) · 9.11 KB
/
dms.py
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
from math import isfinite, isnan, floor, fabs
import re
# note Unicode Degree = U+00B0. Prime = U+2032, Double prime = U+2033
DEGREE_CHAR = '°'
MINUTE_CHAR = "'"
SECONDE_CHAR = '"'
SEPARATOR = ''
NONE_VALUE_CHAR = "–"
def parseDMS(dmsStr):
"""
Parse string representing degrees/minutes/seconds (aka DMS) into numeric degrees.
Return a float representing decimal degrees.
Arguments :
dmsStr {string | float} -- Decimal degrees or deg/min/sec in variety of formats.
Allow signed decimal degrees (eg: -0.13) or deg-min-sec optionally suffixed by compass direction (NSEW).
A variety of separators are accepted (eg 3° 37' 09"W).
Seconds and minutes may be omitted.
Example :
> dms.parseDMS("48°51'25.2'N")
> 48.857000
"""
# check for signed decimal degrees without NSEW compass direction, if so return it directly
if isinstance(dmsStr, float) and isfinite(dmsStr):
return float(dmsStr)
tmpStr = str(dmsStr).strip()
# Strip off any sign at the beginning of the string
tmpStr = tmpStr.replace('^-', '')
# Strip off any compass direction at the end of the string
tmpStr = tmpStr.replace('[NSEW]$]', '', re.IGNORECASE)
# Split out separate d/m/s (degree / minute / second)
dms = re.split('[^0-9.]+', tmpStr)
# Remove first list element if it contains empty string (positive or negative sign)
if dms[0] == '':
dms = dms[1:]
# Remove last list element if it contains empty string (compass direction)
if dms[len(dms)-1] == '':
dms = dms[:len(dms)-1]
if (dms == ''):
return None;
# Convert to decimal degrees
dms_length = len(dms)
if dms_length == 3: # 3-part result d/m/s
deg = float(dms[0])/1 + float(dms[1])/60 + float(dms[2])/3600
elif dms_length == 2: # 2-part result d/m
deg = float(dms[0])/1 + float(dms[1])/60
elif dms_length == 1: # Only d (degrees)
deg = float(dms[0])
else:
return None
m = re.match('^-.*|.*[WS]$', dmsStr.strip(), re.IGNORECASE)
if m is not None:
deg = -deg
return float(deg)
def toDMS(deg, dms_format=None, precision=None):
"""
Converts decimal degrees to deg/min/sec format.
Return a deg/min/sec string.
Degree, prime and double-prime symbols are added.
But sign (+|-) is discarded, though no compass direction (NESW) is added.
Arguments :
deg -- {float | int} -- Degrees to be formatted as specified.
dms_format -- {string} -- Return value format as 'd', 'dm', 'dms' for deg, deg+min, deg+min+sec (default=dms)
precision -- {int} -- Number of decimal to use (default: 1 for dms, 2 for dm, 4 for d).
Example :
> dms.toDMS(-48.857000)
> 48°51'25.2''
> dms.toDMS(48.857000, "d", 2)
> 48.86°''
"""
if isnan(deg):
return None
# Define default format, if needed
if dms_format is None:
dms_format = "dms"
if precision is None:
if dms_format in ["d", "deg"]:
precision = 4
elif dms_format in ["dm", "deg+min"]:
precision = 2
elif dms_format in ["dms", "deg+min+sec"]:
precision = 1
else:
dms_format = "dms"
precision = 1
# unsigned result ready for appending compass direction
deg = fabs(deg)
# decimal pattern used to format float at a fixed precision
digits_count = precision + 3
decimal_pattern = "{:0" + str(digits_count) + "." + str(precision) + "f}"
if dms_format in ["d", "deg"]:
# round degrees
d = float(decimal_pattern.format(deg))
# Get decimal part without dot (eg: 5.55 -> 55) and add padding zeros or truncate the string
# to get the asked precision
dp = str(d).split('.')[1]
if (len(dp) < precision):
# insufficient precision : add padding zero(s)
final_width = len(str(d))+ (precision - len(dp))
dms = str(d).ljust(final_width, '0') + DEGREE_CHAR
else:
# d already is at the good precision
dms = str(d) + DEGREE_CHAR
elif dms_format in ["dm", "deg+min"]:
# convert degrees to minutes & round
mn = deg*60
# get component deg/min
d = floor(mn/60)
# pad with trailing zeros
m = float(decimal_pattern.format(mn % 60))
dms = str(d) + '°'+ SEPARATOR + str(m).zfill(2) + MINUTE_CHAR
elif dms_format in ["dms", "deg+min+sec"]:
# convert degrees to seconds & round
sec = deg * 3600
# get component deg/min/sec
d = floor(sec / 3600)
m = floor(sec / 60) % 60
s = float(decimal_pattern.format(sec % 60))
dms = str(d) + '°' + SEPARATOR + str(m).zfill(2) + MINUTE_CHAR + SEPARATOR + str(s).zfill(2) + SECONDE_CHAR
return dms
def toLat(deg, dms_format=None, precision=None):
"""
Converts numeric degrees to deg/min/sec latitude (2-digit degrees, suffixed with N/S).
Return a string representing degrees formatted as deg/min/secs according to specified format.
Arguments :
deg -- {float | int} -- Degrees to be formatted as specified.
dms_format -- {string} -- Return value format as 'd', 'dm', 'dms' for deg, deg+min, deg+min+sec (default=dms)
precision -- {int} -- Number of decimal to use (default: 1 for dms, 2 for dm, 4 for d).
Example :
> dms.toLat(48.857000)
> 48°51'25.2"N
> dms.toLat(-48.857000)
> 48°51'25.2"S
"""
lat = toDMS(deg, dms_format, precision)
if lat is None:
return NONE_VALUE_CHAR
compass_direction = 'S' if deg<0 else 'N'
return lat + SEPARATOR + compass_direction
def toLon(deg, dms_format=None, precision=None):
"""
Convert numeric degrees to deg/min/sec longitude (3-digit degrees, suffixed with E/W).
Return a string representing degrees formatted as deg/min/secs according to specified format.
Arguments:
deg -- {float | int} -- Degrees to be formatted as specified.
dms_format -- {string} -- Return value format as 'd', 'dm', 'dms' for deg, deg+min, deg+min+sec (default=dms)
precision -- {int} -- Number of decimal to use (default: 1 for dms, 2 for dm, 4 for d).
Example :
> dms.toLon(0.138833)
> 0°08'19.8"E
> dms.toLon(-0.138833)
> 0°08'19.8"W
"""
lon = toDMS(deg, dms_format, precision)
if lon is None:
return NONE_VALUE_CHAR
compass_direction = 'W' if (deg < 0) else 'E'
return lon + SEPARATOR + compass_direction
def toBearing(deg, dms_format=None, precision=None):
"""
Converts numeric degrees to deg/min/sec as a bearing (0°..360°).
Return a string representing degrees formatted as deg/min/secs according to specified format.
Arguments:
deg -- {float | int} -- Degrees to be formatted as specified.
dms_format -- {string} -- Return value format as 'd', 'dm', 'dms' for deg, deg+min, deg+min+sec (default=dms)
precision -- {int} -- Number of decimal to use (default: 1 for dms, 2 for dm, 4 for d).
Example :
> dms.toBearing(-0.138833, "dm", 1)
> 359°51.7
"""
# normalise negative values to 180°..360°
deg = float(deg+360)%360
b = toDMS(deg, dms_format, precision)
if b is None:
return NONE_VALUE_CHAR
else:
# just in case rounding took us up to 360°
return b.replace('360', '0')
def compassPoint(bearing, precision=3):
"""
Return compass point (to given precision) for supplied bearing.
Arguments:
bearing -- {float | int} -- Bearing in degrees from north.
precision -- {float | int} -- Precision (1:cardinal / 2:intercardinal / 3:secondary-intercardinal).
(default: 3)
Example :
> dms.compatPoint(30)
> NNE
> dms.compassPoint(30, 2)
> NE
> dms.compassPoint(30, 1)
> N
"""
if precision not in [1, 2, 3]:
raise ValueError('Precision must be between 1 and 3')
# Normalise to 0..360
bearing = ((bearing%360)+360)%360;
compass_4points = {
0: 'N',
1: 'E',
2: 'S',
3: 'W'
}
compass_8points = {
0: 'N',
1: 'NE',
2: 'E',
3: 'SE',
4: 'S',
5: 'SW',
6: 'W',
7: 'NW'
}
compass_16points = {
0: 'N',
1: 'NNE',
2: 'NE',
3: 'ENE',
4: 'E',
5: 'ESE',
6: 'SE',
7: 'SSE',
8: 'S',
9: 'SSW',
10: 'SW',
11:'WSW',
12: 'W',
13: 'WNW',
14: 'NW',
15: 'NNW',
}
compass_precisions = {
1: compass_4points.get(round(bearing*4/360) % 4, NONE_VALUE_CHAR),
2: compass_8points.get(round(bearing*8/360) % 8, NONE_VALUE_CHAR),
3: compass_16points.get(round(bearing*16/360) % 16, NONE_VALUE_CHAR),
}
return compass_precisions.get(precision)