Point-Feature-Histogram / src / pca.py
pca.py
Raw
import numpy
import math

def getVs(s, v, alpha):
    """

    Returns dimentionality reducted

    """
    vs = []
    for i in range(0, len(s)):
        if s[i] > alpha:
            vs.append(v[:][i]) # append column
    return vs

def pca(X, isNoiseEliminating):
    """

    Implementation of the Principal Component Analysis Algorithm

    X - list of indicies
    P - matrix of points in a point cloud

    isNoiseEliminating - boolean value telling whether the algorithm

        should eliminate noise

    USAGE:

    newPc, vs, meanVec = pca(pc, False)

    # Show the resulting point cloud
    fig = utils.view_pc_two([pc, numpy.asmatrix(newPc)])
    
    # Plot the plane
    norm = numpy.asmatrix(numpy.expand_dims(numpy.cross(vs[0, :], vs[1, :]), axis=1)) # cross prod between two vectors
    meanVec = numpy.asmatrix(numpy.expand_dims(meanVec, axis=1))
    utils.draw_plane(fig, norm, meanVec, color=(0, 1, 0, 0.3))

    """
    X = numpy.array(X)
    #X = numpy.squeeze(X, axis=0)
    mu = numpy.mean(X, axis=0)
    X -= mu
    X = X.T
    Y = X.T/math.sqrt(len(X) - 1)
    u, s, vh = numpy.linalg.svd(Y)
    if(isNoiseEliminating):
        vs = getVs(s, numpy.transpose(vh), 1) # tune alpha
        # print("Vst:")
        # print(numpy.asmatrix(vs).T)
        X = numpy.dot(vs, X)
        return X.T, vs, mu
    else:
        # print("Vt")
        # print(numpy.asmatrix(vh).T)
        X = numpy.dot(vh, X)
        return X.T, vh, mu