【发布时间】:2017-08-01 11:30:36
【问题描述】:
所以我的约束函数没有被正确地施加它会出现。
import numpy as np
import scipy.integrate as integrate
import scipy.interpolate as interpolate
import pylab as plt
import scipy.optimize as op
import math
def make_cons(parameter_guess):
cons=()
for i in range(0,len(parameter_guess)):
constraint = {'type': 'ineq', 'fun': lambda parameter_guess: -math.fabs(parameter_guess[i]) + 1 }
cons +=(constraint,)
# print cons
#cons=({'type': 'ineq', 'fun': lambda parameter_guess: -parameter_guess+ 1 })
return cons
def problem(N,IC):
t=np.linspace(0,5,1000)
tt=np.linspace(0,5+.5,N+1)
parameter_guess = .5*np.ones(len(tt))
res=op.minimize(cost_function, parameter_guess, args=(t,tt,IC), method='SLSQP',constraints=make_cons(parameter_guess))
true_param= res.x
print res.message
print true_param
generate_state_and_control(true_param,t,tt,IC)
def cost_function(parameter_guess,t,tt,IC):
#print parameter_guess
f_p = interpolate.interp1d(tt, parameter_guess)
sol = integrate.odeint(f, [IC[0],IC[1],0], t, args=(f_p,))
cost_sol = sol[:,2]
cost=cost_sol[-1]
print 'cost ' + str(cost)
return cost
def f(y,t,f_p):
dydt=[-y[0] +2*y[1] , y[0] -.2*y[1] + f_p(t), .5*(y[0]**2 + 2*y[1]**2 + 3*f_p(t)**2)]
return dydt
def generate_state_and_control(parameters,t,tt,IC):
f_p = interpolate.interp1d(tt, parameters)
sol = integrate.odeint(f, [IC[0],IC[1],0], t, args=(f_p,))
control=f_p(t)
position=sol[:,0]
velocity=sol[:,1]
cost_sol = sol[:,2]
cost=cost_sol[-1]
print 'cost ' + str(cost)
print parameters
plt.plot(tt,parameters,label='Control')
plt.xlabel('time')
plt.ylabel('u')
plt.title('Control')
plt.show()
plt.clf()
plt.plot(position,velocity,label='Velocity vs Position')
plt.xlabel('Position')
plt.ylabel('Velocity')
plt.title('Velocity vs Position')
plt.show()
problem(15,[3,6])
我在 make_cons 函数中设置约束。我只是说每个变量的绝对值必须小于 1(即 |p_i| =1 形式)
但是,如果我跑步。
problem(15,[3,6])
[ -6.91310983 -11.84886554 -8.39257891 -5.89026938 -3.94611243
-2.83438566 -1.84550722 -1.18591646 -0.72311117 -0.5668469
0.10564927 -0.02283327 -0.0312163 -0.08288569 0.34830762 0.5 ]
我们显然可以看到并非所有这些变量都在 -1 和 1 之间。
有人看到我在这里制作的小错误吗?
【问题讨论】:
-
Hey Cleb,我认为这不是问题,优化器会将参数传递给约束。我试图将其更改为以下 def make_cons(parameter_guess): cons=() for i in range(0,len(parameter_guess)): constraint = {'type': 'ineq', 'fun': lambda x: - math.fabs(x[i]) + 1 } cons +=(constraint,) # print cons #cons=({'type': 'ineq', 'fun': lambda parameter_guess: -parameter_guess+ 1 }) return cons 但是我得到了同样的答案。
标签: python optimization scipy