fit to normal distribution
969134
def norm(table):
    
    print('# norm dist is broken', file=sys.stderr)
    exit()
    from matplotlib.pyplot import hist as hist
    t = []
    for i in table:
        t.append(np.ndarray.tolist(hist(i, bins = len(i), normed = True)[0]))
    return t
473566
def cumulative_distribution(self, X):
        
        self.check_fit()

        U, V = self.split_matrix(X)

        num = np.multiply(
            np.exp(np.multiply(-self.theta, U)) - 1,
            np.exp(np.multiply(-self.theta, V)) - 1
        )
        den = np.exp(-self.theta) - 1

        return -1.0 / self.theta * np.log(1 + num / den)
1161678
def fit(self, X, y=None):
        
        self.transmat, self.genmat, self.transcount, self.statetime = ctmc(
            X, self.numstates, self.transintv, self.toltime, self.debug)
        return self
1032995
def fit_mle(self, data, k_array=np.arange(0.1, 100, 0.1)):
        
        # todo: check and mention in docstring biases of mle for k_agg
        data = np.array(data)
        mu = np.mean(data)
        return mu, _solve_k_from_mu(data, k_array, nbinom_nll, mu)
950122
def fit_null(Y,S_XX,U_XX,nfile,F):
    
    mtSet = limix.MTSet(Y, S_R=S_XX, U_R=U_XX, F=F)

    RV = mtSet.fitNull(cache=False)
    params = np.array([RV['params0_g'],RV['params0_n']])
    np.savetxt(nfile+'.p0',params)
    np.savetxt(nfile+'.nll0',RV['NLL0'])
    np.savetxt(nfile+'.cg0',RV['Cg'])
    np.savetxt(nfile+'.cn0',RV['Cn'])
181984
def fit_gaussian(x, y, yerr, p0):
    
    try:
        popt, pcov = curve_fit(gaussian, x, y, sigma=yerr, p0=p0, absolute_sigma=True)
    except RuntimeError:
        return [0],[0]
    return popt, pcov
317610
def fit(self, X, y,
            sample_weight=None, init_score=None,
            eval_set=None, eval_names=None, eval_sample_weight=None,
            eval_init_score=None, eval_metric=None, early_stopping_rounds=None,
            verbose=True, feature_name='auto', categorical_feature='auto', callbacks=None):
        """"""
        super(LGBMRegressor, self).fit(X, y, sample_weight=sample_weight,
                                       init_score=init_score, eval_set=eval_set,
                                       eval_names=eval_names,
                                       eval_sample_weight=eval_sample_weight,
                                       eval_init_score=eval_init_score,
                                       eval_metric=eval_metric,
                                       early_stopping_rounds=early_stopping_rounds,
                                       verbose=verbose, feature_name=feature_name,
                                       categorical_feature=categorical_feature,
                                       callbacks=callbacks)
        return self
401343
def Fit(self, zxq):
        
        z, trans, Q = zip(*zxq)

        assert len(trans) == len(z)
        ndf = len(z) - 3

        z = np.array(z)
        trans = np.array(trans)

        def dbexpl(t, p):
            return(p[0] - p[1] * t + p[2] * t ** 2)

        def residuals(p, data, t):
            err = data - dbexpl(t, p)
            return err

        doc = {}

        try:
            assert ndf > 0

            p0 = [1, 0, 0]  # initial guesses
            pbest = leastsq(residuals, p0, args=(trans, z), full_output=1)
            bestparams = pbest[0]
            good_of_fit = sum(pbest[2]['fvec'] ** 2)
            good_of_fit = float(good_of_fit / ndf)
            doc['params'] = list(bestparams)
            doc['gof'] = good_of_fit
        except:
            doc['gof'] = 'FAIL'
            doc['params'] = [0, 0, 0]

        return doc
