Гекко Нелинейная оптимизация, ошибка в целевой функции - PullRequest
0 голосов
/ 15 мая 2018
from gekko import GEKKO
sample = [[[0, 0.5, 0, 0, 0.5], [0, 0.08, 0.92, 0, 0], [0, 0.44, 0.56, 0, 0], [0, 0, 0.84, 0.16, 0], [0.34, 0.66, 0, 0, 0], [0, 0.53, 0.47, 0, 0], [0, 0, 0.8, 0.2, 0]], [0.89, 1, 1, 1, 1, 1, 1], [[1], [1], [1], [1], [1], [1], [1]], [0, 0.5, 1, 1.5, 2, 2.3, 3]]

# Initialize Model
m = GEKKO()

#define parameter
eq = m.Param(value=1)

for i in range(0,len(sample[0])):
    for j in range(0,len(sample[0][i])):
        if sample[0][i][j] != None:
            sample[0][i][j] = None

for j in range(0,len(sample[1])):
    if sample[1][j] != None:
        sample[1][j] = None

for i in range(0,len(sample[2])):
    for j in range(0,len(sample[2][i])):
        if sample[2][i][j] != None:
            sample[2][i][j] = None

for i in range(3, len(sample)):
    for j in range(0,len(sample[i])):
        if sample[i][j] != None:
            sample[i][j] = None
x = sample
#print(x)

for i in range(0,len(x[0])):
    for j in range(0,len(x[0][i])):
        x[0][i][j] = m.Var(lb=0.0,ub=1.0)          
for j in range(0,len(x[1])):
    x[1][j] =m.Var(lb=0.0,ub=1.0)  
for i in range(0,len(x[2])):
    for j in range(0,len(x[2][i])):
        x[2][i][j] = m.Var(lb=0.0,ub=1.0)   
for j in range(1,len(x[3])-1):
    x[3][j] = m.Var(lb=0.0,ub=3.00)
x[3][0] = m.Var(lb=0.0,ub=0.000000001)
x[3][len(x[3])-1] = m.Var(lb=3.0,ub=3.0001)  

#Initial value
ini = [[[0, 0.5, 0, 0, 1], [0, 0.08, 0.92, 0, 0], [0, 0.44, 0.56, 0, 0], [0, 0, 0.84, 0.16, 0], [0.34, 0.66, 0, 0, 0], [0, 0.53, 0.47, 0, 0], [0, 0, 0.8, 0.2, 0]], [0.89, 1, 1, 1, 1, 1, 1], [[1], [1], [1], [1], [1], [1], [1]], [0, 0.5, 1, 1.5, 2, 2.3, 3.0]]        
for i in range(0,len(x[0])):
    for j in range(0,len(x[0][i])):
        x[0][i][j].value = ini[0][i][j]         
for j in range(0,len(x[1])):
    x[1][j].value = ini[1][j] 
for i in range(0,len(x[2])):
    for j in range(0,len(x[2][i])):
        x[2][i][j].value = ini[2][i][j]   
for j in range(0,len(x[3])):
    x[3][j].value = ini[3][j]   


#Constraint1 sum of all belief degree is 1
for i in range(0,len(x[0])):
    m.Equation(sum(x[0][i])==eq)

#Constraint2 RV[i+1] > RV[i]
for j in range(1,len(x[3])-1):    
    m.Equation(x[3][j+1] - x[3][j] > 0)

#Objective  


def gekko_obj(x):    
    belief_consequence = x[0]
    rl_weight = x[1]
    att_weight = x[2]
    RV = x[3]
    Data_Transformation(RV)
    List_of_Rule()
    Rule_Activation_Weight(rl_weight,att_weight)
    Aggregated_Belief_and_Output(belief_consequence)
    exp_output()
    objective_minimize() 
    return objective_value
m.Obj(gekko_obj(x)) 

#Set global options
m.options.IMODE = 3 #steady state optimization

#Solve simulation
m.solve(remote=True) # solve on public server   

#Results
print('')
print('Results')
print(x)

Функция def gekko_obj (x) работает с любым значением x.

Тем не менее, он завершается неудачно, когда m вызывается как целевая функция Гекко. Obj (gekko_obj (x)).

Файл "/Anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", строка 710, в runfile execfile (имя файла, пространство имен)

Файл "/Anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", строка 101, в execfile exec (compile (f.read (), filename, 'exec'), пространство имен)

Файл "/ Пользователи / swatisachan / Рабочий стол / Файлы Python / Оптимизация / BRB оптимизация по GEKKO1.py ", строка 451, в m.Obj (gekko_obj (х))

Файл "/ Пользователи / swatisachan / Рабочий стол / Файлы Python / Оптимизация / BRB оптимизация с помощью GEKKO1.py ", строка 444, в gekko_obj Data_Transformation (RV)

Файл "/ Пользователи / swatisachan / Рабочий стол / Файлы Python / Оптимизация / BRB оптимизация с помощью GEKKO1.py ", строка 53, в Data_Transformation если L1 [i] [j]> RV [k]:

Файл "/anaconda3/lib/python3.6/site-packages/gekko/gk_operators.py", строка 25, в len возвращение len (self.value)

Файл "/anaconda3/lib/python3.6/site-packages/gekko/gk_operators.py", строка 122, в len return len (self.value)

TypeError: объект типа 'int' не имеет len ()

Функция преобразования данных:

###Generate input data uniformaly 
from random import randrange, uniform
global L1
L1 = []
data = []
for i in range(10):
    frand = uniform(0, 3)
    data.append(frand)
L1.append(sorted(data))  #Input data 
print('data: '+str(L1))

header =['x']

global RV  

def Data_Transformation(RV):
    #print('Referential value: ' +str(RV))
    global Rule_RV_list
    global L3
    Rule_RV_list = [] 
    L3 = []   
    for i in range(0,len(header)):  
        global L2
        L2 = []
        if all(isinstance(x, (int,float)) for x in L1[i]):  
            global num_RV
            global RV_index
            Rule_RV_list.append(RV) 

            for j in range(0,len(L1[i])):                 
                match = [0 for col in range(len(RV))]  
                intial_bl_dis = list(zip(RV, match))   
                print(RV)
                for k in range(0,len(RV)):
                    if L1[i][j] > RV[k]:
                        a_plus = RV[k+1]
                        print('a plus:' +str(a_plus))

                if RV.index(a_plus) > 0:
                    a_minus = RV[RV.index(a_plus)-1]
                else:
                    a_minus = RV[RV.index(a_plus)+1]

                alpha_minus = abs((a_plus - L1[i][j])/(a_plus - a_minus))
                alpha_plus = 1 - alpha_minus

                RV_index = RV.index(a_plus)     
                intial_bl_dis[RV_index] = (intial_bl_dis[RV_index][0],alpha_plus)
                intial_bl_dis[RV_index-1] = (intial_bl_dis[RV_index-1][0],alpha_minus)
                L2.append(intial_bl_dis)              
            L3.append(L2)

Я опубликовал некоторые части кода.

1 Ответ

0 голосов
/ 17 мая 2018

Элементы RV являются экземплярами класса GEKKO Variable

>>> type(RV[k])
<class 'gekko.gk_variable.GKVariable'>

При печати этих объектов отображается атрибут value, оператор > не сравнивает value объекта (возвращаетстроковое представление сравнения).Вы можете исправить эту ошибку, изменив строку на:

if L1[i][j] > RV[k].value:

Похоже, что есть еще одна ошибка, которая также связана с забавными способами, перегружающими операторы переменных GEKKO.

...