|
| 1 | +from numpy import random |
| 2 | +# Mutation operators |
| 3 | +# AOR: Arithmetic Operator Replacement: a + b -> a - b |
| 4 | +# LCR: Logical Connector Replacement: a and b -> a or b |
| 5 | +# ROR: Relational Operator Replacement: a > b -> a < b |
| 6 | +# UOI: Unary Operator Insertion: a -> not a (only in conditionals) |
| 7 | +# SBR: Statement Block Replacement: stmt -> 0 |
| 8 | + |
| 9 | +from typing import Literal, Callable, Any |
| 10 | + |
| 11 | +Node = Any # TODO: fix later |
| 12 | + |
| 13 | + |
| 14 | +class Converter: |
| 15 | + def __init__(self): |
| 16 | + pass |
| 17 | + |
| 18 | + def convert_to_div(self, node): |
| 19 | + raise NotImplementedError |
| 20 | + |
| 21 | + def convert_to_mult(self, node): |
| 22 | + raise NotImplementedError |
| 23 | + |
| 24 | + def convert_to_add(self, node): |
| 25 | + raise NotImplementedError |
| 26 | + |
| 27 | + def convert_to_sub(self, node): |
| 28 | + raise NotImplementedError |
| 29 | + |
| 30 | + |
| 31 | +class Engine: |
| 32 | + def __init__(self, mutation_rate: float = 0.1, seed=1337): |
| 33 | + self.mutation_rate = mutation_rate |
| 34 | + self.rng = random.default_rng(seed) |
| 35 | + |
| 36 | + def pick(self, iterable): |
| 37 | + return self.rng.choice(iterable) |
| 38 | + |
| 39 | + def mutate(self, node, conv_fn): |
| 40 | + if self.rng.random() < self.mutation_rate: |
| 41 | + return conv_fn(node) |
| 42 | + else: |
| 43 | + return node |
| 44 | + |
| 45 | + |
| 46 | +class Mutator(Converter): |
| 47 | + AOR_OPS = ["+", "-", "*", "/"] |
| 48 | + |
| 49 | + def __init__(self, engine: Engine): |
| 50 | + self.engine = engine |
| 51 | + |
| 52 | + def mutate_aor(self, node, current: Literal["+", "-", "*", "/"]): |
| 53 | + possible = [op for op in self.AOR_OPS if op != current] |
| 54 | + picked = self.engine.pick(possible) |
| 55 | + |
| 56 | + conv_fn = None |
| 57 | + if picked == "+": |
| 58 | + conv_fn = self.convert_to_add |
| 59 | + elif picked == "-": |
| 60 | + conv_fn = self.convert_to_sub |
| 61 | + elif picked == "*": |
| 62 | + conv_fn = self.convert_to_mult |
| 63 | + elif picked == "/": |
| 64 | + conv_fn = self.convert_to_div |
| 65 | + else: |
| 66 | + raise Exception("Unknown operator") |
| 67 | + |
| 68 | + return self.engine.mutate(node, conv_fn) |
0 commit comments