You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pyomo报错ValueError:无法检索组件IndexedVar[1],组件未构建的问题求助

Fixing "ValueError: Error retrieving component IndexedVar[1]: The component has not been constructed" in Pyomo

I see the issue in your code—let's break this down and fix it quickly.

Root Cause

The error happens because your variable M_b1_O_stored_T isn't actually attached to your Pyomo model instance. You created it as a standalone variable instead of making it an attribute of model, so Pyomo doesn't recognize it as part of the model's components and can't construct it when evaluating the objective function.

Corrected Code

Here's the fixed version of your code with the key change highlighted:

from coopr.pyomo import *
import numpy as np
from scipy.optimize import minimize
import math

model = ConcreteModel()
model.days = RangeSet(1, 31)  # model.time
T = model.days

# Fix: Attach the variable to the model using model.M_b1_O_stored_T
model.M_b1_O_stored_T = Var(T, bounds=(0, None))

def obj_rule(model):
    # Now reference the variable as part of the model
    return sum(model.M_b1_O_stored_T[i] for i in model.days)

model.funcobj = Objective(rule=obj_rule, sense=maximize)

Explanation of Changes

  • Attached the variable to the model: Instead of M_b1_O_stored_T = Var(...), we use model.M_b1_O_stored_T = Var(...). This tells Pyomo to register the variable as part of the model, so it gets constructed properly.
  • Updated the objective rule: The rule now accesses model.M_b1_O_stored_T instead of the standalone variable, ensuring it's referencing the model-managed component.

Additional Notes

In Pyomo, all core components (variables, objectives, constraints, sets) must be attributes of your ConcreteModel or AbstractModel instance. This is how Pyomo tracks dependencies, constructs components, and validates the model structure. Always double-check that you're prefixing component definitions with model. to avoid this kind of error.

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 22:07:36