Skip to content

Refactored the inheritance hierarchy of Variable from Expr to ExprLike - #1299

Open
Zeroto521 wants to merge 41 commits into
scipopt:masterfrom
Zeroto521:variable
Open

Zeroto521 wants to merge 41 commits into
scipopt:masterfrom
Zeroto521:variable

Conversation

@Zeroto521

@Zeroto521 Zeroto521 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Why

Variable used to inherit from Expr. The relationship between Term, Variable, and Expr is quite odd. Variable is the subclass of Expr, but Variable also could be a member of a Term.
To fix this problem and follow the math (Variable -> Term -> Expr), we have a duck class called ExprLike (NOT BaseExpr), it defines the basic behavior (like add, sub and others).

image

Performance

I also ran a performance benchmark (in ns). All results are within noise range except for expr_degree.

benchmark master(Variable(Expr)) branch(Variable(ExprLike)) Variable(ExprLike) vs Variable(Expr)
var_add 351–384 369–374 ~0
var_mul 728–734 648–653 -11%
var_add_num 414–425 379–392 -8%
num_mul_var 277–284 289–296 +4%
var_sub 555–665 630–734 ~+10%
var_div 4010–4327 4050–4382 ~0
var_pow2 1299–1339 1228–1309 ~0
quicksum3 724–820 706–775 ~0
expr_add 401–453 400–414 ~0
expr_mul 1287–1295 1199–1230 -5%
expr_add_num 359–368 376–385 +3%
expr_mul_num 289–294 282–316 ~0
expr_getitem 298–301 292–325 ~0
expr_iter 214–222 196–201 -8%
expr_degree 450–484 184–188 -60%
gen_add 3192–3451 3224–3326 ~0
gen_mul 3017–3241 3216–3427 ~0
build_gen 2927–2973 2951–2993 ~0

Zeroto521 added 30 commits June 14, 2026 11:30
Hand-merged conflicts in CHANGELOG.md, expr.pxi, scip.pxd, scip.pyi
(no conflict markers in working tree).

Key changes from upstream f5a761d:
- scipopt#1267: readonly fields on SumExpr/ProdExpr
- scipopt#1256: dual fix
- scipopt#1273: addConsLinear
- scipopt#1277: remove VarExpr.var
- New: stubs/baseline.sh, requirements/types.txt, pylock.types.toml,
  tests/@types/expr.mypy.out, scripts/generate_expr_type_tests.py

M4 core: Variable(ExprLike), ExprLike base with as_expr/expr_view,
__init__ throws NotImplementedError on Variable.

Bug fix: Expr.__add__/__mul__ now delegate to GenExpr when other is
GenExpr, avoiding PyNumber_Add recursion that caused stack overflow
when computing Expr + GenExpr (e.g., 2*x + exp(x)).
__add__/__mul__/__truediv__ now call Expr methods directly via
__Pyx_PyObject_FastCallMethod instead of going through PyNumber_Add/
PyNumber_Mul/PyNumber_TrueDivide slot lookup.

__getitem__/__iter__ inlined to direct dict access (v.terms.get /
iter(v.terms)), equivalent to Expr originals.

__pow__ unchanged (internal res *= self still dispatches; full inline
not worth the complexity).

Perf: x+y regression reduced from +48% to +16%; x*y regression
eliminated (-6%); degree still +15% (as_expr indirection).

97 tests pass, mypy 0 errors.
- Forward __add__, __mul__, and __truediv__ through operator syntax instead of unbound Expr method calls
- Annotate expression-compatible APIs with ExprLike
- Remove duplicated Expr.__getitem__/__iter__ in favor of ExprLike
- Assert ExprCons.expr is a plain Expr after normalize()
- Rename Variable.expr_view to Variable._expr
- Raise clearer errors when indexing or iterating a GenExpr
ExprLike.__neg__ never returns a Variable, so Expr | GenExpr is more accurate. Add a Variable.__neg__ override returning Expr, and apply ruff formatting to the stub.
Move the degree computation from Expr to ExprLike as a cpdef double
method with "except? -1", so Expr, Variable and GenExpr share one
implementation; GenExpr overrides it to return INFINITY. Expr.degree
now returns float instead of int, and the stub is updated accordingly.

