Cost Optimization for feed management.
importing pulp modeller functionality Simplified Cost Model Python Formulation for the PuLP Modeller
from pulp import *
import re
import numpy as np
def get_total_cost(name1, dm, cp, tdn, dm_req, cp_req, tdn_req, price, qty):
# problem defining
# Lp minimize for minimizing function
print("Ingredients:", name1)
dm = {k: v for k, v in zip(name1, dm)}
cp = {k: v for k, v in zip(name1, cp)}
tdn = {k: v for k, v in zip(name1, tdn)}
pri = {k: v for k, v in zip(name1, price)}
qty1 = {k: v for k, v in zip(name1, qty)}
prob = LpProblem("The Cost Model", LpMinimize)
# minimize function variables
ingredients_vars = LpVariable.dicts("", (i for i in name1), lowBound=0, cat='Continuous')
# Minimizing Function
prob += (
lpSum([pri[i] * ingredients_vars[i] for i in name1]), "Total cost of Ingredients",
)
# Constraints:
print("const1", [qty1[i] * dm[i] / 100 for i in name1])
prob += (lpSum([qty1[i] * dm[i] * ingredients_vars[i] for i in name1]) / 100 >= dm_req, "DM Check",)
print("const2", [qty1[i] * dm[i] * cp[i] / 10000 for i in name1])
prob += (
lpSum([qty1[i] * dm[i] * cp[i] * ingredients_vars[i] for i in name1]) / 100 >= cp_req,
"CP Check",)
print("const3", [qty1[i] * dm[i] * tdn[i] / 10000 for i in name1])
prob += (
lpSum([qty1[i] * dm[i] * tdn[i] * ingredients_vars[i] for i in name1]) / 100 >= tdn_req,
"TDN Check",)
# prob.writeLP('CostModel.lp')
print(prob)
solver1 = getSolver('GUROBI')
prob.solve(GUROBI())
# Status of solution:
print("Status:", LpStatus[prob.status])
final_ingredients = []
for v in prob.variables():
if v.varValue == None:
return "No Solution"
if v.varValue > 0:
r_name = v.name
ingredient_name = str(re.sub('_', ' ', r_name)).strip()
quantity = np.round(v.varValue, 2)
final_ingredients.append({"ingredientName": ingredient_name,
"quantity": quantity})
# print((ingredients_vars))
# The optimised objective function value is printed to the screen
# print("Total Cost of Ingredients = ", value(prob.objective))
total_cost = np.round(value(prob.objective), 2)
return {"finalIngredients": final_ingredients,
"totalCost": total_cost}
OUTPUT : {'finalIngredients': [{'ingredientName': 'BREWERS GRAINS wet', 'quantity': 114.37}], 'totalCost': 130.38}
function only giving values for a single ingredient how to change or what to change the code so that it returns multiple ingredients?
also can I assign different upperbounds to each individual ingredient within the LpVariable.dicts()