`alldifferent` method in MiniZinc - minizinc

The following is the constraint I tried to implement in MiniZinc
constraint forall (t in trucks)
(all_different(c in customers where sequence[t,c] !=0) (sequence[t,c]));
that is, I want every row element to be different for the sequence matrix when the sequence value doesn't equal to 0.
and got the error
MiniZinc: type error: no function or predicate with this signature found: all_different(array[int] of var opt int)'.
As indicated by some other threads I've added include "alldifferent.mzn"; command, still showing that error.
This is part of assignment, sorry for not able to push all my code here, please let me know if there is any extra information needed.

To clearly understand what you are doing, you can write your expression in a different way:
all_different([sequence[t,c] | c in customers where sequence[c,t] != 0])
Note that this uses array comprehensions. These are great to express a lot of things, but if sequence is an array of variables then the number of variables in this comprehension is unknown. This is a big problem for many solvers. And is thus not supported by many of them.
It is at least impossible with the all_different predicate.
Your problem however is a well known one, thus a different predicate is available. You can express the same constraint in the following way:
for(t in trucks) (
alldifferent_except_0([sequence[c,t] | c in customers])
)

Related

How to define `last` iterator without collecting/allocating?

Using the example from the Julia Docs, we can define an iterator like the following:
struct Squares
count::Int
end
Base.iterate(S::Squares, state=1) = state > S.count ? nothing : (state*state, state+1)
Base.eltype(::Type{Squares}) = Int # Note that this is defined for the type
Base.length(S::Squares) = S.count
But even though there's a length defined, asking for last(Squares(5)) results in an error:
julia> last(Squares(5))
ERROR: MethodError: no method matching lastindex(::Squares)
Since length is defined, is there a way to iterate through and return the last value without doing an allocating collect? If so, would it be bad to extend the Base.last method for my type?
As you can read in the docstring of last:
Get the last element of an ordered collection, if it can be computed in O(1) time. This is accomplished by calling lastindex to get the last index.
The crucial part is O(1) computation time. In your example the cost of computing last element is O(count) (of course if we want to use the definition of the iterator as in general it would be possible compute it in O(1) time).
The idea is to avoid defining last for collections for which it is expensive to compute it. For this reason the default definition of last is:
last(a) = a[end]
which requires not only lastindex but also getindex defined for the passed value (as the assumption is that if someone defines lastindex and getindex for some type then these operations can be performed fast).
If you look at Interfaces section of the Julia manual you will notice that the iteration interface (something that your example implements) is less demanding than indexing interface (something that is defined for your example in the next section of the manual). Usually the distinction is made that indexing interface is only added for collections that can be indexed efficiently.
If you still want last to work on your type you can either:
add a definition to Base.last specifically - there is nothing wrong with doing this;
add a definition of getindex, firstindex, and lastindex to make the collection indexable (and then the default definition of last would work) - this is the approach presented in the Julia manual

What is the use of minizinc fix function?

