Re: [eclipse-clp-users] Dynamically Imposing Constraints

From: Joachim Schimpf <joachim.schimpf_at_...44...>
Date: Tue, 03 Nov 2009 11:00:08 +1100
Igor Kondrasovas wrote:
> I have a preliminary version of my program running, but one important
> thing missing is that I need to dynamically impose the constraints,
> based on the length of the input arrays. Let me show an example with
> what I mean:
> 
> linear(PieceLengths, BarsLengths, M) :-   
>                 dim(PieceLengths, [NPieces]),
>                 dim(BarsLengths, [NBars]),
>                 dim(M,[NPieces,NBars]),
>                 M #::0..1,
> 
>                 % Constraints that the sum of every column value in each row must be equals 1
>                 M[1,1] + M[1,2] + M[1,3] #= 1,
>                 M[2,1] + M[2,2] + M[2,3] #= 1,
>                 M[3,1] + M[3,2] + M[3,3] #= 1,
>                 M[4,1] + M[4,2] + M[4,3] #= 1,
>                 M[5,1] + M[5,2] + M[5,3] #= 1,
>                 M[6,1] + M[6,2] + M[6,3] #= 1,
>                 M[7,1] + M[7,2] + M[7,3] #= 1,
>                 M[8,1] + M[8,2] + M[8,3] #= 1,
>                 M[9,1] + M[9,2] + M[9,3] #= 1,
>                 M[10,1] + M[10,2] + M[10,3] #= 1,
> 
> As you can see here, this constrains are fixed and will work only when M
> is 10x3 matrix. I must change it in order to accept any input
> configuration.
> 
> I imagine I can iterate to every single line of the M matrix using a
> simple for loop. But for the sum of the columns values a loop will not
> help me since I must “construct” the constraint instead of perform any
> calculation at every iteration. Is it possible to do with Eclipse?

Yes, ECLiPSe is very good at symbolic manipulation, e.g. you could write

	LeftHandSide = M[1,1] + M[1,2] + M[1,3],
	LeftHandSide #= 1.

Here, LeftHandSide contains the symbolic expression _as_a_data_structure_,
and you can use that in the #= constraint.

You can then of course construct such a data structure in a loop:

	( for(J,1,3), fromto(0,LHS1,LHS2,LHS), param(M) do
		LHS2 = LHS1 + M[1,J]
	),
	LHS #= 1.

A little bit simpler is to construct a list and use sum(List):

	( for(J,1,3), foreach(M[1,J],MIJs), param(M) do
		true
	),
	sum(MIJs) #= 1.

And even simpler is the following shorthand:

	sum(M[1,1..3]) #= 1.

Have a look at some examples on the web site
http://eclipse-clp.org/examples/magicsquare.ecl.txt or
http://eclipse-clp.org/examples/tomo.ecl.txt


-- Joachim
Received on Tue Nov 03 2009 - 00:00:09 CET

This archive was generated by hypermail 2.3.0 : Wed Sep 25 2024 - 15:13:20 CEST