{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "**Make sure you run this at the begining**" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "np.set_printoptions(suppress=True)\n", "from scipy.optimize import linprog" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Feasible Example" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\\begin{align}\n", "\\max f=4x_1+x_2 \\\\\n", "\\text{s.t.} -x_1 + 2x_2 &\\leq 4 \\\\\n", "2x_1 + 3x_2 &\\leq 12 \\\\\n", "x_1 - x_2 &\\leq 3 \\\\\n", "\\text{and } x_1, x_2 \\geq 0\n", "\\end{align}" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "c = [-4, -1, 0, 0, 0]\n", "A = [[-1, 2, 0, 0, 0], [2, 3, 0, 0, 0], [1, -1, 0, 0, 0]]\n", "b = [4, 12, 3]\n", "\n", "x0_bounds = (0, None)\n", "x1_bounds = (0, None)\n", "x2_bounds = (None, None)\n", "x3_bounds = (None, None)\n", "x4_bounds = (None, None)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " con: array([], dtype=float64)\n", " fun: -17.999999976555795\n", " message: 'Optimization terminated successfully.'\n", " nit: 4\n", " slack: array([5.8 , 0.00000002, 0. ])\n", " status: 0\n", " success: True\n", " x: array([4.19999999, 1.2 , 0. , 0. , 0. ])\n" ] } ], "source": [ "res = linprog(c, A_ub=A, b_ub=b, bounds=[x0_bounds, x1_bounds, x2_bounds, x3_bounds, x4_bounds])\n", "\n", "print(res)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Infeasible Example" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\\begin{align}\n", "\\min f = x_1 - 2x_2 + 3x_3 \\\\\n", "s.t. -2x_1 + x_2 + 3x_3 & = 2 \\\\\n", "3x_1 + 3x_2 + 4x_3 & = 1 \\\\\n", "\\end{align}" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "c = [-1, 2, -3]\n", "A = [[-2, 1, 3], [3, 3, 4]]\n", "b = [2, 1]\n", "\n", "x0_bounds = (0, None)\n", "x1_bounds = (0, None)\n", "x2_bounds = (0, None)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "scrolled": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " con: array([ 0. , -4.56053464])\n", " fun: -0.6099904044751114\n", " message: 'The algorithm terminated successfully and determined that the problem is infeasible.'\n", " nit: 4\n", " slack: array([], dtype=float64)\n", " status: 2\n", " success: False\n", " x: array([0.2893146 , 0.75265113, 0.60865936])\n" ] } ], "source": [ "res = linprog(c, A_eq=A, b_eq=b, bounds=[x0_bounds, x1_bounds, x2_bounds,])\n", "\n", "print(res)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "