示例#1
0
文件: mah.py 项目: 9578577/mvn
def main():

    #generate data
    N=75
    red = Mvn.rand(2)
    blue = Matrix(red.sample(N))
    red = Mvn.fromData(blue)

    #create figure  
    fig = pylab.figure(1, figsize=(7, 7))
    fig.suptitle('Mahalabois Distance')

    ax = setupAxes(red.transform(-1))

    # scatter plot of the origional data        
    scatter(ax[0,0],red,blue)

    # scatter plot of the normalized data
    scatter(ax[1,0],red/red,blue/red)

    # draw the cumulative distribution
    cumulative(ax[0,1],red,blue)

    # draw the histogram
    hist(red.mah().pdf,red.mah(blue),ax[1,1])

    ax[0,1].set_xlim([0,None])
    ax[1,1].set_ylim([0,None])
    
    pylab.show()
示例#2
0
文件: mah.py 项目: riviera2015/mvn
def main():

    #generate data
    N = 75
    red = Mvn.rand(2)
    blue = Matrix(red.sample(N))
    red = Mvn.fromData(blue)

    #create figure
    fig = pylab.figure(1, figsize=(7, 7))
    fig.suptitle('Mahalabois Distance')

    ax = setupAxes(red.transform(-1))

    # scatter plot of the origional data
    scatter(ax[0, 0], red, blue)

    # scatter plot of the normalized data
    scatter(ax[1, 0], red / red, blue / red)

    # draw the cumulative distribution
    cumulative(ax[0, 1], red, blue)

    # draw the histogram
    hist(red.mah().pdf, red.mah(blue), ax[1, 1])

    ax[0, 1].set_xlim([0, None])
    ax[1, 1].set_ylim([0, None])

    pylab.show()
示例#3
0
文件: fixture.py 项目: 9578577/mvn
    def makeObjects(flat=None, ndim=None, seed=None):        
        if seed is None:
            seed = randint(1, 1e6)
            
        numpy.random.seed(seed)
        randn = numpy.random.randn
    
        if ndim is None:
            ndim = randint(0, 20)
            
        shapes = {
            None:lambda :max(randint(-ndim, ndim), 0),
            True:lambda :randint(1, ndim),
            False:lambda :0,
        }
    
        triple = lambda x:[x, x, x]
        
        if flat in shapes:
            flat = [item() for item in triple(shapes[flat])]

        elif isinstance(flat, int):
            flat = triple(flat)
        
        assert all(f <= ndim for f in flat), "flatness can't be larger than ndim"
        
        rvec = lambda n=1, ndim=ndim:Matrix(randn(n ,ndim))
                
        A,B,C = [
            Mvn.rand([ndim-F, ndim])
            for F in flat
        ]
    
    
        n = randint(1, 2*ndim)
        M = rvec(n).H
        M2 = rvec(n).H    
    
        E = Matrix.eye(ndim)
        
        K1 = (numpy.random.randn())
        K2 = (numpy.random.randn())
    
        N = randint(-5, 5)
        
        return {
            'ndim' : ndim,
            'A' : A,
            'B' : B,
            'C' : C,
            'M' : M,
            'M2' : M2,
            'E' : E,
            'K1' : K1,
            'K2' : K2,
            'N' : N,
        }
示例#4
0
文件: blend.py 项目: 9578577/mvn
def main():
    """
    demonstrate the `covariance intersection algorithm
    <http://en.wikipedia.org/wiki/Kalman_filter#Update>`_ 
    """
    pylab.figure(1, figsize=(5,5))
    
    red  = Mvn.rand(shape=2)    
    blue = Mvn.rand(shape=2)
    
    magenta = red & blue
    
    red.plot(    facecolor = 'r')
    blue.plot(   facecolor = 'b')
    magenta.plot(facecolor = 'm')   
    
    pylab.xlabel('Magenta = Red & Blue')    
    pylab.show()
