Source

geoalg / geoalg / util.py

#!/usr/bin/env python
#coding:utf-8
# Author:  mozman
# Purpose: util functions
# module belongs to package geoalg
# Created: 28.02.2010
# License: GPLv3

from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import

import math

from geoalg import equals_almost

HALF_PI = math.pi / 2.
THREE_PI_HALF = 1.5 * math.pi
DOUBLE_PI = 2. * math.pi

almost_equal = equals_almost

def almost_equal_vectors(v1, v2, places=6):
    return all(almost_equal(a, b, places) for a, b in zip(v1, v2))

def distance(p1, p2):
    """ Distance between p1 and p2.
    """
    dx = p1[0] - p2[0]
    dy = p1[1] - p2[1]
    try:
        dz = p1[2] - p2[2]
    except IndexError:
        dz = 0.
    return (dx**2 + dy**2 + dz**2) ** .5

def mid_point(p1, p2):
        """ Returns the midpoint between p1 and p2 as 3-tuple.
        """
        x = (p1[0] + p2[0]) / 2.0
        y = (p1[1] + p2[1]) / 2.0
        try:
            z = (p1[2] + p2[2]) / 2.0
        except IndexError:
            z = 0.
        return x, y, z

## {{{ http://code.activestate.com/recipes/578231/ (r1)
def memodict(f):
    """ Memoization decorator for a function taking a single argument """
    class memodict(dict):
        def __missing__(self, key):
            ret = self[key] = f(key)
            return ret
    return memodict().__getitem__
## end of http://code.activestate.com/recipes/578231/ }}}

def centroid2d(points):
    sumx, sumy = 0., 0.
    count = 0
    for point in points:
        sumx += point[0]
        sumy += point[1]
        count += 1
    return sumx/count, sumy/count

def centroid3d(points):
    sumx, sumy, sumz = 0., 0., 0.
    count = 0
    for point in points:
        sumx += point[0]
        sumy += point[1]
        sumz += point[2]
        count += 1
    return sumx/count, sumy/count, sumz/count