From b9ac45621044275a13ad6ffc55eb368b09f12cca Mon Sep 17 00:00:00 2001 From: xkamikoo <58092037+xkamikoo@users.noreply.github.com> Date: Thu, 28 May 2020 15:03:13 +0200 Subject: [PATCH] decision tree changes --- Kamila.py | 188 ++++++++++++++++++++++------------------ main.py | 4 +- pathfinding_decision.py | 98 +++++++++++++++++++++ 3 files changed, 204 insertions(+), 86 deletions(-) create mode 100644 pathfinding_decision.py diff --git a/Kamila.py b/Kamila.py index 6b7e2ac..36ff89e 100644 --- a/Kamila.py +++ b/Kamila.py @@ -1,34 +1,38 @@ -import pandas as pd -from sklearn.tree import DecisionTreeClassifier -from sklearn.model_selection import train_test_split -from sklearn import metrics -import numpy +import time header = ["hydration", "weeds", "empty", "ready", "TODO"] work = ["Podlac", "Odchwascic", "Zasadzic", "Zebrac"] +order = [3, 1, 2, 0] -def check(field): +# ustalenie kolejnosci czynnosci +# 3 - zebranie +# 1 - odchwaszczenie +# 2 - zasadzenie +# 0 - podlanie + + +def translate(field): if field == 0: - return [[0, 0, 1, 0, "Zasadzic"], [0, 0, 1, 0, "Podlac"]] + return [0, 0, 1, 0] elif field == 1: - return [[0, 1, 1, 0, "Odchwascic"], [0, 1, 1, 0, "Podlac"], [0, 1, 1, 0, "Zasadzic"]] + return [0, 1, 1, 0] elif field == 2: - return [[0, 0, 0, 0, "Podlac"]] + return [0, 0, 0, 0] elif field == 3: - return [[0, 1, 0, 0, "Odchwascic"], [0, 1, 0, 0, "Podlac"]] + return [0, 1, 0, 0] elif field == 4: - return [[1, 0, 1, 0, "Zasadzic"]] + return [1, 0, 1, 0] elif field == 5: - return [[1, 1, 1, 0, "Odchwascic"], [1, 1, 1, 0, "Zasadzic"]] + return [1, 1, 1, 0] elif field == 6: - return [] + return [1, 0, 0, 0] elif field == 7: - return [[1, 1, 0, 0, "Odchwascic"]] + return [1, 1, 0, 0] elif field == 8: - return [[0, 0, 0, 1, "Zebrac"], [0, 0, 0, 1, "Potem podlac"], [0, 0, 0, 1, "Potem zasadzic"]] + return [0, 0, 0, 1] else: - print("wrong field number") + print("Błąd: Zły numer pola.") # liczenie ilości prac do wykonania @@ -56,13 +60,15 @@ class Question(): def match(self, example): val = example[self.column] if is_numeric(val): + return val >= self.value + else: return val == self.value # wyświetlenie pytania def __repr__(self): if is_numeric(self.value): condition = "==" - return "Is %s %s %s?" % ( + return "Czy %s %s %s?" % ( header[self.column], condition, str(self.value) ) @@ -82,15 +88,15 @@ def partition(rows, question): def gini(rows): counts = class_counts(rows) impurity = 1 - for lbl in counts: - prob_of_lbl = counts[lbl] / float(len(rows)) - impurity -= prob_of_lbl ** 2 + for label in counts: + prob_of_label = counts[label] / float(len(rows)) + impurity -= prob_of_label ** 2 return impurity -def info_gain(left, right, current_uncertainty): - p = float(len(left)) / (len(left) + len(right)) - return current_uncertainty - p * gini(left) - (1 - p) * gini(right) +def info_gain(true, false, current_uncertainty): + p = float(len(true)) / (len(true) + len(false)) + return current_uncertainty - p * gini(true) - (1 - p) * gini(false) # znalezienie najlepszego "miejsca" na podział danych @@ -141,21 +147,38 @@ def build_tree(rows): return DecisionNode(question, true_branch, false_branch) -# funcka wypisująca drzewo +# funkcja wypisująca drzewo def print_tree(node, spacing=""): if isinstance(node, Leaf): - print(spacing + "Predict", node.predictions) + print(spacing + "Przewidywana czynność:", node.predictions) return print(spacing + str(node.question)) - print(spacing + '--> True: ') + print(spacing + '--> Prawda: ') print_tree(node.true_branch, spacing + " ") - print(spacing + '--> False: ') + print(spacing + '--> Fałsz: ') print_tree(node.false_branch, spacing + " ") +def classify(field, node): + if isinstance(node, Leaf): + return node.predictions + if node.question.match(field): + return classify(field, node.true_branch) + else: + return classify(field, node.false_branch) + + +def print_leaf(counts): + total = sum(counts.values()) * 1.0 + probs = {} + for label in counts.keys(): + probs[label] = str(int(counts[label] / total * 100)) + "%" + return probs + + class main(): def __init__(self, traktor, field, ui, path): self.traktor = traktor @@ -164,65 +187,62 @@ class main(): self.path = path self.best_action = 0 - def main(self): - # dane testowe - array = ([[8, 8, 8, 8, 8, 8, 8, 8, 8, 8], - [7, 7, 7, 7, 7, 7, 7, 7, 7, 7], - [6, 6, 6, 6, 6, 6, 6, 6, 6, 6], - [5, 5, 5, 5, 5, 5, 5, 5, 5, 5], - [4, 4, 4, 4, 4, 4, 4, 4, 4, 4], - [3, 3, 3, 3, 3, 3, 3, 3, 3, 3], - [2, 2, 2, 2, 2, 2, 2, 2, 2, 2], - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) + # tworzymy zbior uczacy, w ktorym podajemy wszystkie mozliwe pola i czynnosci + training_data = [[0, 0, 1, 0, "Zasadzic"], + [0, 1, 1, 0, "Odchwascic"], + [0, 0, 0, 0, "Podlac"], + [0, 1, 0, 0, "Odchwascic"], + #[1, 0, 1, 0, "Zasadzic"], + #[1, 1, 1, 0, "Odchwascic"], + [1, 0, 0, 0, "Czekac"], + #[1, 1, 0, 0, "Odchwascic"], + [0, 0, 0, 1, "Zebrac"]] + self.tree = build_tree(training_data) + print_tree(self.tree) + + print("------------------") + print("TEST:") + +# for i in range(len(training_data)): +# print("Przewidziania czynnosc: %s Czynnosc: %s" +# % (print_leaf(classify(translate(i), self.tree)), training_data[i][-1])) +# if training_data[i][-1] in self.work_field(classify(translate(i), self.tree)): +# continue +# else: +# print("Testowanie zakonczone niepowodzeniem") +# break + + print("Przewidziania czynnosc: %s Czynnosc: Zasadzic" + % print_leaf(classify(translate(4), self.tree))) + print("Przewidziania czynnosc: %s Czynnosc: Odchwascic" + % print_leaf(classify(translate(5), self.tree))) + print("Przewidziania czynnosc: %s Czynnosc: Odchwascic" + % print_leaf(classify(translate(7), self.tree))) + + + def main(self): + for action in order: + self.traktor.set_mode(action) + self.search_field() - while (True): - self.find_best_action() - if self.best_action == -1: - break - self.do_best_action() print("Koniec roboty") - def find_best_action(self): - testing_data = [] + def work_field(self, labels): + works = [] + for label in labels: + if labels[label] > 0: + works.append(label) + return works + + def search_field(self): matrix = self.field.get_matrix() - matrix_todo = [] - # print(self.field) - for i in range(10): - matrix_todo.append([]) - verse = matrix[i] - for j in range(len(verse)): - coord = (i, j) - current_field = check(verse[j]) # czynnosci ktore trzeba jeszcze zrobic na kazdym polu - matrix_todo[i].append([]) - for action in current_field: - matrix_todo[i][j].append(action[-1]) - testing_data.extend(current_field) - # testing_data.append(current_field) - if len(testing_data) > 0: - x = build_tree(testing_data) - print_tree(x) - if isinstance(x, Leaf): - self.best_action = self.find_remaining_action(matrix_todo) - return - self.best_action = x.question.column - print(header[x.question.column]) - print(x.question.value) - else: - self.best_action = self.find_remaining_action(matrix_todo) - return + for i in range(len(matrix)): + for j in range(len(matrix[i])): + print("Pole (%d,%d) Przewidziania czynnosc: %s" + % (i, j, print_leaf(classify(translate(matrix[i][j]), self.tree)))) + if work[self.traktor.get_mode()] in self.work_field(classify(translate(matrix[i][j]), self.tree)): + print("Zgodna z aktualnym trybem, czynnosc wykonywana") + self.path.find_path(self.traktor, self.field, self.ui, [j, i]) + self.ui.update() + time.sleep(0.5) - def do_best_action(self): - self.traktor.set_mode(self.best_action) - while self.path.pathfinding(self.traktor, self.field, self.ui) != 0: - pass - - - def find_remaining_action(self, matrix_todo): - for row in matrix_todo: - for field in row: - for action in field: - print(action) - return work.index(action) - return -1 diff --git a/main.py b/main.py index d862999..610c939 100644 --- a/main.py +++ b/main.py @@ -1,5 +1,5 @@ import pygame, sys -import tractor,pathfinding,field,ui,Justyna,Kamila,Marcin,Piotrek +import tractor, pathfinding, field, ui, Justyna, Kamila, Marcin, Piotrek, pathfinding_decision from pygame.locals import * pole = field.field() @@ -7,7 +7,7 @@ path = pathfinding.pathfinding() traktor = tractor.tractor(pole) UI = ui.game_ui(traktor,pole) j = Justyna.main(traktor,pole,UI,path) -k = Kamila.main(traktor,pole,UI,path) +k = Kamila.main(traktor,pole,UI,pathfinding_decision.pathfinding_dec()) neuro = Marcin.main(traktor,pole,UI,path) p = Piotrek.main(traktor,pole,UI,path) pygame.init() diff --git a/pathfinding_decision.py b/pathfinding_decision.py new file mode 100644 index 0000000..bbd9a83 --- /dev/null +++ b/pathfinding_decision.py @@ -0,0 +1,98 @@ +from queue import PriorityQueue +import time + +class pathfinding_dec(): + def __init__(self): + pass + + def heuristic(self,a, b): + (x1, y1) = a + (x2, y2) = b + return abs(x1 - x2) + abs(y1 - y2) + + def points(self, point): + self.point = [] + for i in [[point[0],point[1]-1],[point[0]-1,point[1]],[point[0],point[1]+1],[point[0]+1,point[1]]]: + if i[0] in [-1,10] or i[1] in [-1,10]: + pass + else: + self.point.append(i) + return self.point + + def find_path(self, traktor, field, ui, destination): + self.ui = ui + self.traktor = traktor + self.activity = self.traktor.get_mode() + self.start_position = self.traktor.get_poz() + self.field = field + self.end_point = destination + + if self.start_position == self.end_point: + self.traktor.work() + else: + self.route = self.a_star(self.start_position,self.end_point) + for i in self.route[::-1]: + self.poz = self.traktor.get_poz() + if i[1]> self.poz[1]: + self.traktor.move_down() + elif i[1]< self.poz[1]: + self.traktor.move_up() + elif i[0]> self.poz[0]: + self.traktor.move_right() + elif i[0]< self.poz[0]: + self.traktor.move_left() + self.ui.update() + time.sleep(0.1) + self.traktor.work() + + + def a_star(self,start, end): + self.a_queue = PriorityQueue() + self.a_queue.put(start,0) + self.cost = {tuple(start): 0} + self.path_from = {tuple(start): None} + self.finall_path = [tuple(end)] + self.found = 0 + while not self.a_queue.empty(): + self.current = tuple(self.a_queue.get()) + + if self.current == tuple(end): + break + + for self.next in self.points(self.current): + self.new_cost = self.cost[tuple(self.current)] + self.field.get_value(self.next) + if tuple(self.next) not in self.cost or self.new_cost < self.cost[tuple(self.next)]: + self.cost[tuple(self.next)] = self.new_cost + self.priority = self.new_cost + self.heuristic(end, self.next) + self.a_queue.put(self.next,self.priority) + self.path_from[tuple(self.next)] = self.current + if self.next == end: + self.found = 1 + break + if self.found: + break + + self.pth = self.path_from[tuple(end)] + while not self.pth==tuple(start): + self.finall_path.append(self.pth) + self.pth = self.path_from[self.pth] + + return self.finall_path + + + def search(self,start,value): + self.checked = [] + self.visited = [start] + while self.visited: + if self.field.get_value(self.visited[0]) in value: + # print("Znaleziono pole: "+str(self.visited[0])) + return self.visited[0] + else: + self.p = self.points(self.visited[0]) + for i in self.p: + if i not in self.checked: + self.visited.append(i) + self.checked.append(self.visited[0]) + del self.visited[0] + +