コード例 #1
0
    def peak(cls, maxcps, datapoints, dwelltime, skew=0, sigma=3, location=0):
        location = 0
        scale = 1
        alpha = skew
        #         delta = alpha / np.sqrt(1+alpha**2)
        #         uz = np.sqrt(2/np.pi) * delta
        #         sigmaz = np.sqrt(1.0-uz**2.0)
        #         gamma = (4-np.pi)/2 * (delta*np.sqrt(2/np.pi))**3/(1-2*delta**2/np.pi)**(3/2)
        #         moa = uz - (gamma * sigmaz / 2) - (np.sign(alpha))*np.exp(-2*np.pi/np.abs(alpha))
        #         mode = location + scale * moa
        #         _norm_ = skewnorm.pdf(x=mode, a=alpha, loc=location, scale=scale) # 標準正規分布の高さ

        times = np.linspace(-sigma, sigma, datapoints)
        _refpeak_ = skewnorm.pdf(x=times, a=alpha, loc=0, scale=scale)
        # _refpeak_ = [skewnorm.pdf(x = time, a=alpha, loc=0, scale=scale) for time in times]
        _norm_ = np.max(_refpeak_)
        maxindex = np.argmax(_refpeak_)
        maxtime = times[maxindex]
        # refpeak = np.array(_refpeak_) * maxcps / _norm_
        # refpeak = np.array([skewnorm.pdf(x=time, a=alpha, loc= location - maxtime, scale=scale) * maxcps / _norm_ for time in times])
        #refpeak = np.array(skewnorm.pdf(x=times, a=alpha, loc= location - maxtime, scale=scale) * maxcps / _norm_ )
        refpeak = skewnorm.pdf(
            x=times, a=alpha, loc=location - maxtime,
            scale=scale) * maxcps / _norm_
        # print('maxindex:', maxindex)
        # print('maxpos:', maxtime)
        # samplepeak = np.array([np.random.poisson(peak * dwelltime / 1000) * 1000 / dwelltime for peak in refpeak])
        # return times, refpeak, samplepeak
        return refpeak
コード例 #2
0
def fig4(name, func, eps):
    """Makes figure 4.

    Args:
        name (str): Descriptive name of the model. Posterior samples, statistics, and
            figures are generated and saved in a subdirectory with this name.
        func (:obj:`<class 'function'>): Function for model construction. Should
            return a formatted copy of the data.
        eps (bool): If True, saves the figures to the manuscript subdirectory in .eps
            format.

    """

    with pm.Model() as m:

        fit_model(name, func)
        trace = pm.load_trace(name)
        params = sorted(
            [p.name for p in m.deterministics if "Lambda" in p.name])

    set_fig_defaults()
    rcParams["figure.figsize"] = (3, 3 * 2)
    fig, axes = plt.subplots(5, 1, constrained_layout=True)

    for p, ax in zip(params, axes):

        vals, bins, _ = ax.hist(trace[p],
                                bins=50,
                                density=True,
                                histtype="step",
                                color="lightgray")
        ax.set_xlabel(p)
        if ax == axes[0]:
            ax.set_ylabel("Posterior density")

        start, stop = pm.stats.hpd(trace[p])
        for n, l, r in zip(vals, bins, bins[1:]):

            if l > start:
                if r < stop:
                    ax.fill_between([l, r], 0, [n, n], color="lightgray")
                elif l < stop < r:
                    ax.fill_between([l, stop], 0, [n, n], color="lightgray")
            elif l < start < r:
                ax.fill_between([start, r], 0, [n, n], color="lightgray")

        x = np.linspace(min([bins[0], 0]), max([0, bins[-1]]))
        theta = skewnorm.fit(trace[p])
        ax.plot(x, skewnorm.pdf(x, *theta), "k", label="Normal approx.")
        ax.plot(x, norm.pdf(x), "k--", label="Prior")
        ax.plot([0, 0], [skewnorm.pdf(0, *theta), norm.pdf(0)], "ko")

    fig.savefig(f"{name}/fig4.png")

    if eps is True:
        fig.savefig("manuscript/fig4.eps")
