12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- import copy
- from random import randint
-
- from .rpnlib import RpnExpr, RpnSymbol
-
- ADD = (10, 100)
- DEL = (5,100)
- UPDVAL = (25, 100)
- UPDTYPE = (25,100)
-
- def mutate(expr, force = True, mutcount = 1):
- ''' @brief Introduce a mutation in expr
- @param expr RpnExpr : an RPN expression
- @param force bool : if force a mutation occur each time
- @param mutcount int : count of time
- @return a muatated copy of expr
- '''
- if force:
- return mutatef(expr, mutcount)
-
- res = copy.copy(expr)
- for _ in range(mutcount):
- rep = randint(*ADD)
- if rep <= ADD[0]:
- mutadd(res)
-
- rep = randint(*DEL)
- if rep <= DEL[0]:
- mutdel(res)
-
- rep = randint(*UPDTYPE)
- if rep <= UPDTYPE[0]:
- mutupdtype(res)
-
- rep = randint(*UPDVAL)
- if rep <= UPDVAL[0]:
- mutupdval(res)
-
- return res
-
- def mutatef(expr, mutcount = 1):
- mutations = [mutadd, mutdel]
- mutations += [mutupdtype for _ in range(3)]
- mutations += [mutupdval for _ in range(6)]
- res = copy.copy(expr)
- for _ in range(mutcount):
- mutations[randint(0, len(mutations)-1)](res)
- return res
-
- def mutadd(expr):
- pos = randint(0, len(expr))
- expr.insert(pos, RpnSymbol.random())
- return expr
-
- def mutdel(expr):
- pos = randint(0, len(expr)-1)
- del(expr[pos])
- return expr
-
- def mutupdtype(expr):
- pos = randint(0, len(expr) - 1)
- optype = [RpnSymbol.OPERATION, RpnSymbol.VALUE, RpnSymbol.VARIABLE]
- del(optype[optype.index(expr[pos].optype)])
- expr[pos] = RpnSymbol.random(optype[randint(0,1)])
- return expr
-
- def mutupdval(expr):
- pos = randint(0, len(expr) - 1)
- expr[pos] = RpnSymbol(randint(0, 0xFFFF), expr[pos].optype)
- return expr
|