-
Notifications
You must be signed in to change notification settings - Fork 9
fix: compatibility with linopy v1 arithmetic semantics #729
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
Draft
FBumann
wants to merge
8
commits into
main
Choose a base branch
from
linopy-v1-compat
base: main
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.
Draft
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
2bea718
fix: make modeling compatible with linopy v1 arithmetic semantics
FBumann fb885a8
docs: add linopy v1 semantics compatibility guide
FBumann 0269a53
refactor: build transmission & bus-balance constraints in one pass
FBumann de64faf
fix: keep constraint mutation working on linopy 0.7 and 0.8
FBumann 808b8e9
test: make degenerate clustered-storage SOC assertions robust
FBumann 61c1e6d
fix: drop scalar cluster_boundary coord in intercluster initial-SOC c…
FBumann 1f1756c
refactor: inline shift(-1) + legacy sel for adjacent-step constraints…
FBumann 1cf3a52
docs: update v1 guide to shift(-1)+legacy-sel and build-once/_set_con…
FBumann File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,186 @@ | ||
| # linopy v1 Semantics Compatibility | ||
|
|
||
| !!! info "Who this is for" | ||
| This is a **contributor / maintainer** guide. flixopt end users never | ||
| interact with linopy directly, so nothing in your models or scripts changes. | ||
| This page documents how flixopt's constraint-construction code stays correct | ||
| under linopy's upcoming *v1 arithmetic convention* and how to keep new code | ||
| compatible. | ||
|
|
||
| --- | ||
|
|
||
| ## Background | ||
|
|
||
| [linopy PR #717](https://github.com/PyPSA/linopy/pull/717) introduces a global | ||
| switch: | ||
|
|
||
| ```python | ||
| import linopy | ||
| linopy.options["semantics"] = "legacy" # current default | ||
| linopy.options["semantics"] = "v1" # opt-in; becomes default before linopy 1.0 | ||
| ``` | ||
|
|
||
| Legacy linopy silently *guessed* in three situations where a guess can quietly | ||
| change a model. **v1** replaces each silent guess with an explicit rule and | ||
| **raises** where legacy would have guessed, so a wrong model surfaces as a build | ||
| error instead of a wrong number at solve time: | ||
|
|
||
| | Legacy behaviour | Under v1 | | ||
| |---|---| | ||
| | Coordinate mismatch on a shared dim → aligned by position / inner join | **Raises** — align by label explicitly | | ||
| | A conflicting auxiliary (non-dimension) coordinate → silently dropped | **Raises** — drop or relabel explicitly | | ||
| | `NaN` in a constant / a shifted-in variable → filled with `0` (or `1` for `/`) | **Raises** / absence propagates | | ||
|
|
||
| flixopt builds and solves **identically** under both settings. The full test | ||
| suite is verified under both `"legacy"` and `"v1"`. | ||
|
|
||
| --- | ||
|
|
||
| ## The three patterns flixopt uses | ||
|
|
||
| ### 1. Adjacent-step constraints → `shift(-1)` + a legacy-only slice | ||
|
|
||
| Constraints that relate `x[t+1]` to `x[t]` (storage balance, on/off duration | ||
| tracking, state transitions, level tracking, linked-period sizing) used to slice | ||
| the same variable two ways: | ||
|
|
||
| ```python | ||
| x.isel(time=slice(1, None)) # x[t+1] — labels t[1:] | ||
| x.isel(time=slice(None, -1)) # x[t] — labels t[:-1] | ||
| ``` | ||
|
|
||
| The two slices carry **different labels** on `time`, so combining them is a | ||
| coordinate mismatch. Legacy aligned them by position; v1 raises. | ||
|
|
||
| **Fix:** express "next step" with `.shift({dim: -1})` — the v1-native form — and | ||
| pair it with a legacy-only boundary slice: | ||
|
|
||
| ```python | ||
| # Before (relies on legacy positional alignment): | ||
| x.isel(time=slice(1, None)) - x.isel(time=slice(None, -1)) | ||
|
|
||
| # After (identical under both semantics): | ||
| x.shift(time=-1).isel(time=slice(None, -1)) - x.isel(time=slice(None, -1)) | ||
| # ^^^^^^^^^^^^^^^^^^^^^^^^^^^ legacy-only (see below) | ||
| ``` | ||
|
|
||
| `x.shift({dim: -1})` places `x[t+1]` at position `t`. Under **v1** the | ||
| out-of-range boundary slot is marked *absent*, so that constraint row drops out | ||
| on its own — the shift alone is correct. Under **legacy** `.shift` instead | ||
| *fills* the boundary slot with `0`, leaving a spurious row, so the trailing | ||
| `.isel({dim: slice(None, -1)})` drops it. With the slice, both conventions | ||
| produce **identical** constraints. | ||
|
|
||
| !!! note "The `.isel(...)` is a legacy-only shim" | ||
| Pure `x - x.shift(...)` on its own is **not** identical across conventions — | ||
| that is exactly why the slice is there. But it is needed *only* for legacy: | ||
| once legacy support is dropped, every `.isel({dim: slice(None, -1)})` on a | ||
| shifted operand can be removed, leaving bare `.shift(...)` constraints (v1 | ||
| masks the boundary natively). flixopt marks each such slice as legacy-only | ||
| (see the module note in `modeling.py`) so the future cleanup is mechanical. | ||
|
|
||
| ### 2. Scalar-endpoint constraints → `drop=True` | ||
|
|
||
| A scalar integer index keeps the indexed coordinate as a **leftover scalar | ||
| aux-coord**: | ||
|
|
||
| ```python | ||
| x.isel(time=0) # drops the `time` *dimension*, keeps `time` = first timestamp | ||
| x.isel(time=-1) # keeps `time` = last timestamp | ||
| ``` | ||
|
|
||
| Cyclic / initial / final constraints compare two such endpoints: | ||
|
|
||
| ```python | ||
| x.isel(time=0) == x.isel(time=-1) # `time` = first vs last → conflict | ||
| ``` | ||
|
|
||
| Legacy silently drops the conflicting coord; v1 raises. **Fix:** pass | ||
| `drop=True` so the meaningless scalar coord never appears: | ||
|
|
||
| ```python | ||
| x.isel(time=0, drop=True) == x.isel(time=-1, drop=True) | ||
| ``` | ||
|
|
||
| This applies to any scalar `.isel(...)` whose result is combined with another | ||
| operand — `time`, `scenario`, `cluster_boundary`, and to a value *derived* from | ||
| such a select (e.g. `previous_status.isel(time=-1, drop=True)`). | ||
|
|
||
| ### 3. Constraint mutation → build once, or `_set_constraint_lhs` | ||
|
|
||
| The `Constraint.lhs` / `.rhs` **setters** are deprecated in linopy 0.8 (they were | ||
| the only mutation API in 0.7). Two cases: | ||
|
|
||
| **Prefer building the constraint in one pass** rather than creating it and then | ||
| mutating it. Where a term is only conditionally present, assemble the full LHS | ||
| first (this is what the transmission-loss and bus-balance constraints do now): | ||
|
|
||
| ```python | ||
| # Before: | ||
| con = model.add_constraints(a == b) | ||
| if extra: | ||
| con.lhs += term # deprecated setter | ||
|
|
||
| # After: | ||
| lhs = a | ||
| if extra: | ||
| lhs = lhs + term | ||
| con = model.add_constraints(lhs == b) | ||
| ``` | ||
|
|
||
| **For a genuine incremental accumulator** (e.g. the effect-share totals, which | ||
| are grown across the whole model build) mutation is unavoidable. Use the | ||
| `_set_constraint_lhs` shim, which works on **both** linopy versions — 0.8+ has | ||
| `Constraint.update(lhs=...)` (and deprecates the setter), while 0.7 has only the | ||
| setter (not deprecated there): | ||
|
|
||
| ```python | ||
| from flixopt.modeling import _set_constraint_lhs | ||
|
|
||
| _set_constraint_lhs(con, con.lhs - share) # update() on >=0.8, setter on <0.8 | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## Writing v1-safe constraints (checklist) | ||
|
|
||
| - Relating `x[t+1]` to `x[t]`? → write the next step as `x.shift({dim: -1})` and | ||
| add the legacy-only `.isel({dim: slice(None, -1)})`; never combine raw | ||
| `isel(slice(1, None))` with `isel(slice(None, -1))`. | ||
| - Scalar `.isel(dim=k)` whose result feeds arithmetic or a comparison? → add | ||
| `drop=True`. | ||
| - Mutating an existing constraint? → `con.update(lhs=...)`, not `con.lhs = ...`. | ||
| - Passing a plain numpy array / list into linopy arithmetic? → wrap it in a | ||
| named `DataArray` so it aligns by label, not by size. | ||
| - Never introduce a user-supplied `NaN` as a stand-in for "absent" — express | ||
| absence with `mask=` / `.where(...)` on the variable. | ||
|
|
||
| --- | ||
|
|
||
| ## Testing under v1 | ||
|
|
||
| Run the suite with the option flipped (e.g. via a `conftest`/plugin that sets | ||
| `linopy.options["semantics"] = "v1"` at configure time), and turn the legacy | ||
| warning into an error to surface every remaining site under legacy: | ||
|
|
||
| ```python | ||
| import warnings | ||
| from linopy import LinopySemanticsWarning | ||
| warnings.filterwarnings("error", category=LinopySemanticsWarning) | ||
| ``` | ||
|
|
||
| A green run under **both** `"legacy"` and `"v1"` is the compatibility contract. | ||
|
|
||
| --- | ||
|
|
||
| ## Known non-issue: cyclic-cluster SOC degeneracy | ||
|
|
||
| A handful of clustered-storage tests assert an exact absolute charge-state | ||
| trajectory. In `cluster_mode='cyclic'` the initial/final charge-state | ||
| constraints are intentionally skipped, so the **absolute** SOC level of each | ||
| representative cluster is unpinned — only the per-cluster *delta* is fixed. The | ||
| problem is therefore degenerate in the SOC level: multiple equally-optimal | ||
| solutions exist, and different solver/linopy builds may return a different (but | ||
| equally valid) vertex. Objective and all flow rates are unaffected. This is a | ||
| test-robustness matter, **independent of the semantics setting** (it reproduces | ||
| identically under `"legacy"` and `"v1"`). | ||
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
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
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
Oops, something went wrong.
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Update checklist to recommend the compatibility helper.
The checklist suggests using
con.update(lhs=...), but as explained earlier in the document, calling.update()directly will break compatibility withlinopy0.7. The checklist should instruct contributors to use the_set_constraint_lhshelper (or to assemble the LHS before constraint creation).📝 Proposed fix
📝 Committable suggestion
🤖 Prompt for AI Agents