-
Notifications
You must be signed in to change notification settings - Fork 72
feat: add piecewise linear constraint API (SOS2, incremental, disjunctive) #576
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
FBumann
wants to merge
19
commits into
PyPSA:master
Choose a base branch
from
FBumann:feat/add-piecewise-variants
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+3,191
−0
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add `add_piecewise_constraint` method to Model class that creates piecewise linear constraints using SOS2 formulation. Features: - Single Variable or LinearExpression support - Dict of Variables/Expressions for linking multiple quantities - Auto-detection of link_dim from breakpoints coordinates - NaN-based masking with skip_nan_check option for performance - Counter-based name generation for efficiency The SOS2 formulation creates: 1. Lambda variables with bounds [0, 1] for each breakpoint 2. SOS2 constraint ensuring at most two adjacent lambdas are non-zero 3. Convexity constraint: sum(lambda) = 1 4. Linking constraints: expr = sum(lambda * breakpoints)
…_SUFFIX = "_fill". linopy/model.py — - Added method: str = "sos2" parameter to add_piecewise_constraints() - Updated docstring with the new parameter and incremental formulation notes - Refactored: extracted _add_pwl_sos2() (existing SOS2 logic) and added _add_pwl_incremental() (new delta formulation) - Added _check_strict_monotonicity() static method - method="auto" checks monotonicity and picks accordingly - Numeric coordinate validation only enforced for SOS2 test/test_piecewise_constraints.py — Added TestIncrementalFormulation (10 tests) covering: single variable, two breakpoints, dict case, non-monotonic error, decreasing monotonic, auto-select incremental/sos2, invalid method, extra coordinates. Added TestIncrementalSolverIntegration (Gurobi-gated).
…f(dim).rename() 2. Filling-order constraints: replaced per-segment individual add_constraints calls with a single vectorized constraint via xr.concat + LinearExpression 3. Mask computation: replaced loop over segments with vectorized slice + rename 4. Coordinate lists: unified extra_coords/lambda_coords — lambda_coords = extra_coords + [bp_dim_index], eliminating duplicate list comprehensions
Files Modified
1. linopy/constants.py — Added 3 constants:
- PWL_BINARY_SUFFIX = "_binary"
- PWL_SELECT_SUFFIX = "_select"
- DEFAULT_SEGMENT_DIM = "segment"
2. linopy/model.py — Three changes:
- Updated imports to include the new constants
- Updated _resolve_pwl_link_dim with an optional exclude_dims parameter (backward-compatible) so auto-detection skips both dim and segment_dim
- Added _add_dpwl_sos2 private method implementing the disaggregated convex combination formulation (binary indicators, per-segment SOS2 lambdas, convexity, and linking
constraints)
- Added add_disjunctive_piecewise_constraints public method with full validation, mask computation, and dispatch
3. test/test_piecewise_constraints.py — Added 7 test classes with 17 tests:
- TestDisjunctiveBasicSingleVariable (3 tests) — equal segments, NaN padding, single-breakpoint segments
- TestDisjunctiveDictOfVariables (2 tests) — dict with segments, auto-detect link_dim
- TestDisjunctiveExtraDimensions (1 test) — extra generator dimension
- TestDisjunctiveValidationErrors (5 tests) — missing dim, missing segment_dim, same dim/segment_dim, non-numeric coords, invalid expr
- TestDisjunctiveNameGeneration (2 tests) — shared counter, custom name
- TestDisjunctiveLPFileOutput (1 test) — LP file contains SOS2 + binary sections
- TestDisjunctiveSolverIntegration (3 tests) — min/max picks correct segment, dict case with solver
Create dedicated documentation page covering all three PWL formulations: SOS2 (convex combination), incremental (delta), and disjunctive (disaggregated convex combination). Includes math formulations, usage examples, comparison table, generated variables reference, and solver compatibility. Update index.rst, api.rst, and sos-constraints.rst. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Add 17 new tests covering masking details, expression inputs, multi-dimensional cases, multi-breakpoint segments, and parametrized multi-solver testing. Disjunctive tests go from 17 to 34 unique methods. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
…variants # Conflicts: # doc/release_notes.rst
7 tasks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Piecewise Linear Constraints
Superset of #559 — includes the SOS2 formulation from that PR plus incremental and disjunctive methods.
Summary
add_piecewise_constraints(..., method="sos2")— general PWL for any breakpoint order, uses SOS2 variablesadd_piecewise_constraints(..., method="incremental")— pure LP for strictly monotonic breakpoints, no SOS2/binary variablesadd_disjunctive_piecewise_constraints(...)— for disconnected segments (forbidden zones), uses binary + SOS2method="auto"picks incremental when breakpoints are monotonic, SOS2 otherwiseFeatures
skip_nan_checkoptionTest plan
Checklist
doc/release_notes.rstof the upcoming release is included