:nocov:
 Convert all vectors of type *:numeric* and not containing nils into an NMatrix.
513784
def to_nmatrix
      each_vector.select do |vector|
        vector.numeric? && !vector.include_values?(*Daru::MISSING_VALUES)
      end.map(&:to_a).transpose.to_nm
    end
1097014
def Cinv(self):
        """"""
        try:
            return np.linalg.inv(self.c)
        except np.linalg.linalg.LinAlgError:
            print('Warning: non-invertible noise covariance matrix c.')
            return np.eye(self.c.shape[0])
443264
def f_df_nc(self,x):
        '''
        
        '''
        x = np.atleast_2d(x)
        xx = self.context_manager._expand_vector(x)
        f_nocontext_xx , df_nocontext_xx = self.f_df(xx)
        df_nocontext_xx = df_nocontext_xx[:,np.array(self.context_manager.noncontext_index)]
        return f_nocontext_xx, df_nocontext_xx
719006
def normalize_vector(v):
    
    norm = np.linalg.norm(v)
    return v/norm if not norm == 0 else v
906773
def trim_sparse(M, n_std=3, s_min=None, s_max=None):
    

    try:
        from scipy.sparse import coo_matrix
    except ImportError as e:
        print(str(e))
        print("I am peforming dense normalization by default.")
        return trim_dense(M.todense())
    r = M.tocoo()
    sparsity = np.array(r.sum(axis=1)).flatten()
    mean = np.mean(sparsity)
    std = np.std(sparsity)
    if s_min is None:
        s_min = mean - n_std * std
    if s_max is None:
        s_max = mean + n_std * std
    f = (sparsity > s_min) * (sparsity < s_max)
    indices = [u for u in range(len(r.data)) if f[r.row[u]] and f[r.col[u]]]
    rows = np.array([r.row[i] for i in indices])
    cols = np.array([r.col[j] for j in indices])
    data = np.array([r.data[k] for k in indices])

    N = coo_matrix((data, (rows, cols)))
    return N
310428
def normalize_vector(vector):
    
    v = np.divide(vector, np.linalg.norm(vector))
    return np.round(v, decimals=4)
412239
function _Matrix(numRows, numColumns, data) {
  if(!Number.isInteger(numRows))
    throw new TypeError("/numRows/ must be an integer.");
  if(!Number.isInteger(numColumns))
      throw new TypeError("/numColumns/ must be an integer.");

  var _values;
  var _numValues = numRows * numColumns;
  if (!data || data === undefined)
    _values = [];
  else if (!util.isNumberArray(data))
    throw new TypeError('Invalid values for vector.');
  else
    _values = data;

  // Make sure the matrix has numRows * numColumns values
  if (_values.length < _numValues) {
    var zeros = Array(_numValues - _values.length).fill(0);
    _values = _values.concat(zeros);
  } else if (_values.length > _numValues) {
    _values = _values.slice(0, _numValues);
  }

  var size = {"rows": numRows, "columns": numColumns};
  readonly(this, "size", size);
  readonly(this, "values", _values);
  readonly(this, "rows", _getRows(this));
  readonly(this, "columns", _getColumns(this));
}
871849
public static RowMajorSparseMatrix fromCSV(String csv) {
        return Matrix.fromCSV(csv).to(Matrices.SPARSE_ROW_MAJOR);
    }
326048
def convertToRateMatrix(self, Q):
        
        rowSums             = Q.sum(axis=1).getA1()
        idxRange            = np.arange(Q.shape[0])
        Qdiag               = coo_matrix((rowSums,(idxRange,idxRange)),shape=Q.shape).tocsr()
        return Q-Qdiag
503565
def _reshape_n_vecs(self):
        """"""

        lst = []
        sl = slice(None, None, None)
        lst.append(self.__getitem__((sl, 0)))
        for m in xrange(1, self.mmax + 1):
            lst.append(self.__getitem__((sl, -m)))
            lst.append(self.__getitem__((sl, m)))
        return lst
68052
def toSparse(self):
        """"""
        if self.isTransposed:
            values = np.ravel(self.toArray(), order='F')
        else:
            values = self.values
        indices = np.nonzero(values)[0]
        colCounts = np.bincount(indices // self.numRows)
        colPtrs = np.cumsum(np.hstack(
            (0, colCounts, np.zeros(self.numCols - colCounts.size))))
        values = values[indices]
        rowIndices = indices % self.numRows

        return SparseMatrix(self.numRows, self.numCols, colPtrs, rowIndices, values)
1094467
def GetVectorAsNumpy(self, flags, off):
        
        offset = self.Vector(off)
        length = self.VectorLen(off) # TODO: length accounts for bytewidth, right?
        numpy_dtype = N.to_numpy_type(flags)
        return encode.GetVectorAsNumpy(numpy_dtype, self.Bytes, length, offset)
855483
def fromvector(cls, v):
        """"""
        w = v.normalized()
        return cls(w.x, w.y, w.z)
473706
def remapOpenCv(im, coords):
    
    # required for older OpenCV versions
    im = np.require(im, im.dtype, 'C')
    return cv2.remap(im, coords, None, cv2.INTER_LANCZOS4)
399161
def get_vectors(self, indices=None):
        ''''''
        H_ = self._deflated_solver.H
        (n_, n) = H_.shape
        coeffs = self.coeffs if indices is None else self.coeffs[:, indices]
        return numpy.c_[self._deflated_solver.V[:, :n],
                        self._deflated_solver.projection.U].dot(coeffs)
1160604
def _unvec(vecA, m=None):
    """"""
    N = vecA.shape[0]
    if m is None:
        m = np.sqrt(vecA.shape[1] + 0.25).astype(np.int64)
    return vecA.reshape((N, m, -1), order='F')
735538
def to_vector(np_array):
    
    if len(np_array.shape) == 1:
        return Vectors.dense(np_array)
    else:
        raise Exception("An MLLib Vector can only be created from a one-dimensional " +
                        "numpy array, got {}".format(len(np_array.shape)))