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

Pyomo运行输电网扩展模型遇KeyError:索引'0'对组件'li_f_inv'无效

Troubleshooting the KeyError in Your Pyomo Transmission Expansion Model

Hey there! Let's break down that KeyError you're seeing: KeyError: "Error accessing indexed component: Index '0' is not valid for array component 'li_f_inv'". This error pops up when you try to access an indexed Pyomo component (like a Var, Set, or Constraint) using an index value that isn't part of its defined index set. Here's how to fix it:

1. Double-check how li_f_inv is defined

First, locate where you declared li_f_inv in your code. The problem almost certainly lies in its index binding:

  • If you intended li_f_inv to be indexed over your epoch set model.E (which includes 0), make sure the definition looks like this:
    model.li_f_inv = Var(model.E, domain=NonNegativeReals) # or Binary, depending on your variable type
    
  • If li_f_inv is indexed over a nested set (like model.E_n, your epoch-specific subset), ensure that model.E_n[0] is properly initialized with valid values. Your code cuts off at model.E_n = Set(model.E, initialize...—if your initialize function doesn't return a valid set for e=0, model.E_n[0] will be empty or undefined, making li_f_inv[0] invalid.

2. Verify your indexed set model.E_n

Since model.E_n is an indexed set tied to model.E, you need to guarantee it returns a non-empty, valid set for every element in model.E (including 0). Here's a corrected example of initializing model.E_n:

def init_E_n(model, e):
    # Replace this with your actual subset logic for each epoch
    if e == 0:
        return [101, 102]  # Example branch IDs for epoch 0
    elif e == 1:
        return [103, 104]
    elif e == 2:
        return [105]
    else: # e=3
        return [106, 107, 108]

model.E_n = Set(model.E, initialize=init_E_n)

If your init_E_n function skips e=0 or returns None/an empty list for it, any component indexed over model.E_n will throw an error when accessing index 0.

3. Debug by inspecting the component's index set

Add a quick print statement right before the line that throws the error to confirm what indices li_f_inv actually accepts:

print("Valid indices for li_f_inv:", model.li_f_inv.index_set())

This will show you exactly which index values are allowed. If 0 isn't in that output, you know the component's index set wasn't defined correctly.

4. Check where you're accessing li_f_inv[0]

Make sure you're not accidentally using 0 as an index in a context where li_f_inv expects a different type of index. For example, if li_f_inv is indexed over branches instead of epochs, trying to use an epoch number (0) as an index will fail.


内容的提问来源于stack exchange,提问作者O.Ayo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:16:48