summaryrefslogtreecommitdiff
path: root/tools.py
blob: 6835228537c3ee4dd3ed33020d7459b585d12c4d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import numpy as np
import time
import datetime

def timeit(func):
    def f(*args, **kwargs):
        t0 = time.time()
        retval = func(*args, **kwargs)
        elapsed = time.time() - t0
        print '%s elapsed in %s().' % (datetime.timedelta(seconds=elapsed), func.__name__)
        return retval
    return f

def read_csv(filename):
    """Return an array of comma-separated values from `filename`."""
    f = open(filename)

    points = []
    for line in f:
        try:
            points.append([float(s) for s in line.split(',')])
        except ValueError:
            pass

    f.close()

    return np.array(points)

def offset(points, x):
    """
    Return the set of points obtained by offsetting the edges of the profile
    created by `points` by an amount `x`.

    Args:
        - points: array
            Array of points which define the 2-D profile to be offset.
        - x: float
            Distance to offset the profile; a positive `x` value will offset
            the profile in the direction of the profile path rotated 90 degrees
            clockwise.
    """
    points = np.asarray(points)
    points = np.array([points[0] - (points[1] - points[0])] + list(points) + [points[-1] - (points[-2] - points[-1])])
    
    offset_points = []
    for i in range(1,len(points)-1):
        v1 = np.cross(points[i]-points[i-1], (0,0,1))[:2]
        v1 /= np.linalg.norm(v1)
        v1 *= x

        a = points[i-1] + v1
        b = points[i] + v1

        v2 = np.cross(points[i+1]-points[i], (0,0,1))[:2]
        v2 /= np.linalg.norm(v2)
        v2 *= x

        c = points[i] + v2
        d = points[i+1] + v2

        m = np.empty((2,2))
        m[:,0] = b-a
        m[:,1] = c-d

        try:
            j = np.linalg.solve(m, c-a)[0]
        except np.linalg.linalg.LinAlgError as e:
            offset_points.append(b)
            continue

        offset_points.append((a + j*(b-a)))

    return np.array(offset_points)