Solve linear programming python using Pulp

℡╲_俬逩灬. 提交于 2020-12-07 14:55:29

问题


Hi, this is my code and i need help. This is a simple version of another code, the real one I am using 50 in origin and 70 in destination.. there are two things that i do not know how to do:

first thing that i do not know how to do: I would like to limit the number of orign used in the optimization, in this case I would like to only use 3 "origin", but all destination must be used

second, i would like to print the distance next to each combination I used after the solve(), the distance i created usind rnd.randint

tks for the atention =)

from pulp import *
import pandas as pd 
from random import randint
import numpy as np

rnd = np.random
rnd.seed(1)
seed = 1 
origin = ["1","2","3","4","5"]

destination = ["a","b","c","d","e","f","g"]

demand = {"a":1,"b":1,"c":1,"d":1,"e":1,"f":1,"g":1}

distance = {"1":{"a":rnd.randint(1,50),"b":rnd.randint(1,50),"c":rnd.randint(1,50),"d":rnd.randint(1,50),"e":rnd.randint(1,50),"f":rnd.randint(1,50),"g":rnd.randint(1,50)},
"2":{"a":rnd.randint(1,50),"b":rnd.randint(1,50),"c":rnd.randint(1,50),"d":rnd.randint(1,50),"e":rnd.randint(1,50),"f":rnd.randint(1,50),"g":rnd.randint(1,50)},
"3":{"a":rnd.randint(1,50),"b":rnd.randint(1,50),"c":rnd.randint(1,50),"d":rnd.randint(1,50),"e":rnd.randint(1,50),"f":rnd.randint(1,50),"g":rnd.randint(1,50)},
"4":{"a":rnd.randint(1,50),"b":rnd.randint(1,50),"c":rnd.randint(1,50),"d":rnd.randint(1,50),"e":rnd.randint(1,50),"f":rnd.randint(1,50),"g":rnd.randint(1,50)},
"5":{"a":rnd.randint(1,50),"b":rnd.randint(1,50),"c":rnd.randint(1,50),"d":rnd.randint(1,50),"e":rnd.randint(1,50),"f":rnd.randint(1,50),"g":rnd.randint(1,50)}

}

prob = LpProblem("Exercise", LpMinimize)



Routes = [(i, j) for i in origin for j in destination if j in distance[i]]

qual = LpVariable.dicts("Qual Centroide é atendedido por qual Postp",Routes,0)

prob += lpSum(qual[(i,j)]*distance[i][j] for (i,j) in Routes)


for j in destination:
     
    prob += lpSum(qual[(i,j)] for i in origin if (i,j) in Routes) == demand[j]




prob.solve()
print("Status: ", LpStatus[prob.status])
list1 = []
count = 0
for v in prob.variables():
    if v.varValue > 0:
        count += 1
        list1.append(v.name)
        print(v.name, "=", v.varValue)
new_list = []

for elemento in list1:
        new_list.append((re.findall('\d+', elemento)))

#print(new_list)

flattened = [item for sublist in new_list for item in sublist]
#print(flattened)

flattened = list(dict.fromkeys(flattened))
#print(flattened) 
print("\nNumber of origin used = ",len(flattened)-1)

print("Number of destination used (i need to use them all) = ", count)

来源:https://stackoverflow.com/questions/64869116/solve-linear-programming-python-using-pulp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!