spec: close the term-path gaps so `Model.from_spec` can drop the eager build

未关闭
#1,199 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
5/5
预计耗时
一周以上
新手友好度
12/100
Issue 类型
功能
描述清晰度
基本清楚
活跃度
活跃
技术栈
python
领域
backend

调研方向

Start with builder._from_terms and terms.Unsupported in linopy/spec, which decide when a declaration falls back to the eager evaluator. The issue's two scripts wrap _from_terms and print each fallback reason, so run them first to see which declarations still fall back. Done means the window-sum forms and the objective and constraint products build on the term path, with no Unsupported raised for them. Treat this as design work and coordinate scope with maintainers before writing code.

由索引模型根据 Issue 内容生成。

描述

feature needs triage

[!NOTE]
The following content was generated by AI.

Describe the feature you'd like to see

Model.from_spec builds each declaration on the term path (#1197). Where that path cannot build a declaration, it raises terms.Unsupported, and the builder falls back to the eager evaluator. The fallback is slower, and it is the reason the eager build path cannot go yet. Neither path is released.

Over PyPSA's test suite (PyPSA/PyPSA#2181), 414 declarations still fall back:

  • 409 are window sums: sum_back(..., window=...) from unit-commitment minimum up and down times.
  • 5 are products of two variables: the quadratic objective from marginal_cost_quadratic.

Minimal examples and their output are in the details below.

Tasks

Window sums (WindowSum on the term path)

  • plain: sum_back(x, along=t, window=2)
  • partitioned: window=2, within=season_of[s]
  • wrapped: window=2, edge='wrap'
  • per parameter: window=width, within=season_of[s]

Products of two variables

  • in the objective (PyPSA's quadratic cost)
  • in constraints, where the data zeroes the product. A product that stays nonzero is refused, as before.
  • Quadratic named expressions stay with linopy.spec.evaluate after the solve, which runs on the eager evaluator. That is deliberate for now.

Small gaps

  • a lookup through an empty relation
  • infinity masked by absence
  • division by zero on masked rows
  • user-facing messages for Unsupported. Today builder._from_terms drops the reason without a trace.

Before removing the eager build path (planned for a later 1.x release)

  • the gaps above are closed
  • golden model dumps recorded from the eager path
  • an oracle checks the post-solve fold of named expressions against the built model
Examples: window sums and products fall back to the eager path

Both scripts wrap builder._from_terms and print each Unsupported reason before the fallback. Run on perf/spec-term-table @ d04e922 with python -W ignore <script> (this silences EvolvingAPIWarning).

Window sums: all four forms fall back.

import pandas as pd
from linopy import Model
from linopy.spec import builder, terms

term_path = builder._from_terms
def spy(make, ctx):
    def made():
        try:
            return make()
        except terms.Unsupported as e:
            print(f"  eager fallback: {e}")
            raise
    return term_path(made, ctx)
builder._from_terms = spy
t, s = pd.Index([0, 1, 2, 3], name="t"), pd.Index(["a", "b"], name="s")
data = {"t": t, "s": s, "season_of": pd.DataFrame({"t": t, "s": ["a", "a", "b", "b"]}),
        "width": pd.DataFrame({"s": s, "width": [1, 2]})}
for window in ["2", "2, edge='wrap'", "2, within=season_of[s]", "width, within=season_of[s]"]:
    print(f"window={window}")
    Model.from_spec({
        "dimensions": {"t": {"dtype": "int", "ordered": True}, "s": {"dtype": "str"}},
        "parameters": {"width": {"dims": ["s"], "dtype": "int"}}, "relations": {"season_of": {"key": "t", "values": "s"}},
        "variables": {"on": {"dims": ["t"], "bounds": {"lower": 0, "upper": 1}}},
        "constraints": {"up": {"dims": ["t"], "expression": f"sum_back(on, along=t, window={window}) <= 1"}},
    }, data)
window=2
  eager fallback: a WindowSum of a term
window=2, edge='wrap'
  eager fallback: a WindowSum of a term
window=2, within=season_of[s]
  eager fallback: a WindowSum of a term
window=width, within=season_of[s]
  eager fallback: a WindowSum of a term

Products of two variables: the constraint cap (built first) and the objective both fall back.

import pandas as pd
from linopy import Model
from linopy.spec import builder, terms

term_path = builder._from_terms
def spy(make, ctx):
    def made():
        try:
            return make()
        except terms.Unsupported as e:
            print(f"eager fallback: {e}")
            raise
    return term_path(made, ctx)
builder._from_terms = spy
t = pd.Index([0, 1, 2], name="t")
m = Model.from_spec({
    "dimensions": {"t": {"dtype": "int", "ordered": True}},
    "parameters": {"c2": {"dims": ["t"]}, "k": {"dims": []}},
    "variables": {"p": {"dims": ["t"], "bounds": {"lower": 0, "upper": 10}}},
    "constraints": {"cap": {"dims": ["t"], "expression": "p + k * p * p <= 5"}},
    "objective": {"sense": "minimize", "expression": "sum(c2 * p * p)"},
}, {"t": t, "k": 0.0, "c2": pd.DataFrame({"t": t, "c2": [1.0, 2.0, 3.0]})})
print(m.objective.expression)
print(m.constraints["cap"])
eager fallback: a product of two terms
eager fallback: a product of two terms
QuadraticExpression
-------------------
+1 p[0] p[0] + 2 p[1] p[1] + 3 p[2] p[2]
Constraint `cap` [t: 3]:
------------------------
[0]: +1 p[0] ≤ 5.0
[1]: +1 p[1] ≤ 5.0
[2]: +1 p[2] ≤ 5.0

Generated by Claude Code

主要语言
Python
星标
264
派生
95
平均合并
11 小时 33 分钟
30 天内合并 PR
86

环境准备

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

PyPSA/linopy 的其他 Issue

查看 PyPSA/linopy 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。