Produce multiple models for CVC4 SMT queries - smt

Can I get multiple models for a query like the following?
(set-logic LIA)
(set-option :produce-models true)
(declare-const x Int)
(assert (< x 20))
(check-sat)
(get-model)
Instead of just
sat
(
(define-fun x () Int 0)
)
I'd like to get 0, 1, -1, 2, ...

SMTLib language does not have a mechanism to retrieve "all-models." So, if you're bound to be using SMTLib only, you cannot do this; at least not easily.
However, most solvers (definitely including cvc4 and z3) can be scripted from higher-level languages. The idea is to make a check-sat call, and if you get a solution, you add an additional assertion that disallows that model, and query for a new one. See this answer for how to do this in z3, as scripted from Python: Trying to find all solutions to a boolean formula using Z3 in python. You can do the same from C/Java etc.; or use a higher-level binding that provides such a command out-of-the box.

Related

How to print the entire model in cvc4 using smtlib

so I have just started to learn cvc4 after I have spent some time learning boolector. With it, it is possible to print the model just using boolector_print_model. Unfortunately the doc page for cvc4 is down at the moment and I cannot understand how to do the same with cvc4 in Java.
Can anyone help to do it please?
For instance, you could help me to see the model for this example.
EDIT: Just to be clear, with the entire model I mean a valid value for each BV or in general variable present within my model.
An example model could be:
(model
...
(define-fun number_6_0_7 () (_ BitVec 8) #x00)
(define-fun number_6_1_7 () (_ BitVec 8) #x00)
(define-fun number_6_2_7 () (_ BitVec 8) #x00)
(define-fun number_6_3_7 () (_ BitVec 8) #x78)
...
)
Thanks a lot
Unlike boolector, CVC4 does not have a mechanism of accessing the entire model in once call via the API. This is because CVC4 allows for much richer types, including data-types, uninterpreted-functions, etc.; which makes model construction more complicated.
Instead, you call the getValue method for each of the input variables you have, and print them yourself. Here's an example:
https://github.com/CVC4/CVC4/blob/e3cd4670a080554e4ae1f2f26ee4353d11f02f6b/examples/api/java/FloatingPointArith.java#L66-L68

Why does FParsec use lists?

I thought I'd try writing a fast parser using FParsec and quickly realised that many returning a list is a seriously performance problem. Then I discovered an alternative that uses a ResizeArray in the docs:
let manyA2 p1 p =
Inline.Many(firstElementParser = p1,
elementParser = p,
stateFromFirstElement = (fun x0 ->
let ra = ResizeArray<_>()
ra.Add(x0)
ra),
foldState = (fun ra x -> ra.Add(x); ra),
resultFromState = (fun ra -> ra.ToArray()),
resultForEmptySequence = (fun () -> [||]))
let manyA p = manyA2 p p
Using this in my code instead makes it run several times faster. So why does FParsec use lists by default instead of ResizeArray?
Using the built-in F# list type as the result type for the sequence combinators makes the combinators more convenient to use in F# and arguably leads to more idiomatic client-side code. Since most F# developers value simplicity and elegance over performance (at least in my experience) using lists as the default seemed like the right choice when I designed the API. At the same time I tried to make it easy for users to define their own specialized sequence combinators.
Currently the sequence combinators that return a list also use a list internally for building up the sequence. This is suboptimal for sequences with more than about 2 elements, as the list has to be reversed before it is returned. However, I'm not sure whether changing the implementation would be worth the effort, since if your parser is performance sensitive and you're parsing long sequence you're better off not using lists at all.
I probably should add a section about using arrays instead of lists to the user's guide chapter on performance.

Accessing members of composite sorts (data types) in SMT-LIBv2

According to sec. 3.9.3 of The SMT-LIBv2 Language and Tools: A Tutorial it is possible to declare a composite sort like this in SMT-LIBv2:
(set-logic QF_UF)
(declare-sort Triple 3)
(declare-fun state () (Triple Bool Bool Bool))
I am using CVC4 and it seems to accept this syntax. But how do I access the elements? I tried the following (and various variations of that and other things I found online):
(assert (_ state 1))
(assert (select 1 state))
But it looks like those operators only work on vectors and arrays. I can't find any example that uses such composite sorts and can't find anything about accessing those elements in the tutorial or the language standard. How is it done? Or did I completely misunderstand what this feature is for?
My application: I want to encode a temporal problem and want to do it in form of a state transition function that converts the old state into a new state, so I can write something like the following when experimenting with the system:
....
(declare-fun initial_state () MyStateSort)
(declare-fun state_after_step_1 () MyStateSort)
(declare-fun state_after_step_2 () MyStateSort)
(assert (= (MyTransitionFunc initial_state) state_after_step_1)
(assert (= (MyTransitionFunc state_after_step_1) state_after_step_2)
This is an answer to my own question. If anyone can post an example for a use-case of a user-defined sort with arity > 0, I'll happily accept that as answer.
After reading the SMT-LIBv2 standard more carefully I am now thinking that sort declarations with arity > 0 only have an application in theory definitions (for declaring sorts like Array), not in user-supplied code. The example in David Cok's Tutorial seems to be misleading, as it suggests that this can be used to declare composite sorts. I have not found any indication of that anywhere else. This includes the complete SMT-LIB benchmark that contains not a single sort declaration with arity > 0.
Instead of "composite sorts" one should use uninterpreted functions to create the equivalent of complex data structures. Example:
(set-logic QF_UF)
(declare-sort CONTAINER_SORT 0)
(declare-fun CONTAINER_MEMBER_1 (CONTAINER_SORT) Bool)
(declare-fun CONTAINER_MEMBER_2 (CONTAINER_SORT) Bool)
(declare-fun INSTANCE_1 () CONTAINER_SORT)
(declare-fun INSTANCE_2 () CONTAINER_SORT)
This will effectively declare the following 4 independent Bool expressions.
(CONTAINER_MEMBER_1 INSTANCE_1)
(CONTAINER_MEMBER_2 INSTANCE_1)
(CONTAINER_MEMBER_1 INSTANCE_2)
(CONTAINER_MEMBER_2 INSTANCE_2)

What is the correct way to select real solutions?

Suppose one needs to select the real solutions after solving some equation.
Is this the correct and optimal way to do it, or is there a better one?
restart;
mu := 3.986*10^5; T:= 8*60*60:
eq := T = 2*Pi*sqrt(a^3/mu):
sol := solve(eq,a);
select(x->type(x,'realcons'),[sol]);
I could not find real as type. So I used realcons. At first I did this:
select(x->not(type(x,'complex')),[sol]);
which did not work, since in Maple 5 is considered complex! So ended up with no solutions.
type(5,'complex');
(* true *)
Also I could not find an isreal() type of function. (unless I missed one)
Is there a better way to do this that one should use?
update:
To answer the comment below about 5 not supposed to be complex in maple.
restart;
type(5,complex);
true
type(5,'complex');
true
interface(version);
Standard Worksheet Interface, Maple 18.00, Windows 7, February
From help
The type(x, complex) function returns true if x is an expression of the form
a + I b, where a (if present) and b (if present) are finite and of type realcons.
Your solutions sol are all of type complex(numeric). You can select only the real ones with type,numeric, ie.
restart;
mu := 3.986*10^5: T:= 8*60*60:
eq := T = 2*Pi*sqrt(a^3/mu):
sol := solve(eq,a);
20307.39319, -10153.69659 + 17586.71839 I, -10153.69659 - 17586.71839 I
select( type, [sol], numeric );
[20307.39319]
By using the multiple argument calling form of the select command we here can avoid using a custom operator as the first argument. You won't notice it for your small example, but it should be more efficient to do so. Other commands such as map perform similarly, to avoid having to make an additional function call for each individual test.
The types numeric and complex(numeric) cover real and complex integers, rationals, and floats.
The types realcons and complex(realcons) includes the previous, but also allow for an application of evalf done during the test. So Int(sin(x),x=1..3) and Pi and sqrt(2) are all of type realcons since following an application of evalf they become floats of type numeric.
The above is about types. There are also properties to consider. Types are properties, but not necessarily vice versa. There is a real property, but no real type. The is command can test for a property, and while it is often used for mixed numeric-symbolic tests under assumptions (on the symbols) it can also be used in tests like yours.
select( is, [sol], real );
[20307.39319]
It is less efficient to use is for your example. If you know that you have a collection of (possibly non-real) floats then type,numeric should be an efficient test.
And, just to muddy the waters... there is a type nonreal.
remove( type, [sol], nonreal );
[20307.39319]
The one possibility is to restrict the domain before the calculation takes place.
Here is an explanation on the Maplesoft website regarding restricting the domain:
4 Basic Computation
UPD: Basically, according to this and that, 5 is NOT considered complex in Maple, so there might be some bug/error/mistake (try checking what may be wrong there).
For instance, try putting complex without quotes.
Your way seems very logical according to this.
UPD2: According to the Maplesoft Website, all the type checks are done with type() function, so there is rather no isreal() function.

Defensive functions, invariants, minimum noise

I like the use of require, assert, assume, and ensuring to document pre-conditions and post-conditions of a given function, but I have also come to use scalaz.Validation mostly to perform checks that require used to do. But, lately, I have been most interested in using PartialFunction, possibly with Validation, to document a pre-condition. Something like:
case class Summary(user: String, at: DateTime, ....)
val restricted_add: PartialFunction[(Summary, Summary), Summary] = {
case (s1: Summary, s2: Summary) if s1.user != s2.user && s1.at == s2.at =>
}
with a utility function for capturing and converting a match error into a validation failure (e.g. restricted_add.lift(_).toSucess("Cannot add.")). Somehow the case clause above seems less noisy than a For with scalaz.Validation. But I feel like I am going against the language. I'm not using def's natural syntax for defining parameters, every client of such a function would have to use a utility function when invoking it, I would be capturing exceptions and converting them into validations, instead of working only with validations or only with exceptions.
What seems like the least noisy, most functional way of documenting these pre-conditions through code? Validation returning functions, require statements, PartialFunction, other...?
As #RandallSchulz already stated, implicitly documenting preconditions in code only serves for your private/interal methods, never for your public API. If you're writing public methods, you should also document the preconditions in the methods docs and maybe the usage examples, if they're counter-intuitive.
That being said, in my opinion the least noisy and the most functional way are not the same in Scala. This is because require cannot be considered functional, since it throws an exception if the condition is not met, which would be catched somewhere, changing the control flow and thus being a side effect.
Nonetheless, I think that require is by far the least noisy way to specify a preconditions:
def non_func(x:Int, y:Int):Int = {
require(x >= 0 && y >= 0)
x + y
}
I'm not entirely sure about the most functional way to check preconditions, but I think that using pattern matching and returning an Option could be considered functional, but noisier than require:
def func(x:Int, y:Int):Option[Int] = (x,y) match {
case (x, y) if x >= 0 && y >= 0 => Some(x + y)
case _ => None
}
The advantage of using an Option is that you can flatMap that shit (scnr):
val xs = List((1,2), (0,0), (-1,0), (-1,-1), (3,4))
xs.flatMap(x => func(x._1, x._2)) # => List(3, 0, 7)
The alone is probably a good enough reason to add just a little more noise compared to require since it enables you to use a lot of the standard Scala library more concisely.
Regarding partial functions, you are basically answering your own question, since you say that its more cumbersome to use and to define. I don't have any experience with Scalaz though, so I can't really compare the "pure scala" approach to anything one might do with Scalaz.