Dense LinearExpression.to_constraint('==') keeps sign '==': repr raises KeyError, differs from sparse '='

已关闭 适合新手
#1,054 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
2/5
预计耗时
1-3 小时
新手友好度
78/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
python
领域
backend, testing

调研方向

从 LinearExpression.to_constraint 开始,比较 dense 和 sparse 后端对符号的处理;issue 指出 linopy/constants.py 和 test/test_store_conformance.py 中的 SIGN_EQ 用例可作为参考。检查 dense 路径如何处理 "==",并运行一致性测试。完成标准是 dense 约束存储 "="、其表示正常工作,并且可以移除 SIGN_EQ 的 xfail。

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

描述

bug

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

Version Checks
  • I have confirmed this bug exists on the current master branch of Linopy (95f6bfa4).
Issue Description

LinearExpression.to_constraint("==", rhs) stores the sign verbatim as "==" on the dense backend, while the sparse (CSR) backend normalizes it to "=". linopy's canonical equality sign is EQUAL = "=" (linopy/constants.py; "==" is only in SIGNS_alternative), so the dense backend is the wrong one. Consequences on dense:

  • repr() of the constraint raises KeyError: '==' (SIGNS_pretty only knows "=").
  • The un-normalized "==" is carried into the model by m.add_constraints(con).

x == 1, (1*x) == 1 and m.add_constraints(1*x, "==", 1) are fine on both backends; only the to_constraint path skips sign normalization.

Found while building the dense/sparse conformance suite for #1019 (test/test_store_conformance.py, the case marked SIGN_EQ, currently a strict xfail on sparse).

Reproducible Example
from linopy import Model

for sparse in (False, True):
    m = Model(sparse=sparse)
    x = m.add_variables(name="x")
    con = (1 * x).to_constraint("==", 1)
    m.add_constraints(con, name="c")
    print(f"sparse={sparse}: sign={con.sign.item()!r}, stored={m.constraints['c'].sign.item()!r}")
    try:
        print(repr(con))
    except KeyError as e:
        print(f"repr -> KeyError: {e}")

Output:

sparse=False: sign='==', stored='=='
repr -> KeyError: '=='
sparse=True: sign='=', stored='='
Constraint (unassigned)
-----------------------
+1 x = 1.0
Traceback of the dense repr (without try/except)
  File "linopy/constraints.py", line 581, in __repr__
    f"{header_string}\n{'-' * len(header_string)}\n{expr} {SIGNS_pretty[self.sign.item()]} {self.rhs.item()}"
                                                           ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^
KeyError: '=='
Expected Behavior

Dense to_constraint("==", ...) normalizes the sign to "=", as sparse already does and as x == 1 / add_constraints(lhs, "==", rhs) do, so repr works and both backends agree. The xfail in the conformance suite can then be dropped.

主要语言
Python
星标
263
派生
93
平均合并
2 天 19 小时
30 天内合并 PR
69

环境准备

从这里开始

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

PyPSA/linopy 的其他 Issue

查看 PyPSA/linopy 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

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