Jarvis步进凸包算法

凸包算法作为计算几何的基础和核心问题足以引起重视.
这里给出Jarvis步进算法的Python实现.
测试环境是Ubuntu Python3.4
依赖了numpy(数学运算) matplotlib(绘图) logging(日志) unittest2(测试) 如果没有则需要安装

程序给出了to-left-test lowest-then-leftmost jarvis三个工具的实现

算法的基本思想就是:

  • 找到LTL(lowest-then-leftmost)点,这个点一定是一个EP(extreme point)
  • 以LTL点为起点,遍历所有点,利用to-left-test找到连线最靠右的那条线的端点.
  • 将端点记为EP,并以之为起点重复上步骤.
  • 直到端点与最初起点相同,结束算法返回EE(extreme edge)数列.
# coding=utf-8
'''
Created on Jan 13, 2016

@author: yangjie
'''
"""
def logger
"""

import logging
from matplotlib import pyplot
import numpy
import random
import unittest2


formatStr = "%(asctime)s [%(filename)s line %(lineno)d] [%(name)s %(levelname)s] %(message)s"
fmt = logging.Formatter(formatStr)
streamHandler = logging.StreamHandler()
streamHandler.setFormatter(fmt)
CHLogger = logging.getLogger("CHLogger")
CHLogger.setLevel(logging.INFO)
CHLogger.addHandler(streamHandler)


class PointBasket():
    """
    container of points and edges
    """

    def __init__(self):
        self.pointContainer = []
        self.edgeContainer = []

    def appendPoint(self, point):
        """
        add a point to container
        """
        try:
            self.pointContainer.append(point)
            CHLogger.info("append point %f,%f" % (point.posX, point.posY))
        except Exception as error:
            CHLogger.error(error)

    def appendEdge(self, pointStart, pointEnd):
        """
        add a edge to container, extreme edge.
        """
        try:
            self.edgeContainer.append((pointStart, pointEnd))
            CHLogger.info("append edge (%f,%f)(%f,%f)" %
                          (pointStart.posX, pointStart.posY, pointEnd.posX, pointEnd.posY))
        except Exception as error:
            CHLogger.error(error)

    def getPointPos(self):
        """
        return a dic of position x and position y of points
        """
        try:
            pos = {"posX": [], "posY": []}
            for point in self.pointContainer:
                pos["posX"].append(point.posX)
                pos["posY"].append(point.posY)
            CHLogger.info("get point pos")
            return pos
        except Exception as error:
            CHLogger.error(error)
            return None

    def getEdgePos(self):
        """
        return a dic of position x and position y of edges
        """
        try:
            pos = {"posX": [], "posY": []}
            for edge in self.edgeContainer:
                pos["posX"].append(edge[0].posX)
                pos["posX"].append(edge[1].posX)
                pos["posY"].append(edge[0].posY)
                pos["posY"].append(edge[1].posY)
            CHLogger.info("get edge pos nums:%d" % len(self.edgeContainer))
            return pos
        except Exception as error:
            CHLogger.error(error)
            return None

    def jarvis(self):
        """
        to find the convex hull with jarvis method
        """
        if len(self.pointContainer) < 3:
            CHLogger.warning("not enough point in the set")
            return None, None
        try:
            pointZero = self.LTLTest()
            pointStart = pointZero
            """
            find the TLT point as the first extreme point noted as pointZero
            and start with pointZero
            """
            while True:
                pointEndTem = pointZero
                for pointTest in self.pointContainer:
                    """
                    search for a point that lies on the left of the tem line
                    """
                    if pointTest == pointEndTem or pointTest == pointStart:
                        continue
                    else:
                        flag = self.toLeftTest(
                            pointStart, pointEndTem, pointTest)
                        """
                        to left test
                        """
                        if flag:
                            pass
                        else:
                            pointEndTem = pointTest

                pointEndTem.extreme = True
                self.appendEdge(pointStart, pointEndTem)
                pointStart = pointEndTem
                """
                find a EE and add it to edge container and set the EP as next turn start point
                """
                if pointZero == pointEndTem:
                    """
                    leave when the next extreme point is the LTL point
                    """
                    break
                else:
                    continue

            CHLogger.info("jarvis")
            edgePos = self.getEdgePos()
            return edgePos
        except Exception as error:
            CHLogger.error(error)

    def toLeftTest(self, pointStart, pointEnd, pointTest):
        """
        to left test.
        to calculate the det of area array
        """
        try:
            areaArray = numpy.array([[pointStart.posX, pointStart.posY, 1],
                                     [pointEnd.posX, pointEnd.posY, 1],
                                     [pointTest.posX, pointTest.posY, 1]])
            signedArea = numpy.linalg.det(areaArray)
            """
            signed area>0 means test point lies on the left
            """
            if signedArea > 0:
                flag = True
            else:
                flag = False
            CHLogger.info("to left test (%f,%f)(%f,%f)(%f,%f) %s" % (
                pointStart.posX, pointStart.posY, pointEnd.posX, pointEnd.posY, pointTest.posX, pointTest.posY, flag))
            return flag
        except Exception as error:
            CHLogger.error(error)

    def LTLTest(self):
        """
        LTL(lowest-then-leftmost) test
        """
        try:
            pointLTL = self.pointContainer[0]
            for pointTest in self.pointContainer:
                if pointTest.posY < pointLTL.posY:
                    pointLTL = pointTest
                elif pointTest.posY == pointLTL.posY:
                    if pointTest.posX < pointLTL.posX:
                        pointLTL = pointTest
                    else:
                        pass
                else:
                    continue
            CHLogger.info("find the LTL poing")
            return pointLTL
        except Exception as error:
            CHLogger.error(error)
            return None

    class Point():
        """
        class of point
        """

        def __init__(self, posX, posY, extreme=False):
            self.posX = posX
            self.posY = posY
            self.extreme = extreme

    class Edge():
        """
        class of edge
        """

        def __init__(self, pointStart, pointEnd, extreme=False):
            self.pointStart = pointStart
            self.pointEnd = pointEnd
            self.extreme = extreme


