예제 #1
0
    def build_graph(self, map: np.array) -> List:
        explored = set()

        # add boundry wall
        rows, cols = map.shape
        for col in range(0, cols):
            explored.add(tuple([0, col]))
            explored.add(tuple([rows - 1, col]))
        for row in range(0, rows):
            explored.add(tuple([row, 0]))
            # explored.add(tuple(np.array([row, cols - 1])))

        # find contours
        self.cornerSets = []
        println(explored)
        for col in range(1, cols):
            for row in range(1, rows):
                pos = np.array([row, col])
                if map[row, col] == "+":
                    freePos = np.array([row, col - 1])
                    # println(freePos, tuple(freePos) in explored)
                    if map[row, col - 1] != "+" and tuple(pos) not in explored:
                        # println("first spot", freePos)
                        corners = self.findEdges(freePos, map, explored)
                        if corners:
                            self.cornerSets.append(corners)

        G = self.generateGraph(copy.deepcopy(map))
        return G
예제 #2
0
    def findPathPart(self, state, pathId, combId):
        # (State, pathIndex)
        # TODO when calculating new dijkstras maybe just look at the changing parts
        # TODO make it work for more boxes and goals
        # TODO test performace difference between deepcopy and copy

        # TODO TODO TODO only recalculate new parts of the shorest path. e.g.
        # calculate the distance from pos to Kp, and then simply calculate the distance from
        # Kp to Kp and add them together
        # maybe precalculate every keypoint?

        GTemp = copy.deepcopy(self.graph)
        # println(self.poses, self.poses[combId][pathId])
        startPos, endPos = self.poses[combId][pathId]
        currentPath = state.currentPath[combId][pathId]
        prevKeypoints = state.prevKeypoints[combId][pathId]
        #  println(" start", startPos,endPos, state.currentPath, startId, endId)
        if (
                currentPath is not None
        ):  # and #TODO find if inbetween two points! #G.has_node(state.currentPath[0]):
            # TODO don't re calculate the path
            # TODO do the same at the endPoint
            startKps, endKps = prevKeypoints
            # println(endKps, startKps)
            # println(state.currentPath)
            # println(startKp, boxKp, goalKp)
            # println(state.currentPath.index(startKp), boxKp, goalKp)

            if len(currentPath) > 2 and currentPath[1] == startPos:
                startKps = [currentPath[1], currentPath[2]]
            if len(currentPath) == 2:
                # println(endPos, startKps)
                startKps.append(endPos)

            # dist = manha_dist(startPos, state.currentPath[0])
            # GTemp.add_edge(startPos, state.currentPath[0], weight=dist)
            # dist = manha_dist(startPos, state.currentPath[1])
            # GTemp.add_edge(startPos, state.currentPath[1], weight=dist)

            for kp in startKps:
                dist = manha_dist(startPos, kp)
                GTemp.add_edge(startPos, kp, weight=dist)
            # GTemp.add_edge(startKp, startPos, weight=dist)
            # println(startKp, startPos)

            for kp in endKps:
                dist = manha_dist(endPos, kp)
                GTemp.add_edge(kp, endPos, weight=dist)

            # TODO do some magic for endPos
            # println("is neighbor", startPos, startKp, endPos, boxKp, goalPos, goalKp)
            println("if", startPos, startKps, endPos, endKps)
            self.draw(GTemp)
            length, newPath = nx.bidirectional_dijkstra(
                GTemp, startPos, endPos)

            # println(lengthBox, pathBox[1::], lengthGoal, pathGoal[2::])
            # println(startKp, startPos, boxKp, endPos, goalKp, goalPos)
            prevKeypoints = [startKps, endKps]

            # println(lengthBox,lengthGoal, pathBox, pathGoal)
        else:

            # println(startPos, endPos)
            startKps = self.findBestKeyPoint(startPos, endPos)
            endKps = self.findBestKeyPoint(endPos, startPos)
            # println(startKps, endKps)
            prevKeypoints = [startKps, endKps]
            # println(state.prevKeypoints, endKps)

            for kp in startKps:
                dist = manha_dist(startPos, kp)
                GTemp.add_edge(startPos, kp, weight=dist)

            for kp in endKps:
                dist = manha_dist(kp, endPos)
                GTemp.add_edge(kp, endPos, weight=dist)
            # GTemp.add_edge(endPos, endKp, weight=dist)

            # println("else", startPos, startKps, endPos, endKps)
            # self.draw(GTemp)
            if nx.has_path(GTemp, startPos, endPos):
                length, newPath = nx.bidirectional_dijkstra(
                    GTemp, startPos, endPos)
            else:
                return None
        del GTemp
        currentPath = newPath
        return length  # path[1:-1]
