documentations.rst 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394
  1. ===================
  2. A tour of Macop
  3. ===================
  4. .. image:: _static/logo_macop.png
  5. :width: 300 px
  6. :align: center
  7. This documentation will allow a user who wishes to use the **Macop** optimisation package to understand both how it works and offers examples of how to implement specific needs.
  8. It will gradually take up the major ideas developed within **Macop** to allow for quick development. You can navigate directly via the menu available below to access a specific part of the documentation.
  9. Introduction
  10. ================
  11. `Macop` is a python package for solving discrete optimisation problems in nature. Continuous optimisation is also applicable but not yet developed. The objective is to allow a user to exploit the basic structure proposed by this package to solve a problem specific to him. The interest is that he can quickly abstract himself from the complications related to the way of evaluating, comparing, saving the progress of the search for good solutions but rather concentrate if necessary on his own algorithm. Indeed, `Macop` offers the following main and basic features:
  12. - **solutions:** representation of the solution;
  13. - **validator:** such as constraint programmig, a `validator` is function which is used for validate or not a solution data state;
  14. - **evaluator:** stores problem instance data and implement a `compute` method in order to evaluate a solution;
  15. - **operators:** mutators, crossovers update of solution;
  16. - **policies:** the way you choose the available operators (might be using reinforcement learning);
  17. - **algorithms:** generic and implemented optimisation research algorithms;
  18. - **callbacks:** callbacks to automatically keep track of the search space advancement.
  19. .. image:: _static/documentation/macop_behaviour.png
  20. :width: 50 %
  21. :align: center
  22. Based on all of these generic and/or implemented functionalities, the user will be able to quickly develop a solution to his problem while retaining the possibility of remaining in control of his development by overloading existing functionalities if necessary.
  23. Problem instance
  24. ===================
  25. In this tutorial, we introduce the way of using **Macop** and running your algorithm quickly using the well known `knapsack` problem.
  26. Problem definition
  27. ~~~~~~~~~~~~~~~~~~~~~~
  28. The **knapsack problem** is a problem in combinatorial optimisation: Given a set of items, each with a weight and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible.
  29. The image below provides an illustration of the problem:
  30. .. image:: _static/documentation/knapsack_problem.png
  31. :width: 40 %
  32. :align: center
  33. In this problem, we try to optimise the value associated with the objects we wish to put in our backpack while respecting the capacity of the bag (weight constraint).
  34. .. warning::
  35. It is a combinatorial and therefore discrete problem. **Macop** decomposes its package into two parts, which is related to discrete optimisation on the one hand, and continuous optimisation on the other hand. This will be detailed later.
  36. Problem implementation
  37. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  38. During the whole tutorial, the example used is based on the previous illustration with:
  39. .. image:: _static/documentation/project_knapsack_problem.png
  40. :width: 85 %
  41. :align: center
  42. Hence, we now define our problem in Python:
  43. - worth value of each objects
  44. - weight associated to each of these objects
  45. .. code-block:: python
  46. """
  47. Problem instance definition
  48. """
  49. elements_score = [ 4, 2, 10, 1, 2 ] # worth of each object
  50. elements_weight = [ 12, 1, 4, 1, 2 ] # weight of each object
  51. Once we have defined the instance of our problem, we will need to define the representation of a solution to that problem.
  52. Let's define the ``SimpleBinaryCrossover`` operator, allows to randomly change a binary value of our current solution.
  53. Solutions
  54. =============
  55. Representing a solution to a specific problem is very important in an optimisation process. In this example, we will always use the **knapsack problem** as a basis.
  56. In a first step, the management of the solutions by the macop package will be presented. Then a specific implementation for the current problem will be detailed.
  57. Generic Solution
  58. ~~~~~~~~~~~~~~~~~~~~~~~~~
  59. Inside macop.solutions.base_ module of `Macop`, the ``Solution`` class is available. It's an abstract solution class structure which:
  60. - stores the solution data representation into its ``data`` attribute
  61. - get ``size`` (shape) of specific data representation
  62. - stores the ``score`` of the solution once a solution is evaluated
  63. Some specific methods are available:
  64. .. code-block:: python
  65. class Solution():
  66. def __init__(self, data, size):
  67. """
  68. Abstract solution class constructor
  69. """
  70. ...
  71. def isValid(self, validator):
  72. """
  73. Use of custom function which checks if a solution is valid or not
  74. """
  75. ...
  76. def evaluate(self, evaluator):
  77. """
  78. Evaluate solution using specific `evaluator`
  79. """
  80. ...
  81. @property
  82. def fitness(self):
  83. """
  84. Returns fitness score (by default `score` private attribute)
  85. """
  86. ...
  87. @fitness.setter
  88. def fitness(self, score):
  89. """
  90. Set solution score as wished (by default `score` private attribute)
  91. """
  92. ...
  93. @property
  94. def data(self):
  95. """
  96. Returns solution data (by default `data` private attribute)
  97. """
  98. ...
  99. @data.setter
  100. def data(self, data):
  101. """
  102. Set solution data (by default `data` private attribute)
  103. """
  104. ...
  105. @staticmethod
  106. def random(size, validator=None):
  107. """
  108. initialise solution using random data with validator or not
  109. """
  110. ...
  111. def clone(self):
  112. """
  113. Clone the current solution and its data, but without keeping evaluated `_score`
  114. """
  115. ...
  116. .. caution::
  117. An important thing here are the ``fitness`` and ``data`` functions brought as an editable attribute by the ``@property`` and ``@XXXXX.setter`` decorators. The idea is to allow the user to modify these functions in order to change the expected result of the algorithm regardless of the data to be returned/modified.
  118. From these basic methods, it is possible to manage a representation of a solution to our problem.
  119. Allowing to initialise it randomly or not (using constructor or ``random`` method), to evaluate it (``evaluate`` method) and to check some constraints of validation of the solution (``isValid`` method).
  120. .. note::
  121. Only one of these methods needs specification if we create our own type of solution. This is the ``random`` method, which depends on the need of the problem.
  122. We will now see how to define a type of solution specific to our problem.
  123. Solution representation for knapsack
  124. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  125. We will now use the abstract ``Solution`` type available in the macop.solutions.base_ module in order to define our own solution.
  126. First of all, let's look at the representation of our knapsack problem. **How to represent the solution?**
  127. Knapsack solution
  128. ************************
  129. A valid solution can be shown below where the sum of the object weights is 15 and the sum of the selected objects values is 8 (its fitness):
  130. .. image:: _static/documentation/project_knapsack_solution.png
  131. :width: 85 %
  132. :align: center
  133. Its representation can be translate as a **binary array** with value:
  134. .. code-block::
  135. [1, 1, 0, 0, 1]
  136. where selected objects have **1** as value otherwise **0**.
  137. Binary Solution
  138. **********************
  139. We will now define our own type of solution by inheriting from macop.solutions.base.Solution_, which we will call ``BinarySolution``.
  140. First we will define our new class as inheriting functionality from ``Solution`` (such as child class).
  141. We will also have to implement the ``random`` method to create a new random solution.
  142. .. code-block:: python
  143. """
  144. modules imports
  145. """
  146. from macop.solutions.base import Solution
  147. import numpy as np
  148. class BinarySolution(Solution):
  149. @staticmethod
  150. def random(size, validator=None):
  151. # create binary array of specific size using numpy random module
  152. data = np.random.randint(2, size=size)
  153. # initialise new solution using constructor
  154. solution = BinarySolution(data, size)
  155. # check if validator is set
  156. if not validator:
  157. return solution
  158. # try to generate solution until solution validity (if validator is provided)
  159. while not validator(solution):
  160. data = np.random.randint(2, size=size)
  161. solution = BinarySolution(data, size)
  162. return solution
  163. .. note::
  164. The current developed ``BinarySolution`` is available into macop.solutions.discrete.BinarySolution_ in **Macop**.
  165. Using this new Solution representation, we can now generate solution randomly:
  166. .. code-block:: python
  167. solution = BinarySolution.random(5)
  168. In the next part, we will see how to verify that a solution meets certain modeling constraints of the problem.
  169. Validate a solution
  170. ======================
  171. When an optimisation problem requires respecting certain constraints, Macop allows you to quickly verify that a solution is valid.
  172. It is based on a defined function taking a solution as input and returning the validity criterion (true or false).
  173. Validator definition
  174. ~~~~~~~~~~~~~~~~~~~~~~~~~
  175. An invalid solution can be shown below where the sum of the object weights is greater than 15:
  176. .. image:: _static/documentation/project_knapsack_invalid.png
  177. :width: 85 %
  178. :align: center
  179. In fact, **[1, 0, 1, 0, 0]** is an invalid solution as we have a weight of **16** which violates the knapsack capacity constraint.
  180. To avoid taking into account invalid solutions, we can define our function which will validate or not a solution based on our problem instance:
  181. .. code-block:: python
  182. """
  183. Problem instance definition
  184. """
  185. elements_score = [ 4, 2, 10, 1, 2 ] # worth of each object
  186. elements_weight = [ 12, 1, 4, 1, 2 ] # weight of each object
  187. """
  188. Validator function definition
  189. """
  190. def validator(solution):
  191. weight_sum = 0
  192. for i, w in enumerate(elements_weight):
  193. # add weight if current object is set to 1
  194. weight_sum += w * solution.data[i]
  195. # validation condition
  196. return weight_sum <= 15
  197. Use of validator
  198. ~~~~~~~~~~~~~~~~~~~~~
  199. We can now generate solutions randomly by passing our validation function as a parameter:
  200. .. code-block:: python
  201. """
  202. Problem instance definition
  203. """
  204. ...
  205. """
  206. Validator function definition
  207. """
  208. ...
  209. # ensure valid solution
  210. solution = BinarySolution.random(5, validator)
  211. .. caution::
  212. If the search space for valid solutions is very small compared to the overall search space, this can involve a considerable time for validating the solution and therefore obtaining a solution.
  213. The validation of a solution is therefore now possible. In the next part we will focus on the evaluation of a solution.
  214. Use of evaluators
  215. ====================
  216. Now that it is possible to generate a solution randomly or not. It is important to know the value associated with this solution. We will then speak of evaluation of the solution. With the score associated with it, the `fitness`.
  217. Generic evaluator
  218. ~~~~~~~~~~~~~~~~~~~~~~
  219. As for the management of solutions, a generic evaluator class macop.evaluators.base.Evaluator_ is developed within **Macop**:
  220. Abstract Evaluator class is used for computing fitness score associated to a solution. To evaluate all the solutions, this class:
  221. - stores into its ``_data`` dictionary attritute required measures when computing a solution
  222. - has a ``compute`` abstract method enable to compute and associate a score to a given solution
  223. - stores into its ``_algo`` attritute the current algorithm to use (we will talk about algorithm later)
  224. .. code-block: python
  225. class Evaluator():
  226. """
  227. Abstract Evaluator class which enables to compute solution using specific `_data`
  228. """
  229. def __init__(self, data):
  230. self._data = data
  231. @abstractmethod
  232. def compute(self, solution):
  233. """
  234. Apply the computation of fitness from solution
  235. """
  236. pass
  237. def setAlgo(self, algo):
  238. """
  239. Keep into evaluator reference of the whole algorithm
  240. """
  241. self._algo = algo
  242. We must therefore now create our own evaluator based on the proposed structure.
  243. Custom evaluator
  244. ~~~~~~~~~~~~~~~~~~~~~
  245. To create our own evaluator, we need both:
  246. - data useful for evaluating a solution
  247. - calculate the score (fitness) associated with the state of the solution from these data. Hence, implement specific ``compute`` method.
  248. We will define the ``KnapsackEvaluator`` class, which will therefore allow us to evaluate solutions to our current problem.
  249. .. code-block:: python
  250. """
  251. modules imports
  252. """
  253. from macop.evaluators.base import Evaluator
  254. class KnapsackEvaluator(Evaluator):
  255. def compute(solution):
  256. # `_data` contains worths array values of objects
  257. fitness = 0
  258. for index, elem in enumerate(solution.data):
  259. fitness += self._data['worths'][index] * elem
  260. return fitness
  261. It is now possible to initialise our new evaluator with specific data of our problem instance:
  262. .. code-block:: python
  263. """
  264. Problem instance definition
  265. """
  266. elements_score = [ 4, 2, 10, 1, 2 ] # worth of each object
  267. elements_weight = [ 12, 1, 4, 1, 2 ] # weight of each object
  268. """
  269. Evaluator problem instance
  270. """
  271. evaluator = KnapsackEvaluator(data={'worths': elements_score})
  272. # using defined BinarySolution
  273. solution = BinarySolution.random(5)
  274. # obtaining current solution score
  275. solution_fitness = solution.evaluate(evaluator)
  276. # score is also stored into solution
  277. solution_fitness = solution.fitness
  278. .. note::
  279. The current developed ``KnapsackEvaluator`` is available into macop.evaluators.discrete.mono.KnapsackEvaluator_ in **Macop**.
  280. In the next part we will see how to modify our current solution with the use of modification operator.
  281. Apply operators to solution
  282. ==============================
  283. Applying an operator to a solution consists of modifying the current state of the solution in order to obtain a new one. The goal is to find a better solution in the search space.
  284. Operators definition
  285. ~~~~~~~~~~~~~~~~~~~~~~~~~
  286. In the discrete optimisation literature, we can categorise operators into two sections:
  287. - **mutators**: modification of one or more elements of a solution from its current state.
  288. - **crossovers**: Inspired by Darwin's theory of evolution, we are going here from two solutions to generate a so-called offspring solution composed of the fusion of the data of the parent solutions.
  289. Inside **Macop**, operators are also decomposed into these two categories. Inside macop.operators.base_, generic class ``Operator`` enables to manage any kind of operator.
  290. .. code-block:: python
  291. class Operator():
  292. """
  293. Abstract Operator class which enables to update solution applying operator (computation)
  294. """
  295. @abstractmethod
  296. def __init__(self):
  297. pass
  298. @abstractmethod
  299. def apply(self, solution):
  300. """
  301. Apply the current operator transformation
  302. """
  303. pass
  304. def setAlgo(self, algo):
  305. """
  306. Keep into operator reference of the whole algorithm
  307. """
  308. self._algo = algo
  309. Like the evaluator, the operator keeps **track of the algorithm** (using ``setAlgo`` method) to which he will be linked. This will allow better management of the way in which the operator must take into account the state of current data relating to the evolution of research.
  310. ``Mutation`` and ``Crossover`` classes inherite from ``Operator``. An ``apply`` function is required for any new operator.
  311. .. code-block:: python
  312. class Mutation(Operator):
  313. """Abstract Mutation extend from Operator
  314. Attributes:
  315. kind: {:class:`~macop.operators.base.KindOperator`} -- specify the kind of operator
  316. """
  317. def __init__(self):
  318. self._kind = KindOperator.MUTATOR
  319. def apply(self, solution):
  320. raise NotImplementedError
  321. class Crossover(Operator):
  322. """Abstract crossover extend from Operator
  323. Attributes:
  324. kind: {:class:`~macop.operators.base.KindOperator`} -- specify the kind of operator
  325. """
  326. def __init__(self):
  327. self._kind = KindOperator.CROSSOVER
  328. def apply(self, solution1, solution2):
  329. raise NotImplementedError
  330. We will now detail these categories of operators and suggest some relative to our problem.
  331. Mutator operator
  332. ~~~~~~~~~~~~~~~~~~~~~
  333. As detailed, the mutation operator consists in having a minimum impact on the current state of our solution. Here is an example of a modification that could be done for our problem.
  334. .. image:: _static/documentation/project_knapsack_mutator.png
  335. :width: 90 %
  336. :align: center
  337. In this example we change a bit value randomly and obtain a new solution from our search space.
  338. .. warning::
  339. Applying an operator can conduct to a new but invalid solution from the search space.
  340. The modification applied here is just a bit swapped. Let's define the ``SimpleBinaryMutation`` operator, allows to randomly change a binary value of our current solution.
  341. .. code-block:: python
  342. """
  343. modules imports
  344. """
  345. from macop.operators.discrete.base import Mutation
  346. class SimpleBinaryMutation(Mutation):
  347. def apply(self, solution):
  348. # obtain targeted cell using solution size
  349. size = solution._size
  350. cell = random.randint(0, size - 1)
  351. # copy of solution
  352. copy_solution = solution.clone()
  353. # swicth values
  354. if copy_solution.data[cell]:
  355. copy_solution.data[cell] = 0
  356. else:
  357. copy_solution.data[cell] = 1
  358. # return the new obtained solution
  359. return copy_solution
  360. We can now instanciate our new operator in order to obtain a new solution:
  361. .. code-block:: python
  362. """
  363. BinaryMutator instance
  364. """
  365. mutator = SimpleBinaryMutation()
  366. # using defined BinarySolution
  367. solution = BinarySolution.random(5)
  368. # obtaining new solution using operator
  369. new_solution = mutator.apply(solution)
  370. .. note::
  371. The developed ``SimpleBinaryMutation`` is available into macop.operators.discrete.mutators.SimpleBinaryMutation_ in **Macop**.
  372. Crossover operator
  373. ~~~~~~~~~~~~~~~~~~~~~~~
  374. Inspired by Darwin's theory of evolution, crossover starts from two solutions to generate a so-called offspring solution composed of the fusion of the data of the parent solutions.
  375. .. image:: _static/documentation/project_knapsack_crossover.png
  376. :width: 95%
  377. :align: center
  378. In this example we merge two solutions with a specific splitting criterion in order to obtain an offspring.
  379. We will now implement the SimpleCrossover crossover operator, which will merge data from two solutions.
  380. The first half of solution 1 will be saved and added to the second half of solution 2 to generate the new solution (offspring).
  381. .. code-block:: python
  382. """
  383. modules imports
  384. """
  385. from macop.operators.discrete.base import Crossover
  386. class SimpleCrossover(Crossover):
  387. def apply(self, solution1, solution2):
  388. size = solution1._size
  389. # default split index used
  390. splitIndex = int(size / 2)
  391. # copy data of solution 1
  392. firstData = solution1._data.copy()
  393. # copy of solution 2
  394. copy_solution = solution2.clone()
  395. copy_solution.data[splitIndex:] = firstData[splitIndex:]
  396. return copy_solution
  397. We can now use the crossover operator created to generate new solutions. Here is an example of use:
  398. .. code-block:: python
  399. """
  400. SimpleCrossover instance
  401. """
  402. crossover = SimpleCrossover()
  403. # using defined BinarySolution
  404. solution1 = BinarySolution.random(5)
  405. solution2 = BinarySolution.random(5)
  406. # obtaining new solution using crossover
  407. offspring = crossover.apply(solution1, solution2)
  408. .. tip::
  409. The developed ``SimpleCrossover`` is available into macop.operators.discrete.crossovers.SimpleCrossover_ in **Macop**.
  410. However, the choice of halves of the merged data is made randomly.
  411. Next part introduce the ``policy`` feature of **Macop** which enables to choose the next operator to apply during the search process based on specific criterion.
  412. Operator choices
  413. ===================
  414. The ``policy`` feature of **Macop** enables to choose the next operator to apply during the search process of the algorithm based on specific criterion.
  415. Why using policy ?
  416. ~~~~~~~~~~~~~~~~~~~~~~~
  417. Sometimes the nature of the problem and its instance can strongly influence the search results when using mutation operators or crossovers.
  418. Automated operator choice strategies have also been developed in the literature, notably based on reinforcement learning.
  419. The operator choice problem can be seen as the desire to find the best solution generation operator at the next evaluation that will be the most conducive to precisely improving the solution.
  420. .. image:: _static/documentation/operators_choice.png
  421. :width: 45 %
  422. :align: center
  423. .. note::
  424. An implementation using reinforcement learning has been developed as an example in the macop.policies.reinforcement_ module.
  425. However, it will not be detailed here. You can refer to the API documentation for more details.
  426. Custom policy
  427. ~~~~~~~~~~~~~~~~~~
  428. In our case, we are not going to exploit a complex enough implementation of a ``policy``. Simply, we will use a random choice of operator.
  429. First, let's take a look of the ``policy`` abstract class available in macop.policies.base_:
  430. .. code-block:: python
  431. class Policy():
  432. def __init__(self, operators):
  433. self._operators = operators
  434. @abstractmethod
  435. def select(self):
  436. """
  437. Select specific operator
  438. """
  439. pass
  440. def apply(self, solution):
  441. """
  442. Apply specific operator to create new solution, compute its fitness and return it
  443. """
  444. ...
  445. def setAlgo(self, algo):
  446. """
  447. Keep into policy reference of the whole algorithm
  448. """
  449. ...
  450. ``Policy`` instance will have of ``_operators`` attributs in order to keep track of possible operators when selecting one.
  451. Here, in our implementation we only need to specify the ``select`` abstract method. The ``apply`` method will select the next operator and return the new solution.
  452. .. code-block:: python
  453. """
  454. module imports
  455. """
  456. from macop.policies.base import Policy
  457. class RandomPolicy(Policy):
  458. def select(self):
  459. """
  460. Select specific operator
  461. """
  462. # choose operator randomly
  463. index = random.randint(0, len(self._operators) - 1)
  464. return self._operators[index]
  465. We can now use this operator choice policy to update our current solution:
  466. .. code-block:: python
  467. """
  468. Operators instances
  469. """
  470. mutator = SimpleMutation()
  471. crossover = SimpleCrossover()
  472. """
  473. RandomPolicy instance
  474. """
  475. policy = RandomPolicy([mutator, crossover])
  476. """
  477. Current solutions instance
  478. """
  479. solution1 = BinarySolution.random(5)
  480. solution2 = BinarySolution.random(5)
  481. # pass two solutions in parameters in case of selected crossover operator
  482. new_solution = policy.apply(solution1, solution2)
  483. .. caution::
  484. By default if ``solution2`` parameter is not provided into ``policy.apply`` method for crossover, the best solution known is used from the algorithm linked to the ``policy``.
  485. Updating solutions is therefore now possible with our policy. It is high time to dive into the process of optimizing solutions and digging into our research space.
  486. Optimisation process
  487. =======================
  488. Let us now tackle the interesting part concerning the search for optimum solutions in our research space.
  489. Find local and global optima
  490. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  491. Overall, in an optimization process, we will seek to find the best, or the best solutions that minimize or maximize our objective function (fitness score obtained) in order to respond to our problem.
  492. .. image:: _static/documentation/search_space.png
  493. :width: 95 %
  494. :align: center
  495. Sometimes, the search space can be very simple. A local search can provide access to the global optimum as shown in figure (a) above.
  496. In other cases, the search space is more complex. It may be necessary to explore more rather than exploit in order to get out of a convex zone and not find the global optimum but only a local opmatime solution.
  497. This problem is illustrated in figure (b).
  498. Abstract algorithm class
  499. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  500. An abstract class is proposed within Macop to generalize the management of an algorithm and therefore of a heuristic.
  501. It is located in the macop.algorithms.base_ module.
  502. We will pay attention to the different methods of which she is composed. This class enables to manage some common usages of operation research algorithms:
  503. - initialization function of solution
  504. - validator function to check if solution is valid or not (based on some criteria)
  505. - evaluation function to give fitness score to a solution
  506. - operators used in order to update solution during search process
  507. - policy process applied when choosing next operator to apply
  508. - callbacks function in order to do some relative stuff every number of evaluation or reload algorithm state
  509. - parent algorithm associated to this new algorithm instance (hierarchy management)
  510. She is composed of few default attributes:
  511. - initialiser: {function} -- basic function strategy to initialise solution
  512. - evaluator: {:class:`~macop.evaluators.base.Evaluator`} -- evaluator instance in order to obtained fitness (mono or multiple objectives)
  513. - operators: {[:class:`~macop.operators.base.Operator`]} -- list of operator to use when launching algorithm
  514. - policy: {:class:`~macop.policies.base.Policy`} -- Policy instance strategy to select operators
  515. - validator: {function} -- basic function to check if solution is valid or not under some constraints
  516. - maximise: {bool} -- specify kind of optimisation problem
  517. - verbose: {bool} -- verbose or not information about the algorithm
  518. - currentSolution: {:class:`~macop.solutions.base.Solution`} -- current solution managed for current evaluation comparison
  519. - bestSolution: {:class:`~macop.solutions.base.Solution`} -- best solution found so far during running algorithm
  520. - callbacks: {[:class:`~macop.callbacks.base.Callback`]} -- list of Callback class implementation to do some instructions every number of evaluations and `load` when initialising algorithm
  521. - parent: {:class:`~macop.algorithms.base.Algorithm`} -- parent algorithm reference in case of inner Algorithm instance (optional)
  522. .. code-block:: python
  523. class Algorithm():
  524. def __init__(self,
  525. initialiser,
  526. evaluator,
  527. operators,
  528. policy,
  529. validator,
  530. maximise=True,
  531. parent=None,
  532. verbose=True):
  533. ...
  534. def addCallback(self, callback):
  535. """
  536. Add new callback to algorithm specifying usefull parameters
  537. """
  538. ...
  539. def resume(self):
  540. """
  541. Resume algorithm using Callback instances
  542. """
  543. ...
  544. @property
  545. def result(self):
  546. """Get the expected result of the current algorithm
  547. By default the best solution (but can be anything you want)
  548. """
  549. ...
  550. @result.setter
  551. def result(self, result):
  552. """Set current default result of the algorithm
  553. """
  554. ...
  555. def getParent(self):
  556. """
  557. Recursively find the main parent algorithm attached of the current algorithm
  558. """
  559. ...
  560. def setParent(self, parent):
  561. """
  562. Set parent algorithm to current algorithm
  563. """
  564. ...
  565. def initRun(self):
  566. """
  567. initialise the current solution and best solution using the `initialiser` function
  568. """
  569. ...
  570. def increaseEvaluation(self):
  571. """
  572. Increase number of evaluation once a solution is evaluated for each dependant algorithm (parents hierarchy)
  573. """
  574. ...
  575. def getGlobalEvaluation(self):
  576. """
  577. Get the global number of evaluation (if inner algorithm)
  578. """
  579. ...
  580. def getGlobalMaxEvaluation(self):
  581. """
  582. Get the global max number of evaluation (if inner algorithm)
  583. """
  584. ...
  585. def stop(self):
  586. """
  587. Global stopping criteria (check for parents algorithm hierarchy too)
  588. """
  589. ...
  590. def evaluate(self, solution):
  591. """
  592. Evaluate a solution using evaluator passed when intialize algorithm
  593. """
  594. ...
  595. def update(self, solution):
  596. """
  597. Apply update function to solution using specific `policy`
  598. Check if solution is valid after modification and returns it
  599. """
  600. ...
  601. def isBetter(self, solution):
  602. """
  603. Check if solution is better than best found
  604. """
  605. ...
  606. def run(self, evaluations):
  607. """
  608. Run the specific algorithm following number of evaluations to find optima
  609. """
  610. ...
  611. def progress(self):
  612. """
  613. Log progress and apply callbacks if necessary
  614. """
  615. ...
  616. .. caution::
  617. An important thing here are the ``result`` functions brought as an editable attribute by the ``@property`` and ``@result.setter`` decorators. The idea is to allow the user to modify these functions in order to change the expected result of the algorithm regardless of the data to be returned/modified.
  618. The notion of hierarchy between algorithms is introduced here. We can indeed have certain dependencies between algorithms.
  619. The methods ``increaseEvaluation``, ``getGlobalEvaluation`` and ``getGlobalMaxEvaluation`` ensure that the expected global number of evaluations is correctly managed, just like the ``stop`` method for the search stop criterion.
  620. The ``evaluate``, ``update`` and ``isBetter`` will be used a lot when looking for a solution in the search space.
  621. In particular the ``update`` function, which will call the ``policy`` instance to generate a new valid solution.
  622. ``isBetter`` method is also overloadable especially if the algorithm does not take any more into account than a single solution to be verified (verification via a population for example).
  623. The ``initRun`` method specify the way you intialise your algorithm (``bestSolution`` and ``currentSolution`` as example) if algorithm not already initialised.
  624. .. note::
  625. The ``initRun`` method can also be used for intialise population of solutions instead of only one best solution, if you want to manage a genetic algorithm.
  626. Most important part is the ``run`` method. Into abstract, the ``run`` method only initialised the current number of evaluation for the algorithm based on the parent algorithm if we are into inner algorithm.
  627. It is always **mandatory** to call the parent class ``run`` method using ``super().run(evaluations)``. Then, using ``evaluations`` parameter which is the number of evaluations budget to run, we can process or continue to find solutions into search space.
  628. .. warning::
  629. The other methods such as ``addCallback``, ``resume`` and ``progress`` will be detailed in the next part focusing on the notion of callback.
  630. Local search algorithm
  631. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  632. We are going to carry out our first local search algorithm within our search space. A `local search` consists of starting from a solution, then applying a mutation or crossover operation to it, in order to obtain a new one.
  633. This new solution is evaluated and retained if it is better. We will speak here of the notion of **neighborhood exploration**. The process is then completed in the same way.
  634. The local search ends after a certain number of evaluations and the best evaluated solution obtained is returned.
  635. Let's implement an algorithm well known under the name of hill climber best improvment inheriting from the mother algorithm class and name it ``HillClimberBestImprovment``.
  636. .. code-block:: python
  637. """
  638. module imports
  639. """
  640. from macop.algorithms.base import Algorithm
  641. class HillClimberBestImprovment(Algorithm):
  642. def run(self, evaluations):
  643. """
  644. Run a local search algorithm
  645. """
  646. # by default use of mother method to initialise variables
  647. super().run(evaluations)
  648. # initialise current solution and best solution
  649. self.initRun()
  650. solutionSize = self._currentSolution._size
  651. # local search algorithm implementation
  652. while not self.stop():
  653. for _ in range(solutionSize):
  654. # update current solution using policy
  655. newSolution = self.update(self._currentSolution)
  656. # if better solution than currently, replace it
  657. if self.isBetter(newSolution):
  658. self._bestSolution = newSolution
  659. # increase number of evaluations
  660. self.increaseEvaluation()
  661. # stop algorithm if necessary
  662. if self.stop():
  663. break
  664. # set new current solution using best solution found in this neighbor search
  665. self._currentSolution = self._bestSolution
  666. return self._bestSolution
  667. Our algorithm is now ready to work. As previously, let us define two operators as well as a random choice strategy.
  668. We will also need to define a **solution initialisation function** so that the algorithm can generate new solutions.
  669. .. code-block:: python
  670. """
  671. Problem instance definition
  672. """
  673. elements_score = [ 4, 2, 10, 1, 2 ] # worth of each object
  674. elements_weight = [ 12, 1, 4, 1, 2 ] # weight of each object
  675. # evaluator instance
  676. evaluator = KnapsackEvaluator(data={'worths': elements_score})
  677. # valid instance using lambda
  678. validator = lambda solution: sum([ elements_weight[i] * solution.data[i] for i in range(len(solution.data))]) <= 15
  679. # initialiser instance using lambda with default param value
  680. initialiser = lambda x=5: BinarySolution.random(x, validator)
  681. # operators list with crossover and mutation
  682. operators = [SimpleCrossover(), SimpleMutation()]
  683. # policy random instance
  684. policy = RandomPolicy(operators)
  685. # maximizing algorithm (relative to knapsack problem)
  686. algo = HillClimberBestImprovment(initialiser, evaluator, operators, policy, validator, maximise=True, verbose=False)
  687. # run the algorithm and get solution found
  688. solution = algo.run(100)
  689. print(solution.fitness)
  690. .. note::
  691. The ``verbose`` algorithm parameter will log into console the advancement process of the algorithm is set to ``True`` (the default value).
  692. Exploratory algorithm
  693. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  694. As explained in **figure (b)** of **section 8.1**, sometimes the search space is more complicated due to convex parts and need heuristic with other strategy rather than a simple local search.
  695. The way to counter this problem is to allow the algorithm to exit the exploitation phase offered by local search. But rather to seek to explore other parts of the research space. This is possible by simply carrying out several local searches with our budget (number of evaluations).
  696. The idea is to make a leap in the search space in order to find a new local optimum which can be the global optimum. The explained process is illustrated below:
  697. .. image:: _static/documentation/search_space_simple.png
  698. :width: 45 %
  699. :align: center
  700. We are going to implement a more specific algorithm allowing to take a new parameter as input. This is a local search, the one previously developed. For that, we will have to modify the constructor a little.
  701. Let's called this new algorithm ``IteratedLocalSearch``:
  702. .. code-block:: python
  703. """
  704. module imports
  705. """
  706. from macop.algorithms.base import Algorithm
  707. class IteratedLocalSearch(Algorithm):
  708. def __init__(self,
  709. initialiser,
  710. evaluator,
  711. operators,
  712. policy,
  713. validator,
  714. localSearch,
  715. maximise=True,
  716. parent=None,
  717. verbose=True):
  718. super().__init__(initialiser, evaluator, operators, policy, validator, maximise, parent, verbose)
  719. # specific local search associated with current algorithm
  720. self._localSearch = localSearch
  721. # need to attach current algorithm as parent
  722. self._localSearch.setParent(self)
  723. def run(self, evaluations, ls_evaluations=100):
  724. """
  725. Run the iterated local search algorithm using local search
  726. """
  727. # by default use of mother method to initialise variables
  728. super().run(evaluations)
  729. # initialise current solution
  730. self.initRun()
  731. # local search algorithm implementation
  732. while not self.stop():
  733. # create and search solution from local search (stop method can be called inside local search)
  734. newSolution = self._localSearch.run(ls_evaluations)
  735. # if better solution than currently, replace it
  736. if self.isBetter(newSolution):
  737. self._bestSolution = newSolution
  738. self.information()
  739. return self._bestSolution
  740. In the initialization phase we have attached our local search passed as a parameter with the current algorithm as parent.
  741. The goal is to touch keep track of the overall search evaluation number (relative to the parent algorithm).
  742. Then, we use this local search in our ``run`` method to allow a better search for solutions.
  743. .. code-block:: python
  744. """
  745. Problem instance definition
  746. """
  747. elements_score = [ 4, 2, 10, 1, 2 ] # worth of each object
  748. elements_weight = [ 12, 1, 4, 1, 2 ] # weight of each object
  749. # evaluator instance
  750. evaluator = KnapsackEvaluator(data={'worths': elements_score})
  751. # valid instance using lambda
  752. validator = lambda solution: sum([ elements_weight[i] * solution.data[i] for i in range(len(solution.data))]) <= 15
  753. # initialiser instance using lambda with default param value
  754. initialiser = lambda x=5: BinarySolution.random(x, validator)
  755. # operators list with crossover and mutation
  756. operators = [SimpleCrossover(), SimpleMutation()]
  757. # policy random instance
  758. policy = RandomPolicy(operators)
  759. # maximizing algorithm (relative to knapsack problem)
  760. localSearch = HillClimberBestImprovment(initialiser, evaluator, operators, policy, validator, maximise=True, verbose=False)
  761. algo = IteratedLocalSearch(initialiser, evaluator, operators, policy, validator, localSearch=local_search, maximise=True, verbose=False)
  762. # run the algorithm using local search and get solution found
  763. solution = algo.run(evaluations=100, ls_evaluations=10)
  764. print(solution.fitness)
  765. .. note::
  766. These two last algorithms developed are available in the library within the module macop.algorithms.mono_.
  767. We have one final feature to explore in the next part. This is the notion of ``callback``.
  768. Keep track
  769. ==============
  770. Keeping track of the running algorithm can be useful on two levels. First of all to understand how it unfolded at the end of the classic run. But also in the case of the unwanted shutdown of the algorithm.
  771. This section will allow you to introduce the recovery of the algorithm thanks to a continuous backup functionality.
  772. Logging into algorithm
  773. ~~~~~~~~~~~~~~~~~~~~~~
  774. Some logs can be retrieve after running an algorithm. **Macop** uses the ``logging`` Python package in order to log algorithm advancement.
  775. Here is an example of use when running an algorithm:
  776. .. code-block:: python
  777. """
  778. basic imports
  779. """
  780. import logging
  781. # logging configuration
  782. logging.basicConfig(format='%(asctime)s %(message)s', filename='data/example.log', level=logging.DEBUG)
  783. ...
  784. # maximizing algorithm (relative to knapsack problem)
  785. algo = HillClimberBestImprovment(initialiser, evaluator, operators, policy, validator, maximise=True, verbose=False)
  786. # run the algorithm using local search and get solution found
  787. solution = algo.run(evaluations=100)
  788. print(solution.fitness)
  789. Hence, log data are saved into ``data/example.log`` in our example.
  790. Callbacks introduction
  791. ~~~~~~~~~~~~~~~~~~~~~~~
  792. Having output logs can help to understand an error that has occurred, however all the progress of the research carried out may be lost.
  793. For this, the functionality relating to callbacks has been developed.
  794. Within **Macop**, a callback is a specific instance of macop.callbacks.base.Callback_ that allows you to perform an action of tracing / saving information **every** ``n`` **evaluations** but also reloading information if necessary when restarting an algorithm.
  795. .. code-block:: python
  796. class Callback():
  797. def __init__(self, every, filepath):
  798. ...
  799. @abstractmethod
  800. def run(self):
  801. """
  802. Check if necessary to do backup based on `every` variable
  803. """
  804. pass
  805. @abstractmethod
  806. def load(self):
  807. """
  808. Load last backup line of solution and set algorithm state at this backup
  809. """
  810. pass
  811. def setAlgo(self, algo):
  812. """
  813. Specify the main algorithm instance reference
  814. """
  815. ...
  816. - The ``run`` method will be called during run process of the algo and do backup at each specific number of evaluations.
  817. - The ``load`` method will be used to reload the state of the algorithm from the last information saved. All saved data is saved in a file whose name will be specified by the user.
  818. Towards the use of Callbacks
  819. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  820. We are going to create our own Callback instance called ``BasicCheckpoint`` which will save the best solution found and number of evaluations done in order to reload it for the next run of our algorithm.
  821. .. code-block:: python
  822. """
  823. module imports
  824. """
  825. from macop.callbacks.base import Callback
  826. class BasicCheckpoint(Callback):
  827. def run(self):
  828. """
  829. Check if necessary to do backup based on `every` variable
  830. """
  831. # get current best solution
  832. solution = self._algo._bestSolution
  833. currentEvaluation = self._algo.getGlobalEvaluation()
  834. # backup if necessary every number of evaluations
  835. if currentEvaluation % self._every == 0:
  836. # create specific line with solution data
  837. solution.data = ""
  838. solutionSize = len(solution.data)
  839. for index, val in enumerate(solution.data):
  840. solution.data += str(val)
  841. if index < solutionSize - 1:
  842. solution.data += ' '
  843. # number of evaluations done, solution data and fitness score
  844. line = str(currentEvaluation) + ';' + solution.data + ';' + str(
  845. solution.fitness) + ';\n'
  846. # check if file exists
  847. if not os.path.exists(self._filepath):
  848. with open(self._filepath, 'w') as f:
  849. f.write(line)
  850. else:
  851. with open(self._filepath, 'a') as f:
  852. f.write(line)
  853. def load(self):
  854. """
  855. Load last backup line and set algorithm state (best solution and evaluations)
  856. """
  857. if os.path.exists(self._filepath):
  858. with open(self._filepath) as f:
  859. # get last line and read data
  860. lastline = f.readlines()[-1]
  861. data = lastline.split(';')
  862. # get evaluation information
  863. globalEvaluation = int(data[0])
  864. # restore number of evaluations
  865. if self._algo.getParent() is not None:
  866. self._algo.getParent()._numberOfEvaluations = globalEvaluation
  867. else:
  868. self._algo._numberOfEvaluations = globalEvaluation
  869. # get best solution data information
  870. solution.data = list(map(int, data[1].split(' ')))
  871. # avoid uninitialised solution
  872. if self._algo._bestSolution is None:
  873. self._algo._bestSolution = self._algo.initialiser()
  874. # set to algorithm the lastest obtained best solution
  875. self._algo._bestsolution.data = np.array(solution.data)
  876. self._algo._bestSolution._score = float(data[2])
  877. In this way, it is possible to specify the use of a callback to our algorithm instance:
  878. .. code-block:: python
  879. ...
  880. # maximizing algorithm (relative to knapsack problem)
  881. algo = HillClimberBestImprovment(initialiser, evaluator, operators, policy, validator, maximise=True, verbose=False)
  882. callback = BasicCheckpoint(every=5, filepath='data/hillClimberBackup.csv')
  883. # add callback into callback list
  884. algo.addCallback(callback)
  885. # run the algorithm using local search and get solution found
  886. solution = algo.run(evaluations=100)
  887. print(solution.fitness)
  888. .. note::
  889. It is possible to add as many callbacks as desired in the algorithm in question.
  890. Previously, some methods of the abstract ``Algorithm`` class have not been presented. These methods are linked to the use of callbacks,
  891. in particular the ``addCallback`` method which allows the addition of a callback to an algorithm instance as seen above.
  892. - The ``resume`` method will reload all callbacks list using ``load`` method.
  893. - The ``progress`` method will ``run`` each callbacks during the algorithm search.
  894. If we want to exploit this functionality, then we will need to exploit them within our algorithm. Let's make the necessary modifications for our algorithm ``IteratedLocalSearch``:
  895. .. code-block:: python
  896. """
  897. module imports
  898. """
  899. from macop.algorithms.base import Algorithm
  900. class IteratedLocalSearch(Algorithm):
  901. ...
  902. def run(self, evaluations, ls_evaluations=100):
  903. """
  904. Run the iterated local search algorithm using local search
  905. """
  906. # by default use of mother method to initialise variables
  907. super().run(evaluations)
  908. # initialise current solution
  909. self.initRun()
  910. # restart using callbacks backup list
  911. self.resume()
  912. # local search algorithm implementation
  913. while not self.stop():
  914. # create and search solution from local search
  915. newSolution = self._localSearch.run(ls_evaluations)
  916. # if better solution than currently, replace it
  917. if self.isBetter(newSolution):
  918. self._bestSolution = newSolution
  919. # check if necessary to call each callbacks
  920. self.progress()
  921. self.information()
  922. return self._bestSolution
  923. All the features of **Macop** were presented. The next section will aim to quickly present the few implementations proposed within **Macop** to highlight the modulality of the package.
  924. Implementation examples
  925. =======================
  926. Within the API of **Macop**, you can find an implementation of The Multi-objective evolutionary algorithm based on decomposition (MOEA/D) is a general-purpose algorithm for approximating the Pareto set of multi-objective optimization problems.
  927. It decomposes the original multi-objective problem into a number of single-objective optimization sub-problems and then uses an evolutionary process to optimize these sub-problems simultaneously and cooperatively.
  928. MOEA/D is a state-of-art algorithm in aggregation-based approaches for multi-objective optimization.
  929. .. image:: _static/documentation/search_space_moead.png
  930. :width: 45 %
  931. :align: center
  932. As illustrated below, the two main objectives are sub-divised into 5 single-objective optimization sub-problems in order to find the Pareto front.
  933. - macop.algorithms.multi.MOSubProblem_ class defines each sub-problem of MOEA/D.
  934. - macop.algorithms.multi.MOEAD_ class exploits ``MOSubProblem`` and implements MOEA/D using weighted-sum of objectives method.
  935. An example with MOEAD for knapsack problem is available in knapsackMultiExample.py_.
  936. .. _knapsackMultiExample.py: https://github.com/jbuisine/macop/blob/master/examples/knapsackMultiExample.py
  937. .. _macop.algorithms.base: macop/macop.algorithms.base.html#module-macop.algorithms.base
  938. .. _macop.algorithms.mono: macop/macop.algorithms.mono.html#module-macop.algorithms.mono
  939. .. _macop.solutions.base: macop/macop.solutions.base.html#module-macop.solutions.base
  940. .. _macop.solutions.base.Solution: macop/macop.solutions.base.html#macop.solutions.base.Solution
  941. .. _macop.solutions.discrete.BinarySolution: macop/macop.solutions.discrete.html#macop.solutions.discrete.BinarySolution
  942. .. _macop.evaluators.base.Evaluator: macop/macop.evaluators.base.html#macop.evaluators.base.Evaluator
  943. .. _macop.evaluators.discrete.mono.KnapsackEvaluator: macop/macop.evaluators.discrete.mono.html#macop.evaluators.discrete.mono.KnapsackEvaluator
  944. .. _macop.operators.base: macop/macop.operators.base.html#module-macop.operators.base
  945. .. _macop.operators.discrete.mutators.SimpleBinaryMutation: macop/macop.operators.discrete.mutators.html#macop.operators.discrete.mutators.SimpleBinaryMutation
  946. .. _macop.operators.discrete.crossovers.SimpleCrossover: macop/macop.operators.discrete.crossovers.html#macop.operators.discrete.crossovers.SimpleCrossover
  947. .. _macop.policies.reinforcement: macop/macop.policies.reinforcement.html#module-macop.policies.reinforcement
  948. .. _macop.policies.base: macop/macop.policies.base.html#module-macop.policies.base
  949. .. _macop.callbacks.base.Callback: macop/macop.callbacks.base.html#macop.callbacks.base.Callback
  950. .. _macop.algorithms.multi.MOSubProblem: macop/macop.algorithms.multi.html#macop.algorithms.multi.MOSubProblem
  951. .. _macop.algorithms.multi.MOEAD: macop/macop.algorithms.multi.html#macop.algorithms.multi.MOEAD