Replace the generator-based max() with an explicit C loop (generators
are not allowed inside cpdef functions).

Benchmark (Python call, min of 5 runs):
  1000 terms: 71.6 us -> 9.3 us (7.7x)
  2 terms:    679 ns  -> 151 ns (4.5x)

Also update test_Variable for the single-argument Term constructor.
- __getitem__: reject None explicitly and raise a clear TypeError for
  invalid index types; annotate the return type
- __iter__: simplify and annotate as Iterator[Term]
- __contains__: add O(1) membership test for Term and Variable
- GenExpr: override __contains__ to raise TypeError like __getitem__/__iter__
- Stub: drop the duplicate Expr.__getitem__/__iter__ and update signatures
@github-actions

Copy link
Copy Markdown
Contributor

Reviewer checklist

To be checked by the reviewer.

Code

  • The code change is correct.
  • New methods are named after their SCIP function (e.g. SCIPgetVars() becomes getVars()) and are placed next to related methods, or no new methods were added.
  • The added/modified behavior is identical to SCIP's, or deviations were justified.
  • If methods were added to BaseModel, they work in exact mode.
  • If methods were added to Model, the exact counterpart was added to ExactModel with Fraction i/o, or the method has no meaning in exact mode or SCIP has no exact equivalent.

Documentation

  • The code is documented (numpydoc docstrings with parameter and return types).
  • CHANGELOG.md is updated, including API changes.
  • The type stubs (scip.pyi) are updated for new or changed methods.
  • Docs and examples are updated, or a new docs section was added for new features (e.g. plugin types), or no user-facing behavior changed.

Testing

  • New code is covered by tests, including error paths.
  • If this touches expressions, model building or callbacks, /benchmark was run and shows no regression.
    /benchmark [filter] [timelimit=seconds], e.g. /benchmark expr or plugin. Locally: pytest benchmarks.

Does this PR introduce an API change? ⚠️

  • No, or it is backwards compatible, or the old behavior goes through a deprecation warning first.

Comment thread src/pyscipopt/expr.pxi
Comment on lines +371 to +379
cpdef double degree(self) except? -1:
cdef Expr expr = self.as_expr()
cdef double deg = 0, res = 0
cdef Term t
for t in expr.terms:
deg = len(t)
if deg > res:
res = deg
return res

@Zeroto521 Zeroto521 Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Benchmark (Python call, min of 5 runs):

  • 1000 terms: 71.6 us -> 9.3 us (7.7x)
  • 2 terms: 679 ns -> 151 ns (4.5x)

@Zeroto521

Zeroto521 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

The developer can't check/edit Reviewer checklist. This list should be put in .github/pull_request_template.md.

@codecov

codecov Bot commented Nov 24, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 59.59596% with 40 lines in your changes missing coverage. Please review.
✅ Project coverage is 57.58%. Comparing base (3653fbf) to head (8722916).
⚠️ Report is 12 commits behind head on master.

Files with missing lines Patch % Lines
src/pyscipopt/expr.pxi 58.57% 29 Missing ⚠️
src/pyscipopt/scip.pxi 72.00% 7 Missing ⚠️
src/pyscipopt/matrix.pxi 0.00% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1299      +/-   ##
==========================================
- Coverage   58.15%   57.58%   -0.57%     
==========================================
  Files          27       27              
  Lines        6012     6102      +90     
==========================================
+ Hits         3496     3514      +18     
- Misses       2516     2588      +72     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Joao-Dionisio

Copy link
Copy Markdown
Member

The developer can't check/edit Reviewer checklist.

This is on purpose, it's for the reviewer.

@Joao-Dionisio

Copy link
Copy Markdown
Member

/benchmark

@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

✅ /benchmark by @Joao-Dionisio: results

@Joao-Dionisio

Copy link
Copy Markdown
Member

(I'm running the benchmark just for fun, I really like it :) )

@github-actions

Copy link
Copy Markdown
Contributor

Results for /benchmark by @Joao-Dionisio

Benchmark results (base → PR)

⚠️ 11 regressions

Benchmark Instructions Time Peak memory Retained memory
test_evaluate_nonlinear 3.915 G → 4.226 G (+7.9%) 🔴 176 B → 176 B (+0.0%) 0 B → 0 B
test_expr_arithmetic 5.175 G → 5.182 G (+0.1%) 1.2 MB → 1.2 MB (+0.0%) 32 B → 32 B (+0.0%)
test_expr_ops 4.771 G → 4.690 G (-1.7%) 🟢 25.7 kB → 25.7 kB (+0.0%) 32 B → 32 B (+0.0%)
test_matrix_ops 6.398 G → 7.074 G (+10.6%) 🔴 71.5 MB → 71.5 MB (+0.0%) 1.3 kB → 1.3 kB (+3.8%)
test_nonlinear_expr 3.067 G → 3.167 G (+3.3%) 🔴 11.1 MB → 11.1 MB (+0.0%) 32 B → 32 B (+0.0%)
test_quadratic_expr 5.226 G → 5.374 G (+2.8%) 🔴 89.0 MB → 89.0 MB (+0.0%) 32 B → 32 B (+0.0%)
test_quicksum 4.199 G → 4.701 G (+11.9%) 🔴 10.0 MB → 10.0 MB (+0.0%) 32 B → 32 B (+0.0%)
test_repeated_terms 5.779 G → 6.398 G (+10.7%) 🔴 9.8 kB → 9.8 kB (+0.0%) 32 B → 32 B (+0.0%)
test_add_cons_linear 5.018 G → 5.032 G (+0.3%) 36.9 MB → 36.9 MB (+0.0%) 36.9 MB → 36.9 MB (+0.0%)
test_add_linear_conss 24.57 s → 23.58 s (-4.0%) 259.9 MB → 259.9 MB (-0.0%) 259.9 MB → 259.9 MB (-0.0%)
test_add_nonlinear_conss 5.800 G → 5.836 G (+0.6%) 2.4 MB → 2.4 MB (+0.0%) 2.4 MB → 2.4 MB (+0.0%)
test_add_vars 2.102 G → 1.760 G (-16.3%) 🟢 47.6 MB → 52.4 MB (+10.1%) 🔴 32 B → 32 B (+0.0%)
test_enum_getters 1.031 G → 1.031 G (+0.0%) 184 B → 184 B (+0.0%) 0 B → 0 B
test_getters_after_solve 5.158 G → 5.905 G (+14.5%) 🔴 176 B → 176 B (+0.0%) 0 B → 0 B
test_plugin_callbacks 3.374 G → 3.382 G (+0.2%) 15.9 kB → 17.4 kB (+9.0%) 15.0 kB → 16.5 kB (+9.6%)
test_branch_and_price_columns 10.72 s → 10.55 s (-1.6%) 95.4 MB → 105.0 MB (+10.1%) 🔴 95.4 MB → 105.0 MB (+10.1%) 🔴
test_many_small_models 8.595 G → 8.541 G (-0.6%) 931.7 kB → 917.6 kB (-1.5%) 104 B → 32 B (-69.2%)
test_modify_model 7.422 G → 7.478 G (+0.8%) 9.7 MB → 9.7 MB (+0.0%) 589.9 kB → 589.9 kB (+0.0%)
test_resolve_cycle 1.705 G → 1.753 G (+2.8%) 🔴 2.8 MB → 2.8 MB (+0.0%) 590.2 kB → 590.2 kB (+0.0%)

Instructions from callgrind, time is the best of several runs, memory is Python-side (tracemalloc). Flagged above 1% instructions, 20% time, 5% peak memory, 5% retained memory.

Against v6.3.0

v6.3.0 → PR

⚠️ 9 regressions

Benchmark Instructions Time Peak memory Retained memory
test_evaluate_nonlinear 4.474 G → 4.226 G (-5.5%) 🟢 200 B → 176 B (-12.0%) 0 B → 0 B
test_expr_arithmetic 5.175 G → 5.182 G (+0.1%) 1.2 MB → 1.2 MB (+0.0%) 32 B → 32 B (+0.0%)
test_expr_ops 6.225 G → 4.690 G (-24.7%) 🟢 137.7 kB → 25.7 kB (-81.3%) 🟢 96 B → 32 B (-66.7%)
test_matrix_ops 6.394 G → 7.074 G (+10.6%) 🔴 71.5 MB → 71.5 MB (+0.0%) 1.3 kB → 1.3 kB (+0.0%)
test_nonlinear_expr 3.147 G → 3.167 G (+0.6%) 12.2 MB → 11.1 MB (-9.2%) 🟢 32 B → 32 B (+0.0%)
test_quadratic_expr 6.872 G → 5.374 G (-21.8%) 🟢 89.0 MB → 89.0 MB (-0.0%) 96 B → 32 B (-66.7%)
test_quicksum 4.199 G → 4.701 G (+11.9%) 🔴 10.0 MB → 10.0 MB (+0.0%) 32 B → 32 B (+0.0%)
test_repeated_terms 5.780 G → 6.398 G (+10.7%) 🔴 9.8 kB → 9.8 kB (+0.0%) 32 B → 32 B (+0.0%)
test_add_cons_linear - → 5.032 G - → 36.9 MB - → 36.9 MB
test_add_linear_conss 24.87 s → 23.58 s (-5.2%) 259.9 MB → 259.9 MB (-0.0%) 259.9 MB → 259.9 MB (-0.0%)
test_add_nonlinear_conss 6.782 G → 5.836 G (-13.9%) 🟢 2.5 MB → 2.4 MB (-4.6%) 2.4 MB → 2.4 MB (-0.0%)
test_add_vars 3.005 G → 1.760 G (-41.4%) 🟢 47.6 MB → 52.4 MB (+10.1%) 🔴 32 B → 32 B (+0.0%)
test_enum_getters 593.125 M → 1.031 G (+73.8%) 🔴 184 B → 184 B (+0.0%) 0 B → 0 B
test_getters_after_solve 5.323 G → 5.905 G (+10.9%) 🔴 176 B → 176 B (+0.0%) 0 B → 0 B
test_plugin_callbacks 3.351 G → 3.382 G (+0.9%) 16.0 kB → 17.4 kB (+8.7%) 15.0 kB → 16.5 kB (+9.6%)
test_branch_and_price_columns 10.79 s → 10.55 s (-2.2%) 95.4 MB → 105.0 MB (+10.1%) 🔴 95.4 MB → 105.0 MB (+10.1%) 🔴
test_many_small_models 8.691 G → 8.541 G (-1.7%) 🟢 1.0 MB → 917.6 kB (-9.8%) 104 B → 32 B (-69.2%)
test_modify_model 7.580 G → 7.478 G (-1.4%) 🟢 9.7 MB → 9.7 MB (+0.0%) 589.9 kB → 589.9 kB (+0.0%)
test_resolve_cycle 1.730 G → 1.753 G (+1.3%) 🔴 2.8 MB → 2.8 MB (+0.0%) 590.2 kB → 590.2 kB (+0.0%)

Instructions from callgrind, time is the best of several runs, memory is Python-side (tracemalloc). Flagged above 1% instructions, 20% time, 5% peak memory, 5% retained memory.

Base 7d331b0dfbc106dee951e9c71eca1e6b34055789, PR 2c333ba3ca257c57bdfbac2a5a29cf6f9c534b01. Run

Comment thread src/pyscipopt/scip.pxi
Comment on lines +1565 to +1569
def __init__(self, *_):
raise NotImplementedError(
"Direct instantiation of 'Variable' is not supported. "
"Please use Model to create variables."
)

@Zeroto521 Zeroto521 Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See #1149, this PR is a part of that series. Variable requires a SCIP variable, so it can't be called by users directly. This prevents creating a Variable instance via Variable()

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants