使用ReactiveCocoa创建移动平均线(和其他FIR滤波器)

时间:2016-01-12 10:54:57

标签: ios swift reactive-cocoa reactive-cocoa-3 reactive-cocoa-4

我仍然开始使用ReactiveCocoa和功能反应式编程概念,所以这可能是一个愚蠢的问题。

ReactiveCocoa似乎很自然地设计用于对实时数据流,触摸事件或加速计传感器输入等做出反应。

是否有可能以简单,反应的方式在ReactiveCocoa中应用有限脉冲响应滤波器?或者如果没有,那么最难看的黑客方式是什么?如何实现像简单移动平均线这样的东西呢?

理想情况下寻找Swift 2 + RA4解决方案,但也有兴趣在Objective C和RA2 / RA3中是否可行。

2 个答案:

答案 0 :(得分:3)

你真正需要的是某种句点缓冲区,它会保持一段缓冲值,并且只有当缓冲区达到容量时才开始发送(下面的代码是对takeLast运算符的天启)

extension SignalType {
    func periodBuffer(period:Int) -> Signal<[Value], Error> {
        return Signal { observer in
            var buffer: [Value] = []
            buffer.reserveCapacity(period)

            return self.observe { event in
                switch event {
                case let .Next(value):
                    // To avoid exceeding the reserved capacity of the buffer, we remove then add.
                    // Remove elements until we have room to add one more.
                    while (buffer.count + 1) > period {
                        buffer.removeAtIndex(0)
                    }

                    buffer.append(value)

                    if buffer.count == period {
                        observer.sendNext(buffer)
                    }
                case let .Failed(error):
                    observer.sendFailed(error)
                case .Completed:
                    observer.sendCompleted()
                case .Interrupted:
                    observer.sendInterrupted()
                }
            }
        }
    }
}

基于此,您可以将其映射到您想要的任何算法

let pipe = Signal<Int,NoError>.pipe()

pipe.0
    .periodBuffer(3)
    .map { Double($0.reduce(0, combine: +))/Double($0.count) } // simple moving average
    .observeNext { print($0) }

pipe.1.sendNext(10) // does nothing
pipe.1.sendNext(11) // does nothing
pipe.1.sendNext(15) // prints 12
pipe.1.sendNext(7) // prints 11
pipe.1.sendNext(9) // prints 10.3333
pipe.1.sendNext(6) // prints 7.3333

答案 1 :(得分:1)

您可能正在寻找scan信号运算符。在Andy Jacobs的回答的启发下,我想出了类似的东西(一个简单的移动平均线实现):

  let (signal, observer) = Signal<Int,NoError>.pipe()

  let maxSamples = 3

  let movingAverage = signal.scan( [Int]() ) { (previousSamples, nextValue)  in 
    let samples : [Int] =  previousSamples.count < maxSamples ? previousSamples : Array(previousSamples.dropFirst())
    return samples + [nextValue]
  }
  .filter { $0.count >= maxSamples }
  .map { $0.average }

  movingAverage.observeNext { (next) -> () in
    print("Next: \(next)")
  }

  observer.sendNext(1)
  observer.sendNext(2)
  observer.sendNext(3)
  observer.sendNext(4)
  observer.sendNext(42)

注意:我必须将average方法移动到协议扩展中,否则编译器会抱怨表达式过于复杂。我使用了this answer的一个很好的解决方案:

extension Array where Element: IntegerType {
    var total: Element {
        guard !isEmpty else { return 0 }
        return reduce(0){$0 + $1}
    }
    var average: Double {
        guard let total = total as? Int where !isEmpty else { return 0 }
        return Double(total)/Double(count)
    }
}