How to print formulae and literals when using CVC5? - smt

I am playing with the CVC5 example at https://github.com/cvc5/cvc5/blob/main/examples/api/python/pythonic/linear_arith.py.
from cvc5.pythonic import *
slv = SolverFor('QF_LIRA')
x = Int('x')
y = Real('y')
slv += And(x >= 3 * y, x <= y, -2 < x)
slv.push()
print(slv.check(y-x <= 2/3))
slv.pop()
slv.push()
slv += y-x == 2/3
print(slv.check())
slv.pop()
It works as it is supposed to work.
However, whenever I try to print the content of the formula (i.e., print(slv)), it raises the following error: Cannot print: Kind.CONST_INTEGER
The same happens with literals that compound the formula: i.e., print(x >= 3); but not with variables: print(x) returns x.
I would like to have this printing capability, since Z3 allows it and I am trying my (originally-in-Z3-made) implementation with different SMT sovlers. Any idea?
Note that print(slv) does return info ([]), when it is empty. I tried using str(), but the error persists and indeed I guess print() uses str() before printing.
PS: I am using CVC5, should I use CVC4 or is CVC5 mature enough?

I think this is a bug. You should report it to the CVC5 folks at https://github.com/cvc5/cvc5/issues. (i.e., they should be able to handle this case just fine.)
In the interim, you can use the following workaround:
print(slv.sexpr())
which prints:
(and (let ((_let_1 (to_real x))) (and (>= _let_1 (* 3.0 y)) (<= _let_1 y) (> x (- 2)))))
which takes a bit of squinting to see that this is what you asserted, but it should do the trick.

Related

How to translate the Expr(Const number) in Z3 to be an object in MPQ/MPFR

When I use the Z3-opt(Ocaml version) to solve some planning problem, and I get a result from Z3 like this:
(+ (/ 31.0 10.0) (* (to_real (- 1)) epsilon))
And this result is of type of Z3.Expr. I want to know how to translate this result(of Z3.Expr) to anther common data-type object(for example, MPQ/MPFR).
Does the Z3-opt(Ocaml version) provide the ocaml interface to this?
Many thanks.

Converting a real into an integer in lisp

How can I convert a real number to an integer in LISP?
Is there any primitive function?
Example:
3.0 => 3
There are multiple ways.
I will be using f instead of a float number below.
If you're interested in the next-highest integer, (ceiling f) gives you that. If you are interested in the next-lowest integer, (floor f) gives you that (for values like 1.0, the two functions will return the same integer value). If you prefer having the closest integer, you can use (round f) to find it.
Those are the three simplest and most portable ways I can think of.
Other option is TRUNCATE. Examples
> (truncate 2.2)
=> 2
0.20000005
> (truncate 2.9)
=> 2
0.9000001

Calculating prime numbers in Scala: how does this code work?

