Files
ortools-clone/examples/notebook/contrib/magic_square_mip.ipynb
2020-11-18 11:44:51 +01:00

261 lines
8.2 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Copyright 2020 Google LLC."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"you may not use this file except in compliance with the License.\n",
"You may obtain a copy of the License at\n",
"\n",
" http://www.apache.org/licenses/LICENSE-2.0\n",
"\n",
"Unless required by applicable law or agreed to in writing, software\n",
"distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"See the License for the specific language governing permissions and\n",
"limitations under the License.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# magic_square_mip"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<table align=\"left\">\n",
"<td>\n",
"<a href=\"https://colab.research.google.com/github/google/or-tools/blob/master/examples/notebook/contrib/magic_square_mip.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/master/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
"</td>\n",
"<td>\n",
"<a href=\"https://github.com/google/or-tools/blob/master/examples/contrib/magic_square_mip.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/master/tools/github_32px.png\"/>View source on GitHub</a>\n",
"</td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!pip install ortools"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Copyright 2011 Hakan Kjellerstrand hakank@gmail.com\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# http://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License.\n",
"\"\"\"\n",
"\n",
" Magic square (integer programming) in Google or-tools.\n",
"\n",
" Translated from GLPK:s example magic.mod\n",
" '''\n",
" MAGIC, Magic Square\n",
"\n",
" Written in GNU MathProg by Andrew Makhorin <mao@mai2.rcnet.ru>\n",
"\n",
" In recreational mathematics, a magic square of order n is an\n",
" arrangement of n^2 numbers, usually distinct integers, in a square,\n",
" such that n numbers in all rows, all columns, and both diagonals sum\n",
" to the same constant. A normal magic square contains the integers\n",
" from 1 to n^2.\n",
"\n",
" (From Wikipedia, the free encyclopedia.)\n",
" '''\n",
"\n",
" Compare to the CP version:\n",
" http://www.hakank.org/google_or_tools/magic_square.py\n",
"\n",
" Here we also experiment with how long it takes when\n",
" using an output_matrix (much longer).\n",
"\n",
"\n",
" This model was created by Hakan Kjellerstrand (hakank@gmail.com)\n",
" Also see my other Google CP Solver models:\n",
" http://www.hakank.org/google_or_tools/\n",
"\"\"\"\n",
"from __future__ import print_function\n",
"import sys\n",
"from ortools.linear_solver import pywraplp\n",
"\n",
"#\n",
"# main(n, use_output_matrix)\n",
"# n: size of matrix\n",
"# use_output_matrix: use the output_matrix\n",
"#\n",
"\n",
"\n",
"\n",
"# Create the solver.\n",
"\n",
"print('Solver: ', sol)\n",
"\n",
"# using GLPK\n",
"if sol == 'GLPK':\n",
" solver = pywraplp.Solver('CoinsGridGLPK',\n",
" pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING)\n",
"else:\n",
" # Using CLP\n",
" solver = pywraplp.Solver('CoinsGridCLP',\n",
" pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)\n",
"\n",
"#\n",
"# data\n",
"#\n",
"print('n = ', n)\n",
"\n",
"# range_n = range(1, n+1)\n",
"range_n = list(range(0, n))\n",
"\n",
"N = n * n\n",
"range_N = list(range(1, N + 1))\n",
"\n",
"#\n",
"# variables\n",
"#\n",
"\n",
"# x[i,j,k] = 1 means that cell (i,j) contains integer k\n",
"x = {}\n",
"for i in range_n:\n",
" for j in range_n:\n",
" for k in range_N:\n",
" x[i, j, k] = solver.IntVar(0, 1, 'x[%i,%i,%i]' % (i, j, k))\n",
"\n",
"# For output. Much slower....\n",
"if use_output_matrix == 1:\n",
" print('Using an output matrix')\n",
" square = {}\n",
" for i in range_n:\n",
" for j in range_n:\n",
" square[i, j] = solver.IntVar(1, n * n, 'square[%i,%i]' % (i, j))\n",
"\n",
"# the magic sum\n",
"s = solver.IntVar(1, n * n * n, 's')\n",
"\n",
"#\n",
"# constraints\n",
"#\n",
"\n",
"# each cell must be assigned exactly one integer\n",
"for i in range_n:\n",
" for j in range_n:\n",
" solver.Add(solver.Sum([x[i, j, k] for k in range_N]) == 1)\n",
"\n",
"# each integer must be assigned exactly to one cell\n",
"for k in range_N:\n",
" solver.Add(solver.Sum([x[i, j, k] for i in range_n for j in range_n]) == 1)\n",
"\n",
"# # the sum in each row must be the magic sum\n",
"for i in range_n:\n",
" solver.Add(\n",
" solver.Sum([k * x[i, j, k] for j in range_n for k in range_N]) == s)\n",
"\n",
"# # the sum in each column must be the magic sum\n",
"for j in range_n:\n",
" solver.Add(\n",
" solver.Sum([k * x[i, j, k] for i in range_n for k in range_N]) == s)\n",
"\n",
"# # the sum in the diagonal must be the magic sum\n",
"solver.Add(\n",
" solver.Sum([k * x[i, i, k] for i in range_n for k in range_N]) == s)\n",
"\n",
"# # the sum in the co-diagonal must be the magic sum\n",
"if range_n[0] == 1:\n",
" # for range_n = 1..n\n",
" solver.Add(\n",
" solver.Sum([k * x[i, n - i + 1, k]\n",
" for i in range_n\n",
" for k in range_N]) == s)\n",
"else:\n",
" # for range_n = 0..n-1\n",
" solver.Add(\n",
" solver.Sum([k * x[i, n - i - 1, k]\n",
" for i in range_n\n",
" for k in range_N]) == s)\n",
"\n",
"# for output\n",
"if use_output_matrix == 1:\n",
" for i in range_n:\n",
" for j in range_n:\n",
" solver.Add(\n",
" square[i, j] == solver.Sum([k * x[i, j, k] for k in range_N]))\n",
"\n",
"#\n",
"# solution and search\n",
"#\n",
"solver.Solve()\n",
"\n",
"print()\n",
"\n",
"print('s: ', int(s.SolutionValue()))\n",
"if use_output_matrix == 1:\n",
" for i in range_n:\n",
" for j in range_n:\n",
" print(int(square[i, j].SolutionValue()), end=' ')\n",
" print()\n",
" print()\n",
"else:\n",
" for i in range_n:\n",
" for j in range_n:\n",
" print(\n",
" sum([int(k * x[i, j, k].SolutionValue()) for k in range_N]),\n",
" ' ',\n",
" end=' ')\n",
" print()\n",
"\n",
"print('\\nx:')\n",
"for i in range_n:\n",
" for j in range_n:\n",
" for k in range_N:\n",
" print(int(x[i, j, k].SolutionValue()), end=' ')\n",
" print()\n",
"\n",
"print()\n",
"print('walltime :', solver.WallTime(), 'ms')\n",
"if sol == 'CBC':\n",
" print('iterations:', solver.Iterations())\n",
"\n"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 4
}