Genetic Turmit Evolver
python
c
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

mutator.py 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import copy
  2. from random import randint
  3. from .rpnlib import RpnExpr, RpnSymbol
  4. ADD = (10, 100)
  5. DEL = (5,100)
  6. UPDVAL = (25, 100)
  7. UPDTYPE = (25,100)
  8. def mutate(expr, force = True, mutcount = 1):
  9. ''' @brief Introduce a mutation in expr
  10. @param expr RpnExpr : an RPN expression
  11. @param force bool : if force a mutation occur each time
  12. @param mutcount int : count of time
  13. @return a muatated copy of expr
  14. '''
  15. res = copy.copy(expr)
  16. if force:
  17. return mutatef(res, mutcount)
  18. for _ in range(mutcount):
  19. rep = randint(*ADD)
  20. if rep <= ADD[0]:
  21. mutadd(res)
  22. rep = randint(*DEL)
  23. if rep <= DEL[0]:
  24. mutdel(res)
  25. rep = randint(*UPDTYPE)
  26. if rep <= UPDTYPE[0]:
  27. mutupdtype(res)
  28. rep = randint(*UPDVAL)
  29. if rep <= UPDVAL[0]:
  30. mutupdval(res)
  31. return res
  32. def mutatef(expr, mutcount = 1):
  33. mutations = [mutadd] * 3
  34. if len(expr) > 1:
  35. mutations += [mutdel] * 3
  36. mutations += [mutupdtype for _ in range(3)]
  37. mutations += [mutupdval for _ in range(6)]
  38. #mutations = [mutadd, mutdel]
  39. #mutations += [mutupdtype for _ in range(3)]
  40. #mutations += [mutupdval for _ in range(6)]
  41. res = copy.copy(expr)
  42. for _ in range(mutcount):
  43. mutations[randint(0, len(mutations)-1)](res)
  44. return res
  45. def mutadd(expr):
  46. pos = randint(0, len(expr))
  47. expr.insert(pos, RpnSymbol.random())
  48. return expr
  49. def mutdel(expr):
  50. pos = randint(0, len(expr)-1)
  51. del(expr[pos])
  52. return expr
  53. def mutupdtype(expr):
  54. if len(expr) == 1:
  55. pos = 0
  56. else:
  57. pos = randint(0, len(expr) - 1)
  58. optype = [RpnSymbol.OPERATION, RpnSymbol.VALUE, RpnSymbol.VARIABLE]
  59. del(optype[optype.index(expr[pos].optype)])
  60. expr[pos] = RpnSymbol.random(optype[randint(0,1)])
  61. return expr
  62. def mutupdval(expr):
  63. if len(expr) == 1:
  64. pos = 0
  65. else:
  66. pos = randint(0, len(expr) - 1)
  67. if expr[pos].optype == RpnSymbol.VALUE:
  68. expr[pos] = RpnSymbol.rand_value()
  69. else:
  70. expr[pos] = RpnSymbol(randint(0, 0xFFFF), expr[pos].optype)
  71. return expr