Linjär programmering

Introduktion till optimering i Python

Jasmin Ludolf

Content Developer

Linjär programmering

  • Målfunktioner och bivillkor har ett linjärt samband

  • Till skillnad från linjärt begränsade: blandning av linjära eller icke-linjära element

Introduktion till optimering i Python

Produktmix

 

Typ Antal Flaskor (h/låda) Koppar (h/låda)
$M_A$ 4 1.5 1.3
$M_B$ 3 0.8 2.1

 

  • Varje maskin körs 30 timmar per vecka

 

  • Efterfrågan: flaskor för dryck, koppar för yoghurt
Introduktion till optimering i Python

Maximera vinst

  • Vinst per låda
B ($/låda) C ($/låda)
480 510

 

  • Målfunktion: $480B + 510C$
  • Bivillkor
    • Maskin A: $1.5B+1.3C\leq 4 \times 30$
    • Maskin B: $0.8B+ 2.1C \leq 3\times 30$
    • Icke-negativitetsvillkor: $B, C \geq 0$
Introduktion till optimering i Python

Använda PuLP

from pulp import *


model = LpProblem('MaxProfit', LpMaximize)
B = LpVariable('B', lowBound=0) C = LpVariable('C', lowBound=0)
model += 480*B + 510*C
model += 1.5*B + 1.3*C - 120, "M_A" model += 0.8*B + 2.1*C - 90, "M_B"
  • LpMaximize eller LpMinimize
Introduktion till optimering i Python

Utdata från PuLP-modell

print(model)
ProductMix:
MAXIMIZE
480*B + 510*C + 0
SUBJECT TO
M_A: 1.5 B + 1.3 C <= 120

M_B: 0.8 B + 2.1 C <= 90

VARIABLES
B Continuous
C Continuous
Introduktion till optimering i Python

Lösa med PuLP

status = model.solve()
print(status)
Welcome to the CBC MILP Solver 
...
1
print(f"Profit = {value(model.objective):.2f}")
print(f"Tons of bottles = {B.varValue:.2f}, tons of cups = {C.varValue:.2f}")
Profit = 40137.44
Boxes of bottles = 63.98, boxes of cups = 18.48
Introduktion till optimering i Python

Hantera flera variabler och bivillkor

variables = LpVariable.dicts("Product", ['B', 'C'], lowBound=0)

ELLER

variables = LpVariable.dicts("Product", range(2), 0)
A = LpVariable.matrix('A', (range(2), range(2)), 0)
box_profit = {'B': 480, 'C': 510}
model += lpSum([box_profit[i] * variables[i] for i in ['B', 'C']]) 

model += 1.5*variables['B'] + 1.3*variables['C'] <= 120, "M_A"
model += 0.8*variables['B'] + 2.1*variables['C'] <= 90, "M_B"
Introduktion till optimering i Python

Nu kör vi en övning!

Introduktion till optimering i Python

Preparing Video For Download...