Esempio n. 1
0
 def inf(self, x, meanonly=False):
     x = np.asmatrix(x)
     if x.shape[1] != self.d:
         if x.shape[0] == self.d:
             x = x.T
         else:
             raise Exception('Invalid test-set dimension -- '
                             'expected d = ' + str(self.d) + '.')
     n = x.shape[0]
     # Handle empty test set
     if n == 0:
         return (np.zeros((0, 1)), np.zeros((0, 1)))
     ms = self.kernel.mean*np.ones((n, 1))
     Kbb = self.kernel(x, diag=True)
     # Handle empty training set
     if len(self) == 0:
         return (ms, np.asmatrix(Kbb))
     Kba = self.kernel(x, self.x)
     m = self.kernel.mean*np.ones((len(self), 1))
     fm = ms + Kba*scipy.linalg.cho_solve((self.L, True), self.y - m,
                                          overwrite_b=True)
     if meanonly:
         return fm
     else:
         W = scipy.linalg.cho_solve((self.L, True), Kba.T)
         fv = np.asmatrix(Kbb - np.sum(np.multiply(Kba.T, W), axis=0).T)
         # W = np.asmatrix(scipy.linalg.solve(self.L, Kba.T, lower=True))
         # fv = np.asmatrix(Kbb - np.sum(np.power(W, 2), axis=0).T)
         return (fm, fv)
Esempio n. 2
0
File: core.py Progetto: josipd/Gpy
 def add(self, x, y, update=True):
     assert x.shape[0] == y.shape[0]
     assert x.shape[1] == self.d
     assert y.shape[1] == 1
     x = np.asmatrix(x)
     y = np.asmatrix(y)
     if x.shape[0] > 0:
         self.x = np.concatenate((self.x, x))
         self.y = np.concatenate((self.y, y))
     if update:
         self._update()
Esempio n. 3
0
 def from_mat(cls, fname):
     import scipy.io
     m = scipy.io.loadmat(fname, byte_order='native')
     data = {}
     data['x'] = np.asmatrix(m['tc'][0][0][0][0][0][0].newbyteorder('='))
     data['y'] = np.asmatrix(m['tc'][0][0][0][0][0][1].newbyteorder('='))
     h = m['tc'][0][0][1][0][0].newbyteorder('=')
     name = m['tc'][0][0][3][0]
     hyp = {'mean': 2.4, 'cov': [5.5, 1, 0.75], 'lik': -1}
     k = kernels.SE(hyp)
     tc = Testcase(k, data=data, h=h, name=name)
     return tc
Esempio n. 4
0
 def from_mat(cls, fname):
     import scipy.io
     m = scipy.io.loadmat(fname, byte_order='native')
     data = {}
     data['x'] = np.asmatrix(m['tc'][0][0][0][0][0][0].newbyteorder('='))
     data['y'] = np.asmatrix(m['tc'][0][0][0][0][0][1].newbyteorder('='))
     h = m['tc'][0][0][1][0][0].newbyteorder('=')
     name = m['tc'][0][0][3][0]
     hyp = {'mean': 2.4, 'cov': [5.5, 1, 0.75], 'lik': -1}
     k = kernels.SE(hyp)
     tc = Testcase(k, data=data, h=h, name=name)
     return tc
Esempio n. 5
0
 def __call__(self, x, z=[], diag=False):
     if x.shape[0] == 0:
         return np.zeros((0, 0))
     if diag:
         return self.sf2*np.ones((x.shape[0], 1))
     sx = x*self.covd
     if z == []:
         K = np.asmatrix(ssd.squareform(ssd.pdist(sx, 'sqeuclidean')))
     else:
         sz = z*self.covd
         K = np.asmatrix(ssd.cdist(sx, sz, 'sqeuclidean'))
     K = self.sf2*np.exp(-K/2)
     return K
