Given an N x M matrix, returns mean and std computed on the rows,
    i.e. two M-dimensional vectors.
960004
def mean_std(fractions):
    
    n = fractions.shape[0]
    if n == 1:  # avoid warnings when computing the stddev
        return fractions[0], numpy.ones_like(fractions[0]) * numpy.nan
    return numpy.mean(fractions, axis=0), numpy.std(fractions, axis=0, ddof=1)
1166659
def gausspars(data):
    
    N, mean, d = len(data), 0., 0.
    if N < 1:
        return "", ""
    if N == 1:
        return data[0], 0
    for j in range(N):
        mean += old_div(data[j], float(N))
    for j in range(N):
        d += (data[j] - mean)**2
    stdev = np.sqrt(d * (1./(float(N - 1))))
    return mean, stdev
61491
function mmult(A, B, n) {
  var C = new Array(n * n);

  for (var i = 0; i < n; i++) {
    for (var j = 0; j < n; j++) {
      C[i * n + j] = 0;
    }

    for (var k = 0; k < n; k++) {
      for (var _j = 0; _j < n; _j++) {
        C[i * n + _j] += A[i * n + k] * B[k * n + _j];
      }
    }
  }

  return C;
}
562076
private static int getDataRows(Chunk[] chunks, Frame f, int[] chunksIds, int cols) {
        double totalRows = 0;
        if(null != chunks) {
            for (Chunk ch : chunks) {
                totalRows += ch.len();
            }
        } else {
            for(int chunkId : chunksIds) {
                totalRows += f.anyVec().chunkLen(chunkId);
            }
        }
        return (int) Math.ceil(totalRows * cols / SPARSE_MATRIX_DIM);
    }
64226
public static void doubleCenterMatrix(double[] dMatrix, int size) {
    double[] rowMean = new double[size];
    // row sum
    for(int i = 0, c = 0; i < size; i++) {
      for(int j = 0; j < i; j++) {
        double v = dMatrix[c++];
        rowMean[i] += v;
        rowMean[j] += v;
      }
      assert (dMatrix[c] == 0.);
      c++; // Diagonal entry. Must be zero!
    }
    // Normalize averages:
    double matrixMean = 0.;
    for(int i = 0; i < size; i++) {
      matrixMean += rowMean[i];
      rowMean[i] /= size;
    }
    matrixMean /= size * size;

    for(int o = 0, c = 0; o < size; o++) {
      // Including row mean!
      for(int p = 0; p <= o; p++) {
        dMatrix[c++] -= rowMean[o] + rowMean[p] - matrixMean;
      }
    }
  }
873291
def compute_rmsd_by_matrix(dataframe_1, dataframe_2, use_assertion = False):
    ''' '''
    if use_assertion: assert([i for i in dataframe_1.index] == [i for i in dataframe_2.index]) # Note: this assertion creates garbage memory allocations
    num_points = dataframe_1.shape[0]
    return numpy.linalg.norm(dataframe_1 - dataframe_2) / numpy.sqrt(num_points)
549272
def get_mean_and_stddevs(self, sctx, rctx, dctx, imt, stddev_types):
        
        # Get original mean and standard deviations
        mean, stddevs = super().get_mean_and_stddevs(
            sctx, rctx, dctx, imt, stddev_types)
        cff = SInterCan15Mid.SITE_COEFFS[imt]
        mean += np.log(cff['mf'])
        return mean, stddevs
762433
def stdev(x):
    
    """
    from math import sqrt
    n = len(x)
    mean = sum(x) / float(n)
    std = sqrt(sum((a - mean)**2 for a in x) / float(n - 1))
    return std
274869
def M(self, t, tips=None, gaps=None):
        """"""
        assert isinstance(t, float) and t > 0, "Invalid t: {0}".format(t)
        with scipy.errstate(under='ignore'): # don't worry if some values 0
            if ('expD', t) not in self._cached:
                self._cached[('expD', t)] = scipy.exp(self.D * self.mu * t)
            expD = self._cached[('expD', t)]
            # swap axes to broadcast multiply D as diagonal matrix
            temp = scipy.ascontiguousarray((self.A.swapaxes(0, 1)
                    * expD).swapaxes(1, 0), dtype=float)
            M = broadcastMatrixMultiply(temp, self.Ainv)
            assert M.min() > -1e-3, "Overly negative M: {0}".format(M.min())
            M[M < 0] = 0.0
            if tips is None:
                return scipy.tile(M, (self.nsites, 1, 1))
            else:
                newM = scipy.zeros((len(tips), N_CODON))
                for i in range(len(tips)):
                    newM[i] =(M[0][:,tips[i]])
                if gaps is not None:
                    newM[gaps] = scipy.ones(N_CODON, dtype='float')
                return newM
1272959
def Mean(a, axis, keep_dims):
    
    return np.mean(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),
                   keepdims=keep_dims),
610731
public static DMatrixRMaj[] span(int dimen, int numVectors , Random rand ) {
        if( dimen < numVectors )
            throw new IllegalArgumentException("The number of vectors must be less than or equal to the dimension");

        DMatrixRMaj u[] = new DMatrixRMaj[numVectors];

        u[0] = RandomMatrices_DDRM.rectangle(dimen,1,-1,1,rand);
        NormOps_DDRM.normalizeF(u[0]);

        for( int i = 1; i < numVectors; i++ ) {
//            System.out.println(" i = "+i);
            DMatrixRMaj a = new DMatrixRMaj(dimen,1);
            DMatrixRMaj r=null;

            for( int j = 0; j < i; j++ ) {
//                System.out.println("j = "+j);
                if( j == 0 )
                    r = RandomMatrices_DDRM.rectangle(dimen,1,-1,1,rand);

                // find a vector that is normal to vector j
                // u[i] = (1/2)*(r + Q[j]*r)
                a.set(r);
                VectorVectorMult_DDRM.householder(-2.0,u[j],r,a);
                CommonOps_DDRM.add(r,a,a);
                CommonOps_DDRM.scale(0.5,a);

//                UtilEjml.print(a);

                DMatrixRMaj t = a;
                a = r;
                r = t;

                // normalize it so it doesn't get too small
                double val = NormOps_DDRM.normF(r);
                if( val == 0 || Double.isNaN(val) || Double.isInfinite(val))
                    throw new RuntimeException("Failed sanity check");
                CommonOps_DDRM.divide(r,val);
            }

            u[i] = r;
        }

        return u;
    }
401939
public static DMatrixRMaj concatRowsMulti(DMatrixRMaj ...m ) {
        int rows = 0;
        int cols = 0;

        for (int i = 0; i < m.length; i++) {
            rows += m[i].numRows;
            cols = Math.max(cols,m[i].numCols);
        }
        DMatrixRMaj R = new DMatrixRMaj(rows,cols);

        int row = 0;
        for (int i = 0; i < m.length; i++) {
            insert(m[i],R,row,0);
            row += m[i].numRows;
        }

        return R;
    }
380648
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
        

        dists_mod = copy.deepcopy(dists)
        dists_mod.rrup[dists.rrup <= 5.] = 5.

        return super().get_mean_and_stddevs(
            sites, rup, dists_mod, imt, stddev_types)
1074001
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
        

        # get mean and std using the superclass
        mean, stddevs = super().get_mean_and_stddevs(
            sites, rup, dists, imt, stddev_types)

        # correction factor (see Atkinson and Boore, 2011; equation 5 at
        # page 1126 and nga08_gm_tmr.for line 508
        corr_fact = 10.0**(np.max([0, 3.888 - 0.674 * rup.mag]) -
                           (np.max([0, 2.933 - 0.510 * rup.mag]) *
                            np.log10(dists.rjb + 10.)))

        return np.log(np.exp(mean)*corr_fact), stddevs
1368059
def weighted_mean(data):
    
    W, N, mean, d = 0, len(data), 0, 0
    if N < 1:
        return "", ""
    if N == 1:
        return data[0][0], 0
    for x in data:
        W += x[1]  # sum of the weights
    for x in data:
        mean += old_div((float(x[1]) * float(x[0])), float(W))
    for x in data:
        d += (old_div(float(x[1]), float(W))) * (float(x[0]) - mean)**2
    stdev = np.sqrt(d * (old_div(1., (float(N - 1)))))
    return mean, stdev
446961
def within_n_std(df, n=3):
    
    means = df.mean()
    stds = df.std()
    inliers = (np.abs(df[means.index] - means) < n * stds)
    if not np.all(inliers):
        msg = generic.bad_locations(~inliers)
        raise AssertionError(msg)
    return df
1346678
def std_filter(array, n_std=2.0, return_index=False):
    
    if not isinstance(array, np.ndarray):
        array = np.array(array)
    mean, std = array.mean(), array.std()

    good_index = np.where(abs(array - mean) <= n_std * std)
    bad_index = np.where(abs(array - mean) > n_std * std)

    if return_index:
        return good_index[0], bad_index[0]
    else:
        return array[good_index], array[bad_index]