920503
def _fit(self, index, width, height):
        """"""
        node = self._atlas_nodes[index]
        x, y = node[0], node[1]
        width_left = width
        if x+width > self._shape[1]:
            return -1
        i = index
        while width_left > 0:
            node = self._atlas_nodes[i]
            y = max(y, node[1])
            if y+height > self._shape[0]:
                return -1
            width_left -= node[2]
            i += 1
        return y
1209321
def fit(self, X, y, **fit_params):
        
        # pylint: disable=useless-super-delegation
        # this is actually a pylint bug:
        # https://github.com/PyCQA/pylint/issues/1085
        return super().fit(X, y, **fit_params)
134492
def fit(self, data=None):
        
        if self.is_pyclustering_instance(self.model):
            if isinstance(self.model, xmeans):
                data = self.input_preprocess(data)
                self.model._xmeans__pointer_data = data
            elif isinstance(self.model, clarans):
                data = self.input_preprocess(data)
                self.model._clarans__pointer_data = data

            self.model.process()
        else:
            self.model.fit(data)
            return self
1201929
def apply_fit(xy,coeffs):
    
    x_new = coeffs[0][2] + coeffs[0][0]*xy[:,0] + coeffs[0][1]*xy[:,1]
    y_new = coeffs[1][2] + coeffs[1][0]*xy[:,0] + coeffs[1][1]*xy[:,1]

    return x_new,y_new
710489
def fit_predict(self,
                    X,
                    num_epochs=10,
                    updates_epoch=10,
                    stop_param_updates=dict(),
                    batch_size=1,
                    show_progressbar=False):
        """"""
        self.fit(X,
                 num_epochs,
                 updates_epoch,
                 stop_param_updates,
                 batch_size,
                 show_progressbar)

        return self.predict(X, batch_size=batch_size)
76415
def zip_fit_params(data):
    
    genes, cells = data.shape
    m = data.mean(1)
    v = data.var(1)
    M = (v-m)/(m**2+v-m)
    #M = v/(v+m**2)
    #M[np.isnan(M)] = 0.0
    M = np.array([min(1.0, max(0.0, x)) for x in M])
    L = m + v/m - 1.0
    #L = (v + m**2)/m
    L[np.isnan(L)] = 0.0
    L = np.array([max(0.0, x) for x in L])
    return L, M
1000503
def plot_normal(x=None, mean_x=None,std_x=None,color='red',linewidth=2,alpha=1,bins=20,xlim=False,plot_mean=True,plot_std=False,plot_2std=True,figure=None,annotate=True,histogram=True):
    
    import pylab
    if figure is None:
        figure=pylab.figure()
    if mean_x is None:
        #fit maximum likelihood Normal distribution mean to samples X
        mean_x = x.mean() #sample mean
    if std_x is None:
        #fit maximum likelihood Normal distribution standard deviation to samples X
        std_x = x.std()   #sample standard deviation

    xvals=np.arange(mean_x-5*std_x,mean_x+5*std_x,.001)
    yvals=st.norm.pdf(xvals,mean_x,std_x)
    #plot normal distribution:
    ax = pylab.plot(xvals,yvals,color=color,linewidth=linewidth,alpha=alpha)
    if x is not None and histogram:
        #plot histogram of x-values
        pylab.hist(x,bins,normed=True)

    if plot_mean:
        #evaluate distribution at the mean:
        max_cdf=st.norm.pdf(mean_x,mean_x,std_x)
        pylab.plot([mean_x,mean_x],[0,max_cdf],color=color,linewidth=linewidth,alpha=alpha,linestyle="--")
        if annotate:
            pylab.annotate('$\mu$', xy=(mean_x+0.6*std_x, 1.0*max_cdf),
                horizontalalignment='center', verticalalignment='center',fontsize=15,color=color)
    if plot_std:#plot mean +- 1*standard deviation (64% interval)
        std_cdf=st.norm.pdf(mean_x+std_x,mean_x,std_x)
        pylab.plot([mean_x+std_x,mean_x+std_x],[0,std_cdf],color=color,linewidth=linewidth,alpha=alpha,linestyle="--")
        pylab.plot([mean_x-std_x,mean_x-std_x],[0,std_cdf],color=color,linewidth=linewidth,alpha=alpha,linestyle="--")
        if annotate:
            pylab.annotate('$\mu+\sigma$', xy=(mean_x+1.6*std_x, 1.5*std_cdf),
                horizontalalignment='center', verticalalignment='center',fontsize=15,color=color)
    if plot_2std:#plot mean +- 2*standard deviations (95% interval)
        std2_cdf=st.norm.pdf(mean_x+2*std_x,mean_x,std_x)
        pylab.plot([mean_x+2*std_x,mean_x+2*std_x],[0,std2_cdf],color=color,linewidth=linewidth,alpha=alpha,linestyle="--")
        pylab.plot([mean_x-2*std_x,mean_x-2*std_x],[0,std2_cdf],color=color,linewidth=linewidth,alpha=alpha,linestyle="--")
        if annotate:
            pylab.annotate('$\mu+2\sigma$', xy=(mean_x+2.6*std_x, 1.5*std2_cdf),
                horizontalalignment='center', verticalalignment='center',fontsize=15,color=color)
    if xlim: #cut of unused space on y-axis
        pylab.xlim([mean_x-4*std_x,mean_x+4*std_x])
    return figure