Esempio n. 6
0
        def computeCovariance(self):
            """
            Computes the time-lagged covariance matrix :math:`C^{\\tau}` with
            :math:`c_{ij}^{\\tau} = \\frac{1}{N-\\tau-1}\\sum_{t=1}^{N-\\tau}x_{ti}x_{(t+\\tau)j}`
            """

            self.m_prinComp.m_dataImporter.rewind()

            dataChunk = np.asarray(self.m_prinComp.m_dataImporter.get_data(self.m_prinComp.param_chunkSize), dtype=np.float32)
            dimData = self.m_prinComp.m_dataImporter.get_shape_inFile()
            shapeDataChunk = dataChunk.shape
            m = shapeDataChunk[0]

            self.m_covMatTimeLag = matlib.zeros([shapeDataChunk[1], shapeDataChunk[1]], dtype = np.float64)
            normalizedPCs = matlib.zeros([shapeDataChunk[1], shapeDataChunk[1]], dtype = np.float64)

            if 1 < m:

                pcs = self.m_prinComp.computePCs(dataChunk, shapeDataChunk[1])
                del dataChunk
                normalizedPCs = self.m_prinComp.normalizePCs(pcs)
                del pcs
                self.m_covMatTimeLag += np.dot(normalizedPCs[0:(m - self.param_timeLag), :].T,
                                               normalizedPCs[self.param_timeLag:m, :])

            lastRowsChunkBefore = normalizedPCs[(m-self.param_timeLag):m, :]
            del normalizedPCs

            while self.m_prinComp.m_dataImporter.has_more_data():

                dataChunk = np.asarray(self.m_prinComp.m_dataImporter.get_data(self.m_prinComp.param_chunkSize), dtype=np.float32)
                shapeDataChunk = dataChunk.shape
                m = shapeDataChunk[0]

                pcs = self.m_prinComp.computePCs(dataChunk, shapeDataChunk[1])
                del dataChunk
                normalizedPCs = self.m_prinComp.normalizePCs(pcs)
                del pcs
                self.m_covMatTimeLag += np.dot(matlib.asmatrix(lastRowsChunkBefore).T,
                                               matlib.asmatrix(normalizedPCs[0:self.param_timeLag, :]))

                if 1 < m:

                    self.m_covMatTimeLag += np.dot(normalizedPCs[0:(m - self.param_timeLag), :].T,
                                                   normalizedPCs[self.param_timeLag:m, :])

                lastRowsChunkBefore = normalizedPCs[(m-self.param_timeLag):m, :]
                del normalizedPCs

            self.m_covMatTimeLag *= 1.0 / (dimData[0] - self.param_timeLag - 1.0)
Esempio n. 7
0
    def normalizePCs(self, i_pcsChunk):
        """
        This function computes the normalizes the principle components :math:`Y` of the input data :math:`X`.
        Let :math:`\\Lambda` be a diagonal matrix with the ordered eigenvalues of the instantaneous
        #covariance matrix :math:`C`. The normalized principle components :math:`\\tilde{Y}` are computed
        by :math:`\\tilde{Y} = \\Lambda^{-\\frac{1}{2}}Y)`.

        :param i_pcsChunk: A chunk of principle components.
        :type i_pcsChunk: numpy.array

        :return o_pcNorm: The normalized principle components :math:`\\tilde{Y}`.
        :rtype: numpy.array
        """

        temp = self.m_eigenDecomp.m_eigenValReal + self.param_addEpsilon

        if ( any(temp < 0) or any(np.isnan(temp)) ) and self.param_useDampingAdapt:

            lamb = self.naiveDampingParamAdapt()

        else:

            lamb = 1.0 / np.sqrt(self.m_eigenDecomp.m_eigenValReal + self.param_addEpsilon)

        if not 1 < i_pcsChunk.shape[0]:

            o_pcNorm = np.dot(matlib.asmatrix(i_pcsChunk), np.diag(lamb))

        else:

            o_pcNorm = np.dot(i_pcsChunk, np.diag(lamb))

        return o_pcNorm
