• Docs »
  • Example tour »
  • Resource Constrained Project Scheduling Problem (RCPSP)

Resource Constrained Project Scheduling Problem (RCPSP)

Principles learned

  • Set precedence constraints

  • Use a lambda expression to compute a sum with a variable number of terms

Problem

../_images/rcpsp.svg

In the resource constrained project scheduling problem, a project consists of a set of tasks that have to be scheduled. Each task has a given duration and cannot be interrupted. There are precedence constraints between the tasks: each task must end before any of its successors can start. There are a set of renewables resources. Each task has a given resource requirement, or weight, (possibly zero) on each resource, representing the amount of resource it consumes while it is being processed. Each resource has a given maximum capacity: it can process several tasks at once, but the sum of the processed tasks’s weights can never exceed this maximum capacity.

The goal is to find a schedule that minimizes the makespan: the time when all tasks have been processed.

Download the example


Data

The instances provided follow the Patterson format. The format of the data files is as follows:

  • First line:

    • Number of tasks (including two additional dummy tasks with duration 0, the source and the sink)

    • Number of renewable resources

  • Second line: Maximum capacity for each resource

  • From the third line, for each task:

    • Duration of the task

    • Resource requirements (weights) for each resource

    • Number of successors

    • Task ID for each successor

Program

We use integer decision variables to model the start times of the tasks. The end time expressions are deduced by summing the start time and the duration of each task.

The precedence constraints are easily written: each task must end before any of its successors can start.

The cumulative resource constraints can be formulated as follows: for each resource, and for each time slot d, the amount of resource consumed by the tasks that are being processed must not exceed the resource’s capacity.

To model these constraints, we sum up, for each resource, the weights of all the tasks started before and ended after each time slot d.

The makespan to minimize is the time when all the tasks have been processed.

Execution:
localsolver rcpsp.lsp inFileName=instances/Pat1.rcp [outFileName=] [lsTimeLimit=]
use io;

// The input files follow The "Patterson" Format
function input() {
    local usage = "Usage: localsolver rcpsp.lsp inFileName=instanceFile "
            + "[outFileName=outputFile] [lsTimeLimit=timeLimit]";
    if (inFileName == nil) throw usage;

    inFile = io.openRead(inFileName);
    nbTasks = inFile.readInt();
    nbResources = inFile.readInt();

    // Maximum capacity of each resource
    for [r in 0..nbResources-1] {
        capacity[r] = inFile.readInt();
    }

    for [t in 0..nbTasks-1] {
        // Duration of each task
        duration[t] = inFile.readInt();
        for[r in 0..nbResources-1] {
            // Resource weight of resource r required for task t
            weight[t][r] = inFile.readInt();
        }
        nbSuccessors[t] = inFile.readInt();
        // Successors of each task t
        for [s in 0..nbSuccessors[t]-1] {
            successors[t][s] = inFile.readInt() - 1;
        }
    }

    // Trivial upper bound for the start times of the tasks
    horizon = sum[t in 0..nbTasks-1](duration[t]);
    
    inFile.close();
}

function model() {
    // Integer decisions: start time of each task
    start[t in 0..nbTasks-1] <- int(0, horizon);
    end[t in 0..nbTasks-1] <- start[t] + duration[t];

    // Precedence constraints between the tasks
    for[t in 0..nbTasks-1][s in 0..nbSuccessors[t]-1] {
        constraint start[successors[t][s]] >= end[t];
    }

    // Makespan: end of the last task
    makespan <- max[t in 0..nbTasks-1] (end[t]);
    
    // Cumulative resource constraints
    for [r in 0..nbResources-1] {
        constraint and(0..makespan-1, d =>
                sum[t in 0..nbTasks-1](weight[t][r] * (start[t] <= d && end[t] > d)) <= capacity[r]);
    }
    
    // Minimize the makespan
    minimize makespan;
}

// Parameterize the solver
function param() {
    if (lsTimeLimit == nil) lsTimeLimit = 60;
}

/* Write the solution in a file with the following format:
 *  - total makespan
 *  - for each task, the task id, the start and end times */
