required | Labor A

required | Labor B

required | Market

Demand | Price |\n", "| :-: | :-: | :-: | :-: | :-: | :-: |\n", "| U | 10 g | 1 hr | 2 hr | $\\leq$ 40 units | \\$270 |\n", "| V | 9 g | 1 hr | 1 hr | unlimited | \\$210 |\n", "\n", "| Resource | Amount

Available | Cost |\n", "| :-: | :-: | :-: |\n", "| M | unlimited | \\$10 / g |\n", "| A | 80 hours | \\$50 / hour |\n", "| B | 100 hours | \\$40 / hour |\n", "\n", "Two distinct *sets* of objects are evident from these tables. The first is the set of products, comprising $U$ and $V$. The second is the set of resources used to produce those products, comprising raw materials and two labor types, which we have abbreviated as $M$, $A$, and $B$.\n", "\n", "Having identified these sets, the data for this application be factored into three simple tables. The first two tables list attributes of the products and attributes of the resources. The third table summarizes the processes used to create the products from the resources, which requires providing a value for each combination of product and resource:\n", "\n", "**Table: Products**\n", "\n", "| Product | Demand | Price |\n", "| :-: | :-: | :-: |\n", "| U | $\\leq$ 40 units | \\$270 |\n", "| V | unlimited | \\$210 |\n", "\n", "**Table: Resources**\n", "\n", "| Resource | Available | Cost |\n", "| :-: | :-: | :-: |\n", "| M | ? | \\$10 / g |\n", "| A | 80 hours | \\$50 / hour |\n", "| B | 100 hours | \\$40 / hour |\n", "\n", "**Table: Processes**\n", "\n", "| Product | M | A | B\n", "| :-: | :-: | :-: | :-: |\n", "| U | 10 g | 1 hr | 2 hr |\n", "| V | 9 g | 1 hr | 1 hr |\n" ] }, { "cell_type": "markdown", "metadata": { "id": "Lrx4Bpo2ctc-" }, "source": [ "How does a Python-based AMPL application work with this data? We can think of the data as being handled in three steps:\n", "\n", "1. Import the data into Python, in whatever form is convenient for the application.\n", "\n", "1. Convert the data to the forms required by the optimization model.\n", "\n", "1. Send the data to AMPL.\n", "\n", "For our example, we implement step 1 by use of Python *nested dictionaries* that closely resemble the above three tables:\n", "\n", "- In the `products` data structure, the product abbreviations serve as keys for outermost dictionary, and the product-related attribute names (`demand` and `price`) as keys for the inner dictionaries.\n", "\n", "- In the `resources` data structure, the resource abbreviations serve as keys for outermost dictionary, and the resource-related attribute names (`available` and `cost`) as keys for the inner dictionaries.\n", "\n", "- In the `processes` data structure, there is a value corresponding to each combination of a product and a resource; the product abbreviations serve as keys for outermost dictionary, and resource abbreviations as keys for the inner dictionaries.\n", "\n", "Where demand or availability is \"unlimited\", we use an expression that Python interprets as an infinite value.\n", "\n", "You will see a variety of data representation in this book, chosen in each case to be most efficient and convenient for the application at hand. Some will use Python packages, particularly *numpy* and *pandas*, that are designed for large-scale data handling." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "id": "J49LJ253ctc_" }, "outputs": [], "source": [ "Inf = float(\"inf\")\n", "\n", "products = {\n", " \"U\": {\"demand\": 40, \"price\": 270},\n", " \"V\": {\"demand\": Inf, \"price\": 210},\n", "}\n", "\n", "resources = {\n", " \"M\": {\"available\": Inf, \"cost\": 10},\n", " \"A\": {\"available\": 80, \"cost\": 50},\n", " \"B\": {\"available\": 100, \"cost\": 40},\n", "}\n", "\n", "processes = {\n", " \"U\": {\"M\": 10, \"A\": 2, \"B\": 1},\n", " \"V\": {\"M\": 9, \"A\": 1, \"B\": 1},\n", "}" ] }, { "cell_type": "markdown", "metadata": { "id": "JrmOWyi0ctdE", "jp-MarkdownHeadingCollapsed": true, "tags": [] }, "source": [ "## Mathematical model\n", "\n", "Once the problem data is rearranged into tables like this, the structure of the production planning problem becomes evident. Along with the two sets, we have a variety of symbolic *parameters* that specify the model's costs, limits, and processes in a general way.Compared to the previous notebook, these abstractions allow us to create mathematical models that can adapt and scale with the supplied data.\n", "\n", "Let $\\cal{P}$ and $\\cal{R}$ be the set of products and resources, respectively, and let $p$ and $r$ be representative elements of those sets. We use indexed decision variables $x_r$ to denote the amount of resource $r$ that is consumed in production, and $y_p$ to denote the amount of product $p$ produced.\n", "\n", "The model specifies lower and upper bounds on the values of the variables. We represent these as\n", "\n", "$$\n", "\\begin{aligned}\n", " 0 \\leq x_r \\leq b^x_r & & \\forall r\\in\\cal{R} \\\\\n", " 0 \\leq y_p \\leq b^y_p & & \\forall p\\in\\cal{P} \\\\\n", "\\end{aligned}\n", "$$\n", "\n", "where the upper bounds, $b^x_r$ and $b^y_p$, are data taken from the tables of attributes.\n", "\n", "The objective is given as before,\n", "\n", "$$\n", "\\begin{aligned}\n", " \\text{profit} & = \\text{revenue} - \\text{cost} \\\\\n", "\\end{aligned}\n", "$$\n", "\n", "but now the expressions for revenue and cost are expressed more generally as sums over the product and resource sets,\n", "\n", "$$\n", "\\begin{aligned}\n", " \\text{revenue} & = \\sum_{p\\in\\cal{P}} c^y_p y_p \\\\\n", " \\text{cost} & = \\sum_{r\\in\\cal{R}} c^x_r x_r \\\\\n", "\\end{aligned}\n", "$$\n", "\n", "where parameters $c^y_p$ and $c^x_r$ represent the selling prices for products and the costs for resources, respectively. The limits on available resources can be written as\n", "\n", "$$\n", "\\begin{aligned}\n", " \\sum_{p\\in\\cal{P}} a_{rp} y_p & \\leq x_r & \\forall r\\in\\cal{R}\n", "\\end{aligned}\n", "$$\n", "\n", "where $a_{rp}$ is the amount of resource $r$ needed to make 1 unit of product $p$. Putting these pieces together, we have the following symbolic model for the production planning problem.\n", "\n", "$$\n", "\\begin{align}\n", "{\\rm maximize} \\quad & \\sum_{p\\in\\cal{P}} c^y_p y_p - \\sum_{r\\in\\cal{R}} c^x_r x_r \\\\\n", "\\text{subject to} \\quad & \\sum_{p\\in\\cal{P}} a_{rp} y_p \\leq x_r & \\forall r\\in\\cal{R} \\nonumber \\\\\n", " & 0 \\leq x_r \\leq b^x_r & \\forall r\\in\\cal{R} \\nonumber \\\\\n", " & 0 \\leq y_p \\leq b^y_p & \\forall p\\in\\cal{P} \\nonumber \\\\\n", "\\end{align}\n", "$$\n", "\n", "When formulated this way, the model can be applied to any problem with the same structure, regardless of the number of products or resources. This flexibility is possible due to the use of sets to describe the products and resources for a particular problem instance, indices like $p$ and $r$ to refer to elements of those sets, and data tables that hold the relevant parameter values.\n", "\n", "Generalizing mathematical models in this fashion is a feature of all large-scale optimization applications. Next we will see how this type of generalization carries over naturally into formulating and solving the model in AMPL." ] }, { "cell_type": "markdown", "metadata": { "id": "Z9izg44dctdF" }, "source": [ "## The production model in AMPL\n", "\n", "As before, we begin the construction of an AMPL model by importing the needed components into the AMPL environment." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Uqz3b8xuctdF", "outputId": "c26a8c8a-d5b8-4086-93d2-5b4059686c12" }, "outputs": [], "source": [ "from amplpy import AMPL, ampl_notebook\n", "\n", "ampl = ampl_notebook(\n", " modules=[\"highs\"], # modules to install\n", " license_uuid=\"default\", # license to use\n", ") # instantiate AMPL object and register magics" ] }, { "cell_type": "markdown", "metadata": { "id": "CYEdqS6sctdG" }, "source": [ "Next we use AMPL `set` statements to define the product and resource sets. Notice that at this point, we are only telling AMPL about the two sets will be used in the model. The members of these sets will be sent from Python to AMPL later, as part of the problem data.\n", "\n", "In mathematical formulations, it is customary to keep the names of all components short. But when writing the model in AMPL, we are free to use longer, more meaningful names that make the model statements easier to read. Thus, for example, here we use `PRODUCTS` and `RESOURCES` as the AMPL names of the sets that are are called $\\cal P$ and $\\cal R$ in the mathematical model." ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "id": "_DrA1iQ6ctdG" }, "outputs": [], "source": [ "%%ampl_eval\n", "# define sets\n", "\n", "set PRODUCTS;\n", "set RESOURCES;" ] }, { "cell_type": "markdown", "metadata": { "id": "Bo6264AJctdH" }, "source": [ "The next step is to introduce parameters that will be used as data in the objective function and the constraints.\n", "\n", "A statement that defines and AMPL parameter begin with the `param` keyword and a unique name. Then between braces `{` and `}` it specifies the index sets for the parameter. For example:\n", "\n", "- `param demand {PRODUCTS} >= 0;` states that there is a \"product demanded\" value for each member of the set PRODUCTS.\n", "\n", "- `param need {RESOURCES,PRODUCTS} >= 0;` states that there is a \"resource needed\" value for each combination of a resource and a product.\n", "\n", "At the end of each `param` statement, we specify that the values for the parameter must be nonnegative or positive, as appropriate. These specifications will be used to later to check that the actual data values are appropriate for the problem.\n", "\n", "There are 5 different `param` statements in all, corresponding to the 5 different kinds of data in tables, and the 5 different symbolic parameters $b_p^y$, $c_p^y$, $b_r^x$, $c_r^x$, and $a_{rp}$ in the mathematical model." ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "id": "2JrQACvVctdH" }, "outputs": [], "source": [ "%%ampl_eval\n", "# define parameters\n", "\n", "param demand {PRODUCTS} >= 0;\n", "param price {PRODUCTS} > 0;\n", "\n", "param available {RESOURCES} >= 0;\n", "param cost {RESOURCES} > 0;\n", "\n", "param need {RESOURCES,PRODUCTS} >= 0;" ] }, { "cell_type": "markdown", "metadata": { "id": "BWJ_ElJFctdH" }, "source": [ "AMPL defines the decision variables in much the same way as the parameters, but with `var` as the keyword starting the statement. We name the variables `Use` for resource use, and `Sell` for product sales.\n", "\n", "To express the bounds on the variables in the same way as the mathematical formulation, a more general form of the AMPL statement is needed. In the case of the `Use` variables, for example:\n", "\n", "* The indexing expression is written `{r in RESOURCES}` to say that there is a variable for each member of the resource set, and also to associate the *index* `r` with members of the set for purpose of this statement. This is the AMPL equivalent of $\\forall r\\in\\cal{R}$ in the mathematical statement.\n", "\n", "* The upper bound is written `<= available[r]` to say that for each member `r` of the resource set, the variable's upper bound is given by the corresponding value from the availability table. This is the AMPL equivalent of $\\leq b^x_r$ in the mathematical statement.\n", "\n", "An expression in brackets `[...]` is called an AMPL *subscript* because it plays the same role as a mathematical subscript like $r$ in $\\leq b^x_r$. Anywhere that the model refers to particular values of an indexed parameter or variables, you will see subscript expressions. For example,\n", "\n", "* `need[r,p]` will be the amount of resource `r` needed to make one unit of product `p`.\n", "\n", "* `Use[r]` will be the total amount of resource `r` used." ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "id": "Ee1AbvSBctdH" }, "outputs": [], "source": [ "%%ampl_eval\n", "# define variables\n", "\n", "var Use {r in RESOURCES} >= 0, <= available[r];\n", "var Sell {p in PRODUCTS} >= 0, <= demand[p];" ] }, { "cell_type": "markdown", "metadata": { "id": "B5oNLBh5ctdH" }, "source": [ "Just as in the previous notebook, the AMPL statement for the objective function begins with `maximize Profit`. But now, as in the mathematical formulation, AMPL uses general summation expressions:\n", "\n", "* `sum {p in PRODUCTS} price[p] * Sell[p]` is the sum, over all products, of the price per unit time the number sold. It corresponds to $\\sum_{p\\in\\cal{P}} c^y_p y_p$ in the mathematical formulation.\n", "\n", "* `sum {r in RESOURCES} cost[r] * Use[r]` is the sum, over all resources, of the cost per unit time the amount used. It corresponds to $\\sum_{r\\in\\cal{R}} c^x_r x_r$ in the mathematical formulation.\n", "\n", "The full expression for the objective function is simply the first of these expressions minus the second one." ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "id": "jYyLpse3ctdI" }, "outputs": [], "source": [ "%%ampl_eval\n", "# define objective function\n", "\n", "maximize Profit:\n", " sum {p in PRODUCTS} price[p] * Sell[p] -\n", " sum {r in RESOURCES} cost[r] * Use[r];" ] }, { "cell_type": "markdown", "metadata": { "id": "QOD6rVX_ctdI" }, "source": [ "The previous AMPL model had 3 constraints, each defined by a `subject to` statement. But the data-driven mathematical formulation recognizes that there is only one different *kind* of constraint --- resources needed must be less than or equal to resources used --- repeated 3 times, once for each resource. The AMPL version combines expressions that have already appeared in earlier parts of the model:\n", "\n", "* `subject to ResourceLimit {r in RESOURCES}` says that the model will have one constraint corresponding to each member `r` of the resource set.\n", "\n", "* `sum {p in PRODUCTS} need[r,p] * Sell[p] <= Use[r]` says that the total of resource `r` needed, summed over all produces sold, must be `<=` the total of resource `r` used. This corresponds to $\\sum_{p\\in\\cal{P}} a_{rp} y_p \\leq x_r$ in the mathematical formulation." ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "id": "svwpLdJHctdI" }, "outputs": [], "source": [ "%%ampl_eval\n", "# create indexed constraint\n", "\n", "subject to ResourceLimit {r in RESOURCES}:\n", " sum {p in PRODUCTS} need[r,p] * Sell[p] <= Use[r];" ] }, { "cell_type": "markdown", "metadata": { "id": "rbrilQKuoA49" }, "source": [ "## The production data in AMPL\n", "\n", "Now that the AMPL model is defined, we can carry out step 2 of data handling, which is to convert the data to the forms that the model requires:\n", "\n", "- For the two sets, Python lists of the set members.\n", "- For the two parameters indexed over products, Python dictionaries whose keys are the product names.\n", "- For the two parameters indexed over resources, Python dictionaries whose keys are the resource names.\n", "- For the parameter indexed over resource-product pairs, a Python dictionary whose keys are tuples consisting of a a resource and a product.\n", "\n", "Using Python's powerful expression forms, all of these lists and dictionaries are readily extracted from the nested dictionaries that our application set up in step 1. To avoid having too many different names, we assign each list and dictionary to a Python program variable that has the same name as the corresponding AMPL set or parameter:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "-FBbrXX8tVLC", "outputId": "9239ed6d-32c9-4366-9c55-ff0e4fdf2392" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "dict_keys(['U', 'V']) dict_keys(['M', 'A', 'B'])\n", "{'U': 40, 'V': inf} {'U': 270, 'V': 210}\n", "{'M': inf, 'A': 80, 'B': 100} {'M': 10, 'A': 50, 'B': 40}\n", "{('M', 'U'): 10, ('A', 'U'): 2, ('B', 'U'): 1, ('M', 'V'): 9, ('A', 'V'): 1, ('B', 'V'): 1}\n" ] } ], "source": [ "# set data\n", "PRODUCTS = products.keys()\n", "RESOURCES = resources.keys()\n", "\n", "# product data\n", "demand = {k: v[\"demand\"] for k, v in products.items()}\n", "price = {k: v[\"price\"] for k, v in products.items()}\n", "\n", "# resource data\n", "available = {k: v[\"available\"] for k, v in resources.items()}\n", "cost = {k: v[\"cost\"] for k, v in resources.items()}\n", "\n", "need = {(r, p): value for p in processes.keys() for r, value in processes[p].items()}\n", "\n", "print(PRODUCTS, RESOURCES)\n", "print(demand, price)\n", "print(available, cost)\n", "print(need)" ] }, { "cell_type": "markdown", "metadata": { "id": "74WdA_kSctdI" }, "source": [ "## Solving the production problem\n", "\n", "Now the Python data can be sent to AMPL, and AMPL can invoke a solver. For this simple model, we can make the Python data correspond exactly to the AMPL data, and thus the statements for sending the data to AMPL are particularly easy to write.\n", "\n", "The statements for selecting a solver and for initiating the solver process are the same as we used with the basic production planning example. When the solver is finished, it displays a few lines of output to confirm that a solution has been found." ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "SvByD4BOctdJ", "outputId": "2a178685-6a45-4846-c063-1abda763f539" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "HiGHS 1.5.1: HiGHS 1.5.1: optimal solution; objective 2400\n", "2 simplex iterations\n", "0 barrier iterations\n" ] } ], "source": [ "# load set data\n", "ampl.set[\"PRODUCTS\"] = PRODUCTS\n", "ampl.set[\"RESOURCES\"] = RESOURCES\n", "\n", "# load parameter data\n", "ampl.param[\"price\"] = price\n", "ampl.param[\"demand\"] = demand\n", "ampl.param[\"cost\"] = cost\n", "ampl.param[\"available\"] = available\n", "ampl.param[\"need\"] = need\n", "\n", "# set solver and solve\n", "ampl.option[\"solver\"] = \"highs\"\n", "ampl.solve()" ] }, { "cell_type": "markdown", "metadata": { "id": "6_TwbPmvgQiv" }, "source": [ "## Reporting the results\n", "\n", "It remains to retrieve the solution from AMPL, after which Python's extensive features and ecosystem can be used to present the results in any way desired. For this first example we use one of the simplest Python features, the `print` statement.\n", "\n", "An AMPL entity is referenced in Python code via its name in the AMPL model. For example, the objective function `Profit` is `ampl.obj['Profit']`, and the collection of `Sell` variables is `ampl.var['Sell']`.\n", "\n", "For an entity that is not indexed, the `value()` method returns the associated value. Thus the first print statement refers to `ampl.obj['Profit'].value()`.\n", "\n", "For an indexed entity, we use the `to_dict()` method to return the values in a Python dictionary, with the set members as keys. Then a for loop can use the `items()` method to iterate over the dictionary and print a line for each member." ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "TDe9WUufgZ9I", "outputId": "18d296e6-6bdb-48e2-93d4-e03ab08da1b5" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Profit = 2400.0\n", "\n", "Production Report\n", " U produced = 0\n", " V produced = 80\n", "\n", "Resource Report\n", " A consumed = 80\n", " B consumed = 80\n", " M consumed = 720\n" ] } ], "source": [ "# create a solution report\n", "print(f\"Profit = {ampl.obj['Profit'].value()}\")\n", "\n", "print(\"\\nProduction Report\")\n", "for product, Sell in ampl.var[\"Sell\"].to_dict().items():\n", " print(f\" {product} produced = {Sell}\")\n", "\n", "print(\"\\nResource Report\")\n", "for resource, Use in ampl.var[\"Use\"].to_dict().items():\n", " print(f\" {resource} consumed = {Use}\")" ] }, { "cell_type": "markdown", "metadata": { "id": "TniGUMcLctdJ" }, "source": [ "## For Python experts: Creating subclasses of `AMPL`\n", "\n", "Some readers of these notebooks may be more experienced Python developers who wish to apply AMPL in more specialized, data driven applications. The following cell shows how the AMPL class can be extended to create specialized model classes. Here we create a subclass called `ProductionModel` that accepts a particular representation of the problem data to produce a production model object. The production model object inherits all of the methods associated with any AMPL model, such as `.display()` and `.solve()`, but can be extended with additional methods." ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "UwwMXq9tctdJ", "outputId": "4191746d-1642-413c-d5a5-5fa6830e343c" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting production_planning.mod\n" ] } ], "source": [ "%%writefile production_planning.mod\n", "\n", "# define sets\n", "set PRODUCTS;\n", "set RESOURCES;\n", "\n", "# define parameters\n", "param demand {PRODUCTS} >= 0;\n", "param price {PRODUCTS} > 0;\n", "param available {RESOURCES} >= 0;\n", "param cost {RESOURCES} > 0;\n", "param need {RESOURCES,PRODUCTS} >= 0;\n", "\n", "# define variables\n", "var Use {r in RESOURCES} >= 0, <= available[r];\n", "var Sell {p in PRODUCTS} >= 0, <= demand[p];\n", "\n", "# define objective function\n", "maximize Profit:\n", " sum {p in PRODUCTS} price[p] * Sell[p] -\n", " sum {r in RESOURCES} cost[r] * Use[r];\n", "\n", "# create indexed constraint\n", "subject to ResourceLimit {r in RESOURCES}:\n", " sum {p in PRODUCTS} need[r,p] * Sell[p] <= Use[r];" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 787 }, "id": "69sZb_YcctdK", "outputId": "55feda56-3283-4032-cc2e-4a67832c5975" }, "outputs": [ { "data": { "text/html": [ "

\n",
"\n",
"\n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
"

\n",
"

"
],
"text/plain": [
" demand price\n",
"U 40.0 270.0\n",
"V inf 210.0"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"demand | price | |
---|---|---|

U | 40.0 | 270.0 |

V | inf | 210.0 |

\n",
"\n",
"\n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
"

\n",
"

"
],
"text/plain": [
" available cost\n",
"M inf 10.0\n",
"A 80.0 50.0\n",
"B 100.0 40.0"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"available | cost | |
---|---|---|

M | inf | 10.0 |

A | 80.0 | 50.0 |

B | 100.0 | 40.0 |

\n",
"\n",
"\n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
"

\n",
"

"
],
"text/plain": [
" M A B\n",
"U 10 2 1\n",
"V 9 1 1"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"HiGHS 1.5.1: HiGHS 1.5.1: optimal solution; objective 2400\n",
"2 simplex iterations\n",
"0 barrier iterations\n",
"Profit = 2400.0\n",
"\n",
"Production Report\n"
]
},
{
"data": {
"text/html": [
"M | A | B | |
---|---|---|---|

U | 10 | 2 | 1 |

V | 9 | 1 | 1 |

\n",
"\n",
"\n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
"

\n",
"

"
],
"text/plain": [
" produced\n",
"PRODUCTS \n",
"U 0\n",
"V 80"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Resource Report\n"
]
},
{
"data": {
"text/html": [
"produced | |
---|---|

PRODUCTS | |

U | 0 |

V | 80 |

\n",
"\n",
"\n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
" \n",
"

\n",
"

"
],
"text/plain": [
" consumed\n",
"RESOURCES \n",
"A 80\n",
"B 80\n",
"M 720"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import pandas as pd\n",
"\n",
"\n",
"class ProductionModel(AMPL):\n",
" \"\"\"\n",
" A class representing a production model using AMPL.\n",
" \"\"\"\n",
"\n",
" def __init__(self, products, resources, processes):\n",
" \"\"\"\n",
" Initialize ProductionModel as an AMPL instance.\n",
"\n",
" :param products: A dictionary containing product information.\n",
" :param resources: A dictionary containing resource information.\n",
" :param processes: A dictionary containing process information.\n",
" \"\"\"\n",
" super(ProductionModel, self).__init__()\n",
"\n",
" # save data in the model instance\n",
" self.products = products\n",
" self.resources = resources\n",
" self.processes = processes\n",
"\n",
" # flag to monitor solution status\n",
" self.solved = False\n",
"\n",
" def load_data(self):\n",
" \"\"\"\n",
" Prepare the data and pass the information to AMPL.\n",
" \"\"\"\n",
" # convert the data dictionaries into pandas data frames\n",
" products = pd.DataFrame(self.products).T\n",
" resources = pd.DataFrame(self.resources).T\n",
" processes = pd.DataFrame(self.processes).T\n",
"\n",
" # display the generated data frames\n",
" display(products)\n",
" display(resources)\n",
" display(processes)\n",
"\n",
" # pass data to AMPL\n",
" self.set_data(products, \"PRODUCTS\")\n",
" self.set_data(resources, \"RESOURCES\")\n",
" self.param[\"need\"] = processes.T\n",
"\n",
" def solve(self, solver=\"highs\"):\n",
" \"\"\"\n",
" Read the model, load the data, set the solver and solve the optimization problem.\n",
" \"\"\"\n",
" self.read(\"production_planning.mod\")\n",
" self.load_data()\n",
" self.option[\"solver\"] = solver\n",
" super(ProductionModel, self).solve()\n",
" self.solved = True\n",
"\n",
" def report(self):\n",
" \"\"\"\n",
" Solve, if necessary, then report the model solution.\n",
" \"\"\"\n",
" if not self.solved:\n",
" self.solve()\n",
"\n",
" print(f\"Profit = {self.obj['Profit'].value()}\")\n",
"\n",
" print(\"\\nProduction Report\")\n",
" Sell = self.var[\"Sell\"].to_pandas()\n",
" Sell.rename(columns={Sell.columns[0]: \"produced\"}, inplace=True)\n",
" Sell.index.rename(\"PRODUCTS\", inplace=True)\n",
" display(Sell)\n",
"\n",
" print(\"\\nResource Report\")\n",
" Use = self.var[\"Use\"].to_pandas()\n",
" Use.rename(columns={Use.columns[0]: \"consumed\"}, inplace=True)\n",
" Use.index.rename(\"RESOURCES\", inplace=True)\n",
" display(Use)\n",
"\n",
"\n",
"m = ProductionModel(products, resources, processes)\n",
"m.report()"
]
}
],
"metadata": {
"colab": {
"include_colab_link": true,
"provenance": []
},
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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.10.12"
},
"latex_envs": {
"LaTeX_envs_menu_present": true,
"autoclose": false,
"autocomplete": true,
"bibliofile": "biblio.bib",
"cite_by": "apalike",
"current_citInitial": 1,
"eqLabelWithNumbers": true,
"eqNumInitial": 1,
"hotkeys": {
"equation": "Ctrl-E",
"itemize": "Ctrl-I"
},
"labels_anchors": false,
"latex_user_defs": false,
"report_style_numbering": false,
"user_envs_cfg": false
}
},
"nbformat": 4,
"nbformat_minor": 1
}
consumed | |
---|---|

RESOURCES | |

A | 80 |

B | 80 |

M | 720 |