NetworkX统计父节点并在Pyomo中创建对应动态变量的问题
解决方案
1. 修改mygraph函数统计父节点数量
在mygraph函数中遍历节点属性,统计type为parent的节点总数,同时返回图对象和统计结果,方便后续mymodel函数调用:
import networkx as nx def mygraph(): G = nx.Graph() G.add_nodes_from([ ("N1", {"type":"parent","demand": 10}), ("N2",{"type":"parent","demand": 12}), ("N3", {"type":"parent","demand": 25}), ("S1", {"type":"server","demand": 12}), ("S2",{"type":"server","demand": 20}) ]) # 统计type为parent的节点总数 parent_count = sum(1 for node, attr in G.nodes(data=True) if attr["type"] == "parent") # 返回图对象和父节点数 return G, parent_count
2. 在mymodel函数中创建对应数量的变量
从mygraph获取图和父节点数,筛选出所有父节点,为每个父节点创建Pyomo变量,并将初始值设为对应节点的demand属性:
from pyomo.environ import ConcreteModel, Var, Constraint, Objective, SolverFactory from pyomo.util.infeasible import assert_optimal_termination def mymodel(): # 获取图对象和父节点数 g, parent_count = mygraph() # 筛选出所有父节点 parent_nodes = [node for node, attr in g.nodes(data=True) if attr["type"] == "parent"] model = ConcreteModel() # 创建对应数量的变量,初始值为父节点的demand model.parent_vars = Var(range(parent_count), initialize=lambda model, i: g.nodes[parent_nodes[i]]["demand"]) # 补充你的约束与目标函数(替换为实际业务逻辑) model.const1 = Constraint(expr=...) # 替换为约束1的具体表达式 model.const2 = Constraint(expr=...) # 替换为约束2的具体表达式 model.obj1 = Objective(expr=...) # 替换为目标函数的具体表达式 status = SolverFactory('glpk') results = status.solve(model) assert_optimal_termination(results) model.display() mymodel()
补充说明
- 通过
parent_nodes列表确保变量与父节点一一对应,顺序与节点添加顺序一致; - 若需要将变量固定为
demand值而非仅初始值,可添加model.parent_vars[i].fix(g.nodes[parent_nodes[i]]["demand"])锁定变量值。
内容的提问来源于stack exchange,提问作者Waqas Swati
相关产品推荐
相关产品推荐