コード例 #3
0
ファイル: test_maths.py プロジェクト: mcsloy/CITesting
def _random_skewed_norm(n):
    """Generate a random skewed normal distribution.

    This function will construct & return a specified number of skewed normal
    distributions using scipy's stats.skewnorm function.

    Arguments:
        n: Number of distributions to return.

    Returns:
        distributions: A nx100 array where each row is a separate distribution.

    """
    from scipy.stats import skewnorm

    # The range of the distributions
    x_values = np.linspace(-6.0, 6.0, 100)

    # Generate an array of `n` distributions
    distributions = np.array([
        skewnorm.pdf(
            # The x values
            x_values,
            # How much to skew the distribution by
            2.5 - (np.random.rand() * 5),
            # How much to scale the distribution by
            scale=np.random.rand() * 3) for _ in range(n)
    ])

    # Return the distributions
    return distributions
コード例 #4
0
    def gen_bets(self, total_dice, bet_history, last_bet=None, num_bets=30):
        if last_bet:
            bets = set()
            i = 0
            probs = skewnorm.pdf(range(last_bet.num_of_dice, total_dice + 1),
                                 5, .5, 4)
            probs = probs / sum(probs)
            dice_probs = [1 / 5 for _ in range(5)]
            for die in bet_history.keys():
                dice_probs[i - 2] += bet_history[die] / 100
            dice_probs = [x / sum(dice_probs) for x in dice_probs]
            while len(bets) != num_bets and i < 150:
                die_value = int(
                    np.random.choice(np.arange(2, 7), 1, p=dice_probs)[0])
                die_amount = int(
                    np.random.choice(np.arange(last_bet.num_of_dice,
                                               total_dice + 1),
                                     1,
                                     p=probs)[0])
                bet = Bet(die_value, die_amount)
                if bet.verify_bet(total_dice, last_bet, verbose=False):
                    bets.add(bet)

                i += 1

            return list(bets)

        return [Bet(x, y) for x in range(2, 7) for y in range(1, 4)]
コード例 #5
0
def compare_hist_to_norm_ax(x, data, bins=25):

    mu, std = scipy.stats.norm.fit(data)

    ax[x].hist(data,
               bins=bins,
               density=True,
               alpha=0.6,
               color='purple',
               label="Données")

    # Plot le PDF.
    xmin, xmax = plt.xlim()
    X = np.linspace(xmin, xmax)

    ax[x].plot(X,
               scipy.stats.norm.pdf(X, mu, std),
               label="Normal Distribution")
    ax[x].plot(X,
               skewnorm.pdf(X, *skewnorm.fit(data)),
               color='black',
               label="Skewed Normal Distribution")

    mu, std = scipy.stats.norm.fit(data)
    sk = scipy.stats.skew(data)

    title2 = "Moments mu: {}, sig: {}, sk: {}".format(round(mu, 4),
                                                      round(std, 4),
                                                      round(sk, 4))
    ax[x].ylabel("Fréquence", rotation=90)
    ax[x].title(title2)
    ax[x].legend()
    pass
コード例 #6
0
def loss_func(params, data_stimuli, data_response, Type=None):
    # Negative Log-likelihood function for directional tuning curves??

    return -np.log(
        np.prod(
            skewnorm.pdf(
                data_stimuli, a=params[0], loc=params[1], scale=params[2])))
コード例 #7
0
ファイル: NReval.py プロジェクト: 0rhisia0/ThesisCode
def skewnorm_eval(s1, s2, xi_popts, ome_popts, alp_popts):
    """
    skewnorm_eval
    Evaluates probability of S1 and S2 events
    inputs: mass of WIMP, number of events
    """
    xi = FUNC_EPS(s1, *xi_popts)
    omega = FUNC_OME(s1, *ome_popts)
    alpha = FUNC_ALP(s1, *alp_popts)
    return skewnorm.pdf(s2, alpha, loc=xi, scale=omega)
