Skip to content

Can not solve model after adding custom variable #1351

@tom-welfonder

Description

@tom-welfonder

Version Checks (indicate both or one)

  • I have confirmed this bug exists on the lastest release of PyPSA.

  • I have confirmed this bug exists on the current master branch of PyPSA.

Issue Description

I tried to add a custom variable to my model. This resulted in an error when trying to solve the model.

Here is the resulting traceback:

Traceback (most recent call last):
  File "/main.py", line 13, in <module>
    n.optimize.solve_model(assign_all_duals=True)
  File "/pypsa/optimization/optimize.py", line 598, in solve_model
    self._n.optimize.assign_solution()
  File "/pypsa/optimization/optimize.py", line 620, in assign_solution
    c = n.c[_c_name]
  File "/pypsa/components/store.py", line 134, in __getitem__
    return super().__getitem__(item)
KeyError: 'custom'

Reproducible Example

import pypsa

# Create minimal network
n = pypsa.Network()
n.add("Bus", "bus")
n.add("Load", "load", bus="bus", p_set=1)
n.add("Generator", "generator", bus="bus", p_nom=1, marginal_cost=1)

# create custom variable
n.optimize.create_model()
m = n.model
m.add_variables(name="custom-var", coords=[n.snapshots])

# solve model
n.optimize.solve_model()

Expected Behavior

Custom variables with arbitrary name should not break the optimization.

Installed Versions

Details asttokens==3.0.0 bottleneck==1.5.0 certifi==2025.8.3 cftime==1.6.4.post1 click==8.2.1 cloudpickle==3.1.1 comm==0.2.3 contourpy==1.3.2 cycler==0.12.1 dask==2025.7.0 debugpy==1.8.16 decorator==5.2.1 deprecation==2.1.0 exceptiongroup==1.3.0 executing==2.2.1 fonttools==4.59.2 fsspec==2025.9.0 geopandas==1.1.1 gurobipy==12.0.3 highspy==1.11.0 importlib-metadata==8.7.0 ipykernel==6.30.1 ipython==8.37.0 jedi==0.19.2 jupyter-client==8.6.3 jupyter-core==5.8.1 kiwisolver==1.4.10rc0 linopy==0.5.6 locket==1.0.0 matplotlib==3.10.6 matplotlib-inline==0.1.7 narwhals==2.3.0 nest-asyncio==1.6.0 netcdf4==1.7.2 networkx==3.4.2 numexpr==2.11.0 numpy==1.26.4 packaging==25.0 pandas==2.3.2 parso==0.8.5 partd==1.4.2 patsy==1.0.1 pexpect==4.9.0 pillow==11.3.0 platformdirs==4.4.0 plotly==6.3.0 polars==1.33.0 prompt-toolkit==3.0.52 psutil==7.0.0 ptyprocess==0.7.0 pure-eval==0.2.3 pygments==2.19.2 pyogrio==0.11.1 pyparsing==3.2.3 pyproj==3.7.1 pypsa==1.0.0rc1 python-dateutil==2.9.0.post0 pytz==2025.2 pyyaml==6.0.2 pyzmq==27.0.2 scipy==1.15.3 seaborn==0.13.2 shapely==2.0.7 six==1.17.0 stack-data==0.6.3 statsmodels==0.14.5 toolz==1.0.0 tornado==6.5.2 tqdm==4.67.1 traitlets==5.14.3 typing-extensions==4.15.0 tzdata==2025.2 validators==0.35.0 wcwidth==0.2.13 xarray==2025.6.1 zipp==3.23.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    needs triageIssue needs initial review by the maintainers

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions