|
235 | 235 | { |
236 | 236 | "cell_type": "markdown", |
237 | 237 | "id": "r0wxi7v1m7l", |
238 | | - "source": "## Coordinate Alignment in Constraints\n\nAs an alternative to the ``<=``, ``>=``, ``==`` operators, linopy provides ``.le()``, ``.ge()``, and ``.eq()`` methods on variables and expressions. These methods accept a ``join`` parameter (``\"inner\"``, ``\"outer\"``, ``\"left\"``, ``\"right\"``) for explicit control over how coordinates are aligned when creating constraints. See the :doc:`coordinate-alignment` guide for details.", |
| 238 | + "metadata": {}, |
| 239 | + "source": "## Coordinate Alignment in Constraints\n\nAs an alternative to the ``<=``, ``>=``, ``==`` operators, linopy provides ``.le()``, ``.ge()``, and ``.eq()`` methods on variables and expressions. These methods accept a ``join`` parameter (``\"inner\"``, ``\"outer\"``, ``\"left\"``, ``\"right\"``) for explicit control over how coordinates are aligned when creating constraints. See the :doc:`coordinate-alignment` guide for details." |
| 240 | + }, |
| 241 | + { |
| 242 | + "cell_type": "markdown", |
| 243 | + "id": "csr-backend-intro", |
| 244 | + "metadata": {}, |
| 245 | + "source": [ |
| 246 | + "## CSR Backend (Advanced)\n", |
| 247 | + "\n", |
| 248 | + "By default, linopy stores each constraint as an `xarray.Dataset` (`Constraint`). This is flexible and allows full label-based indexing, but can use significant memory when constraints have many terms.\n", |
| 249 | + "\n", |
| 250 | + "For large models, linopy provides an alternative **CSR backend** via the `CSRConstraint` class. It stores the constraint coefficients as a [scipy CSR sparse matrix](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_array.html) with flat numpy arrays for the right-hand side and signs. This can reduce memory usage by up to **90%** and speeds up matrix generation for direct solver APIs by **30–120x**.\n", |
| 251 | + "\n", |
| 252 | + "`CSRConstraint` is **immutable** — once frozen, the constraint data cannot be modified in place. You can always convert back to the mutable xarray-backed `Constraint` if needed." |
| 253 | + ] |
| 254 | + }, |
| 255 | + { |
| 256 | + "cell_type": "markdown", |
| 257 | + "id": "csr-per-constraint", |
| 258 | + "metadata": {}, |
| 259 | + "source": [ |
| 260 | + "### Freezing individual constraints\n", |
| 261 | + "\n", |
| 262 | + "Pass `freeze=True` to `add_constraints` to store a single constraint in CSR format:" |
| 263 | + ] |
| 264 | + }, |
| 265 | + { |
| 266 | + "cell_type": "code", |
| 267 | + "execution_count": null, |
| 268 | + "id": "csr-per-constraint-code", |
| 269 | + "metadata": {}, |
| 270 | + "outputs": [], |
| 271 | + "source": [ |
| 272 | + "import numpy as np\n", |
| 273 | + "\n", |
| 274 | + "from linopy import Model\n", |
| 275 | + "\n", |
| 276 | + "m2 = Model()\n", |
| 277 | + "y = m2.add_variables(coords=[np.arange(100)], name=\"y\")\n", |
| 278 | + "\n", |
| 279 | + "m2.add_constraints(y <= 10, name=\"upper\", freeze=True)\n", |
| 280 | + "\n", |
| 281 | + "print(type(m2.constraints[\"upper\"]))\n", |
| 282 | + "m2.constraints[\"upper\"]" |
| 283 | + ] |
| 284 | + }, |
| 285 | + { |
| 286 | + "cell_type": "markdown", |
| 287 | + "id": "csr-global", |
| 288 | + "metadata": {}, |
| 289 | + "source": [ |
| 290 | + "### Freezing all constraints globally\n", |
| 291 | + "\n", |
| 292 | + "Set `freeze_constraints=True` on the `Model` to automatically freeze every constraint added via `add_constraints`:" |
| 293 | + ] |
| 294 | + }, |
| 295 | + { |
| 296 | + "cell_type": "code", |
| 297 | + "execution_count": null, |
| 298 | + "id": "csr-global-code", |
| 299 | + "metadata": {}, |
| 300 | + "outputs": [], |
| 301 | + "source": [ |
| 302 | + "m3 = Model(freeze_constraints=True)\n", |
| 303 | + "z = m3.add_variables(coords=[np.arange(50)], name=\"z\")\n", |
| 304 | + "m3.add_constraints(z >= 0, name=\"lower\")\n", |
| 305 | + "m3.add_constraints(z <= 100, name=\"upper\")\n", |
| 306 | + "\n", |
| 307 | + "print(type(m3.constraints[\"lower\"]))\n", |
| 308 | + "print(type(m3.constraints[\"upper\"]))" |
| 309 | + ] |
| 310 | + }, |
| 311 | + { |
| 312 | + "cell_type": "markdown", |
| 313 | + "id": "csr-roundtrip", |
| 314 | + "metadata": {}, |
| 315 | + "source": [ |
| 316 | + "### Converting between representations\n", |
| 317 | + "\n", |
| 318 | + "Use `.freeze()` and `.mutable()` to convert between the two representations. The conversion is lossless:" |
| 319 | + ] |
| 320 | + }, |
| 321 | + { |
| 322 | + "cell_type": "code", |
| 323 | + "execution_count": null, |
| 324 | + "id": "csr-roundtrip-code", |
| 325 | + "metadata": {}, |
| 326 | + "outputs": [], |
| 327 | + "source": [ |
| 328 | + "frozen = m3.constraints[\"lower\"]\n", |
| 329 | + "print(f\"Frozen type: {type(frozen).__name__}\")\n", |
| 330 | + "\n", |
| 331 | + "thawed = frozen.mutable()\n", |
| 332 | + "print(f\"Mutable type: {type(thawed).__name__}\")\n", |
| 333 | + "\n", |
| 334 | + "refrozen = thawed.freeze()\n", |
| 335 | + "print(f\"Re-frozen type: {type(refrozen).__name__}\")" |
| 336 | + ] |
| 337 | + }, |
| 338 | + { |
| 339 | + "cell_type": "markdown", |
| 340 | + "id": "7843d42c", |
| 341 | + "source": "### API differences from `Constraint`\n\n`CSRConstraint` deliberately exposes a narrower API than the xarray-backed `Constraint`:\n\n- **No in-place mutation.** Setters such as `con.coeffs = ...`, `con.vars = ...`, `con.sign = ...`, `con.rhs = ...`, and `con.lhs = ...` are only available on `Constraint`.\n- **No label-based indexing.** `con.loc[...]` is only available on `Constraint`.\n- **Accessing `.coeffs` / `.vars` triggers reconstruction.** On a `CSRConstraint` these properties rebuild the full xarray `Dataset` on demand and emit a `PerformanceWarning`. For solver-oriented workflows prefer `con.to_matrix()` or work with the CSR data directly.\n\nIf you need any of the above, call `.mutable()` first to get a `Constraint`:\n\n```python\ncon = m.constraints[\"my_constraint\"].mutable()\ncon.loc[{\"time\": 0}] # label-based indexing now available\ncon.rhs = 5 # mutation now available\n```", |
239 | 342 | "metadata": {} |
| 343 | + }, |
| 344 | + { |
| 345 | + "cell_type": "markdown", |
| 346 | + "id": "csr-when-to-use", |
| 347 | + "metadata": {}, |
| 348 | + "source": [ |
| 349 | + "### When to use the CSR backend\n", |
| 350 | + "\n", |
| 351 | + "The CSR backend is most beneficial when:\n", |
| 352 | + "\n", |
| 353 | + "- Your model has **many constraints with many terms**.\n", |
| 354 | + "- **Memory** is a bottleneck.\n", |
| 355 | + "- You use a **direct solver API** (e.g. HiGHS, Gurobi Python bindings) rather than file-based I/O.\n", |
| 356 | + "\n", |
| 357 | + "For small models the overhead is negligible and the default xarray-backed `Constraint` is perfectly fine.\n", |
| 358 | + "\n", |
| 359 | + "Additionally, if you don't need variable and constraint names in the solver (e.g. for batch solves), you can disable name export for extra speed:\n", |
| 360 | + "\n", |
| 361 | + "```python\n", |
| 362 | + "m = Model(freeze_constraints=True, set_names_in_solver_io=False)\n", |
| 363 | + "```" |
| 364 | + ] |
240 | 365 | } |
241 | 366 | ], |
242 | 367 | "metadata": { |
|
0 commit comments