Hacktoberfest 2026: le issue che i maintainer hanno segnato per ottobre, aperte e adatte ai principianti. Sfoglia le issue Hacktoberfest

Constant LinearExpression * multi-term LinearExpression raises TypeError (mirrored product works)

Aperta Adatta ai principianti
#1,055 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
68/100
Tipo di issue
Bug
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
python
Ambito
backend

Direzione di ricerca

Inizia leggendo LinearExpression._multiply_by_linear_expression e __mul__, che l’issue indica come causa; poi esegui le riproduzioni dense e sparse dell’issue. Il lavoro è terminato quando una LinearExpression costante moltiplicata per una LinearExpression con più termini restituisce lo stesso risultato lineare scalato in entrambi i backend, mentre i casi speculari esistenti e quelli con un solo termine continuano a funzionare.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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

Multiplying a constant LinearExpression (no terms) by a multi-term LinearExpression raises TypeError on both the dense and sparse backends. The mirrored product (multi-term × constant) and constant × one-term expression both work and return the scaled linear expression.

Cause: LinearExpression._multiply_by_linear_expression checks other.nterm > 1 and raises before checking self.is_constant. __mul__ then turns that TypeError into NotImplemented, so the user only sees the generic unsupported operand type(s) message.

Found while building the dense/sparse conformance suite for #1019.

Reproducible Example
import warnings
from linopy import LinearExpression, Model

warnings.simplefilter("ignore")  # PerformanceWarning on sparse
for sparse in (False, True):
    m = Model(sparse=sparse)
    x = m.add_variables(name="x")
    y = m.add_variables(name="y")
    c = LinearExpression(3, m)
    print(f"sparse={sparse}")
    for lab, f in {
        "c * (2*x + 3*y)": lambda: c * (2 * x + 3 * y),
        "(2*x + 3*y) * c": lambda: (2 * x + 3 * y) * c,
        "c * (2*x)": lambda: c * (2 * x),
        "3 * (2*x + 3*y)": lambda: 3 * (2 * x + 3 * y),
    }.items():
        try:
            r = repr(f()).splitlines()[-1]
        except Exception as e:
            r = f"{type(e).__name__}: {e}"
        print(f"  {lab:18} -> {r}")

Output:

sparse=False
  c * (2*x + 3*y)    -> TypeError: unsupported operand type(s) for *: 'LinearExpression' and 'LinearExpression'
  (2*x + 3*y) * c    -> +6 x + 9 y
  c * (2*x)          -> +6 x
  3 * (2*x + 3*y)    -> +6 x + 9 y
sparse=True
  c * (2*x + 3*y)    -> TypeError: unsupported operand type(s) for *: 'LinearExpression' and 'LinearExpression'
  (2*x + 3*y) * c    -> +6 x + 9 y
  c * (2*x)          -> +6 x
  3 * (2*x + 3*y)    -> +6 x + 9 y
Traceback (without try/except)
Traceback (most recent call last):
  File "repro.py", line 18, in <module>
    c * (2 * x + 3 * y)
    ~~^~~~~~~~~~~~~~~~~
TypeError: unsupported operand type(s) for *: 'LinearExpression' and 'LinearExpression'

The same asymmetry applies to non-constant one-term factors, e.g. (x*0 + 3) * (2*x + 3*y) raises while (2*x + 3*y) * (x*0 + 3) returns a QuadraticExpression.

Expected Behavior

A constant expression acts like a scalar factor: c * (2*x + 3*y) returns the LinearExpression +6 x + 9 y, the same as (2*x + 3*y) * c and 3 * (2*x + 3*y).

Lingua principale
Python
Stelle
262
Fork
89
Merge medio
2g 11h
PR unite (30g)
28

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di PyPSA/linopy

Tutte le issue di PyPSA/linopy

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.