function output() {
    if (outFileName != nil) {
        outFile = io.openWrite(outFileName);
        println("Solution written in file ", outFileName);
        outFile.println(makespan.value);
        for [t in 0..nbTasks-1] {
            outFile.println(t + 1, " ", start[t].value, " ", end[t].value);
        }
    }
}
Execution (Windows)
set PYTHONPATH=%LS_HOME%\bin\python
python rcpsp.py instances\Pat1.rcp
Execution (Linux)
export PYTHONPATH=/opt/localsolver_11_5/bin/python
python rcpsp.py instances/Pat1.rcp
import localsolver
import sys


# The input files follow the "Patterson" format
def read_instance(filename):
    with open(filename) as f:
        lines = f.readlines()

    first_line = lines[0].split()

    # Number of tasks
    nb_tasks = int(first_line[0])

    # Number of resources
    nb_resources = int(first_line[1])

    # Maximum capacity of each resource
    capacity = [int(lines[1].split()[r]) for r in range(nb_resources)]

    # Duration of each task
    duration = [0 for t in range(nb_tasks)]

    # Resource weight of resource r required for task t
    weight = [[] for t in range(nb_tasks)]

    # Number of successors
    nb_successors = [0 for t in range(nb_tasks)]

    # Successors of each task t
    successors = [[] for t in range(nb_tasks)]

    for t in range(nb_tasks):
        line = lines[t + 2].split()
        duration[t] = int(line[0])
        weight[t] = [int(line[r + 1]) for r in range(nb_resources)]
        nb_successors[t] = int(line[nb_resources + 1])
        successors[t] = [int(line[nb_resources + 2 + s]) - 1 for s in range(nb_successors[t])]

    # Trivial upper bound for the start times of the tasks
    horizon = sum(duration[t] for t in range(nb_tasks))

    return (nb_tasks, nb_resources, capacity, duration, weight, nb_successors, successors, horizon)


def main(instance_file, output_file, time_limit):
    nb_tasks, nb_resources, capacity, duration, weight, nb_successors, successors, horizon = read_instance(instance_file)

    with localsolver.LocalSolver() as ls:
        #
        # Declare the optimization model
        #
        model = ls.model

        # Integer decisions: start time of each task
        start = [model.int(0, horizon) for t in range(nb_tasks)]
        end = [start[t] + duration[t] for t in range(nb_tasks)]

        # Precedence constraints between the tasks
        for t in range(nb_tasks):
            for s in range(nb_successors[t]):
                model.constraint(start[successors[t][s]] >= end[t])

        # Makespan: end of the last task
        makespan = model.max([end[t] for t in range(nb_tasks)])

        # Cumulative resource constraints
        for r in range(nb_resources):
            capacity_respected = model.lambda_function(
                lambda d: model.leq(
                    model.sum(
                        weight[t][r] * model.and_(model.leq(start[t], d), model.gt(end[t], d))
                        for t in range(nb_tasks)),
                    capacity[r]))
            model.constraint(model.and_(model.range(makespan), capacity_respected))

        # Minimize the makespan
        model.minimize(makespan)

        model.close()

        # Parameterize the solver
        ls.param.time_limit = time_limit

        ls.solve()

        #
        # Write the solution in a file with the following format:
        # - total makespan
        # - for each task, the task id, the start and end times
        #
        if output_file != None:
            with open(output_file, "w") as f:
                print("Solution written in file", output_file)
                f.write(str(makespan.value) + "\n")
                for t in range(nb_tasks):
                    f.write(str(t + 1) + " " + str(start[t].value) + " " + str(end[t].value))
                    f.write("\n")


if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("Usage: python rcpsp.py instance_file [output_file] [time_limit]")
        sys.exit(1)

    instance_file = sys.argv[1]
    output_file = sys.argv[2] if len(sys.argv) >= 3 else None
    time_limit = int(sys.argv[3]) if len(sys.argv) >= 4 else 60
    main(instance_file, output_file, time_limit)
Compilation / Execution (Windows)
cl /EHsc rcpsp.cpp -I%LS_HOME%\include /link %LS_HOME%\bin\localsolver115.lib
rcpsp instances\Pat1.rcp
Compilation / Execution (Linux)
g++ rcpsp.cpp -I/opt/localsolver_11_5/include -llocalsolver115 -lpthread -o rcpsp
./rcpsp instances/Pat1.rcp
#include "localsolver.h"
#include <algorithm>
#include <fstream>
#include <iostream>
#include <limits>
#include <numeric>
#include <vector>

using namespace localsolver;

class Rcpsp {
  private:
    // Number of tasks
    int nbTasks;
    // Number of resources
    int nbResources;
    // Maximum capacity of each resource
    std::vector<int> capacity;
    // Duration of each task
    std::vector<int> duration;
    // Resource weight of resource r required for task t
    std::vector<std::vector<int>> weight;
    // Number of successors
    std::vector<int> nbSuccessors;
    // Successors for each task t
    std::vector<std::vector<int>> successors;
    // Trivial upper bound for the start times of the tasks
    int horizon = 0;

    // Localsolver
    LocalSolver localsolver;
    // Integer decisions: start time of the tasks
    std::vector<LSExpression> start;
    // End times for each task
    std::vector<LSExpression> end;
    // Objective = minimize the makespan: end of the last task of the last job
    LSExpression makespan;

  public:
    Rcpsp(const std::string& fileName) : localsolver() {}

    // The input files follow the "Patterson" format
    void readInstance(const std::string& fileName) {
        std::ifstream infile;
        infile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
        infile.open(fileName.c_str());

        infile >> nbTasks;
        infile >> nbResources;

        // The maximum capacity of each resource
        capacity.resize(nbResources);
        for (int r = 0; r < nbResources; ++r) {
            infile >> capacity[r];
        }

        duration.resize(nbTasks);
        weight.resize(nbTasks);
        nbSuccessors.resize(nbTasks);
        successors.resize(nbTasks);

        for (int t = 0; t < nbTasks; ++t) {
            infile >> duration[t];
            weight[t].resize(nbResources);
            for (int r = 0; r < nbResources; ++r) {
                infile >> weight[t][r];
            }
            infile >> nbSuccessors[t];
            successors[t].resize(nbSuccessors[t]);
            for (int s = 0; s < nbSuccessors[t]; ++s) {
                int x;
                infile >> x;
                successors[t][s] = x - 1;
            }
            horizon += duration[t];
        }

        infile.close();
    }

    void solve(int TimeLimit) {
        // Declare the optimization model
        LSModel model = localsolver.getModel();

        // Integer decisions: start time of each task
        start.resize(nbTasks);
        end.resize(nbTasks);
        for (int t = 0; t < nbTasks; ++t) {
            start[t] = model.intVar(0, horizon);
            end[t] = start[t] + duration[t];
        }

        // Precedence constraints between the tasks
        for (int t = 0; t < nbTasks; ++t) {
            for (int s = 0; s < nbSuccessors[t]; ++s) {
                model.constraint(start[successors[t][s]] >= end[t]);
            }
        }

        // Makespan: end of the last task
        makespan = model.max();
        for (int t = 0; t < nbTasks; ++t) {
            makespan.addOperand(end[t]);
        }

        // Cumulative resource constraints
        for (int r = 0; r < nbResources; ++r) {
            LSExpression capacityRespected = model.createLambdaFunction([&](LSExpression d) {
                LSExpression totalWeight = model.sum();
                for (int t = 0; t < nbTasks; ++t) {
                    LSExpression taskWeight = weight[t][r] * model.and_(model.leq(start[t], d), model.gt(end[t], d));
                    totalWeight.addOperand(taskWeight);
                }
                return model.leq(totalWeight, capacity[r]);
            });
            model.constraint(model.and_(model.range(0, makespan), capacityRespected));
        }

        // Minimize the makespan
        model.minimize(makespan);

        model.close();

        // Parameterize the solver
        localsolver.getParam().setTimeLimit(TimeLimit);

        localsolver.solve();
    }

