Project-Platypus / Platypus

A Free and Open Source Python Library for Multiobjective Optimization
GNU General Public License v3.0
565 stars 153 forks source link

Convert FixedLengthArray default value #96

Closed jbussemaker closed 1 year ago

jbussemaker commented 5 years ago

Currently, if a convert function is given to the FixedLengthArray class, the default value is not passed through this convert function. This gives a problem when defining a new problem that has constraints, but after which the constraint types are not explicitly set:

from platypus import *

problem = Problem(1, 1, nconstrs=1, function=lambda _: ([1], [1]))
problem.types[:] = Real(0, 1)
# problem.constraints[:] = "==0"  # Uncomment this line to make the script work

algorithm = GeneticAlgorithm(problem)
algorithm.run(100)

This script will result in an exception, because the constraints array is initialized with the raw (e.g. non-converted) "==0" value. If the commented line is uncommented, the script works as expected.

The change should be easy: simply run default_value through the convert function if this is given:

class FixedLengthArray(object):

    def __init__(self, size, default_value = None, convert = None):
        super(FixedLengthArray, self).__init__()
        self._size = size
        if convert is not None:
            self._data = [convert(default_value) for _ in range(size)]
        else:
            self._data = [default_value for _ in range(size)]
        self.convert = convert
github-actions[bot] commented 1 year ago

This issue is stale and will be closed soon. If you feel this issue is still relevant, please comment to keep it active. Please also consider working on a fix and submitting a PR.