我想使用算法COBYLA最大化两个对象之间的距离。我有一个每个对象的x和y值的二维数组。
可能变化的变量是a1,a2,a3,b1,b2,b3。我希望COBYLA计算这些变量的哪些值可以最大化两个对象之间的距离。
有两个限制因素:
a1,a2,a3 >= 1.5
b1,b2,b3 <= 3.0
我已经编写了大部分代码,但我不明白如何调用此函数。我希望我的代码能够进行2000次迭代,以确保变量的最佳值。这就是我到目前为止所拥有的:
import sys
import numpy as np
from scipy import optimize
from scipy.optimize import _cobyla
obj1_data = np.loadtxt('obj1_data.txt')
obj2_data = np.loadtxt('obj2_data.txt')
x_obj1 = obj1_data[:,0] #array of x-values for obj1
y_obj1 = obj1_data[:,1] #array of y-values for obj1
y_obj2 = obj2_data[:,0] #array of x-values for obj2
x_obj2 = obj2_data[:,1] #array of y-values for obj2
def cobyla(a1,a2,a3,b1,b2,b3):
#~~~ OBJECT 1 ~~~#
#OBJECT 1 RANGE (a1 to b1)
#np.where returns elements, either x or y, depending on condition
#find index of elements where (from a to b)
xindex1 = np.where(np.logical_and(x_obj1 >= a1, x_obj1 <= b1))
#make an x array that corresponds to x index
obj1_xarray1 = x_obj1[xindex1]
#find y values corresponding to x range
obj1_yarray1 = y_obj1[xindex1]
#integrate values in yarray to give summed value of x-values in array
obj1_int1 = np.trapz(obj1_yarray1,x=obj1_xarray1)
#OBJECT 1 RANGE (a2 to b2)
xindex2 = np.where(np.logical_and(x_obj1 >= a2, x_obj1 <= b2))
obj1_xarray2 = x_obj1[xindex2]
obj1_yarray2 = y_obj1[xindex2]
obj1_int2 = np.trapz(obj1_yarray2,x=obj1_xarray2)
#OBJECT 1 RANGE (a3 to b3)
xindex3 = np.where(np.logical_and(x_obj1 >= a2, x_obj1 <= b2))
obj1_xarray3 = x_obj1[xindex3]
obj1_yarray3 = y_obj1[xindex3]
obj1_int3 = np.trapz(obj1_yarray3,x=obj1_xarray3)
#~~~ OBJECT 2 ~~~#
#OBJECT 1 RANGE (a1 to b1)
#np.where returns elements, either x or y, depending on condition
#find index of elements where (from a to b)
xindex4 = np.where(np.logical_and(x_obj2 >= a1, x_obj2 <= b1))
#make an earth x array that corresponds to x index
obj2_xarray1 = x_obj2[xindex4]
#find y values corresponding to x range
obj2_yarray1 = y_obj2[xindex4]
#integrate values in yarray to give summed value of x-values in array
obj2_int1 = np.trapz(obj2_yarray1,x=obj2_xarray1)
##OBJECT 1 RANGE (a2 to b2)
xindex5 = np.where(np.logical_and(x_obj2 >= a2, x_obj2 <= b2))
obj2_xarray2 = x_obj2[xindex5]
obj2_yarray2 = y_obj2[xindex5]
obj2_int2 = np.trapz(obj2_yarray2,x=obj2_xarray2)
#OBJECT 1 RANGE (a3 to b3)
xindex6 = np.where(np.logical_and(x_obj2 >= a2, x_obj2 <= b2))
obj2_xarray3 = x_obj2[xindex6]
obj2_yarray3 = y_obj2[xindex6]
obj2_int3 = np.trapz(obj2_yarray3,x=obj2_xarray3)
#~~~~EQUATION THAT SHOULD BE OPTMIZED~~~#
max = (((obj1_int1/obj1_int2) - (obj2_int1/obj2_int2))**2 +
((obj1_int3/obj1_int2) - (obj2_int3/obj2_int2))**2)**0.5
return max
def constr1(a1,a2,a3):
a1,a2,a3 >= 1.5
return a1, a2, a3
def constr2(b1,b2,b3):
b1,b2,b3 <= 3.0
return b1,b2,b3
p = optimize.fmin_cobyla(cobyla, cons=[constr1,constr2])
答案 0 :(得分:0)
我使用此方法为SGD Basket Trading创建策略。 虽然我不是这方面的专家,但我有一个公平的想法。 尝试将您的目标和约束转换为函数。 然后在
中调用这些函数x = fmin_cobyla(objtv_func,x0,constr_funcs,rhoend = 1e-7)
这应该可以解决调用cobyla优化器的问题。 如果您遇到错误,您还可以看到确切的错误点。
希望这适合你!祝你好运!