Skip to content

Instantly share code, notes, and snippets.

@Spaxe
Created May 8, 2017 05:51
Show Gist options
  • Save Spaxe/c75876371712b43f980763e0c7b07d60 to your computer and use it in GitHub Desktop.
Save Spaxe/c75876371712b43f980763e0c7b07d60 to your computer and use it in GitHub Desktop.
Interpolation
#!/usr/bin/env python3
'''Interpolates numeric datasets'''
import sortedcontainers
def mix(a, b, ratio):
'''Return a if raio is 0, b if ratio is 1, and between a and b for a ratio inbetween.'''
return a + (b - a) * ratio
def interpolate(sorted_container, interval):
'''Interpolate a sorted container with linear blending'''
start_key = sorted_container.iloc[0]
end_key = sorted_container.iloc[-1]
this_key = start_key
output = sortedcontainers.SortedDict()
while this_key <= end_key:
# Copy over an item if it already exists, and the two end points
if this_key in sorted_container \
or this_key == start_key \
or this_key == end_key:
output[this_key] = sorted_container[this_key]
# Locate the nearest two data points and interpolate
else:
# Find the two items between this data point, and get their distances
left_index = sorted_container.bisect(this_key) - 1
right_index = sorted_container.bisect(this_key)
left_key = sorted_container.peekitem(left_index)[0]
right_key = sorted_container.peekitem(right_index)[0]
# Blend the left and right using the ratio of two distances
ratio = (right_key - this_key) / (right_key - left_key)
left = sorted_container.peekitem(left_index)[1]
right = sorted_container.peekitem(right_index)[1]
inbetween = mix(left, right, ratio)
output[this_key] = inbetween
this_key += interval
return output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment