Beispiel #1
0
    def full_gen_data(self, fbar, nSamples, sigma, density):
        totalSize = self.ndc * nSamples
        ss = sigma * sigma
        denom = 2.0 * self.k * pi * ss * density + self.g0
        phi = np.zeros((self.ndc))

        phi_bar = 0
        for i, d in enumerate(self.dist2):
            if d == 0:
                p = self.g0 / denom
            else:
                p = sy.nsum(lambda t: exp(self.mu2 * t) *
                            exp(-d / (4.0 * ss * t)) / (2.0 * t), [
                            1, sy.inf], error=False, verbose=False,
                            method='euler-maclaurin', steps=[1000])
                p = p / denom
            phi_bar += p * nSamples
            phi[i] = p

        phi_bar /= float(totalSize)
        r = (phi - phi_bar) / (1.0 - phi_bar)
        pIBD = fbar + (1.0 - fbar) * r
        pIBD = np.array(pIBD, dtype=float)
        # simulate values from binomial distribution
        # np.random.seed(1209840)
        counts = np.random.binomial(nSamples, pIBD)
        return counts
Beispiel #2
0
def hypsum(expr, n, start, prec):
    """
    Sum a rapidly convergent infinite hypergeometric series with
    given general term, e.g. e = hypsum(1/factorial(n), n). The
    quotient between successive terms must be a quotient of integer
    polynomials.
    """
    from sympy import hypersimp, lambdify

    if start:
        expr = expr.subs(n, n + start)
    hs = hypersimp(expr, n)
    if hs is None:
        raise NotImplementedError("a hypergeometric series is required")
    num, den = hs.as_numer_denom()

    func1 = lambdify(n, num)
    func2 = lambdify(n, den)

    h, g, p = check_convergence(num, den, n)

    if h < 0:
        raise ValueError("Sum diverges like (n!)^%i" % (-h))

    # Direct summation if geometric or faster
    if h > 0 or (h == 0 and abs(g) > 1):
        term = expr.subs(n, 0)
        term = (MPZ(term.p) << prec) // term.q
        s = term
        k = 1
        while abs(term) > 5:
            term *= MPZ(func1(k - 1))
            term //= MPZ(func2(k - 1))
            s += term
            k += 1
        return from_man_exp(s, -prec)
    else:
        alt = g < 0
        if abs(g) < 1:
            raise ValueError("Sum diverges like (%i)^n" % abs(1/g))
        if p < 1 or (p == 1 and not alt):
            raise ValueError("Sum diverges like n^%i" % (-p))
        # We have polynomial convergence: use Richardson extrapolation
        # Need to use at least quad precision because a lot of cancellation
        # might occur in the extrapolation process
        prec2 = 4*prec
        term = expr.subs(n, 0)
        term = (MPZ(term.p) << prec2) // term.q

        def summand(k, _term=[term]):
            if k:
                k = int(k)
                _term[0] *= MPZ(func1(k - 1))
                _term[0] //= MPZ(func2(k - 1))
            return make_mpf(from_man_exp(_term[0], -prec2))

        with workprec(prec):
            v = nsum(summand, [0, mpmath_inf], method='richardson')

        return v._mpf_
Beispiel #3
0
 def full_likelihood(self):
     phi = np.zeros((self.ndc))
     phi_bar = 0
     denom = 2 * self.k * self.ss * pi * self.de + self.g0
     for i, d in enumerate(self.dist2):
         if d == 0:
             p = self.g0 / denom
         else:
             p = sy.nsum(lambda t: exp(self.mu2 * t) *
                         exp(-d / (4.0 * self.ss * t)) / (2.0 * t), [
                         1, sy.inf], error=False, verbose=False,
                         method='euler-maclaurin', steps=[100])
             p = p / denom
         phi_bar += p * self.sz[i]
         phi[i] = p
     phi_bar /= float(self.tsz)
     cml = 0
     for i in xrange(self.ndc):
         r = (phi[i] - phi_bar) / (1.0 - phi_bar)
         pIBD = self.fhat + (1 - self.fhat) * r
         if pIBD <= 0:
             print("WARNING: Prabability of IBD has fallen "
                   "below zero for distance class {}.").format(self.dist[i])
             print("This marginal likelihood will not be "
                   "included in composite likelihood.")
             continue
         cml += self.data[i] * log(pIBD) +\
             (self.sz[i] - self.data[i]) * log(1 - pIBD)
     return cml
