Search code examples
arraysswiftinterpolationaccelerate-frameworklinear-interpolation

Swift Linear Interpolation and UpSampling


I have a stream of metrics that are unevenly sampled. I want to linearly interpolate and upsample these metrics to a specific sampling frequency. I have tried to use the Accelerate Framework and the SIMD framework but I am not really sure what to do.

The problem itself is as follows:

let original_times:[Double] = [0.0, 2.0, 3.0, 6.0, 10.0]
let original_values: [Double] = [50.0, 20.0, 30.0, 40.0, 10.0]
let new_times:[Double] = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]

So I am looking for a way to find the new_values through some sort of linear interpolation method.


Solution

  • vDSP_vgenpD will do the job for you. Pass it the original times and values, and it will populate an array with the interpolated values. For example:

    import Accelerate
    
    let original_times:[Double] =    [0.0,  2.0,  3.0,  6.0, 10.0]
    let original_values: [Double] = [50.0, 20.0, 30.0, 40.0, 10.0]
    
    var new_values = [Double](repeating: 0,
                              count: 11)
    
    let stride = vDSP_Stride(1)
    
    vDSP_vgenpD(original_values, stride,
                original_times, stride,
                &new_values, stride,
                vDSP_Length(new_values.count),
                vDSP_Length(original_values.count))
    

    You can get an array of time / value tuples with:

    let result = new_values.enumerated().map{ return $0 }
    

    That looks like:

    enter image description here