python,超出了迭代限制

时间:2018-11-12 17:30:56

标签: python-3.x

这是一个简单的问题,但是我尝试了很多次,却找不到代码中的错误。 假设有一股力量将群众推向目标。使用优化器找到最佳位置,速度,力。 约束1用于描述位置关系,约束2用于描述速度关系。 代码如下:

import numpy as np
from scipy.optimize import minimize
import matplotlib.pyplot as plt

t=0.1
m=10
g=9.8
s_goal=3
n=80
e=0.01

A = np.zeros((n,n))
for i in range (n):
    A[0,i]=0
    A[i,i-1]=1
B = np.zeros((n,n))
for i in range (n):
    B[0,i]=0
    B[i,i-1]=t
C = np.zeros((n,1))
for i in range (n):
    C[i,0]=t*g

x0=np.zeros((n,3))

def constraint1(x):
    x=x.reshape(n,3)
    s=x[:,0].reshape(n,1)
    v=x[:,1].reshape(n,1)
    a=s-np.dot(A,s)-np.dot(B,v)
    a=a.reshape(n,)
    return a
def constraint2(x):
    x=x.reshape(n,3)
    F=x[:,2].reshape(n,1)
    v=x[:,1].reshape(n,1)
    b=v-np.dot(A,v)-(t/m)*np.dot(A,F)+C
    b=b.reshape(n,)
    return b
def objective(x):
    x=x.reshape(n,3)
    s=x[:,0].reshape(n,1)
    v=x[:,1].reshape(n,1)
    #F=x[:,2].reshape(n,1)
    sum_up=0  
    for i in range (n):
        sum_up = sum_up + (s[i,0]-s_goal)**2 + e*(v[i,0])**2
        #print(sum_up )
    return sum_up
# optimize
con1 = {'type':'eq','fun':constraint1}
con2 = {'type':'eq','fun':constraint2}
cons = ([con1,con2])
solution = minimize(objective,x0,method='SLSQP',constraints=cons)
print(solution)
#print (np.shape(solution.x))
m=(solution.x).reshape(n,3)

position=m[:,0]
velocity=m[:,1]
Force=m[:,2]
#plot
tn=np.linspace(0,n*t,n)
plt.plot(tn,position)
plt.ylabel('position')
plt.xlabel('time')
plt.legend(loc='best')
plt.show()


plt.plot(tn,velocity)
plt.ylabel('velocity')
plt.xlabel('time')
plt.legend(loc='best')
plt.show()


plt.plot(tn,Force)
plt.ylabel('Force')
plt.xlabel('time')
plt.legend(loc='best')
plt.show()

我认为限制很明确,但结果是:      消息:“超出迭代限制”         nfev:24442          尼特:101         涅夫:101       状态:9      成功:错误

能否请你告诉我我在哪里做错了。非常感谢!!!

0 个答案:

没有答案