    /* Write the solution in a file with the following format:
     *  - total makespan
     *  - for each task, the task id, the start and end times */
    void writeSolution(const std::string& fileName) {
        std::ofstream outfile(fileName.c_str());
        if (!outfile.is_open()) {
            std::cerr << "File " << fileName << " cannot be opened." << std::endl;
            exit(1);
        }
        std::cout << "Solution written in file " << fileName << std::endl;

        outfile << makespan.getValue() << std::endl;
        for (int t = 0; t < nbTasks; ++t) {
            outfile << t + 1 << " " << start[t].getValue() << " " << end[t].getValue() << std::endl;
        }
        outfile.close();
    }
};

int main(int argc, char** argv) {
    if (argc < 2) {
        std::cout << "Usage: Rcpsp instanceFile [outputFile] [timeLimit]" << std::endl;
        exit(1);
    }

    const char* instanceFile = argv[1];
    const char* outputFile = argc > 2 ? argv[2] : NULL;
    const char* strTimeLimit = argc > 3 ? argv[3] : "60";

    Rcpsp model(instanceFile);
    try {
        model.readInstance(instanceFile);
        const int timeLimit = atoi(strTimeLimit);
        model.solve(timeLimit);
        if (outputFile != NULL)
            model.writeSolution(outputFile);
        return 0;
    } catch (const std::exception& e) {
        std::cerr << "An error occurred: " << e.what() << std::endl;
        return 1;
    }
}
Compilation / Execution (Windows)
copy %LS_HOME%\bin\localsolvernet.dll .
csc Rcpsp.cs /reference:localsolvernet.dll
Rcpsp instances\Pat1.rcp
using System;
using System.IO;
using localsolver;

public class Rcpsp : IDisposable
{
    // Number of tasks
    private int nbTasks;

    // Number of resources
    private int nbResources;

    // Maximum capacity of each resource
    private int[] capacity;

    // Duration of each task
    private int[] duration;

    // Resource weight of resource r required for task t
    private int[,] weight;

    // Number of successors
    private int[] nbSuccessors;

    // Successors for each task t
    private int[][] successors;

    // Trivial upper bound for the start times of the tasks
    private int horizon = 0;

    // LocalSolver
    private LocalSolver localsolver;

    // Decision variables: start times of the tasks
    private LSExpression[] start;

    // End times for each task
    private LSExpression[] end;

    // Objective = minimize the makespan: end of the last activity of the last task
    private LSExpression makespan;

    public Rcpsp(string fileName)
    {
        localsolver = new LocalSolver();
    }

    // The input files follow the "Patterson" format
    private void ReadInstance(string fileName)
    {
        using (StreamReader input = new StreamReader(fileName))
        {
            string[] splitted = input.ReadLine().Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            if (splitted.Length == 0)
                splitted = input.ReadLine().Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            nbTasks = int.Parse(splitted[0]);
            nbResources = int.Parse(splitted[1]);

            // The maximum capacity of each resource
            capacity = new int[nbResources];
            splitted = input.ReadLine().Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            for (int r = 0; r < nbResources; ++r)
                capacity[r] = int.Parse(splitted[r]);

            duration = new int[nbTasks];
            weight = new int[nbTasks, nbResources];
            nbSuccessors = new int[nbTasks];
            successors = new int[nbTasks][];

            for (int t = 0; t < nbTasks; ++t)
            {
                splitted = input.ReadLine().Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                if (splitted.Length == 0)
                    splitted = input.ReadLine().Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                duration[t] = int.Parse(splitted[0]);
                for (int r = 0; r < nbResources; ++r)
                    weight[t, r] = int.Parse(splitted[r + 1]);
                nbSuccessors[t] = int.Parse(splitted[nbResources + 1]);
                successors[t] = new int[nbSuccessors[t]];
                for (int s = 0; s < nbSuccessors[t]; ++s)
                    successors[t][s] = int.Parse(splitted[s + nbResources + 2]) - 1;
                horizon += duration[t];
            }
        }
    }

    public void Dispose()
    {
        localsolver.Dispose();
    }

