请尝试这样做,它应该可以工作;)您需要安装pulp
。该脚本分为3部分:
pulp
from pulp import LpMaximize, LpProblem, LpStatus, lpSum, LpVariable
import numpy as np
import matplotlib.pyplot as plt
from numpy.random import rand
#%% PARAMETRIZE the PROBLEM
N = 10 # number of circles
X = 15 # size on X
Y = 15 # size on Y
Rmin = 1 # min radius
Rmax = 2 # max radius
#%% GENERATE RANDOM CIRCLES
cx = rand(N)*(X-2*Rmax) + Rmax
cy = rand(N)*(Y-2*Rmax) + Rmax
r = rand(N)*(Rmax-Rmin) + Rmin
plt.figure(1)
plt.clf()
for i in range(N): plt.gca().add_artist(plt.Circle((cx[i], cy[i]), r[i], alpha=0.7))
plt.axis('image')
plt.xlim(0,X)
plt.ylim(0,Y)
#%% GET SOLUTION
model = LpProblem(name="small-problem", sense=LpMaximize)
var = [LpVariable(name="x%u"%i, lowBound=0,upBound=1,cat='Integer') for i in range(N)]
# Add objective function to model
model += lpSum(var)
# Add constraints
for i in range(N):
for j in range(i+1,N):
dij = np.sqrt((cx[i]-cx[j])**2 + (cy[i]-cy[j])**2)
if dij < (r[i]+r[j]):
model += (var[i]+var[j]<=1,"intersec %u - %u"%(i,j))
# Solve it
status = model.solve()
print(f"status: {model.status}, {LpStatus[model.status]}")
print(f"objective: {model.objective.value()}")
for v in model.variables():
print(f"{v.name}: {v.value()}")
if v.value():
i = int(v.name[1])
plt.gca().add_artist(plt.Circle((cx[i], cy[i]), r[i],fc='none',ec='C1',lw=2))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句