Esempio n. 8
0
 def get_u(self):
     points = npmat.hstack([s.center_position for s in self.solids])
     center = npmat.asmatrix(npmat.average(points, axis = 1)).T
     centered_points = points - center
     correlation_matrix = (centered_points * centered_points.T)/self.nb_solids   
     u = iterate(correlation_matrix, self.NB_ITERATIONS)
     return u
Esempio n. 9
0
    def computePCs(self, i_dataChunk, i_domComp):
        """
        This function computes the principle components of the input data :math:`X`.
        Let :math:`\\Gamma` be the matrix which contains the ordered eigenvectors of the instantaneous
        covariance matrix :math:`C`. The principle components :math:`Y` are computed
        by :math:`Y = \\Gamma^{T}(X-mean(X))`.

        :param i_dataChunk: A data chunk as a subset of hole data.
        :type i_dataChunk: numpy.array
        :param i_domComp: Number of dominated components which are considered.
        :type i_domComp: int
        :return o_pc: The principle components :math:`Y`.
        :rtype: numpy.array
        """

        if not 1 < i_dataChunk.shape[0]:

            meanFreeChunk = i_dataChunk[:, 0:i_dataChunk.shape[1]] - self.m_colMeans
            o_pc = np.dot(matlib.asmatrix(meanFreeChunk), self.m_eigenDecomp.m_eigenVecReal[:, 0:i_domComp])
            del meanFreeChunk

        else:

            meanFreeChunk = i_dataChunk[:, 0:i_dataChunk.shape[1]] - self.m_colMeans
            o_pc = np.dot( meanFreeChunk, self.m_eigenDecomp.m_eigenVecReal[:, 0:i_domComp])
            del meanFreeChunk

        return o_pc
Esempio n. 10
0
def cross_product_matrix(w):
    """
        Returns a matrix representing the linear function (v -> cross_product(w,v))
        where w is a 3 dimensional vector
    """
    x = w[0, 0]
    y = w[1, 0]
    z = w[2, 0]
    return npmat.asmatrix([[0., -z, y], [z, 0., -x], [-y, x, 0.]])
Esempio n. 11
0
def iterate(M, nb_iterations):
    
    w = npmat.asmatrix(npmat.random.uniform(0., 1., size = (3, 1)))
    w /= npmat.linalg.norm(w)
    
    for i in range(nb_iterations):
        w = M * w
        w /= npmat.linalg.norm(w)
                
    return w
Esempio n. 12
0
    def colliding_boxes(self):
        
        nb_solids = self.nb_solids
        points = npmat.hstack([s.center_position for s in self.solids])
        center = npmat.asmatrix(npmat.average(points, axis = 1)).T
        centered_points = points - center
        correlation_matrix = (centered_points * centered_points.T) / nb_solids
        u = iterate(correlation_matrix, self.NB_ITERATIONS)

    
        if self.projected_bounds is None:
            
            self.projected_bounds = []
            
            for i in range(nb_solids):
                self.projected_bounds.append((i, 0, 0.))
                self.projected_bounds.append((i, 1, 0.))
                
        
        min_max_projections = npmat.empty((nb_solids, 2))
        
        for solid_id in range(nb_solids):
            solid_AABB_corners = self.solids[solid_id].AABB_corners()
            corners_projections = u.T * solid_AABB_corners
            min_max_projections[solid_id, 0] = np.min(corners_projections)
            min_max_projections[solid_id, 1] = np.max(corners_projections)
            
        for i in range(2 * nb_solids):            
            solid_id, begin_or_end_id, value = self.projected_bounds[i]
            new_value = min_max_projections[solid_id, begin_or_end_id]
            self.projected_bounds[i] = (solid_id, begin_or_end_id, new_value)
                
        # TODO: linear sorting
        self.projected_bounds.sort(key = lambda x : x[2])
        
        output = []
        active_solids = []
    
        for i in range(2 * nb_solids):
            
            solid_id, begin_or_end_id, value = self.projected_bounds[i]
            
            if begin_or_end_id == 0:
                for active_solid_id in active_solids:
                    if self.solids[active_solid_id].AABB_intersect_with(self.solids[solid_id]):
                        output.append((active_solid_id, solid_id))
                        
                active_solids.append(solid_id)
                
            else:
                active_solids.remove(solid_id)
                
        return output
    def forward(self, ngrami):
        aux = self.C[ngrami[0, :], :][0]
        aux = aux.reshape((aux.shape[0] * aux.shape[1], 1))

        x = shared(np.asmatrix(aux, 'float32'))

        o = self.linear(self.H, x, self.D)
        a = self.sigmoid(o)
        e = self.linear(self.U, a, self.B)
        z = self.dot(self.W, x)
        y = np.add(e, z)

        return y, a, x
