求解欠定线性方程Ax + By = C,其中y受x约束

时间:2018-08-28 01:31:10

标签: python numpy scipy linear-programming quadratic-programming

我是优化新手,一直在努力求解线性方程Ax + By = C中的变量x和y,而y受x的解约束。 该问题的一个示例可以是:

A = np.random.rand(20,100)
B = np.random.rand(20,200)
C = np.random.rand(20)
     

解决xy,使Ax +By = C约束x为非负且-0.7*x0 < y0,y1 <0.7*x0, -0.7*x1 < y2,y3 <0.7*x1... ( -0.7x[i] < y[2i],y[2i+1]<0.7x[i] )

如果有人可以向我推荐一个可以解决此问题的python软件包,或者以某种方式将我的问题转换为可以通过Scipy.optimize之类的库直接解决的更传统的格式,我将不胜感激

2 个答案:

答案 0 :(得分:0)

这取决于您要解决的意思,您所描述的内容具有多种解决方案,并且它是多面体的内部。

如果您愿意将问题转换为

,则这是线性编程问题
-0.7x_0 <=y_0 <= 0.7x_0

假设不是,请考虑引入一个小的正数m来进行线性编程。

-0.7x_0 + m <=y_0 <= 0.7x_0 - m

然后可以使用scipy.optimize.linprog来求解线性程序。

如果您只对特定的解决方案感兴趣,只需将目标函数中的c设置为零即可。

编辑:

import numpy as np
from scipy.optimize import linprog

m_size = 20
bound = 0.7
x_size = 100
y_size = 2 * x_size
small_m = 0

A = np.random.rand(m_size, x_size)
B = np.random.rand(m_size, y_size)
C = np.random.rand(m_size)

A_eq = np.hstack((A, B))
b_eq = C

sub_block = np.array([-bound, -bound ])
sub_block.shape = (2,1)
block = np.kron(np.eye(x_size), sub_block)

upper_block = np.hstack((block, - np.eye(y_size)))
lower_block = np.hstack((block, np.eye(y_size)))

A_ub = np.vstack((upper_block, lower_block))
b_ub = -small_m * np.ones( 2 * y_size)

bounds = tuple([tuple([0, None]) for i in range(x_size)] + [tuple([None, None]) for i in range(y_size)])

c = [0 for i in range(x_size+y_size)]

res = linprog(c, A_ub = A_ub, b_ub = b_ub, A_eq = A_eq, b_eq = b_eq, bounds = bounds)

x_part = res.x[:x_size]
y_part = res.x[x_size:]

答案 1 :(得分:0)

我使用CVXPY解决了该问题:

import cvxpy as cp
import numpy as np
m = 20
n = 100
A = np.random.rand(m,n)
B = np.random.rand(m,n)
C = np.random.rand(m,n)
d = np.random.rand(m)

# construct the problem.

x = cp.Variable(n)
y = cp.Variable(n)
z = cp.Variable(n)
objective = cp.Minimize(cp.sum_squares(A*x + B*y + C*z -d))
constaints = [0 <= x, x <= 1, y <= 0.7*x, y >= -0.7*x, z <= 0.7*x, z >= -0.7*x]
prob = cp.Problem(objective, constraints)
result = prob.solve()