从外部访问优化函数中的变量

时间:2019-06-22 21:11:12

标签: python scipy global-variables scipy-optimize

我正在使用scipy.optimize.differential_evolution进行优化。在优化函数中,我调用了另一个函数。我想从优化项的外部获取内部函数的返回值。

from scipy.optimize import differential_evolution
import numpy as np

def test():
    a = 5
    b = 10
    ab = a + b
    ab2 = a + b**2
    return ab, ab2


def ackley(x):

    arg1 = -0.2 * np.sqrt(0.5 * (x[0] ** 2 + x[1] ** 2))
    arg2 = 0.5 * (np.cos(2. * np.pi * x[0]) + np.cos(2. * np.pi * x[1]))

    global Value1, Value2
    Value1, Value2 = test()

    return -20. * np.exp(arg1) - np.exp(arg2) + 20. + np.e

if __name__ == "__main__":
    bounds = [(-5, 5), (-5, 5), (-5, 5), (-5, 5), (-5, 5), (-5, 5), (-5, 5)]
    result = differential_evolution(ackley, bounds, args=(), workers=-1)

    print(Value1, Value2)

虽然上面的代码有效,但是在打印Value1和Value2时,下面的等效代码失败。

import numpy as np
import math
from reference_section import ref_section

def test():
    a = 5
    b = 10
    ab = a + b
    ab2 = a + b**2
    return ab, ab2

def Objective(coeff):

    n = 8  
    m = 100  
    x = 0.5 * (1 - np.cos(np.linspace(0, np.pi, m))) 

    BPn_list = []
    for r in range(0, n + 1):
        BPn_terms = (math.factorial(n) / (math.factorial(r) * math.factorial(n - r))) * (x ** r) * ((1 - x) ** (n - r))
        BPn_list.append(BPn_terms.tolist())

    N1 = 0.5
    N2 = 1
    c = 1
    Zte = 0.00126 * 2

    # ----------------------
    Class_function = []
    ND_TE_ratio_upper = []
    for items in x:
        C = ((items / c) ** N1) * ((1 - (items / c)) ** N2)
        Class_function.append(C)
        TE = (items / c) * ((Zte / 2) / c)
        ND_TE_ratio_upper.append(TE)
    ND_TE_ratio_lower= [-i for i in ND_TE_ratio_upper]
    # -----------------------------------------------------------------------------
    Aui = [np.sqrt((2 * coeff[0]) / c), coeff[1], coeff[2], coeff[3], coeff[4], coeff[5], coeff[6], coeff[7], np.tan(np.deg2rad(coeff[8])) + (Zte / c)]
    Ali = [np.tan(np.deg2rad(coeff[9])) + (Zte / c), coeff[10], coeff[11], coeff[12], coeff[13], coeff[14], coeff[15], coeff[16], -Aui[0]]
    # ------------------------------------------------------------    
    UpperSurf = [sum(x) for x in zip([x*y for x,y in zip(Class_function,[sum(x) for x in zip(*[[Aui[i] * j for j in sub] for i, sub in enumerate(BPn_list)])])], ND_TE_ratio_upper)]
    LowerSurf = [sum(x) for x in zip([x*y for x,y in zip(Class_function,[sum(x) for x in zip(*[[Ali[i] * j for j in sub] for i, sub in enumerate(BPn_list)])][::-1])], ND_TE_ratio_lower)]
    y_prediction = np.append(UpperSurf[::-1], LowerSurf[1:])

    global Value1, Value2
    Value1, Value2 = test()

    return np.sum(np.sqrt(np.array(y_reference - y_prediction)**2.0))

if __name__ == "__main__":

    y_reference, suctReference, pressReference = ref_section("ref.dat")

    BOUNDS = [(0.0 , 0.1), (0.0 , 0.5), (0.0 , 0.5), (0.0 , 0.5), (0.0 , 0.5), (0.0 , 0.5), (0.0 , 0.5), (0.0 , 0.5), (0.0 , 50.0),
              (-50.0 , 50.0), (0.1 , -0.5), (0.1 , -0.5), (0.1 , -0.5), (0.0 , -0.5), (0.0 , -0.5), (0.0 , -0.5), (0.0 , -0.1)]

    from scipy.optimize import differential_evolution
    result = differential_evolution(Objective, BOUNDS, maxiter=100, disp=True, workers=-1)


    print(Value1, Value2)

1 个答案:

答案 0 :(得分:0)

在调用函数之前在全局范围内定义变量,例如:

if __name__ == "__main__":
    n = m = x = N1 = N2 = c = Zte = Rle = Beta_TE = 0
    UpperSurf = []; LowerSurf = []; suctReference = []; pressReference = [];