Programmazione lineare

Introduzione all'ottimizzazione in Python

Jasmin Ludolf

Content Developer

Programmazione lineare

  • Funzione obiettivo e vincoli sono lineari

  • Diverso da vincoli lineari: mix di elementi lineari o non lineari

Introduzione all'ottimizzazione in Python

Mix di prodotti

 

Tipo N. Bottiglie (h/scatola) Bicchieri (h/scatola)
$M_A$ 4 1.5 1.3
$M_B$ 3 0.8 2.1

 

  • Ogni macchina lavora 30 ore/settimana

 

  • Domanda: bottiglie per bibite, bicchieri per yogurt
Introduzione all'ottimizzazione in Python

Massimizza il profitto

  • Profitto per scatola
B ($/scatola) C ($/scatola)
480 510

 

  • Funzione obiettivo: $480B + 510C$
  • Vincoli
    • Macchina A: $1.5B+1.3C\leq 4 \times 30$
    • Macchina B: $0.8B+ 2.1C \leq 3\times 30$
    • Non negatività: $B, C \geq 0$
Introduzione all'ottimizzazione in Python

Uso di 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 o LpMinimize
Introduzione all'ottimizzazione in Python

Output del modello PuLP

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
Introduzione all'ottimizzazione in Python

Risoluzione con 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
Introduzione all'ottimizzazione in Python

Gestire più variabili e vincoli

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

OR

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"
Introduzione all'ottimizzazione in Python

Ayo berlatih!

Introduzione all'ottimizzazione in Python

Preparing Video For Download...