コード例 #1
0
ファイル: routines.py プロジェクト: x75/mdp-toolkit
def symrand(dim_or_eigv, dtype="d"):
    """Return a random symmetric (Hermitian) matrix.

    If 'dim_or_eigv' is an integer N, return a NxN matrix, with eigenvalues
        uniformly distributed on (-1,1).

    If 'dim_or_eigv' is  1-D real array 'a', return a matrix whose
                      eigenvalues are 'a'.
    """
    if isinstance(dim_or_eigv, int):
        dim = dim_or_eigv
        d = (numx_rand.random(dim) * 2) - 1
    elif isinstance(dim_or_eigv, numx.ndarray) and len(dim_or_eigv.shape) == 1:
        dim = dim_or_eigv.shape[0]
        d = dim_or_eigv
    else:
        raise mdp.MDPException("input type not supported.")

    v = random_rot(dim)
    #h = mdp.utils.mult(mdp.utils.mult(hermitian(v), mdp.numx.diag(d)), v)
    h = mdp.utils.mult(mult_diag(d, hermitian(v), left=False), v)
    # to avoid roundoff errors, symmetrize the matrix (again)
    h = 0.5 * (h.T + h)
    if dtype in ('D', 'F', 'G'):
        h2 = symrand(dim_or_eigv)
        h = h + 1j * (numx.triu(h2) - numx.tril(h2))
    return refcast(h, dtype)
コード例 #2
0
    def pseudo_inverse(self, x, use_hint=None):
        """Calculate a pseudo inverse of the expansion using
        scipy.optimize.
        
        This method requires scipy.
        
        :param x: The data.
        :type x: numpy.ndarray
        
        :param use_hint: When calculating a pseudo inverse of the expansion,
            the hint determines the starting point for the approximation.
            For details on this parameter see the function 
            ``invert_exp_funcs2`` in ``mdp.utils.routines.py``.
        :type use_hint: numpy.ndarray or bool
        
        :return: The pseudo inverse.
        :rtype: numpy.ndarray
        """

        try:
            app_x_2, app_ex_x_2 = invert_exp_funcs2(x,
                                                    self.input_dim,
                                                    self.funcs,
                                                    use_hint=use_hint,
                                                    k=0.000001)
            return app_x_2.astype(self.dtype)
        except NotImplementedError as exc:
            raise mdp.MDPException(exc)
コード例 #3
0
ファイル: signal_node.py プロジェクト: yarikoptic/afni
 def __init__(self, *args, **kwargs):
     super(Cumulator, self).__init__(*args, **kwargs)
     self._cumulator_fields = fields
     for arg in self._cumulator_fields:
         if hasattr(self, arg):
             errstr = "Cumulator Error: Property %s already defined"
             raise mdp.MDPException(errstr % arg)
         setattr(self, arg, [])
     self.tlen = 0
コード例 #4
0
 def _init_internals(self, x, y):
     if self._dtype is None:
         self._dtype = x.dtype
         if y.dtype != x.dtype:
             err = 'dtype mismatch: x (%s) != y (%s)' % (x.dtype, y.dtype)
             raise mdp.MDPException(err)
     dim_x = x.shape[1]
     dim_y = y.shape[1]
     type_ = self._dtype
     self._cov_mtx = numx.zeros((dim_x, dim_y), type_)
     self._avgx = numx.zeros(dim_x, type_)
     self._avgy = numx.zeros(dim_y, type_)
コード例 #5
0
    def update(self, x, y):
        # check internal dimensions consistency
        if x.shape[0] != y.shape[0]:
            err = '# samples mismatch: x (%d) != y (%d)' % (x.shape[0],
                                                            y.shape[0])
            raise mdp.MDPException(err)

        if self._cov_mtx is None:
            self._init_internals(x, y)

        # cast input
        x = mdp.utils.refcast(x, self._dtype)
        y = mdp.utils.refcast(y, self._dtype)

        self._cov_mtx += mdp.utils.mult(x.T, y)
        self._avgx += x.sum(axis=0)
        self._avgy += y.sum(axis=0)
        self._tlen += x.shape[0]
コード例 #6
0
    def pseudo_inverse(self, x, use_hint=None):
        """Calculate a pseudo inverse of the expansion using
        scipy.optimize.

        ``use_hint``
               when calculating the pseudo inverse of the expansion,
               the hint determines the starting point for the approximation

        This method requires scipy."""

        try:
            app_x_2, app_ex_x_2 = invert_exp_funcs2(x,
                                                    self.input_dim,
                                                    self.funcs,
                                                    use_hint=use_hint,
                                                    k=0.001)
            return app_x_2.astype(self.dtype)
        except NotImplementedError, exc:
            raise mdp.MDPException(exc)
コード例 #7
0
    def update(self, x):
        """Update internal structures."""
        if self._cov_mtx is None:
            self._init_internals(x)

        # cast input
        x = mdp.utils.refcast(x, self._dtype)

        dt = self._dt

        # the number of data points in each block should be at least dt+1
        tlen = x.shape[0]
        if tlen < (dt + 1):
            err = 'Block length is %d, should be at least %d.' % (tlen, dt + 1)
            raise mdp.MDPException(err)

        # update the covariance matrix, the average and the number of
        # observations (try to do everything inplace)
        self._cov_mtx += mdp.utils.mult(x[:tlen - dt, :].T, x[dt:tlen, :])
        totalsum = x.sum(axis=0)
        self._avg += totalsum - x[tlen - dt:, :].sum(axis=0)
        self._avg_dt += totalsum - x[:dt, :].sum(axis=0)
        self._tlen += tlen - dt