-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkmldecimate.py
More file actions
330 lines (300 loc) · 11.7 KB
/
kmldecimate.py
File metadata and controls
330 lines (300 loc) · 11.7 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
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import argparse
import datetime
import sys
parser = argparse.ArgumentParser(description='decimate (and retime) a folder or track from a kml file')
#parser.add_argument('-i', '--ifile', metavar='F', type=str, action='store', default = "20170527 Corral couloir.kml",
parser.add_argument('-i', '--ifile', metavar='F', type=str, action='store', default = None,
help='input file. Leave blank to use stdin')
parser.add_argument('-o', '--ofile', metavar='F', type=str, action='store', default = None,
help='output file. Leave blank for stdout, use "-" to append "_dec" to input filename')
parser.add_argument('-d', '--interval', metavar='F', type=int, action='store', default = 50,
help='Decimation interval. default = %(default)s')
#parser.add_argument('--folder', metavar='F', type=str, action='store', default = "Points",
parser.add_argument('--folder', metavar='F', type=str, action='store', default = None,
help='Folder name')
#parser.add_argument('--tracks', metavar='F', type=str, action='store', default = Points,
parser.add_argument('--tracks', metavar='F', type=str, action='store', default = None,
help='Track name')
parser.add_argument('-n', dest='retime', action='store_false', default = True,
help='No retime. Default is to retime the decimated track')
parser.add_argument('-t', '--timeincr', metavar='F', type=str, action='store', default = "min",
help='time increment [sec|min|hour]')
parser.add_argument('--append_str', metavar='F', type=str, action='store', default = '_dec',
help='String to append to names in the kml output')
parser.add_argument('-v', dest='verbose', action='store_true', default = False,
help='print some debug info')
opts = parser.parse_args()
if opts.verbose:
print opts
ofile = None
fout = None
if opts.ifile:
f = open(opts.ifile)
else:
f = sys.stdin
if opts.ofile:
if opts.ofile[0] == "-":
if opts.ifile:
ofile = opts.ifile.split('.')[0] +'_dec.' +opts.ifile.split('.')[1]
else:
ofile = "kmldecimate_dec.kml"
print "ofile: " +str(ofile)
else:
ofile = opts.ofile
fout = open(ofile, 'w')
else:
fout = sys.stdout
#--------------------------------------------------------------
def folder2track(s, track_name, dlm=" ", eol="\n"):
#--------------------------------------------------------------
if opts.verbose:
print "folder2track()"
track = dlm +"<Placemark>" +eol
track += dlm +dlm +"<name>" +track_name +"</name>" +eol
track += dlm +dlm +"<visibility>0</visibility>\n"
track += dlm +dlm +"<open>1</open>" +eol
track += """ <StyleMap>
<Pair>
<key>normal</key>
<Style>
<IconStyle>
<scale>1</scale>
<Icon>
<href>http://maps.google.com/mapfiles/kml/shapes/track.png</href>
</Icon>
</IconStyle>
<LineStyle>
<color>ff40c4ff</color>
<width>3</width>
</LineStyle>
</Style>
</Pair>
<Pair>
<key>highlight</key>
<Style>
<IconStyle>
<scale>1.33</scale>
<Icon>
<href>http://maps.google.com/mapfiles/kml/shapes/track.png</href>
</Icon>
</IconStyle>
<LineStyle>
<color>ff40c4ff</color>
<width>4</width>
</LineStyle>
</Style>
</Pair>
</StyleMap>"""
track += eol
track += dlm +dlm +"<gx:Track>" +eol
coordinates = ""
times = ""
for line in s.split("\n"):
#print "folder2track: line = " +line
if "<TimeStamp><when>" in line:
t = line.split('>')[2].split('<')[0]
#print "folder2track: t = " +t
times += dlm +dlm +dlm +"<when>"
times += t
times += "</when>" +eol
if "<coordinates>" in line:
coord = line.split('>')[1].split('<')[0]
#print "folder2track: coord = " +coord
coordinates += dlm +dlm +dlm +"<gx:coord>"
coordinates += coord
coordinates += "</gx:coord>" +eol
track += times
track += coordinates
track += dlm +dlm +dlm +"<ExtendedData>" +eol
track += dlm +dlm +dlm +dlm +'<Data name="name">' +eol
track += dlm +dlm +dlm +dlm +dlm +"<value>" +track_name +"</value>" +eol
track += dlm +dlm +dlm +dlm +"</Data>" +eol
track += dlm +dlm +dlm +"</ExtendedData>" +eol
track += dlm +dlm +"</gx:Track>" +eol
track += dlm +"</Placemark>" +eol
return track
#--------------------------------------------------------------
def retime_track(track, dlm=" ", eol="\n"):
#--------------------------------------------------------------
start = False
inside_track = False
ret_track = ""
for line in track.split("\n"):
if "<gx:Track>" in line:
inside_track = True
elif "</gx:Track>" in line:
inside_track = False
start = False
if "<when>" in line and inside_track:
n_leading_spaces = len(line) - len(line.lstrip())
leading_spaces = ''
for n in range(n_leading_spaces):
leading_spaces = leading_spaces + line[0]
if not start:
s = line.split('>')[1].split('<')[0]
print "retiming with Start Time: " +str(s)
s = s.split('T')
d = s[0].split('-')
year = int(d[0])
month = int(d[1])
day = int(d[2])
tline = s[1].split(':')
hour = int(tline[0])
minute = int(tline[1])
#second = int(tline[2].split('Z')[0])
second = int(tline[2][0:-1])
timezone = tline[2][-1]
#print ",".join([year, month, day, hour, minute, second])
start = datetime.datetime(year,month,day,hour,minute,second)
t = start
else:
if opts.timeincr[0] == 's':
delta = datetime.timedelta(0,1)
elif opts.timeincr[0] == 'm':
delta = datetime.timedelta(0,60)
elif opts.timeincr[0] == 'h':
delta = datetime.timedelta(0,3600)
t = t + delta
#print "time: " +str(timenow)
lineout = leading_spaces +t.strftime("<when>%Y-%m-%dT%H:%M:%S") +timezone +"</when>\n"
ret_track += lineout
else:
ret_track += line +"\n"
return ret_track
#-----------------------------------
if opts.tracks:
#-----------------------------------
# Handle the case of tracks
have_track_name = False
start = False
inside_track = False
n = 0
npoints = 1
last_line = ""
dec_track = ""
with f:
for line in f:
if "<Placemark>" in last_line and "<name>" in line:
name = line.split('>')[1].split('<')[0]
if name == opts.tracks:
have_track_name = True
if "<gx:Track>" in line and have_track_name:
inside_track = True
elif "</gx:Track>" in line:
inside_track = False
n = 0
elif "</Placemark>" in line:
dec_track += line
have_track_name = False
elif "<when>" in last_line and "<gx:coord>" in line:
n = 0
if ("<when>" in line or "<gx:coord>" in line) and inside_track:
n = n + 1;
if n == opts.interval:
fout.write(line)
dec_track += line
n = 0
npoints += 1
else:
if have_track_name:
if "Data name" in last_line and "value" in line:
name = line.split('>')[1].split('<')[0]
dec_track += line.replace(name, name+opts.append_str)
elif "<Placemark>" in last_line and "<name>" in line:
dec_track += last_line
dec_track += line.replace(name, name+opts.append_str)
else:
dec_track += line
if "</Document>" in line:
#if opts.verbose:
# print "Document line = " +line
if opts.retime:
ret_tracks = retime_track(dec_track)
fout.write(ret_tracks)
else:
fout.write(dec_track)
fout.write(line)
last_line = line
print "Decimated to " +str(npoints) +" points in track"
elif opts.folder:
# Handle the case of a folder of placemarks
dec_tracks = ""
folder_out_str = ""
store_folder = False
have_folder_name = False
name = False
placemark = False
n = opts.interval
npoints = 1
last_line = ""
#with open(opts.ifile) as f:
with f:
for line in f:
if "</Folder>" in line:
name = False
if have_folder_name:
store_folder = True
dec_tracks = folder2track(folder_out_str, "dec_tracks")
if opts.retime:
ret_tracks = retime_track(dec_tracks)
have_folder_name = False
if "</Folder>" in last_line:
store_folder = False
if "<Folder>" in last_line and "<name>" in line:
name = line.split('>')[1].split('<')[0]
print "folder name = " +str(name)
if name == opts.folder:
have_folder_name = True
folder_out_str += last_line
store_folder = True
if have_folder_name:
if "</Placemark>" in last_line:
placemark = False
store_folder = False
if "<Placemark>" in line:
placemark = True
n = n + 1;
if n >= opts.interval:
store_folder = True
n = 0
npoints += 1
else:
store_folder = False
#print str(n) +" " +str(placemark) +" " +str(store_folder)
#print "hfn " +str(n) +" " +str(placemark) +" " +str(store_folder)
if store_folder:
if "<Folder>" in last_line and "<name>" in line:
folder_out_str += line.replace(name, name+opts.append_str)
leading_space = line[:len(line)-len(line.lstrip())]
folder_out_str += leading_space +"<visibility>0</visibility>\n"
elif "<Placemark>" in last_line and "<name>" in line:
folder_out_str += line
leading_space = line[:len(line)-len(line.lstrip())]
folder_out_str += leading_space +"<visibility>0</visibility>\n"
else:
folder_out_str += line
if "</Document>" in line:
fout.write(folder_out_str)
if opts.retime:
fout.write(ret_tracks)
else:
fout.write(dec_tracks)
#print dec_tracks
fout.write(line)
last_line = line
print "Decimated to " +str(npoints) +" points in folder"
else:
# TODO: handle paths formatted as triplets, like the one below
"""
<Placemark>
<name>Path</name>
<styleUrl>#lineStyle</styleUrl>
<LineString>
<tessellate>1</tessellate>
<coordinates>
6.960669,45.947431,3242.8 6.960675,45.947429,3242.8 ...
</coordinates>
</LineString>
</Placemark>
"""
#:vim ts=4