Esempio n. 14
0
 def add(self, x, y, update=True):
     x = np.asmatrix(x)
     y = np.asmatrix(y)
     if x.shape[1] != self.d:
         if x.shape[0] == self.d:
             x = x.T
         else:
             raise Exception('Invalid train-set (x) dimension -- '
                             'expected d = ' + str(self.d) + '.')
     if y.shape[1] != 1:
         if y.shape[0] == 1:
             y = y.T
         else:
             raise Exception('Invalid train-set (y) dimension -- '
                             'expected d = 1.')
     if y.shape[0] != x.shape[0]:
         raise Exception('Incompatible train-set (x, y) lengths.')
     x = np.asmatrix(x)
     y = np.asmatrix(y)
     if x.shape[0] > 0:
         self.x = np.concatenate((self.x, x))
         self.y = np.concatenate((self.y, y))
     if update:
         self._update()
Esempio n. 15
0
File: core.py Progetto: josipd/Gpy
 def inf(self, x, meanonly=False):
     x = np.asmatrix(x)
     assert x.shape[1] == self.d
     n = x.shape[0]
     # Handle empty test set
     if n == 0:
         return (np.zeros((0, 1)), np.zeros((0, 1)))
     ms = self.kernel.mean*np.ones((n, 1))
     Kbb = self.kernel(x, diag=True)
     # Handle empty training set
     if len(self) == 0:
         return (ms, np.asmatrix(np.diag(Kbb)).T)
     Kba = self.kernel(x, self.x)
     m = self.kernel.mean*np.ones((len(self), 1))
     fm = ms + Kba*scipy.linalg.cho_solve((self.L, True), self.y - m,
                                          overwrite_b=True)
     if meanonly:
         return fm
     else:
         W = scipy.linalg.cho_solve((self.L, True), Kba.T)
         fv = np.asmatrix(Kbb - np.sum(np.multiply(Kba.T, W), axis=0).T)
         # W = np.asmatrix(scipy.linalg.solve(self.L, Kba.T, lower=True))
         # fv = np.asmatrix(Kbb - np.sum(np.power(W, 2), axis=0).T)
         return (fm, fv)
Esempio n. 16
0
def rotation_matrix_from_quaternion(q):
    """
        Returns the rotation matrix associated to a unitary
        quaternion represented by a 4 dimensional vector
    """
    a, b, c, d = npmat.asarray(q).reshape(-1)
    a2 = a * a
    b2 = b * b
    c2 = c * c
    d2 = d * d

    return npmat.asmatrix(
        [[a2 + b2 - c2 - d2, 2. * (b * c - a * d), 2. * (a * c + b * d)],
         [2. * (a * d + b * c), a2 - b2 + c2 - d2, 2. * (c * d - a * b)],
         [2. * (b * d - a * c), 2. * (a * b + c * d), a2 - b2 - c2 + d2]])
    def train(self, w, z, eta=0.005, epoca=1000, error=0.01):

        count = 0

        training_samples_pos = sample(range(w.shape[0]), min(w.shape[0], epoca))

        while count < epoca:
            for i in training_samples_pos:

                traini = w[i, :]

                y, a, x = self.forward(traini)

                x = shared(np.asmatrix(y, 'float32'))

                self.probs = self.softmax(y)
