def doors2(self): opening_locations = [] for i in range(8): doors = [] random_num = randint(1, 10) if random_num <= 5: doors = [1, 2] else: doors = [2, 1] opening_locations.append([sample(range(0, 12), 2), doors]) wall_location_index = 1 for x in range(len(opening_locations)): for y in range(12): if y != opening_locations[x][0][0] and y != opening_locations[ x][0][1]: self.tile_objects.append( Rock(self.rock_img, wall_location_index, y)) if y == opening_locations[x][0][0]: self.tile_objects.append( Leaf(self.leaf_img, wall_location_index, y, opening_locations[x][1][0])) elif y == opening_locations[x][0][1]: self.tile_objects.append( Leaf(self.leaf_img, wall_location_index, y, opening_locations[x][1][1])) wall_location_index += 2
def insert( self, key, data ): leaf = Leaf( key, data ) if self.root == None: self.root = leaf else: # If tree is not empty, we need to find an empty node # at the correct location current = self.root l_key = leaf.get_key() parent = current c_key = 0 while current != None: parent = current c_key = current.get_key() if l_key < c_key: current = current.get_left() elif l_key > c_key: current = current.get_right() # Do not forget to set our parent of the leaf current = leaf current.set_parent( parent ) # Set child if l_key < c_key: parent.set_left( current ) else: parent.set_right( current )
def SimpleDistribOR(self, leaf): if (leaf.symbol.code == "OP_AND"): l = leaf.left r = leaf.right if (l.symbol.code == "OP_OR" and r.symbol.code == "IDENTIFIER"): op = l ident = r elif (r.symbol.code == "OP_OR" and l.symbol.code == "IDENTIFIER"): op = r ident = l else: return False leaf.symbol = Symbol("v") opL = op.left opR = op.right ident2, identt = ident.DuplicateTree() self.tree += identt nl = Leaf(Symbol("^"), True, leaf, opL, ident) nr = Leaf(Symbol("^"), True, leaf, opR, ident2) leaf.left = nl leaf.right = nr return True
def transform_tree(array): if isinstance(array[0], tuple): tree = np.array([]) for tupl in array: l = Leaf() l.set_name(tupl[0]) l.set_freq(tupl[1]) tree = np.append(tree, l) else : tree = np.array(array) return tree
def row_to_be_sorted(self): stack_list = [] for i in range(16): rand_num = randint(1, 32) while rand_num in stack_list: rand_num = randint(1, 32) stack_list.append(rand_num) for i in range(len(stack_list)): self.tile_objects.append(Leaf(self.leaf_img, i, 0, stack_list[i])) self.tile_objects.append(Leaf(self.leaf_img, i, 1, stack_list[i]))
def create_mass_scenario(n_results: int = 100, root_starter: int = 1) -> [str, Leaf]: tree = Leaf(root_starter) for i in range(n_results): tree.insert(i) expected = '63|31|15|7|3|1|0|2|5|4|6|11|9|8|10|13|12|14|23|19|17|16|18|21|20|22|27|25|24|26|29|28|30|47|39|35|' expected += '33|32|34|37|36|38|43|41|40|42|45|44|46|55|51|49|48|50|53|52|54|59|57|56|58|61|60|62|79|71|67|65|' expected += '64|66|69|68|70|75|73|72|74|77|76|78|87|83|81|80|82|85|84|86|95|91|89|88|90|93|92|94|97|96|98|99' return [expected, tree]
def make_tree(tree): temp = tree while(len(tree) > 1): leaves = tree[-2:] tree = tree[:-2] leaf = Leaf() leaf.set_children(leaves[0], leaves[1]) tree = np.append(tree, leaf) arr = sort_by_freq(tree) tree = transform_tree(arr) root = tree[0] root.expand('') return root, temp
def DistribOR(self, leaf): if (leaf.symbol.code == "OP_OR"): l = leaf.left r = leaf.right if (l.symbol.code == "OP_AND" and r.symbol.code == "OP_AND"): ll1 = l.left lr1 = l.right rl1 = r.left rr1 = r.right leaf.symbol = Symbol("^") ll2, llt = ll1.DuplicateTree() self.tree += llt lr2, lrt = lr1.DuplicateTree() self.tree += lrt rl2, rlt = rl1.DuplicateTree() self.tree += rlt rr2, rrt = rr1.DuplicateTree() self.tree += rrt nsym = Symbol("v") nll = Leaf(nsym, True, l, ll1, rl1) self.tree.append(nll) ll1.upper = nll rl1.upper = nll nlr = Leaf(nsym, True, l, ll2, rr1) self.tree.append(nlr) ll2.upper = nlr rr1.upper = nlr nrl = Leaf(nsym, True, r, lr1, rl2) self.tree.append(nrl) lr1.upper = nrl rl2.upper = nrl nrr = Leaf(nsym, True, r, lr2, rr2) self.tree.append(nrr) lr2.upper = nrr rr2.upper = nrr l.left = nll l.right = nlr r.left = nrl r.right = nrr return True return False
def build_tree(self, rows): """Recursively builds decision tree""" # Try partitioing the dataset on each of the unique attribute, # calculate the information gain, # and return the question that produces the highest gain. gain, question = find_optimal_split(rows) # Base case: no further info gain # Since we can ask no further questions, # we'll return a leaf. if gain == 0: return Leaf(rows) # If we reach here, we have found a useful feature / value # to partition on. true_rows, false_rows = partition(rows, question) # Recursively build the true branch. true_branch = self.build_tree(true_rows) # Recursively build the false branch. false_branch = self.build_tree(false_rows) # Return a Question node. # This records the best feature / value to ask at this point, # as well as the branches to follow # dependingo on the answer. return DecisionNode(question, true_branch, false_branch)
def decision_tree(examples, attributes, parent_examples=(), depth=0): """ Same algorithm as AI:AMA Text-book :param depth: :param examples: Data - rows :param attributes: Attributes :param parent_examples: Root node examples :return: tree """ # Depth check if depth == MAX_DEPTH: return plurality_value(examples) # If examples empty if len(examples) == 0: return plurality_value(parent_examples) # If all have same class if is_same_classification(examples): return Leaf(examples[0][-1]) # If attributes are empty if len(attributes) == 0: return plurality_value(examples) # "A" <- argmax_ Importance(a, examples) A = best_attribute(attributes, examples) depth += 1 # tree <- tree with root "a" tree = Node(A, data.attribute_name[A], plurality_value(examples)) for (vk, vk_values) in split(A, examples): subtree = decision_tree(vk_values, remove_all(A, attributes), examples, depth) tree.add(vk, subtree) return tree
def get_clusters(dataset_iterator, batch_size, skip_count, threshold, MIN_SAMPLES_FOR_SPLIT): line_count = 0 clusters = [] for line in dataset_iterator: line_split = line.text.split() if len(line_split) > skip_count: has_matched = False for i in range(len(clusters)): if clusters[i].check_for_match(line_split, threshold, skip_count): clusters[i].add_to_leaf(line, threshold, skip_count) has_matched = True if not has_matched: clusters.append(Cluster(Leaf(line))) # Create a new cluster line_count += 1 if line_count > batch_size: # Split leafs that are too large for i in range(len(clusters)): if clusters[i].get_num_lines() > MIN_SAMPLES_FOR_SPLIT: clusters[i].split_leaf(MIN_SAMPLES_FOR_SPLIT, skip_count, min_word_pos_entropy=.0001, min_percent=.1) line_count = 0 return clusters
def maze(self): startx = 7 starty = 5 leaf_num = 1 # 0-up, 1-right, 2-down, 3-left while (startx > 0 and startx < 15) and (starty > 0 and starty < 11): currentx = startx currenty = starty iterations = 0 while self.something_on_spot(currentx, currenty): currentx = startx currenty = starty direction = randint(0, 3) if direction == 0: currenty -= 1 elif direction == 1: currentx += 1 elif direction == 2: currenty += 1 elif direction == 3: currentx -= 1 iterations += 1 if iterations > 50: break if iterations > 50: break # breaks used when random leaf placement is not possible(ex. surrounded on all sides) startx = currentx starty = currenty self.tile_objects.append( Leaf(self.leaf_img, startx, starty, leaf_num)) leaf_num += 1
def MaterialEquivalence(self, leaf): if (leaf.symbol.code == "OP_IF_ONLY_IF"): leaf.symbol = Symbol('^') lbranch = leaf.left rbranch = leaf.right lbranch2, ltree = lbranch.DuplicateTree() self.tree += ltree rbranch2, rtree = rbranch.DuplicateTree() self.tree += rtree leaf.left = Leaf(Symbol('->'), True, leaf, lbranch, rbranch) self.tree.append(leaf.left) leaf.right = Leaf(Symbol('->'), True, leaf, rbranch2, lbranch2) self.tree.append(leaf.right) return True return False
def generate_leaves(self): [ self.leaves.append( Leaf( PVector(random.randint(0, 700), random.randint(0, 300), random.randint(0, 600)), 'sun')) for i in range(400) ]
def alpha_eq(root, seen, sub, free_vars): if type(root) == Abstract: head = root.head body = root.body new_sub = sub.copy() new_sub.append({}) new_head = [] for i in head: if (i in seen) or (i in free_vars): j = choose_symbol(seen + free_vars, i) new_sub[-1][i] = j new_head.append(j) seen.append(j) else: new_sub[-1][i] = i new_head.append(i) seen.append(i) root.head = new_head root.body = alpha_eq(body, seen, new_sub, free_vars) return root elif type(root) == Aplication: left = root.leftNode right = root.rightNode new_left = alpha_eq(left, seen, sub, free_vars) new_right = alpha_eq(right, seen, sub, free_vars) root.leftNode = new_left root.rightNode = new_right return root # livre ou lig?? else: for j in reversed(sub): if root.value in j.keys(): return Leaf(j[root.value]) return root
def decision_stump(data, weight): """ Does everything and normalizes the weights :param data: data is of Dataset class :param weight: weights of corresponding stumps/trees :return: """ all_examples = data.examples all_attributes = data.inputs col_num, weights = choose_best_attribute(all_examples, all_attributes, weight) hypothesis = Node(col_num, data.attribute_name[col_num]) if weights[0] > weights[1]: hypothesis.add("True", Leaf("True")) else: hypothesis.add("True", Leaf("False")) if weights[2] > weights[3]: hypothesis.add("False", Leaf("True")) else: hypothesis.add("False", Leaf("False")) correct, wrong = [], [] total_error = 0 for example_id in range(len(all_examples)): this_row = all_examples[example_id] if this_row[col_num] != this_row[-1]: total_error += weight[example_id] wrong.append(example_id) else: correct.append(example_id) importance = (1 / 2) * (math.log(abs((1 - total_error) / total_error))) for c in correct: weight[c] *= (math.e**importance) for i_c in wrong: weight[i_c] *= (math.e**(-1 * importance)) weight = normalize(weight) return hypothesis, abs(importance), weight
def random_leaves(self): # used for setup 1 where wombat collects all the leaves on the board for i in range(0, 25): chosen_x_y = [randint(0, 15), randint(0, 11)] while (chosen_x_y[0] * 50 == self.wombat.x and chosen_x_y[1] * 50 == self.wombat.y) or self.something_on_spot( chosen_x_y[0], chosen_x_y[1]): chosen_x_y = [randint(0, 15), randint(0, 11)] leaf_image = Leaf(self.leaf_img, chosen_x_y[0], chosen_x_y[1], randint(1, 10)) self.tile_objects.append(leaf_image)
def setup_10(self): # need to setup wombat in main at the bottom left corner final_height = 0 for i in range(4, 16): height = randint(0, 7) for j in range(0, height): new_rock = Rock(self.rock_img, i, 11 - j) self.tile_objects.append(new_rock) if i == 15: final_height = height self.tile_objects.append(Leaf(self.leaf_img, i, 11 - final_height, 1))
def buildTree(self, rows): ''' builds DT ''' gain, split = self.findBestSplit(rows) if gain == 0: return Leaf(rows) yesRows, noRows = self.splitRows(rows, split) yesBranch = self.buildTree(yesRows) noBranch = self.buildTree(noRows) return Node(yesBranch, noBranch, split)
def create_error_message(msg: str = '', leaf_before: Leaf = None, leaf_after: Leaf = None): message = '' if msg: message += msg if leaf_before and leaf_after: if message != '': message += '\n\n' message += 'Before:\n' tree_before = leaf_before.get_displayed_tree() for line in tree_before: message += line + '\n' message += '\n\nAfter:\n' tree_after = leaf_after.get_displayed_tree() for line in tree_after: message += line + '\n' return message
def huffman_tree(n): queue = [(freq, Leaf(ch)) for ch, freq in Counter(n).items()] heapq.heapify(queue) if len(queue) == 1: _, leaf, = heapq.heappop(queue) codes = {leaf.char: "0"} return codes while len(queue) > 1: freq1, left, = heapq.heappop(queue) freq2, right, = heapq.heappop(queue) elem = (freq1 + freq2, Node(left, right)) heapq.heappush(queue, elem) [(_freq, root)] = queue codes = {} root.walk(codes, "") return codes
def place_leaf(self): if self.broken: return in_tile_list = False if self.has_leaf(): for obj in self.tile_objects: if obj.x == self.x and obj.y == self.y: obj.num += 1 in_tile_list = True if not in_tile_list: self.tile_objects.append(Leaf(self.leaf_img, int(self.x/int(pygame_x / 16.0)), int(self.y/int(pygame_y / 12.0)), 1)) else: self.broken = True self.change_to_broken_image() print("broke, tried to place leaf even though didn't have any")
def build_tree(self, trainingData): # calculate the information gain and return the question that produces the highest gain gain, question = find_best_split(trainingData) # if the information gain is 0 --> return a leaf if gain == 0: return Leaf(trainingData) true_rows, false_rows = partition(trainingData, question) # Recursively build the true and false branch true_branch = self.build_tree(true_rows) false_branch = self.build_tree(false_rows) # in the decision node we will keep: # the best question so far # the true branch we need to follow # the false branch we need to follow return DecisionNode(question, true_branch, false_branch)
def plurality_value(examples): summation = lambda v: sum(e[-1] == v for e in examples) popular = argmax(data.values[-1], key=summation) return Leaf(popular)
from leaf import Leaf from crosstrek import CrossTrek from mustang import Mustang from ram import Ram from pumpstation import PumpStation from chargingstation import ChargingStation ram = Ram() must = Mustang() tree = Leaf() gas_pump_station = PumpStation() electric_charging_station = ChargingStation() gas_pump_station.add_vehicle(ram) gas_pump_station.add_vehicle(must) electric_charging_station.add_vehicle(tree)
#!/usr/bin/env import sys import time leaftimer = open('/var/www/html/openWB/ramdisk/soctimer', 'r') leaftimer = int(leaftimer.read()) if (leaftimer < 181): leaftimer += 1 f = open('/var/www/html/openWB/ramdisk/soctimer', 'w') f.write(str(leaftimer)) f.close() if (leaftimer == 10): from leaf import Leaf leaf = Leaf(sys.argv[1], sys.argv[2]) socit = leaf.BatteryStatusRecordsRequest() justsoc = socit['BatteryStatusRecords']['BatteryStatus']['SOC'][ 'Value'] f = open('/var/www/html/openWB/ramdisk/soc', 'w') f.write(str(justsoc)) f.close() if (leaftimer == 60): from leaf import Leaf leaf = Leaf(sys.argv[1], sys.argv[2]) socit = leaf.BatteryStatusRecordsRequest() justsoc = socit['BatteryStatusRecords']['BatteryStatus']['SOC'][ 'Value'] f = open('/var/www/html/openWB/ramdisk/soc', 'w') f.write(str(justsoc)) f.close()
def test_simple_insert(self): tree = Leaf(1) tree.insert(2) self.assertEqual('1|2', str(tree), 'Insertion of second leaf in right') tree.insert(0) self.assertEqual('1|0|2', str(tree), 'Insertion of third leaf in left of root') tree.insert(1) self.assertEqual( '1|0|2', str(tree), 'Insertion of element that already exist in tree (root)') tree.insert(2) self.assertEqual( '1|0|2', str(tree), 'Insertion of element that already exist in tree (right leaf)') tree.insert(0) self.assertEqual( '1|0|2', str(tree), 'Insertion of element that already exist in tree (left leaf)') tree.insert(3) self.assertEqual('1|0|2|3', str(tree), 'Insertion of leaf in left of left leaf of root') tree.insert(4) self.assertEqual( '1|0|3|2|4', str(tree), 'Insertion of element that will execute normalization in tree')
from mustang import Mustang from ram import Ram from leaf import Leaf from crosstrek import Crosstrek mach1 = Mustang() mach1.refuel() mach1.drive() mach1.drive() cummins = Ram() cummins.refuel() cummins.drive() cummins.drive() hippie = Leaf() hippie.refuel() hippie.drive() hippie.drive() busaru = Crosstrek() busaru.refuel() busaru.drive() busaru.drive()
#!/usr/bin/env import sys import time leaftimer = open('/var/www/html/openWB/ramdisk/soctimer1', 'r') leaftimer = int(leaftimer.read()) if (leaftimer < 60): leaftimer += 1 f = open('/var/www/html/openWB/ramdisk/soctimer1', 'w') f.write(str(leaftimer)) f.close() else: from leaf import Leaf leaf = Leaf(sys.argv[1], sys.argv[2]) #response = leaf.BatteryStatusCheckRequest() #time.sleep(10) #leaf.BatteryStatusCheckResultRequest(resultKey=response['resultKey']) #time.sleep(10) socit = leaf.BatteryStatusRecordsRequest() justsoc = socit['BatteryStatusRecords']['BatteryStatus']['SOC']['Value'] f = open('/var/www/html/openWB/ramdisk/soc1', 'w') f.write(str(justsoc)) f.close() f = open('/var/www/html/openWB/ramdisk/soctimer1', 'w') f.write(str(0)) f.close()
from mustang import Mustang from ram import Ram from leaf import Leaf from crosstrek import CrossTreck from pumpstation import PumpStation from chargingstation import ChargingStation ram = Ram() must = Mustang() tree = Leaf() tree.drive() gas_pump_station = PumpStation() electric_charging_station = ChargingStation() gas_pump_station.add_vehicles(ram) gas_pump_station.add_vehicles(must) electric_charging_station.add_vehicles(tree)
def run_game(run_is_pressed): pygame.init() clock = pygame.time.Clock() screen = pygame.display.set_mode((640, 480)) picture = 'leaf.png' blocks = [] i = 0 while i < 5: #blocks.append(Hurdle()) i = i + 1 SCREEN_SIZE = (screen.get_width(), screen.get_height()) leaf_velocity = Vector2((0, 0.5)) maple = Leaf(SCREEN_SIZE[0] / 2, 0, leaf_velocity, picture) print maple.w, maple.h gale = Wind(0) while True: for event in pygame.event.get(): if event.type == QUIT: exit() elif pygame.mouse.get_pressed()[0]: pos = pygame.mouse.get_pos() gale.get_dir(maple.get_pos(), pos) maple.wind_affect(gale) elif pygame.mouse.get_pressed()[2]: maple.x = SCREEN_SIZE[0] / 2 maple.y = 0 maple.velocity = Vector2((0, 0.2)) clock.tick(60) screen.fill((255, 255, 255)) maple.render(screen) i = 0 #while(i<5): #blocks[i].render(screen) maple.simple_collision_check() # i=i+1 maple.fall() pygame.display.update()
def test_creation(self): tree = Leaf(1) self.assertEqual( '1', str(tree), 'Creation of Leaf, string cast and describe in pre order')