示例#5
0
文件: blend.py 项目: riviera2015/mvn
def main():
    """
    demonstrate the `covariance intersection algorithm
    <http://en.wikipedia.org/wiki/Kalman_filter#Update>`_ 
    """
    pylab.figure(1, figsize=(5, 5))

    red = Mvn.rand(shape=2)
    blue = Mvn.rand(shape=2)

    magenta = red & blue

    red.plot(facecolor='r')
    blue.plot(facecolor='b')
    magenta.plot(facecolor='m')

    pylab.xlabel('Magenta = Red & Blue')
    pylab.show()
示例#6
0
    def makeObjects(flat=None, ndim=None, seed=None):
        if seed is None:
            seed = randint(1, 1e6)

        numpy.random.seed(seed)
        randn = numpy.random.randn

        if ndim is None:
            ndim = randint(0, 20)

        shapes = {
            None: lambda: max(randint(-ndim, ndim), 0),
            True: lambda: randint(1, ndim),
            False: lambda: 0,
        }

        triple = lambda x: [x, x, x]

        if flat in shapes:
            flat = [item() for item in triple(shapes[flat])]

        elif isinstance(flat, int):
            flat = triple(flat)

        assert all(f <= ndim
                   for f in flat), "flatness can't be larger than ndim"

        rvec = lambda n=1, ndim=ndim: Matrix(randn(n, ndim))

        A, B, C = [Mvn.rand([ndim - F, ndim]) for F in flat]

        n = randint(1, 2 * ndim)
        M = rvec(n).H
        M2 = rvec(n).H

        E = Matrix.eye(ndim)

        K1 = (numpy.random.randn())
        K2 = (numpy.random.randn())

        N = randint(-5, 5)

        return {
            'ndim': ndim,
            'A': A,
            'B': B,
            'C': C,
            'M': M,
            'M2': M2,
            'E': E,
            'K1': K1,
            'K2': K2,
            'N': N,
        }
示例#7
0
def main():
    M1 = Mvn.rand(2)
    M2 = Mvn.rand(2)

    data1 = M1.sample(100)
    data2 = M2.sample(100)

    M1 = Mvn.fromData(data1)
    M2 = Mvn.fromData(data2)
    M3 = Mvn.fromData([M1, M2])

    data3 = Matrix.stack([[data1], [data2]])

    assert M3 == Mvn.fromData(data3)

    A = pylab.gca()

    M3.plot(A, facecolor='m', minalpha=0.1, zorder=-1)

    M1.plot(A, facecolor='b', minalpha=0.1, zorder=0)
    M2.plot(A, facecolor='r', minalpha=0.1, zorder=1)

    pylab.scatter(data1[:, 0], data1[:, 1], facecolor='b', zorder=2)
    pylab.scatter(data2[:, 0], data2[:, 1], facecolor='r', zorder=3)

    pylab.show()
示例#8
0
文件: fromData.py 项目: 9578577/mvn
def main():
    M1=Mvn.rand(2)    
    M2=Mvn.rand(2)    
    
    data1 = M1.sample(100)
    data2 = M2.sample(100)
    
    M1 = Mvn.fromData(data1)
    M2 = Mvn.fromData(data2)
    M3 = Mvn.fromData([M1,M2])
    
    data3 = Matrix.stack([[data1],[data2]])
        
    assert M3 == Mvn.fromData(data3)

    A=pylab.gca()

    M3.plot(A,facecolor='m',minalpha=0.1,zorder = -1)
    
    M1.plot(A,facecolor='b',minalpha = 0.1,zorder = 0)
    M2.plot(A,facecolor='r',minalpha = 0.1,zorder = 1)

    pylab.scatter(data1[:,0],data1[:,1],facecolor='b',zorder = 2)
    pylab.scatter(data2[:,0],data2[:,1],facecolor='r',zorder = 3)
    

    pylab.show()