コード例 #8
0
def mixturemodel_skew(params, x):
    """Mixture of two skew normal distributions.
    
    Parameters
    ----------
    params : list or ndarray
        List of parameters (expect 2x3).
    x : float or ndarray
        Values to calculate the model.
    
    Returns
    -------
    model : float or ndarray
        Mixture model evaluated at x.
    """
    a, mua, sga, askew = params[:4]
    b, mub, sgb, bskew = params[4:]
    return a*skewnorm.pdf(x, askew, loc=mua, scale=sga) + \
           b*skewnorm.pdf(x, bskew, loc=mub, scale=sgb)
コード例 #9
0
 def get_sample_by_params(self, name: str, params: np.ndarray):
     fractions = params[-self.n_components:] / np.sum(params[-self.n_components:])
     distributions = np.array([skewnorm.pdf(self.classes_φ, *params[i*3:(i+1)*3]) * self.interval_φ for i in range(self.n_components)])
     mixed = (fractions.reshape((1, -1)) @ distributions).reshape((-1))
     mixed += np.random.random(mixed.shape) * 10 ** (-self.noise)
     mixed = np.round(mixed, self.precision)
     parameter = self.get_generate_parameter(params)
     sample = ArtificialSample(name, self.classes_μm, self.classes_φ,
                               mixed, distributions, fractions, parameter)
     return sample
コード例 #10
0
def get_samples_from_percentiles(val,
                                 ehi,
                                 elo,
                                 Nsamp=1e3,
                                 add_p5_p95=True,
                                 pltt=False):
    '''Given the 16, 50, and 84 percentiles of a parameter's distribution,
    fit a Skew normal CDF and sample it.'''
    # don't do anything if NaNs are input
    if np.any(np.isnan([val, ehi, elo])):
        return np.nan, np.nan, np.repeat(np.nan, int(Nsamp))

    # get percentiles
    p16, med, p84 = float(val - elo), float(val), float(val + ehi)
    assert p16 < med
    assert med < p84

    # add approximate percentiles to help with fitting the wings
    # otherwise the resulting fitting distritubions tend to
    if add_p5_p95:
        p5_approx = med - 2 * (med - p16)
        p95_approx = med + 2 * (p84 - med)
        xin = [p5_approx, p16, med, p84, p95_approx]
        yin = [.05, .16, .5, .84, .95]
    else:
        xin, yin = [p16, med, p84], [.16, .5, .84]

    # make initial parameter guess
    mu, sig = med, np.mean([abs(p16), abs(p84)])
    a = (abs(p16) - abs(p84)) / sig
    p0 = a, mu, sig
    popt, pcov = curve_fit(Skewnorm_CDF_func,
                           xin,
                           yin,
                           p0=p0,
                           sigma=np.repeat(.01, len(yin)),
                           absolute_sigma=False)

    # sample the fitted pdf
    samples = skewnorm.rvs(*popt, size=int(Nsamp))

    # plot distribution if desired
    if pltt:
        plt.hist(samples,
                 bins=30,
                 normed=True,
                 label='Sampled parameter posterior')
        plt.plot(np.sort(samples),
                 skewnorm.pdf(np.sort(samples), *popt),
                 '-',
                 label='Skew-normal fit: a=%.3f, m=%.3f, s=%.3f' % tuple(popt))
        plt.xlabel('Parameter values'), plt.legend(loc='upper right')
        plt.show()

    return p0, popt, samples
コード例 #11
0
def calculate_gradient(t_values, gradient_function, skew_norm_params,
                       n_classes):
    gradient_arguments = [
        skewnorm.pdf(t_values[i], *skew_norm_params[i][j])
        for i in range(n_classes) for j in range(n_classes)
    ]
    gradient_arguments += [
        skewnorm.cdf(t_values[i], *skew_norm_params[i][j])
        for i in range(n_classes) for j in range(n_classes)
    ]
    return np.array(gradient_function(*gradient_arguments))