if __name__ == "__main__":
    class MainTest(unittest2.TestCase):
        """
        test case
        """

        def drawPoint(self):
            pos = self.pointList.getPointPos()
            pyplot.plot(pos["posX"], pos["posY"], "o")

        def setUp(self):
            self.pointList = PointBasket()
            for index in range(10):  # @UnusedVariable
                self.pointList.appendPoint(
                    self.pointList.Point(random.uniform(0, 10), random.uniform(0, 10)))

        def tearDown(self):
            pass

        def test_drawPoint(self):
            pos = self.pointList.getPointPos()
            pyplot.plot(pos["posX"], pos["posY"], "*")
            pyplot.title("draw point")
            pyplot.show()

        def test_drawEdge(self):
            self.pointList.appendEdge(
                self.pointList.pointContainer[0], self.pointList.pointContainer[1])
            pos = self.pointList.getEdgePos()
            self.drawPoint()
            pyplot.plot(pos["posX"], pos["posY"])
            pyplot.title("draw edge")
            pyplot.show()

        def test_LTL(self):
            pointLTL = self.pointList.LTLTest()
            self.drawPoint()
            pyplot.annotate("LTL", xy=(pointLTL.posX, pointLTL.posY))
            pyplot.title("LTL test")
            pyplot.show()

        def test_toLeft(self):
            self.drawPoint()
            li = self.pointList.pointContainer[:3]
            flag = self.pointList.toLeftTest(li[0], li[1], li[2])
            pyplot.plot(
                [point.posX for point in li], [point.posY for point in li], "*")
            pyplot.plot(
                [point.posX for point in li[:2]], [point.posY for point in li[:2]])
            pyplot.annotate("start", xy=(li[0].posX, li[0].posY))
            pyplot.annotate("end", xy=(li[1].posX, li[1].posY))
            pyplot.annotate(flag, xy=(li[2].posX, li[2].posY))
            pyplot.title("to left test")
            pyplot.show()

        def test_jarvis(self):
            self.drawPoint()
            pos = self.pointList.jarvis()
            pyplot.plot(pos["posX"], pos["posY"])
            pyplot.title("jarvis test")
            pyplot.show()
    unittest2.main()

你可能感兴趣的:(Jarvis步进凸包算法)