{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Constrained sum of elements\n\n\nFrom a shuffled set of integers, find the numbers that minimize the sum of\n5 (five) elements, so that the result is also an odd number\n\nIn this case, since the objective function is the sum of the elements, the order doesn't matter, so we use the ``Combination`` optimizer.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import random\nfrom psopt import Combination\n\n\ndef main():\n    # define objective function: f([a, b, c, ...]) = a + b + c + ...\n    def obj_func(x):\n        return sum(x)\n\n    # list of possible candidates\n    random.seed(0)\n    candidates = random.sample(list(range(1, 12)), 11)\n\n    # constraint: sum of values cannot be even\n    def mod(x):\n        return sum(x) % 2\n\n    constraint = {\"fn\": mod, \"type\": \"==\", \"value\": 1}\n\n    # instantiate the optimizer\n    opt = Combination(obj_func, candidates, constraints=constraint)\n\n    # define a threshold of acceptance for early convergence\n    threshold = 15\n\n    # minimize the obj function\n    results = opt.minimize(selection_size=5, threshold=threshold, seed=0, verbose=1)\n    print(\"Solution: \", results.solution)\n\n    results.history.plot([\"global_best\", \"iteration_best\"])\n\n\nif __name__ == \"__main__\":\n    main()"
      ]
    }
  ],
  "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.7.3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}