Esempio n. 18
0
def haar_inverse(image, dim=2):
    '''
    Apply haar inverse transformation.

    :param image: square matrix
    :param dim: dimension
    :return: None
    '''
    P = permutation_matrix(dim)
    T = haar_matrix(dim)

    image[0:dim, 0:dim] = T.T * P.T * M.asmatrix(image[0:dim, 0:dim]) * P * T

    if dim == M.shape(image)[0]:
        return

    haar_inverse(image, dim * 2)
Esempio n. 19
0
def haar_inverse(image, dim=2):
    '''
    Apply haar inverse transformation.

    :param image: square matrix
    :param dim: dimension
    :return: None
    '''
    P = permutation_matrix(dim)
    T = haar_matrix(dim)

    image[0:dim, 0:dim] = T.T * P.T * M.asmatrix(image[0:dim, 0:dim]) * P * T

    if dim == M.shape(image)[0]:
        return

    haar_inverse(image, dim * 2)
Esempio n. 20
0
 def minfo(self, x):
     x = np.asmatrix(x)
     assert x.shape[1] == self.d
     n = x.shape[0]
     # Handle empty test set
     if n == 0:
         return 0
     Kbb = self.kernel(x)
     # Handle empty training set
     if len(self) == 0:
         S = Kbb
     else:
         Kba = self.kernel(x, self.x)
         S = Kbb - Kba*scipy.linalg.cho_solve((self.L, True), Kba.T)
     sn2 = np.exp(2*self.kernel.lik)
     (sng, mi) = numpy.linalg.slogdet(np.eye(n) + S/sn2)
     return 0.5*mi
Esempio n. 21
0
def onComputeClick():    
    epsilon = float(epsilonInput.get())    
    if matrixInput.get() == "rand":
        N = int(matrixSizeInput.get())
        m = generateRandMatrix(N)
    elif matrixInput.get() == "conv_ex":
        N = 3
        m = [[6., 3., 2.], [7., 2., 3.], [5., 5., 1.]]
    elif matrixInput.get() == "non_conv_ex":
        N = 2
        m = [[1., 1.], [0., -1.]]
        
    maxIt =N*1000 
       
    if  numPySelectionInput.get() == "no":
        startComputation(m, N, epsilon, maxIt)
    elif numPySelectionInput.get() == "yes":
        m = matlib.asmatrix(m)        
        startComputation_np(m, N, epsilon, maxIt)        
Esempio n. 22
0
def haar_forward(image, dim=None, recursive=True):
    '''
    Apply haar transformation to image.

    :param image: square matrix
    :param dim: dimension
    :param recursive: apply recursively
    :return: None
    '''
    if dim is None:
        dim = M.shape(image)[0]

    if dim == 1:  # base case
        return

    P = permutation_matrix(dim)
    T = haar_matrix(dim)

    image[0:dim, 0:dim] = P * T * M.asmatrix(image[0:dim, 0:dim]) * T.T * P.T

    if recursive:
        haar_forward(image, dim / 2)
Esempio n. 23
0
def haar_forward(image, dim=None, recursive=True):
    '''
    Apply haar transformation to image.

    :param image: square matrix
    :param dim: dimension
    :param recursive: apply recursively
    :return: None
    '''
    if dim is None:
        dim = M.shape(image)[0]

    if dim == 1:  # base case
        return

    P = permutation_matrix(dim)
    T = haar_matrix(dim)

    image[0:dim, 0:dim] = P * T * M.asmatrix(image[0:dim, 0:dim]) * T.T * P.T

    if recursive:
        haar_forward(image, dim / 2)
    Simultaneous estimation of the full pose, i.e. including all six channels.
