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 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. if force:
  16. return mutatef(expr, mutcount)
  17. res = copy.copy(expr)
  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, mutdel]
  34. mutations += [mutupdtype for _ in range(3)]
  35. mutations += [mutupdval for _ in range(6)]
  36. res = copy.copy(expr)
  37. for _ in range(mutcount):
  38. mutations[randint(0, len(mutations)-1)](res)
  39. return res
  40. def mutadd(expr):
  41. pos = randint(0, len(expr))
  42. expr.insert(pos, RpnSymbol.random())
  43. return expr
  44. def mutdel(expr):
  45. pos = randint(0, len(expr)-1)
  46. del(expr[pos])
  47. return expr
  48. def mutupdtype(expr):
  49. pos = randint(0, len(expr) - 1)
  50. optype = [RpnSymbol.OPERATION, RpnSymbol.VALUE, RpnSymbol.VARIABLE]
  51. del(optype[optype.index(expr[pos].optype)])
  52. expr[pos] = RpnSymbol.random(optype[randint(0,1)])
  53. return expr
  54. def mutupdval(expr):
  55. pos = randint(0, len(expr) - 1)
  56. expr[pos] = RpnSymbol(randint(0, 0xFFFF), expr[pos].optype)
  57. return expr