    public void Solve(int timeLimit)
    {
        // Declare the optimization model
        LSModel model = localsolver.GetModel();

        // Integer decisions: start time of each task
        start = new LSExpression[nbTasks];
        end = new LSExpression[nbTasks];
        for (int t = 0; t < nbTasks; ++t)
        {
            start[t] = model.Int(0, horizon);
            end[t] = start[t] + duration[t];
        }

        // Precedence constraints between the tasks
        for (int t = 0; t < nbTasks; ++t)
        {
            for (int s = 0; s < nbSuccessors[t]; ++s)
                model.Constraint(start[successors[t][s]] >= end[t]);
        }

        // Makespan: end of the last task
        makespan = model.Max();
        for (int t = 0; t < nbTasks; ++t)
            makespan.AddOperand(end[t]);

        // Cumulative resource constraints
        for (int r = 0; r < nbResources; ++r)
        {
            LSExpression capacityRespected = model.LambdaFunction(d =>
                {
                    LSExpression totalWeight = model.Sum();
                    for (int t = 0; t < nbTasks; ++t) 
                    {
                        totalWeight.AddOperand(weight[t,r] * model.And(start[t] <= d, end[t] > d));
                    }
                    return totalWeight <= capacity[r];
                }
            );
            model.Constraint(model.And(model.Range(0, makespan), capacityRespected));
        }

        // Minimize the makespan
        model.Minimize(makespan);

        model.Close();

        // Parameterize the solver
        localsolver.GetParam().SetTimeLimit(timeLimit);

        localsolver.Solve();
    }

    /* Write the solution in a file with the following format:
     *  - total makespan
     *  - for each task, the task id, the start and end times */
    public void WriteSolution(string fileName)
    {
        using (StreamWriter output = new StreamWriter(fileName))
        {
            Console.WriteLine("Solution written in file " + fileName);
            output.WriteLine(makespan.GetValue());
            for (int t = 0; t < nbTasks; ++t)
            {
                output.Write((t + 1) + " " + start[t].GetValue() + " " + end[t].GetValue());
                output.WriteLine();
            }
        }
    }

    public static void Main(string[] args)
    {
        if (args.Length < 1)
        {
            Console.WriteLine("Usage: Rcpsp instanceFile [outputFile] [timeLimit]");
            System.Environment.Exit(1);
        }

        string instanceFile = args[0];
        string outputFile = args.Length > 1 ? args[1] : null;
        string strTimeLimit = args.Length > 2 ? args[2] : "60";

        using (Rcpsp model = new Rcpsp(instanceFile))
        {
            model.ReadInstance(instanceFile);
            model.Solve(int.Parse(strTimeLimit));
            if (outputFile != null)
                model.WriteSolution(outputFile);
        }
    }
}
Compilation / Execution (Windows)
javac Rcpsp.java -cp %LS_HOME%\bin\localsolver.jar
java -cp %LS_HOME%\bin\localsolver.jar;. Rcpsp instances\Pat1.rcp
Compilation / Execution (Linux)
javac Rcpsp.java -cp /opt/localsolver_11_5/bin/localsolver.jar
java -cp /opt/localsolver_11_5/bin/localsolver.jar:. Rcpsp instances/Pat1.rcp
import java.util.*;
import java.io.*;
import localsolver.*;

public class Rcpsp {
    // Number of tasks
    private int nbTasks;
    // Number of resources
    private int nbResources;
    // Maximum capacity of each resource
    private int[] capacity;
    // Duration of each task
    private int[] duration;
    // Resource weight of resource r required for task t
    private int[][] weight;
    // Number of successors
    private int[] nbSuccessors;
    // Successors for each task t
    private int[][] successors;
    // Trivial upper bound for the start times of the tasks
    private int horizon = 0;

    // LocalSolver
    final LocalSolver localsolver;
    // Decision variables: start times of the tasks
    private LSExpression[] start;
    // End times for each task
    private LSExpression[] end;
    // Objective = minimize the makespan: end of the last task of the last job
    private LSExpression makespan;

    public Rcpsp(LocalSolver localsolver, String fileName) throws IOException {
        this.localsolver = localsolver;
    }

