我想在gekko中定义一个方程,但随之而来的是错误:

Traceback (most recent call last):
  File "/Users/stefantomaschko/Desktop/Bundeswettbewerb Informatik/2.Runde/Päckchen/paeckchen_gurobi.py", line 131, in <module>
    m.solve()
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/gekko/gekko.py", line 2166, in solve
    raise Exception(apm_error)
Exception: @error: Equation Definition
 Equation without an equality (=) or inequality (>,<)
 true
 STOPPING...

我的代码(不是所有的功能,但最重要的功能):

def fitness(var):
    anzahl_sorte_stil = {}
    boxes = convert(var)
    print(boxes)
    stile = set()
    for var_box in var:
        #anzahl_box = []
        for v in var_box:
            try:
                value = int(str(v.value))
            except:
                value = int(float(str(v.value[0])))# if v.value != None else 0
            info = info_name(v)
            stile.add(info[1])
            if info not in anzahl_sorte_stil:
                
                anzahl_sorte_stil[info] = value
            else:
                anzahl_sorte_stil[info] += value
            #anzahl_box.append(value)
    #   if min(anzahl_box) == 0:
    gruppen = finde_gruppen(stile)
    for g in gruppen:
        if g not in kombinierbar:
            return unmoeglich
    #print(anzahl_sorte_stil)
    uebrig = 0
    for kleid in kleider:
        dif = kleid[2] - anzahl_sorte_stil[(kleid[0],kleid[1])]
        if dif<0:
            print("ZU OFT VERWENDET!")
            return unmoeglich
        else:
            uebrig += dif
    
    return uebrig
    


sorten,stile,kombinierbar,kleider,gesamt = read_data("paeckchen0.txt")
unmoeglich = gesamt+1
min_boxen,max_boxen = get_min_max_boxen(sorten,kleider)
print("Min. Anzahl Boxen: ", min_boxen)
print("Max. Anzahl Boxen: ", max_boxen)

m = GEKKO(remote=False)
m.options.max_time = 1000
m.options.max_iter = 1000
m.options.max_memory = 1000
var = [[] for _ in range(max_boxen)]

for i,var_box in enumerate(var):
    for kleid in kleider:
        #print(kleid[:2])
        var_box.append(m.Var(0,lb=1,ub=min((kleid[2],3)),integer=True,name=f"{kleid[0]}_{kleid[1]}_{i}"))#wie oft ist Kleid {kleid[:2]} in Box {i}

#m.Equation(fitness(var) < gesamt)
m.Minimize(fitness(var))
m.Equation(fitness(var) <= unmoeglich)


m.options.SOLVER=1
m.solve()

在文档中我没有发现任何与此有关的东西.有人可以帮我修改它.我也会很高兴看到我的代码,为什么它没有找到正确的解决方案.现在我想实现这个等式,甚至不允许不正确的解.

推荐答案

Gekko优化模型可以通过函数调用来定义,然后将模型编译成字节码.函数fitness()仅被调用两次,定义了目标函数和方程:

m.Minimize(fitness(var))
m.Equation(fitness(var) <= unmoeglich)

您可以在文件gk0_model.apm中以m.open_folder()打开的文件夹中判断模型,该文件夹作为文本文件.fitness()函数覆盖Gekko变量并返回标量值.这就是为什么返回True作为等式,因为Gekko算子重载不用于计算不等式约束.它变成了一个简单的Python表达式,计算值为True.为了解决这个问题,使用Gekko表达式,为基于梯度的求解器(如m.if3(condition,val1,val2)m.max3(0,expression))提供连续的一阶导数和二阶导数信息.

从约束和变量名来看,我猜测应用程序是一个带有类别和组合的包装优化问题,以判断包装配置,并根据项目的数量、类型以及它们在盒子中的分布方式计算得分.目标似乎是一个成本或效率指标.求解器中的可行性约束应在不需要if个语句的情况下找到解决方案.下面是Gekko中的一个包装优化示例:

from gekko import GEKKO
m = GEKKO(remote=False)

# 5 types of items, and a maximum of 10 boxes to use
num_items = 5
max_boxes = 10

# size of each item type (units of volume or weight)
item_sizes = [3, 4, 2, 5, 3]