Beispiel #4
0
def hypsum(expr, n, start, prec):
    """
    Sum a rapidly convergent infinite hypergeometric series with
    given general term, e.g. e = hypsum(1/factorial(n), n). The
    quotient between successive terms must be a quotient of integer
    polynomials.
    """
    from sympy import hypersimp, lambdify

    if start:
        expr = expr.subs(n, n + start)
    hs = hypersimp(expr, n)
    if hs is None:
        raise NotImplementedError("a hypergeometric series is required")
    num, den = hs.as_numer_denom()

    func1 = lambdify(n, num)
    func2 = lambdify(n, den)

    h, g, p = check_convergence(num, den, n)

    if h < 0:
        raise ValueError("Sum diverges like (n!)^%i" % (-h))

    # Direct summation if geometric or faster
    if h > 0 or (h == 0 and abs(g) > 1):
        term = expr.subs(n, 0)
        term = (MPZ(term.p) << prec) // term.q
        s = term
        k = 1
        while abs(term) > 5:
            term *= MPZ(func1(k - 1))
            term //= MPZ(func2(k - 1))
            s += term
            k += 1
        return from_man_exp(s, -prec)
    else:
        alt = g < 0
        if abs(g) < 1:
            raise ValueError("Sum diverges like (%i)^n" % abs(1 / g))
        if p < 1 or (p == 1 and not alt):
            raise ValueError("Sum diverges like n^%i" % (-p))
        # We have polynomial convergence: use Richardson extrapolation
        # Need to use at least quad precision because a lot of cancellation
        # might occur in the extrapolation process
        prec2 = 4 * prec
        term = expr.subs(n, 0)
        term = (MPZ(term.p) << prec2) // term.q

        def summand(k, _term=[term]):
            if k:
                k = int(k)
                _term[0] *= MPZ(func1(k - 1))
                _term[0] //= MPZ(func2(k - 1))
            return make_mpf(from_man_exp(_term[0], -prec2))

        with workprec(prec):
            v = nsum(summand, [0, mpmath_inf], method="richardson")

        return v._mpf_
Beispiel #5
0
def cramerVonMises(x, y):

	try:
		x = sorted(x);
		y = sorted(y);

		pool = x + y;

		ps, pr = _sortRank(pool)

		rx = array ( [ pr[ind] for ind in [ ps.index(element) for element in x ] ] )
		ry = array ( [ pr[ind] for ind in [ ps.index(element) for element in y ] ] )

		n = len(x)
		m = len(y)

		i = array(range(1, n+1))
		j = array(range(1, m+1))

		u = n * sum ( power( (rx - i), 2 ) ) + m * sum ( power((ry - j), 2) )

		t = u / (n*m*(n+m)) - (4*n*m-1) / (6 * (n+m))
		Tmu = 1/6 + 1 / (6*(n+m))
		Tvar = 1/45 * ( (m+n+1) / power((m+n),2) ) * (4*m*n*(m+n) - 3*(power(m,2) + power(n,2)) - 2*m*n) / (4*m*n)
		t = (t - Tmu) / power(45*Tvar, 0.5) + 1/6

		if t < 0:
			return -1
		elif t <= 12:
			a = 1-mp.nsum(lambda x : ( mp.gamma(x+0.5) / ( mp.gamma(0.5) * mp.fac(x) ) ) *
					 mp.power( 4*x + 1, 0.5 ) * mp.exp ( - mp.power(4*x + 1, 2) / (16*t) ) *
					  mp.besselk(0.25 , mp.power(4*x + 1, 2) / (16*t) ), [0,100] ) / (mp.pi*mp.sqrt(t))
			return float(mp.nstr(a,3))
		else:
			return 0
	except Exception as e:
		print e
		return -1

