Search code examples
c#constraint-programmingms-solver-foundation

How can I define a constraint that prevents a resource to be allocated to 2 tasks that overlap?


How can I define a constraint that prevents a resource to be allocated to 2 tasks that overlap?

I have defined 5 resources: R1,R2,...,R5 and 3 tasks: T1,T2,T3 that have their corresponding start and end date(s1, e1 represent the start and end date of the first task, s2,e2 of second task and so on). My constraint should prevent R1 to be allocated to task T1 and task T2 if these two tasks overlap. R1 can be allocated to any number of tasks so if T1 and T3 do not overlap, they can both be performed by R1.

I am planning to use C# and Microsoft Solver Foundation to solve this problem but of course this is not so important. My problem is that I don't know how to formulate this problem as a constraint.


Solution

  • There are many ways to formulate these kinds of constraints to handle overlaps and conflicts.

    Here's one very common and standard practice.

    Preprocessing to create conflict matrix

    First, create a conflict matrix (technically the lower triangle is enough) of size T^2 where T is the number of Tasks. If Tj and Tk overlap, then you will mark a 1, otherwise 0 (to indicate no conflict).

    For example, this could be your conflict matrix:

         T1  | T2 | T3
    T1   --  | 1  | 0
    T2    1  | -- | 1
    T3    0  | 1  | --
    

    In order to create this matrix, you have to make O(T^2) comparisons involving each pair of tasks j and k (sj, ej) and (sk, ek). Note that this can be computed once, offline, before you even invoke your solver.

    Formulation

    Let X_Ri_Tj = 1 if Resource i is assigned to Task j.

    Now, you can write the "overlap prevention constraints." For each conflict in the matrix, there will be R number of constraints.

    As a concrete example, from the matrix above, let's say that we want to write the constraints to prevent the same Resource being assigned to tasks T2 and T3 (since they are overlapping). You will write those as:

      Xr1t2 + Xr1t3 <= 1
      Xr2t2 + Xr2t3 <= 1
      Xr3t2 + Xr3t3 <= 1
      ... for each resource R
    

    This type of constraint generation is fairly common in Job Shop Scheduling and in the "time tabling" class of problems.