Pyomo运行输电网扩展模型遇KeyError:索引'0'对组件'li_f_inv'无效
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_invto be indexed over your epoch setmodel.E(which includes0), 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_invis indexed over a nested set (likemodel.E_n, your epoch-specific subset), ensure thatmodel.E_n[0]is properly initialized with valid values. Your code cuts off atmodel.E_n = Set(model.E, initialize...—if yourinitializefunction doesn't return a valid set fore=0,model.E_n[0]will be empty or undefined, makingli_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