size = 50

XX, YY = np.mgrid[0:d.magnitude:complex(0, size),
                  0:d.magnitude:complex(0, size)]
Pressure = np.empty((size, size))
dmag = d.magnitude


def somando(x, y, r, s):
    return (cos((2*r + 1)*pi)*x/dmag)*(cos((2*s + 1)*pi)*y/dmag)/((2*r + 1)**2 + (2*s + 1)**2)

for i in xrange(size):
    for j in xrange(size):
        somatorio = nsum(lambda ri, si: somando(XX[i, j], YY[i, j], ri, si),
                         [0, inf], [0, inf], maxterms=30)
        pres = Pi - (16. / pi**2) * ((muo * qo_std * Bo) / (k * h)) * somatorio
        Pressure[i, j] = pres.magnitude

fig1 = plt.figure()
fig1.patch.set_facecolor('white')
plt.rcParams['legend.loc'] = 'best'

plt.title(u'Pressão em curvas de nível - padrão five-spot')
plt.xlabel(u'x [ft]')
plt.ylabel(u'y [ft]')
pressure_levels = np.linspace(500, 2200, 9).tolist()
CS = plt.contour(XX, YY, Pressure, levels=pressure_levels, colors='k')
plt.clabel(CS, fmt='%.1f', fontsize=12, inline=1)
Beispiel #7
0
def hypsum(expr, n, start, prec):
    """
    Sum a rapidly convergent infinite hypergeometric series with
    given general term, e.g. e = hypsum(1/factorial(n), n). The
    quotient between successive terms must be a quotient of integer
    polynomials.
    """
    from sympy import hypersimp, lambdify

    if prec == float('inf'):
        raise NotImplementedError('does not support inf prec')

    if start:
        expr = expr.subs(n, n + start)
    hs = hypersimp(expr, n)
    if hs is None:
        raise NotImplementedError("a hypergeometric series is required")
    num, den = hs.as_numer_denom()

    func1 = lambdify(n, num)
    func2 = lambdify(n, den)

    h, g, p = check_convergence(num, den, n)

    if h < 0:
        raise ValueError("Sum diverges like (n!)^%i" % (-h))

    term = expr.subs(n, 0)
    if not term.is_Rational:
        raise NotImplementedError("Non rational term functionality is not implemented.")

    # Direct summation if geometric or faster
    if h > 0 or (h == 0 and abs(g) > 1):
        term = (MPZ(term.p) << prec) // term.q
        s = term
        k = 1
        while abs(term) > 5:
            term *= MPZ(func1(k - 1))
            term //= MPZ(func2(k - 1))
            s += term
            k += 1
        return from_man_exp(s, -prec)
    else:
        alt = g < 0
        if abs(g) < 1:
            raise ValueError("Sum diverges like (%i)^n" % abs(1/g))
        if p < 1 or (p == 1 and not alt):
            raise ValueError("Sum diverges like n^%i" % (-p))
        # We have polynomial convergence: use Richardson extrapolation
        vold = None
        ndig = prec_to_dps(prec)
        while True:
            # Need to use at least quad precision because a lot of cancellation
            # might occur in the extrapolation process; we check the answer to
            # make sure that the desired precision has been reached, too.
            prec2 = 4*prec
            term0 = (MPZ(term.p) << prec2) // term.q

            def summand(k, _term=[term0]):
                if k:
                    k = int(k)
                    _term[0] *= MPZ(func1(k - 1))
                    _term[0] //= MPZ(func2(k - 1))
                return make_mpf(from_man_exp(_term[0], -prec2))

            with workprec(prec):
                v = nsum(summand, [0, mpmath_inf], method='richardson')
            vf = C.Float(v, ndig)
            if vold is not None and vold == vf:
                break
            prec += prec  # double precision each time
            vold = vf

        return v._mpf_