i see that fix documentation says:
http://www.minizinc.org/doc-lib/doc-builtins-reflect.html#Ifunction-dd-T-cl-fix-po-var-opt-dd-T-cl-x-pc
function array [$U] of $T: fix(array [$U] of var opt $T: x)
Check if the value of every element of the array x is fixedat this point in evaluation. If all are fixed, return an array of their values, otherwise abort.
I am thinking it can be used to coerce a var to a par.
Here is the code.
array [1..num] of var int: value ;
%% generate random numbers from 0..num-1, this should fix the value of the var "value" or so i think
constraint forall(i in index_set(value))(let {int:temp_value=discrete_distribution([1|i in index_set(value)]); } in value[i]=trace(show(temp_value)++"\n", temp_value));
%%% this i was expecting to work, as "value" elements are fixed above
array [1..num] of int:value__ =[ trace(show(fix(value[i])), fix(value[i])) | i in index_set(value)] ;
But i get:
MiniZinc: evaluation error:
with i = 1
in call 'trace'
in call 'fix'
expression is not fixed
My questions are:
1) I think i should expect this error as minizinc is not sequential execution language?
2) Examples of fix in user guide is only where output statement is used. Is it the only place to use fix?
3) How would i coerce a var to a par?
By the way I am trying this var to par conversion because i am having problem with array generator expression. Here is the code
int:num__=200;
int:seed=134;
int: two_m=2097184;
%% prepare weights for generating numbers form 1..(two_m div 64), basically same weight
array [1..(two_m div 64)] of int: value_6_wt= [seed+1 | i in 1..(two_m div 64)] ;
%% generate numbers. this dose not work gives out
%% in variable declaration for 'value6'
%% parameter value out of range
array [1..num__] of int : value6 = [ discrete_distribution(value_6_wt) | j in 1..num__];
In the MiniZinc language the difference between a parameter and a variable is only the fact that a parameter must have a value at compile time. Within the compiler we turn as many variables into parameters as we can. This saves the solver from having to do some work. When we know that a variable has been turned into a parameter, then we can use the fix function to convince the type system that we really can use this variable as a parameter and see its value.
The problem here however is that fix is defined to abort when the variable is not fixed to one value. If no testing is done, this requires some (magic/)knowledge about the compilation process. In your case it seems that the second array is evaluated before the optimisation stage, in which all aliasing is resolved. This is the reason why it does not work. (This is indeed one of the things that is a consequence of a declarative language)
Although fix might only be used in the output statements in the examples (where it's guaranteed to work), it is used in many locations in the MiniZinc libraries. If we for example look at the library that is used for MIP solvers, there are many constraints that can be encoded more efficiently if one of the arguments is a parameter. Therefore, you will often see that the a constraint in this library first tests its arguments with is_fixed, and then use a better encoding if this returns true.
The output statement and when is_fixed returns true will both give the guarantee that a variable is fixed and ensure that the compilation doesn't abort. There is no other way to coerce a variable to a parameter, but unless you are dealing with dependant predicate definitions, you can just trust the MiniZinc compiler to ensure that the resulting FlatZinc will contain a parameter instead of a variable.

Interfaces in Fortran

I stumbled over a particular problem with interfaces while debugging some code, where a called subroutine has a dummy argument of rank 2 but an actual argument of rank 1. The resulting difference in the arguments resulted in an invalid read.
To reproduce I created a small program (ignore the comments ! <> for now):
PROGRAM ptest
USE mtest ! <>
IMPLICIT NONE
REAL, ALLOCATABLE, DIMENSION(:) :: field
INTEGER :: n
REAL :: s
n = 10
ALLOCATE(field(n))
CALL RANDOM_NUMBER(field)
CALL stest(n, field, s)
WRITE(*,*) s
DEALLOCATE(field)
END PROGRAM
and a module
MODULE mtest ! <>
IMPLICIT NONE ! <>
CONTAINS ! <>
SUBROUTINE stest(n, field, erg)
INTEGER :: n
REAL, DIMENSION(n,n) :: field
REAL :: erg
erg = SUM(field)
END SUBROUTINE
END MODULE ! <>
As far as I understand, this subroutine gets an automatic (explicit?) interface from being placed in the module. The problem is, that the actual field has length 10, while the subroutine sums a field of length 10x10=100 which is clearly visible in valgrind as an invalid read.
Then I tested this same code without the module, i.e. all lines marked with ! <> got removed/commented. As a result, gfortran's -Wimplicit-interface threw a warning, but the code worked as before.
So my question is: What is the best way, to deal with such a situation? Should I always place a generic interface à la
INTERFACE stest
MODULE PROCEDURE stest
END INTERFACE
in the module? Or should I replace the definition of field with an deferred-shape array (i.e. REAL, ALLOCATABLE, DIMENSION(:,:) :: field)?
EDIT: To be more precise on my question, I don't want to solve this particular problem, but want to know, what to do, to get a better diagnostic output from the compiler.
E.g. the given code doesn't give an error message and does, in principle, produce a segmentation fault (though, the code doesn't notice it). Placing a generic interface produces at least an error, complaining, that no matching definition for stest is found, which is also not really helpful, especially in the case, where you don't have the source code. Only a deferred-shape array resulted in an understandable error message (rank mismatch).
And this is, were I'm wondering, why the automatic module interface doesn't give a similar warning/error message.
The compiler cannot warn you, because the code is legal! You just pass wrong n and a non-square number of points. For explicit shape arrays you are responsible for correct dimensions. Consider
ALLOCATE(field(1000))
CALL stest(10, field, s)
this code will work although the number of elements of the actual and dummy arguments is not the same. Maybe suggest to gfortran developers to check whether the dummy argument is not larger, but I am not sure how difficult that is.
The generic interface causes the compiler to check the TKR rules. No sequence association of arrays of different rank is allowed and the compilation will fail. Therefore it will disable all legal uses of passing arrays of different rank to explicit shape and assumed size dummy arguments and limit your possibilities.
What is the solution? Use explicit shape arrays for situations they are good for and use assumed shape arrays otherwise (possibly with the contiguous attribute). The generic interface might help too, but changes the semantics and limits the possible use.

Lisp Function Interpretation

I am reading a book and I am confused on what the following code does:
(defmethod execute ((o ORDER) (l SIMUL) (e MARKETUPDATE))
(values
(list (make-TRADE :timestamp (timestamp e)
:price (price e)
:quantity (orderquantity o)))
NIL))
The source to which I got this function says that it returns two values. My question is what the body does. From my understanding, the line 3-5 creates a list with :timestamp, :price, :quantity. Am I correct? What about values, the second line? Does it return this variable too? Any summary would help. Thanks
This is a method for a generic function, specializing on arguments of types order, simul, and marketupdate.
It returns 2 values:
A list of length 1 created by the eponymous function list, which contains a single object of, presumably, type trade (probably - but not necessarily - created by a defstruct), which has slots timestamp, price, and quantity.
Symbol nil.
You can probably access the slots of the trade using functions trade-timestamp &c (unless the defstruct form is non-trivial or trade is not defined by a defstruct at all).
Why the result of make-trade is wrapped in a list is hard to guess without more context, but I'd guess that an execute can be split into N trades in some scenarios.
I suspect your confusion arises almost entire because this is the first time you have encountered a use of values. Common Lisp allows functions to return multiple values. That's slightly similar to how any language allows functions to receive multiple parameters.
These multiple return values are quite efficiently implemented. Most newbies encounter multiple values for the first time on the integer division functions, which will return a remainder as their second value. Hash table look ups will return a second value to indicate if the key was actually in the table, since the value stored for the key might be nil.
In your example the second value is NIL, presumably other execute methods might return something more interesting - for example where in the update Q the order was place, or an error code if something goes wrong. Of course checking out the manual for values will be fraught with educational values(sic).
This function is a method returning two values by using the keyword values. Have a look at CLOS to better understand object orientation and at "values" for the way of returning more than one value.

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.