コード例 #12
0
ファイル: distributions.py プロジェクト: yuriok/QGrain
 def interpret(parameters: np.ndarray, classes: np.ndarray, interval: float):
     n_samples, n_components, n_classes = classes.shape
     assert parameters.ndim == 3
     assert parameters.shape == (n_samples, SkewNormal.N_PARAMETERS + 1, n_components)
     shapes = np.expand_dims(parameters[:, 0, :], 2).repeat(n_classes, 2)
     locations = np.expand_dims(parameters[:, 1, :], 2).repeat(n_classes, 2)
     scales = np.expand_dims(relu(parameters[:, 2, :]), 2).repeat(n_classes, 2)
     proportions = np.expand_dims(softmax(parameters[:, 3, :], axis=1), 1)
     components = skewnorm.pdf(classes, shapes, loc=locations, scale=scales) * interval
     m, v, s, k = skewnorm.stats(shapes[:, :, 0], loc=locations[:, :, 0], scale=scales[:, :, 0], moments="mvsk")
     return proportions, components, (m, np.sqrt(v), s, k)
コード例 #13
0
 def _count_p_days(self, n, t, pdf='poisson'):
     if pdf == 'poisson':
         p_days = n * poisson.pmf(np.arange(self.n_days - self.day), mu=t)
     elif pdf == 'skewnorm':
         p_days = n * skewnorm.pdf(
             np.arange(self.n_days - self.day), a=5, loc=t, scale=15)
     elif pdf == 'lognorm':
         p_days = n * lognorm(np.arange(self.n_days - self.day))
     else:
         raise NotImplementedError(
             "Density function pdf='%s' not implemented!" % pdf)
     return np.pad(p_days, (self.day, 0), mode='constant')
コード例 #14
0
    def sensing_pdf(self,C,Q,z,x):
        if self.noisetype == 'multivariate_normal':
            k = len(z)
            e = z-np.matmul(C,x)
            p1 = np.power((2*np.pi),-k/2)*np.power(np.linalg.det(Q),-0.5)
            p2 = np.exp(-0.5*(e).T*np.linalg.inv(Q)*(e))
            e_ = e*(np.linalg.norm(e)-0.5)
            p2_ = np.exp(-0.5*(e_).T*np.linalg.inv(Q)*(e_))
            return float(p1*p2) + float(p1*p2_)

        if self.noisetype == 'skewnorm':
            e = z-np.matmul(C,x) + self.sensingNoiseMode
            return np.linalg.norm(skewnorm.pdf(e, self.Q[0], self.Q[1], self.Q[2]))
コード例 #15
0
def plot_hist(data, mu, std, smu, sstd, skew, title):
    """
    create a histogram plot panel
    input:  data    --- a list of data
            mu      --- estimated center location
            std     --- estimated width
            smu     --- estimated skewed center location
            sstd    --- estimated skewed width
            skew    --- estimated skewness
            title   --- the title of the plot
    output: a histogram plot panel (does not create a plot file)
    """
    #
    #--- plot histogram data
    #
    try:
        #
        #--- older format... if the starndard one does not work
        #
        plt.hist(data,
                 bins=20,
                 range=(-10, 10),
                 normed=True,
                 alpha=0.4,
                 color='green')
    except:
        plt.hist(data,
                 bins=20,
                 range=(-10, 10),
                 density=True,
                 alpha=0.4,
                 color='green')
#
#--- plot the normal/skewed normal fitting
#
    xmin, xmax = plt.xlim()
    xlist = numpy.linspace(xmin, xmax, 100)

    ylist = snorm.pdf(xlist, mu, std)
    plt.plot(xlist, ylist, color='blue', linewidth=2)

    ylist = skewnorm.pdf(xlist, skew, smu, sstd)
    plt.plot(xlist, ylist, color='red', linewidth=2)

    plt.title(title)
    ymin, ymax = plt.ylim()
    ydiff = ymax - ymin
    ypos1 = ymax - 0.1 * ydiff
    ypos2 = ymax - 0.2 * ydiff
    plt.text(-11, ypos1, 'normal', color='blue')
    plt.text(-11, ypos2, 'skewed', color='red')
