在Python语言中实现带约束函数的最小化

人气:53 发布:2023-01-03 标签: python numeric scipy numerical-methods scipy-optimize

问题描述

我正在尝试最小化包含我想要查找的最小化参数的三个N大小数组的函数。例如,假设为了最小化函数而要查找的参数由数组x = x[0],x[1],...,x[N-1]a = a[0],a[1],...,a[N-1]b = b[0],b[1],...,b[N-1]给出。此外,在该问题中,最小化边界是受约束的,约束如下:

0 <= x[i]  and  sum(x[i])-1=0  for all  i=0,...,N-1
0 <= a[i] <= Pi/2  for all  i=0,...,N-1
0 <= b[i] <= Pi/2  for all  i=0,...,N-1

在this问题之后,我能够将这些约束定义如下:

import numpy as np

#defining the constraints for minimization
#constraints on x:
Dx_lhs = np.diag(np.ones(N))
def xlhs(x): #left hand side
    return Dx_lhs @ x
def xrhs(x): #right hand side
    return np.sum(x) -1
con1x = {'type': 'ineq', 'fun': lambda x: xlhs(x)}
con2x = {'type': 'eq', 'fun': lambda x: xrhs(x)}

#constraints on a:
Da_lhs = np.diag(np.ones(N))
Da_rhs = -np.diag(np.ones(N))
def alhs(a):
    return Da_lhs @ a
def arhs(a): 
    return Da_rhs @ a + (np.ones(N))*np.pi/2
con1a = {'type': 'ineq', 'fun': lambda a: alhs(H)}
con2a = {'type': 'ineq', 'fun': lambda a: -1.0*Hrhs(H)}

# Restrições em b:
Db_lhs = np.diag(np.ones(N))
Db_rhs = -np.diag(np.ones(N))
def blhs(b):
    return Db_lhs @ b
def brhs(b): 
    return Db_rhs @ b + (np.ones(N))*np.pi/2
con1b = {'type': 'ineq', 'fun': lambda b: alhs(H)}
con2b = {'type': 'ineq', 'fun': lambda b: -1.0*Hrhs(H)}

现在假设我有如下函数:

def fun(mins): #just an example
    x, a, b = mins
    for i in range(N):
        sbi=0; sai=0
        for j in range(i+1):
            sbi += 2*x[j]*np.tan(b[j])
            sli += 2*x[j]*np.tan(a[j])
        B[i]=sbi
        A[i]=sai
    return (B @ C)

这不起作用,因为函数的第一行可能不是定义它的正确方式(我不知道应该如何声明包含我想要最小化的变量的数组)。谁能帮助我解决这个问题并应用scipy.optimize.minimize来查找最小化我的函数的x[], a[]b[]的值?

附注:所提供的函数仅用于说明目的,最小化解可能是显而易见的。

推荐答案

要最小化的函数应接受所有参数的一维数组。如果要将此数组拆分为3个不同的数组,可以使用重塑操作:

x, a, b = mins.reshape(3, N)

16