-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCoordinateReducer.py
More file actions
252 lines (212 loc) · 8.16 KB
/
Copy pathCoordinateReducer.py
File metadata and controls
252 lines (212 loc) · 8.16 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
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
import os
import math
import sys
import glob
import argparse
def parse_es_coord(s):
if not s:
return 0.0
side = s[0]
normalized = s[1:].replace(' ', '.')
parts = normalized.split('.')
try:
deg = int(parts[0])
min = int(parts[1])
if len(parts) >= 4:
sec = float(parts[2] + '.' + parts[3])
elif len(parts) == 3:
sec = float(parts[2])
else:
sec = 0.0
decimal = deg + min/60.0 + sec/3600.0
if side in ['S', 'W']:
decimal = -decimal
return decimal
except (ValueError, IndexError):
return 0.0
def format_es_coord(val, is_lat):
side = ''
if is_lat:
side = 'N' if val >= 0 else 'S'
else:
side = 'E' if val >= 0 else 'W'
val = abs(val)
deg = int(val)
min_float = (val - deg) * 60
min = int(min_float)
sec_float = (min_float - min) * 60
sec = int(sec_float)
millis = int(round((sec_float - sec) * 1000))
if millis >= 1000:
sec += 1
millis -= 1000
if sec >= 60:
min += 1
sec -= 60
if min >= 60:
deg += 1
min -= 60
return f"{side}{deg:03d}.{min:02d}.{sec:02d}.{millis:03d}"
def dist_to_segment(p, s1, s2):
x, y = p
x1, y1 = s1
x2, y2 = s2
dx = x2 - x1
dy = y2 - y1
if dx == 0 and dy == 0:
return math.sqrt((x - x1)**2 + (y - y1)**2)
t = ((x - x1) * dx + (y - y1) * dy) / (dx**2 + dy**2)
if t < 0:
return math.sqrt((x - x1)**2 + (y - y1)**2)
elif t > 1:
return math.sqrt((x - x2)**2 + (y - y2)**2)
else:
nearest_x = x1 + t * dx
nearest_y = y1 + t * dy
return math.sqrt((x - nearest_x)**2 + (y - nearest_y)**2)
def rdp(points, epsilon):
if len(points) < 3:
return points
dmax = 0
index = 0
end = len(points) - 1
for i in range(1, end):
d = dist_to_segment(points[i], points[0], points[end])
if d > dmax:
index = i
dmax = d
if dmax > epsilon:
res1 = rdp(points[:index + 1], epsilon)
res2 = rdp(points[index:], epsilon)
return res1[:-1] + res2
else:
return [points[0], points[end]]
def process_file(input_path, output_path, epsilon):
with open(input_path, 'r', encoding='utf-8', errors='ignore') as f:
lines = f.readlines()
output_lines = []
coord_block = []
line_block = []
current_color = ""
def flush_coords():
if not coord_block:
return
points = []
for c in coord_block:
p = (c[1], c[2])
if not points or abs(p[0] - points[-1][0]) > 1e-10 or abs(p[1] - points[-1][1]) > 1e-10:
points.append(p)
if len(points) > 5:
simplified = rdp(points, epsilon)
for p in simplified:
output_lines.append(f"COORD:{format_es_coord(p[0], True)}:{format_es_coord(p[1], False)}\n")
elif len(points) > 1:
for p in points:
output_lines.append(f"COORD:{format_es_coord(p[0], True)}:{format_es_coord(p[1], False)}\n")
coord_block.clear()
def flush_lines():
if not line_block:
return
i = 0
while i < len(line_block):
current_color = line_block[i][1]
while i < len(line_block) and abs(line_block[i][2] - line_block[i][4]) < 1e-10 and abs(line_block[i][3] - line_block[i][5]) < 1e-10:
i += 1
if i >= len(line_block):
break
sequence = [ (line_block[i][2], line_block[i][3]), (line_block[i][4], line_block[i][5]) ]
orig_indices = [i]
j = i + 1
while j < len(line_block):
next_color, nlat1, nlon1, nlat2, nlon2 = line_block[j][1:]
if next_color == current_color and abs(nlat1 - sequence[-1][0]) < 1e-10 and abs(nlon1 - sequence[-1][1]) < 1e-10:
if abs(nlat2 - nlat1) > 1e-10 or abs(nlon2 - nlon1) > 1e-10:
sequence.append((nlat2, nlon2))
orig_indices.append(j)
j += 1
else:
break
if len(sequence) > 3:
simplified = rdp(sequence, epsilon)
for k in range(len(simplified) - 1):
p1 = simplified[k]
p2 = simplified[k+1]
output_lines.append(f"LINE:{format_es_coord(p1[0], True)}:{format_es_coord(p1[1], False)}:{format_es_coord(p2[0], True)}:{format_es_coord(p2[1], False)}\n")
else:
for idx in orig_indices:
l = line_block[idx]
if abs(l[2] - l[4]) > 1e-10 or abs(l[3] - l[5]) > 1e-10:
output_lines.append(l[0])
i = j
line_block.clear()
for line in lines:
stripped = line.strip()
if stripped.startswith("FOLDER:"):
flush_coords()
flush_lines()
output_lines.append(line)
elif stripped.startswith("COLOR:"):
flush_coords()
flush_lines()
current_color = stripped
output_lines.append(line)
elif stripped.startswith("COORD:"):
flush_lines()
parts = stripped.split(':')
if len(parts) >= 3:
lat = parse_es_coord(parts[1])
lon = parse_es_coord(parts[2])
coord_block.append((line, lat, lon))
else:
flush_coords()
output_lines.append(line)
elif stripped.startswith("COORDPOLY") or stripped.startswith("COORDLINE"):
flush_coords()
output_lines.append(line)
elif stripped.startswith("LINE:"):
flush_coords()
parts = stripped.split(':')
if len(parts) >= 5:
lat1 = parse_es_coord(parts[1])
lon1 = parse_es_coord(parts[2])
lat2 = parse_es_coord(parts[3])
lon2 = parse_es_coord(parts[4])
line_block.append((line, current_color, lat1, lon1, lat2, lon2))
else:
flush_lines()
output_lines.append(line)
else:
flush_coords()
flush_lines()
output_lines.append(line)
flush_coords()
flush_lines()
with open(output_path, 'w', encoding='utf-8') as f:
f.writelines(output_lines)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Topsky Coordinates Reducer - Simplifies coordinate sequences using RDP algorithm.")
parser.add_argument("--epsilon", type=float, default=0.00001, help="Simplification threshold in degrees (e.g., 0.00001 for ~1m). Default: 0.00001")
parser.add_argument("--input", type=str, default="Input", help="Directory containing input files. Default: Input")
parser.add_argument("--output", type=str, default="Output", help="Directory for optimized files. Default: Output")
args = parser.parse_args()
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
input_dir = os.path.join(BASE_DIR, args.input)
output_dir = os.path.join(BASE_DIR, args.output)
if not os.path.exists(output_dir):
os.makedirs(output_dir, exist_ok=True)
epsilon = args.epsilon
files = glob.glob(os.path.join(input_dir, "*.txt"))
if not files:
print(f"No files found in {input_dir}")
sys.exit(1)
print(f"--- Topsky Coordinates Reducer ---")
print(f"Simplification threshold: {epsilon}")
print(f"Processing {len(files)} files...\n")
for f in files:
basename = os.path.basename(f)
output_file = os.path.join(output_dir, basename)
process_file(f, output_file, epsilon)
orig_size = os.path.getsize(f) / 1024
opt_size = os.path.getsize(output_file) / 1024
reduction = (1 - (opt_size / orig_size)) * 100 if orig_size > 0 else 0
print(f" [+] {basename:15} | {orig_size:7.1f}KB -> {opt_size:7.1f}KB ({reduction:5.1f}%)")