本文整理匯總了Python中scipy.optimize.linprog方法的典型用法代碼示例。如果您正苦於以下問題:Python optimize.linprog方法的具體用法?Python optimize.linprog怎麽用?Python optimize.linprog使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類scipy.optimize
的用法示例。
在下文中一共展示了optimize.linprog方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _assert_success
# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import linprog [as 別名]
def _assert_success(res, desired_fun=None, desired_x=None,
rtol=1e-8, atol=1e-8):
# res: linprog result object
# desired_fun: desired objective function value or None
# desired_x: desired solution or None
if not res.success:
msg = "linprog status {0}, message: {1}".format(res.status,
res.message)
raise AssertionError(msg)
assert_equal(res.status, 0)
if desired_fun is not None:
assert_allclose(res.fun, desired_fun,
err_msg="converged to an unexpected objective value",
rtol=rtol, atol=atol)
if desired_x is not None:
assert_allclose(res.x, desired_x,
err_msg="converged to an unexpected solution",
rtol=rtol, atol=atol)
示例2: test_linprog_cyclic_bland_bug_8561
# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import linprog [as 別名]
def test_linprog_cyclic_bland_bug_8561(self):
# Test that pivot row is chosen correctly when using Bland's rule
c = np.array([7, 0, -4, 1.5, 1.5])
A_ub = np.array([
[4, 5.5, 1.5, 1.0, -3.5],
[1, -2.5, -2, 2.5, 0.5],
[3, -0.5, 4, -12.5, -7],
[-1, 4.5, 2, -3.5, -2],
[5.5, 2, -4.5, -1, 9.5]])
b_ub = np.array([0, 0, 0, 0, 1])
if self.method == "simplex":
res = linprog(c, A_ub=A_ub, b_ub=b_ub,
options=dict(maxiter=100, bland=True),
method=self.method)
else:
res = linprog(c, A_ub=A_ub, b_ub=b_ub, options=dict(maxiter=100),
method=self.method)
_assert_success(res, desired_x=[0, 0, 19, 16/3, 29/3])
示例3: wasserstein_distance
# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import linprog [as 別名]
def wasserstein_distance(p, q, D):
"""Wasserstein-distance
p.shape=[m], q.shape=[n], D.shape=[m, n]
p.sum()=1, q.sum()=1, p∈[0,1], q∈[0,1]
"""
A_eq = []
for i in range(len(p)):
A = np.zeros_like(D)
A[i, :] = 1
A_eq.append(A.reshape(-1))
for i in range(len(q)):
A = np.zeros_like(D)
A[:, i] = 1
A_eq.append(A.reshape(-1))
A_eq = np.array(A_eq)
b_eq = np.concatenate([p, q])
D = D.reshape(-1)
result = linprog(D, A_eq=A_eq[:-1], b_eq=b_eq[:-1])
return result.fun
示例4: test_negative_variable
# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import linprog [as 別名]
def test_negative_variable(self):
# Test linprog with a problem with one unbounded variable and
# another with a negative lower bound.
c = np.array([-1, 4]) * -1 # maximize
A_ub = np.array([[-3, 1],
[1, 2]], dtype=np.float64)
A_ub_orig = A_ub.copy()
b_ub = [6, 4]
x0_bounds = (-np.inf, np.inf)
x1_bounds = (-3, np.inf)
res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=(x0_bounds, x1_bounds),
method=self.method, options=self.options)
assert_equal(A_ub, A_ub_orig) # user input not overwritten
_assert_success(res, desired_fun=-80 / 7, desired_x=[-8 / 7, 18 / 7])
示例5: test_network_flow
# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import linprog [as 別名]
def test_network_flow(self):
# A network flow problem with supply and demand at nodes
# and with costs along directed edges.
# https://www.princeton.edu/~rvdb/542/lectures/lec10.pdf
c = [2, 4, 9, 11, 4, 3, 8, 7, 0, 15, 16, 18]
n, p = -1, 1
A_eq = [
[n, n, p, 0, p, 0, 0, 0, 0, p, 0, 0],
[p, 0, 0, p, 0, p, 0, 0, 0, 0, 0, 0],
[0, 0, n, n, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, p, p, 0, 0, p, 0],
[0, 0, 0, 0, n, n, n, 0, p, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, n, n, 0, 0, p],
[0, 0, 0, 0, 0, 0, 0, 0, 0, n, n, n]]
b_eq = [0, 19, -16, 33, 0, 0, -36]
res = linprog(c=c, A_eq=A_eq, b_eq=b_eq,
method=self.method, options=self.options)
_assert_success(res, desired_fun=755, atol=1e-6, rtol=1e-7)
示例6: test_enzo_example
# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import linprog [as 別名]
def test_enzo_example(self):
# http://projects.scipy.org/scipy/attachment/ticket/1252/lp2.py
#
# Translated from Octave code at:
# http://www.ecs.shimane-u.ac.jp/~kyoshida/lpeng.htm
# and placed under MIT licence by Enzo Michelangeli
# with permission explicitly granted by the original author,
# Prof. Kazunobu Yoshida
c = [4, 8, 3, 0, 0, 0]
A_eq = [
[2, 5, 3, -1, 0, 0],
[3, 2.5, 8, 0, -1, 0],
[8, 10, 4, 0, 0, -1]]
b_eq = [185, 155, 600]
res = linprog(c=c, A_eq=A_eq, b_eq=b_eq,
method=self.method, options=self.options)
_assert_success(res, desired_fun=317.5,
desired_x=[66.25, 0, 17.5, 0, 183.75, 0],
atol=6e-6, rtol=1e-7)
示例7: test_enzo_example_b
# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import linprog [as 別名]
def test_enzo_example_b(self):
# rescued from https://github.com/scipy/scipy/pull/218
c = [2.8, 6.3, 10.8, -2.8, -6.3, -10.8]
A_eq = [[-1, -1, -1, 0, 0, 0],
[0, 0, 0, 1, 1, 1],
[1, 0, 0, 1, 0, 0],
[0, 1, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 1]]
b_eq = [-0.5, 0.4, 0.3, 0.3, 0.3]
if self.method == "simplex":
# Including the callback here ensures the solution can be
# calculated correctly.
res = linprog(c=c, A_eq=A_eq, b_eq=b_eq,
method=self.method, options=self.options,
callback=lambda x, **kwargs: None)
else:
with suppress_warnings() as sup:
sup.filter(OptimizeWarning, "A_eq does not appear...")
res = linprog(c=c, A_eq=A_eq, b_eq=b_eq,
method=self.method, options=self.options)
_assert_success(res, desired_fun=-1.77,
desired_x=[0.3, 0.2, 0.0, 0.0, 0.1, 0.3])
示例8: test_bug_6690
# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import linprog [as 別名]
def test_bug_6690(self):
# https://github.com/scipy/scipy/issues/6690
A_eq = np.array([[0., 0., 0., 0.93, 0., 0.65, 0., 0., 0.83, 0.]])
b_eq = np.array([0.9626])
A_ub = np.array([[0., 0., 0., 1.18, 0., 0., 0., -0.2, 0.,
-0.22],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0.43, 0., 0., 0., 0., 0., 0.],
[0., -1.22, -0.25, 0., 0., 0., -2.06, 0., 0.,
1.37],
[0., 0., 0., 0., 0., 0., 0., -0.25, 0., 0.]])
b_ub = np.array([0.615, 0., 0.172, -0.869, -0.022])
bounds = np.array(
[[-0.84, -0.97, 0.34, 0.4, -0.33, -0.74, 0.47, 0.09, -1.45, -0.73],
[0.37, 0.02, 2.86, 0.86, 1.18, 0.5, 1.76, 0.17, 0.32, -0.15]]).T
c = np.array([-1.64, 0.7, 1.8, -1.06, -1.16,
0.26, 2.13, 1.53, 0.66, 0.28])
with suppress_warnings() as sup:
sup.filter(RuntimeWarning, "scipy.linalg.solve\nIll...")
sup.filter(OptimizeWarning, "Solving system with option...")
sol = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq,
bounds=bounds, method=self.method,
options=self.options)
_assert_success(sol, desired_fun=-1.191, rtol=1e-6)
示例9: test_zero_column_2
# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import linprog [as 別名]
def test_zero_column_2(self):
# detected in presolve?
np.random.seed(0)
m, n = 2, 4
c = np.random.rand(n)
c[1] = -1
A_eq = np.random.rand(m, n)
A_eq[:, 1] = 0
b_eq = np.random.rand(m)
A_ub = np.random.rand(m, n)
A_ub[:, 1] = 0
b_ub = np.random.rand(m)
res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds=(None, None),
method=self.method, options=self.options)
_assert_unbounded(res)
assert_equal(res.nit, 0)
示例10: linear_program_ineq
# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import linprog [as 別名]
def linear_program_ineq(c, A, b):
c = c.reshape((c.size,))
b = b.reshape((b.size,))
# make unbounded bounds
bounds = []
for i in range(c.size):
bounds.append((None, None))
A_ub, b_ub = -A, -b
res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, options={"disp": False}, method='simplex')
if res.success:
return res.x.reshape((c.size, 1))
else:
np.savez('bad_scipy_lp_ineq_{:010d}'.format(np.random.randint(int(1e9))),
c=c, A=A, b=b, res=res)
raise Exception('Scipy did not solve the LP. Blame Scipy.')
示例11: solve_linprog
# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import linprog [as 別名]
def solve_linprog(self, nu):
n_hs = len(self.hs)
n_constraints = len(self.constraints.index)
if self.last_linprog_n_hs == n_hs:
return self.last_linprog_result
c = np.concatenate((self.errors, [self.B]))
A_ub = np.concatenate((self.gammas - self.eps, -np.ones((n_constraints, 1))), axis=1)
b_ub = np.zeros(n_constraints)
A_eq = np.concatenate((np.ones((1, n_hs)), np.zeros((1, 1))), axis=1)
b_eq = np.ones(1)
result = opt.linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, method='simplex')
Q = pd.Series(result.x[:-1], self.hs.index)
dual_c = np.concatenate((b_ub, -b_eq))
dual_A_ub = np.concatenate((-A_ub.transpose(), A_eq.transpose()), axis=1)
dual_b_ub = c
dual_bounds = [(None, None) if i == n_constraints else (0, None) for i in range(n_constraints + 1)] # noqa: E501
result_dual = opt.linprog(dual_c,
A_ub=dual_A_ub,
b_ub=dual_b_ub,
bounds=dual_bounds,
method='simplex')
lambda_vec = pd.Series(result_dual.x[:-1], self.constraints.index)
self.last_linprog_n_hs = n_hs
self.last_linprog_result = (Q, lambda_vec, self.eval_gap(Q, lambda_vec, nu))
return self.last_linprog_result
示例12: label_prop
# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import linprog [as 別名]
def label_prop(C, nt, Dct, lp="linear"):
#Inputs:
# C : Number of share classes between src and tar
# nt : Number of target domain samples
# Dct : All d_ct in matrix form, nt * C
# lp : Type of linear programming: linear (default) | binary
#Outputs:
# Mcj : all M_ct in matrix form, m * C
intcon = C * nt
Aeq = np.zeros([nt, intcon])
Beq = np.ones([nt, 1])
for i in range(nt):
Aeq[i, i*C:(i+1)*C] = 1;
D_vec = np.reshape(Dct, (1, intcon))
CC = np.asarray(D_vec, dtype=np.double)
A = np.array([])
B = -1 * np.ones([C, 1])
for i in range(C):
all_zeros = np.zeros([1, intcon])
for j in range(i, C * nt, C):
all_zeros[0][j] = -1
if i == 0:
A = all_zeros
else:
A = np.vstack((A, all_zeros))
if lp == "binary":
print("not implemented yet!")
else:
res = linprog(CC,A,B,Aeq,Beq, bounds=tuple((0, 1) for _ in range(intcon)))
Mct_vec = res.get("x")[0:C*nt]
Mcj = Mct_vec.reshape((C,nt), order="F").T
return Mcj
示例13: _get_plan_no_prioties
# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import linprog [as 別名]
def _get_plan_no_prioties(self, demand_lst, outcome, gold_demand, exp_demand, convertion_dr, probs_matrix, convertion_matrix, convertion_outc_matrix, cost_lst, convertion_cost_lst):
"""
To solve linear programming problem without prioties.
Args:
demand_lst: list of materials demand. Should include all items (zero if not required).
Returns:
strategy: list of required clear times for each stage.
fun: estimated total cost.
"""
if convertion_dr != 0.18:
convertion_outc_matrix = (convertion_outc_matrix - convertion_matrix)/0.18*convertion_dr+convertion_matrix
A_ub = (np.vstack([probs_matrix, convertion_outc_matrix])
if outcome else np.vstack([probs_matrix, convertion_matrix])).T
cost = (np.hstack([cost_lst, convertion_cost_lst]))
assert np.any(cost_lst>=0)
excp_factor = 1.0
dual_factor = 1.0
while excp_factor>1e-7:
solution = linprog(c=cost,
A_ub=-A_ub,
b_ub=-np.array(demand_lst)*excp_factor,
method='interior-point')
if solution.status != 4:
break
excp_factor /= 10.0
while dual_factor>1e-7:
dual_solution = linprog(c=-np.array(demand_lst)*excp_factor*dual_factor,
A_ub=A_ub.T,
b_ub=cost,
method='interior-point')
if solution.status != 4:
break
dual_factor /= 10.0
return solution, dual_solution, excp_factor
示例14: find_feasible_point
# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import linprog [as 別名]
def find_feasible_point(halfspaces):
"""
Use linear programming to find a point inside the halfspaces (needed to
define it).
Code taken from scipy documentation:
https://docs.scipy.org/doc/scipy-0.19.0/reference/generated/scipy.spatial.HalfspaceIntersection.html
Parameters
----------
halfspaces: a matrix representation of halfspaces
Returns:
--------
numpy array
"""
norm_vector = np.reshape(
np.linalg.norm(halfspaces[:, :-1], axis=1), (halfspaces.shape[0], 1)
)
c = np.zeros((halfspaces.shape[1],))
c[-1] = -1
A = np.hstack((halfspaces[:, :-1], norm_vector))
b = -halfspaces[:, -1:]
res = linprog(c, A_ub=A, b_ub=b)
return res.x[:-1]
示例15: apply
# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import linprog [as 別名]
def apply(self, resp_matrix, orbit, weights=None):
m, n = np.shape(resp_matrix)
f = np.zeros(n + 1)
f[-1] = 1
Ane = np.vstack((np.hstack((resp_matrix, -np.ones((m, 1)))), np.hstack((-resp_matrix, -np.ones((m, 1))))))
bne = np.vstack((+orbit, -orbit))
res = linprog(f, A_ub=Ane, b_ub=bne)
x = res["x"][:-1]
return x