示例#9
0
文件: rand.py 项目: MarkDaoust/mvn
def main():
    axes = triax()

    N = int(10.0 ** (1 + 2 * numpy.random.rand()))

    for dims in range(3):
        ax = axes[dims]
        ax.set_title("Mvn.rand((%s,2))" % dims)
        for n in range(N):
            M = Mvn.rand((dims, 2))
            M.plot(ax, facecolor=numpy.random.rand(3))

    pylab.tight_layout()
    pylab.show()
示例#10
0
文件: rand.py 项目: riviera2015/mvn
def main():
    axes = triax()

    N = int(10.0**(1 + 2 * numpy.random.rand()))

    for dims in range(3):
        ax = axes[dims]
        ax.set_title("Mvn.rand((%s,2))" % dims)
        for n in range(N):
            M = Mvn.rand((dims, 2))
            M.plot(ax, facecolor=numpy.random.rand(3))

    pylab.tight_layout()
    pylab.show()
示例#11
0
def main():
    """
    demonstrate marginal distributions
    """
    N = numpy.round(10.0**(1 + 2.5 * numpy.random.rand()))

    #generate a random mvn
    red = Mvn.rand(2)

    #sample some data
    blue = red.sample(N)

    #create a figures of the apropriate size
    pylab.figure(1, figsize=(6, 6))

    #create axes for plotting
    axes = triax()
    mainax = axes[1, 0]
    topax = axes[0, 0]
    sideax = axes[1, 1]

    #do the main plot
    mainax.scatter(blue[:, 0], blue[:, 1], zorder=0, alpha=alpha)
    red.plot(axis=mainax,
             nstd=2,
             zorder=1,
             label=r'$\pm 2 \sigma$',
             **plotParams)
    mainax.legend()

    #freeze the main axes
    mainax.autoscale(False)
    topax.set_autoscalex_on(False)
    sideax.set_autoscaley_on(False)

    #plot the histograms
    hist(red[:, 0], blue[:, 0], topax, orientation='vertical')
    hist(red[:, 1], blue[:, 1], sideax, orientation='horizontal')

    #set the main title
    font = {'size': 12}
    mainax.set_xlabel('red', font)
    topax.set_title('red[:,0]', font)
    sideax.set_title('red[:,1]', font)

    #draw the figure
    pylab.show()
示例#12
0
文件: marginals.py 项目: 9578577/mvn
def main():
    """
    demonstrate marginal distributions
    """
    N=numpy.round(10.0**(1+2.5*numpy.random.rand()))
    
    #generate a random mvn
    red=Mvn.rand(2)
    
    #sample some data
    blue = red.sample(N)

    #create a figures of the apropriate size    
    pylab.figure(1, figsize=(6,6))

    #create axes for plotting
    axes = triax()
    mainax = axes[1,0]
    topax  = axes[0,0]
    sideax = axes[1,1]
        
    #do the main plot
    mainax.scatter(blue[:,0],blue[:,1],zorder = 0,alpha = alpha);
    red.plot(axis = mainax, nstd=2, zorder = 1,label=r'$\pm 2 \sigma$',**plotParams)    
    mainax.legend()    
    
    #freeze the main axes
    mainax.autoscale(False)
    topax.set_autoscalex_on(False)
    sideax.set_autoscaley_on(False)
    
    #plot the histograms
    hist(red[:,0],blue[:,0],topax,orientation = 'vertical')
    hist(red[:,1],blue[:,1],sideax,orientation = 'horizontal')
    
    #set the main title
    font = {'size':12}
    mainax.set_xlabel('red',font)
    topax.set_title('red[:,0]',font)
    sideax.set_title('red[:,1]',font)
    
    #draw the figure
    pylab.show()
示例#13
0
def main():

    #get axis
    ax0 = pylab.subplot(1, 2, 1)
    ax1 = pylab.subplot(1, 2, 2)

    #get data
    A = Mvn.rand(2)
    data = A.sample(10000)

    #squish the data to spherical variance
    deltas = ((data - A.mean) / A).array()

    #calculate the errors in the squished space
    errors = (deltas**2).sum(1)

    print errors

    hist(A.dist2(), errors, ax0)

    pylab.show()
