Daniel
Daniel

Reputation: 12026

Resampling data to target grid

Is there an efficient way to solve the following problem?

Imagine we have these 2 lists. They represent non-uniformly sampled data:

MeasTimes = [0, 2, 4, 6, 8, 11, 12, 14, 18, 20, 22]
MeasValues = [-1, 0, 1, 0, -1, 0.5, 1, 0, 0, 1, 0]

How does one interpolate the data from this measurement to a target grid? Example:

TargetTimes = [0, 5, 10, 15, 18, 20] # given

Upvotes: 1

Views: 410

Answers (2)

FunkySayu
FunkySayu

Reputation: 8061

meas_times = [0, 2, 4, 6, 8, 11, 12, 14, 18, 20, 22]
meas_values = [-1, 0, 1, 0, -1, 0.5, 1, 0, 0, 1, 0]

def get_value(target_value):
    if target_value in meas_times:
        return meas_values[meas_times.index(target_value)]
    else:
        upper_index, upper_time = next((i, e) for i, e in enumerate(meas_times) if e > target_value)
        lower_value, upper_value = meas_values[upper_index - 1], meas_values[upper_index]
        abs_dt = float(abs(lower_value) + abs(upper_value)) / (upper_time - meas_times[upper_index - 1])

        if upper_value > lower_value:
            return lower_value + abs_dt * (target_value - meas_times[upper_index - 1])
        else:
            return lower_value - abs_dt * (target_value - meas_times[upper_index - 1])

target_times = [0, 5, 10, 15, 18, 20]
print map(get_value, target_times)
# [-1, 0.5, 0.0, 0.0, 0, 1]

Upvotes: 2

Anandhakumar R
Anandhakumar R

Reputation: 391

I think in times you have give wrong data ( 5 and 10)

the Code is

MeasValuesAtTargetTimes=[MeasValues[MeasTimes.index(i)] for i in TargetTimes]

Upvotes: 0

Related Questions