So I've spent hours trying to work out exactly how this code produces prime numbers.
lazy val ps: Stream[Int] = 2 #:: Stream.from(3).filter(i =>
ps.takeWhile{j => j * j <= i}.forall{ k => i % k > 0});
I've used a number of printlns etc, but nothings making it clearer.
This is what I think the code does:
/**
* [2,3]
*
* takeWhile 2*2 <= 3
* takeWhile 2*2 <= 4 found match
* (4 % [2,3] > 1) return false.
* takeWhile 2*2 <= 5 found match
* (5 % [2,3] > 1) return true
* Add 5 to the list
* takeWhile 2*2 <= 6 found match
* (6 % [2,3,5] > 1) return false
* takeWhile 2*2 <= 7
* (7 % [2,3,5] > 1) return true
* Add 7 to the list
*/
But If I change j*j in the list to be 2*2 which I assumed would work exactly the same, it causes a stackoverflow error.
I'm obviously missing something fundamental here, and could really use someone explaining this to me like I was a five year old.
Any help would be greatly appreciated.
I'm not sure that seeking a procedural/imperative explanation is the best way to gain understanding here. Streams come from functional programming and they're best understood from that perspective. The key aspects of the definition you've given are:
It's lazy. Other than the first element in the stream, nothing is computed until you ask for it. If you never ask for the 5th prime, it will never be computed.
It's recursive. The list of prime numbers is defined in terms of itself.
It's infinite. Streams have the interesting property (because they're lazy) that they can represent a sequence with an infinite number of elements. Stream.from(3) is an example of this: it represents the list [3, 4, 5, ...].
Let's see if we can understand why your definition computes the sequence of prime numbers.
The definition starts out with 2 #:: .... This just says that the first number in the sequence is 2 - simple enough so far.
The next part defines the rest of the prime numbers. We can start with all the counting numbers starting at 3 (Stream.from(3)), but we obviously need to filter a bunch of these numbers out (i.e., all the composites). So let's consider each number i. If i is not a multiple of a lesser prime number, then i is prime. That is, i is prime if, for all primes k less than i, i % k > 0. In Scala, we could express this as
nums.filter(i => ps.takeWhile(k => k < i).forall(k => i % k > 0))
However, it isn't actually necessary to check all lesser prime numbers -- we really only need to check the prime numbers whose square is less than or equal to i (this is a fact from number theory*). So we could instead write
nums.filter(i => ps.takeWhile(k => k * k <= i).forall(k => i % k > 0))
So we've derived your definition.
Now, if you happened to try the first definition (with k < i), you would have found that it didn't work. Why not? It has to do with the fact that this is a recursive definition.
Suppose we're trying to decide what comes after 2 in the sequence. The definition tells us to first determine whether 3 belongs. To do so, we consider the list of primes up to the first one greater than or equal to 3 (takeWhile(k => k < i)). The first prime is 2, which is less than 3 -- so far so good. But we don't yet know the second prime, so we need to compute it. Fine, so we need to first see whether 3 belongs ... BOOM!
* It's pretty easy to see that if a number n is composite then the square of one of its factors must be less than or equal to n. If n is composite, then by definition n == a * b, where 1 < a <= b < n (we can guarantee a <= b just by labeling the two factors appropriately). From a <= b it follows that a^2 <= a * b, so it follows that a^2 <= n.
Your explanations are mostly correct, you made only two mistakes:
takeWhile doesn't include the last checked element:
scala> List(1,2,3).takeWhile(_<2)
res1: List[Int] = List(1)
You assume that ps always contains only a two and a three but because Stream is lazy it is possible to add new elements to it. In fact each time a new prime is found it is added to ps and in the next step takeWhile will consider this new added element. Here, it is important to remember that the tail of a Stream is computed only when it is needed, thus takeWhile can't see it before forall is evaluated to true.
Keep these two things in mind and you should came up with this:
ps = [2]
i = 3
takeWhile
2*2 <= 3 -> false
forall on []
-> true
ps = [2,3]
i = 4
takeWhile
2*2 <= 4 -> true
3*3 <= 4 -> false
forall on [2]
4%2 > 0 -> false
ps = [2,3]
i = 5
takeWhile
2*2 <= 5 -> true
3*3 <= 5 -> false
forall on [2]
5%2 > 0 -> true
ps = [2,3,5]
i = 6
...
While these steps describe the behavior of the code, it is not fully correct because not only adding elements to the Stream is lazy but every operation on it. This means that when you call xs.takeWhile(f) not all values until the point when f is false are computed at once - they are computed when forall wants to see them (because it is the only function here that needs to look at all elements before it definitely can result to true, for false it can abort earlier). Here the computation order when laziness is considered everywhere (example only looking at 9):
ps = [2,3,5,7]
i = 9
takeWhile on 2
2*2 <= 9 -> true
forall on 2
9%2 > 0 -> true
takeWhile on 3
3*3 <= 9 -> true
forall on 3
9%3 > 0 -> false
ps = [2,3,5,7]
i = 10
...
Because forall is aborted when it evaluates to false, takeWhile doesn't calculate the remaining possible elements.
That code is easier (for me, at least) to read with some variables renamed suggestively, as
lazy val ps: Stream[Int] = 2 #:: Stream.from(3).filter(i =>
ps.takeWhile{p => p * p <= i}.forall{ p => i % p > 0});
This reads left-to-right quite naturally, as
primes are 2, and those numbers i from 3 up, that all of the primes p whose square does not exceed the i, do not divide i evenly (i.e. without some non-zero remainder).
In a true recursive fashion, to understand this definition as defining the ever increasing stream of primes, we assume that it is so, and from that assumption we see that no contradiction arises, i.e. the truth of the definition holds.
The only potential problem after that, is the timing of accessing the stream ps as it is being defined. As the first step, imagine we just have another stream of primes provided to us from somewhere, magically. Then, after seeing the truth of the definition, check that the timing of the access is okay, i.e. we never try to access the areas of ps before they are defined; that would make the definition stuck, unproductive.
I remember reading somewhere (don't recall where) something like the following -- a conversation between a student and a wizard,
student: which numbers are prime?
wizard: well, do you know what number is the first prime?
s: yes, it's 2.
w: okay (quickly writes down 2 on a piece of paper). And what about the next one?
s: well, next candidate is 3. we need to check whether it is divided by any prime whose square does not exceed it, but I don't yet know what the primes are!
w: don't worry, I'l give them to you. It's a magic I know; I'm a wizard after all.
s: okay, so what is the first prime number?
w: (glances over the piece of paper) 2.
s: great, so its square is already greater than 3... HEY, you've cheated! .....
Here's a pseudocode1 translation of your code, read partially right-to-left, with some variables again renamed for clarity (using p for "prime"):
ps = 2 : filter (\i-> all (\p->rem i p > 0) (takeWhile (\p->p^2 <= i) ps)) [3..]
which is also
ps = 2 : [i | i <- [3..], and [rem i p > 0 | p <- takeWhile (\p->p^2 <= i) ps]]
which is a bit more visually apparent, using list comprehensions. and checks that all entries in a list of Booleans are True (read | as "for", <- as "drawn from", , as "such that" and (\p-> ...) as "lambda of p").
So you see, ps is a lazy list of 2, and then of numbers i drawn from a stream [3,4,5,...] such that for all p drawn from ps such that p^2 <= i, it is true that i % p > 0. Which is actually an optimal trial division algorithm. :)
There's a subtlety here of course: the list ps is open-ended. We use it as it is being "fleshed-out" (that of course, because it is lazy). When ps are taken from ps, it could potentially be a case that we run past its end, in which case we'd have a non-terminating calculation on our hands (a "black hole"). It just so happens :) (and needs to ⁄ can be proved mathematically) that this is impossible with the above definition. So 2 is put into ps unconditionally, so there's something in it to begin with.
But if we try to "simplify",
bad = 2 : [i | i <- [3..], and [rem i p > 0 | p <- takeWhile (\p->p < i) bad]]
it stops working after producing just one number, 2: when considering 3 as the candidate, takeWhile (\p->p < 3) bad demands the next number in bad after 2, but there aren't yet any more numbers there. It "jumps ahead of itself".
This is "fixed" with
bad = 2 : [i | i <- [3..], and [rem i p > 0 | p <- [2..(i-1)] ]]
but that is a much much slower trial division algorithm, very far from the optimal one.
--
1 (Haskell actually, it's just easier for me that way :) )

Using 'ash' in LISP to perform a binary search?

So, I'm reading Land of Lisp now, and Lisp is turning out to be quite different than other programming languages that I've seen.
Anyways, the book provides some code that we're meant to enter into the CLISP REPL:
(defparameter *small* 1)
(defparameter *big* 100)
(defun guess-my-number ()
(ash (+ *small* *big*) -1))
(defun smaller ()
(setf *big* (1- (guess-my-number)))
(guess-my-number))
(defun bigger ()
(setf *small* (1+ (guess-my-number)))
(guess-my-number))
Now, the basic goal is to create a number guessing game wherein the user/player chooses a number, and then the computer tries to guess the number. It performs a "binary search", to find the player's number, by having the player report whether the computer-guessed number is higher or lower than the player's number.
I'm a little bit confused about the ash function. It's my understanding that this is vital to the binary search, but I'm not really sure why. The book somewhat explains what it does, but it's a little confusing.
What does the ash function do? Why is it passed the parameters of *small* added to *big* and -1? How does it work? What purpose does it serve to the binary search?
Google gives you this page which explains that ash is an arithmetic shift operation. So (ash x -1) shift x by one bit to the right, so gives its integer half.
Thanks to Basile Starynkevitch for the help on this one...
Anyhow, ash performs an arithmetic shift operation.
In the case of (ash x -1) it shifts x by one bit to the right, which ultimately returns the integer half.
For example, consider the binary number 1101. 1101 in binary is equivalent to 13 in decimal, which can be calculated like so:
8 * 1 = 8
4 * 1 = 4
2 * 0 = 0
1 * 1 = 1
8 + 4 + 0 + 1 = 13
Running (ash 13 -1) would look at the binary representation of 13, and perform an arithmetic shift of -1, shifting all the bits to the right by 1. This would produce a binary output of 110 (chopping off the 1 at the end of the original number). 110 in binary is equivalent to 6 in decimal, which can be calculated like so:
4 * 1 = 4
2 * 1 = 2
1 * 0 = 0
4 + 2 + 0 = 6
Now, 13 divided by 2 is not equivalent to 6, it's equivalent to 6.5, however, since it will return the integer half, 6 is the acceptable answer.
This is because binary is base 2.
Q. What does the ash function do? Why is it passed the parameters of small added to big and -1? How does it work? What purpose does it serve to the binary search?
It does operation of of shifting bits, more precisely Arithmetic shifting as explained/represented graphically for particular case of Lisp:
> (ash 51 1)
102
When you do (ash 51 1) it will shift the binary of 51 i.e 110011 by 1 bit place towards left side and results in 1100110 which gives you 102 in decimal. (process of binary to decimal conversion is explained in this answer)
Here it adds 0 in the vacant most right place (called Least Significant Bit).
> (ash 51 -1)
25
When you do (ash 51 -1) it will shift the binary of 51 i.e 110011 by 1 bit place towards right side (negative value stands for opposite direction) and results in 11001 which gives you 102 in decimal.
Here it discards the redundant LSB.
In particular example of "guess-my-number" game illustrated in Land of Lisp, we are interested in halving the range or to average. So, (ash (+ *small* *big*) -1)) will do halving of 100+1 = 100 / 2 to result in 50. We can check it as follows:
> (defparameter *small* 1)
*SMALL*
> (defparameter *big* 100)
*BIG*
>
(defun guess-my-number ()
(ash (+ *small* *big*) -1))
GUESS-MY-NUMBER
> (guess-my-number)
50
An interesting thing to notice is you can double the value of integer by left shifting by 1 bit and (approximately) halve it by right shifting by 1 bit.

