OpenJij/OpenJij

View on GitHub
docs/tutorial/en/optimization/number_partition.ipynb

Summary

Maintainability
Test Coverage
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Number Partitioning\n",
    "\n",
    "Here we show how to solve the number partitioning problem using OpenJij, [JijModeling](https://www.ref.documentation.jijzept.com/jijmodeling/), and [JijModeling Transpiler](https://www.ref.documentation.jijzept.com/jijmodeling-transpiler/). This problem is also mentioned in 2.1. Number Partitioning in [Lucas, 2014, \"Ising formulations of many NP problems\"](https://doi.org/10.3389/fphy.2014.00005).\n",
    "\n",
    "## Overview of the Number Partitioning Problem\n",
    "Number partitioning is the problem of dividing a given set of numbers into two subsets such that the sum of the numbers is equal.\n",
    "\n",
    "### Example\n",
    "\n",
    "Let us have a set of numbers $A=\\{1, 2, 3, 4\\}$.\n",
    "It is easy to divide this set into equal sums: $\\{1, 4\\}, \\{2, 3\\}$ and the sum of each subset is 5.\n",
    "Thus, when the size of the set is small, the answer is relatively easy to obtain.\n",
    "When the problem is large, however, it is not immediately solvable.\n",
    "Here, we solve this problem using annealing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from jijmodeling.transpiler.pyqubo import to_pyqubo\n",
    "import openjij as oj\n",
    "import jijmodeling as jm\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Mathematical Model\n",
    "First, let us model the Hamiltonian of this problem.\n",
    "Let $A$ be the set to be partitioned and $a_i (i = \\{0,1,\\dots,N-1\\})$ be its elements.\n",
    "Here $N$ is the number of elements in this set.\n",
    "We consider dividing $A$ into two sets $A_0$ and $A_1$.\n",
    "Let $x_i$ be a variable whose $i$th element of $A$ is 0 when it is contained in the set $A_0$ and 1 when it is contained in $A_1$.\n",
    "Using this variable $x_i$, the total value of the numbers in $A_0$ is written as $\\sum_i a_i (1-x_i)$ and $\\sum_i a_i x_i$ for $A_1$.\n",
    "As we find a solution that satisfies the constraint that the sum of the numbers contained in $A_0$ and $A_1$ be equal, this can be expressed as:\n",
    "\n",
    "$$\\sum_i a_i (1-x_i)=\\sum_i a_i x_i$$\n",
    "\n",
    "The problem is to find $x_i$ that satisfies the constraint.\n",
    "By transforming this expression, we can write $\\sum_i a_i (2-x_i)=0$, and by using the Penalty method and squaring this constraint, the Hamiltonian for the number-splitting problem is:\n",
    "\n",
    "$$H=\\left( \\sum_{i=0}^{N-1} a_i (2-x_i)\\right)^2$$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Modeling by JijModeling\n",
    "Next, we show how to implement the above equation using JijModeling.\n",
    "We first define variables for the mathematical model described above."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/latex": [
       "$$\\begin{alignat*}{4}\\text{Problem} & \\text{: number partition} \\\\\\min & \\quad \\left( \\sum_{ i = 0 }^{ N - 1 } a_{i} \\cdot \\left( 2 \\cdot x_{i} - 1 \\right) \\right) ^ { 2 } \\\\& x_{i_{0}} \\in \\{0, 1\\}\\end{alignat*}$$"
      ],
      "text/plain": [
       "<jijmodeling.problem.problem.Problem at 0x120cd3d00>"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "problem = jm.Problem(\"number partition\")\n",
    "a = jm.Placeholder(\"a\",dim = 1)\n",
    "N = a.shape[0].set_latex(\"N\")\n",
    "x = jm.Binary(\"x\",shape=(N,))\n",
    "i = jm.Element(\"i\",(0,N))\n",
    "s_i = 2*x[i] - 1\n",
    "problem += (jm.Sum(i,a[i] * s_i))**2\n",
    "problem"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Instance\n",
    "As an example, let us solve an easy problem; let us consider the problem of dividing numbers from 1 to 40.\n",
    "When dividing consecutive numbers from $N_i$ to $N_f$ and keeping the total number of consecutive numbers even, there are several patterns of division.\n",
    "However, the total value of the divided set is:\n",
    "\n",
    "$$\\mathrm{total\\ value} = \\frac{(N_{i} + N_{f})(N_{f} - N_{i} + 1)}{4}$$\n",
    "\n",
    "In this case, the total value is expected to be 410.\n",
    "Let us confirm this."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "N = 40\n",
    "instance_data = {\"a\":np.arange(1,N+1)}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Conversion to PyQUBO by JijModeling Transpiler\n",
    "JijModeling has executed all the implementations so far.\n",
    "By converting this to [PyQUBO](https://pyqubo.readthedocs.io/en/latest/), it is possible to perform combinatorial optimization calculations using OpenJij and other solvers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "model,cache = to_pyqubo(problem,instance_data,{})\n",
    "Q,offset = model.compile().to_qubo()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The PyQUBO model is created by `to_pyqubo` with the `problem` created by JijModeling and the `instance_data` we set to a value as arguments.\n",
    "Next, we compile it into a QUBO model that can be computed by OpenJij or other solver.\n",
    "\n",
    "### Optimization by OpenJij\n",
    "\n",
    "This time, we will use OpenJij's simulated annealing to solve the optimization problem.\n",
    "We set the `SASampler` and input the QUBO into that sampler to get the result of the calculation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "sampler = oj.SASampler(num_reads=100)\n",
    "response = sampler.sample_qubo(Q=Q)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Decoding and Displaying the Solution\n",
    "Let us take a look at the results obtained.\n",
    "We decode the returned calculation results to facilitate analysis."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "result = cache.decode(response)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We sum the indices classified as $A_1$ and $A_0$ in $A$ here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "class 1 : [ 1  2  3  4  6  7  9 10 11 12 14 18 23 24 28 29 30 32 33 37 38 39] , total value = 410\n",
      "class 0 : [ 5  8 13 15 16 17 19 20 21 22 25 26 27 31 34 35 36 40] , total value = 410\n"
     ]
    }
   ],
   "source": [
    "class_1_index = result.record.solution['x'][0][0][0]\n",
    "class_0_index = [i for i in range(0,N) if i not in class_1_index]\n",
    "\n",
    "class_1 = instance_data['a'][class_1_index]\n",
    "class_0 = instance_data['a'][class_0_index]\n",
    "\n",
    "print(f\"class 1 : {class_1} , total value = {np.sum(class_1)}\")\n",
    "print(f\"class 0 : {class_0} , total value = {np.sum(class_0)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As expected, both total values are 410.\n",
    "Above, we dealt with a problem whose solution is known because it is a consecutive number.\n",
    "We recommend you try more complex problems, such as generating numbers randomly."
   ]
  }
 ],
 "metadata": {
  "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.9.15"
  },
  "vscode": {
   "interpreter": {
    "hash": "2e8d7574d7ec71e14cb1575cf43673432d6fae464c836a7b3733d4f6c20243fb"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}