Skip to content

Instantly share code, notes, and snippets.

@sjednac
Last active June 4, 2018 14:32
Show Gist options
  • Save sjednac/93a7b04cc0da496d7a9b to your computer and use it in GitHub Desktop.
Save sjednac/93a7b04cc0da496d7a9b to your computer and use it in GitHub Desktop.
Computing local information within a rolling time window in Scala
organization := "com.mintbeans"
version := "0.1"
scalaVersion := "2.11.7"
scalacOptions := Seq("-unchecked", "-deprecation", "-encoding", "utf8")
import scala.io.Source
case class Observation(time: Int, value: BigDecimal)
class Memory(val length: Int, val observation: Option[Observation], val pastEvents: List[Observation]) {
def record(newObservation: Observation): Memory = {
val newEvents = (newObservation :: pastEvents).takeWhile(_.time > newObservation.time - length)
new Memory(length, Some(newObservation), newEvents)
}
override def toString = s"${observation} after ${pastEvents}"
}
object TimeSeries extends App {
val source = Source.stdin
val T = 60
val observations = source.getLines.map(l => l.split('\t')).map(parts => Observation(parts(0).toInt, BigDecimal(parts(1))))
val memories = observations.scanLeft(new Memory(T, None, Nil))( (h, o) => h.record(o))
for (memory <- memories) memory.observation match {
case Some(observation) =>
val pastEvents = memory.pastEvents
val pastValues = pastEvents.map(_.value)
println(s"""${observation.time} ${observation.value} ${pastEvents.size}
|${pastValues.sum.underlying.stripTrailingZeros}
|${pastValues.min.underlying.stripTrailingZeros}
|${pastValues.max.underlying.stripTrailingZeros}""".stripMargin.replaceAll("\n", " "))
case None =>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment