In How to compare GPS tracks I showed how the Needleman-Wunsch algorithm, originally designed for aligning DNA and protein sequences, can be used to compare GPS tracks.

The method I introduced relies on pre-processing the GPS file so that all points are evenly distributed to reduce noise in the data set, but I didn't cover how that's done.

# Trace the path

Starting from the first point, the path is followed and the great-circle distance between each point is accumulated until it exceeds the desired distribution distance.

When the distance has been exceeded, a new point is interpolated between the current point and the previous point.

gpxpy has a function for moving points when given an angle and a distance in meters. The distance is the accumulated distance minus the required distance. gpxpy doesn't have a function for calculating the angle, otherwise known as initial bearing, between two points. Using the information here, I implemented the following function:

def bearing(point1, point2): lat1r = math.radians(point1.latitude) lat2r = math.radians(point2.latitude) dlon = math.radians(point2.longitude - point1.longitude) y = math.sin(dlon) * math.cos(lat2r) x = math.cos(lat1r) * math.sin(lat2r) - math.sin(lat1r) \ * math.cos(lat2r) * math.cos(dlon) return math.degrees(math.atan2(y, x))

# Interpolate points

Points are interpolated between the last correct point and current point until the distance no longer exceeds the distribution distance, then the entire process repeats until the end of the track is reached. The final point is always retained.

def interpolate_distance(points, distance): d = 0 i = 0 even_points = [] while i < len(points): if i == 0: even_points.append(points[0]) i += 1 continue if d == 0: p1 = even_points[-1] else: p1 = points[i-1] p2 = points[i] d += gpxpy.geo.distance(p1.latitude, p1.longitude, p1.elevation, p2.latitude, p2.longitude, p2.elevation) if d >= distance: brng = bearing(p1, p2) ld = gpxpy.geo.LocationDelta(distance=-(d-distance), angle=brng) p2_copy = copy.deepcopy(p2) p2_copy.move(ld) even_points.append(p2_copy) d = 0 else: i += 1 else: even_points.append(points[-1]) return even_points

# Results

The result from using this algorithm on the same data produces a much more spectacular result:

And just in case you don't believe me, here's the same data with points distributed every 50 meters:

The code can be found in jonblack/cmpgpx repository on github.