コード例 #16
0
def predict_log_capacity(m, n, p, logX, params, raw=False):

    x = np.linspace(np.amin(logX), np.amax(logX), num=100)
    m_frac = float(m) / float(n)

    f = skewnorm.pdf(x, *get_interpolated_params(m_frac, p, params))
    f = f / np.sum(f)

    C = np.random.choice(x, p=f, size=(n, 100000))

    pred_raw = np.amin(C, axis=0)
    pred_mean = np.mean(pred_raw)

    return pred_raw if raw else pred_mean
コード例 #17
0
def simulate_PDF(median, lower_err, upper_err, size=1, plot=True):
    '''
    Simulates a draw of posterior samples from a value and asymmetric errorbars
    by assuming the underlying distribution is a skewed normal distribution.
    
    Developed to estimate PDFs from literature exoplanet parameters that did not report their MCMC chains.
    
    Inputs:
    -------
    median : float
        the median value that was reported
    lower_err : float
        the lower errorbar that was reported
    upper_err : float
        the upper errorbar that was reported
    size : int
        the number of samples to be drawn
        
    Returns:
    --------
    samples : array of float
        the samples drawn from the simulated skrewed normal distribution
    '''

    sigma, omega, alpha = calculate_skewed_normal_params(
        median, lower_err, upper_err)
    samples = skewnorm.rvs(alpha, loc=sigma, scale=omega, size=size)

    if plot == False:
        return samples

    else:
        lower_err = np.abs(lower_err)
        upper_err = np.abs(upper_err)
        x = np.arange(median - 4 * lower_err, median + 4 * upper_err, 0.01)
        fig = plt.figure()
        for i in range(3):
            plt.axvline([median - lower_err, median, median + upper_err][i],
                        color='k',
                        lw=2)
        plt.plot(x, skewnorm.pdf(x, alpha, loc=sigma, scale=omega), 'r-', lw=2)
        fit_percentiles = skewnorm.ppf([0.16, 0.5, 0.84],
                                       alpha,
                                       loc=sigma,
                                       scale=omega)
        for i in range(3):
            plt.axvline(fit_percentiles[i], color='r', ls='--', lw=2)
        plt.hist(samples, density=True, color='red', alpha=0.5)
        return samples, fig
コード例 #18
0
def plot_skew_norm_fit(ax,
                       data,
                       bins,
                       color='k',
                       linestyle='-',
                       linewidth=3,
                       label=None):
    s, loc, scale = skewnorm.fit(data)
    pdf = skewnorm.pdf(bins, s, scale=scale, loc=loc)
    ax.plot(bins,
            pdf,
            color=color,
            linestyle=linestyle,
            linewidth=linewidth,
            label=label)
コード例 #19
0
    def __init__(self,N,init_range,random_ratio,noisetype=None,R=None,Q=None):
        self.X = np.zeros((N,len(init_range)))
        self.W = np.ones(N)/N
        self.N = N
        self.random_ratio = random_ratio
        self.init_range = init_range
        self.noisetype = noisetype

        if noisetype == 'skewnorm':
            self.Q = Q
            s = np.linspace(skewnorm.ppf(0.01, Q[0], Q[1], Q[2]),skewnorm.ppf(0.99, Q[0], Q[1], Q[2]), 100)
            y = skewnorm.pdf(s, Q[0], Q[1], Q[2])
            self.sensingNoiseMode = s[np.argmax(y)]

        for i,random_range in enumerate(init_range):
            self.X[:,i] = np.random.uniform(random_range[0],random_range[1],N)
コード例 #20
0
def predict_log_capacity(m, n, p, logX, params, raw=False):

    m_frac = float(m) / float(n)

    a, loc, scale = get_interpolated_params(m_frac, p, params)
    x_min = loc - 5. * scale
    x_max = loc + 5. * scale
    x = np.linspace(x_min, x_max, num=100)

    f = skewnorm.pdf(x, a, loc, scale)
    f = f / np.sum(f)
    C = np.random.choice(x, p=f, size=(n, 100000))

    pred_raw = np.amin(C, axis=0)
    pred_mean = np.mean(pred_raw)

    return pred_raw if raw else pred_mean
