FICO
FICO Xpress Optimization Examples Repository
FICO Optimization Community FICO Xpress Optimization Home
Back to examples browserNext example

Using 'exists' for loops over sparse arrays

Description
The models loop.mos/looph.mos and proj.mos show the effect of using the keyword exists in conditions on loops over sparse arrays. As can be seen, the careful formulation of loops may result in a considerable speedup of the model execution time. Mosel defines two forms of sparse arrays, namely dynamic arrays and hashmap arrays. The model sparsearrays.mos compares the performance of these two forms for different cases of enumerations.

Further explanation of this example: 'Mosel User Guide', Appendix 'Good modeling practice' explains in detail the correct use of exists.


Source Files

Data Files





loop.mos

(!*******************************************************
   Mosel Example Problems 
   ======================

   file loop.mos
   `````````````
   Demonstrate effect of `exists'
       
   (c) 2008 Fair Isaac Corporation
       author: S. Heipcke, 2002, rev. Sep. 2018
*******************************************************!)

model "loop"
 uses "mmsystem"

 public declarations
  R1,R2,R3,R4,R5: range 
  Cost: dynamic array(R1,R2,R3,R4,R5) of real
  x: dynamic array(R1,R2,R3,R4,R5) of mpvar
 end-declarations

                  ! This would normally be read in from a file
 Cost(1,1,1,1,1) := 1.1
 Cost(1,30,1,3,3) := 2.2
 Cost(1,1,30,1,4) := 3.3
 Cost(1,1,1,30,1) := 4.4
 Cost(1,6,1,1,30) := 5.5
 Cost(30,1,1,1,3) := 6.6

 forall(i1 in R1, i2 in R2, i3 in R3, i4 in R4, i5 in R5 | 
   exists(Cost(i1,i2,i3,i4,i5)) )  create(x(i1,i2,i3,i4,i5))

 starttime:=gettime

! 'exists' is not required here from a logical point of view, since the
! sum  will only contain the variables that have been created, but it
! helps speeding up things. Compare the running times with and without it:

 sum(i1 in R1, i2 in R2, i3 in R3, i4 in R4, i5 in R5 | 
   exists(Cost(i1,i2,i3,i4,i5)) ) 
  Cost(i1,i2,i3,i4,i5) * x(i1,i2,i3,i4,i5) = 1

 writeln("Time using `exists': ", gettime-starttime)

 sum(i1 in R1, i2 in R2, i3 in R3, i4 in R4, i5 in R5 ) 
  Cost(i1,i2,i3,i4,i5) * x(i1,i2,i3,i4,i5) = 1

 writeln("Time without `exists': ", gettime-starttime)

! Display the resulting constraint definitions
 exportprob(0,"",0)
end-model  

Back to examples browserNext example