What is the preferred order for operands in boolean expressions?

Is there any benefit to structuring boolean expressions like:
if (0 < x) { ... }
instead of
if (x > 0) { ... }
I have always used the second way, always putting the variable as the first operand and using whatever boolean operator makes sense, but lately I have read code that uses the first method, and after getting over the initial weirdness I am starting to like it a lot more.
Now I have started to write all my boolean expressions to only use < or <= even if this means the variable isn't the first operand, like the above example. To me it seems to increase readability, but that might just be me :)
What do other people think about this?
Do whatever is most natural for whatever expression you are trying to compare.
If you're wondering about other operations (like ==) there are previous topics comparing the orderings of operands for those comparisons (and the reasons why).
It is mostly done to avoid the problem of using = instead of == in if conditions. To keep the consistency many people use the same for with other operators also. I do not see any problem in doing it.
Use whatever 'reads' best. One thing I'd point out is that if I'm testing to see if a value is within bounds, I try to write it so the bounds are on the 'outside' just like they might be in a mathematical expression:
So, to test that (0 < x <= 10):
if ((0 < x) && (x <= 10)) { ... }
instead of
if ((0 < x) && (10 >= x)) { ... }
or
if ((x > 0) && (10 >= x)) { ... }
I find this pattern make is somewhat easier to follow the logic.
An advantage for putting the number first is that it can prevent bug of using = when == is wanted.
if ( 0 == x ) // ok
if ( 0 = x ) //is a compiler error
compare to the subtle bug:
if ( x = 0 ) // assignment and not comparison. most likely a typo
To be honest it's unusual to write expressions with the variable on the right-side, and as a direct consequence of that unusualness readability suffers. Coding conventions have intrinsic value merely by virtue of being conventions; people are used to code being written in particular standard ways, x >= 0 being one example. Unnecessarily deviating from simple norms like these should be avoided without good cause.
The fact that you had to "get over the initial weirdness" should perhaps be a red flag.
I would not write 0 < x just as I would not use Hungarian notation in Java. When in Rome, do as the Romans do. The Romans write x >= 0. No, it's not a huge deal, it just seems like an unnecessary little quirk.