Pyomo报错ValueError:无法检索组件IndexedVar[1],组件未构建的问题求助
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 usemodel.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_Tinstead 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

