1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- 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
- '''
- res = copy.copy(expr)
-
- if force:
- return mutatef(res, mutcount)
-
- 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] * 3
- if len(expr) > 1:
- mutations += [mutdel] * 3
- mutations += [mutupdtype for _ in range(3)]
- mutations += [mutupdval for _ in range(6)]
- """
- 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):
- if len(expr) <= 1:
- return mutadd(expr)
- pos = randint(0, len(expr)-1)
- del(expr[pos])
- return expr
-
- def mutupdtype(expr):
- if len(expr) <= 1:
- pos = 0
- else:
- 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):
- if len(expr) <= 1:
- pos = 0
- else:
- pos = randint(0, len(expr) - 1)
- if expr[pos].optype == RpnSymbol.VALUE:
- expr[pos] = RpnSymbol.rand_value()
- else:
- expr[pos] = RpnSymbol(randint(0, 0xFFFF), expr[pos].optype)
- return expr
|