Is solve before needed with dist? - system-verilog

Section 18.5.10 in the IEEE Std 1800-2017 has the following example to illustrate why we need solve before:
rand bit s;
rand bit [31:0] d;
constraint c { s -> d == 0; }
Do the following 2 options still require solve before?
A.
rand bit s;
rand bit [31:0] d;
constraint c1 { d < 1000; }
constraint c2 { if ( s == 1 ) d == 0; }
B.
rand bit s;
rand bit [31:0] d;
constraint c1 { d < 1000;
if ( s == 1 ) d == 0;
}
constraint c2 { s dist { 0 :/ 95, 1 :/ 5 }; }
A naive reading of all the above would assume a 50% (5% for option B) chance of choosing s as 1, whereas the IEEE standard says you need a solve s before d constraint in the first example to get the 50% chance.
Do A and B need a solve before to get the expected 50%/5% chance of s being 1?

Option A would give you a 0.0999% chance of s being 1 without the solve s before d construct. (s is 1'b1 in only 1 in 1001 solutions).
Option B would give you a 5% chance of s being 1 regardless of having the solve s before d construct. The dist constraint implies an ordering in picking values within the solution space, so adding the solve before construct would be redundant.

Related

Unsatisfiable solution with `constraint forall(i in x)( x[i] <= x[i+1] );`

I'm working on a toy problem to learn minizinc. Take an array (hardcoded to size 3 for now) of values between 0 and 9 and find the combinations where the sum is equal to the product.
par int: n = 3; % hardcode for now
array[1..n] of var 0..9: x;
constraint sum(x) != 0;
constraint sum(x) == product(x);
output["\(x)"];
Outputs
[2, 3, 1]
----------
This works as expected, however, next I try to constrain so that the values must increase in order.
First I tried this:
constraint forall(i in x)(
x[i] <= x[i+1]
);
This was UNSATISFIABLE. I was thinking this could be due to the i+1 index being greater than the size of the array for the last item. So I added a condition to the forall to prevent the index of the last item being out of bounds:
constraint forall(i in x)(
i < n /\ x[i] <= x[i+1]
);
However, this was also UNSATISFIABLE.
Something is amiss with my conceptual understanding. What is wrong with my approach?
PROBLEM(s).
In general, the constraint is fine. In the context of this example, however, it is inconsistent. Let's see why this is the case.
We know that the solution must include 1, 2, 3, thus, we can infer that the constraint
constraint forall (i in x) (
x[i] <= x[i+1]
);
is "equivalent" to
constraint x[1] <= x[2];
constraint x[2] <= x[3];
constraint x[3] <= x[4];
for which mzn2fzn reports the following issue:
WARNING: undefined result becomes false in Boolean context
(array access out of bounds)
./t.mzn:12:
in binary '<=' operator expression
in array access
When the same constraint is written without hard-encoded index values, the mzn2fzn compiler is unable to detect the inconsistency before the solver is invoked. However, the semantics of the access out of bounds is still the same (i.e. false) at run-time, so the formula becomes unsatisfiable.
The constraint
constraint forall(i in x)(
i < n /\ x[i] <= x[i+1]
);
augments the previous constraint with the requirement that i must be smaller than n. This is clearly false for i = 3, so there is one more inconsistency in the model. The constraint would be correct if you used the implication symbol -> instead of the (logical) and symbol /\.
SOLUTION(s).
First, let me set aside a possible misunderstanding of the language. The comprehension i in x, which you used in your model, refers to the elements inside the array x, and not to the index set of x. In this particular case the solution and the index set of x contain the same values, so it does not cause an inconsistency. However, this is not true in general, so it's better to use the function index_set() as follows:
constraint forall(i, j in index_set(x) where i < j)(
x[i] <= x[j]
);
example:
par int: n = 3; % hardcode for now
array[1..n] of var 0..9: x;
constraint sum(x) != 0;
constraint sum(x) == product(x);
constraint forall(i, j in index_set(x) where i < j)(
x[i] <= x[j]
);
solve satisfy;
output["\(x)"];
yields
~$ mzn2fzn test.mzn
~$ optimathsat -input=fzn < test.fzn
x = array1d(1..3, [1, 2, 3]);
----------
A more elegant solution is to use the following global constraint, which is mentioned in the documentation (v. 2.2.3) of MiniZinc:
predicate increasing(array [int] of var bool: x)
predicate increasing(array [int] of var int: x)
predicate increasing(array [int] of var float: x)
The predicate admits duplicate values in the array, that is, it enforces a non-strict increasing order (if that is needed, combine increasing with distinct).
The predicate is contained in the file increasing.mzn. However, people normally include the file globals.mzn instead, so as to have access to all predicates at once.
example:
include "globals.mzn";
par int: n = 3; % hardcode for now
array[1..n] of var 0..9: x;
constraint sum(x) != 0;
constraint sum(x) == product(x);
constraint increasing(x);
solve satisfy;
output["\(x)"];
yields
~$ mzn2fzn t.mzn
~$ optimathsat -input=fzn < t.fzn
x = array1d(1..3, [1, 2, 3]);
----------

Hash Function for 3 Integers

I have 3 non-negative integers and a number n such that
0 <= a <= n, 0 <= b <= n, and 0 <= c <= n.
I need a one-way hash function that maps these 3 integers to one integer (could be any integer, positive or negative). Is there a way to do this, and if so, how? Is there a way so that this this function can be expressed as a simple mathematical expression where the only parameters are a, b, c, and n?
Note: I need this function because I was using tuples of 3 integers as keys in a dictionary on python, and with upwards of 10^10 keys, space is a real issue.
How about the Cantor pairing function (https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function)?
Let
H(a,b) := .5*(a + b)*(a + b + 1) + b
then
H(a,b,c) := .5*(H(a,b) + c)*(H(a,b) + c + 1) + c
You mentioned that you need a one-way hash, but based on your detailed description about memory constraints it seems that an invertible hash would also suffice.
This doesn't use the assumption that a, b, and c are bounded above and below.
Augmenting the answer above for a more concise implementation:
int cantor(int a, int b) {
return (a + b + 1) * (a + b) / 2 + b;
}
int hash(int a, int b, int c) {
return cantor(a, cantor(b, c));
}
The easiest way to understand this is that Cantor algorithm assigns a natural number to every integer pair of numbers.
Once we've assigned a natural number N = cantor(b, c), then we can assign a new unique natural number M = cantor(a, N), which we can use as a hash code and is a unique natural number for every triple a, b, c.
As a more general case, you could hash more integers by just another cantor with the next integer (e.g. cantor(a, cantor(b, cantor(c, d)))).

Ordering a list of lists subject to constraints

I have encountered a surprisingly challenging problem arranging a matrix-like (List of Lists) of values subject to the following constraints (or deciding it is not possible):
A matrix of m randomly generated rows with up to n distinct values (no repeats within the row) arrange the matrix such that the following holds (if possible):
1) The matrix must be "lower triangular"; the rows must be ordered in ascending lengths so the only "gaps" are in the top right corner
2) If a value appears in more than one row it must be in the same column (i.e. rearranging the order of values in a row is allowed).
Expression of the problem/solution in a functional language (e.g. Scala) is desirable.
Example 1 - which has a solution
A B
C E D
C A B
becomes (as one solution)
A B
E D C
A B C
since A, B and C all appear in columns 1, 2 and 3, respectively.
Example 2 - which has no solution
A B C
A B D
B C D
has no solution since the constraints require the third row to have the C and D in the third
column which is not possible.
I thought this was an interesting problem and have modeled a proof-of-concept-version in MiniZinc (a very high level Constraint Programming system) which seems to be correct. I'm not sure if it's of any use, and to be honest I'm not sure if it's powerful for very largest problem instances.
The first problem instance has - according to this model - 4 solutions:
B A _
E D C
B A C
----------
B A _
D E C
B A C
----------
A B _
E D C
A B C
----------
A B _
D E C
A B C
The second example is considered unsatisfiable (as it should).
The complete model is here: http://www.hakank.org/minizinc/ordering_a_list_of_lists.mzn
The basic approach is to use matrices, where shorter rows are filled with a null value (here 0, zero). The problem instance is the matrix "matrix"; the resulting solution is in the matrix "x" (the decision variables, as integers which are then translated to strings in the output). Then there is a helper matrix, "perms" which are used to ensure that each row in "x" is a permutation of the corresponding row in "matrix", done with the predicate "permutation3". There are some other helper arrays/sets which simplifies the constraints.
The main MiniZinc model (sans output) is show below.
Here are some comments/assumptions which might make the model useless:
this is just a proof-of-concept model since I thought it was an interesting
problem.
I assume that the rows in the matrix (the problem data) is already ordered
by size (lower triangular). This should be easy to do as a preprocessing step
where Constraint Programming is not needed.
the shorter lists are filled with 0 (zero) so we can work with matrices.
since MiniZinc is a strongly typed language and don't support
symbols, we just define integers 1..5 to represent the letters A..E.
Working with integers is also beneficial when using traditional
Constraint Programming systems.
% The MiniZinc model (sans output)
include "globals.mzn";
int: rows = 3;
int: cols = 3;
int: A = 1;
int: B = 2;
int: C = 3;
int: D = 4;
int: E = 5;
int: max_int = E;
array[0..max_int] of string: str = array1d(0..max_int, ["_", "A","B","C","D","E"]);
% problem A (satifiable)
array[1..rows, 1..cols] of int: matrix =
array2d(1..rows, 1..cols,
[
A,B,0, % fill this shorter array with "0"
E,D,C,
A,B,C,
]);
% the valid values (we skip 0, zero)
set of int: values = {A,B,C,D,E};
% identify which rows a specific values are.
% E.g. for problem A:
% value_rows: [{1, 3}, {1, 3}, 2..3, 2..2, 2..2]
array[1..max_int] of set of int: value_rows =
[ {i | i in 1..rows, j in 1..cols where matrix[i,j] = v} | v in values];
% decision variables
% The resulting matrix
array[1..rows, 1..cols] of var 0..max_int: x;
% the permutations from matrix to x
array[1..rows, 1..cols] of var 0..max_int: perms;
%
% permutation3(a,p,b)
%
% get the permutation from a b using the permutation p.
%
predicate permutation3(array[int] of var int: a,
array[int] of var int: p,
array[int] of var int: b) =
forall(i in index_set(a)) (
b[i] = a[p[i]]
)
;
solve satisfy;
constraint
forall(i in 1..rows) (
% ensure unicity of the values in the rows in x and perms (except for 0)
alldifferent_except_0([x[i,j] | j in 1..cols]) /\
alldifferent_except_0([perms[i,j] | j in 1..cols]) /\
permutation3([matrix[i,j] | j in 1..cols], [perms[i,j] | j in 1..cols], [x[i,j] | j in 1..cols])
)
/\ % zeros in x are where there zeros are in matrix
forall(i in 1..rows, j in 1..cols) (
if matrix[i,j] = 0 then
x[i,j] = 0
else
true
endif
)
/\ % ensure that same values are in the same column:
% - for each of the values
% - ensure that it is positioned in one column c
forall(k in 1..max_int where k in values) (
exists(j in 1..cols) (
forall(i in value_rows[k]) (
x[i,j] = k
)
)
)
;
% the output
% ...
I needed a solution in a functional language (XQuery) so I implemented this first in Scala due to its expressiveness and I post the code below. It uses a brute-force, breadth first style search for solutions. I'm inly interested in a single solution (if one exists) so the algorithm throws away the extra solutions.
def order[T](listOfLists: List[List[T]]): List[List[T]] = {
def isConsistent(list: List[T], listOfLists: List[List[T]]) = {
def isSafe(list1: List[T], list2: List[T]) =
(for (i <- list1.indices; j <- list2.indices) yield
if (list1(i) == list2(j)) i == j else true
).forall(_ == true)
(for (row <- listOfLists) yield isSafe(list, row)).forall(_ == true)
}
def solve(fixed: List[List[T]], remaining: List[List[T]]): List[List[T]] =
if (remaining.isEmpty)
fixed // Solution found so return it
else
(for {
permutation <- remaining.head.permutations.toList
if isConsistent(permutation, fixed)
ordered = solve(permutation :: fixed, remaining.tail)
if !ordered.isEmpty
} yield ordered) match {
case solution1 :: otherSolutions => // There are one or more solutions so just return one
solution1
case Nil => // There are no solutions
Nil
}
// Ensure each list has unique items (i.e. no dups within the list)
require (listOfLists.forall(list => list == list.distinct))
/*
* The only optimisations applied to an otherwise full walk through all solutions is to sort the list of list so that the lengths
* of the lists are increasing in length and then starting the ordering with the first row fixed i.e. there is one degree of freedom
* in selecting the first row; by having the shortest row first and fixing it we both guarantee that we aren't disabling a solution from being
* found (i.e. by violating the "lower triangular" requirement) and can also avoid searching through the permutations of the first row since
* these would just result in additional (essentially duplicate except for ordering differences) solutions.
*/
//solve(Nil, listOfLists).reverse // This is the unoptimised version
val sorted = listOfLists.sortWith((a, b) => a.length < b.length)
solve(List(sorted.head), sorted.tail).reverse
}

Why Modulo When Finding Prime Numbers

I'm trying to understand why one needs modulo operator in writing a program that finds prime numbers; I'm a student analysing some code for learning purposes, and I am confused as to why modulo is needed.
Explicit modulo isn't required. Consider an implementation of the sieve of Eratosthenes (in C for the sake of using something):
int numbersThatMayBePrime[100];
memset(numbersThatMayBePrime, 0, sizeof(int)*100);
for(int c = 2; c < 100; c++)
{
if(!numbersThatMayBePrime[c])
{
printf("%d\n", c);
for(int strikeThrough = c; strikeThrough < 100; strikeThrough += c)
numbersThatMayBePrime[strikeThrough] = -1;
}
}
If the modulo of n % (all numbers between n and zero) is always positive and never zero, the number is prime.
I am trying to figure out how to code this in javascript.

How to delete zero components in a vector in Matlab?

I have a vector for example
a = [0 1 0 3]
I want to turn a into b which equals b = [1 3].
How do I perform this in general? So I have a vector with some zero components and I want to remove the zeroes and leave just the non-zero numbers?
If you just wish to remove the zeros, leaving the non-zeros behind in a, then the very best solution is
a(a==0) = [];
This deletes the zero elements, using a logical indexing approach in MATLAB. When the index to a vector is a boolean vector of the same length as the vector, then MATLAB can use that boolean result to index it with. So this is equivalent to
a(find(a==0)) = [];
And, when you set some array elements to [] in MATLAB, the convention is to delete them.
If you want to put the zeros into a new result b, while leaving a unchanged, the best way is probably
b = a(a ~= 0);
Again, logical indexing is used here. You could have used the equivalent version (in terms of the result) of
b = a(find(a ~= 0));
but mlint will end up flagging the line as one where the purely logical index was more efficient, and thus more appropriate.
As always, beware EXACT tests for zero or for any number, if you would have accepted elements of a that were within some epsilonic tolerance of zero. Do those tests like this
b = a(abs(a) >= tol);
This retains only those elements of a that are at least as large as your tolerance.
I just came across this problem and wanted to find something about the performance, but I couldn't, so I wrote a benchmarking script on my own:
% Config:
rows = 1e6;
runs = 50;
% Start:
orig = round(rand(rows, 1));
t1 = 0;
for i = 1:runs
A = orig;
tic
A(A == 0) = [];
t1 = t1 + toc;
end
t1 = t1 / runs;
t2 = 0;
for i = 1:runs
A = orig;
tic
A = A(A ~= 0);
t2 = t2 + toc;
end
t2 = t2 / runs;
t1
t2
t1 / t2
So you see, the solution using A = A(A ~= 0) is the quicker of the two :)
I often ended up doing things like this. Therefore I tried to write a simple function that 'snips' out the unwanted elements in an easy way. This turns matlab logic a bit upside down, but looks good:
b = snip(a,'0')
you can find the function file at:
http://www.mathworks.co.uk/matlabcentral/fileexchange/41941-snip-m-snip-elements-out-of-vectorsmatrices
It also works with all other 'x', nan or whatever elements.
b = a(find(a~=0))
Data
a=[0 3 0 0 7 10 3 0 1 0 7 7 1 7 4]
Do
aa=nonzeros(a)'
Result
aa=[3 7 10 3 1 7 7 1 7 4]
Why not just, a=a(~~a) or a(~a)=[]. It's equivalent to the other approaches but certainly less key strokes.
You could use sparse(a), which would return
(1,2) 1
(1,4) 3
This allows you to keep the information about where your non-zero entries used to be.