示例#14
0
文件: dist.py 项目: 9578577/mvn
def main():
    
    #get axis
    ax0 = pylab.subplot(1,2,1)
    ax1 = pylab.subplot(1,2,2)    
    
    #get data
    A = Mvn.rand(2)
    data = A.sample(10000)
    
    #squish the data to spherical variance    
    deltas = ((data-A.mean)/A).array()
    
    #calculate the errors in the squished space
    errors = (deltas**2).sum(1)
    
    print errors
    
    hist(A.dist2(),errors,ax0)
    
    
    pylab.show()
示例#15
0
文件: kalman.py 项目: 9578577/mvn
    path = 'kalman'    
    #seed the rng so results are reproducible.
    seed(path)
    #create publisher
    P = Publisher(path)
    #create figure
    fig = pylab.figure(figsize = (6, 6))


    ## kalman filter parameters

    #the actual, hidden state
    actual = numpy.array([[0, 5]])

    #the sensor
    sensor = Mvn(vectors = [[1, 0], [0, 1]],var = [1, numpy.inf])

    #the system noise
    noise = Mvn(vectors = [[1, 0], [0, 1]], var = numpy.array([0.5, 1])**2)

    #the shear transform to move the system forward
    transform = Matrix([[1, 0], [0.5, 1]])

    filtered = sensor.measure(actual)


    ## initial plot

    ax = newAx(fig)
    
    #plot the initial actual position
示例#16
0
文件: EM.py 项目: riviera2015/mvn
#! /usr/bin/env python

import numpy

from mvn import Mvn
from mvn.matrix import Matrix
from mvn.mixture import Mixture

import pylab
pylab.ion()

source = Mixture([
    Mvn.rand(2),
    Mvn.rand(2),
])

data = source.sample(200)

W1, R1 = [1e7], Mvn(mean=[10.0, 10.0], var=numpy.array([10.0, 10.0])**2)
W2, R2 = [1e7], Mvn(mean=[-10.0, -10.0], var=numpy.array([10.0, 10.0])**2)

old_p = numpy.inf

for N in range(10):
    pylab.gcf().clear()

    pi1 = sum(W1)
    pi2 = sum(W2)

    (pi1, pi2) = [pi1 / (pi1 + pi2), pi2 / (pi1 + pi2)]
示例#17
0
文件: EM.py 项目: 9578577/mvn
#! /usr/bin/env python

import numpy

from mvn import Mvn
from mvn.matrix import Matrix
from mvn.mixture import Mixture

import pylab; 
pylab.ion()

source = Mixture([
    Mvn.rand(2),
    Mvn.rand(2),
])

data = source.sample(200) 


W1,R1 = [1e7],Mvn(mean=[ 10.0, 10.0],var=numpy.array([10.0,10.0])**2)
W2,R2 = [1e7],Mvn(mean=[-10.0,-10.0],var=numpy.array([10.0,10.0])**2)

old_p = numpy.inf

