Ejemplo n.º 1
0
def nearestNeighbor(trainingSet, testRow, classCol, k):
    minHeap = MinHeap(len(trainingSet.index))
    for row in trainingSet.iterrows():
        dropRow = row[1].drop(classCol)
        dist = findDistance(dropRow, testRow, classCol)
        minHeap.insert((row, dist))
    minHeap.minHeap()

    # Determine class by k neighbor voting
    votes = {}
    for i in range(k):
        minVal = minHeap.remove()
        if minVal[0][1][classCol] in votes:
            votes[minVal[0][1][classCol]] += 1
        else:
            votes[minVal[0][1][classCol]] = 1

    maxVotes = 0
    predictedClass = ""
    for key in votes:
        if votes[key] > maxVotes:
            maxVotes = votes[key]
            predictedClass = key

    return 0 if (predictedClass == testRow[1][classCol]) else 1
    def dijkstraFindPath(self,
                         startPoint,
                         endPoint,
                         pointsInPath,
                         checkLineIntersection=False,
                         searchRange=DEFAULT_SEARCH_RANGE):
        # pre-calculate distances in a search range cube
        self.gridScanDistances = []
        for k in range(-searchRange, searchRange + 1):
            grid2dDistances = []
            for i in range(-searchRange, searchRange + 1):
                tmp = []
                for j in range(-searchRange, searchRange + 1):
                    tmp.append((i**2 + (j * LENGTH / WIDTH)**2 +
                                (k * LENGTH / HEIGHT)**2)**0.5)
                grid2dDistances.append(tmp)
            self.gridScanDistances.append(grid2dDistances)

        self.grid[startPoint[2]][startPoint[1]][startPoint[0]].setDistance(0)
        pq = MinHeap()
        pq.insert(
            self.grid[startPoint[2]][startPoint[1]][startPoint[0]], self.grid[
                startPoint[2]][startPoint[1]][startPoint[0]].getDistance())

        count = 0
        while pq.counter != 0:
            currGridPoint = pq.del_min()
            if currGridPoint.getDistance(
            ) > LARGE_DISTANCE:  # these are the points that cannot be reached from the start point
                print("points covered: " + str(count))
                print("Destination point cannot be reached")
                raise Exception()
                break
            currGridPoint.visit()
            currX = currGridPoint.x
            currY = currGridPoint.y
            currZ = currGridPoint.z

            if (
                    currX, currY
            ) == endPoint:  # if we've reached the endpoint, then its okay to stop
                break

            # go through all the neighbours of the current point
            for k in range(-searchRange, searchRange + 1):
                z = k + currZ
                for i in range(-searchRange, searchRange + 1):
                    y = i + currY
                    for j in range(-searchRange, searchRange + 1):
                        x = j + currX

                        if x < 0 or x >= WIDTH or y < 0 or y >= LENGTH or z < 0 or z >= HEIGHT:  # check if out of bounds
                            continue

                        # check if point has been visited and whether it is accessible or not
                        currPoint = self.grid[z][y][x]
                        if currPoint.beenVisited(
                        ) or not currPoint.isAccessible():
                            continue
                        if checkLineIntersection:  # option that adds a shitton of time to the algo
                            line = LineString([[currX, currY], [x, y]])
                            continueFlag = False
                            for noFlyZone in self.noFlyZones:
                                if line.intersects(noFlyZone):
                                    continueFlag = True
                                    break
                            if continueFlag:
                                continue

                        oldDist = currPoint.getDistance()
                        newDist = currGridPoint.getDistance(
                        ) + self.gridScanDistances[k + searchRange][
                            i + searchRange][j + searchRange]
                        if newDist < oldDist:
                            currPoint.setDistance(newDist)
                            pq.insert(currPoint, currPoint.getDistance())
                            currPoint.setParent(currGridPoint)
            count = count + 1

        # check if the endpoint has actually been visited (probs not necessary but why not)
        endGridPoint = self.grid[endPoint[2]][endPoint[1]][endPoint[0]]
        if endGridPoint.getDistance() > LARGE_DISTANCE:
            print("no path could be found")
            raise Exception()
            return

        # now find the shortest path by going up the tree
        startGridPoint = self.grid[startPoint[2]][startPoint[1]][startPoint[0]]
        tempPath = []
        while endGridPoint != startGridPoint:
            if endGridPoint == None:
                print("no path could be found between following two points: ",
                      end="")
                print(startPoint, end="")
                print(endPoint)
                raise Exception()
                return
            tempPath.append((endGridPoint.x, endGridPoint.y, endGridPoint.z))
            endGridPoint = endGridPoint.getParent()
        tempPath.append((startGridPoint.x, startGridPoint.y, endGridPoint.z))

        totalDistance = 0
        # reverse them, append onto list then calculate distance
        for x in range(len(tempPath) - 2, -1, -1):
            totalDistance = totalDistance + (
                abs(tempPath[x + 1][0] - tempPath[x][0])**2 +
                abs(tempPath[x + 1][1] - tempPath[x][1])**2 +
                abs(tempPath[x + 1][2] - tempPath[x][2])**2)**0.5
            pointsInPath.append(tempPath[x])

        self.gridReset()

        return totalDistance
Ejemplo n.º 3
0
# Add, edit, or remove tests in this file.
# Treat it as your playground!

from minHeap import MinHeap
import unittest

test1 = MinHeap([2, 3, 1])

test2 = MinHeap([1, 2, 3, 4, 5, 6, 7, 8, 9])

test3 = MinHeap([48, 12, 24, 7, 8, -5, 24, 391, 24, 56, 2, 6, 8, 41])
test3.insert(76)
test3.remove()
test3.remove()
test3.insert(87)

test3a = MinHeap([[1, 48], [1, 12], [1, 24], [1, 7], [1, 8], [1, -5], [1, 24],
                  [1, 39], [1, 24], [1, 56], [1, 2], [1, 6], [1, 8], [1, 41]])
test3a.insert([1, 76])
test3a.remove()
test3a.remove()
test3a.insert([1, 9])
test3a.insert([1, 10])
test3a.insert([1, 87])
test3a.insert([1, -87])
test3a.insert([1, 49])

test4 = MinHeap(
    [-4, 5, 10, 8, -10, -6, -4, -2, -5, 3, 5, -4, -5, -1, 1, 6, -7, -6, -7, 8])

test5 = MinHeap(