예제 #3
0
    def generateGraph(self, map):
        cornerSets = self.cornerSets
        for corners in cornerSets:
            println("corner set", corners)
            if type(corners) != list:
                corners = [corners]
            for corner in corners:
                self.uniqueCorners.add(corner)
                map[corner] = "O"
        println(map)

        self.uniqueCorners = list(self.uniqueCorners)

        # TODO fix order of corners
        # cornerSets[0] = cornerSets[0][-1::] + cornerSets[0][:-1:]

        G = nx.DiGraph()

        println(cornerSets)
        # for corner in self.uniqueCorners:
        #     G.add_node(tuple(corner), pos=corner)

        for corners in cornerSets:
            # First position is always at the end
            for i in range(len(corners)):
                # println(corners[i - 1], corners[i])
                if not np.array_equal(corners[i - 1], corners[i]):
                    if self.getValidKeypoint(map, corners[i - 1], corners[i],
                                             []) is True:

                        corner1 = corners[i - 1]
                        corner2 = corners[i]
                        dist = manha_dist((corner1[0], corner1[1]),
                                          (corner2[0], corner2[1]))
                        println(corner1, corner2, dist)
                        G.add_edge(corner1, corner2, weight=dist)
                        G.add_edge(corner2, corner1, weight=dist)

        for corner1 in self.uniqueCorners:
            #G.add_node(tuple(corner), pos=corner)
            closestCorners = self.connectCornerSets(corner1, 4, 0.5)
            #println(corner1, closestCorners)
            for corner2 in closestCorners:
                dist = manha_dist((corner1[0], corner1[1]),
                                  (corner2[0], corner2[1]))
                G.add_edge(corner1, corner2, weight=dist)

        # if len(cornerSets) > 1:
        #     raise Exception("####### No edge fusion implemented yet")

        # println(cornerSets)
        # self.draw(G)

        # import sys; sys.exit()

        # for corners in cornerSets:
        #     for i in range(len(corners) - 1):
        #         if not np.array_equal(corners[i], corners[i + 1]):
        #             corner1 = corners[i]
        #             corner2 = corners[i + 1]
        #             dist = manha_dist(
        #                 (corner1[0], corner1[1]), (corner2[0], corner2[1])
        #             )
        #             println(corner1, corner2, dist)
        #             G.add_edge(corner1, corner2, weight=dist)
        #             G.add_edge(corner2, corner1, weight=dist)
        #             pass
        del map
        return G
import numpy as np
import random
import time
import utils
import matplotlib.pyplot as plt
from networkMod import Network
import matplotlib.patches as mpatches
from utils import println
import pandas as pd
from sklearn.metrics import confusion_matrix

# PART 1 - GETTING THE DATA READY:
println(5)
print("Getting the data ready...")

# Importing the dataset
dataset = pd.read_csv('wine.data')
X = dataset.iloc[:, 1:14].values
y = dataset.iloc[:, 0].values
'''
# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X_1 = LabelEncoder()
X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])
labelencoder_X_2 = LabelEncoder()
X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])
onehotencoder = OneHotEncoder(categorical_features = [1])
X = onehotencoder.fit_transform(X).toarray()
# - Taka care of the dummy variable trap:
X = X[:, 1:]
'''
예제 #5
0
import numpy as np
import random
import time
import utils
import matplotlib.pyplot as plt
from networkMod import Network
from utils import println
import pandas as pd



println(10)
print("Test variants:")
print(" - 0 for Simple test  : Constant Answer")
print(" - 1 for Basic test   : Dependent Answer")
print(" - 2 for Classifier   : Answer(Coordinate)")
print(" - 3 for Permutation  : Answer(Perm(input))")
testVariant = input("Please choose a test: ")
testVariant = int(testVariant)



#########################
# SIMPLE AND BASIC TESTS:
if testVariant == 0 or testVariant == 1:
    print()
    if testVariant == 0:
        print(" - Simple test: Constant Answer")
        print("   Input may be [0,1] or [1,0]")
        print("   Correct answer is always [0,1]")
    elif testVariant == 1:
예제 #6
0
import time, datetime
from time import sleep
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from utils import println
import pickle

println(10)
print('--------------------------')
print('BOT for statistics testing')
print('--------------------------')
'''
NOTES:
- Data in stat files must be from oldest to newest:
1 -> oldest
4 -> previous
2 -> newest
-- If the data is the opposite way, use the reverser_script to reverse it
- 
'''


def saveBot(bot: 'Network Class Obj', pickle_out_file: 'File name'):
    'Saves the bot to the pickle_out_file file'
    print("- Saving bot...")
    pickle_out = open(pickle_out_file, "wb")
    pickle.dump(bot, pickle_out)
    pickle_out.close()
    print("- Done!")
예제 #7
0
    j,
    o,
    d,
    e,
    s,
    w,
]
while m < 3:
    random.choice(p) = input("enter letter:  ")
    if random.choice(p) == "e":
        print("you have one point")
        m = m + 1
    elif random.choice(p) == "a":
        print("you have one point")
    elif random.choice(p) == "t":
        print("you have one point")
    else:
        print("wrong")
        m = m - 1
    if m == 3:
        print("the game is finished")
    elif m == 2:
        print("nice try")
    elif m == 1:
        print("bad luck")
    elif m == 0:
        print("you failed")
import utils

utils.println("thank you for playing")