Genetic Turmit Evolver
python
c
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mutator.py 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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] * 2
  34. if len(expr) > 1:
  35. mutations += [mutdel] * 2
  36. mutations += [mutupdtype for _ in range(6)]
  37. mutations += [mutupdval for _ in range(8)]
  38. """
  39. mutations = [mutadd, mutdel]
  40. mutations += [mutupdtype for _ in range(3)]
  41. mutations += [mutupdval for _ in range(6)]
  42. """
  43. res = copy.copy(expr)
  44. for _ in range(mutcount):
  45. mutations[randint(0, len(mutations)-1)](res)
  46. return res
  47. def mutadd(expr):
  48. pos = randint(0, len(expr))
  49. expr.insert(pos, RpnSymbol.random())
  50. return expr
  51. def mutdel(expr):
  52. if len(expr) <= 1:
  53. return mutadd(expr)
  54. pos = randint(0, len(expr)-1)
  55. del(expr[pos])
  56. return expr
  57. def mutupdtype(expr):
  58. if len(expr) <= 1:
  59. pos = 0
  60. else:
  61. pos = randint(0, len(expr) - 1)
  62. optype = [RpnSymbol.OPERATION, RpnSymbol.VALUE, RpnSymbol.VARIABLE]
  63. del(optype[optype.index(expr[pos].optype)])
  64. expr[pos] = RpnSymbol.random(optype[randint(0,1)])
  65. return expr
  66. def mutupdval(expr):
  67. if len(expr) <= 1:
  68. pos = 0
  69. else:
  70. pos = randint(0, len(expr) - 1)
  71. if expr[pos].optype == RpnSymbol.VALUE:
  72. expr[pos] = RpnSymbol.rand_value()
  73. else:
  74. expr[pos] = RpnSymbol(randint(0, 0xFFFF), expr[pos].optype)
  75. return expr