I'm using Z3-3.2's c-api (on linux) for solving QF_AUFBV problems.
If the formula is satisfiable, I'd like to read out the value of the free array variables from the model.
I tried something along the lines of the following code and I'd like to know if the general idea of how to do this is right:
void evaluate(Z3_context context, Z3_model model, Z3_ast array)
{
Z3_ast value;
Z3_bool success = Z3_eval(context, model, array, &value);
if (success) {
unsigned num_entries;
if (Z3_is_array_value(context, model, value, &num_entries)) {
Z3_ast indices[num_entries];
Z3_ast values[num_entries];
Z3_ast def;
Z3_get_array_value(context, model, array, num_entries, indices, values, &def);
// do something with indices, values, and def
}
}
}
The input Z3_ast array is definitely a free array expression. Z3_eval returns true, so we seem to have successfully evaluated the expression, but then Z3_is_array_value returns false. I would have expected the result of a successfull Z3_eval on an array expression to be an array value, so why is this not the case?
By the way: We managed to get at the desired information by iterating over all model_func_decls and trying to find the right one for that array by comparing their get_symbol_string. So the information seems to be available somewhere in Z3, but that hardly counts as a nice solution.
Thanks for any help on this.
Best regards,
Florian
The evaluator is a bit more powerful than the API for accessing array values.
The function is_array_value succeeds only when the represented array is of the form
(store (store (store (... (const v) ...) ..)..))
or of the form as-array[f], where f is a finite unary function.
The is_array_value and get_array_value functions can be implemented using the existing API
and are exposed for convenience
(as you describe, except we can avoid using string comparisons and instead use comparisons on
the function declarations that are enumeration sorts).
So it sounds like we would be able to support more in your case and I am curious how the model value
looks like. Would you be able to provide additional information about the example that does not pass? (print it?)
Thanks
Related
This question already has answers here:
Order of init calls in Kotlin Array initialization
(2 answers)
Closed 3 years ago.
I will be reading data from a byte stream. Are the indices given by Kotlin to an array generation function (as described in https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-array/-init-.html) guaranteed to be called in order, ascending from zero?
The Array.kt file is under builtins so I'm at a loss as to where to find the actual code.
Take a look at the source code for Array:
public inline constructor(size: Int, init: (Int) -> T)
The init parameter is a function that takes an int (the index for a specific item), to which it expects a return value of type T, which the array consists of.
As the other answers have shown by examples, these are called in order, because it's the "natural" way of doing it. If you don't get what I mean, think about the implementation alternatives:
for (i in 0..size) {
this.addToArray(init(i));
}
Alternatively:
for (i in (size - 1)..0 {
this.addToArray(init(i));
}
Compared to:
val indices = mutableListOf<Int>()
while (indices.size != size) {
val i = random.nextInt(size);
if (i !in indices) {
indices.add(i);
this.addToArray(init(i));
}
}
While we can't see the source code for the constructor, the examples show in the other answers alone show they cannot be using a random approach. Applying the code from the first answer, mathematically speaking, the odds of using random and getting 0-49 printed out in order are extremely low.
Additionally, this is backed up by an answer here. The resulting compiled Java code creates a for-loop going from 0 to size. For the JVM, assuming they don't change the implementation, you can assume it'll go from 0 to size. But whether it goes from 0 to size or from size to 0, you can always reverse it if you don't like the order.
If you need to be 100% sure it goes from 0 to size, or if the implementation changes, you can do something like:
var a = (0 until 10).step(1).toList().toTypedArray()
Which, in this case, yields an array with the numbers 0-9.
If you want objects, or otherwise alter the object, you can add a .map {} before the list creation. That being said, this is an overkill alternative as long as the init function works as you'd expect.
And you can always confirm by decompiling the code using IntelliJ, Android Studio, some other IDE, or a decompiler of your choice. But regardless of the implementation, they'll always end up in order - so you don't need to worry about that. The only thing they oculd possibly change is the order the init function is called in, but it'll still end up in the same order in the resulting array.
That does seem to be the case.
Code:
fun main() {
val x = Array(50) {println(it)}
}
I am doing a project in scala and i am struggling with a certain thing. I am making a matrix DSL so i am overloading some operators like +,- or * so that i can do :
matrixMult = matrix1*matrix2
The thing is i made this class where the matrix was represented as a Array[Array[Double]] type but i would like to make it generic: Array[Array[T]]
The thing is i do not know how to handle this in the class methods since for operations like +,- and *. It should work for doubles or ints, but strings should throw an error. Here is my current code:
def +(other : Matrix[Double]): Matrix[Double] = {
var array = new Array[Array[Double]](rows)
for (i <- 0 to (rows - 1)) {
var arrayRow = new Array[Double](columns)
for (j <- 0 to (columns - 1)) {
arrayRow(j) = this.array(i)(j) + other.array(i)(j)
}
array(i) = arrayRow
}
return new Matrix(array)
}
I get an error on the arrayRow(j) =... line which is normal because it does not know what type the "this" object is.
What should i do to make this work? Like i would like this method only to be accessible to doubles (or ints) and not strings, if this method was to be invoked on a Matrix[String] object it should throw an error. I tried pattern matching with isInstanceOf() but that doesn't remove the error and i can't compile.
If kind of have the same issue with all of my methods in my class, so i'd like a generic answer if possible.
Any help is appreciated,
Thank you very much!
Not sure which version of Scala you are using, but if you're on 2.8, I found this thread on Scala-lang, and it looks like you may be able to use T:Numerics to limit it to Int, Long, Float, Double.
A little farther down in the thread, to limit it to JUST a subset of those (like Int, Double), they say to define your own generic Trait.
https://www.scala-lang.org/old/node/4787
Answer can be found in comments:
Matrix addition has been asked, and answered, before. Even though the question posses a different matrix implementation, I believe the answer from the redoubtable Rex Kerr is still applicable. – jwvh
I'm trying to make an Array-like class with chainable methods, but I seem to be screwed because Ruby's Array methods call ::Array.new instead of self.class.new:
class MyArray < Array; end
x = MyArray.new
y = MyArray.new
(x+y).class # Array, expected MyArray!
I understand that I could go through and re-implement all of Array's methods which call its constructor, but that seems really bogus.
Interestingly, Set DOES work 'correctly':
class MySet < Set; end
x = MySet.new([1,2,3])
y = MySet.new([4,5,6])
(x+y).class # MySet -- yeah!
What am I missing? Is there a Ruby idiom for subclassing Array in this way? Thanks!
The underlying implementation of + method is different between Array and Set. We can read the source code to find the root cause:
For Array, it uses a new variable to store the generated array:
rb_ary_plus(VALUE x, VALUE y)
{
VALUE z;
long len, xlen, ylen;
......
return z;
}
but for Set, + is alias for: |; it uses dup, which produces a shallow copy of the original Set object, it doesn't generate a new Set object to store the result.
def |(enum)
dup.merge(enum)
end
yeah, things are kind of inconsistent implementation with regard to stuff like this in the stdlib, I've found too. Sorry, I don't think there's any simple magic answer. There isn't really a ruby idiom, ruby doesn't really want you to do it, and some people have posted advocating for never sub-classing Array or Hash. http://words.steveklabnik.com/beware-subclassing-ruby-core-classes
I see that there's a relatively new feature in Ruby which allows chained iteration -- in other words, instead of each_with_indices { |x,i,j| ... } you might do each.with_indices { |x,i,j| ... }, where #each returns an Enumerator object, and Enumerator#with_indices causes the additional yield parameters to be included.
So, Enumerator has its own method #with_index, presumably for one-dimensional objects, source found here. But I can't figure out the best way to adapt this to other objects.
To be clear, and in response to comments: Ruby doesn't have an #each_with_indices right now -- it's only got an #each_with_index. (That's why I want to create one.)
A series of questions, themselves chained:
How would one adapt chained iteration to a one-dimensional object? Simply do an include Enumerable?
Presumably the above (#1) would not work for an n-dimensional object. Would one create an EnumerableN class, derived from Enumerable, but with #with_index converted into #with_indices?
Can #2 be done for Ruby extensions written in C? For example, I have a matrix class which stores various types of data (floats, doubles, integers, sometimes regular Ruby objects, etc.). Enumeration needs to check the data type (dtype) first as per the example below.
Example:
VALUE nm_dense_each(VALUE nm) {
volatile VALUE nm = nmatrix; // Not sure this actually does anything.
DENSE_STORAGE* s = NM_STORAGE_DENSE(nm); // get the storage pointer
RETURN_ENUMERATOR(nm, 0, 0);
if (NM_DTYPE(nm) == nm::RUBYOBJ) { // matrix stores VALUEs
// matrix of Ruby objects -- yield those objects directly
for (size_t i = 0; i < nm_storage_count_max_elements(s); ++i)
rb_yield( reinterpret_cast<VALUE*>(s->elements)[i] );
} else { // matrix stores non-Ruby data (int, float, etc)
// We're going to copy the matrix element into a Ruby VALUE and then operate on it. This way user can't accidentally
// modify it and cause a seg fault.
for (size_t i = 0; i < nm_storage_count_max_elements(s); ++i) {
// rubyobj_from_cval() converts any type of data into a VALUE using macros such as INT2FIX()
VALUE v = rubyobj_from_cval((char*)(s->elements) + i*DTYPE_SIZES[NM_DTYPE(nm)], NM_DTYPE(nm)).rval;
rb_yield( v ); // yield to the copy we made
}
}
}
So, to combine my three questions into one: How would I write, in C, a #with_indices to chain onto the NMatrix#each method above?
I don't particularly want anyone to feel like I'm asking them to code this for me, though if you did want to, we'd love to have you involved in our project. =)
But if you know of some example elsewhere on the web of how this is done, that'd be perfect -- or if you could just explain in words, that'd be lovely too.
#with_index is a method of Enumerator: http://ruby-doc.org/core-1.9.3/Enumerator.html#method-i-with_index
I suppose you could make a subclass of Enumerator that has #with_indices and have your #each return an instance of that class? That's the first thing that comes to mind, although your enumerator might have to be pretty coupled to the originating class...
Since you are saying that you are also interested in Ruby linguistics, not just C, let me contribute my 5 cents, without claiming to actually answer the question. #each_with_index and #with_index already became so idiomatic, that majority of the people rely on the index being a number. Therefore, if you go and implement your NMatrix#each_with_index in such way, that in the block { |e, i| ... } it would supply eg. arrays [0, 0], [0, 1], [0, 2], [1, 0], [1, 1], ... as index i, you would surprise people. Also, if others chain your NMatrix#each enumerator with #with_index method, they will receive just a single number as index. So, indeed, you are right to conclude that you need a distinct method to take care for the 2 indices-type (or, more generally, n indices for higher dimension matrices):
matrix.each_with_indices { |e, indices| ... }
This method should return a 2-dimensional (n-dimensional) array as indices == [i, j] . You should not go for the version:
matrix.each_with_indices { |e, i, j| ... }
As for the #with_index method, it is not your concern at all. If your NMatrix provides #each method (which it certainly does), then #with_index will work normally with it, out of your control. And you do not need to ponder about introducing matrix-specific #with_indices, because #each itself is not really specific to matrices, but to one-dimensional ordered collections of any sort. Finally, sorry for not being a skilled C programmer to cater to your C-related part of the question.
I am newbie in C and new to stackoveflow too. I have some problems in coding first oder formula like
forall([X],implies(X,f(X)))
Here x is a variable, implies is predicate and f is function. It sounds like for all x, x implies function of x i'e f(x).
using C. Any kind of suggestions and help will be appreciated.
First order formulas have boolean propositional parts (in your example, "implies(x,f(x))") and quantifiers ("Forall x").
You should already know that coding a function call "f(x)" is coded exactly that way in C.
You code the propositional part as boolean C code using logic connectives. For your example, "implication" isn't a native C operator so you have to substitute slightly different code for it. In c, the "?" operator does the trick. "a?b:c" produces "b" if "a" is true, and "c" otherwise. For your example:
x?f(x):false
Quantifiers mean you have to enumerate the set of possible values of the quantified variable, which always has some abstract type. In logic, this set might be infinite, but it computers it is not. In your case, you need to enumerate the set of values which could be "x"s. To do that, you need a way to represent a set; a cheesy way to do that in C is to use an array to hold the set members X, and to iterate through the array:
type_of_x set_of_x[1000];
... fill x somehow ...
for(i=1;i<number_of_set_elements;i++)
{ x= set_of_x[i];
... evaluate formula ...
}
Since a "forall" is false if any propositional instance is false, you need to exit the enumeration when you find a false example:
boolean set_of_x[1000]; // in your example, x must be a boolean variable
// forall x
... fill x somehow ...
final_value=true;
for (i=1;i<number_set_elements; i++)
{ x= set_of_x[i];
if (x?f(x):false)
{ final_value=false;
break;
}
}
... final_value set correctly here...
"exists" is true if any propositional instance is true, so you need to exit the enumeration when you find a true result:
// exists x
... fill x somehow ...
final_value=false;
for (i=1;i<number_set_elements; i++)
{ x= set_of_x[i];
if (x?f(x):false)
{ final_value=true;
break;
}
}
... final_value set correctly here...
If you have multiple quantifiers, you'll end up with nested loops, one loop for each quantifier. If your formula is complex, you'll likely need several intermediate boolean variables to compute the values of the various parts.
You'll also end up with a variety of "sets" (some arrays, some linked lists, some hash tables) so you'll need to learn how to use these data structures. Also, your quantified values might not be booleans, but that's OK;
you can still pass them to functions that compute boolean values. To compute the FOL for:
forall p:Person old(p) and forall f:Food ~likes(p,f)
the following code skeleton would be used (details left to the reader):
person array_of_persons[...];
foods array_of_foods[...]
for (i=...
{ p=array_of_persons[i];
is_old = old(p);
for(j=...
{ f=array_of_foods[j];
...
if (is_old && !likes(p,f)) ...
}
}
C is an imperative programming language. "Imperative" here means that execution happens via the programmer specifically telling the computer what to do.
For what you want, Prolog is more appropriate. It is based on first-order predicate logic, and execution happens by trying to "find a resolution refutation of the negated query" that's specified by the user's goal. This approach is very unlike C since execution is much more implicit and the expression of intent looks much different.
If you have lots of time, you can write your own constraint solver or Prolog interpreter in C, but by default, C has no first-class support for what you're looking for.