Skip to content

Instantly share code, notes, and snippets.

@JimHaughwout
Created November 13, 2014 23:55
Show Gist options
  • Save JimHaughwout/73d589089cae19775d94 to your computer and use it in GitHub Desktop.
Save JimHaughwout/73d589089cae19775d94 to your computer and use it in GitHub Desktop.
Compute distance and interpolate speed along path of coordinates and timestamps
from sys import argv
import csv
import dateutil.parser
from geopy.distance import vincenty
'''
Input file is downloaded movements from Savi Tracking
column 1 (a.k.a. row[0]) = lat
column 2 (a.k.a. row[1]) = lng
column 3 (a.k.a. row[2]) = utc time
'''
# Pass the filename as an arg, use it to open the CSV reader
source = open(argv[1])
reader = csv.reader(source)
# Set default agg values
row_num = 0
max_speed = 0
total_t = 0
total_s = 0
# Loop through the file and increment
for row in reader:
# Skip the header
if row_num == 0:
pass
# Use the first data row as the starting point
elif row_num == 1:
last_loc = (float(row[0]), float(row[1]))
last_ts = dateutil.parser.parse(str(row[2]))
# Calculated deltas from last point and aggregate
else:
this_loc = (float(row[0]), float(row[1]))
this_ts = dateutil.parser.parse(str(row[2]))
delta_s = vincenty(last_loc, this_loc).km
delta_t = (this_ts - last_ts).total_seconds()
total_s += delta_s
total_t += delta_t
try:
speed = delta_s / delta_t * 3600
if speed > max_speed: max_speed = speed
if speed > 80: msg = ' * GPS Drift *'
else: msg = ''
except ZeroDivisionError:
speed = 0
# Make these values the last values
last_loc = this_loc
last_ts = this_ts
# Print so far
print "Clock: %-26s\tDelta S: %-4.3f km\tDelta T: %-4.2f sec\tSpeed: %-5.2f kph%s" % \
(this_ts, delta_s, delta_t, speed, msg)
row_num += 1
# Wrap it up
try:
avg_speed = total_s / total_t * 3600
except ZeroDivisionError:
avg_speed = 0
print "Traversed %.3f km in %.2f minutes." % (total_s, total_t / 60)
print "Max Speed = %.2f kph.\tAvg speed = %.2f kph" % (max_speed, avg_speed)
source.closed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment