How to solve constraints with boolean and bitvector variables in c/c++ interface of stp - smt

Suppose I have the following constraints
(declare-fun x () Bool)
(declare-fun y () Bool)
(declare-fun t1 () (_ BitVec 8))
(declare-fun t2 () (_ BitVec 8))
(assert (or x y))
(assert (=> x (bvule t1 t2)))
(assert (=> y (bvule t2 t1)))
(check-sat)
How to write the corresponding code in c/c++ interface of stp?
My application requires to solve a constraint set similar to this.
Any help is appreciated.

See the C API testcases. There are a number of small, easy to read examples for how to use STP's C interface. Here is push-pop.c.
/* g++ -I$(HOME)/stp/c_interface push-pop.c -L$(HOME)/lib -lstp -o cc*/
#include <stdio.h>
#include "c_interface.h"
int main() {
VC vc = vc_createValidityChecker();
vc_setFlags('n');
vc_setFlags('d');
vc_setFlags('p');
//vc_setFlags('v');
//vc_setFlags('s');
Type bv8 = vc_bvType(vc, 8);
Expr a = vc_varExpr(vc, "a", bv8);
Expr ct_0 = vc_bvConstExprFromInt(vc, 8, 0);
Expr a_eq_0 = vc_eqExpr(vc, a, ct_0);
int query = vc_query(vc, a_eq_0);
printf("query = %d\n", query);
vc_push(vc);
query = vc_query(vc, a_eq_0);
vc_pop(vc);
printf("query = %d\n", query);
}
This corresponds to the smt query:
(declare-fun a () (_ BitVec 8))
(push)
(assert (not (= a (_ bv0 8))))
(check-sat)
(pop)
Once you have gotten a couple of these working, you can take a look at the c interface header for how to construct different operators.

Related

How to type-hint in Hy

Is it possible to type-hint variables and return values of functions in Hy language?
# in python we can do this
def some_func() -> str:
return "Hello World"
Yes... Hy implements PEP 3107 & 526 annotations since at least 8 Oct 2019 (see this pull request: https://github.com/hylang/hy/pull/1810)
There is the #^ form as in the example below (from the documentation: https://docs.hylang.org/en/master/api.html?highlight=annotation##^)
; Annotate the variable x as an int (equivalent to `x: int`).
#^int x
; Can annotate with expressions if needed (equivalent to `y: f(x)`).
#^(f x) y
; Annotations with an assignment: each annotation (int, str) covers the term that
; immediately follows.
; Equivalent to: x: int = 1; y = 2; z: str = 3
(setv #^int x 1 y 2 #^str z 3)
; Annotate a as an int, c as an int, and b as a str.
; Equivalent to: def func(a: int, b: str = None, c: int = 1): ...
(defn func [#^int a #^str [b None] #^int [c 1]] ...)
; Function return annotations come before the function name (if it exists)
(defn #^int add1 [#^int x] (+ x 1))
(fn #^int [#^int y] (+ y 2))
and also the extended form annotate macro. There is also the of macro (detailed here https://hyrule.readthedocs.io/en/master/index.html#hyrule.misc.of):

Make [StackExp] instance of Expr class

I make class Expr for arithmetic operations
class Expr a where
mul :: a -> a -> a
add :: a -> a -> a
lit :: Integer -> a
i want to "parse" something like this: mul ( add (lit 3) (lit 2)) (lit 4) = (3+2)*4
and i have data type:
data StackExp = PushI Integer
| PushB Bool
| Add
| Mul
| And
| Or
deriving Show
and
type Program = [StackExp] --i use this type for function of stack calculator later
my task is: i need to make instance of Expr for type Program
more concrete - i want to make this transformation:
mul ( add (lit 3) (lit 2)) (lit 4) ->>> [PushI 2, PushI 3, Add, PushI 4, Mul]
i have problems because i receive [[StackExp]] at the output of my instance declaration.
my try:
instance Expr Program where
lit n = (PushI n):[]
add exp1 exp2 = exp1:(exp2:[Add])
mul exp1 exp2 = exp1:(exp2:[Mul])
i don't know how to concatenate all sub-expressions into list
---------------- compiler error looks like this------------------------
Couldn't match type `[StackExp]' with `StackExp'
Expected type: StackExp
Actual type: Program
..........
So, what you basically want to do is you want to compile from the abstract syntax of your expression language (the type class Expr) to code for a simple stack machine (a list of elements of type StackExpr).
One problem that you immediately run into then is that, in just Haskell 98 or Haskell 2010, you cannot declare [StackExpr] an instance of a class. For example, GHC will complain with
Illegal instance declaration for `Expr [StackExp]'
(All instance types must be of the form (T a1 ... an)
where a1 ... an are *distinct type variables*,
and each type variable appears at most once in the instance head.
Use -XFlexibleInstances if you want to disable this.)
In the instance declaration for `Expr [StackExp]'
To work your way around this, you could define Program as a type isomorphism (rather than as a mere type synonym as you have now):
newtype Program = P [StackExp] deriving Show
and then make Program an instance of the class Expr. (Alternatively, you could enable FlexibleInstances as suggested by the error message above.)
Now we can write the required instance declaration:
instance Expr Program where
mul (P x) (P y) = P (x ++ y ++ [Mul])
add (P x) (P y) = P (x ++ y ++ [Add])
lit n = P [PushI n]
That is, for multiplication and addition, we first compile the operands and then produce, respectively, the Mul or Add instruction; for literals we produce the corresponding push instruction.
With this declaration, we get, for your example:
> mul (add (lit 3) (lit 2)) (lit 4) :: Program
P [PushI 3,PushI 2,Add,PushI 4,Mul]
(Not quite as in your example. You swap the order of the operands to Add. As addition is commutative, I will assume that this version is acceptable as well.)
Of course it is more fun to also write a small evaluator for stack programs:
eval :: Program -> [Integer]
eval (P es) = go es []
where
go [] s = s
go (PushI n : es) s = go es (n : s)
go (Add : es) (m : n : s) = go es ((m + n) : s)
go (Mul : es) (m : n : s) = go es ((m * n) : s)
(Note that I am ignoring instructions that deal with Booleans here as you only seem to deal with integer expressions anyway.)
Now we have, for your example,
> eval (mul (add (lit 3) (lit 2)) (lit 4))
[20]
which seems about right.

Why does my CoffeeScript program issue 'number is not a function' error?

In the program below the first two logs work fine. I'm not doing anything new in the third and final log but somehow it crashes at runtime. Where is the error in my script? I have looked it over a large number of times and it seems like a fairly trivial modification of the proven working code above it.
sumSq = (n) -> ([0..n].map (i) -> i * i).reduce (a, b) -> a + b
sq = (n) -> n * n
sqSum = ((n) -> ([0..n].reduce (a, b) -> a + b))
console.log(sqSum 5)
console.log(sq(sqSum 5))
newSqSum = sq ((n) -> ([0..n].reduce (a, b) -> a + b))
console.log(newSqSum(5))
This is a function, not a number:
(n) -> ([0..n].reduce (a, b) -> a + b)
so when you say this:
newSqSum = sq ((n) -> ([0..n].reduce (a, b) -> a + b))
you're calling sq with a function as its argument. Then sq will try to multiply that function with itself and the result will be NaN because there is no sensible numeric representation of a function. And finally, your third console.log tries to call that NaN value as function and there's your error message.
Something of the form fn1 fn2, for functions f1 and f2, is not a function composition, it is in fact the same as writing fn1(fn2) and that won't produce a new function unless fn1 is explicitly constructed to return a function. If you want to compose the functions then I think you need to do it by hand:
newSqSum = (n) -> sq ((n) -> ([0..n].reduce (a, b) -> a + b)) n
# Or with less hate for the people maintaining your code:
newSqSum = (n) -> sq sqSum n

Too many possible configurations in z3 using scala^z3

This is mainly a logic problem I guess...
I use this smtlib formula:
(declare-fun a () Bool)
(declare-fun b () Bool)
(declare-fun c () Bool)
(declare-fun d () Bool)
(assert (xor (and a (xor b c)) d))
Which is a term of this structure(in my opinion, at least):
XOR
| |
AND d
| |
a XOR
| |
b c
My guess: The resultSet would look like this:
{ab, ac, d}
But its this using scala^z3 ctx.checkAndGetAllModels():
{ab, d, ac, ad, abcd}
Why is ad and abcd in there?
Is it possible to get only the results I would expect?
Using Scala (without Z3) to show that there are, in fact, more solutions to the constraint:
val tf = Seq(true, false)
val allValid =
for(a <- tf; b <- tf; c <- tf; d <- tf;
if((a && (b ^ c)) ^ d)) yield (
(if(a) "a" else "") + (if(b) "b" else "") +
(if(c) "c" else "") + (if(d) "d" else ""))
allValid.mkString("{ ", ", ", " }")
Prints:
{ abcd, ab, ac, ad, bcd, bd, cd, d }
So unless I'm missing something, the question is, why does it not find all solutions? Now here is the answer to that one. (Spoiler alert: "getAllModels" doesn't really get all models.) First, let's reproduce what you observed:
import z3.scala._
val ctx = new Z3Context("MODEL" -> true)
val a = ctx.mkFreshConst("a", ctx.mkBoolSort)
val b = ctx.mkFreshConst("b", ctx.mkBoolSort)
val c = ctx.mkFreshConst("c", ctx.mkBoolSort)
val d = ctx.mkFreshConst("d", ctx.mkBoolSort)
val cstr0 = ctx.mkXor(b, c)
val cstr1 = ctx.mkAnd(a, cstr0)
val cstr2 = ctx.mkXor(cstr1, d)
ctx.assertCnstr(cstr2)
Now, if I run: ctx.checkAndGetAllModels.foreach(println(_)), I get:
d!3 -> false
a!0 -> true
c!2 -> false
b!1 -> true
d!3 -> true // this model is problematic
a!0 -> false
d!3 -> false
a!0 -> true
c!2 -> true
b!1 -> false
d!3 -> true
a!0 -> true
c!2 -> false
b!1 -> false
d!3 -> true
a!0 -> true
c!2 -> true
b!1 -> true
Now, the problem is that the second model is an incomplete model. Z3 can return it, because whatever the values for b and c are, the constraint is satisfied (b and c are don't-care variables). The current implementation of checkAndGetAllModels simply negates the model to prevent repetition; in this case, it will ask for another model such that (not (and d (not a))) holds. This will prevent all other models with this two values from being returned. In a sense, the incomplete model actually represents four valid, completed, models.
By the way, what happens if you use the DSL of ScalaZ3 with the findAll function is that all models will be completed with default values when they are incomplete (and before they are used to compute the next one). In the context of the DSL we can do this, because we know the set of variables that appear in the formula. In this case, it's harder to guess how the model should be completed. One option would be for ScalaZ3 to remember which variables were used. A better solution would be for Z3 to have an option to always return values for don't-care variables, or perhaps simply to list all don't-care variables in a model.

Calculating the Moving Average of a List

This weekend I decided to try my hand at some Scala and Clojure. I'm proficient with object oriented programming, and so Scala was easy to pick up as a language, but wanted to try out functional programming. This is where it got hard.
I just can't seem to get my head into a mode of writing functions. As an expert functional programmer, how do you approach a problem?
Given a list of values and a defined period of summation, how would you generate a new list of the simple moving average of the list?
For example: Given the list values (2.0, 4.0, 7.0, 6.0, 3.0, 8.0, 12.0, 9.0, 4.0, 1.0), and the period 4, the function should return: (0.0, 0.0, 0.0, 4.75, 5.0, 6.0, 7.25, 8.0, 8.25, 6.5)
After spending a day mulling it over, the best I could come up with in Scala was this:
def simpleMovingAverage(values: List[Double], period: Int): List[Double] = {
(for (i <- 1 to values.length)
yield
if (i < period) 0.00
else values.slice(i - period, i).reduceLeft(_ + _) / period).toList
}
I know this is horribly inefficient, I'd much rather do something like:
where n < period: ma(n) = 0
where n = period: ma(n) = sum(value(1) to value(n)) / period
where n > period: man(n) = ma(n -1) - (value(n-period) / period) + (value(n) / period)
Now that would be easily done in a imperative style, but I can't for the life of me work out how to express that functionally.
Interesting problem. I can think of many solutions, with varying degrees of efficiency. Having to add stuff repeatedly isn't really a performance problem, but let's assume it is. Also, the zeroes at the beginning can be prepended later, so let's not worry about producing them. If the algorithm provides them naturally, fine; if not, we correct it later.
Starting with Scala 2.8, the following would give the result for n >= period by using sliding to get a sliding window of the List:
def simpleMovingAverage(values: List[Double], period: Int): List[Double] =
List.fill(period - 1)(0.0) ::: (values sliding period map (_.sum) map (_ / period))
Nevertheless, although this is rather elegant, it doesn't have the best performance possible, because it doesn't take advantage of already computed additions. So, speaking of them, how can we get them?
Let's say we write this:
values sliding 2 map sum
We have a list of the sum of each two pairs. Let's try to use this result to compute the moving average of 4 elements. The above formula made the following computation:
from d1, d2, d3, d4, d5, d6, ...
to (d1+d2), (d2+d3), (d3+d4), (d4+d5), (d5+d6), ...
So if we take each element and add it to the second next element, we get the moving average for 4 elements:
(d1+d2)+(d3+d4), (d2+d3)+(d4+d5), (d3+d4)+(d5+d6), ...
We may do it like this:
res zip (res drop 2) map Function.tupled(_+_)
We could then compute the moving average for 8 elements, and so on. Well, there is a well known algorithm to compute things that follow such pattern. It's most known for its use on computing the power of a number. It goes like this:
def power(n: Int, e: Int): Int = e match {
case 0 => 1
case 1 => n
case 2 => n * n
case odd if odd % 2 == 1 => power(n, (odd - 1)) * n
case even => power(power(n, even / 2), 2)
}
So, let's apply it here:
def movingSum(values: List[Double], period: Int): List[Double] = period match {
case 0 => throw new IllegalArgumentException
case 1 => values
case 2 => values sliding 2 map (_.sum)
case odd if odd % 2 == 1 =>
values zip movingSum(values drop 1, (odd - 1)) map Function.tupled(_+_)
case even =>
val half = even / 2
val partialResult = movingSum(values, half)
partialResult zip (partialResult drop half) map Function.tupled(_+_)
}
So, here's the logic. Period 0 is invalid, period 1 is equal to the input, period 2 is sliding window of size 2. If greater than that, it may be even or odd.
If odd, we add each element to the movingSum of the next (odd - 1) elements. For example, if 3, we add each element to the movingSum of the next 2 elements.
If even, we compute the movingSum for n / 2, then add each element to the one n / 2 steps afterwards.
With that definition, we can then go back to the problem and do this:
def simpleMovingAverage(values: List[Double], period: Int): List[Double] =
List.fill(period - 1)(0.0) ::: (movingSum(values, period) map (_ / period))
There's a slight inefficiency with regards to the use of :::, but it's O(period), not O(values.size). It can be made more efficient with a tail recursive function. And, of course, the definition of "sliding" I provided is horrendous performance-wise, but there will be a much better definition of it on Scala 2.8. Note that we can't make an efficient sliding method on a List, but we can do it on an Iterable.
Having said all that, I'd go with the very first definition, and optimize only if a critical path analysis pinpointed this as a big deal.
To conclude, let's consider how I went about the problem. We have a moving average problem. A moving average is the sum of a moving "window" on a list, divided by the size of that window. So, first, I try to get a sliding window, sum everything on it, and then divide by the size.
The next problem was to avoid repetition of already computed additions. In this case, I went to the smallest addition possible, and tried to figure out how to compute bigger sums reusing such results.
Finally, let's try to solve the problem the way you figured it, by adding and subtracting from the previous result. Getting the first average is easy:
def movingAverage(values: List[Double], period: Int): List[Double] = {
val first = (values take period).sum / period
Now we make two lists. First, the list of elements to be subtracted. Next, the list of elements to be added:
val subtract = values map (_ / period)
val add = subtract drop period
We can add these two lists by using zip. This method will only produce as many elements as the smaller list has, which avoids the problem of subtract being bigger than necessary:
val addAndSubtract = add zip subtract map Function.tupled(_ - _)
We finish by composing the result with a fold:
val res = (addAndSubtract.foldLeft(first :: List.fill(period - 1)(0.0)) {
(acc, add) => (add + acc.head) :: acc
}).reverse
which is the answer to be returned. The whole function looks like this:
def movingAverage(values: List[Double], period: Int): List[Double] = {
val first = (values take period).sum / period
val subtract = values map (_ / period)
val add = subtract drop period
val addAndSubtract = add zip subtract map Function.tupled(_ - _)
val res = (addAndSubtract.foldLeft(first :: List.fill(period - 1)(0.0)) {
(acc, add) => (add + acc.head) :: acc
}).reverse
res
}
I know Clojure better than Scala, so here goes. As I write this the other Clojure entry here is imperative; that's not really what you're after (and isn't idiomatic Clojure). The first algorithm that comes to my mind is repeatedly taking the requested number of elements from the sequence, dropping the first element, and recurring.
The following works on any kind of sequence (vector or list, lazy or not) and gives a lazy sequence of averages---which could be helpful if you're working on a list of indefinite size. Note that it takes care of the base case by implicitly returning nil if there aren't enough elements in the list to consume.
(defn moving-average [values period]
(let [first (take period values)]
(if (= (count first) period)
(lazy-seq
(cons (/ (reduce + first) period)
(moving-average (rest values) period))))))
Running this on your test data yields
user> (moving-average '(2.0, 4.0, 7.0, 6.0, 3.0, 8.0, 12.0, 9.0, 4.0, 1.0) 4)
(4.75 5.0 6.0 7.25 8.0 8.25 6.5)
It doesn't give "0" for the first few elements in the sequence, though that could easily be handled (somewhat artificially).
The easiest thing of all is to see the pattern and be able to bring to mind an available function that fits the bill. partition gives a lazy view of portions of a sequence, which we can then map over:
(defn moving-average [values period]
(map #(/ (reduce + %) period) (partition period 1 values))
Someone asked for a tail recursive version; tail recursion vs. laziness is a bit of a tradeoff. When your job is building up a list then making your function tail recursive is usually pretty simple, and this is no exception---just build up the list as an argument to a subfunction. We'll accumulate to a vector instead of a list because otherwise the list will be built up backwards and will need to be reversed at the end.
(defn moving-average [values period]
(loop [values values, period period, acc []]
(let [first (take period values)]
(if (= (count first) period)
(recur (rest values) period (conj acc (/ (reduce + first) period)))
acc))))
loop is a way to make an anonymous inner function (sort of like Scheme's named let); recur must be used in Clojure to eliminate tail calls. conj is a generalized cons, appending in the manner natural for the collection---the beginning of lists and the end of vectors.
Here is another (functional) Clojure solution:
(defn avarage [coll]
(/ (reduce + coll)
(count coll)))
(defn ma [period coll]
(map avarage (partition period 1 coll)))
The zeros at the beginning of the sequence must still be added if that is a requirement.
Here's a purely functional solution in Clojure. More complex than those already provided, but it is lazy and only adjusts the average at each step, instead of recalculating it from scratch. It's actually slower than a simple solution which calculates a new average at each step if the period is small; for larger periods, however, it experiences virtually no slowdown, whereas something doing (/ (take period ...) period) will perform worse for longer periods.
(defn moving-average
"Calculates the moving average of values with the given period.
Returns a lazy seq, works with infinite input sequences.
Does not include initial zeros in the output."
[period values]
(let [gen (fn gen [last-sum values-old values-new]
(if (empty? values-new)
nil
(let [num-out (first values-old)
num-in (first values-new)
new-sum (+ last-sum (- num-out) num-in)]
(lazy-seq
(cons new-sum
(gen new-sum
(next values-old)
(next values-new)))))))]
(if (< (count (take period values)) period)
nil
(map #(/ % period)
(gen (apply + (take (dec period) values))
(cons 0 values)
(drop (dec period) values))))))
Here's a partially point-free one line Haskell solution:
ma p = reverse . map ((/ (fromIntegral p)) . sum . take p) . (drop p) . reverse . tails
First it applies tails to the list to get the "tails" lists, so:
Prelude List> tails [2.0, 4.0, 7.0, 6.0, 3.0]
[[2.0,4.0,7.0,6.0,3.0],[4.0,7.0,6.0,3.0],[7.0,6.0,3.0],[6.0,3.0],[3.0],[]]
Reverses it and drops the first 'p' entries (taking p as 2 here):
Prelude List> (drop 2 . reverse . tails) [2.0, 4.0, 7.0, 6.0, 3.0]
[[6.0,3.0],[7.0,6.0,3.0],[4.0,7.0,6.0,3.0],[2.0,4.0,7.0,6.0,3.0]]
In case you aren't familiar with the (.) dot/nipple symbol, it is the operator for 'functional composition', meaning it passes the output of one function as the input of another, "composing" them into a single function. (g . f) means "run f on a value then pass the output to g", so ((f . g) x) is the same as (g(f x)). Generally its usage leads to a clearer programming style.
It then maps the function ((/ (fromIntegral p)) . sum . take p) onto the list. So for every list in the list it takes the first 'p' elements, sums them, then divides them by 'p'. Then we just flip the list back again with "reverse".
Prelude List> map ((/ (fromIntegral 2)) . sum . take 2) [[6.0,3.0],[7.0,6.0,3.0]
,[4.0,7.0,6.0,3.0],[2.0,4.0,7.0,6.0,3.0]]
[4.5,6.5,5.5,3.0]
This all looks a lot more inefficient than it is; "reverse" doesn't physically reverse the order of a list until the list is evaluated, it just lays it out onto the stack (good ol' lazy Haskell). "tails" also doesn't create all those separate lists, it just references different sections of the original list. It's still not a great solution, but it one line long :)
Here's a slightly nicer but longer solution that uses mapAccum to do a sliding subtraction and addition:
ma p l = snd $ mapAccumL ma' a l'
where
(h, t) = splitAt p l
a = sum h
l' = (0, 0) : (zip l t)
ma' s (x, y) = let s' = (s - x) + y in (s', s' / (fromIntegral p))
First we split the list into two parts at "p", so:
Prelude List> splitAt 2 [2.0, 4.0, 7.0, 6.0, 3.0]
([2.0,4.0],[7.0,6.0,3.0])
Sum the first bit:
Prelude List> sum [2.0, 4.0]
6.0
Zip the second bit with the original list (this just pairs off items in order from the two lists). The original list is obviously longer, but we lose this extra bit:
Prelude List> zip [2.0, 4.0, 7.0, 6.0, 3.0] [7.0,6.0,3.0]
[(2.0,7.0),(4.0,6.0),(7.0,3.0)]
Now we define a function for our mapAccum(ulator). mapAccumL is the same as "map", but with an extra running state/accumulator parameter, which is passed from the previous "mapping" to the next one as map runs through the list. We use the accumulator as our moving average, and as our list is formed of the element that has just left the sliding window and the element that just entered it (the list we just zipped), our sliding function takes the first number 'x' away from the average and adds the second number 'y'. We then pass the new 's' along and return 's' divided by 'p'. "snd" (second) just takes the second member of a pair (tuple), which is used to take the second return value of mapAccumL, as mapAccumL will return the accumulator as well as the mapped list.
For those of you not familiar with the $ symbol, it is the "application operator". It doesn't really do anything but it has a has "low, right-associative binding precedence", so it means you can leave out the brackets (take note LISPers), i.e. (f x) is the same as f $ x
Running (ma 4 [2.0, 4.0, 7.0, 6.0, 3.0, 8.0, 12.0, 9.0, 4.0, 1.0]) yields [4.75, 5.0, 6.0, 7.25, 8.0, 8.25, 6.5] for either solution.
Oh and you'll need to import the module "List" to compile either solution.
Here are 2 more ways to do moving average in Scala 2.8.0(one strict and one lazy). Both assume there are at least p Doubles in vs.
// strict moving average
def sma(vs: List[Double], p: Int): List[Double] =
((vs.take(p).sum / p :: List.fill(p - 1)(0.0), vs) /: vs.drop(p)) {(a, v) =>
((a._1.head - a._2.head / p + v / p) :: a._1, a._2.tail)
}._1.reverse
// lazy moving average
def lma(vs: Stream[Double], p: Int): Stream[Double] = {
def _lma(a: => Double, vs1: Stream[Double], vs2: Stream[Double]): Stream[Double] = {
val _a = a // caches value of a
_a #:: _lma(_a - vs2.head / p + vs1.head / p, vs1.tail, vs2.tail)
}
Stream.fill(p - 1)(0.0) #::: _lma(vs.take(p).sum / p, vs.drop(p), vs)
}
scala> sma(List(2.0, 4.0, 7.0, 6.0, 3.0, 8.0, 12.0, 9.0, 4.0, 1.0), 4)
res29: List[Double] = List(0.0, 0.0, 0.0, 4.75, 5.0, 6.0, 7.25, 8.0, 8.25, 6.5)
scala> lma(Stream(2.0, 4.0, 7.0, 6.0, 3.0, 8.0, 12.0, 9.0, 4.0, 1.0), 4).take(10).force
res30: scala.collection.immutable.Stream[Double] = Stream(0.0, 0.0, 0.0, 4.75, 5.0, 6.0, 7.25, 8.0, 8.25, 6.5)
The J programming language facilitates programs such as moving average. Indeed, there are fewer characters in (+/ % #)\ than in their label, 'moving average.'
For the values specified in this question (including the name 'values') here is a straightforward way to code this:
values=: 2 4 7 6 3 8 12 9 4 1
4 (+/ % #)\ values
4.75 5 6 7.25 8 8.25 6.5
We can describe this by using labels for components.
periods=: 4
average=: +/ % #
moving=: \
periods average moving values
4.75 5 6 7.25 8 8.25 6.5
Both examples use exactly the same program. The only difference is the use of more names in the second form. Such names can help readers who don't know the J primaries.
Let's look a bit further into what's going on in the subprogram, average. +/ denotes summation (Σ) and % denotes division (like the classical sign ÷). Calculating a tally (count) of items is done by # . The overall program, then, is the sum of values divided by the tally of values: +/ % #
The result of the moving-average calculation written here does not include the leading zeros expected in the original question. Those zeros are arguably not part of the intended calculation.
The technique used here is called tacit programming. It is pretty much the same as the point-free style of functional programming.
Here is Clojure pretending to be a more functional language. This is fully tail-recursive, btw, and includes leading zeroes.
(defn moving-average [period values]
(loop [[x & xs] values
window []
ys []]
(if (and (nil? x) (nil? xs))
;; base case
ys
;; inductive case
(if (< (count window) (dec period))
(recur xs (conj window x) (conj ys 0.0))
(recur xs
(conj (vec (rest window)) x)
(conj ys (/ (reduce + x window) period)))))))
(deftest test-moving-average
(is (= [0.0 0.0 0.0 4.75 5.0 6.0 7.25 8.0 8.25 6.5]
(moving-average 4 [2.0 4.0 7.0 6.0 3.0 8.0 12.0 9.0 4.0 1.0]))))
Usually I put the collection or list parameter last to make the function easier to curry. But in Clojure...
(partial moving-average 4)
... is so cumbersome, I usually end up doing this ...
#(moving-average 4 %)
... in which case, it doesn't really matter what order the parameters go.
Here's a clojure version:
Because of the lazy-seq, it's perfectly general and won't blow stack
(defn partialsums [start lst]
(lazy-seq
(if-let [lst (seq lst)]
(cons start (partialsums (+ start (first lst)) (rest lst)))
(list start))))
(defn sliding-window-moving-average [window lst]
(map #(/ % window)
(let [start (apply + (take window lst))
diffseq (map - (drop window lst) lst)]
(partialsums start diffseq))))
;; To help see what it's doing:
(sliding-window-moving-average 5 '(1 2 3 4 5 6 7 8 9 10 11))
start = (+ 1 2 3 4 5) = 15
diffseq = - (6 7 8 9 10 11)
(1 2 3 4 5 6 7 8 9 10 11)
= (5 5 5 5 5 5)
(partialsums 15 '(5 5 5 5 5 5) ) = (15 20 25 30 35 40 45)
(map #(/ % 5) (20 25 30 35 40 45)) = (3 4 5 6 7 8 9)
;; Example
(take 20 (sliding-window-moving-average 5 (iterate inc 0)))
This example makes use of state, since to me it's a pragmatic solution in this case, and a closure to create the windowing averaging function:
(defn make-averager [#^Integer period]
(let [buff (atom (vec (repeat period nil)))
pos (atom 0)]
(fn [nextval]
(reset! buff (assoc #buff #pos nextval))
(reset! pos (mod (+ 1 #pos) period))
(if (some nil? #buff)
0
(/ (reduce + #buff)
(count #buff))))))
(map (make-averager 4)
[2.0, 4.0, 7.0, 6.0, 3.0, 8.0, 12.0, 9.0, 4.0, 1.0])
;; yields =>
(0 0 0 4.75 5.0 6.0 7.25 8.0 8.25 6.5)
It is still functional in the sense of making use of first class functions, though it is not side-effect free. The two languages you mentioned both run on top of the JVM and thus both allow for state-management when necessary.
This solution is in Haskell, which is more familiar to me:
slidingSums :: Num t => Int -> [t] -> [t]
slidingSums n list = case (splitAt (n - 1) list) of
(window, []) -> [] -- list contains less than n elements
(window, rest) -> slidingSums' list rest (sum window)
where
slidingSums' _ [] _ = []
slidingSums' (hl : tl) (hr : tr) sumLastNm1 = sumLastN : slidingSums' tl tr (sumLastN - hl)
where sumLastN = sumLastNm1 + hr
movingAverage :: Fractional t => Int -> [t] -> [t]
movingAverage n list = map (/ (fromIntegral n)) (slidingSums n list)
paddedMovingAverage :: Fractional t => Int -> [t] -> [t]
paddedMovingAverage n list = replicate (n - 1) 0 ++ movingAverage n list
Scala translation:
def slidingSums1(list: List[Double], rest: List[Double], n: Int, sumLastNm1: Double): List[Double] = rest match {
case Nil => Nil
case hr :: tr => {
val sumLastN = sumLastNm1 + hr
sumLastN :: slidingSums1(list.tail, tr, n, sumLastN - list.head)
}
}
def slidingSums(list: List[Double], n: Int): List[Double] = list.splitAt(n - 1) match {
case (_, Nil) => Nil
case (firstNm1, rest) => slidingSums1(list, rest, n, firstNm1.reduceLeft(_ + _))
}
def movingAverage(list: List[Double], n: Int): List[Double] = slidingSums(list, n).map(_ / n)
def paddedMovingAverage(list: List[Double], n: Int): List[Double] = List.make(n - 1, 0.0) ++ movingAverage(list, n)
A short Clojure version that has the advantage of being O(list length) regardless of your period:
(defn moving-average [list period]
(let [accums (let [acc (atom 0)] (map #(do (reset! acc (+ #acc %1 ))) (cons 0 list)))
zeros (repeat (dec period) 0)]
(concat zeros (map #(/ (- %1 %2) period) (drop period accums) accums))))
This exploits the fact that you can calculate the sum of a range of numbers by creating a cumulative sum of the sequence (e.g. [1 2 3 4 5] -> [0 1 3 6 10 15]) and then subtracting the two numbers with an offset equal to your period.
It looks like you are looking for a recursive solution. In that case, I would suggest to slightly change the problem and aim for getting (4.75, 5.0, 6.0, 7.25, 8.0, 8.25, 6.5, 0.0, 0.0, 0.0) as a solution.
In that case, you can write the below elegant recursive solution in Scala:
def mavg(values: List[Double], period: Int): List[Double] = {
if (values.size < period) List.fill(values.size)(0.0) else
if (values.size == period) (values.sum / values.size) :: List.fill(period - 1)(0.0) else {
val rest: List[Double] = mavg(values.tail, period)
(rest.head + ((values.head - values(period))/period)):: rest
}
}
I know how I would do it in python (note: the first 3 elements with the values 0.0 are not returned since that is actually not the appropriate way to represent a moving average). I would imagine similar techniques will be feasible in Scala. Here are multiple ways to do it.
data = (2.0, 4.0, 7.0, 6.0, 3.0, 8.0, 12.0, 9.0, 4.0, 1.0)
terms = 4
expected = (4.75, 5.0, 6.0, 7.25, 8.0, 8.25, 6.5)
# Method 1 : Simple. Uses slices
assert expected == \
tuple((sum(data[i:i+terms])/terms for i in range(len(data)-terms+1)))
# Method 2 : Tracks slots each of terms elements
# Note: slot, and block mean the same thing.
# Block is the internal tracking deque, slot is the final output
from collections import deque
def slots(data, terms):
block = deque()
for datum in data :
block.append(datum)
if len(block) > terms : block.popleft()
if len(block) == terms :
yield block
assert expected == \
tuple(sum(slot)/terms for slot in slots(data, terms))
# Method 3 : Reads value one at a time, computes the sums and throws away read values
def moving_average((avgs, sums),val):
sums = tuple((sum + val) for sum in sums)
return (avgs + ((sums[0] / terms),), sums[1:] + (val,))
assert expected == reduce(
moving_average,
tuple(data[terms-1:]),
((),tuple(sum(data[i:terms-1]) for i in range(terms-1))))[0]
# Method 4 : Semantically same as method 3, intentionally obfuscates just to fit in a lambda
assert expected == \
reduce(
lambda (avgs, sums),val: tuple((avgs + ((nsum[0] / terms),), nsum[1:] + (val,)) \
for nsum in (tuple((sum + val) for sum in sums),))[0], \
tuple(data[terms-1:]),
((),tuple(sum(data[i:terms-1]) for i in range(terms-1))))[0]
Being late on the party, and new to functional programming too, I came to this solution with an inner function:
def slidingAvg (ixs: List [Double], len: Int) = {
val dxs = ixs.map (_ / len)
val start = (0.0 /: dxs.take (len)) (_ + _)
val head = List.make (len - 1, 0.0)
def addAndSub (sofar: Double, from: Int, to: Int) : List [Double] =
if (to >= dxs.length) Nil else {
val current = sofar - dxs (from) + dxs (to)
current :: addAndSub (current, from + 1, to + 1)
}
head ::: start :: addAndSub (start, 0, len)
}
val xs = List(2, 4, 7, 6, 3, 8, 12, 9, 4, 1)
slidingAvg (xs.map (1.0 * _), 4)
I adopted the idea, to divide the whole list by the period (len) in advance.
Then I generate the sum to start with for the len-first-elements.
And I generate the first, invalid elements (0.0, 0.0, ...) .
Then I recursively substract the first and add the last value.
In the end I listify the whole thing.
In Haskell pseudocode:
group4 (a:b:c:d:xs) = [a,b,c,d] : group4 (b:c:d:xs)
group4 _ = []
avg4 xs = sum xs / 4
running4avg nums = (map avg4 (group4 nums))
or pointfree
runnig4avg = map avg4 . group4
(Now one really should abstract the 4 out ....)
Using Haskell:
movingAverage :: Int -> [Double] -> [Double]
movingAverage n xs = catMaybes . (fmap avg . take n) . tails $ xs
where avg list = case (length list == n) -> Just . (/ (fromIntegral n)) . (foldl (+) 0) $ list
_ -> Nothing
The key is the tails function, which maps a list to a list of copies of the original list, with the property that the n-th element of the result is missing the first n-1 elements.
So
[1,2,3,4,5] -> [[1,2,3,4,5], [2,3,4,5], [3,4,5], [4,5], [5], []]
We apply fmap (avg . take n) to the result, which means we take the n-length prefix from the sublist, and compute its avg. If the length of the list we are avg'ing is not n, then we do not compute the average (since it is undefined). In that case, we return Nothing. If it is, we do, and wrap it in "Just". Finally, we run "catMaybes" on the result of fmap (avg . take n), to get rid of the Maybe type.
I was (surprised and) disappointed by the performance of what seemed to me the most idiomatic Clojure solutions, #JamesCunningham 's lazy-seq solutions.
(def integers (iterate inc 0))
(def coll (take 10000 integers))
(def n 1000)
(time (doall (moving-average-james-1 coll n)))
# "Elapsed time: 3022.862 msecs"
(time (doall (moving-average-james-2 coll n)))
# "Elapsed time: 3433.988 msecs"
So here's a combination of James' solution with #DanielC.Sobral 's idea of adapting fast-exponentiation to moving sums :
(defn moving-average
[coll n]
(letfn [(moving-sum [coll n]
(lazy-seq
(cond
(= n 1) coll
(= n 2) (map + coll (rest coll))
(odd? n) (map + coll (moving-sum (rest coll) (dec n)))
:else (let [half (quot n 2)
hcol (moving-sum coll half)]
(map + hcol (drop half hcol))))))]
(cond
(< n 1) nil
(= n 1) coll
:else (map #(/ % n) (moving-sum coll n)))))
(time (doall (moving-average coll n)))
# "Elapsed time: 42.034 msecs"
Edit: this one -based on #mikera 's solution- is even faster.
(defn moving-average
[coll n]
(cond
(< n 1) nil
(= n 1) coll
:else (let [sums (reductions + 0 coll)]
(map #(/ (- %1 %2) n) (drop n sums) sums))))
(time (doall (moving-average coll n)))
# "Elapsed time: 9.184 msecs"