.. note:: :class: sphx-glr-download-link-note Click :ref:`here ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr_source_auto_examples_combination_plot_constrained_sum.py: =========================== Constrained sum of elements =========================== From a shuffled set of integers, find the numbers that minimize the sum of 5 (five) elements, so that the result is also an odd number In this case, since the objective function is the sum of the elements, the order doesn't matter, so we use the ``Combination`` optimizer. .. image:: /source/auto_examples/combination/images/sphx_glr_plot_constrained_sum_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out Out: .. code-block:: none Iteration 0: global_best: 17.000 iteration_best: 17.000 Iteration 1: global_best: 15.000 iteration_best: 15.000 Iteration completed ========================== Exit code 2: Algorithm has reached the value threshold of 15 Elapsed time 0.011 1 iterations Best selection: [1, 5, 4, 3, 2] Best evaluation: 15.0 Solution: [1, 5, 4, 3, 2] | .. code-block:: default import random from psopt import Combination def main(): # define objective function: f([a, b, c, ...]) = a + b + c + ... def obj_func(x): return sum(x) # list of possible candidates random.seed(0) candidates = random.sample(list(range(1, 12)), 11) # constraint: sum of values cannot be even def mod(x): return sum(x) % 2 constraint = {"fn": mod, "type": "==", "value": 1} # instantiate the optimizer opt = Combination(obj_func, candidates, constraints=constraint) # define a threshold of acceptance for early convergence threshold = 15 # minimize the obj function results = opt.minimize(selection_size=5, threshold=threshold, seed=0, verbose=1) print("Solution: ", results.solution) results.history.plot(["global_best", "iteration_best"]) if __name__ == "__main__": main() .. rst-class:: sphx-glr-timing **Total running time of the script:** ( 0 minutes 0.185 seconds) .. _sphx_glr_download_source_auto_examples_combination_plot_constrained_sum.py: .. only :: html .. container:: sphx-glr-footer :class: sphx-glr-footer-example .. container:: sphx-glr-download :download:`Download Python source code: plot_constrained_sum.py ` .. container:: sphx-glr-download :download:`Download Jupyter notebook: plot_constrained_sum.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_