【问题标题】:Python - Using an array index that depends on an input valuePython - 使用取决于输入值的数组索引
【发布时间】:2012-03-03 04:14:18
【问题描述】:

我正在尝试在一个名为 pyomo(python 库)的程序中编写一个数学程序。下面,model 是我已经声明的对象,BRANCH 是一个集合; model.branch_scptmodel.Mmodel.branch_tbusmodel.branch_fbus 都是在代码执行时作为输入加载的参数列表(它们都有维度 = BRANCH)。此外,model.bus_anglemodel.line_flowmodel.z_line 是决策变量列表(也都是维度 BRANCH)。这是我的一种约束类型的定义,其中jBRANCH 中:

def Line_FlowA_rule(model,j):    

    return ( model.branch_scpt[j]*( model.bus_angle[model.branch_tbus[j]]
                                    - model.bus_angle[model.branch_fbus[j]] )
            - model.line_flow[j] + (1 - model.z_line[j]) * model.M[j] >= 0 )

model.Line_FlowA = Constraint(model.BRANCH, rule=LineFlowA_rule)

请注意,约束 Line_FlowA[j] 中引用的元素 model.bus_angle[j] 取决于 model.branch_tbus[j] 返回的元素(类似地,model.branch_fbus[j] 返回的元素)。但是,model.branch_tbus[j] 是一个数据输入值,我相信这是导致以下错误的原因:

"Unexpected exception while running model arpatest_nbp_constraint.py
        Unable to index variable bus_angle using supplied index with unhashable type: '_ParamValue'"

为了让函数更整洁,我尝试重新定义函数如下:

def Line_FlowA_rule(model,j):

    t = model.branch_tbus[j]
    f = model.branch_fbus[j]

    return ( model.branch_scpt[j]*( model.bus_angle[f]
                                    - model.bus_angle[t] )
            - model.line_flow[j] + (1 - model.z_line[j]) * model.M[j] >= 0 )

model.Line_FlowA = Constraint(model.BRANCH, rule=Line_FlowA_rule)

但我得到了同样的错误。

最后,我尝试将值 t 和 f 转换为不可变类型:

def Line_FlowA_rule(model,j):

    t = tuple(model.branch_tbus[j])
    f = tuple(model.branch_fbus[j])

    return ( model.branch_scpt[j]*( model.bus_angle[f]
                                    - model.bus_angle[t] )
            - model.line_flow[j] + (1 - model.z_line[j]) * model.M[j] >= 0 )

model.Line_FlowA = Constraint(model.BRANCH, rule=Line_FlowA_rule)

这导致了错误:

ERROR: Unexpected exception while running model arpatest_nbp_constraint.py
        '_ParamValue' object is not iterable

谁能告诉我我在这里做错了什么?我是 python 新手,所以它可能是基本的东西。非常感谢

【问题讨论】:

  • 你能告诉我们错误指向哪一行吗? model.branch_tbusmodel.branch_tbus[j](或“fbus”上的等价物)似乎都不是可迭代类型(列表、元组等)。

标签: python arrays indices


【解决方案1】:

第一次看到这个,但是检查源代码,我们可以看到,class _ParamValue 定义的here 扩展了class NumericConstant,定义了here,从代码中我们可以了解到有属性value,所以我唯一能建议的就是改变这样的代码:

def Line_FlowA_rule(model,j):

    t = model.branch_tbus[j].value
    f = model.branch_fbus[j].value

    return ( model.branch_scpt[j]*( model.bus_angle[f]
                                    - model.bus_angle[t] )
            - model.line_flow[j] + (1 - model.z_line[j]) * model.M[j] >= 0 )

model.Line_FlowA = Constraint(model.BRANCH, rule=Line_FlowA_rule)

但如果这些参数包含其他参数的索引,这当然可以工作。

【讨论】:

  • 非常感谢!这解决了一切。我希望我能投票,但我没有足够高的声誉。你太棒了!
  • @user1246364 显然,如果它满足您的需求,您可以接受答案
猜你喜欢
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-19
  • 2014-02-27
  • 2023-03-31
相关资源
最近更新 更多