def apply(self, state: State) -> (State, Base): # Check whether the state is an actual State object, and the statement inside is of the right form. if not self.applicable(state): raise Exception(f"State does not support using the {self} rule") # There exist two Comp rules because where we choose to split up the statement can be arbitrary, # as regardless of where we split we always get the same execution. # However, in our implementation, we can go for the simplest option which is to just take the first # legal statement and try to execute that. # This method will produce the smallest possible trees and chains. # Unpack the state values s, a, p, i, o = state.unpack() # Copy the array to avoid impacting the old state a = a.copy() # Get first legal statement index = 1 if s[0] == "[": count = 1 # Get the corresponding ] for c in s[1:]: if c == "]": count -= 1 elif c == "[": count += 1 index += 1 if count <= 0: break #try: # index = s.rindex("]") + 1 #except ValueError: # raise Exception("Syntax error detected in program, missing ]") # Split the statement into two separate statements s1 = s[:index] s2 = s[index:] # Get the new state from applying a rule before_state = State(s1, a, p, i, o) try: after_state, rule = self.interpreter.apply_rule(before_state) except: return FinalState(err=True), Error() self.interpreter.sequence.add_nested(before_state, rule, after_state) if isinstance(after_state, State): # If the new state is not final, then we append the remaining statement # back to statement s2 ns, na, np, ni, no = after_state.unpack() s2 = ns + s2 return State(s2, na, np, ni, no), self.co else: na, np, ni, no = after_state.unpack() # Otherwise, we simply keep s2 and use the new state values return State(s2, na, np, ni, no), self.ct
def apply(self, state: State) -> (State, Base): # Check whether the state is an actual State object, and the statement inside is of the right form. if not self.applicable(state): raise Exception(f"State does not support using the {self} rule") # Unpack the information from the given state s, a, p, i, o = state.unpack() # Copy the array to avoid impacting the old state a = a.copy() # And create a State by prepending S to the [S]. # We can do this by slicing off the first and last index from s s = s[1:-1] + s return State(s, a, p, i, o), self
def initialize(self, program, inp = ""): if not isinstance(program, Statement): raise TypeError("Program must be passed as a str object.") if not isinstance(program, Input): raise TypeError("Input must be passed as a str object.") self.s = re.sub("[^\<\>\,\.\[\]\-\+]", "", program) self.rulecount = { # Reset rulecount Right().tex(): 0, Left().tex(): 0, Plus().tex(): 0, Minus().tex(): 0, Dot().tex(): 0, Comma().tex(): 0, Loop.LoopBody().tex():0, Loop.LoopEnd().tex():0, Comp.CompOne().tex():0, Comp.CompTwo().tex():0 } # Initialize state variables a = defaultdict(lambda: 0) p = 0 o = "" self.initial_state = State(self.s, a, p, inp, o)
def __init__(self, before: State, rule: Base = None, after: Union[State, FinalState] = None): super().__init__() self.before = before.copy() self.rule = rule if after: self.after = after.copy() else: self.after = after self.nested = None
def apply(self, state: State) -> (FinalState, Base): # Check whether the state is an actual State object, and the statement inside is of the right form. if not self.applicable(state): raise Exception(f"State does not support using the {self} rule") # Unpack the information from the given state s, a, p, i, o = state.unpack() # Copy the array to avoid impacting the old state a = a.copy() # And create a FinalState with these state values return FinalState(a, p, i, o), self
def apply(self, state: State) -> (FinalState, Base): # Check whether the state is an actual State object, and the statement inside is of the right form. if not self.applicable(state): raise Exception(f"State does not support using the {self} rule") # Unpack the state s, a, p, i, o = state.unpack() # Copy the array to avoid impacting the old state a = a.copy() # Apply the Left rule by decrementing data pointer p -= 1 # Return a FinalState with the correct information return FinalState(a, p, i, o), self
def apply(self, state: State) -> (FinalState, Base): # Check whether the state is an actual State object, and the statement inside is of the right form. if not self.applicable(state): raise Exception(f"State does not support using the {self} rule") # Unpack the state s, a, p, i, o = state.unpack() # Copy the array to avoid impacting the old state a = a.copy() # Apply the Dot rule by adding the char version of the currently # pointed at value to the output o += chr(a[p]) # Return a FinalState with the correct information return FinalState(a, p, i, o), self
def apply(self, state: State) -> (FinalState, Base): # Check whether the state is an actual State object, and the statement inside is of the right form. if not self.applicable(state): raise Exception(f"State does not support using the {self} rule") # Unpack the state s, a, p, i, o = state.unpack() # Copy the array to avoid impacting the old state a = a.copy() # Apply the Comma rule by setting the currently pointed to value to # the ordinal value corresponding to the first input character # and then updating i to remove this first character. a[p] = ord(i[0]) i = i[1:] # Return a FinalState with the correct information return FinalState(a, p, i, o), self
def __init__(self, s: Statement = "", i: Input = ""): if not isinstance(s, Statement): raise TypeError("Program must be passed as a str object.") if not isinstance(i, Input): raise TypeError("Input must be passed as a str object.") # Set up list of Rules to be used self.rules = [ Right(), Left(), Plus(), Minus(), Dot(), Comma(), Loop(), Comp(self) # Composition takes an instance of Interpreter as it will want to execute a rule. ] self.rulecount = { Right().tex(): 0, Left().tex(): 0, Plus().tex(): 0, Minus().tex(): 0, Dot().tex(): 0, Comma().tex(): 0, Loop.LoopBody().tex():0, Loop.LoopEnd().tex():0, Comp.CompOne().tex():0, Comp.CompTwo().tex():0 } self.sequence = Sequence() self.s = re.sub("[^\<\>\,\.\[\]\-\+]", "", s) # Initialize state variables a = defaultdict(lambda: 0) p = 0 o = "" self.initial_state = State(s, a, p, i, o) self.stepcount = 0 if(len(self.s) > 0): self.parse(self.initial_state)
#!/usr/bin/env python # -*- coding: utf-8 -*- # # FileName: main # CreatedDate: 2018-10-30 01:53:18 # import numpy as np from configurations import State, Action, Observation from bayesian_filter import BayesianFilter if __name__ == '__main__': state_prob = np.array([0.5, 0.5]) prob_matrix = np.array( [[[1.0, 0.0], [1.0, 0.0]], [[0.8, 0.2], [0.0, 1.0]]], dtype=np.float32) state = State(state_prob, prob_matrix) actions = Action(['push', 'do_nothing']) observations = Observation([[0.6, 0.4], [0.2, 0.8]]) b = BayesianFilter(state, actions, observations) action_list = ['push', 'do_nothing', 'push'] print(b.calculate_belief(action_list, 3))