Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/delphi/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 查找坐标x和y列表的优化位置_Python_Numpy_Optimization_Mathematical Optimization_Nonlinear Optimization - Fatal编程技术网

Python 查找坐标x和y列表的优化位置

Python 查找坐标x和y列表的优化位置,python,numpy,optimization,mathematical-optimization,nonlinear-optimization,Python,Numpy,Optimization,Mathematical Optimization,Nonlinear Optimization,我是编程新手,尤其是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,

我是编程新手,尤其是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)

正如我在评论中所指出的,我认为这个问题很严重,因此不容易解决

这是一个带有某种基数约束的问题,也就是说,一般来说,很难/不可能使用连续优化(scipy.optimize中几乎所有内容都假设了)

此外,最小化最小距离并不是特别平滑的,这也是scipy中几乎所有内容都假设的。但重新表述是可能的(至少在支持约束的情况下是如此!)

如果没有基数约束(该问题离散性质的核心),它就会陷入问题,很容易在线性时间内解决。更一般。但这对给定的问题没有多大帮助

这是一个演示,可能不适合心脏病患者(取决于背景知识):

  • 基于

    • 将在给定无限时间内求解最优(ε近似)(忽略数值问题;fp数学)
    • 不打NP硬度;但在利用数据中的某种结构时可能会很好
    • 对于基于欧几里得距离(范数)的问题,感觉很自然
  • 用作建模工具

  • 用作解算器
    • 警告:这是一个概念验证/玩具解决方案(我们将在结果中看到)
    • MISOCP/是一个活跃的研究领域,但非商业专业解算器的数量很少!
      • 可能应该使用Bonmin或商业广告(Gurobi、CPLEX、Mosek和co.)来代替ECOS_BB
      • Pajarito看起来很有趣,但与python一起使用并不有趣;因此,考虑我的代码演示与演示解决方案!<李>
下面的代码将解决20个问题中的10个(前20个点;其中一个重复点被丢弃以获得更好的可视化效果!)

对于整个问题,它将失败(将返回非常好的近似值;但不是最佳值!)。我责备ECOS_BB(但同时非常感谢韩旺的代码!)。你的问题肯定会通过更好的选择很容易解决。但不要期望任何解算器都能为1000点解算:-)

代码: 绘图:

编辑

我将上述代码移植到julia,以便能够使用前面提到的解算器Pajarito。尽管过去我没有太多的julia编程,但现在它正在工作:

  • 用作建模工具
    • 上面基于cvxpy的代码几乎是1:1的映射
  • 使用3个开源解算器的组合:
    • 作为MISOCP/MICP解算器
      • 用作内部MIP解算器(Coin CBC通常更好;但由于Pajarito中可能存在错误,因此不适合我)
      • 用作内凸求解器
  • 重用了上面基于matplotlib的绘图代码;手动复制的结果值:-)
这种方法可以解决您的全部问题(我再次放弃了重复点),达到最佳状态

它输出一些数值不稳定警告,但声称结果是最优的!(Pajarito仍然是一个非常新的研究软件,我没有对众多选项进行调整;我们使用的开源解决方案与商业替代方案相比没有那么强大)

我对结果非常满意,很高兴我尝试了Julia/Convex.jl/Pajarito

代码: 可视化:

所有点中的select-23还有一个绘图:


请修复您的格式对我来说相当难。这更像是一个离散优化问题,scipy在这方面帮不了你。试着搜索聚类算法-
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
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]