2

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.

2 Answers2

5

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

Flex Monkey
  • 3,583
  • 17
  • 19
3

Interpolation is a wide field (see. Wikipedia : https://en.wikipedia.org/wiki/Interpolation)

The simplest method is a linear interpolation like this.

class LinearInterpolation {

    private var n : Int
    private var x : [Double]
    private var y : [Double]
    init (x: [Double], y: [Double]) {
        assert(x.count == y.count)
        self.n = x.count-1
        self.x = x
        self.y = y
    }
    
    func Interpolate(t: Double) -> Double {
        if t <= x[0] { return y[0] }
        for i in 1...n {
            if t <= x[i] {
                let ans = (t-x[i-1]) * (y[i] - y[i-1]) / (x[i]-x[i-1]) + y[i-1]
                return ans
            }
        }
        return y[n]
    }
}

Usage:

    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]
    let ipol = LinearInterpolation(x: original_times, y: original_values)
    for t in new_times {
        let y = ipol.Interpolate(t: t)
        print("t: \(t) y: \(y)")
    }

In your Usecase with something like audio data you should take a look at Fourier analysis.

Alex
  • 724
  • 1
  • 9
  • 24