コード例 #21
0
def main():
	symbol = 'BTCUSDT'
	start = int(datetime.datetime.timestamp(datetime.datetime(2019, 6, 1))) * 1000 - 365 * 24 * 60 * 60 * 1000
	previous = start
	trades = []
	total_trades = 0
	max_trades = 0
	time_step = 1
	with open('../Binance/' + symbol + '.csv', 'r') as csvfile:
		reader = csv.DictReader(csvfile)
		for line in reader:
			if int(line['Timestamp']) > previous + time_step * 60 * 60 * 1000:
				previous += time_step * 60 * 60 * 1000
				trades.append(total_trades)
				if max_trades < total_trades:
					max_trades = total_trades
				total_trades = 0
			total_trades += 1

	mean = np.mean(trades)
	print(mean)

	trades = [t for t in trades if t != 1]

	#mean, scale = norm.fit(np.log(trades))
	a, loc, scale = skewnorm.fit(np.log(trades))
	loc_n, scale_n = norm.fit(np.log(trades))

	k, loc_ne, scale_ne = exponnorm.fit(np.log(trades))

	plt.hist(np.log(trades), bins=100, density=True)
	x = np.linspace(6, 12, 100)
	plt.plot(x, skewnorm.pdf(x, a, loc=loc, scale=scale), label='skewnorm')
	plt.plot(x, norm.pdf(x, loc=loc_n, scale=scale_n), label='norm')
	plt.plot(x, exponnorm.pdf(x, k, loc=loc_n, scale=scale_n), label='Exponentially modified Gaussian')

	plt.xlabel('Log Trades')
	plt.ylabel('Density')

	plt.legend()

	#plt.plot([i for i in range(1, max_trades)], poisson_density(np.array([i for i in range(1, max_trades)]), mean))
	#plt.plot([i for i in range(0, max_trades)], norm.pdf([i for i in range(max_trades)], loc=mean, scale=np.sqrt(mean)))
	plt.savefig(symbol + ' log Trades')

	plt.show()
コード例 #22
0
ファイル: auxiliary.py プロジェクト: aimas-lund/ML-Report-01
def calc_distribution(y, type='norm', lower=0.01, upper=99.99, points=100):
    lo, up = get_percentiles(y, lower, upper)
    X = np.linspace(lo, up, points)

    if type == 'norm':
        p1, p2 = norm.fit(y)
        Y = norm.pdf(X, p1, p2)

        return X, Y

    elif type == 'skewed':
        p1, p2, p3 = skewnorm.fit(y)
        Y = skewnorm.pdf(X, p1, p2, p3)

        return X, Y

    else:
        raise AttributeError("'type' not recognized.")
コード例 #23
0
def table2(name, func, tex):
    """Makes table 2.

    Args:
        name (str): Descriptive name of the model. Posterior samples, statistics, and
            figures are generated and saved in a subdirectory with this name.
        func (:obj:`<class 'function'>): Function for model construction. Should
            return a formatted copy of the data.
        tex (bool): If True, saves the table to the manuscript subdirectory.

    """

    with pm.Model() as m:
        fit_model(name, func)
        trace = pm.load_trace(name)
        params = sorted([p.name for p in m.deterministics if "Lambda" in p.name])
        df = pm.summary(trace, var_names=params)

    table = []
    for p, i in zip(params, interps):

            theta = skewnorm.fit(trace[p])
            p0 = norm.pdf(0)
            p1 = skewnorm.pdf(0, *theta)
            bf = p0 / p1
            a, b, c = df.loc[p, ["mean", "hpd_2.5", "hpd_97.5"]]

            dic = {
                "Variable": p,
                "Posterior mean (95% HPD)": "%s (%s, %s)" % (
                    latexify(a), latexify(b), latexify(c)),
                "During roved-frequency trials ...": i,
                "BF": latexify(bf),
                "Evidence": interpret(bf),
            }
            table.append(dic)
            # print(p, bf)

    df = pd.DataFrame(table)[dic.keys()]
    df.to_latex(f"{name}/table2.tex", escape=False, index=False)

    if tex is True:
        df.to_latex("manuscript/table2.tex", escape=False, index=False)
