### BiqMac Example Setup Source: https://github.com/mosek/tutorials/blob/master/binary-quadratic/binquad.html This section introduces the BiqMac library for binary quadratic problems. It specifies that instances with n <= 100 are considered and highlights the use of a stronger termination criterion due to integral Q matrices. ```python mo.md(r""" # Example 2: BiqMac We next consider problems of the same form from the library [BiqMac](http://biqmac.aau.at/biqmaclib.html) of binary quadratic problems. We take all instances with $n\leq 100$. Since all the $Q$ matrices in BiqMac are integral, we can use a stronger termination criterion: """) return ``` -------------------------------- ### MOSEK K-Means Clustering Setup Source: https://github.com/mosek/tutorials/blob/master/kmeans-clustering/kmeans.html Initializes MOSEK's static configuration for a Python notebook, setting up file information and mount configuration for the KMeans clustering example. ```python window.__MARIMO__STATIC__ = {}; window.__MARIMO__STATIC__.files = {}; window.__MARIMO__MOUNT__CONFIG__ = { "filename": "kmeans.py", "mode": "read", "version": "0.18.4", "serverToken": "static", "config": { "ai": { "models": { "custom_models": [], "displayed_models": [] } }, "completion": { "activate_on_typing": true, "copilot": false }, "diagnostics": { "sql_linter": true }, "display": { "cell_output": "below", "code_editor_font_size": 14, "dataframes": "rich", "default_table_max_columns": 50, "default_table_page_size": 10, "default_width": "medium", "reference_highlighting": false, "theme": "light" }, "formatting": { "line_length": 79 }, "keymap": { "overrides": {}, "preset": "default" }, "language_servers": { "pylsp": { "enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": false } }, "mcp": { "mcpServers": {}, "presets": [] }, "package_management": { "manager": "pip" }, "runtime": { "auto_instantiate": false, "auto_reload": "off", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy" }, "save": { "autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false }, "server": { "browser": "default", "follow_symlink": false }, "snippets": { "custom_paths": [], "include_default_snippets": true } }, "configOverrides": {}, "appConfig": { "sql_output": "auto", "width": "compact" }, "view": { "showAppCode": true }, "notebook": { "cells": [ { "code": "mo.md(r\"\"\"!\n[MOSEK ApS](https://www.mosek.com/static/images/branding/webgraphmoseklogocolor.png )\"\"\"", "code_hash": "271c93fd1913447fc8645725a5909adb", "config": { "column": null, "disabled": false, "hide_code": true }, "id": "Hbol", "name": "_" }, { "code": "mo.md(\\n r\"\"\"\\n# Clustering using Disjunctive Constraints\\n\\n[K-Means clustering](https://en.wikipedia.org/wiki/K-means_clustering) is one of the most used clustering problems in unsupervised learning. Typically, a heuristic algorithm is used to solve the K-Means clustering problem. Such algorithms however do not guarantee a global optimum. In this notebook, we show how K-Means can be expressed as a Generalized Disjunctive Program (GDP) with a Quadratic Rotated Cone, and we demonstrate how to implement it in MOSEK using Disjunctive Constraints (DJC). Such problem was for example studied by [Papageorgiou, Trespalacios](https://link.springer.com/article/10.1007/s13675-017-0088-0) and [Kronqvist, Misener, Tsay](https://link.springer.com/chapter/10.1007/978-3-030-78230-6_19). We further show a modification called Euclidean clustering by changing only a few lines of code. \n\\nWe assume a set of points $\\textbf{p}\_1, \\ldots, \\textbf{p}n \\in \\mathbb{R}^\\mathcal{D}$ and a natural number $\\mathcal{K} \\in \\{1, 2, ..., n\\}$ which specifies number of centroids. We want to find positions of the centroids such that the overall squared Euclidean distance from each point to the closest centroid is minimized. The formulation using disjunctions can look as follows\n\n$$\\begin{array}{rll}\\n\\text{minimize} \\u0026 \\sum_{i=1}^n d_i & \\\\\\\n\\text{subject to} \\u0026 \\bigvee_{j \in \{1 ... \mathcal{K}}\ \Bigl[ d_i \gentrif || \bfpc_j - \bfpc_i ||_2^2 \wedge Y""", "code_hash": "8186414911304464811", "config": { "column": null, "disabled": false, "hide_code": false }, "id": "QhQn", "name": "Clustering using Disjunctive Constraints" } ] } } ``` -------------------------------- ### Huber Regression Example Setup Source: https://github.com/mosek/tutorials/blob/master/leastsquares/regression-leastsquares.html Provides introductory markdown text for a Huber regression example, highlighting its comparison with standard least-squares regression on data with outliers. ```markdown ### Huber regression example We demonstrate the Huber regression compared to standard least-squares regression on an example with distant outliers. ``` -------------------------------- ### Introduction to BiqMac Example with MOSEK Source: https://github.com/mosek/tutorials/blob/master/binary-quadratic/binquad.html Introduces Example 2: BiqMac, which considers binary quadratic problems from the BiqMac library and suggests a stronger termination criterion for integral matrices. ```python mo.md( r""" # Example 2: BiqMac We next consider problems of the same form from the library [BiqMac](http://biqmac.aau.at/biqmaclib.html) of binary quadratic problems. We take all instances with $n\leq 100$. Since all the $Q$ matrices in BiqMac are integral, we can use a stronger termination criterion: """ ) ``` -------------------------------- ### Market Setup Description (Markdown) Source: https://github.com/mosek/tutorials/blob/master/dist-robust-portfolio/Data-driven_distributionally_robust_portfolio.html Describes the market setup for simulations, including the number of assets, return distributions, and parameters for the uncertainty set and loss function. ```markdown mo.md( r""" ### Market setup The simulation results presented in the paper are based on a market with $m = 10$ assets. Each asset's return is expressed as $\\xi_i = \\psi + \\zeta_i$, where $\\psi \\sim \\mathcal{N}(0, 0.02)$ is the systematic risk factor and $\\zeta_i \\sim \\mathcal{N}(0.03\\times i, 0.025\\times i)$ is the idiosyncratic risk factor. By construction, assets with higher indices have higher risk as well as higher returns. The uncertainty set is $\\Xi \\in \\mathbb{R}^m$, thus $C$ and $d$ are set to zero. $1$-norm is used to define the Wasserstein ball, therefore the dual norm will be the $\\infty$-norm. Lastly, $\\alpha = 20\\%$ and $\\rho = 10$ are used within the loss function. """ ) ``` -------------------------------- ### Marimo App Setup Source: https://github.com/mosek/tutorials/blob/master/kmeans-clustering/kmeans.html Initializes the Marimo application and imports necessary libraries. ```python import marimo as mo return (mo,) ``` -------------------------------- ### Run Wasserstein Fusion Example Source: https://github.com/mosek/tutorials/blob/master/wasserstein/wasserstein-bary-reg.html An example demonstrating the usage of the Wasserstein_Fusion class to compute the regularized barycenter and print the time taken. ```python @app.cell def _(Wasserstein_Fusion, train): fusion_model = Wasserstein_Fusion() f_bc = fusion_model.Wasserstein_regBarycenter(train) print('%5%nTime%20Spent%20to%20solve%20problem%20with%20Fusion%3A%20%5Cn%20%7B0%7D'.format(fusion_model.time)) print('Time ``` -------------------------------- ### Markdown Description for Example 2 Source: https://github.com/mosek/tutorials/blob/master/f-sparc/fsparc.html Describes the second example, which uses a small, randomly generated dataset with 15 channels and 3 users. It notes that this example should be solved to optimality and mentions that the bar plot shows power assignments to channels, with each color representing a user. ```python mo.md( r""" The bar plot shows power assignments to the channels. Each color represents one user. # Example 2 The next example is a small, randomly generated set of data with 15 channels and 3 users, which we should solve to optimality. """ ) ``` -------------------------------- ### Executable Binary Quadratic Example Source: https://github.com/mosek/tutorials/blob/master/binary-quadratic/binquad.html A small, executable Python example demonstrating the use of the 'branchbound' library to solve a binary quadratic problem. It sets up a solver with a randomly generated quadratic matrix Q and a linear vector, then solves and summarizes the result. ```python import branchbound from branchbound import BB import numpy as np n=25 Q1 = np.random.normal(0.0, 1.0, (n,n)) solver = BB((Q1+Q1.transpose())/2, np.random.uniform(-1.0, 3.0, n), 0.0) solver.solve() solver.summary() return (np,) ``` -------------------------------- ### Run Example: Simple String Configuration Source: https://github.com/mosek/tutorials/blob/master/equilibrium/equilibrium.html Executes the string model with a basic configuration and displays the resulting shape. This is a simple test case to verify the model and display functions. ```python def _(): x, c = stringModel(w, l, f, g) if x is not None: return display(x, c, list(l.keys())) _() ``` -------------------------------- ### Initialize MOSEK Static Environment Source: https://github.com/mosek/tutorials/blob/master/pwl-convex-approximation/pwl-convex-approximation.html Initializes the MOSEK static environment for use in the notebook. This is a standard setup for MOSEK Python examples. ```python import mosek import numpy as np from mosek.fusion import * # MOSEK environment setup with Env() as env: env.set_Stream_func(stream.msg, lambda msg: print(msg)) with Model( ``` -------------------------------- ### Simulation Setup and Execution Source: https://github.com/mosek/tutorials/blob/master/dist-robust-portfolio/Data-driven_distributionally_robust_portfolio.html Sets up simulation parameters, generates synthetic data, instantiates the `SimSet1` class, runs the simulation, and prints initial solve times. ```python @app.cell def _(SimSet1, normal_returns, np): # Cardinality N = 300 # Number of simulations num_sim = 200 # Range of Wasserstein radii to consider epsilon_range = np.append(np.concatenate( [np.arange(1, 10)*10.0**(i) for i in range(-4, 0)] ), 1.0) # Making 200 independent datasets sim_data = [normal_returns(10, N) for i in range(num_sim)] # Instantiate SimSet1 class sim1 = SimSet1(N, epsilon_range) # 200 simulations... sim1.run_sim(sim_data) print("Time taken in initial solve of model with N={0}: {1:.4f} s".format( N, sim1.sol_time[0])) print("Mean time to" ``` -------------------------------- ### Import Necessary Libraries for Option Pricing Source: https://github.com/mosek/tutorials/blob/master/option-pricing/utility-option-pricing.html Imports essential libraries such as numpy for numerical operations, mosek.fusion for optimization modeling, and matplotlib for plotting. This setup is required for most of the subsequent code examples. ```python import numpy as np from mosek.fusion import Model, Domain, Expr, ObjectiveSense, Matrix, Var, SolutionStatus import sys import matplotlib.pyplot as plt import time ``` -------------------------------- ### Import necessary libraries for Mosek Fusion Source: https://github.com/mosek/tutorials/blob/master/approx-uncertain-ineq/hard_uncertain.html Imports essential libraries including numpy, scipy, and Mosek Fusion for numerical operations and optimization modeling. This setup is required for all subsequent code examples. ```python import numpy as np from numpy import random from mosek.fusion import Model, Domain, Expr, ObjectiveSense, Matrix, Var import mosek.fusion.pythonic import sys import scipy from scipy import sparse import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = [16, 9] ``` -------------------------------- ### Setup for Problem Instances Source: https://github.com/mosek/tutorials/blob/master/approx-uncertain-ineq/hard_uncertain.html Sets up parameters for generating problem instances, including the maximum length of the uncertain parameter and dimensions. ```python #Making instances of the problem with n=m=100 and L ranging from 1 to L_max. #Solve some initial ones exactly and others approximately #You can increase L_max, here we keep it small for the purpose of demonstration L_max = 10 t, tExact, n, m = L_max, 4, 100, 100 n_list = [n]*t m_list = [m]*t L_list = np.arange(1,t+1,1) return L_list, L_max, m_list, n_list, tExact ``` -------------------------------- ### Markdown Header for Small Executable Example Source: https://github.com/mosek/tutorials/blob/master/binary-quadratic/binquad.html Renders a markdown header for a small executable example section. ```python mo.md(r""# Small executable example""" ) ``` -------------------------------- ### Initialize Marimo Environment Source: https://github.com/mosek/tutorials/blob/master/wasserstein/wasserstein-bary-reg.html Sets up the Marimo environment with configuration for file handling and display settings. This is boilerplate for running Marimo notebooks. ```python window.__MARIMO_STATIC__ = {}; window.__MARIMO_STATIC__.files = {}; window.__MARIMO_MOUNT_CONFIG__ = { "filename": "wasserstein-bary-reg.py", "mode": "read", "version": "0.18.4", "serverToken": "static", "config": {"ai": {"models": {"custom_models": [], "displayed_models": []}}, "completion": {"activate_on_typing": true, "copilot": false}, "diagnostics": {"sql_linter": true}, "display": {"cell_output": "below", "code_editor_font_size": 14, "dataframes": "rich", "default_table_max_columns": 50, "default_table_page_size": 10, "default_width": "medium", "reference_highlighting": false, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": false}}, "mcp": {"mcpServers": {}, "presets": []}, "package_management": {"manager": "pip"}, "runtime": {"auto_instantiate": false, "auto_reload": "off", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}, "configOverrides": {}, "appConfig": {"sql_output": "auto", "width": "compact"}, "view": {"showAppCode": true}, "notebook": {"cells": [{"code": "mo.md(r\"\"!\"[MOSEK ApS](https://www.mosek.com/static/images/branding/webgraphmoseklogocolor.png )\"\"", "code_hash": "271c93fd1913447fc8645725a5909adb", "config": {"column": null, "disabled": false, "hide_code": true}, "id": "Hbol", "name": \"_\"}, {"code": "mo.md(r\"\"\"# Regularized Wasserstein Barycenters using Mosek and the exponential cone\"\"\", "code_hash": "f668b74280977f8a6875e8a0b3ab27ab", "config": {"column": null, "disabled": false, "hide_code": true}, "id": "MJUe", "name": \"_\"}, {"code": "mo.md(r\"\"\"In a [previous notebook related to Wasserstein distances](https://github.com/MOSEK/Tutorials/tree/master/wasserstein) we defined the linear optimization problem of computing the Wasserstein barycenter of a set of discrete measures. Here we solve an entropy-regularized variant of the same problem and to demonstrate the exponential cone capabilities of MOSEK. We also use this problem to compare Fusion and CVXPY.\"\"", "code_hash": "797b5fb5dc1fe1b18dd956cb0ae2e3bc", "config": {"column": null, "disabled": false, "hide_code": true}, "id": "vblA", "name": \"_\"}, {"code": "mo.md(\n r\"\"\nAs a reminder, the $p$-th order Wasserstein distance $W_p(\\mu,\\upsilon)$ between discrete probability distributions $\\mu,\\upsilon$ is the objective value of the following problem:\n\n\n$$ \\text{minimize} \\quad \\sum_{i=1}\\sum_{j=1} D(X_i,Y_j)^p\\pi_{ij}$$\n\n\n$$ \\text{st.} \\quad \\sum_{j=1} \\pi_{ij} = \\mu_i , \\quad i = 1,2,..n $$\n\n$$ \\quad \\sum_{i=1} \\pi_{ij} = \\upsilon_j, \\quad j = 1,2,..m $$\n\n$$ \\pi_{ij} \\geq 0, \\quad \\forall_{i,j}$$\n\nwhere $D(X_i,Y_j)$ is the distance function.\n\"\""\n)", "code_hash": "c0cca35d0f31c3f5bfdcf52047aabe76", "c ``` -------------------------------- ### MOSEK Fusion Constraint Example Source: https://github.com/mosek/tutorials/blob/master/approx-uncertain-ineq/hard_uncertain.html A simple linear constraint example within a MOSEK Fusion model. ```python constraint('Lin1',Expr.sum(h1,0)<=1.0) M.solve() return(M.primalObjValue(),M.getSolverDoubleInfo('optimizerTime')) ``` -------------------------------- ### Run Full Example 3 Source: https://github.com/mosek/tutorials/blob/master/approx-uncertain-ineq/hard_uncertain.html This snippet displays an image related to the third full example of uncertain inequalities. It's part of a larger demonstration. ```python mo.image(src=_src3,rounded=True) ``` -------------------------------- ### Main Problem Setup and Data Generation Source: https://github.com/mosek/tutorials/blob/master/mle-convex-density-function/MLEConvexDensityFunction.html Sets up the main cell for generating samples from different density functions and preparing data for the Mosek model. It calculates delta_y values from sorted samples. ```python def _( NodeSize, np, sample_arcsine, sample_exponential, sample_inverse, sample_quadratic, ): # Number of samples n = NodeSize.value # Generate samples from different density functions exponential_samples = sample_exponential(n) arcsine_samples = sample_arcsine(n) quadratic_samples = sample_quadratic(n) inverse_samples = sample_inverse(n) # Select which sample to use y = exponential_samples # In the paper the y's are assumed to be in non-decreasing order y.sort() # As parameter of the model, we need the delta values array where delta_y = y[i] - y[i-1] delta_y = np.diff(y) return delta_y, n, y ``` -------------------------------- ### Introduction to Binary Least Squares Example with MOSEK Source: https://github.com/mosek/tutorials/blob/master/binary-quadratic/binquad.html Introduces Example 3: Binary Least Squares, defining the problem and the method for generating random data for testing. ```python mo.md( r""" # Example 3: Binary least squares Binary least squares is the problem $$ \mathrm{minimize}_{x\in\{0,1\}^n} \\ \|Ax-b\|_2^2 \quad (=x^T(A^TA)x-(2A^Tb)^Tx+b^Tb) $$ where $A\in\mathbb{R}^{m\times n}, b\in \mathbb{R}^m$. This is a mixed-integer SOCP, so we can compare our solver with the solutions obtained directly with MOSEK. As suggested in [Park, Boyd 2017](https://web.stanford.edu/~boyd/papers/pdf/int_least_squares.pdf) we generate reasonably hard random data by taking $$ \begin{array}{l} A\in\mathbb{R}^{m\times n},\quad A_{i,j}\sim \mathrm{Normal}(0,1) \\ b=Ac,\quad c\in\mathbb{R}^n,\quad c_i\sim\mathrm{Uniform}(0,1) \\end{array} $$ For this test we fix $n=50$ and vary $40\leq m\leq 150$. """ ) ``` -------------------------------- ### Run Main Experiment with Defined Parameters Source: https://github.com/mosek/tutorials/blob/master/approx-uncertain-ineq/hard_uncertain.html This function initializes parameters for the experiment, including sparsity density (s) and the number of terms in the log-sum-exp (p), then calls the main solving function. ```python @app.cell def _(L_list, m_list, main, n_list): #Sparsity density set to 0.1 and number of terms in the log-sum-exp is 2, like in the paper. s = 0.1 p = 2 Ex,App1,App2 = main(n_list,m_list,L_list,p,s) return App1, App2, Ex ``` -------------------------------- ### Import MOSEK Fusion API and Print Version Source: https://github.com/mosek/tutorials/blob/master/regression/regression.html Imports necessary MOSEK Fusion modules and prints the installed MOSEK version. Ensure MOSEK is installed and accessible. ```python import mosek from mosek.fusion import Model, Domain, Expr, ObjectiveSense, Matrix, Var, SolutionStatus import mosek.fusion.pythonic print("MOSEK version", Model.getVersion()) ```