Search code examples
pythonoptimizationlinear-programmingpyomo

How to build a correct linking constraint in Pyomo - Mixed Integer Linear program?


Context: I am working on an assignment for which I am using Pyomo in order to learn this framework. Here is the assignment :

header

Fixed cost contraint

From this problem, I understand that I should be introducing a binary variable in order to trigger the fixed cost constraint.

Here is my implementation :

from pyomo.environ import *

VERY_LARGE_NUMBER = 1e8


def part_4_april(data, limit_ballons, limit_labor):

    model = ConcreteModel()

    PACKAGES = data.keys()

    model.x = Var(PACKAGES, within=NonNegativeReals)
    model.y = Var(PACKAGES, within=Binary)

    model.profit = Objective(
        expr=sum(
            (
                (data[p]["price"] - data[p]["cost"]) * model.x[p]
                - data[p]["fixed_cost"] * model.y[p]
            )
            for p in PACKAGES
        ),
        sense=maximize,
    )

    model.ballon_cst = Constraint(
        expr=sum(data[p]["ballons"] * model.x[p] for p in PACKAGES) <= limit_ballons
    )

    model.labor_cst = Constraint(
        expr=sum(data[p]["labor"] * model.x[p] for p in PACKAGES) <= limit_labor
    )

    model.fixed_cost_cst = Constraint(
        expr=sum(model.x[p] - VERY_LARGE_NUMBER * model.y[p] for p in PACKAGES) <= 0
    )

    opt = SolverFactory("cbc")
    results = opt.solve(model, tee=True)
    model.pprint()
    return model


if __name__ == "__main__":
    # part 4
    data = {
        "Standard": {"labor": 3, "ballons": 2, "cost": 2, "price": 3, "fixed_cost": 10},
        "Joyful": {"labor": 5, "ballons": 5, "cost": 3, "price": 5, "fixed_cost": 5},
        "Fabulous": {"labor": 8, "ballons": 8, "cost": 4, "price": 7, "fixed_cost": 1},
    }
    model = part_4_april(data, limit_ballons=360, limit_labor=500)
    print("----- PART 4: April -----")
    print("Profit:", model.profit())
    for c in data.keys():
        print("  ", c, ":", model.x[c]())

The code does not produce the expected output, instead, it must produce the following output :

    # must produce :
    # Profit: 188.0
    #     Standard : 140.0
    #     Joyful : 0.0
    #     Fabulous : 10.0

Is there a problem with my code or the way I use the binary variables ?


Solution

  • I finally found the solution with the comment from Bethany Nicholson and Erwin Kalvelangen - there were two issues with my code. First, the fixed cost must not contain sum and should be applied to all packages individually

    # NOT...
    # model.fixed_cost_cst = Constraint(
    #     expr=sum(model.x[p] - VERY_LARGE_NUMBER * model.y[p] for p in PACKAGES) <= 0
    # )
    
    # must be applied to all packages individually 
    def fixed_cost_rule(model, p):
        return model.x[p] - VERY_LARGE_NUMBER * model.y[p] <= 0
    
    model.fixed_cost_cst = Constraint(PACKAGES, rule=fixed_cost_rule)
    

    Second, the result must be 159 and not 188.