for N in range(10):
    pylab.gcf().clear()

    pi1 = sum(W1)
    pi2 = sum(W2)

    (pi1,pi2) = [
示例#18
0
    #directory for resulting figures
    path = 'kalman'
    #seed the rng so results are reproducible.
    seed(path)
    #create publisher
    P = Publisher(path)
    #create figure
    fig = pylab.figure(figsize=(6, 6))

    ## kalman filter parameters

    #the actual, hidden state
    actual = numpy.array([[0, 5]])

    #the sensor
    sensor = Mvn(vectors=[[1, 0], [0, 1]], var=[1, numpy.inf])

    #the system noise
    noise = Mvn(vectors=[[1, 0], [0, 1]], var=numpy.array([0.5, 1])**2)

    #the shear transform to move the system forward
    transform = Matrix([[1, 0], [0.5, 1]])

    filtered = sensor.measure(actual)

    ## initial plot

    ax = newAx(fig)

    #plot the initial actual position
    ax.plot(actual[:, 0], actual[:, 1], **actualParams)
示例#19
0
def main():
    N = 75  #numpy.round(10.0**(1.5+1*numpy.random.rand()))

    #generate data
    red = Mvn.rand(2)
    blue = red.sample(N)
    red = Mvn.fromData(blue)

    #create figure
    fig = pylab.figure(1, figsize=(7, 7))
    fig.suptitle('Mahalabois Distance')

    axgrid = GridSpec(2, 2)
    ax = numpy.empty([2, 2], dtype=object)

    #get axes
    ax[0, 0] = subplot(axgrid[0, 0])
    ax[0, 0].axis('equal')
    ax[0, 0].grid('on')
    ax[0, 0].set_title('red')

    @curry
    def forewardTransform(center, M, x, y):

        center = center.squeeze()

        x = Matrix(x)
        y = Matrix(y)
        xy = numpy.hstack([x.T, y.T])
        xy = xy - center[None, :]

        xy = numpy.array(xy * M)

        mags = (numpy.array(xy)**2).sum(1)[:, None]**0.5
        dirs = xy / mags

        xy = dirs * mags**2

        return xy[:, 0].squeeze(), xy[:, 1].squeeze()

    @curry
    def reverseTransform(center, M, x, y):

        center = center.squeeze()

        x = Matrix(x)
        y = Matrix(y)
        xy = numpy.hstack([x.T, y.T])
        xy = xy - center[None, :]

        xy = numpy.array(xy * M)

        mags = (numpy.array(xy)**2).sum(1)[:, None]**0.5
        dirs = xy / mags

        xy = dirs * mags**0.5 + center

        return xy[:, 0].squeeze(), xy[:, 1].squeeze()

    foreward = forewardTransform(red.mean, red.transform(-1))
    reverse = reverseTransform(red.mean, red.transform(1))

    grid_helper = GridHelperCurveLinear([foreward, reverse])

    ax[1, 0] = subplot(axgrid[1, 0],
                       projection='custom',
                       transform=grid_helper)
    ax[1, 0].axis('equal')
    ax[1, 0].grid('on')
    ax[1, 0].set_title('red/red')

    ax[0, 1] = subplot(axgrid[0, 1])
    ax[0, 1].grid('on')
    ax[0, 1].set_title('red.mah2().cdf()')
    ax[0, 1].set_ylim([0, 1])

    ax[1, 1] = pylab.subplot(axgrid[1, 1], sharex=ax[0, 1])  #,sharey=ax[0,1])
    ax[1, 1].grid('on')
    ax[1, 1].set_title('red.mah2().pdf()')

    scatter(ax[0, 0], red, blue)

    #  blue0 = Matrix(blue)/red
    #  blue0 = blue0.array()
    red0 = red / red

    blue0 = foreward(blue[:, 0], blue[:, 1])
    blue0 = numpy.hstack([blue0[0][:, None], blue0[1][:, None]])

    scatter(ax[1, 0], red0, blue0)

    mah2 = red.mah2(blue)
    mah2.sort()
    ax[0, 1].hlines(numpy.arange(mah2.size, dtype=float) / mah2.size,
                    0,
                    mah2,
                    color='b',
                    alpha=alpha)
    ax[0, 1].scatter(mah2,
                     numpy.arange(mah2.size, dtype=float) / mah2.size,
                     color='b',
                     alpha=alpha)
    x = numpy.linspace(*ax[0, 1].get_xlim(), num=500)
    ax[0, 1].plot(x, red.mah2().cdf(x), color='r', linewidth=2, alpha=alpha)
    hist(red.mah2().pdf, red.mah2(blue), ax[1, 1])

    ax[0, 1].set_xlim([0, None])
    ax[1, 1].set_ylim([0, None])

    pylab.show()
示例#20
0
文件: mah2.py 项目: 9578577/mvn
def main():
    N=75#numpy.round(10.0**(1.5+1*numpy.random.rand()))

    #generate data
    red = Mvn.rand(2)
    blue = red.sample(N)
    red = Mvn.fromData(blue)

    #create figure
    fig = pylab.figure(1, figsize=(7, 7))
    fig.suptitle('Mahalabois Distance')
    
    axgrid = GridSpec(2, 2)
    ax = numpy.empty([2, 2],dtype = object)

    #get axes
    ax[0, 0] = subplot(axgrid[0, 0])
    ax[0, 0].axis('equal')
    ax[0, 0].grid('on')
    ax[0, 0].set_title('red')
    
    
    @curry
    def forewardTransform(center, M, x, y):

        center = center.squeeze()

        x = Matrix(x)
        y = Matrix(y)
        xy = numpy.hstack([x.T, y.T])
        xy = xy - center[None, :]

        xy = numpy.array(xy*M)

        mags = (numpy.array(xy)**2).sum(1)[:, None]**0.5
        dirs = xy/mags

        xy = dirs*mags**2
        
        return xy[:, 0].squeeze(), xy[:, 1].squeeze()

    @curry
    def reverseTransform(center, M, x, y):

        center = center.squeeze()

        x = Matrix(x)
        y = Matrix(y)
        xy = numpy.hstack([x.T, y.T])
        xy = xy - center[None, :]

        xy = numpy.array(xy*M)

        mags = (numpy.array(xy)**2).sum(1)[:, None]**0.5
        dirs = xy/mags

        xy = dirs*mags**0.5 + center
        
        return xy[:, 0].squeeze(), xy[:, 1].squeeze()


    foreward = forewardTransform(red.mean, red.transform(-1))
    reverse = reverseTransform(red.mean, red.transform(1))
    
    grid_helper =  GridHelperCurveLinear([
        foreward,
        reverse
    ])
    
    
    
    

    ax[1, 0] = subplot(axgrid[1, 0],
        projection = 'custom', 
        transform = grid_helper
    )    
    ax[1, 0].axis('equal')
    ax[1, 0].grid('on')
    ax[1, 0].set_title('red/red')
    
    ax[0, 1] = subplot(axgrid[0, 1])
    ax[0, 1].grid('on')
    ax[0, 1].set_title('red.mah2().cdf()')
    ax[0, 1].set_ylim([0, 1])
    
    ax[1, 1] = pylab.subplot(axgrid[1, 1], sharex=ax[0, 1])#,sharey=ax[0,1])
    ax[1, 1].grid('on')
    ax[1,1].set_title('red.mah2().pdf()')
    
    scatter(ax[0, 0], red, blue)

  #  blue0 = Matrix(blue)/red
  #  blue0 = blue0.array()
    red0 = red/red
    
    blue0 = foreward(blue[:, 0], blue[:, 1])
    blue0 = numpy.hstack([blue0[0][:, None], blue0[1][:, None]])
    
    scatter(ax[1, 0], red0, blue0)

    mah2 = red.mah2(blue)
    mah2.sort()
    ax[0, 1].hlines(numpy.arange(mah2.size, dtype = float)/mah2.size, 0,mah2, color = 'b', alpha = alpha)
    ax[0, 1].scatter(mah2, numpy.arange(mah2.size, dtype = float)/mah2.size, color = 'b', alpha = alpha)
    x = numpy.linspace(*ax[0, 1].get_xlim(), num=500)    
    ax[0, 1].plot(x, red.mah2().cdf(x), color = 'r', linewidth = 2, alpha = alpha)
    hist(red.mah2().pdf, red.mah2(blue), ax[1, 1])

    ax[0, 1].set_xlim([0, None])
    ax[1, 1].set_ylim([0, None])
    
    pylab.show()