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()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 201,049评论 5 473
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,478评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 148,109评论 0 333
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,097评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,115评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,280评论 1 279
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,748评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,398评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,553评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,440评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,487评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,176评论 3 317
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,750评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,821评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,049评论 1 257
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,559评论 2 348
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,150评论 2 341

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,271评论 0 10
  • Binner阅读 494评论 0 50
  • 姓名:夏振亚 公司:常州新日催化剂有限公司 【日精进打卡22第天】 【知~学习】 《六项精进》1遍共176遍 《大...
    夏振亚阅读 207评论 0 0