我尝试最小化向量x,y,但它们只是满足约束而没有最小化的工作。
例如:
输入init:x=[0.2,0.3,0.5]
(元素总和为1),反馈:res.x=[0.,0.3,0.5]
,它根本没有变化!
# -*- coding:utf8-*-
import random
import numpy as np
from scipy import optimize
import networkx as nx
import matplotlib.pyplot as plt
def Ud(x, X, Aj, G, p):
lost = G.node[Aj[-1]]["weight"]
Aj = Aj[:-1]
P = 1
sum = 0
for xi in x:
for Xi in X:
N = set(Aj).intersection(set(Xi))
# N=[random.randint(90,120) for _ in range(0,1)]
for n in N:
P *= (1 - p[n - 1])
sum += xi * P
P = 1
return -lost * sum
### objective function for defenders ###
def min_Ud(x, X, A, G, p):
min = float("inf")
for Aj in A:
temp_min = Ud(x, X, Aj, G, p)
if temp_min < min:
min = temp_min
return -min
### objective function for attackers ###
def Ua(a, X, A, G, p):
sum = 0
P = 1
for aj, Aj in a, A:
for Xi in X:
N = set(Aj[:-1]).intersection(set(Xi))
for n in N:
P *= (1 - p[n - 1])
sum += G.node[Aj[-1]]["weight"] * aj * P
P = 1
return sum
### fun for LP ###
def coreLP(X, A, G, p):
x0 = np.array([0.7, 0.2, 0.1])
a0 = np.array([0.5, 0.2, 0.3])
x_res = float("inf")
a_res = float("inf")
def c1(x):
return x.sum() - 1
cons = ({'type': 'eq', 'fun': c1})
Ud_star = optimize.minimize(min_Ud, x0, args=(X, A, G, p), constraints=cons, bounds=((0, 1), (0, 1), (0, 1)))
Ua_star = optimize.minimize(min_Ud, a0, args=(X, A, G, p), constraints=cons, bounds=((0, 1), (0, 1), (0, 1)))
print Ud_star
print Ua_star
return Ud_star.x, Ua_star.x