コード例 #24
0
    def test_summary_max_central_3(self):
        c = ChainConsumer()
        c.add_chain(self.data_skew)
        summary_area = 0.95
        c.configure(statistics="max_central",
                    bins=1.0,
                    summary_area=summary_area)
        summary = c.analysis.get_summary()['0']

        xs = np.linspace(-1, 5, 1000)
        pdf = skewnorm.pdf(xs, 5, 1, 1.5)
        cdf = skewnorm.cdf(xs, 5, 1, 1.5)
        xval = interp1d(
            cdf, xs)([0.5 - 0.5 * summary_area, 0.5 + 0.5 * summary_area])
        xmax = xs[pdf.argmax()]

        assert np.isclose(xmax, summary[1], atol=0.05)
        assert np.isclose(xval[0], summary[0], atol=0.05)
        assert np.isclose(xval[1], summary[2], atol=0.05)
コード例 #25
0
    def test_summary_max_symmetric_3(self):
        c = ChainConsumer()
        c.add_chain(self.data_skew)
        summary_area = 0.95
        c.configure(statistics="max_symmetric",
                    bins=1.0,
                    summary_area=summary_area)
        summary = c.analysis.get_summary()['0']

        xs = np.linspace(0, 2, 1000)
        pdf = skewnorm.pdf(xs, 5, 1, 1.5)
        xmax = xs[pdf.argmax()]
        cdf_top = skewnorm.cdf(summary[2], 5, 1, 1.5)
        cdf_bottom = skewnorm.cdf(summary[0], 5, 1, 1.5)
        area = cdf_top - cdf_bottom

        assert np.isclose(xmax, summary[1], atol=0.05)
        assert np.isclose(area, summary_area, atol=0.05)
        assert np.isclose(summary[2] - summary[1], summary[1] - summary[0])
コード例 #26
0
def LL_FUNCTION(theta, array):

    alpha = theta[0]
    mu = theta[1]
    sigma = theta[2]
    N = len(array)
    try:
        constant = GLOBAL_INTERP([alpha, mu, sigma])[0]
    except:
        return -np.inf

    #LL = N*np.log(constant) + (erf((array - mu)/(np.sqrt(2) * sigma)*alpha) - 0.5*np.square((array - mu)/sigma) - np.log(sigma)).sum()
    LL = N * np.log(constant) + np.log(skewnorm.pdf(array, alpha, mu,
                                                    sigma)).sum()

    if not np.isfinite(LL):
        return -np.inf

    return LL + alpha_prior(alpha) + mu_prior(mu)
def skewgauss(n, relative_location=0, alpha=0):
    ''' Generate a squew gaussian.

        Args:
            n: (int) timesteps
            relative_location: (float) relative shifting of the
                distribution [0, 1] (0.1 indicates a shifting toward
                the beginning of the interval,0.9 indicates a shifting
                toward its end)
            alpha: (float) skewness

        Example:
            stime = 1500
            plt.plot(stime, skewgauss(stime, location=0.6, alpha=4))
    '''
    location = 10 * relative_location - 5
    rng = np.array([-2, 2]) - location
    x = np.linspace(rng[0], rng[1], n)
    return skewnorm.pdf(x, alpha)
コード例 #28
0
def plot_histogram_and_skew_norm(train_features_given_class, skew_norm_params,
                                 n_classes, do_skew_norm_plots):
    if do_skew_norm_plots:
        all_min = np.min(train_features_given_class)
        all_max = np.max(train_features_given_class)
        for class_i in range(n_classes):
            for feature_i in range(n_classes):
                plt.subplot(3, 3, 1 + feature_i + n_classes * class_i)
                plt.hist(train_features_given_class[class_i, :, feature_i],
                         density=True)
                minf = np.min(train_features_given_class[class_i, :,
                                                         feature_i])
                maxf = np.max(train_features_given_class[class_i, :,
                                                         feature_i])
                x = np.linspace(minf, maxf)
                plt.plot(
                    x, skewnorm.pdf(x, *skew_norm_params[class_i][feature_i]))
                plt.xlim((all_min, all_max))
                plt.ylim((0, 0.5))
                plt.title("C=" + str(class_i + 1) + " F=" + str(feature_i + 1))
        plt.show()
