查找给定数据集的局部最大点

时间:2016-07-11 15:52:37

标签: ios swift algorithm matlab accelerometer

所以我开始尝试使用我从加速度计获得的数据来计算用户所采取的步数,即 x y z 坐标。

我正在尝试实现this算法但我目前停留在本地最大值部分。 Matlab有一个内置的findpeaks()方法,可以定位给定数据集的所有局部最大值。

以下是我尝试实现该算法但我仍然从中获得了非常巨大的成果。 首先,使用由20个实际步骤组成的数据集,算法计算出所采取的步骤数为990+。我调整并调试了它,然后我设法将此数字降低到大约660 ..然后110最终到达当前45。目前我只是陷入困境,感觉我的findpeaks()方法错了。

这是我的班级实施

import Foundation

class StepCounter
{
   private var xAxes: [Double] = [Double]()
   private var yAxes: [Double] = [Double]()
   private var zAxes: [Double] = [Double]()
   private var rmsValues: [Double] = [Double]()

  init(graphPoints: GraphPoints)
 {
    xAxes = graphPoints.xAxes
    yAxes = graphPoints.yAxes
    zAxes = graphPoints.zAxes
    rmsValues = graphPoints.rmsValues
 }

func numberOfSteps()-> Int
{
    var pointMagnitudes: [Double] = rmsValues

    removeGravityEffectsFrom(&pointMagnitudes)

    let minimumPeakHeight: Double = standardDeviationOf(pointMagnitudes)

    let peaks = findPeaks(&pointMagnitudes)

    var totalNumberOfSteps: Int = Int()

    for thisPeak in peaks
    {
        if thisPeak > minimumPeakHeight
        {
            totalNumberOfSteps += 1
        }
    }

    return totalNumberOfSteps
}

// TODO: dummy method for the time being. replaced with RMS values from controller itself
private func calculateMagnitude()-> [Double]
{
    var pointMagnitudes: [Double] = [Double]()

    for i in 0..<xAxes.count
    {
        let sumOfAxesSquare: Double = pow(xAxes[i], 2) + pow(yAxes[i], 2) + pow(zAxes[i], 2)
        pointMagnitudes.append(sqrt(sumOfAxesSquare))
    }

    return pointMagnitudes
}

private func removeGravityEffectsFrom(inout magnitudesWithGravityEffect: [Double])
{
    let mean: Double = calculateMeanOf(rmsValues)

    for i in 0..<magnitudesWithGravityEffect.count
    {
        magnitudesWithGravityEffect[i] -= mean
    }
}

// Reference: https://en.wikipedia.org/wiki/Standard_deviation
private func standardDeviationOf(magnitudes: [Double])-> Double
{
    var sumOfElements: Double = Double()
    var mutableMagnitudes: [Double] = magnitudes

    // calculates the numerator of the equation
    /* no need to do (mutableMagnitudes[i] = mutableMagnitudes[i] - mean) 
     * because it has already been done when the gravity effect was removed
     * from the dataset
     */
    for i in 0..<mutableMagnitudes.count
    {
        mutableMagnitudes[i] = pow(mutableMagnitudes[i], 2)
    }

    // sum the elements
    for thisElement in mutableMagnitudes
    {
        sumOfElements += thisElement
    }

    let sampleVariance: Double = sumOfElements/Double(mutableMagnitudes.count)

    return sqrt(sampleVariance)
}

// Reference: http://www.mathworks.com/help/signal/ref/findpeaks.html#examples
private func findPeaks(inout magnitudes: [Double])-> [Double]
{
    var peaks: [Double] = [Double]()

    // ignore the first element
    peaks.append(max(magnitudes[1], magnitudes[2]))

    for i in 2..<magnitudes.count
    {
        if i != magnitudes.count - 1
        {
            peaks.append(max(magnitudes[i], magnitudes[i - 1], magnitudes[i + 1]))
        }
        else
        {
            break
        }
    }

    // TODO:Does this affect the number of steps? Are they clumsly lost or foolishly added?
    peaks = Array(Set(peaks)) // removing duplicates.

    return peaks
}

private func calculateMeanOf(magnitudes: [Double])-> Double
{
    var sumOfElements: Double = Double()

    for thisElement in magnitudes
    {
        sumOfElements += thisElement
    }

    return sumOfElements/Double(magnitudes.count)
}

}`

使用此datasheet,实际执行的步骤数为20,但我一直在45。即使我尝试使用包含30个实际步骤的数据集,计算出的数字也接近100s.

非常感谢任何协助/指导

PS :数据表格式为 X Y Z RMS (均方根)

2 个答案:

答案 0 :(得分:3)

此功能适用于您提供的示例。它将高原视为一个峰值,并允许相同值的多个峰值。唯一的问题是 - @ user3386109指出 - 如果数据中有很多小的振荡,你将获得比实际更多的峰值。如果您要处理类似的数据,您可能希望在此计算中实现数据集的方差。

此外,由于您没有更改传入的变量,因此无需使用inout

private func findPeaks(magnitudes: [Double]) -> [Double] {

    var peaks = [Double]()
    // Only store initial point, if it is larger than the second. You can ignore in most data sets 
    if max(magnitudes[0], magnitudes[1]) == magnitudes[0] { peaks.append(magnitudes[0]) }

    for i in 1..<magnitudes.count - 2 {
        let maximum = max(magnitudes[i - 1], magnitudes[i], magnitudes[i + 1])
        // magnitudes[i] is a peak iff it's greater than it's surrounding points 
        if maximum == magnitudes[i] && magnitudes[i] != magnitudes[i+1] {
            peaks.append(magnitudes[i])
        }
    }
    return peaks
}

<强>更新 我注意到我的解决方案在集合结束时找不到局部最大值。我已将其更新并将其作为Collection的扩展程序实施。这很容易适应Sequence虽然我不确定这是否有意义。

extension Collection where Element: Comparable {
    func localMaxima() -> [Element] {
        return localMaxima(in: startIndex..<endIndex)
    }

    func localMaxima(in range: Range<Index>) -> [Element] {
        var slice = self[range]
        var maxima = [Element]()

        var previousIndex: Index? = nil
        var currentIndex = slice.startIndex
        var nextIndex = slice.index(after: currentIndex)

        while currentIndex < slice.endIndex {
            defer {
                previousIndex = currentIndex
                currentIndex = nextIndex
                nextIndex = slice.index(after: nextIndex)
            }

            let current = slice[currentIndex]
            let next = slice[nextIndex]

            // For the first element, there is no previous
            if previousIndex == nil, Swift.max(current, next) == current {
                maxima.append(current)
                continue
            }

            // For the last element, there is no next
            if nextIndex == slice.endIndex {
                let previous = slice[previousIndex!]
                if Swift.max(previous, current) == current {
                    maxima.append(current)
                }
                continue
            }

            let previous = slice[previousIndex!]

            let maximum = Swift.max(previous, current, next)
            // magnitudes[i] is a peak iff it's greater than it's surrounding points
            if maximum == current && current != next {
                maxima.append(current)
            }
        }
        return maxima
    }
}

对于它的价值,这是Sequence

的扩展名
extension Sequence where Element: Comparable {
    func localMaxima() -> [Element] {
        var maxima = [Element]()
        var iterator = self.makeIterator()

        var previous: Element? = nil
        guard var current = iterator.next() else { return [] }
        while let next = iterator.next() {
            defer {
                previous = current
                current = next
            }

            // For the first element, there is no previous
            if previous == nil, Swift.max(current, next) == current {
                maxima.append(current)
                continue
            }

            let maximum = Swift.max(previous!, current, next)
            // magnitudes[i] is a peak iff it's greater than it's surrounding points
            if maximum == current && current != next {
                maxima.append(current)
            }
        }

        // For the last element, there is no next
        if Swift.max(previous!, current) == current {
            maxima.append(current)
        }

        return maxima
    }
}

答案 1 :(得分:0)

此解决方案基于@jjatie 的回答。它修复了我在可选值意外为零时遇到的问题,并添加了一个内部标志以允许抑制最后一个最大值(如果它是最后一个元素)。

我需要最后一点,因为就我而言,它只是上升沿,而不是真正的最大值。

它还返回索引而不是值。相关部分我刚刚被注释掉了。如果需要,您可以轻松地将其改回。如果需要,您甚至可以让代码返回对。不过,获取索引的实际值真的很容易。

查看包含的示例数据。它突出了我发现的所有问题。如果您感到好奇,可以尝试使用原始答案。

代码是在 iPad Swift Playgrounds 中编写的。这就是它可能看起来不稳定的原因。

extension Collection where Element: Comparable {
    func localMaximaIndexes() -> [Index] {
        return localMaximaIndexes(in: startIndex..<endIndex)
    }
    
    func localMaximaIndexes(in range: Range<Index>) -> [Index] {
        let wantLastElementIfLocalMaximum = false
        
        var slice = self[range]
        //var maxima = [Element]()
        var indexes = [Index]()
        
        var previousIndex: Index? = nil
        var currentIndex = slice.startIndex
        var nextIndex = slice.index(after: currentIndex)
        
        while currentIndex < slice.endIndex {
            defer {
                previousIndex = currentIndex
                currentIndex = nextIndex
                nextIndex = slice.index(after: nextIndex)
            }
            
            let current = slice[currentIndex]
            
            // For the last element, there is no next.
            if nextIndex == slice.endIndex {
                if wantLastElementIfLocalMaximum, 
                   let previousIndex = previousIndex {
                    let previous = slice[previousIndex]
                    if Swift.max(previous, current) == current {
                        //maxima.append(current)
                        indexes.append(currentIndex)
                    }
                }
                
                continue
            }
            
            let next = slice[nextIndex]
            
            // For the first element, there is no previous.
            if previousIndex == nil {
                if Swift.max(current, next) == current {
                    //maxima.append(current)
                    indexes.append(currentIndex)
                }
                
                continue
            }
            
            let previous = slice[previousIndex!]
            
            let maximum = Swift.max(previous, current, next)
            // magnitudes[i] is a peak iff it's greater than it's surrounding points.
            if maximum == current && current != next {
                //maxima.append(current)
                indexes.append(currentIndex)
            }
        }
        
        return indexes
    }
}

typealias Sample = Float

let result: [Sample]  = [-1.1324883e-06, 3.0614667, 5.6568537, 7.391036, 8.0, 7.391037, 5.6568546, 3.0614676, 5.5134296e-07, -3.0614667, -5.6568537, -7.391036, -8.0, -7.3910365, -5.6568546, -3.0614681, -4.3213367e-07, 3.0614672, 5.3033004, 6.4671564, 6.5, 5.543277, 3.8890872, 1.9134172, -1.937151e-07, -1.5307341, -2.474874, -2.7716386, -2.5, -1.847759, -1.06066, -0.38268328]

let maximaIndexes = result.localMaximaIndexes()