m._compute_ambig_ll() -- Extend log-likelihood matrix to include ambiguity codes
                                 e.g.  What the score of a 'S'?  Here we use the max of C and G.
166558
def _compute_ambig_ll(self):
        
        for Dll in self.ll:
            for L in one2two.keys():
                Dll[L] = max(Dll[one2two[L][0]],  Dll[one2two[L][1]] )
            Dll['N'] = 0.0
            Dll['B'] = 0.0
469883
def leastsq_generalized(x, y, x2, y2, res_std=None, res2_std=None, fit_offset=False, fit_offset2=False, perc=None):
    
    if perc is not None:
        if not fit_offset and isinstance(perc, (list, tuple)): perc = perc[1]
        weights = csr_matrix(get_weight(x, y, perc)).astype(bool)
        x, y = weights.multiply(x).tocsr(), weights.multiply(y).tocsr()

    n_obs, n_var = x.shape
    offset, offset_ss = np.zeros(n_var, dtype="float32"), np.zeros(n_var, dtype="float32")
    gamma = np.ones(n_var, dtype="float32")

    if (res_std is None) or (res2_std is None): res_std, res2_std = np.ones(n_var), np.ones(n_var)
    ones, zeros = np.ones(n_obs), np.zeros(n_obs)

    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        x, y = np.vstack((make_dense(x)/res_std, x2/res2_std)), np.vstack((make_dense(y)/res_std, y2/res2_std))

    if fit_offset and fit_offset2:
        for i in range(n_var):
            A = np.c_[np.vstack((np.c_[ones/res_std[i], zeros], np.c_[zeros, ones/res2_std[i]])), x[:, i]]
            offset[i], offset_ss[i], gamma[i] = np.linalg.pinv(A.T.dot(A)).dot(A.T.dot(y[:, i]))
    elif fit_offset:
        for i in range(n_var):
            A = np.c_[np.hstack((ones/res_std[i], zeros)), x[:, i]]
            offset[i], gamma[i] = np.linalg.pinv(A.T.dot(A)).dot(A.T.dot(y[:, i]))
    elif fit_offset2:
        for i in range(n_var):
            A = np.c_[np.hstack((zeros, ones/res2_std[i])), x[:, i]]
            offset_ss[i], gamma[i] = np.linalg.pinv(A.T.dot(A)).dot(A.T.dot(y[:, i]))
    else:
        for i in range(n_var):
            A = np.c_[x[:, i]]
            gamma[i] = np.linalg.pinv(A.T.dot(A)).dot(A.T.dot(y[:, i]))

    offset[np.isnan(offset)] = 0
    offset_ss[np.isnan(offset_ss)] = 0
    gamma[np.isnan(gamma)] = 0

    return offset, offset_ss, gamma
196731
function computeLcsMatrix(xs, ys) {
  var n = xs.size||0;
  var m = ys.size||0;
  var a = makeMatrix(n + 1, m + 1, 0);

  for (var i = 0; i < n; i++) {
    for (var j = 0; j < m; j++) {
      if (Immutable.is(xs.get(i), ys.get(j))) {
        a[i + 1][j + 1] = a[i][j] + 1;
      }
      else {
        a[i + 1][j + 1] = Math.max(a[i + 1][j], a[i][j + 1]);
      }
    }
  }

  return a;
}
703482
def log_likelihood_rankings(data, params):
    """"""
    loglik = 0
    params = np.asarray(params)
    for ranking in data:
        for i, winner in enumerate(ranking[:-1]):
            loglik -= logsumexp(params.take(ranking[i:]) - params[winner])
    return loglik
521521
def cublasSgbmv(handle, trans, m, n, kl, ku, alpha, A, lda,
                x, incx, beta, y, incy):
    

    status = _libcublas.cublasSgbmv_v2(handle,
                                       trans, m, n, kl, ku,
                                       ctypes.byref(ctypes.c_float(alpha)),
                                       int(A), lda,
                                       int(x), incx,
                                       ctypes.byref(ctypes.c_float(beta)),
                                       int(y), incy)
    cublasCheckStatus(status)
24661
def ambiguate(sequence1, sequence2, delete_ambiguous=False):
    
    delete = False
    combination = list()
    z = list(zip(sequence1, sequence2))
    for (a, b) in z:
        if a == b:
            combination.append(a)
        else:
            if a == '-' or b == '-':
                combination.append('-')
            else:
                if delete_ambiguous:
                    delete = True
                ambig = get_ambiguity(a, b)
                combination.append(ambig)
    if delete:
        return 'X' * len(combination)
    return ''.join(combination)
486388
def tnr(y_true, y_pred, round=True):
    
    y_true, y_pred = _mask_value_nan(y_true, y_pred)
    if round:
        y_true = np.round(y_true)
        y_pred = np.round(y_pred)
    c = skm.confusion_matrix(y_true, y_pred)
    return c[0, 0] / c[0].sum()
938380
private boolean checkMax(T image, double adj, double bestScore, int c_x, int c_y) {
		sparseLaplace.setImage(image);
		boolean isMax = true;
		beginLoop:
		for (int i = c_y - 1; i <= c_y + 1; i++) {
			for (int j = c_x - 1; j <= c_x + 1; j++) {
				double value = adj*sparseLaplace.compute(j, i);
				if (value >= bestScore) {
					isMax = false;
					break beginLoop;
				}
			}
		}
		return isMax;
	}
190907
def expected_log_likelihood(self, mus, sigmas, y):
        

        # Flatten the covariance
        T = mus.shape[0]
        D = self.D_in
        sigs_vec = sigmas.reshape((T, D ** 2))

        # Compute the log likelihood of each column
        ll = np.zeros((T, self.D_out))
        for n in range(self.D_out):

            an = self.A[n]

            E_loglmbda = np.dot(mus, an)
            ll[:,n] += y[:,n] * E_loglmbda

            # Vectorized log likelihood calculation
            aa_vec = np.outer(an, an).reshape((D ** 2,))
            ll[:,n] = -np.exp(E_loglmbda + 0.5 * np.dot(sigs_vec, aa_vec))

        return ll
366540
def loss_ratio_exceedance_matrix(self, loss_ratios):
        
        # LREM has number of rows equal to the number of loss ratios
        # and number of columns equal to the number of imls
        lrem = numpy.empty((len(loss_ratios), len(self.imls)))
        for row, loss_ratio in enumerate(loss_ratios):
            for col, (mean_loss_ratio, stddev) in enumerate(
                    zip(self.mean_loss_ratios, self.stddevs)):
                lrem[row, col] = self.distribution.survival(
                    loss_ratio, mean_loss_ratio, stddev)
        return lrem
423540
function hm(n, v, incv, offv, tau, b, offb) {
    // Apply householder transformation b = b - tau v v' b
    // LAPACK: DLARF

    if (tau === 0.0) {
      return;
    }

    // compute v' b
    var d = b[offb + 0];
    for (var i = 1; i < n; ++i) {
      d += b[offb + i] * v[offv + incv*i];
    }

    // compute b = b - tau v v' b
    b[offb + 0] -= tau * d;
    for (var i = 1; i < n; ++i) {
      b[offb + i] -= tau * v[offv + incv*i] * d;
    }
  }
361202
def np_lst_sq(vecMdl, aryFuncChnk):
    
    aryTmpBts, vecTmpRes = np.linalg.lstsq(vecMdl,
                                           aryFuncChnk,
                                           rcond=-1)[:2]

    return aryTmpBts, vecTmpRes
397700
def likelihood(self, x, cl):
        

        # sha = x.shape
        # xr = x.reshape(-1, sha[-1])
        # outsha = sha[:-1]
        # from PyQt4.QtCore import pyqtRemoveInputHook
        # pyqtRemoveInputHook()
        logger.debug("likel " + str(x.shape))
        if self.modelparams["type"] == "gmmsame":

            px = self.mdl[cl].score_samples(x)

        # todo ošetřit více dimenzionální fv
        # px = px.reshape(outsha)
        elif self.modelparams["type"] == "kernel":
            px = self.mdl[cl].score_samples(x)
        elif self.modelparams["type"] == "gaussian_kde":
            # print x
            # np.log because it is likelihood
            # @TODO Zde je patrně problém s reshape
            # old
            # px = np.log(self.mdl[cl](x.reshape(-1)))
            # new
            px = np.log(self.mdl[cl](x))
            # px = px.reshape(outsha)
            # from PyQt4.QtCore import pyqtRemoveInputHook
            # pyqtRemoveInputHook()
        elif self.modelparams["type"] == "dpgmm":
            # todo here is a hack
            # dpgmm z nějakého důvodu nefunguje pro naše data
            # vždy natrénuje jednu složku v blízkosti nuly
            # patrně to bude mít něco společného s parametrem alpha
            # přenásobí-li se to malým číslem, zázračně to chodí
            logger.warning(".score() replaced with .score_samples() . Check it.")
            # px = self.mdl[cl].score(x * 0.01)
            px = self.mdl[cl].score_samples(x * 0.01)
        elif self.modelparams["type"] == "stored":
            px = self.mdl[cl].score(x)
        return px
899587
def Imm(extended_map, s, lmax):
    
    import numpy as np
    extended_map = np.ascontiguousarray(extended_map, dtype=np.complex128)
    NImm = (2*lmax + 1)**2
    imm = np.empty(NImm, dtype=np.complex128)
    _Imm(extended_map, imm, s, lmax)
    return imm
196109
private static long SBOG_LPSti64(Int512 t, int i) {
        return (StreebogTables.sbob_sl64[0][t.getByte(i) & 0xFF] ^
                StreebogTables.sbob_sl64[1][t.getByte(i + 8) & 0xFF] ^
                StreebogTables.sbob_sl64[2][t.getByte(i + 16) & 0xFF] ^
                StreebogTables.sbob_sl64[3][t.getByte(i + 24) & 0xFF] ^
                StreebogTables.sbob_sl64[4][t.getByte(i + 32) & 0xFF] ^
                StreebogTables.sbob_sl64[5][t.getByte(i + 40) & 0xFF] ^
                StreebogTables.sbob_sl64[6][t.getByte(i + 48) & 0xFF] ^
                StreebogTables.sbob_sl64[7][t.getByte(i + 56) & 0xFF]);
    }
792605
def mean_squared_logarithmic_error(pred:Tensor, targ:Tensor)->Rank0Tensor:
    ""
    pred,targ = flatten_check(pred,targ)
    return F.mse_loss(torch.log(1 + pred), torch.log(1 + targ))
1195638
def logsumexp(x):
    """"""
    max_x = np.max(x)
    return max_x + np.log(np.sum(np.exp(x - max_x)))