### Installing Linopy Solvers Wrapper - Pip - Bash Source: https://github.com/pypsa/linopy/blob/master/doc/prerequisites.rst Command to install Linopy along with optional dependencies for supported solver wrappers using pip. Provides convenient interfaces for certain optimization solvers. ```bash pip install linopy[solvers] ``` -------------------------------- ### Installing Linopy - Pip - Bash Source: https://github.com/pypsa/linopy/blob/master/doc/prerequisites.rst Command to install the Linopy library using the pip package manager. Requires a working Python environment with pip installed. ```bash pip install linopy ``` -------------------------------- ### Installing Linopy - Conda - Bash Source: https://github.com/pypsa/linopy/blob/master/doc/prerequisites.rst Command to install the Linopy library using the conda package manager from the conda-forge channel. Requires a working conda environment. ```bash conda install -c conda-forge linopy ``` -------------------------------- ### Installing HiGHS Solver - Pip - Bash Source: https://github.com/pypsa/linopy/blob/master/doc/prerequisites.rst Command to install the HiGHS optimization solver using pip. HiGHS is a recommended, free, and open-source solver compatible with Linopy, though availability may vary by platform. ```bash pip install highspy ``` -------------------------------- ### Solving a Linopy Model - Python Source: https://github.com/pypsa/linopy/blob/master/examples/create-a-model.ipynb Invokes the `solve` method on the fully configured Linopy model `m`. This action triggers the optimization process, using an underlying solver (like CBC, GLPK, or Gurobi if installed and configured) to find the optimal values for the decision variables that minimize or maximize the objective function within the feasible region defined by the constraints. ```python m.solve() ``` -------------------------------- ### Initializing a Linopy Model - Python Source: https://github.com/pypsa/linopy/blob/master/examples/create-a-model.ipynb Imports the `Model` class from the `linopy` library and creates a new empty `Model` instance. This instance serves as the container for defining the entire optimization problem, including variables, constraints, and the objective function. ```python from linopy import Model m = Model() ``` -------------------------------- ### Listing Available Solvers in Linopy Source: https://github.com/pypsa/linopy/blob/master/examples/transport-tutorial.ipynb Imports the `linopy` library and prints the `available_solvers` attribute. This shows a list of optimization solvers installed and detected by linopy, which can be used to solve models. Requires the `linopy` library to be installed in the Python environment. ```python print(linopy.available_solvers) ``` -------------------------------- ### Installing Linopy with Pip | Bash Source: https://github.com/pypsa/linopy/blob/master/README.md Provides the command to install the linopy Python package using the pip package installer. This method fetches the library from the Python Package Index (PyPI). Ensure pip is installed and accessible in your environment. ```Bash pip install linopy ``` -------------------------------- ### Installing uv Tool | Bash Source: https://github.com/pypsa/linopy/blob/master/README.md Installs the 'uv' tool using pip within the activated virtual environment. uv is a fast Python package installer and resolver. This step is part of the development setup process for linopy. ```Bash pip install uv ``` -------------------------------- ### Installing Linopy Development Dependencies | Bash Source: https://github.com/pypsa/linopy/blob/master/README.md Installs the linopy package in editable mode (`-e`), linking it directly to the source code directory. It also installs the required development dependencies and solver dependencies specified by the `[dev,solvers]` extras using the 'uv' installer within the activated virtual environment. ```Bash uv pip install -e .[dev,solvers] ``` -------------------------------- ### Installing Linopy with Conda | Bash Source: https://github.com/pypsa/linopy/blob/master/README.md Provides the command to install the linopy Python package using the conda package manager. This method installs the library from the conda-forge channel, which is recommended for environments managed by Conda. Ensure Conda is installed. ```Bash conda install -c conda-forge linopy ``` -------------------------------- ### Running Linopy Tests | Bash Source: https://github.com/pypsa/linopy/blob/master/README.md Executes the test suite for the linopy library using the pytest framework. This command verifies that the local development setup and code changes function correctly by running automated tests. Requires pytest and test dependencies to be installed. ```Bash pytest ``` -------------------------------- ### Solving and Displaying Results in Pyomo Source: https://github.com/pypsa/linopy/blob/master/examples/transport-tutorial.ipynb Imports `SolverFactory`, creates a GLPK solver instance, and calls `solve(model)` to run the optimization. It then uses `results.write()` for standard output and calls a custom `pyomo_postprocess` function which displays variable solutions using `model.x.display()`. Requires a Pyomo model and the GLPK solver installed and accessible. ```python def pyomo_postprocess(options=None, instance=None, results=None): model.x.display() from pyomo.opt import SolverFactory opt = SolverFactory("glpk") results = opt.solve(model) # Sends results to stdout results.write() print("\nDisplaying Solution\n" + '-'*60) pyomo_postprocess(None, model, results) ``` -------------------------------- ### Defining Jupyter Notebook Link (nblink) Configuration Source: https://github.com/pypsa/linopy/blob/master/doc/contributing.rst This snippet shows the required content for an `.nblink` file. These files are used in the linopy documentation built with Sphinx to link to Jupyter notebook examples (`.ipynb`). The file contains a simple dictionary with a 'path' key, specifying the relative path from the documentation source file (`.nblink` file) to the actual notebook file. This allows the documentation to include and render the notebook. ```Configuration { 'path' : '../../examples/foo.ipynb' } ``` -------------------------------- ### Example of Double Logging Output in Bash Source: https://github.com/pypsa/linopy/blob/master/doc/gurobi-double-logging.rst This snippet shows an example of the duplicate log messages generated by the Gurobi solver when double logging occurs in the console output. It illustrates how the same log message appears twice. ```bash Total elapsed time = 498.27s [INFO] Total elapsed time = 498.27s ``` -------------------------------- ### Adding Variables to Linopy Model - Python Source: https://github.com/pypsa/linopy/blob/master/examples/create-a-model.ipynb Uses the `add_variables` method of the `Model` instance `m` to define two scalar variables, `x` and `y`. Both are given a lower bound of 0 and an optional name for easier identification and referencing within the model. ```python x = m.add_variables(lower=0, name="x") y = m.add_variables(lower=0, name="y"); ``` -------------------------------- ### Initializing and Solving Linopy Model Source: https://github.com/pypsa/linopy/blob/master/examples/manipulating-models.ipynb Sets up a basic linopy optimization model for demonstration. It defines time-indexed variables `x` and `y` with lower bounds, creates linear constraints using these variables and a factor series, sets an objective function, and then solves the model twice, displaying the solution plot. This snippet establishes the base model used for subsequent modification examples. ```python m = linopy.Model() time = pd.Index(range(10), name="time") x = m.add_variables( lower=0, coords=[time], name="x", ) y = m.add_variables(lower=0, coords=[time], name="y") factor = pd.Series(time, index=time) con1 = m.add_constraints(3 * x + 7 * y >= 10 * factor, name="con1") con2 = m.add_constraints(5 * x + 2 * y >= 3 * factor, name="con2") m.add_objective(x + 2 * y) m.solve() m.solve() sol = m.solution.to_dataframe() sol.plot(grid=True, ylabel="Optimal Value") ``` -------------------------------- ### Activating Python Virtual Environment | Bash Source: https://github.com/pypsa/linopy/blob/master/README.md Activates the previously created Python virtual environment named 'venv'. After activation, subsequent Python commands and installed packages will be managed within this isolated environment. The command varies slightly between operating systems. ```Bash source venv/bin/activate ``` -------------------------------- ### Adding Constraints to Linopy Model - Python Source: https://github.com/pypsa/linopy/blob/master/examples/create-a-model.ipynb Adds two defined constraint expressions, `3 * x + 7 * y >= 10` and `5 * x + 2 * y >= 3`, to the Linopy model `m`. The `add_constraints` method takes the expressions and incorporates them into the model's structure, defining the feasible region for the optimization problem. ```python m.add_constraints(3 * x + 7 * y >= 10) m.add_constraints(5 * x + 2 * y >= 3); ``` -------------------------------- ### Solving linopy Model with Gurobi (Python) Source: https://github.com/pypsa/linopy/blob/master/examples/infeasible-model.ipynb Attempts to solve the previously defined `linopy` model using the Gurobi solver. This step is expected to fail and report infeasibility due to the conflicting constraints in the model. Requires the Gurobi solver to be installed and configured. ```python m.solve(solver_name="gurobi") ``` -------------------------------- ### Defining Alternative Linopy Constraint Expression - Python Source: https://github.com/pypsa/linopy/blob/master/examples/create-a-model.ipynb Demonstrates an alternative way to write the same constraint expression as `3x + 7y - 10 >= 0`. Linopy automatically parses this expression and separates the terms containing variables on the left-hand side from the constant values on the right-hand side when the constraint is added to the model. ```python 3 * x + 7 * y - 10 >= 0 ``` -------------------------------- ### Displaying a Linopy Variable Object - Python Source: https://github.com/pypsa/linopy/blob/master/examples/create-a-model.ipynb Displays the `linopy.Variable` object `x` after it has been created and added to the model. In an interactive Python environment like a Jupyter notebook, this will typically show a representation of the variable object, including its name and dimensions. ```python x ``` -------------------------------- ### Defining a Linopy Constraint Expression - Python Source: https://github.com/pypsa/linopy/blob/master/examples/create-a-model.ipynb Creates a Linopy expression representing the constraint `3x + 7y >= 10` using the previously defined variable objects `x` and `y`. This expression is a temporary object that needs to be explicitly added to the model using `m.add_constraints` to become an active constraint. ```python 3 * x + 7 * y >= 10 ``` -------------------------------- ### Adding Objective Function to Linopy Model - Python Source: https://github.com/pypsa/linopy/blob/master/examples/create-a-model.ipynb Sets the objective function for the Linopy model `m` to minimize the expression `x + 2 * y`. The `add_objective` method takes an expression formed by variable objects and constants, which the solver will attempt to minimize (or maximize, if specified) while respecting the defined constraints. ```python m.add_objective(x + 2 * y) ``` -------------------------------- ### Solving the Linopy Model | Python Source: https://github.com/pypsa/linopy/blob/master/README.md Executes the optimization solver to find the optimal solution for the defined linear programming problem. This process determines the variable values that satisfy all constraints while minimizing (or maximizing) the objective function. Requires a solver to be installed and configured. ```Python m.solve() ``` -------------------------------- ### Creating Python Virtual Environment | Bash Source: https://github.com/pypsa/linopy/blob/master/README.md Creates a new isolated Python virtual environment named 'venv' in the current directory. This practice helps manage project-specific dependencies without interfering with the system's Python installation. Requires the `venv` module, usually bundled with Python 3. ```Bash python -m venv venv ``` -------------------------------- ### Accessing Solution of Linopy Variable (y) - Python Source: https://github.com/pypsa/linopy/blob/master/examples/create-a-model.ipynb Accesses the `solution` attribute of the Linopy variable object `y` after the model has been successfully solved. This attribute holds the optimal numerical value determined by the solver for variable `y`. The solution for scalar variables is typically stored within an xarray.Dataset. ```python y.solution ``` -------------------------------- ### Accessing Solution of Linopy Variable (x) - Python Source: https://github.com/pypsa/linopy/blob/master/examples/create-a-model.ipynb Accesses the `solution` attribute of the Linopy variable object `x` after the model has been successfully solved. This attribute holds the optimal numerical value determined by the solver for variable `x`. The solution for scalar variables is typically stored within an xarray.Dataset. ```python x.solution ``` -------------------------------- ### Setting Constraint RHS Source: https://github.com/pypsa/linopy/blob/master/examples/manipulating-models.ipynb Modifies the right-hand side (RHS) of a specific constraint (`con1`). The RHS can be set to a scalar value or a dimension-aligned pandas Series or xarray DataArray, allowing constraints to vary across dimensions or time steps. This example sets it using a series `factor` multiplied by a scalar. ```python con1.rhs = 8 * factor ``` -------------------------------- ### Adding Variable with Different Coordinates Linopy Python Source: https://github.com/pypsa/linopy/blob/master/examples/creating-expressions.ipynb Illustrates adding a new Linopy variable (`b`) to the model with the same dimension name ('time') and size as variable `x` but using a different pandas Index for coordinates. This sets up an example to demonstrate how Linopy handles operations between variables with identical dimension names but differing coordinate values. ```python other_time = pd.Index(range(10, 20), name="time") b = m.add_variables(coords=[other_time], name="b") b ``` -------------------------------- ### Creating and Activating Conda Environment (Bash) Source: https://github.com/pypsa/linopy/blob/master/benchmark/README.md This snippet provides the bash commands necessary to set up the required Python environment for running the linopy benchmark. It first creates a conda environment based on a specified YAML file (`environment.yaml` or `environment.fixed.yaml`) containing all package dependencies, and then activates the newly created environment to make its packages available. ```bash conda env create -f environment.yaml conda activate linopy-benchmark ``` -------------------------------- ### Initializing Plotting Environment Python Source: https://github.com/pypsa/linopy/blob/master/benchmark/notebooks/plot-benchmarks.py.ipynb Imports necessary libraries for data manipulation and plotting (matplotlib.pyplot, pandas, seaborn) and sets a seaborn theme ('paper', 'white') for consistent plot aesthetics. Commented lines show options for using LaTeX text and a sans-serif font. ```python import matplotlib.pyplot as plt import pandas as pd import seaborn as sns sns.set_theme("paper", "white") # plt.rc('text', usetex=True) # plt.rc('font', family='sans-serif') ``` -------------------------------- ### Creating Linopy Model Instance (Python) Source: https://github.com/pypsa/linopy/blob/master/examples/testing-framework.ipynb Initializes an empty `linopy.Model` instance. This model serves as the container for variables, constraints, and other components that will be added and subsequently tested. ```python m = linopy.Model() ``` -------------------------------- ### Creating Optimization Model with Pyomo (Python) Source: https://github.com/pypsa/linopy/blob/master/doc/syntax.rst This Python code snippet defines a function to create the optimization model using the Pyomo library. It uses a ConcreteModel, defines indexed variables and sets, and specifies the constraints and objective using rule functions. ```python from numpy import arange from pyomo.environ import ConcreteModel, Constraint, Objective, Set, Var def create_model(N): m = ConcreteModel() m.N = Set(initialize=arange(N)) m.x = Var(m.N, m.N, bounds=(None, None)) m.y = Var(m.N, m.N, bounds=(None, None)) def bound1(m, i, j): return m.x[(i, j)] - m.y[(i, j)] >= i def bound2(m, i, j): return m.x[(i, j)] + m.y[(i, j)] >= 0 def objective(m): return sum(2 * m.x[(i, j)] + m.y[(i, j)] for i in m.N for j in m.N) m.con1 = Constraint(m.N, m.N, rule=bound1) m.con2 = Constraint(m.N, m.N, rule=bound2) m.obj = Objective(rule=objective) return m ``` -------------------------------- ### Initializing Linopy Model and Variables Python Source: https://github.com/pypsa/linopy/blob/master/examples/creating-expressions.ipynb Demonstrates setting up a Linopy model by importing necessary libraries, defining dimensions using pandas Indexes, and adding variables with specified lower bounds and coordinates. Shows how to create variables with one (`x`) and two (`y`) dimensions attached to the model. ```python import pandas as pd import xarray as xr import linopy time = pd.Index(range(10), name="time") port = pd.Index(list("abcd"), name="port") m = linopy.Model() x = m.add_variables(lower=0, coords=[time], name="x") y = m.add_variables(lower=0, coords=[time, port], name="y") m ``` -------------------------------- ### Initializing Linopy Model Python Source: https://github.com/pypsa/linopy/blob/master/examples/creating-constraints.ipynb Imports the `Model` class from the `linopy` library and creates an instance named `m`. This model instance is required before adding variables or constraints. ```python from linopy import Model m = Model() ``` -------------------------------- ### Creating Optimization Model with JuMP (Julia) Source: https://github.com/pypsa/linopy/blob/master/doc/syntax.rst This Julia code snippet defines a function to create an optimization model using the JuMP library. It sets up a minimization problem with two sets of variables `x` and `y` indexed by N x N, subject to two linear inequality constraints. ```julia using JuMP function create_model(N) m = Model() @variable(m, x[1:N, 1:N]) @variable(m, y[1:N, 1:N]) @constraint(m, x - y .>= 0:(N-1)) @constraint(m, x + y .>= 0) @objective(m, Min, 2 * sum(x) + sum(y)) return m end ``` -------------------------------- ### Running Linopy Benchmark (Bash) Source: https://github.com/pypsa/linopy/blob/master/benchmark/README.md This bash command executes the Snakemake workflow defined in the directory. The workflow orchestrates the benchmarking process, running the specified optimization problems against different modeling packages. The `--cores 4` flag indicates that Snakemake should use up to 4 CPU cores for parallel execution, potentially speeding up the benchmark run. ```bash snakemake --cores 4 ``` -------------------------------- ### Creating a Linopy Model Locally - Python Source: https://github.com/pypsa/linopy/blob/master/examples/solve-on-remote.ipynb This snippet demonstrates how to define a basic optimization model using linopy on the local machine. It involves importing necessary modules, initializing a Model, adding variables, defining constraints, and setting an objective function. The resulting model is stored in the 'm' variable for subsequent steps. ```python from numpy import arange from xarray import DataArray from linopy import Model N = 10 m = Model() coords = [arange(N), arange(N)] x = m.add_variables(coords=coords, name="x") y = m.add_variables(coords=coords, name="y") m.add_constraints(x - y >= DataArray(arange(N))) m.add_constraints(x + y >= 0) m.add_objective((2 * x + y).sum()) m ``` -------------------------------- ### Initializing linopy Model and Variables (Python) Source: https://github.com/pypsa/linopy/blob/master/examples/migrating-from-pyomo.ipynb Sets up a basic `linopy` model instance and adds a multi-dimensional variable `x` using the `add_variables` method. The variable is defined over a set of coordinates specified by a Pandas `RangeIndex` and a list, with bounds set between 0 and 100. ```python import pandas as pd import linopy m = linopy.Model() coords = pd.RangeIndex(10), ["a", "b"] x = m.add_variables(0, 100, coords, name="x") x ``` -------------------------------- ### Initializing Linopy Model (Python) Source: https://github.com/pypsa/linopy/blob/master/examples/transport-tutorial.ipynb Imports the necessary `xarray` and `linopy` libraries and instantiates the main `linopy.Model` object, which will serve as the container for the optimization problem's variables, constraints, and objective function. This is the foundational step for building a model in Linopy. ```python # Import of linopy and related modules import xarray as xr import linopy # Creation of a Model m = linopy.Model() ``` -------------------------------- ### Creating Infeasible linopy Model (Python) Source: https://github.com/pypsa/linopy/blob/master/examples/infeasible-model.ipynb Demonstrates how to build a simple linear programming model using `linopy` with constraints that make it infeasible. It defines variables `x` and `y` over time and adds constraints `x <= 5`, `y <= 5`, and `x + y >= 12`, which cannot all be satisfied simultaneously. Requires `pandas` and `linopy`. ```python import pandas as pd import linopy m = linopy.Model() time = pd.RangeIndex(10, name="time") x = m.add_variables(lower=0, coords=[time], name="x") y = m.add_variables(lower=0, coords=[time], name="y") m.add_constraints(x <= 5) m.add_constraints(y <= 5) m.add_constraints(x + y >= 12) ``` -------------------------------- ### Initializing Linopy RemoteHandler - Python Source: https://github.com/pypsa/linopy/blob/master/examples/solve-on-remote.ipynb This code initializes the Linopy RemoteHandler, which manages the SSH connection to the remote server. It requires the remote host address and a valid username. The handler instance facilitates subsequent remote operations like environment activation and model solving. ```python from linopy import RemoteHandler host = "your.host.de" username = "username" handler = RemoteHandler(host, username=username) ``` -------------------------------- ### Importing Linopy Testing Functions (Python) Source: https://github.com/pypsa/linopy/blob/master/examples/testing-framework.ipynb Imports the necessary libraries, including `pandas` for data structures, the main `linopy` library, and specific assertion functions (`assert_conequal`, `assert_linequal`, `assert_varequal`) from `linopy.testing` for verifying `linopy` objects. ```python import pandas as pd import linopy from linopy.testing import assert_conequal, assert_linequal, assert_varequal ``` -------------------------------- ### Initializing Linopy Model and Variables | Python Source: https://github.com/pypsa/linopy/blob/master/README.md Imports necessary libraries (pandas, linopy), initializes a linopy model object, defines a pandas Index to represent coordinates ('day'), and adds continuous optimization variables ('apples', 'bananas') to the model with a lower bound of 0 and assigned coordinates. The output shows the representation of the created variable. ```Python import pandas as pd import linopy m = linopy.Model() days = pd.Index(['Mon', 'Tue', 'Wed', 'Thu', 'Fri'], name='day') apples = m.add_variables(lower=0, name='apples', coords=[days]) bananas = m.add_variables(lower=0, name='bananas', coords=[days]) apples ``` -------------------------------- ### Creating Optimization Model with linopy (Python) Source: https://github.com/pypsa/linopy/blob/master/doc/syntax.rst This Python code snippet defines a function to create the same optimization model using the linopy library. It adds variables with specified coordinates, defines constraints using linopy's syntax for linear expressions, and sets the objective function. ```python from linopy import Model from numpy import arange def create_model(N): m = Model() x = m.add_variables(coords=[arange(N), arange(N)]) y = m.add_variables(coords=[arange(N), arange(N)]) m.add_constraints(x - y >= arange(N)) m.add_constraints(x + y >= 0) m.add_objective((2 * x).sum() + y.sum()) return m ``` -------------------------------- ### Creating Simple Scalar linopy Constraint (Python) Source: https://github.com/pypsa/linopy/blob/master/examples/migrating-from-pyomo.ipynb Shows the creation of a basic scalar inequality constraint directly from a `ScalarVariable` obtained using the `.at[]` method. This operation results in an `AnonymousScalarConstraint` object, which represents a single constraint instance before being explicitly added to the model's collection of constraints. ```python x.at[0, "a"] <= 3 ``` -------------------------------- ### Printing Infeasible Constraints Directly (Python) Source: https://github.com/pypsa/linopy/blob/master/examples/infeasible-model.ipynb Shows a consolidated method, `print_infeasibilities()`, which combines the steps of computing and printing the infeasible constraints into a single function call. This provides a convenient way to diagnose infeasibility directly after attempting to solve the model. Requires the model to have been solved (or attempted to be solved). ```python m.print_infeasibilities() ``` -------------------------------- ### Initializing a Linopy Model (Python) Source: https://github.com/pypsa/linopy/blob/master/examples/create-a-model-with-coordinates.ipynb Imports the linopy library and creates a new Model instance. This model object will serve as the container for defining variables, constraints, and the objective function of the linear programming problem. ```python import linopy m = linopy.Model() ``` -------------------------------- ### Solving Linopy Model Remotely with RemoteHandler - Python Source: https://github.com/pypsa/linopy/blob/master/examples/solve-on-remote.ipynb This code initiates the model solving process on the remote server by passing the RemoteHandler instance as the 'remote' argument to the local model's solve method. Linopy handles the transfer of the model, execution of the solver on the remote machine, and retrieval of the solution. ```python m.solve(remote=handler) ``` -------------------------------- ### Asserting Expression Equality with assert_linequal (Python) Source: https://github.com/pypsa/linopy/blob/master/examples/testing-framework.ipynb Shows how to add another variable `y` and create a linear expression `expr` involving `x` and `y`. The `assert_linequal` function is then used to verify that the constructed expression `expr` is equivalent to an identical expression created directly from `x` and `y`. ```python y = m.add_variables(coords=[pd.RangeIndex(10, name="first")], name="y") expr = 2 * x + y assert_linequal(expr, 2 * x + y) ``` -------------------------------- ### Solving Linopy Model Source: https://github.com/pypsa/linopy/blob/master/examples/transport-tutorial.ipynb Calls the `solve()` method on the linopy model object `m`. This executes the optimization process using the selected solver to find the optimal variable values. Requires a complete linopy model `m` with defined variables, constraints, and objective function. ```python m.solve() ``` -------------------------------- ### Creating linopy Linear Expression with Function (Python) Source: https://github.com/pypsa/linopy/blob/master/examples/migrating-from-pyomo.ipynb Illustrates how to create a multi-dimensional linear expression (`expr`) in linopy by defining a Python function (`bound`) that returns a `ScalarLinearExpression` for given coordinates `i` and `j`. The `m.linexpr` method is then used to apply this function over the specified `coords` to generate the collection of scalar expressions. ```python def bound(m, i, j): if i % 2: return (i / 2) * x.at[i, j] else: return i * x.at[i, j] expr = m.linexpr(bound, coords) expr ``` -------------------------------- ### Printing Infeasible Constraints by Label (Python) Source: https://github.com/pypsa/linopy/blob/master/examples/infeasible-model.ipynb Utilizes the `print_labels()` method of the model's constraints object, passing the list of infeasible constraint labels obtained from `compute_infeasibilities()`. This displays the actual constraint expressions that were identified as infeasible. Requires the list of labels computed in the previous step. ```python m.constraints.print_labels(labels) ``` -------------------------------- ### Adding linopy Constraints with Function (Python) Source: https://github.com/pypsa/linopy/blob/master/examples/migrating-from-pyomo.ipynb Demonstrates how to add a set of constraints to the linopy model (`m`) using the `m.add_constraints` method with a function (`bound`) and coordinates. The function is defined to return an `AnonymousScalarConstraint` (either inequality or equality) based on the variable and coordinates, and `add_constraints` applies it over the `coords` to create and add the collection of constraints to the model. ```python def bound(m, i, j): if i % 2: return (i / 2) * x.at[i, j] >= i else: return i * x.at[i, j] == 0.0 con = m.add_constraints(bound, coords=coords) con ``` -------------------------------- ### Accessing Scalar linopy Variable with .at[] (Python) Source: https://github.com/pypsa/linopy/blob/master/examples/migrating-from-pyomo.ipynb Demonstrates how to access a specific scalar variable instance from the multi-dimensional variable `x` using the `.at[]` indexing method. This method is the recommended way to retrieve individual `ScalarVariable` objects for use in expressions or constraints, replacing the deprecated `[]` operator for this purpose. ```python x.at[0, "a"] ``` -------------------------------- ### Forming Supply Constraint Expression (Linopy/xarray, Python) Source: https://github.com/pypsa/linopy/blob/master/examples/transport-tutorial.ipynb Demonstrates how to construct the mathematical expression for the supply constraint using the xarray `sum` method. This line calculates the total shipments from each plant by summing the variable `x` across the 'Markets' dimension and compares it to the plant capacity parameter `a`, creating an xarray object representing the constraint expression before it is added to the model. ```python x.sum(dim="Markets") <= a ``` -------------------------------- ### Selecting and Adding Variable Subsets with .loc Linopy Python Source: https://github.com/pypsa/linopy/blob/master/examples/creating-expressions.ipynb Shows selecting subsets of two different Linopy variables (`x` and `y`) using `.loc` with the same index slice (first 5 elements) along the 'time' dimension and then performing element-wise addition on the resulting sub-expressions. ```python x.loc[:5] + y.loc[:5] ``` -------------------------------- ### Applying .rolling and Aggregation Linopy Python Source: https://github.com/pypsa/linopy/blob/master/examples/creating-expressions.ipynb Demonstrates using the `.rolling` method on a Linopy variable (`x`) to create rolling windows of a specified size (`time=3`) along the 'time' dimension. It then applies an aggregation function (`.sum()`) to each window, resulting in an expression representing the rolling sum. ```python x.rolling(time=3).sum() ``` -------------------------------- ### Accessing All Model Constraints Linopy Python Source: https://github.com/pypsa/linopy/blob/master/examples/creating-constraints.ipynb Accesses and displays the container object (`.constraints`) within the model instance `m` that holds all constraints that have been successfully added to the model. ```python m.constraints ``` -------------------------------- ### Adding Objective Function in Linopy Source: https://github.com/pypsa/linopy/blob/master/examples/transport-tutorial.ipynb Defines the objective function `obj` as the total cost `c * x`. Adds `obj` to the linopy model `m` for optimization (minimization). Requires a pre-configured linopy model `m` with defined variables `x` and parameters `c` representing costs. ```python obj = c * x m.add_objective(obj) ``` -------------------------------- ### Defining Problem Sets (Python) Source: https://github.com/pypsa/linopy/blob/master/examples/transport-tutorial.ipynb Defines the sets representing the canning plants (`i`) and markets (`j`) using standard Python dictionaries. These dictionaries are structured to specify dimension names and their corresponding labels, facilitating their use as coordinates within xarray DataArrays for parameters and variables. ```python ## Define sets ## # Sets # i canning plants / seattle, san-diego / # j markets / new-york, chicago, topeka / ; i = {"Canning Plants": ["seattle", "san-diego"]} j = {"Markets": ["new-york", "chicago", "topeka"]} ``` -------------------------------- ### Creating Expression with Constant Linopy Python Source: https://github.com/pypsa/linopy/blob/master/examples/creating-constraints.ipynb Creates and displays a linopy expression representing `3 * x - 10`. This expression is shown to demonstrate how linopy handles constants when they are on the left-hand side before a comparison operation. ```python 3 * x - 10 ``` -------------------------------- ### Asserting Variable Equality with assert_varequal (Python) Source: https://github.com/pypsa/linopy/blob/master/examples/testing-framework.ipynb Demonstrates adding a variable `x` to the model with specified coordinates. It then uses the `assert_varequal` function to confirm that the variable object `x` is equal to the variable accessed through the model's `variables` attribute, illustrating basic variable equality testing. ```python x = m.add_variables(coords=[pd.RangeIndex(10, name="first")], name="x") assert_varequal(x, m.variables.x) # or assert_varequal(x, m.variables["x"]) ``` -------------------------------- ### Accessing Specific Model Constraint Linopy Python Source: https://github.com/pypsa/linopy/blob/master/examples/creating-constraints.ipynb Accesses and displays the specific constraint object stored in the model `m` under the key "my-constraint". This demonstrates how to retrieve and inspect individual constraints after they have been added to the model. ```python m.constraints["my-constraint"] ``` -------------------------------- ### Selecting Expression Subset with .loc Linopy Python Source: https://github.com/pypsa/linopy/blob/master/examples/creating-expressions.ipynb Demonstrates applying the `.loc` accessor directly to a combined Linopy expression (`x + y`) to select a subset of the expression elements based on index slicing. This is equivalent to applying `.loc` to each variable before combining them. ```python expr = x + y expr.loc[:5] ``` -------------------------------- ### Asserting Constraint Equality with assert_conequal (Python) Source: https://github.com/pypsa/linopy/blob/master/examples/testing-framework.ipynb Illustrates adding a constraint `con` to the model based on the expression `expr`. The `assert_conequal` function is utilized to check if the created constraint object `con` is equal to the constraint accessed via the model's `constraints` attribute, verifying that the constraint was correctly added. ```python con = m.add_constraints(expr >= 3, name="con") assert_conequal(con, m.constraints.con) ``` -------------------------------- ### Computing Infeasible Constraints in linopy (Python) Source: https://github.com/pypsa/linopy/blob/master/examples/infeasible-model.ipynb Uses the `compute_infeasibilities()` method on the solved `linopy` model to identify and retrieve the labels of the constraints that contribute to the model's infeasibility. This method is currently supported for the Gurobi solver. It returns a list of constraint labels. ```python labels = m.compute_infeasibilities() labels ``` -------------------------------- ### Defining Problem Parameters (Linopy/xarray, Python) Source: https://github.com/pypsa/linopy/blob/master/examples/transport-tutorial.ipynb Defines the problem parameters: plant capacities (`a`), market demands (`b`), distance matrix (`d`), and freight cost (`f`). Parameters `a`, `b`, and `d` are created as xarray DataArrays, leveraging the previously defined sets `i` and `j` as coordinates for labeled access. The scalar freight cost `f` is defined as an integer. ```python ## Define parameters ## # Parameters # a(i) capacity of plant i in cases # / seattle 350 # san-diego 600 / # b(j) demand at market j in cases # / new-york 325 # chicago 300 # topeka 275 / ; # Table d(i,j) distance in thousands of miles # new-york chicago topeka # seattle 2.5 1.7 1.8 # san-diego 2.5 1.8 1.4 ; # Scalar f freight in dollars per case per thousand miles /90/ ; a = xr.DataArray([350, 600], coords=i, name="capacity of plant i in cases") b = xr.DataArray([325, 300, 275], coords=j, name="demand at market j in cases") d = xr.DataArray( [[2.5, 1.7, 1.8], [2.5, 1.8, 1.4]], coords=i | j, name="distance in thousands of miles", ) f = 90 # Freight in dollars per case per thousand miles # Access data using e.g.: # a.loc[{"Canning Plants":"seattle"}] # d.loc[{"Canning Plants":"seattle", "Markets":"new-york"}] ``` -------------------------------- ### Accessing Solved Linopy Model Solution - Python Source: https://github.com/pypsa/linopy/blob/master/examples/solve-on-remote.ipynb After the model has been solved, whether locally or remotely via the RemoteHandler, this snippet shows how to access the resulting solution data. The solution is available as the '.solution' attribute of the model object, containing the optimized variable values and potentially other solution details. ```python m.solution ``` -------------------------------- ### Plotting Time and Memory Performance FacetGrid Python Source: https://github.com/pypsa/linopy/blob/master/benchmark/notebooks/plot-benchmarks.py.ipynb Generates a seaborn FacetGrid plot to visualize 'Time' and 'Memory' performance ('value') against 'Number of Variables', using 'kind' to separate the plots into rows and 'API' for hue and style. It dynamically sets the y-axis labels based on the `snakemake.wildcards["kind"]` and saves the resulting figure to a file path provided by `snakemake.output.time_memory`. ```python if snakemake.wildcards["kind"] == "overhead": labels = ["Overhead time (s)", "Overhead memory (MB)"] else: labels = ["Time (s)", "Memory (MB)"] g = sns.FacetGrid(data=df, row="kind", sharey=False, height=2.0, aspect=2) g.map_dataframe( sns.lineplot, x="Number of Variables", y="value", hue="API", style="API", marker=".", legend="full", zorder=8, ) for ax, label in zip(g.axes.ravel(), labels): ax.set_ylabel(label) ax.set_title("") ax.grid(axis="y", lw=0.2, color="grey", zorder=3, alpha=0.4) g.fig.tight_layout() g.add_legend() g.fig.savefig( snakemake.output.time_memory, bbox_inches="tight", pad_inches=0.1, dpi=300 ) ``` -------------------------------- ### Applying .groupby and Aggregation Linopy Python Source: https://github.com/pypsa/linopy/blob/master/examples/creating-expressions.ipynb Shows how to group a Linopy expression (`x + y`) using the `.groupby` method with a pandas Series as the grouping key based on time steps. It then applies an aggregation function (`.sum()`) to the resulting groups, creating an expression aggregated over the defined groups. ```python group_key = pd.Series(time.values // 2, index=time) (x + y).groupby(group_key).sum() ``` -------------------------------- ### Defining Objective Rule in Pyomo Source: https://github.com/pypsa/linopy/blob/master/examples/transport-tutorial.ipynb Defines the `objective_rule` function to calculate the sum of `c[i,j] * x[i,j]` over relevant indices. Assigns this rule to `model.objective` with `sense=minimize` to define the optimization goal in Pyomo. Requires a Pyomo model object with indexed parameters `c` and variables `x` defined. ```python def objective_rule(model): return sum(model.c[i,j]*model.x[i,j] for i in model.i for j in model.j) model.objective = Objective(rule=objective_rule, sense=minimize, doc='Define objective function') ``` -------------------------------- ### Adding Supply and Demand Constraints (Linopy, Python) Source: https://github.com/pypsa/linopy/blob/master/examples/transport-tutorial.ipynb Defines and adds the supply and demand constraints to the Linopy model `m`. The supply constraint ensures the total shipments from each plant do not exceed its capacity, while the demand constraint ensures the total shipments to each market meet its demand. Constraint expressions are formed using xarray's sum and comparison operators and then registered with the model. ```python ## Define contraints ## # supply(i) observe supply limit at plant i # supply(i) .. sum (j, x(i,j)) =l= a(i) # demand(j) satisfy demand at market j ; # demand(j) .. sum(i, x(i,j)) =g= b(j); con = x.sum(dim="Markets") <= a con1 = m.add_constraints(con, name="Observe supply limit at plant i") con = x.sum(dim="Canning Plants") >= b con2 = m.add_constraints(con, name="Satisfy demand at market j") ``` -------------------------------- ### Combining Variable Subsets with Different Slices Linopy Python Source: https://github.com/pypsa/linopy/blob/master/examples/creating-expressions.ipynb Illustrates selecting subsets of two Linopy variables (`x` and `y`) using `.loc` with different index slices along the 'time' dimension (first 5 for `x`, elements from index 5 onwards for `y`) and then adding the resulting sub-expressions. This demonstrates combining potentially non-overlapping selections. ```python x.loc[:4] + y.loc[5:] ``` -------------------------------- ### Displaying Solution as Pandas DataFrame | Python Source: https://github.com/pypsa/linopy/blob/master/README.md Retrieves the optimal solution values for all variables from the solved model. The .to_pandas() method converts these solution values into a pandas DataFrame, providing a convenient tabular format for inspecting the results. ```Python m.solution.to_pandas() ``` -------------------------------- ### Executing Remote Shell Command with RemoteHandler - Python Source: https://github.com/pypsa/linopy/blob/master/examples/solve-on-remote.ipynb This snippet demonstrates how to execute a shell command on the remote server through the RemoteHandler's execute method. It's used here to activate a specific conda environment named 'linopy-env', ensuring the remote environment is set up correctly for running linopy. ```python handler.execute("conda activate linopy-env") ``` -------------------------------- ### Asserting Constraint Equality with Unassigned Expression (Python) Source: https://github.com/pypsa/linopy/blob/master/examples/testing-framework.ipynb Provides a workaround to compare an assigned constraint object with its original unassigned expression form. It uses `assert_conequal` to compare the initial expression (`expr >= 3`) with a constraint derived by combining the left-hand side (`lhs`) and right-hand side (`rhs`) of the assigned constraint object `con`. ```python assert_conequal(expr >= 3, con.lhs >= con.rhs) ``` -------------------------------- ### Adding Coordinated Constraints to Linopy Model (Python) Source: https://github.com/pypsa/linopy/blob/master/examples/create-a-model-with-coordinates.ipynb Takes the formulated linear expression inequalities involving coordinated variables and adds them as named constraints ('con1', 'con2') to the linopy model 'm'. This incorporates the defined relationships for each time step into the optimization problem. ```python con1 = m.add_constraints(3 * x + 7 * y >= 10 * factor, name="con1") con2 = m.add_constraints(5 * x + 2 * y >= 3 * factor, name="con2") m ``` -------------------------------- ### Plotting Computational Resource Metric Python Source: https://github.com/pypsa/linopy/blob/master/benchmark/notebooks/plot-benchmarks.py.ipynb Calculates a 'Resource' metric by multiplying the 'Time' and 'Memory' columns in the original data. It then melts this 'Resource' column and creates a standard seaborn line plot showing 'Resource' against 'Number of Variables', separated by 'API'. The y-axis label is set based on the `snakemake.wildcards["kind"]`, and the plot is saved to the file path from `snakemake.output.resource`. ```python if snakemake.wildcards["kind"] == "overhead": label = "Computational overhead [MBs]" else: label = "Computational resource [MBs]" df = data.assign(Resource=data["Time"] * data["Memory"]) cols = ["Resource"] df = df.melt(id_vars=df.columns.drop(cols), value_vars=cols, var_name="kind") fig, ax = plt.subplots(figsize=(6, 3)) sns.lineplot( data=df, x="Number of Variables", y="value", hue="API", style="API", marker=".", legend="full", zorder=8, ) sns.despine() ax.set_ylabel(label) ax.set_title("") plt.ticklabel_format(axis="both", style="sci", scilimits=(3, 3)) ax.grid(axis="y", lw=0.2, color="grey", zorder=3, alpha=0.4) fig.tight_layout() fig.savefig(snakemake.output.resource, bbox_inches="tight", pad_inches=0.1, dpi=300) ``` -------------------------------- ### Importing Linopy Libraries Source: https://github.com/pypsa/linopy/blob/master/examples/manipulating-models.ipynb Imports the necessary Python libraries: `pandas` for data manipulation, `xarray` for labeled multi-dimensional arrays, and `linopy` for creating and solving linear optimization models. These imports are required to build and interact with linopy models. ```python import pandas as pd import xarray as xr import linopy ``` -------------------------------- ### Solving the Linopy Model (Python) Source: https://github.com/pypsa/linopy/blob/master/examples/create-a-model-with-coordinates.ipynb Invokes the solver associated with the linopy model 'm'. This attempts to find the optimal values for all coordinated variables that minimize the objective function while satisfying all added constraints. ```python m.solve() ``` -------------------------------- ### Displaying Variable Solution in Linopy Source: https://github.com/pypsa/linopy/blob/master/examples/transport-tutorial.ipynb Accesses the `.solution` attribute of the linopy variable object `x`. This provides an `xarray.DataArray` containing the optimal values for variable `x` after the model has been successfully solved. Requires the linopy model containing `x` to have been solved beforehand. ```python x.solution ``` -------------------------------- ### Applying .shift on Variable Linopy Python Source: https://github.com/pypsa/linopy/blob/master/examples/creating-expressions.ipynb Demonstrates using the `.shift` method on a Linopy variable (`y`) to create an expression where elements are shifted by a specified offset (`time=1`) along a dimension ('time'). Shows subtracting the shifted variable from the original, which can be used to model time delays or differences. ```python y - y.shift(time=1) ``` -------------------------------- ### Defining Objective Function | Python Source: https://github.com/pypsa/linopy/blob/master/README.md Defines the prices for apples and bananas for each day and sets the model's objective function. The objective is a linear expression representing the total cost, calculated by multiplying variable arrays by price arrays and summing the result. Linopy minimizes or maximizes this objective. ```Python apple_price = [1, 1.5, 1, 2, 1] banana_price = [1, 1, 0.5, 1, 0.5] m.objective = apple_price * apples + banana_price * bananas ``` -------------------------------- ### Formulating a Coordinated Constraint Expression (Python) Source: https://github.com/pypsa/linopy/blob/master/examples/create-a-model-with-coordinates.ipynb Creates a pandas Series 'factor' indexed by time, which is used as a time-dependent value on the right-hand side of a constraint. It then constructs a linear expression inequality using the previously defined coordinated variables 'x', 'y', and the 'factor' Series, demonstrating how coordinated objects interact in expressions. ```python factor = pd.Series(time, index=time) 3 * x + 7 * y >= 10 * factor ``` -------------------------------- ### Selecting Variable Subset with .loc Linopy Python Source: https://github.com/pypsa/linopy/blob/master/examples/creating-expressions.ipynb Demonstrates using the `.loc` accessor on a Linopy variable (`x`) to select elements based on pandas-like index slicing along its dimension ('time'). This operation returns a new expression representing the specified subset of the original variable. ```python x.loc[:5] ``` -------------------------------- ### Adding Daily Constraints | Python Source: https://github.com/pypsa/linopy/blob/master/README.md Adds a set of linear constraints to the linopy model. This constraint applies independently to each element along the 'day' coordinate, ensuring that a weighted sum of 'apples' and 'bananas' meets a minimum value for each day. It leverages linopy's support for array-like operations on variables. ```Python m.add_constraints(3 * apples + 2 * bananas >= 8, name='daily_vitamins') ``` -------------------------------- ### Performing Variable Multiplication Linopy Python Source: https://github.com/pypsa/linopy/blob/master/examples/creating-expressions.ipynb Shows element-wise multiplication between two Linopy variables (`x` and `y`) using the `*` operator. Note that multiplying two variables results in a QuadraticExpression, which captures the product terms. ```python z = x * y z ``` -------------------------------- ### Visualizing Coordinated Variable Solution (Python) Source: https://github.com/pypsa/linopy/blob/master/examples/create-a-model-with-coordinates.ipynb Accesses the optimal solution stored in the model ('m.solution'), which contains the optimal values for all variables, including those indexed by time. It converts this solution into a pandas DataFrame for easy handling and then plots the solution values over time using pandas/matplotlib plotting capabilities, visualizing the time-dependent optimal result. ```python m.solution.to_dataframe().plot(grid=True, ylabel="Optimal Value"); ``` -------------------------------- ### Performing Variable Addition Linopy Python Source: https://github.com/pypsa/linopy/blob/master/examples/creating-expressions.ipynb Shows how to perform element-wise addition between two Linopy variables (`x` and `y`) using the `+` operator. Notes that variable `x` is broadcasted to match the dimensions of variable `y`, and the result is a LinearExpression with the dimensions of `y`. ```python z = x + y z ``` -------------------------------- ### Displaying Linopy Solution Dataframe Source: https://github.com/pypsa/linopy/blob/master/examples/manipulating-models.ipynb Displays the contents of the `sol` variable, which holds the optimal values for the model's variables after a successful solve operation. The solution is typically stored in a pandas DataFrame, indexed by the model's dimensions, allowing for inspection of the results. ```python sol ```