コード例 #29
0
ファイル: main.py プロジェクト: juzikong/GalEvo
def cal_tot_sf(SFR, SFEN):
    # Skew normal distribution for star formation history
    # took input: maximum star formation rate, star formation event number
    import numpy as np
    from scipy.stats import skewnorm
    # from scipy.stats import f
    global skewness, location
    x = np.linspace(skewnorm.ppf(0.01, skewness, location, 1),
                    skewnorm.ppf(0.99, skewness, location, 1), SFEN)
    y = skewnorm.pdf(x, skewness, location, 1)
    # skewnorm.pdf(x, a, loc, scale) is the location and scale parameters,
    #   [identically equivalent to skewnorm.pdf(y, a) / scale with y = (x - loc) / scale]
    # The scale is not used as the SFEN & SFR setup the scale through parameter tot_sf_set & mult.
    mult = 10**SFR / max(y)
    j = 0
    tot_sf = 0
    while j < SFEN:
        sf = mult * y[j]
        tot_sf += sf
        (j) = (j + 1)
    return tot_sf, mult, y
コード例 #30
0
def compare_hist_to_norm(data, bins=25):
    """

    :param data:
    :param bins:
    :return:
    """
    fig = plt.figure(figsize=(10, 5))

    mu, std = scipy.stats.norm.fit(data)

    plt.hist(data,
             bins=bins,
             density=True,
             alpha=0.6,
             color='purple',
             label="Données")

    # Plot le PDF.
    xmin, xmax = plt.xlim()
    X = np.linspace(xmin, xmax)

    plt.plot(X, scipy.stats.norm.pdf(X, mu, std), label="Normal Distribution")
    plt.plot(X,
             skewnorm.pdf(X, *skewnorm.fit(data)),
             color='black',
             label="Skewed Normal Distribution")

    mu, std = scipy.stats.norm.fit(data)
    sk = scipy.stats.skew(data)

    title2 = "Moments mu: {}, sig: {}, sk: {}".format(round(mu, 4),
                                                      round(std, 4),
                                                      round(sk, 4))
    plt.ylabel("Fréquence", rotation=90)
    plt.title(title2)
    plt.legend()
    #plt.show()
    pass
コード例 #31
0
ファイル: Calculator.py プロジェクト: mikelei8291/DFB2016
def s(p):
    func_s = skewnorm.pdf(p,alpha,mu,sigma)
    return func_s
コード例 #32
0
ファイル: stats.py プロジェクト: Samreay/Wigglez
    return (1 + erf(x/sqrt(2))) / 2

def skew(x,e=0,w=1,a=0):
    t = (x-e) / w
    return 2 / w * pdf(t) * cdf(a*t)
    # You can of course use the scipy.stats.norm versions
    # return 2 * norm.pdf(t) * norm.cdf(a*t)


n = 2**12
e = 1.0 # location
w = 2.0 # scale
x = linspace(0,7,n) 
#p = skew(x,e,w,9)

p = skewnorm.pdf(x, 5, loc=1, scale=1.5)
print(x[p.argmax()])
c = skewnorm.cdf(x, 5, loc=1, scale=1.5)
#c = p.cumsum()
#c /= c.max()



b0 = np.where(c > 0.15865)[0][0]
bm = np.where(c > 0.5)[0][0]
b1 = np.where(c > 0.84135)[0][0]
x0 = x[b0]
x1 = x[b1]


s=30
コード例 #33
0
ファイル: models.py プロジェクト: deisi/SFG2D
 def fit_funct(self, x, A, mu, sigma, kurt, c):
     return A * skewnorm.pdf(x, kurt, mu, sigma) + c