File size: 5,361 Bytes
6e246aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# Copyright (c) Napol Thanarangkaun
# Licensed under the MIT License - See LICENSE file for details

import math

try:
    from .model_config import CONFIG
    from .model_utils import clamp
except ImportError:  # run as a script from core/model
    from model_config import CONFIG
    from model_utils import clamp


def _js_number(value):
    if value is None:
        return 0
    try:
        return float(value)
    except (TypeError, ValueError):
        return math.nan


class RuleEngine:
    def __init__(self, rules=None):
        self.rules = rules if rules is not None else []

    def evaluate_condition(self, condition, state):
        if not condition:
            return False
        condition_type = condition.get("type")
        variable = condition.get("variable")
        if condition_type == "always":
            return True
        if condition_type == "less-than":
            return _js_number(state.get(variable)) < condition.get("value")
        if condition_type == "greater-than":
            return _js_number(state.get(variable)) > condition.get("value")
        if condition_type == "equals":
            value = state.get(variable)
            expected = condition.get("value")
            return type(value) is type(expected) and value == expected
        return False

    def get_applicable(self, state):
        applicable = [
            rule
            for rule in self.rules
            if rule.get("enabled") and self.evaluate_condition(rule.get("condition"), state)
        ]
        return sorted(applicable, key=lambda rule: (rule.get("safety", False), rule["priority"]), reverse=True)

    def select(self, state):
        applicable = self.get_applicable(state)
        return applicable[0] if applicable else None

    def reward(self, rule_id, reward):
        rule = next((item for item in self.rules if item.get("id") == rule_id), None)
        if rule and not rule.get("safety", False):
            if reward > 0:
                rule["success"] += 1
                rule["priority"] += 1
            else:
                rule["failure"] += 1
                rule["priority"] -= 1
            rule["priority"] = clamp(rule["priority"], 0, 1000)

    def evolve(self):
        for rule in self.rules:
            if rule.get("safety", False):
                continue
            total = rule["success"] + rule["failure"]
            if total >= 10 and rule["success"] / total < 0.1:
                rule["enabled"] = False
        if len(self.rules) > CONFIG["RULE_LIMIT"]:
            self.rules = sorted(self.rules, key=lambda rule: (rule.get("safety", False), rule["priority"]), reverse=True)[
                : CONFIG["RULE_LIMIT"]
            ]


class BehaviorEngine:
    def __init__(self, program=None):
        self.program = program if program is not None else []

    def run(self, state):
        action = "observe"
        value_stack = []
        conditions = []
        for index, instruction in enumerate(self.program):
            if index >= CONFIG["BEHAVIOR_LIMIT"]:
                break
            if not instruction:
                continue
            op = instruction[0]
            arg = instruction[1] if len(instruction) > 1 else None
            if op == "READ":
                value_stack.append(state.get(arg))
            elif op == "LESS_THAN":
                value = value_stack.pop() if value_stack else None
                value_stack.append(_js_number(value) < arg)
            elif op == "GREATER_THAN":
                value = value_stack.pop() if value_stack else None
                value_stack.append(_js_number(value) > arg)
            elif op == "IF":
                condition = bool(value_stack.pop()) if value_stack else False
                conditions.append({"condition": condition, "in_else": False})
            elif op == "ELSE":
                if conditions:
                    conditions[-1]["in_else"] = True
            elif op == "ACTION" and all(
                condition["condition"] != condition["in_else"]
                for condition in conditions
            ):
                action = arg
            elif op == "END":
                if conditions:
                    conditions.pop()
        return action

    def mutate(self, random):
        if len(self.program) >= CONFIG["BEHAVIOR_LIMIT"]:
            return
        actions = ["rest", "explore", "observe", "learn"]
        mutation = int(random.next() * 3)
        if mutation == 0:
            action_index = int(random.next() * len(actions))
            self.program.append(["ACTION", actions[action_index]])
        elif mutation == 1:
            action_indexes = [
                index
                for index, instruction in enumerate(self.program)
                if instruction and instruction[0] == "ACTION"
            ]
            if action_indexes:
                index = action_indexes[int(random.next() * len(action_indexes))]
                self.program.pop(index)
        else:
            comparisons = [
                instruction
                for instruction in self.program
                if instruction and instruction[0] in ("LESS_THAN", "GREATER_THAN")
            ]
            if comparisons:
                instruction = comparisons[int(random.next() * len(comparisons))]
                instruction[1] = int(random.next() * 91) + 5