    // The input files follow the "Patterson" format
    private void readInstance(String fileName) throws IOException {
        try (Scanner input = new Scanner(new File(fileName))) {
            nbTasks = input.nextInt();
            nbResources = input.nextInt();

            // The maximum capacity of each resource
            capacity = new int[nbResources];
            for (int r = 0; r < nbResources; ++r) {
                capacity[r] = input.nextInt();
            }

            duration = new int[nbTasks];
            weight = new int[nbTasks][nbResources];
            nbSuccessors = new int[nbTasks];
            successors = new int[nbTasks][];
            for (int t = 0; t < nbTasks; ++t) {
                duration[t] = input.nextInt();
                for (int r = 0; r < nbResources; ++r) {
                    weight[t][r] = input.nextInt();
                }
                nbSuccessors[t] = input.nextInt();
                successors[t] = new int[nbSuccessors[t]];
                for (int s = 0; s < nbSuccessors[t]; ++s) {
                    successors[t][s] = input.nextInt() - 1;
                }
                horizon += duration[t];
            }
        }
    }

    public void solve(int timeLimit) {
        // Declare the optimization model
        LSModel model = localsolver.getModel();

        // Integer decisions: start time of each task
        start = new LSExpression[nbTasks];
        end = new LSExpression[nbTasks];
        for (int t = 0; t < nbTasks; ++t) {
            start[t] = model.intVar(0, horizon);
            end[t] = model.sum(start[t], duration[t]);
        }

        // Precedence constraints between the tasks
        for (int t = 0; t < nbTasks; ++t) {
            for (int s = 0; s < nbSuccessors[t]; ++s) {
                model.constraint(model.geq(start[successors[t][s]], end[t]));
            }
        }

        // Makespan: end of the last task
        makespan = model.max();
        for (int t = 0; t < nbTasks; ++t) {
            makespan.addOperand(end[t]);
        }

        // Cumulative resource constraints
        for (int r = 0; r < nbResources; ++r) {
            LSExpression rExpr = model.createConstant(r);
            LSExpression capacityArray = model.array(capacity);
            LSExpression capacityRespected = model.lambdaFunction(d ->
                {
                    LSExpression totalWeight = model.sum();
                    for (int t = 0; t < nbTasks; ++t) {
                        LSExpression weightArray = model.array(weight[t]);
                        totalWeight.addOperand(model.prod(
                                                model.at(weightArray,rExpr),
                                                model.and(model.leq(start[t], d),
                                                                model.gt(end[t], d))));
                    }
                    return model.leq(totalWeight, model.at(capacityArray, rExpr));
                }
            );
            model.constraint(model.and(model.range(0, makespan), capacityRespected));
        }

        // Minimize the makespan
        model.minimize(makespan);

        model.close();

        // Parameterize the solver
        localsolver.getParam().setTimeLimit(timeLimit);

        localsolver.solve();
    }

    /*
     * Write the solution in a file with the following format:
     * - total makespan
     * - for each task, the task id, the start and end times
     */
    public void writeSolution(String fileName) throws IOException {
        try (PrintWriter output = new PrintWriter(fileName)) {
            System.out.println("Solution written in file " + fileName);

            output.println(makespan.getValue());

            for (int t = 0; t < nbTasks; ++t) {
                output.println((t + 1) + " " + start[t].getValue() + " " + end[t].getValue());
            }
        }
    }

    public static void main(String[] args) {
        if (args.length < 1) {
            System.out.println("Usage: java Rcpsp instanceFile [outputFile] [timeLimit]");
            System.exit(1);
        }

        String instanceFile = args[0];
        String outputFile = args.length > 1 ? args[1] : null;
        String strTimeLimit = args.length > 2 ? args[2] : "60";

        try (LocalSolver localsolver = new LocalSolver()) {
            Rcpsp model = new Rcpsp(localsolver, instanceFile);
            model.readInstance(instanceFile);
            model.solve(Integer.parseInt(strTimeLimit));
            if (outputFile != null) {
                model.writeSolution(outputFile);
            }
        } catch (Exception ex) {
            System.err.println(ex);
            ex.printStackTrace();
            System.exit(1);
        }
    }
}