#!/usr/bin/env python
#
# basic vector operations (2D, 3D, ...)

from math import sqrt, cos, sin, atan2


def vec_add(v1, *rest):
    """Adds an arbitrary number of vectors."""
    res = []
    for i in range(len(v1)):
	res.append(v1[i])
	for j in range(len(rest)):
	    res[i] += rest[j][i]
    return tuple(res)


def vec_sub(v1, v2):
    """Performs v1 - v2."""
    res = []
    for i in range(len(v1)):
	res.append(v1[i]-v2[i])
    return tuple(res)


def vec_mult(v, f):
    """Multiplies the vector `v' by the scalar factor `f'."""
    return tuple(map(lambda x: x*f, v))


def vec_dot(v1, v2):
    """Returns the dot product of the two vectors."""
    return reduce(lambda x,y: x+y, map(lambda x,y: x*y, v1, v2))


def vec_mag(v):
    """Returns the magnitude of `v'."""
    return sqrt(vec_dot(v,v))


def vec_norm(v):
    """Returns the normalized version of `v'."""
    mag = vec_mag(v)
    return vec_mult(v, 1/float(mag))


def vec_from_polar(r,th):
    """Constructs a vector from polar coordinates."""
    return (r*cos(th), r*sin(th))


def vec_to_polar(v):
    """Returns the vector in polar coordinates."""
    return (vec_mag(v), atan2(v[1], v[0]))
    