'''

import numpy as np
import numpy.matlib as mt

from kalmanfilter import Constant, exponentialSmooth, M
import kalmanfilter
from kalman_simulation2 import getTrack


def SetupKf(measurement, dt, (sigmaQ, sigmaQVPfactor, sigmaQVVfactor)):
  R = mt.asmatrix([ 
  [ 1.334363e-02 , 1.460443e-03 , 1.540213e-03 , -2.719011e-02 , -3.486926e-04 , 1.866799e-02 , ],
  [ 1.460443e-03 , 5.416844e-03 , -3.137613e-03 , 1.608790e-02 , -2.012435e-03 , 8.478703e-03 , ],
  [ 1.540213e-03 , -3.137613e-03 , 8.234656e-02 , 1.201560e-02 , 4.897242e-02 , -2.295807e-03 , ],
  [ -2.719011e-02 , 1.608790e-02 , 1.201560e-02 , 6.615176e-01 , -2.021002e-02 , 7.779090e-03 , ],
  [ -3.486926e-04 , -2.012435e-03 , 4.897242e-02 , -2.021002e-02 , 2.195976e-01 , 7.623157e-05 , ],
  [ 1.866799e-02 , 8.478703e-03 , -2.295807e-03 , 7.779090e-03 , 7.623157e-05 , 5.354048e-02 , ],
  ])
  # Stuff works better if we pretend that there are less correlations ...
  R.A[...] *= (0.5 + 0.5 *np.identity(6) )
  
  h = np.matrix([
      [ 1. , 0. ],
  ])        
  H = mt.zeros((6,12))
  for k in xrange(6):
    H[k::6,k::6] = h

  # Consider varying time delta, so system matrices change from step to step.
  def computeA(k):
Esempio n. 25
0
 def __init__(self, hyp):
     self.mean = hyp['mean']
     self.cov = np.exp(hyp['cov'][:-1])
     self.covd = np.asmatrix(np.diagflat(1/self.cov))
     self.sf2 = np.exp(2*hyp['cov'][-1])
     self.lik = hyp['lik']
Esempio n. 26
0
import numpy.matlib as np
print(np.matrix('1,2;3,4'))
print(np.asmatrix('1,2;3,4'))
Esempio n. 27
0
n = np.array(range(L))  # Дискретное нормированное время
plt.subplot(1, 1, 1)
plt.gcf().canvas.set_window_title('Discrete Triangular Impulse')
plt.title('Discrete Triangular Impulse x4(n)')
plt.stem(n, x4)
plt.xlabel('n')
plt.show()

print('\n----------------------------------------')
print('п8. Линейная комбинация дискретных гармонических сигналов')
input(
    'Для вывода ГРАФИКОВ гармонических сигналов и их линейной комбинации нажмите <ENTER>'
)
n = np.array(range(5 * N - 1))
xi = np.multiply(matlib.repmat(B, len(n), 1),
                 np.sin(matlib.asmatrix(n).transpose() * w))
ai = matlib.repmat(A, len(n), 1)
x5 = np.sum(np.multiply(ai, xi), axis=1)
plt.subplot(4, 1, 1)
plt.gcf().canvas.set_window_title(
    'Discrete Harmonic Signals and their Linear Combination')
plt.stem(n, xi[:, 0])
plt.title('First Discrete Harmonic Signal')
plt.subplot(4, 1, 2)
plt.stem(n, xi[:, 1])
plt.title('Second Discrete Harmonic Signal')
plt.subplot(4, 1, 3)
plt.stem(n, xi[:, 2])
plt.title('Third Discrete Harmonic Signal')
plt.subplot(4, 1, 4)
plt.title('Linear Combination x5(n)')
Esempio n. 28
0
def Vect(l):
    """
        Creates a vector, represented by a matrix column
    """
    return npmat.asmatrix(l).reshape((-1, 1))