# number of each item type available
item_counts = [10, 6, 8, 5, 7]

# max capacity of each box
box_capacity = [10,10,10,15,15,15,15,20,20,20]

# number of each item type in each box
item_in_box = [[m.Var(lb=0, ub=item_counts[i], integer=True) 
               for i in range(num_items)] 
               for _ in range(max_boxes)]

# Objective: minimize the number of boxes used
# could also minimize unused volume or another metric
boxes_used = m.Array(m.Var,max_boxes,lb=0,ub=1,integer=True)
m.Minimize(sum(boxes_used))

# total size of items in each box does not exceed box capacity
for box in range(max_boxes):
    m.Equation(m.sum([item_in_box[box][i] * item_sizes[i]
                      for i in range(num_items)]) 
               <= box_capacity[box] * boxes_used[box])

# all items are packed
for i in range(num_items):
    m.Equation(m.sum([item_in_box[box][i] 
               for box in range(max_boxes)])==item_counts[i])

# Solve the problem with APOPT solver
m.options.SOLVER = 1
m.solve(disp=True)

# Output the solution
print("Optimal Packing Solution:")
for box in range(max_boxes):
    if boxes_used[box].value[0] > 0.5:  # box is used
        print(f"Box {box + 1}:")
        for i in range(num_items):
            iib = int(item_in_box[box][i].value[0])
            if iib > 0:
                print(f" - Item Type {i+1}: {iib}")

优化器 Select 最大的盒子,因为目标是最小化所使用的盒子数量.解决方案如下:

 ---------------------------------------------------
 Solver         :  APOPT (v1.0)
 Solution time  :    2.23269999999320      sec
 Objective      :    7.00000000000000     
 Successful solution
 ---------------------------------------------------

Optimal Packing Solution:
Box 4:
 - Item Type 2: 1
 - Item Type 3: 1
 - Item Type 4: 1
 - Item Type 5: 1
Box 5:
 - Item Type 1: 1
 - Item Type 3: 2
 - Item Type 4: 1
 - Item Type 5: 1
Box 6:
 - Item Type 1: 1
 - Item Type 2: 1
 - Item Type 3: 1
 - Item Type 5: 1
Box 7:
 - Item Type 1: 2
 - Item Type 2: 1
 - Item Type 3: 1
 - Item Type 5: 1
Box 8:
 - Item Type 1: 2
 - Item Type 2: 1
 - Item Type 3: 1
 - Item Type 4: 1
 - Item Type 5: 1
Box 9:
 - Item Type 1: 2
 - Item Type 2: 1
 - Item Type 3: 1
 - Item Type 4: 1
 - Item Type 5: 1
Box 10:
 - Item Type 1: 2
 - Item Type 2: 1
 - Item Type 3: 1
 - Item Type 4: 1
 - Item Type 5: 1

可以调整目标,以最小化未使用的体积或其他指标.Design Optimization course中有一个相关的circle packing optimization.

Circle packing optimization

Python相关问答推荐

使用新的类型语法正确注释ParamSecdecorator (3.12)

仿制药的类型铸造

Deliveryter Notebook -无法在for循环中更新matplotlib情节(保留之前的情节),也无法使用动画子功能对情节进行动画

将jit与numpy linSpace函数一起使用时出错

递归访问嵌套字典中的元素值

在含噪声的3D点网格中识别4连通点模式

如何并行化/加速并行numba代码?

考虑到同一天和前2天的前2个数值,如何估算电力时间序列数据中的缺失值?

使用特定值作为引用替换数据框行上的值

如何杀死一个进程,我的Python可执行文件以sudo启动?

跳过嵌套JSON中的级别并转换为Pandas Rame

Python—为什么我的代码返回一个TypeError

在Docker容器(Alpine)上运行的Python应用程序中读取. accdb数据库

Cython无法识别Numpy类型

Beautifulsoup:遍历一个列表,从a到z,并解析数据,以便将其存储在pdf中.

如何在Python中自动创建数字文件夹和正在进行的文件夹?

Python OPCUA,modbus通信代码运行3小时后出现RuntimeError

在matplotlib中重叠极 map 以创建径向龙卷风图

时间戳上的SOAP头签名无效

如何将django url参数传递给模板&S url方法?