簡體   English   中英

找到坐標x和y列表的優化位置

[英]finding the optimized location for a list of coordinates x and y

我是編程新手,尤其是python,但我正在努力學習它,到目前為止我發現它非常迷人。

我有一個30個固定坐標x和y的列表。

x = np.array([[13,10,12,13,11,12,11,13,12,13,14,15,15,16,18,2,3,4,6,9,1,3,6,7,8,10,12,11,10,30]])
y = np.array([[12,11,10,9,8,7,6,6,7,8,11,12,13,15,14,18,12,11,10,13,15,16,18,17,16,15,14,13,12,3]])

我想找到一個優化的(集中式)位置,通過找到最小距離可以連接最多10個固定坐標。

我厭倦了使用優化算法,但我只能得到一個坐標列表的最佳位置(即我不能將位置約束到10個坐標)。

任何幫助,將不勝感激。

def objective(x):
    px = x[0]
    py = x[1]
    wdistance = sum(((px - wx)**2 + (py - wy)**2)**0.5)
    tdistance = (((px - tx)**2 + (py - ty)**2)**0.5)
    cost = wdistance * 2.5 + tdistance * 5 
    return cost

# initial estimate of the centralized location 
x0 = [10,10]

# boundary values for the centralized locations 
bnds = ((0,15), (0,15))
sol = minimize(objective, x0, bounds=bnds, method='SLSQP')

print(sol)

正如我的評論中所指出的,我認為這個問題是NP難的 ,因此解決它並不容易。

這是某種基數約束的問題,這意味着,通常很難/不可能使用連續優化(假設scipy.optimize中的幾乎所有內容)。

此外,最小化最小距離並不是特別平滑,幾乎所有內容都假設在scipy內。 但重新制定是可能的(至少在支持約束的情況下!)。

如果沒有基數約束(這個問題的離散性的核心),它就會崩潰成最小的封閉圓問題,很容易在線性時間內解決。 更一般的維基文章 但這對給定的問題沒有多大幫助。

這是一個演示,可能不適合膽小的人(取決於背景知識):

  • 基於混合整數二階錐編程

    • 在無限時間內解決最優性(epsilon-approximation)(忽略數值問題; fp-math)
    • 沒有超過NP硬度; 但在利用數據中的某種結構時可能會很好
    • 對於基於歐氏距離(標准)的問題感覺很自然
  • 使用cvxpy作為建模工具

  • 使用ECOS_BB作為求解器
    • 警告:這是一個概念驗證/玩具解算器(我們將在結果中看到)
    • MISOCP / MICP是一個活躍的研究領域,但非商業專業解決方案的數量很少!
      • 可能應該使用Pajarito ,可能使用Bonmin或商業廣告(Gurobi,CPLEX,Mosek和co。)而不是ECOS_BB。
      • Pajarito看起來很有趣, 基於julia ,(imho)與python一起使用並不好玩; 因此請考慮我的代碼演示解算器的演示!

以下代碼將解決20個問題中的10個問題(前20個問題;為了更好的可視化,丟棄了一個復制品!)

它會因完整問題而失敗(很可能會返回近似值;但不是最佳值!)。 我責備ECOS_BB(但同時非常感謝Han Wang的代碼!)。 通過更好的替代方案,您的問題肯定會很容易解決。 但是不要指望任何解決方案能夠做到1000分:-)。

碼:

import numpy as np
import cvxpy as cvx
import matplotlib.pyplot as plt
from scipy.spatial.distance import pdist

""" (Reduced) Data """
# removed a duplicate point (for less strange visualization)
x = np.array([13,10,12,13,11,12,11,13,13,14,15,15,16,18,2,3,4,6,9,1])#,3,6,7,8,10,12,11,10,30])
y = np.array([12,11,10,9,8,7,6,6,8,11,12,13,15,14,18,12,11,10,13,15])#,16,18,17,16,15,14,13,12,3])
N = x.shape[0]
M = 10

""" Mixed-integer Second-order cone problem """
c = cvx.Variable(2)                                # center position to optimize
d = cvx.Variable(N)              # helper-var: lower-bound on distance to center
d_prod = cvx.Variable(N) # helper-var: lower-bound on distance * binary/selected
b = cvx.Bool(N)                          # binary-variables used for >= M points

dists = pdist(np.vstack((x,y)).T)
U = np.amax(dists)    # upper distance-bound (not tight!) for bigM-linearization

helper_expr_c_0 = cvx.vec(c[0] - x)
helper_expr_c_1 = cvx.vec(c[1] - y)

helper_expr_norm = cvx.norm(cvx.hstack(helper_expr_c_0, helper_expr_c_1), axis=1)

constraints = []
constraints.append(cvx.sum_entries(b) >= M)           # M or more points covered
constraints.append(d >= helper_expr_norm)             # lower-bound of distances
constraints.append(d_prod <= U * b)                   # linearization of product
constraints.append(d_prod >= 0)                       # """
constraints.append(d_prod <= d)                       # """
constraints.append(d_prod >= d - U * (1-b))           # """

objective = cvx.Minimize(cvx.max_entries(d_prod))

problem = cvx.Problem(objective, constraints)
problem.solve(verbose=False)
print(problem.status)

# Visualization

center = np.array(c.value.flat)
tmp = np.array(np.round(b.value.T.flat), dtype=int)
selected_points = np.where(tmp == 1)[0]
non_selected_points = np.where(tmp == 0)[0]

ax = plt.subplot(aspect='equal')
ax.set_title('Optimal solution radius: {0:.2f}'.format(problem.value))
ax.scatter(x[non_selected_points], y[non_selected_points], c='blue', s=70, alpha=0.9)
ax.scatter(x[selected_points], y[selected_points], c='magenta', s=70, alpha=0.9)
ax.scatter(c[0].value, c[1].value, c='red', s=70, alpha=0.9)
circ = plt.Circle((center[0], center[1]), radius=problem.value, color='g', fill=True, alpha=0.1)
ax.add_patch(circ)
plt.tight_layout()
plt.show()

輸出:

optimal

情節:

在此輸入圖像描述

編輯

我將上面的代碼移植到julia,以便能夠使用上面提到的求解器Pajarito。 盡管過去對我來說沒有太多的julia編程,但它現在正在運行:

  • 使用Convex.jl作為建模工具
    • 從上面基於cvxpy的代碼幾乎1:1的映射!
  • 使用3個開源求解器的組合:
    • Pajarito作為MISOCP / MICP求解器
      • 使用GLPK作為內部MIP解算器(硬幣CBC通常要好得多;但由於Pajarito中可能存在錯誤而無法為我工作)
      • 使用ECOS作為內部凸面解算器
  • 重用上面基於matplotlib的繪圖代碼; 手寫的結果值:-)

這種方法正在解決您的完整問題(我再次刪除了重復點)以達到最佳狀態!

它輸出一些數值不穩定警告,但聲稱結果是最佳的! (Pajarito仍然是相當新的研究軟件,我沒有調整眾多選項;我們使用的開源解算器與商業替代品相比並不那么強大)

我對結果非常滿意,我很高興我試試了Julia / Convex.jl / Pajarito!

碼:

using Convex, Pajarito, ECOS, GLPKMathProgInterface

# DATA
x = [13 10 12 13 11 12 11 13 13 14 15 15 16 18 2 3 4 6 9 1 3 6 7 8 10 12 11 10 30]
y = [12 11 10 9 8 7 6 6 8 11 12 13 15 14 18 12 11 10 13 15 16 18 17 16 15 14 13 12 3]
N = size(x)[2]
M = 10

# MISOCP
c = Variable(2)
d = Variable(N)
d_prod = Variable(N)
b = Variable(N, :Bin)

U = 100  # TODO

# Objective
problem = minimize(maximum(d_prod))

# Constraints
problem.constraints += sum(b) >= M
problem.constraints += d_prod <= U*b
problem.constraints += d_prod >= 0
problem.constraints += d_prod <= d
problem.constraints += d_prod >= d - U * (1-b)
for i = 1:N
    problem.constraints += d[i] >= norm([c[1] - x[i], c[2] - y[i]])  # ugly
end

# Solve
mip_solver_drives = false
log_level = 2
rel_gap = 1e-8
mip_solver = GLPKSolverMIP()
cont_solver = ECOSSolver(verbose=false)
solver = PajaritoSolver(
    mip_solver_drives=mip_solver_drives,
    log_level=log_level,
    rel_gap=rel_gap,
    mip_solver=mip_solver,
    cont_solver=cont_solver,
    init_exp=true,
)
# option taken from https://github.com/JuliaOpt/Pajarito.jl/blob/master/examples/gatesizing.jl
# not necessarily optimal

solve!(problem, solver)

# Print out results
println(problem.status)
println(problem.optval)
println(b.value)
println(c.value)

輸出:

Problem dimensions:
       variables |       120
     constraints |       263
   nonzeros in A |       466

Cones summary:
Cone             | Count     | Min dim.  | Max dim.
    Second order |        29 |         3 |         3

Variable types:
      continuous |        91
          binary |        29

Transforming data...               1.10s

Creating conic subproblem...       0.52s

Building MIP model...              2.35s

Solving conic relaxation...        1.38s

Starting iterative algorithm
    0 |           +Inf |  +3.174473e-11 |         Inf |   6.434e+00
Warning: numerical instability (primal simplex, phase I)

Iter. | Best feasible  | Best bound     | Rel. gap    | Time (s)
    1 |  +2.713537e+00 |  +2.648653e+00 |   2.391e-02 |   1.192e+01
Warning: numerical instability (primal simplex, phase I)
Warning: numerical instability (primal simplex, phase I)
Warning: numerical instability (dual simplex, phase II)
... some more ...
    2 |  +2.713537e+00 |  +2.713537e+00 |   5.134e-12 |   1.341e+01

Iterative algorithm summary:
 - Status               =        Optimal
 - Best feasible        =  +2.713537e+00
 - Best bound           =  +2.713537e+00
 - Relative opt. gap    =      5.134e-12
 - Total time (s)       =       1.34e+01

Outer-approximation cuts added:
Cone             | Relax.    | Violated  | Nonviol.
    Second order |        58 |        32 |        24

0 numerically unstable cone duals encountered

Distance to feasibility (negative indicates strict feasibility):
Cone             | Variable  | Constraint
          Linear |        NA |  5.26e-13
    Second order |        NA |  2.20e-11

Distance to integrality of integer/binary variables:
          binary |  0.00e+00

Optimal
2.7135366682753825
[1.0; 1.0; 1.0; 1.0; 0.0; 0.0; 0.0; 0.0; 0.0; 1.0; 1.0; 1.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 1.0; 1.0; 1.0; 0.0]
[12.625; 11.6875]

可視化:

在此輸入圖像描述

在所有點中還有一個選擇-23的情節:

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM