At least one Var equals to X within a Var array using Choco Solver - constraint-programming

I'm using Choco Solver and given an array of int vars, I want a constraint that check that at least one var in the array is equal to a static value...
Something similar to IntConstraintFactory#count but with the following doc :
/**
* Let N be the number of variables of the VARIABLES collection assigned to value VALUE;
* Enforce condition N >= LIMIT to hold.
* <p>
*
* #param VALUE an int
* #param VARS a vector of variables
* #param LIMIT a variable
*/
public static Constraint at_least(int VALUE, IntVar[] VARS, IntVar LIMIT) {
return new Constraint("At least", /* help here ? */);
}
Does someone knows if it exists or how I can implement it efficiently ?

If you want to post constraint atLeast(VALUE,VARS, LIMIT) in Choco Solver, you can simply post count(VALUE,VARS,X), with X an IntVar of initial domain [0,VARS.length], and post arithm(X,">=",LIMIT). This will do the job. There is no need of implementing a specific constraint for that.
If you want to check that at least one variable in VARS is equal to VALUE, it is even simpler, simply post count(VALUE, VARS, X) with [1,VARS.length] as the initial domain for X. So the minimal number of occurrence of VALUE will be at least 1. No need to create a second variable and the arithmetic constraint.

Related

Get greater number in a field? Alloy model checker