571195
def fit_mle(self, data, fix_mean=False):
        

        if not fix_mean:
            sigma, _, scale = stats.lognorm.fit(data, floc=0)
            return np.log(scale), sigma

        else:
            mean = np.mean(data)

            # MLE fxn to be optmimized
            mle = lambda sigma, x, mean: -1 *\
                                    np.sum(self._pdf_w_mean(x, mean, sigma))

            sigma = optim.fmin(mle, np.array([np.std(np.log(data), ddof=1)]),
                                            args=(data, mean), disp=0)[0]

            return self.translate_args(mean, sigma)
282312
def fit(self, obs, pstates, unique_pstates=None):
        
        obs = [np.array(o) for o in obs]
        pstates = [np.array(p) for p in pstates]

        # List or array of observation sequences
        assert len(obs) == len(pstates)
        assert obs[0].ndim == 2
        assert pstates[0].ndim == 1

        if unique_pstates is not None:
            self._init_pstates(unique_pstates)
        else:
            self._init_pstates(list(set(np.concatenate(pstates))))

        # Map the partial states to a unique index
        pstates_idx = [np.array([self.e[p] for p in seq]) for seq in pstates]

        if self.init_method == 'rand':
            self._init_random()
        elif self.init_method == 'obs':
            self._init_from_obs(obs, pstates_idx)

        self._init_pstate_freqs(pstates_idx)
        self._smooth()

        logprob = []
        for i in range(self.max_iter):
            # Expectation step
            stats = self._initialize_sufficient_statistics()
            curr_logprob = 0
            for obs_i, pstates_idx_i in zip(obs, pstates_idx):
                framelogprob = self._compute_log_likelihood(obs_i, pstates_idx_i)
                lpr, fwdlattice = self._do_forward_pass(framelogprob, pstates_idx_i)
                bwdlattice = self._do_backward_pass(framelogprob, pstates_idx_i)
                gamma = fwdlattice + bwdlattice
                posteriors = np.exp(gamma.T - logsumexp(gamma, axis=1)).T
                curr_logprob += lpr

                self._accumulate_sufficient_statistics(stats, obs_i,
                                                       pstates_idx_i, framelogprob, posteriors, fwdlattice, bwdlattice)

            logprob.append(curr_logprob)
            self.logprob_ = curr_logprob

            # Check for convergence.
            self.n_iter_performed_ = i
            if i > 0:
                self.logprob_delta = logprob[-1] - logprob[-2]
                if self.logprob_delta < self.thresh:
                    break

            # Maximization step
            self._do_mstep(stats)

            # Mix the parameters
            self._smooth()

        return self