{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.5"
},
"colab": {
"name": "Guia 1 - Ejercicio 1 final.ipynb",
"provenance": [],
"collapsed_sections": [
"bkKyWz4HpYKv",
"65dDjhT6pYLH"
]
}
},
"cells": [
{
"cell_type": "code",
"metadata": {
"id": "hmA0i2opzcgQ"
},
"source": [
""
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "4gRc7Tuzplau"
},
"source": [
"# Instalacion de librerias"
]
},
{
"cell_type": "code",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "G6VN53Mopkk0",
"outputId": "db98051d-59f7-49ec-af95-a8c3d4e84310"
},
"source": [
"pip install pulp"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"Collecting pulp\n",
"\u001b[?25l Downloading https://files.pythonhosted.org/packages/14/c4/0eec14a0123209c261de6ff154ef3be5cad3fd557c084f468356662e0585/PuLP-2.4-py3-none-any.whl (40.6MB)\n",
"\u001b[K |████████████████████████████████| 40.6MB 83kB/s \n",
"\u001b[?25hCollecting amply>=0.1.2\n",
" Downloading https://files.pythonhosted.org/packages/f3/c5/dfa09dd2595a2ab2ab4e6fa7bebef9565812722e1980d04b0edce5032066/amply-0.1.4-py3-none-any.whl\n",
"Requirement already satisfied: docutils>=0.3 in /usr/local/lib/python3.7/dist-packages (from amply>=0.1.2->pulp) (0.17)\n",
"Requirement already satisfied: pyparsing in /usr/local/lib/python3.7/dist-packages (from amply>=0.1.2->pulp) (2.4.7)\n",
"Installing collected packages: amply, pulp\n",
"Successfully installed amply-0.1.4 pulp-2.4\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "k94MmZPnrIIO"
},
"source": [
"# Carga de librerias"
]
},
{
"cell_type": "code",
"metadata": {
"id": "sxKlfYC4pYJ8"
},
"source": [
"import pandas as pd\n",
"import numpy as np\n",
"from scipy.optimize import linprog\n",
"from pulp import LpMaximize, LpProblem, LpStatus, lpSum, LpVariable"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "Qug49EqtsKTm"
},
"source": [
"try:\n",
" # settings colab:\n",
" from google.colab import drive\n",
"except ModuleNotFoundError: \n",
" print(\"Ha ocurrido un error\")"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "BId135-bsCTH",
"outputId": "59c0dd30-1705-4d5e-fad6-a494f61de99a"
},
"source": [
"try:\n",
" drive.mount('/content/drive')\n",
"except Exception: \n",
" print(\"Ha ocurrido un error\") "
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"Mounted at /content/drive\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "kDAFG8GSpYKc"
},
"source": [
"# Ejercicio 1"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fY1enPsIpYKf"
},
"source": [
"En un taller metalúrgico se fabrican dos tipos de piezas A y B, que deben seguir los siguientes\n",
"procesos:\n",
"1. Estampado en hojas metálicas\n",
"2. Soldado\n",
"3. Pintado\n",
"\n",
"La operación de estampado consiste en preparar partes idénticas que luego serán soldadas de a\n",
"pares, formando la pieza A. El mismo proceso se realiza para la pieza B.\n",
"Los insumos de equipos son los siguientes, para la realización de cada una de las operaciones\n",
"(expresados en segundos por pieza):\n",
"\n",
"\n",
"\n",
"La utilidad unitaria es de \\$ 4 para la pieza A y \\$ 3 para la pieza B. Se desea establecer el\n",
"programa semanal de producción que maximice la utilidad del taller con respecto a las piezas\n",
"consideradas."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ajSjaeqopYKg"
},
"source": [
"## Con Scipy"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "jfHan20npYKi"
},
"source": [
"Se define la funcion objetivo y las restricciones"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "jN1iNgJxpYKj"
},
"source": [
"Observaciones de Scipy: \n",
"* Solamente se pueden resolver problemas de Mínimización\n",
"* No acepta restricciones de Mayor o igual (>=)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "G5xaW9H-pYKk"
},
"source": [
"En este problema como es de Maximizacion, se cambia a minimizacion de la siguiente forma:\n",
"* max z = 4 * x + 3 * y -----> es equivalente a ------> min z = -4 * x - 3 * y"
]
},
{
"cell_type": "code",
"metadata": {
"id": "Cbb7BPqHpYKl"
},
"source": [
"obj = [-4, -3] # se cambian de signos para pasar de maximizacion a minimizacion\n",
"# ─┬ ─┬\n",
"# │ └┤ coeficiente para y\n",
"# └────┤ coeficiente para x\n",
"\n",
"lhs_ineq = [[ 3, 8], # Coeficientes estampado lado izquierdo\n",
" [12, 6], # Coeficientes soldado lado izquierdo\n",
" [ 9, 9]] # Coeficientes pintado ecuacion coeficientes lado izquierdo\n",
"\n",
"rhs_ineq = [48000, # Estampado ecuacion lado derecho\n",
" 42000, # Soldado lado derecho\n",
" 36000] # Pintado lado derecho"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "fCvKVuQapYKn"
},
"source": [
"Se definen los limites de las variables x e y. Esta definicion es redundante ya que son los valores por defecto"
]
},
{
"cell_type": "code",
"metadata": {
"id": "N5J8qJW9pYKo"
},
"source": [
"bnd = [(0, float(\"inf\")), # Limite de x\n",
" (0, float(\"inf\"))] # Limite of y"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "3Q6JjHJ-pYKp"
},
"source": [
"Optimizacion y resolucion del problema"
]
},
{
"cell_type": "code",
"metadata": {
"id": "5aAT_DsVpYKq",
"outputId": "35d2cd43-83ae-458b-c26a-e51b8cabf668"
},
"source": [
"opt = linprog(c=obj, A_ub=lhs_ineq, b_ub=rhs_ineq,\n",
" bounds=bnd, method=\"revised simplex\")\n",
"opt"
],
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
" con: array([], dtype=float64)\n",
" fun: -15000.0\n",
" message: 'Optimization terminated successfully.'\n",
" nit: 2\n",
" slack: array([31000., 0., 0.])\n",
" status: 0\n",
" success: True\n",
" x: array([3000., 1000.])"
]
},
"metadata": {
"tags": []
},
"execution_count": 4
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "reUtuxA-pYKu"
},
"source": [
"Valores que se obtienen son:\n",
"* con: Residuos de restricciones de igualdad\n",
"* fun: Valor optimo de la función objetivo en la igualdad (si es que existe)\n",
"* message: Status de la solucion\n",
"* nit: Numero de iteraciones necesarias para realizar el calculo\n",
"* slack: Valores de las variables slack\n",
"* status: Numero entero entre 0 y 4 que muestra el resultado de la solucion:\n",
" * 0: solucion optima\n",
" * 1: iteracion limitada\n",
" * 2: solucion degenerada\n",
" * 3: solucion irrestrica\n",
" * 4: se encuentran dificultadas numericas\n",
"* success: Variable booleana que indica si se alcanzo la solucion optima\n",
"* x: NumPy array que continiene los valores optimos para las variables de decision"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bkKyWz4HpYKv"
},
"source": [
"## Con Pulp"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "txbDcxsRpYKw"
},
"source": [
"Se inicializa una instancia de LpProblem:\n",
"* Maximizacion: sense = LpMaximize o -1\n",
"* Minimizacion: sense = LpMinimize o 1 (es la opcion que viene por default)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "PeXcGXsppYKx"
},
"source": [
"Creacion del modelo"
]
},
{
"cell_type": "code",
"metadata": {
"id": "j8pTDYG7pYKz"
},
"source": [
"model = LpProblem(name=\"Maximizacion_Beneficio_Fabrica\", sense=LpMaximize)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "aWHXRtVRpYK0"
},
"source": [
"Inicializacion de variables"
]
},
{
"cell_type": "code",
"metadata": {
"id": "HTZVp7TOpYK7"
},
"source": [
"A = LpVariable(name=\"A\", lowBound=0)\n",
"B = LpVariable(name=\"B\", lowBound=0)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "KrhY8DyFpYK8"
},
"source": [
"Restricciones"
]
},
{
"cell_type": "code",
"metadata": {
"id": "36o0IU0-WhOc"
},
"source": [
"random_demanda = rnd()"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "rPygJ5hLpYK9"
},
"source": [
"model += ( 3 * A + 8 * B <= 48000, \"estampado\")\n",
"model += (12 * A + 6 * B <= 42000, \"soldado\")\n",
"model += ( 9 * A + 9 * B <= 36000, \"pintado\")"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "82Ie0am0pYK-"
},
"source": [
"Funcion Objetivo"
]
},
{
"cell_type": "code",
"metadata": {
"id": "GTcFxlzLpYK_"
},
"source": [
"obj_func = 4 * A + 3 * B\n",
"model += obj_func"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "26EmmA_CpYK_",
"outputId": "7dee8a77-e7be-4152-880a-15136e4c777a"
},
"source": [
"model"
],
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"Maximizacion_Beneficio_Fabrica:\n",
"MAXIMIZE\n",
"4*A + 3*B + 0\n",
"SUBJECT TO\n",
"estampado: 3 A + 8 B <= 48000\n",
"\n",
"soldado: 12 A + 6 B <= 42000\n",
"\n",
"pintado: 9 A + 9 B <= 36000\n",
"\n",
"VARIABLES\n",
"A Continuous\n",
"B Continuous"
]
},
"metadata": {
"tags": []
},
"execution_count": 9
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Qn-CR8PYpYLB"
},
"source": [
"Resolucion del problema"
]
},
{
"cell_type": "code",
"metadata": {
"id": "hUUml0N1pYLB"
},
"source": [
"status = model.solve()"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "C7iL_ysipYLC",
"outputId": "96a387fc-f319-41cd-9cf2-ffb5716cb9ab"
},
"source": [
"print(f\"status: {model.status}, {LpStatus[model.status]}\")"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"status: 1, Optimal\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "t2TQBV8cpYLD",
"outputId": "f1c94c5b-d8b6-4451-bded-2d56d54ef24b"
},
"source": [
"print(f\"objective: {model.objective.value()}\")"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"objective: 15000.0\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "AloPHKDtpYLE",
"outputId": "e9fb9f68-1847-4b4b-d53a-38102c9fa42f"
},
"source": [
"for var in model.variables():\n",
" print(f\"{var.name}: {var.value()}\")"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"A: 3000.0\n",
"B: 1000.0\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "WMAQkVbqpYLF",
"outputId": "8d6796a7-a170-428b-f6aa-c8e3ddbbd114"
},
"source": [
"for name, constraint in model.constraints.items():\n",
" print(f\"{name}: {constraint.value()}\")"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"estampado: -31000.0\n",
"soldado: 0.0\n",
"pintado: 0.0\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "65dDjhT6pYLH"
},
"source": [
"## Con Pulp - Lectura de dataframes"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "JHpHjuQVpYLH"
},
"source": [
"Lectura del dataframe"
]
},
{
"cell_type": "code",
"metadata": {
"id": "XaNR1wbZpYLI"
},
"source": [
"df_insumos = pd.read_excel('/content/drive/My Drive/Guia 1 - Ejercicio 1/Guia 1 - Ejercicio 1 insumos.xlsx')"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 141
},
"id": "zreySA-bpYLJ",
"outputId": "67412b2b-7460-4079-937a-98ac04d6f4f7"
},
"source": [
"df_insumos"
],
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/html": [
"
\n",
"\n",
"
\n",
" \n",
" \n",
" | \n",
" Operacion | \n",
" Pieza_A | \n",
" Pieza_B | \n",
" Tiempo_Disponible_seg_por_semana | \n",
"
\n",
" \n",
" \n",
" \n",
" 0 | \n",
" Estampado | \n",
" 3 | \n",
" 8 | \n",
" 48000 | \n",
"
\n",
" \n",
" 1 | \n",
" Soldado | \n",
" 12 | \n",
" 6 | \n",
" 42000 | \n",
"
\n",
" \n",
" 2 | \n",
" Pintado | \n",
" 9 | \n",
" 9 | \n",
" 36000 | \n",
"
\n",
" \n",
"
\n",
"
"
],
"text/plain": [
" Operacion Pieza_A Pieza_B Tiempo_Disponible_seg_por_semana\n",
"0 Estampado 3 8 48000\n",
"1 Soldado 12 6 42000\n",
"2 Pintado 9 9 36000"
]
},
"metadata": {
"tags": []
},
"execution_count": 11
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "ybcpgsMapYLK"
},
"source": [
"df_utilidad = pd.read_excel('/content/drive/My Drive/Guia 1 - Ejercicio 1/Guia 1 - Ejercicio 1 utilidad.xlsx')"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "HTJx2pI1pYLK",
"outputId": "0b7f6592-ffb9-44ef-a84b-434998bd143f"
},
"source": [
"df_utilidad"
],
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/html": [
"\n",
"\n",
"
\n",
" \n",
" \n",
" | \n",
" Pieza_A | \n",
" Pieza_B | \n",
"
\n",
" \n",
" \n",
" \n",
" 0 | \n",
" 4 | \n",
" 3 | \n",
"
\n",
" \n",
"
\n",
"
"
],
"text/plain": [
" Pieza_A Pieza_B\n",
"0 4 3"
]
},
"metadata": {
"tags": []
},
"execution_count": 18
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "GMeqJsDapYLL"
},
"source": [
"Inicializacion de variables"
]
},
{
"cell_type": "code",
"metadata": {
"id": "Y8SHP3bwpYLM"
},
"source": [
"A = LpVariable(name=\"A\", lowBound=0)\n",
"B = LpVariable(name=\"B\", lowBound=0)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "IERtH0GdpYLN"
},
"source": [
"Creacion del modelo"
]
},
{
"cell_type": "code",
"metadata": {
"id": "jztoak_IpYLO"
},
"source": [
"model_2 = LpProblem(name=\"Maximizacion_Beneficio_Fabrica\", sense=LpMaximize)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "eoNdBjQSpYLO"
},
"source": [
"Definicion de restricciones\n",
"* la funcion lp realiza una suma de los elementos que hay dentro\n",
"* luego de la coma se agrega como string el nombre de cada una de las variables"
]
},
{
"cell_type": "code",
"metadata": {
"id": "jIbl0YXapYLP"
},
"source": [
"for i in range(len(df_insumos)):\n",
" model_2 += lpSum(df_insumos['Pieza_A'][i] * A + df_insumos['Pieza_B'][i] * B) <= df_insumos['Tiempo_Disponible_seg_por_semana'][i], str(df_insumos['Operacion'][i])"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "H3e984h-pYLQ"
},
"source": [
"Funcion objetivo"
]
},
{
"cell_type": "code",
"metadata": {
"id": "vLxzlWEHpYLR"
},
"source": [
"obj_func_2 = lpSum(df_utilidad['Pieza_A'] * A + df_utilidad['Pieza_B'] * B)\n",
"model_2 += obj_func_2"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "bi3EMa2FpYLR",
"outputId": "0df0feba-999f-4497-a30a-c51c64715764"
},
"source": [
"obj_func_2"
],
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"4*A + 3*B + 0"
]
},
"metadata": {
"tags": []
},
"execution_count": 23
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "FSBZO0pTpYLS"
},
"source": [
"status_2 = model_2.solve()"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "GVbgr3tfpYLT",
"outputId": "97fc811e-9294-4214-fd45-3025d3d7c7e8"
},
"source": [
"print(f\"status: {model_2.status}, {LpStatus[model_2.status]}\")"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"status: 1, Optimal\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "nYeeC9lYpYLU",
"outputId": "2f86ff81-0520-48f9-b93b-8b7d88ce962f"
},
"source": [
"print(f\"objective: {model_2.objective.value()}\")"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"objective: 15000.0\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "K96pCCYppYLW",
"outputId": "65eb01cc-f0bd-475e-a1f9-03d5a239fc16"
},
"source": [
"for var in model_2.variables():\n",
" print(f\"{var.name}: {var.value()}\")"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"A: 3000.0\n",
"B: 1000.0\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "nrYltBuSpYLX",
"outputId": "2f251597-59a6-4de8-b9e2-ce0e6699ca86"
},
"source": [
"for name, constraint in model_2.constraints.items():\n",
" print(f\"{name}: {constraint.value()}\")"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"Estampado: -31000.0\n",
"Soldado: 0.0\n",
"Pintado: 0.0\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "fZzGwm5UpYLY"
},
"source": [
""
],
"execution_count": null,
"outputs": []
}
]
}