I want to return the greater number max(loc.x) in a field scope:
sig Locations{
x: set Int // all x locations visited
xgreater: one Int // greater location
}
fact{all loc:Locations| xgreater = greaterX[loc]} // get greater location
fun greaterX[loc:Locations]:Int{ // get the greater location
max(loc.x) // HOW do I do this?
}
Any ideas? Thank you.
How about making it a predicate
pred greatest [locs: set Location, x: Location] {...}
with a constraint that there is no location in lock larger than the x?
(Note also that I've changed the signature name to Location: as with classes and types, the convention is to use the singular noun.)

Comparator vs Closure in min call in groovy?

I am trying to understand the difference between passing a Closure vs a Comparator to the min function on a collection:
// Example 1: Closure/field/attribute?
Sample min = container.min { it.timespan.start }
// Example 2: Comparator
Sample min2 = container.min(new Comparator<Sample>() {
#Override
int compare(Sample o1, Sample o2) {
return o1.timespan.start <=> o2.timespan.start
}
})
They both return the correct result.
Where:
class Sample {
TimeSpan timespan
static constraints = {
}
}
And:
class TimeSpan {
LocalDate start
LocalDate end
}
In Example 1 I just pass the field timespan.start to min which I guess means that I am passing a Closure (even though its just a field in a class)?
In Example 1 does groovy convert the field timespan.start into a Comparator behind the scenes like the one I create explicitly in Example 2?
The difference is, that those are two different min methods both
taking different arguments. There is one for passing
a closure
and one for the
comparator
(there is a third one using identity and some deprecated ones, but we can ignore that for now).
The first version (Closure with one (implicit argument)) you have to
extract the value from the passed value, you want to make the min
aggregate with. Therefor this versions has some inner working to deal
with comparing the values.
But the docs also state:
If the closure has two parameters it is used like a traditional
Comparator. I.e. it should compare its two parameters for order,
returning a negative integer, zero, or a positive integer when the
first parameter is less than, equal to, or greater than the second
respectively. Otherwise, the Closure is assumed to take a single
parameter and return a Comparable (typically an Integer) which is then
used for further comparison.
So you can use a Closure version also to the same as your second example
(you have to define two params explicitly):
container.min{ a, b -> a <=> b }
And there is also a shorter version of the second example. You can cast
a Closure to an interface with groovy. So this works too:
container.min({ a, b -> a <=> b } as Comparator)

How do you easily differentiate the use of * as a pointer, * as a de-reference operator, * as a multiplication operator in C?

The use of * is all so confusing especially for us new comers to C. I mean, how do you easily differentiate the use of * as a pointer, * as a de-reference operator, * as a multiplication operator? I see alot of different use of * online and it's quite confusing, especially regarding different positions of the * e.g. as in the sample code below. What positions of * are correct and advisable to use to avoid confusion with pointers, de-referencing and multiplication?
Code is just sample and may...infact will not compile.
int main(void){
int *size, length, width;
*size1= malloc(sizeof(int) * length);
*size2= (int *) malloc(width * sizeof(int) * width);
*size3= malloc(sizeof(int) *length);
printf("%d\n%d\n%d\n", size1,size2,size3);
return (0);
}
N.B: I'm new in C and pls don't refer me to useless links and ("supposedly") duplicates that doesn't answer exactly same question as this...pls allow others to air their views so we get maximum answers, none knows it all, u will be surprised that something new can pop-up, even for the so called C old-timers.
When you read C code, you must be able to distinguish definitions and expressions. A definition starts with a type optionally preceded by a storage class such as extern, static, typedef... and/or type qualifiers such as const and, volatile. A star in front of the identifier being defined indicates that this variable is a pointer, multiple stars indicate multiple levels of indirection.
In an expression, a star can occur as a binary operator, between operands, or as unary operator, in front of its operand. The binary operator * is the multiplication operator, whereas the unary * is the dereference operator.
As a rule of thumb, a * that follows an identifier or a postfix operator is a multiplication operator. Postfix operators are ++, --, indexing with [] and calling a function with optional arguments inside ().
The confusion comes from the conciseness of the C language, which allows the programmer to combine these different uses at will:
int x=0,*p=&x,n=*p**p;
This ugly line is indeed confusing. Let's first insert meaningful spaces to improve readability:
int x = 0, *p = &x, n = *p * *p;
Spacing is mostly unnecessary for the C compiler, but following simple rules increases readability for humans:
add a space on both sides of binary operators
add a space after , and ; except at the end of a line
do not insert a space between unary operators and their operand, except for sizeof.
indent code in a consistent manner, typically 4 spaces per level
The above line of code defines 3 variables x, p and n.
* p is a pointer to int, while x and n are int variables.
* x is initialized to 0
* p is initialized to the address of x.
* the initializer for n is the result of multiplying of the value pointed to by p by itself.
Defining multiple variables with different levels of indirection in the same definition is frowned upon because it is confusing and error prone. Rewriting the above definition on 3 lines is highly advisable:
int x = 0;
int *p = &x;
int n = *p * *p;

How to create an array of functions which partly depend on outside parameters? (Python)

I am interested in creating a list / array of functions "G" consisting of many small functions "g". This essentially should correspond to a series of functions 'evolving' in time.
Each "g" takes-in two variables and returns the product of these variables with an outside global variable indexed at the same time-step.
Assume obs_mat (T x 1) is a pre-defined global array, and t corresponds to the time-steps
G = []
for t in range(T):
# tried declaring obs here too.
def g(current_state, observation_noise):
obs = obs_mat[t]
return current_state * observation_noise * obs
G.append(g)
Unfortunately when I test the resultant functions, they do not seem to pick up on the difference in the obs time-varying constant i.e. (Got G[0](100,100) same as G[5](100,100)). I tried playing around with the scope of obs but without much luck. Would anyone be able to help guide me in the right direction?
This is a common "gotcha" to referencing variables from an outer scope when in an inner function. The outer variable is looked up when the inner function is run, not when the inner function is defined (so all versions of the function see the variable's last value). For each function to see a different value, you either need to make sure they're looking in separate namespaces, or you need to bind the value to a default parameter of the inner function.
Here's an approach that uses an extra namespace:
def make_func(x):
def func(a, b):
return a*b*x
return func
list_of_funcs = [make_func(i) for i in range(10)]
Each inner function func has access to the x parameter in the enclosing make_func function. Since they're all created by separate calls to make_func, they each see separate namespaces with different x values.
Here's the other approach that uses a default argument (with functions created by a lambda expression):
list_of_funcs = [lambda a, b, x=i: a*b*x for i in range(10)]
In this version, the i variable from the list comprehension is bound to the default value of the x parameter in the lambda expression. This binding means that the functions wont care about the value of i changing later on. The downside to this solution is that any code that accidentally calls one of the functions with three arguments instead of two may work without an exception (perhaps with odd results).
The problem you are running into is one of scoping. Function bodies aren't evaluated until the fuction is actually called, so the functions you have there will use whatever is the current value of the variable within their scope at time of evaluation (which means they'll have the same t if you call them all after the for-loop has ended)
In order to see the value that you would like, you'd need to immediately call the function and save the result.
I'm not really sure why you're using an array of functions. Perhaps what you're trying to do is map a partial function across the time series, something like the following?
from functools import partial
def g(current_state, observation_noise, t):
obs = obs_mat[t]
return current_state * observation_noise * obs
g_maker = partial(g, current, observation)
results = list(map(g_maker, range(T)))
What's happening here is that partial creates a partially-applied function, which is merely waiting for its final value to be evaluated. That final value is dynamic (but the first two are fixed in this example), so mapping that partially-applied function over a range of values gets you answers for each value.
Honestly, this is a guess because it's hard to see what else you are trying to do with this data and it's hard to see what you're trying to achieve with the array of functions (and there are certainly other ways to do this).
The issue (assuming that your G.append call is mis-indented) is simply that the name t is mutated when you loop over the iterator returned by range(T). Since every function g you create stores returns the same name t, they wind up all returning the same value, T - 1. The fix is to de-reference the name (the simplest way to do this is by sending t into your function as a default value for an argument in g's argument list):
G = []
for t in range(T):
def g(current_state, observation_noise, t_kw=t):
obs = obs_mat[t_kw]
return current_state * observation_noise * obs
G.append(g)
This works because it creates another name that points at the value that t references during that iteration of the loop (you could still use t rather than t_kw and it would still just work because tg is bound to the value that tf is bound to - the value never changes, but tf is bound to another value on the next iteration, while tg still points at the "original" value.

Groovy, troubles with the range operator

I wrote a method in Groovy using the range operator in order to execute the same code multiple times:
/**
* Prints the {#code files} {#code copyCount} times using
* {#code printService}.
* <p>
* Exceptions may be thrown.
* #param printService Print service
* #param files List of {#code File} objects
* #param copyCount Number of copies to print
*/
private static void printJob(
PrintService printService,
List<File> files,
int copyCount) {
// No multiple copy support for PS files, must do it manually
for ( i in 1..copyCount ) {
// Print files
}
}
This method did not pass unit testing as it badly fails when copyCount is 0.
I searched the documentation and it seems that Groovy implements ranges like a "list of sequential values". As I understand, a range does not represent a representation of an interval of integers since it also has the notion of order embedded.
In Groovy a..b is not the set of integers x such that a <= x <= b.
In Groovy a..b is the representation of the enumeration u: [0,|b-a|] -> [a..b] defined as: u(0) = a, for all i in [1,|b-a|], u(i) = u(i-1) + sgn(b-a)
Now I can fix my code:
if (copyCount > 0) for ( i in 1..copyCount ) {
// Print files
}
Also in Groovy a..<b is the representation of the enumeration u: [0,|b-a|-1] -> [a..b-1] defined as: u(0) = a, for all i in [1,|b-a|-1], u(i) = u(i-1) + sgn(b-a)
I noticed that the code below is also working for copyCount positive or zero:
for ( i in 0..<copyCount ) {
// Print files
}
Still, if I can choose a solution where damages are minimized in case of inconsistency (say copyCount is -200, I may get 200 prints)...
0.step(copyCount, 1) {
// Print files
}
At least with this solution I get a GroovyRuntimeException: Infinite loop in case of a negative copyCount. It is groovy but not very pretty and I feel like I’m playing with fire.
There is also this solution, but I find it ugly.
for ( i in 0..<[0,n].max() ) {
// Print files
}
Therefore, in this case, I think the best is to avoid using the range operator, because it may be confusing for developers that are used to Perl, Ruby or Mathematics, or French (there is no word for this definition of range in French, we would just say "intervalle" for a range)... I also found it safer in case of inconsistency. Still, it is not so groovy.
for ( i = 1 ; i <= copyCount ; i++ ) {
// Print files
}
Why does the range operator in Groovy is so complicated? As I see it, the fact that the step is "magically" determined and that we can’t force it (like in Ruby) is a big flaw in this implementation. Am I the only one who was ever troubled by this (two prints instead of none, it would have been a bad bug ^^ )? Did I miss something? Is there any practical case where it is required for a range to revert order when the higher bound gets lower than the lower bound? Am I being too picky?

Resources