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

Đang mở
#1,199 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

Chưa có ai nhận issue này.

Đánh giá

Độ khó
5/5
Thời gian dự kiến
Hơn một tuần
Mức phù hợp với người mới
12/100
Loại issue
Tính năng
Độ rõ ràng
Khá rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
python
Lĩnh vực
backend

Hướng nghiên cứu

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.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

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

Ngôn ngữ chính
Python
Star
264
Fork
95
Merge trung bình
11 giờ 33 phút
Pull request đã merge (30 ngày)
86

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của PyPSA/linopy

Tất cả issue của PyPSA/linopy

Issue tương tự

Thêm issue về Python

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.