continuous.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. """Continuous solution classes implementation
  2. """
  3. import numpy as np
  4. # modules imports
  5. from macop.solutions.base import Solution
  6. class ContinuousSolution(Solution):
  7. """
  8. Continuous solution class
  9. - store solution as a float array (example: [0.5, 0.2, 0.17, 0.68, 0.42])
  10. - associated size is the size of the array
  11. - mainly use for selecting or not an element in a list of valuable objects
  12. Attributes:
  13. data: {ndarray} -- array of float values
  14. size: {int} -- size of float array values
  15. score: {float} -- fitness score value
  16. """
  17. def __init__(self, data, size):
  18. """
  19. initialise continuous solution using specific data
  20. Args:
  21. data: {ndarray} -- array of float values
  22. size: {int} -- size of float array values
  23. Example:
  24. >>> from macop.solutions.continuous import ContinuousSolution
  25. >>>
  26. >>> # build of a solution using specific data and size
  27. >>> data = [0.2, 0.4, 0.6, 0.8, 1]
  28. >>> solution = ContinuousSolution(data, len(data))
  29. >>>
  30. >>> # check data content
  31. >>> sum(solution.data) == 3
  32. True
  33. >>> # clone solution
  34. >>> solution_copy = solution.clone()
  35. >>> all(solution_copy.data == solution.data)
  36. True
  37. """
  38. super().__init__(np.array(data), size)
  39. @staticmethod
  40. def random(size, interval, validator=None):
  41. """
  42. Intialize float array with use of validator to generate valid random solution
  43. Args:
  44. size: {int} -- expected solution size to generate
  45. interval: {(float, float)} -- tuple with min and max expected interval value for current solution
  46. validator: {function} -- specific function which validates or not a solution (if None, not validation is applied)
  47. Returns:
  48. {:class:`~macop.solutions.discrete.Continuous`}: new generated continuous solution
  49. Example:
  50. >>> from macop.solutions.continuous import ContinuousSolution
  51. >>>
  52. >>> # generate random solution using specific validator
  53. >>> validator = lambda solution: True if sum(solution.data) > 5 else False
  54. >>> solution = ContinuousSolution.random(10, (-2, 2), validator)
  55. >>> sum(solution.data) > 5
  56. True
  57. """
  58. mini, maxi = interval
  59. data = np.random.random(size=size) * (maxi - mini) + mini
  60. solution = ContinuousSolution(data, size)
  61. if not validator:
  62. return solution
  63. while not validator(solution):
  64. data = np.random.random(size=size) * (maxi - mini) + mini
  65. solution = ContinuousSolution(data, size)
  66. return solution
  67. def __str__(self):
  68. return f"Continuous solution {self._data}"