spec: from_spec spends about 2 ms per constraint entry, whatever its size

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

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
5/5
预计耗时
一周以上
新手友好度
18/100
Issue 类型
缺陷
描述清晰度
需要澄清
活跃度
活跃
技术栈
python
领域
performance

调研方向

Start with the reproducer in the issue, which times Model.from_spec per constraint entry at two grid sizes. The profile points at where / admits_a_row, _constraints and _objective, so read those in the spec code path first. The issue does not say what to change, and the work is performance investigation with an open design question. Done means a measured drop in per-entry cost that the maintainers accept.

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

描述

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

Model.from_spec has a fixed cost of about 2 ms per constraint entry. The grid size hardly changes it:

grid 10 entries 200 entries
2 × 2 2.38 ms per entry 2.06 ms per entry
200 × 200 2.87 ms per entry 2.62 ms per entry

Measured on stack/spec-perf (master + #1155, #1156, #1157), Python 3.13, 4 cores, spec lowered beforehand, best of 3.

This dominates real builds: in PyPSA/PyPSA#2128, from_spec is 79–84% of a warm create_model, and a network 300× larger costs only 0.43 s more. A profile of that build points at where / admits_a_row, _constraints and _objective. A spec with one flat name dimension will have fewer entries, but the cost per entry still sets the floor.

Reproducer
import time

import xarray as xr
from linopy import Model
from linopy.spec import lowered


def spec(n: int) -> dict:
    constraints = {
        f"c{i}": {"dims": ["t", "g"], "where": "active", "expression": f"x <= {i + 1}"}
        for i in range(n)
    }
    return {
        "dimensions": {"t": {"dtype": "str"}, "g": {"dtype": "str"}},
        "parameters": {"active": {"dims": ["t", "g"], "dtype": "bool"}},
        "variables": {"x": {"dims": ["t", "g"], "bounds": {"lower": 0}}},
        "constraints": constraints,
        "objective": {"sense": "minimize", "expression": "sum(x)"},
    }


for size in (2, 200):
    t, g = [f"t{i}" for i in range(size)], [f"g{i}" for i in range(size)]
    active = xr.DataArray(True, coords={"t": t, "g": g}, dims=["t", "g"]).copy()
    sources = {"t": t, "g": g, "active": active}
    for n in (10, 200):
        program = lowered(spec(n))
        times = []
        for _ in range(3):
            start = time.perf_counter()
            Model.from_spec(program, sources)
            times.append(time.perf_counter() - start)
        print(f"{size}x{size}, {n} entries: {1000 * min(times) / n:.2f} ms per entry")

Part of PyPSA/PyPSA#2138.

主要语言
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 摘要。