示例#1
0
	def _int_keys(self, data):
		t = self.cls()
		self.assertNode(t)
		self.assertIsNone(t._root)
		i = len(data)
		for j in range(i):
			self.assertEqual(j, len(t))
			self.assertNotIn(j, t)
			self.assertEqual(list(range(j)), list(t))
			t._set(j, data[j])
			self.assertNode(t)
			if j > 1:
				self.assertLess(t._root.height(), 2.0 * _log(j + 1, 2))
			else:
				self.assertEqual(t._root.height(), j + 1)
			self.assertEqual(data[j], t.get(j))
			self.assertIn(j, t)
		self.assertEqual(i, len(t))
		self.assertEqual(list(range(len(data))), list(t))
		self.assertIsNone(t.get(i + 1))
		# Deletion
		for j in range(i - 1, -1, -1):
			self.assertEqual(j + 1, len(t))
			self.assertIn(j, t)
			t._delete(j)
			self.assertNode(t)
			if j > 1:
				self.assertLessEqual(t._root.height(), 2.0 * _log(j, 2))
			elif j == 1:
				self.assertEqual(t._root.height(), j)
			else:
				self.assertIsNone(t._root)
			self.assertNotIn(j, t)
			self.assertEqual(list(range(j)), list(t))
		self.assertIsNone(t._root)
示例#2
0
    def gammavariate(self, alpha, beta):
        """Gamma distribution.  Not the gamma function!
        
        Conditions on the parameters are alpha > 0 and beta > 0.
        
        The probability distribution function is:
        
                    x ** (alpha - 1) * math.exp(-x / beta)
          pdf(x) =  --------------------------------------
                      math.gamma(alpha) * beta ** alpha
        
        """
        if alpha <= 0.0 or beta <= 0.0:
            raise ValueError, "gammavariate: alpha and beta must be > 0.0"
        random = self.random
        if alpha > 1.0:
            ainv = _sqrt(2.0 * alpha - 1.0)
            bbb = alpha - LOG4
            ccc = alpha + ainv
            while 1:
                u1 = random()
                if not 1e-07 < u1 < 0.9999999:
                    continue
                u2 = 1.0 - random()
                v = _log(u1 / (1.0 - u1)) / ainv
                x = alpha * _exp(v)
                z = u1 * u1 * u2
                r = bbb + ccc * v - x
                if r + SG_MAGICCONST - 4.5 * z >= 0.0 or r >= _log(z):
                    return x * beta

        else:
            if alpha == 1.0:
                u = random()
                while u <= 1e-07:
                    u = random()

                return -_log(u) * beta
            while 1:
                u = random()
                b = (_e + alpha) / _e
                p = b * u
                if p <= 1.0:
                    x = p ** (1.0 / alpha)
                else:
                    x = -_log((b - p) / alpha)
                u1 = random()
                if p > 1.0:
                    if u1 <= x ** (alpha - 1.0):
                        break
                elif u1 <= _exp(-x):
                    break

            return x * beta
    def projCoordinate(self, point):
        """ Convert from Point object in EPSG:900913 to a Coordinate object
        """
        # the zoom at which we're dealing with meters on the ground
        diameter = 2 * _pi * 6378137
        zoom = _log(diameter) / _log(2)

        # global offsets
        coord = Coordinate(point.y, point.x, zoom)
        coord.column = coord.column + diameter/2
        coord.row = diameter/2 - coord.row
        
        return coord
    def coordinateProj(self, coord):
        """ Convert from Coordinate object to a Point object in EPSG:900913
        """
        # the zoom at which we're dealing with meters on the ground
        diameter = 2 * _pi * 6378137
        zoom = _log(diameter) / _log(2)
        coord = coord.zoomTo(zoom)
        
        # global offsets
        point = Point(coord.column, coord.row)
        point.x = point.x - diameter/2
        point.y = diameter/2 - point.y

        return point
示例#5
0
    def stdgamma(self, alpha, ainv, bbb, ccc):
        # ainv = sqrt(2 * alpha - 1)
        # bbb = alpha - log(4)
        # ccc = alpha + ainv

        random = self.random
        if alpha <= 0.0:
            raise ValueError, 'stdgamma: alpha must be > 0.0'

        if alpha > 1.0:

            # Uses R.C.H. Cheng, "The generation of Gamma
            # variables with non-integral shape parameters",
            # Applied Statistics, (1977), 26, No. 1, p71-74

            while 1:
                u1 = random()
                u2 = random()
                v = _log(u1/(1.0-u1))/ainv
                x = alpha*_exp(v)
                z = u1*u1*u2
                r = bbb+ccc*v-x
                if r + SG_MAGICCONST - 4.5*z >= 0.0 or r >= _log(z):
                    return x

        elif alpha == 1.0:
            # expovariate(1)
            u = random()
            while u <= 1e-7:
                u = random()
            return -_log(u)

        else:   # alpha is between 0 and 1 (exclusive)

            # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle

            while 1:
                u = random()
                b = (_e + alpha)/_e
                p = b*u
                if p <= 1.0:
                    x = pow(p, 1.0/alpha)
                else:
                    # p > 1
                    x = -_log((b-p)/alpha)
                u1 = random()
                if not (((p <= 1.0) and (u1 > _exp(-x))) or
                          ((p > 1)  and  (u1 > pow(x, alpha - 1.0)))):
                    break
            return x
示例#6
0
文件: random.py 项目: Afey/pyjs
    def gauss(self, mu, sigma):
        # """Gaussian distribution.
        # mu is the mean, and sigma is the standard deviation.  This is
        # slightly faster than the normalvariate() function.
        # Not thread-safe without a lock around calls.
        # """

        # When x and y are two variables from [0, 1), uniformly
        # distributed, then
        #
        #    cos(2*pi*x)*sqrt(-2*log(1-y))
        #    sin(2*pi*x)*sqrt(-2*log(1-y))
        #
        # are two *independent* variables with normal distribution
        # (mu = 0, sigma = 1).
        # (Lambert Meertens)
        # (corrected version; bug discovered by Mike Miller, fixed by LM)

        # Multithreading note: When two threads call this function
        # simultaneously, it is possible that they will receive the
        # same return value.  The window is very small though.  To
        # avoid this, you have to use a lock around all calls.  (I
        # didn't want to slow this down in the serial case by using a
        # lock here.)

        __random = self.random
        z = self.gauss_next
        self.gauss_next = None
        if z is None:
            x2pi = __random() * TWOPI
            g2rad = _sqrt(-2.0 * _log(1.0 - __random()))
            z = _cos(x2pi) * g2rad
            self.gauss_next = _sin(x2pi) * g2rad

        return mu + z*sigma
示例#7
0
def dup_revert(f, n, K):
    """
    Compute ``f**(-1)`` mod ``x**n`` using Newton iteration.

    This function computes first ``2**n`` terms of a polynomial that
    is a result of inversion of a polynomial modulo ``x**n``. This is
    useful to efficiently compute series expansion of ``1/f``.

    Examples
    ========

    >>> from sympy.polys import ring, QQ
    >>> R, x = ring("x", QQ)

    >>> f = -QQ(1,720)*x**6 + QQ(1,24)*x**4 - QQ(1,2)*x**2 + 1

    >>> R.dup_revert(f, 8)
    61/720*x**6 + 5/24*x**4 + 1/2*x**2 + 1

    """
    g = [K.revert(dup_TC(f, K))]
    h = [K.one, K.zero, K.zero]

    N = int(_ceil(_log(n, 2)))

    for i in range(1, N + 1):
        a = dup_mul_ground(g, K(2), K)
        b = dup_mul(f, dup_sqr(g, K), K)
        g = dup_rem(dup_sub(a, b, K), h, K)
        h = dup_lshift(h, dup_degree(h), K)

    return g
示例#8
0
文件: power.py 项目: hrashk/sympy
def integer_nthroot(y, n):
    """
    Return a tuple containing x = floor(y**(1/n))
    and a boolean indicating whether the result is exact (that is,
    whether x**n == y).

    >>> from sympy import integer_nthroot
    >>> integer_nthroot(16,2)
    (4, True)
    >>> integer_nthroot(26,2)
    (5, False)

    """
    y, n = int(y), int(n)
    if y < 0:
        raise ValueError("y must be nonnegative")
    if n < 1:
        raise ValueError("n must be positive")
    if y in (0, 1):
        return y, True
    if n == 1:
        return y, True
    if n == 2:
        x, rem = mpmath_sqrtrem(y)
        return int(x), not rem
    if n > y:
        return 1, False
    # Get initial estimate for Newton's method. Care must be taken to
    # avoid overflow
    try:
        guess = int(y**(1./n) + 0.5)
    except OverflowError:
        exp = _log(y, 2)/n
        if exp > 53:
            shift = int(exp - 53)
            guess = int(2.0**(exp - shift) + 1) << shift
        else:
            guess = int(2.0**exp)
    #print n
    if guess > 2**50:
        # Newton iteration
        xprev, x = -1, guess
        while 1:
            t = x**(n - 1)
            #xprev, x = x, x - (t*x-y)//(n*t)
            xprev, x = x, ((n - 1)*x + y//t)//n
            #print n, x-xprev, abs(x-xprev) < 2
            if abs(x - xprev) < 2:
                break
    else:
        x = guess
    # Compensate
    t = x**n
    while t < y:
        x += 1
        t = x**n
    while t > y:
        x -= 1
        t = x**n
    return x, t == y
示例#9
0
	def sample(self, population, k, generator=None):
		# This function exactly parallels the code in Random.py.
		# Comments are therefore omitted, to save space.
		
		n = len(population)
		if not 0 <= k <= n:
			raise ValueError('sample larger than population')
		randrange = self.randrange
		result = [None] * k
		setsize = 21
		if k > 5:
			setsize += 4 ** _ceil(_log(k * 3, 4))
		if n <= setsize or hasattr(population, 'keys'):
			pool = list(population)
			for i in xrange(k):
				j = randrange(n-i, generator=generator)
				result[i] = pool[j]
				pool[j] = pool[n-i-1]
		else:
			try:
				selected = set()
				selected_add = selected.add
				for i in xrange(k):
					j = randrange(n, generator=generator)
					while j in selected:
						j = randrange(n, generator=generator)
					selected_add(j)
					result[i] = population[j]
			except (TypeError, KeyError):
				if isinstance(population, list):
					raise
				return self.sample(tuple(population), k, generator)
		return result
示例#10
0
文件: random.py 项目: zegab/diane
    def sample(self, population, k):
        """Chooses k unique random elements from a population sequence.

        Returns a new list containing elements from the population while
        leaving the original population unchanged.  The resulting list is
        in selection order so that all sub-slices will also be valid random
        samples.  This allows raffle winners (the sample) to be partitioned
        into grand prize and second place winners (the subslices).

        Members of the population need not be hashable or unique.  If the
        population contains repeats, then each occurrence is a possible
        selection in the sample.

        To choose a sample in a range of integers, use xrange as an argument.
        This is especially fast and space efficient for sampling from a
        large population:   sample(xrange(10000000), 60)
        """

        # Sampling without replacement entails tracking either potential
        # selections (the pool) in a list or previous selections in a set.

        # When the number of selections is small compared to the
        # population, then tracking selections is efficient, requiring
        # only a small set and an occasional reselection.  For
        # a larger number of selections, the pool tracking method is
        # preferred since the list takes less space than the
        # set and it doesn't suffer from frequent reselections.

        n = len(population)
        if not 0 <= k <= n:
            raise ValueError("sample larger than population")
        random = self.random
        _int = int
        result = [None] * k
        setsize = 21        # size of a small set minus size of an empty list
        if k > 5:
            setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets
        if n <= setsize or hasattr(population, "keys"):
            # An n-length list is smaller than a k-length set, or this is a
            # mapping type so the other algorithm wouldn't work.
            pool = list(population)
            for i in xrange(k):         # invariant:  non-selected at [0,n-i)
                j = _int(random() * (n-i))
                result[i] = pool[j]
                pool[j] = pool[n-i-1]   # move non-selected item into vacancy
        else:
            try:
                selected = set()
                selected_add = selected.add
                for i in xrange(k):
                    j = _int(random() * n)
                    while j in selected:
                        j = _int(random() * n)
                    selected_add(j)
                    result[i] = population[j]
            except (TypeError, KeyError):   # handle (at least) sets
                if isinstance(population, list):
                    raise
                return self.sample(tuple(population), k)
        return result
示例#11
0
    def _randbelow(self, n, _log=_log, _int=int, _maxwidth=1<<BPF,
                   _Method=_MethodType, _BuiltinMethod=_BuiltinMethodType):
        """Return a random int in the range [0,n)

        Handles the case where n has more bits than returned
        by a single call to the underlying generator.
        """

        try:
            getrandbits = self.getrandbits
        except AttributeError:
            pass
        else:
            # Only call self.getrandbits if the original random() builtin method
            # has not been overridden or if a new getrandbits() was supplied.
            # This assures that the two methods correspond.
            if type(self.random) is _BuiltinMethod or type(getrandbits) is _Method:
                k = _int(1.00001 + _log(n-1, 2.0))   # 2**k > n-1 > 2**(k-2)
                r = getrandbits(k)
                while r >= n:
                    r = getrandbits(k)
                return r
        if n >= _maxwidth:
            _warn("Underlying random() generator does not supply \n"
                "enough bits to choose from a population range this large")
        return _int(self.random() * n)
示例#12
0
    def sample(self, population, k):
        n = len(population)
        if not 0 <= k <= n:
            raise ValueError, 'sample larger than population'
        random = self.random
        _int = int
        result = [None] * k
        setsize = 21
        if k > 5:
            setsize += 4 ** _ceil(_log(k * 3, 4))
        if n <= setsize or hasattr(population, 'keys'):
            pool = list(population)
            for i in xrange(k):
                j = _int(random() * (n - i))
                result[i] = pool[j]
                pool[j] = pool[n - i - 1]

        else:
            try:
                selected = set()
                selected_add = selected.add
                for i in xrange(k):
                    j = _int(random() * n)
                    while j in selected:
                        j = _int(random() * n)

                    selected_add(j)
                    result[i] = population[j]

            except (TypeError, KeyError):
                if isinstance(population, list):
                    raise
                return self.sample(tuple(population), k)

        return result
示例#13
0
    def expovariate(self, lambd):
        random = self.random
        u = random()
        while u <= 1e-07:
            u = random()

        return -_log(u) / lambd
示例#14
0
 def sample(self, population, k):
     if isinstance(population, _Set):
         population = tuple(population)
     if not isinstance(population, _Sequence):
         raise TypeError('Population must be a sequence or set.  For dicts, use list(d).')
     randbelow = self._randbelow
     n = len(population)
     if not 0 <= k <= n:
         raise ValueError('Sample larger than population')
     result = [None]*k
     setsize = 21
     if k > 5:
         setsize += 4**_ceil(_log(k*3, 4))
     if n <= setsize:
         pool = list(population)
         for i in range(k):
             j = randbelow(n - i)
             result[i] = pool[j]
             pool[j] = pool[n - i - 1]
     else:
         selected = set()
         selected_add = selected.add
         for i in range(k):
             j = randbelow(n)
             while j in selected:
                 j = randbelow(n)
             selected_add(j)
             result[i] = population[j]
     return result
示例#15
0
def dup_revert(f, n, K):
    """
    Compute ``f**(-1)`` mod ``x**n`` using Newton iteration.

    This function computes first ``2**n`` terms of a polynomial that
    is a result of inversion of a polynomial modulo ``x**n``. This is
    useful to efficiently compute series expansion of ``1/f``.

    Examples
    ========

    >>> from sympy.polys.domains import QQ
    >>> from sympy.polys.densetools import dup_revert

    >>> f = [-QQ(1,720), QQ(0), QQ(1,24), QQ(0), -QQ(1,2), QQ(0), QQ(1)]

    >>> dup_revert(f, 8, QQ)
    [61/720, 0/1, 5/24, 0/1, 1/2, 0/1, 1/1]

    """
    g = [K.revert(dup_TC(f, K))]
    h = [K.one, K.zero, K.zero]

    N = int(_ceil(_log(n, 2)))

    for i in xrange(1, N + 1):
        a = dup_mul_ground(g, K(2), K)
        b = dup_mul(f, dup_sqr(g, K), K)
        g = dup_rem(dup_sub(a, b, K), h, K)
        h = dup_lshift(h, dup_degree(h), K)

    return g
示例#16
0
    def expovariate(self, lambd):

        """Exponential distribution.


        lambd is 1.0 divided by the desired mean.  It should be

        nonzero.  (The parameter would be called "lambda", but that is

        a reserved word in Python.)  Returned values range from 0 to

        positive infinity if lambd is positive, and from negative

        infinity to 0 if lambd is negative.


        """

        # lambd: rate lambd = 1/mean

        # ('lambda' is a Python reserved word)


        # we use 1-random() instead of random() to preclude the

        # possibility of taking the log of zero.

        return -_log(1.0 - self.random())/lambd
示例#17
0
 def sample(self, population, k):
    """Chooses k unique random elements from a population sequence."""
    # https://github.com/python/cpython/blob/2.7/Lib/random.py#L275
    n = len(population)
    if not 0 <= k <= n:
       raise ValueError("sample larger than population")
    random = self.random
    _int = int
    result = [None] * k
    setsize = 21      # size of a small set minus size of an empty list
    if k > 5:
       setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets
    if n <= setsize or hasattr(population, "keys"):
       # An n-length list is smaller than a k-length set, or this is a
       # mapping type so the other algorithm wouldn't work.
       pool = list(population)
       for i in xrange(k):       # invariant:  non-selected at [0,n-i)
          j = _int(random() * (n-i))
          result[i] = pool[j]
          pool[j] = pool[n-i-1]   # move non-selected item into vacancy
    else:
       try:
          selected = set()
          selected_add = selected.add
          for i in xrange(k):
             j = _int(random() * n)
             while j in selected:
                j = _int(random() * n)
             selected_add(j)
             result[i] = population[j]
       except (TypeError, KeyError):   # handle (at least) sets
          if isinstance(population, list):
             raise
          return self.sample(tuple(population), k)
    return result
示例#18
0
    def sample(self, population: Iterable[T], k: int) -> List[T]:
        """Chooses k unique random elements from a population sequence or set.

        Returns a new list containing elements from the population while
        leaving the original population unchanged.  The resulting list is
        in selection order so that all sub-slices will also be valid random
        samples.  This allows raffle winners (the sample) to be partitioned
        into grand prize and second place winners (the subslices).

        Members of the population need not be hashable or unique.  If the
        population contains repeats, then each occurrence is a possible
        selection in the sample.

        To choose a sample in a range of integers, use range as an argument.
        This is especially fast and space efficient for sampling from a
        large population:   sample(range(10000000), 60)
        """

        # Sampling without replacement entails tracking either potential
        # selections (the pool) in a list or previous selections in a set.

        # When the number of selections is small compared to the
        # population, then tracking selections is efficient, requiring
        # only a small set and an occasional reselection.  For
        # a larger number of selections, the pool tracking method is
        # preferred since the list takes less space than the
        # set and it doesn't suffer from frequent reselections.

        if isinstance(population, _Sequence):
            populationseq = population
        elif isinstance(population, _Set):
            populationseq = list(population)
        else:
            raise TypeError("Population must be a sequence or set.  For dicts, use list(d).")
        randbelow = self._randbelow
        n = len(populationseq)
        if not (0 <= k and k <= n):
            raise ValueError("Sample larger than population")
        result = [cast(T, None)] * k
        setsize = 21        # size of a small set minus size of an empty list
        if k > 5:
            setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets
        if n <= setsize:
            # An n-length list is smaller than a k-length set
            pool = list(populationseq)
            for i in range(k):         # invariant:  non-selected at [0,n-i)
                j = randbelow(n-i)
                result[i] = pool[j]
                pool[j] = pool[n-i-1]   # move non-selected item into vacancy
        else:
            selected = Set[int]()
            selected_add = selected.add
            for i in range(k):
                j = randbelow(n)
                while j in selected:
                    j = randbelow(n)
                selected_add(j)
                result[i] = populationseq[j]
        return result
示例#19
0
 def weibullvariate(self, alpha, beta):
     """Weibull distribution.
     
     alpha is the scale parameter and beta is the shape parameter.
     
     """
     u = 1.0 - self.random()
     return alpha * pow(-_log(u), 1.0 / beta)
示例#20
0
文件: random.py 项目: Afey/pyjs
    def weibullvariate(self, alpha, beta):
        # """Weibull distribution.
        # alpha is the scale parameter and beta is the shape parameter.
        # """
        # Jain, pg. 499; bug fix courtesy Bill Arms

        u = 1.0 - self.random()
        return alpha * pow(-_log(u), 1.0/beta)
示例#21
0
    def gammavariate(self, alpha, beta):
        if alpha <= 0.0 or beta <= 0.0:
            raise ValueError('gammavariate: alpha and beta must be > 0.0')
        random = self.random
        if alpha > 1.0:
            ainv = _sqrt(2.0*alpha - 1.0)
            bbb = alpha - LOG4
            ccc = alpha + ainv
            u1 = random()
            if not 1e-07 < u1 < 0.9999999:
                continue
            u2 = 1.0 - random()
            v = _log(u1/(1.0 - u1))/ainv
            x = alpha*_exp(v)
            z = u1*u1*u2
            r = bbb + ccc*v - x
            #ERROR: Unexpected statement:   517 BINARY_MULTIPLY  |   518 RETURN_VALUE 

            if r + SG_MAGICCONST - 4.5*z >= 0.0 or r >= _log(z):
                return x*beta
                continue
        else:
            if alpha == 1.0:
                u = random()
                while u <= 1e-07:
                    u = random()
                return -_log(u)*beta
            while True:
                u = random()
                b = (_e + alpha)/_e
                p = b*u
                if p <= 1.0:
                    x = p**(1.0/alpha)
                else:
                    x = -_log((b - p)/alpha)
                u1 = random()
                if p > 1.0:
                    if u1 <= x**(alpha - 1.0):
                        break
                        continue
                        if u1 <= _exp(-x):
                            break
                elif u1 <= _exp(-x):
                    break
            return x*beta
示例#22
0
	def test_height_after_ordered_set(self):
		data = list(range(2 * _getrecursionlimit()))
		size = len(data)
		t = self.cls()
		self.assertNode(t)
		for i in data:
			t._set(i, i)
			self.assertNode(t)
		self.assertLessEqual(t._root.height(), 2.0 * _log(size, 2))
示例#23
0
    def expovariate(self, lambd):
        # lambd: rate lambd = 1/mean
        # ('lambda' is a Python reserved word)

        random = self.random
        u = random()
        while u <= 1e-7:
            u = random()
        return -_log(u)/lambd
示例#24
0
def dup_zz_hensel_lift(p, f, f_list, l, K):
    """
    Multifactor Hensel lifting in `Z[x]`.

    Given a prime `p`, polynomial `f` over `Z[x]` such that `lc(f)`
    is a unit modulo `p`, monic pair-wise coprime polynomials `f_i`
    over `Z[x]` satisfying::

        f = lc(f) f_1 ... f_r (mod p)

    and a positive integer `l`, returns a list of monic polynomials
    `F_1`, `F_2`, ..., `F_r` satisfying::

       f = lc(f) F_1 ... F_r (mod p**l)

       F_i = f_i (mod p), i = 1..r

    References
    ==========

    1. [Gathen99]_

    """
    r = len(f_list)
    lc = dup_LC(f, K)

    if r == 1:
        F = dup_mul_ground(f, K.gcdex(lc, p**l)[0], K)
        return [ dup_trunc(F, p**l, K) ]

    m = p
    k = r // 2
    d = int(_ceil(_log(l, 2)))

    g = gf_from_int_poly([lc], p)

    for f_i in f_list[:k]:
        g = gf_mul(g, gf_from_int_poly(f_i, p), p, K)

    h = gf_from_int_poly(f_list[k], p)

    for f_i in f_list[k + 1:]:
        h = gf_mul(h, gf_from_int_poly(f_i, p), p, K)

    s, t, _ = gf_gcdex(g, h, p, K)

    g = gf_to_int_poly(g, p)
    h = gf_to_int_poly(h, p)
    s = gf_to_int_poly(s, p)
    t = gf_to_int_poly(t, p)

    for _ in range(1, d + 1):
        (g, h, s, t), m = dup_zz_hensel_step(m, f, g, h, s, t, K), m**2

    return dup_zz_hensel_lift(p, g, f_list[:k], l, K) \
        + dup_zz_hensel_lift(p, h, f_list[k:], l, K)
示例#25
0
    def weibullvariate(self, alpha: float, beta: float) -> float:
        """Weibull distribution.

        alpha is the scale parameter and beta is the shape parameter.

        """
        # Jain, pg. 499; bug fix courtesy Bill Arms

        u = 1.0 - self.random()
        return alpha * (-_log(u)) ** (1.0/beta)
示例#26
0
 def normalvariate(self, mu, sigma):
     random = self.random
     while True:
         u1 = random()
         u2 = 1.0 - random()
         z = NV_MAGICCONST*(u1 - 0.5)/u2
         zz = z*z/4.0
         if zz <= -_log(u2):
             break
     return mu + z*sigma
示例#27
0
 def gauss(self, mu, sigma):
     random = self.random
     z = self.gauss_next
     self.gauss_next = None
     if z is None:
         x2pi = random() * TWOPI
         g2rad = _sqrt(-2.0 * _log(1.0 - random()))
         z = _cos(x2pi) * g2rad
         self.gauss_next = _sin(x2pi) * g2rad
     return mu + z * sigma
示例#28
0
    def gammavariate(self, alpha, beta):
        if alpha <= 0.0 or beta <= 0.0:
            raise ValueError, 'gammavariate: alpha and beta must be > 0.0'
        random = self.random
        if alpha > 1.0:
            ainv = _sqrt(2.0 * alpha - 1.0)
            bbb = alpha - LOG4
            ccc = alpha + ainv
            while 1:
                u1 = random()
                if not 1e-07 < u1 < 0.9999999:
                    continue
                u2 = 1.0 - random()
                v = _log(u1 / (1.0 - u1)) / ainv
                x = alpha * _exp(v)
                z = u1 * u1 * u2
                r = bbb + ccc * v - x
                if r + SG_MAGICCONST - 4.5 * z >= 0.0 or r >= _log(z):
                    return x * beta

        else:
            if alpha == 1.0:
                u = random()
                while u <= 1e-07:
                    u = random()

                return -_log(u) * beta
            while 1:
                u = random()
                b = (_e + alpha) / _e
                p = b * u
                if p <= 1.0:
                    x = p ** (1.0 / alpha)
                else:
                    x = -_log((b - p) / alpha)
                u1 = random()
                if p > 1.0:
                    if u1 <= x ** (alpha - 1.0):
                        break
                elif u1 <= _exp(-x):
                    break

            return x * beta
示例#29
0
def log(S):
    """Convenience function for taking logarithms of PowerSeries.
    
    This can also replace the ``math.log`` function, extending it to
    take a PowerSeries as an argument.
    """
    from math import log as _log
    if isinstance(S, PowerSeries):
        return S.logarithm()
    return _log(S)
示例#30
0
	def test(self, example):
		lables = {}
		#get every classifers prediction
		for learner in self.classifiers:
			choosenLabel = learner.inst.test(example)
			try:
				lables[choosenLabel] += _log(1/learner.B)
			except KeyError:
				lables[choosenLabel] = _log(1/learner.B)

		bestValue = -1 * _MAX_INT 
		bestKey = None
		#find the class with the best
		for key, value in lables.items():
			if value > bestValue:
				bestValue = value
				bestKey = key

		return bestKey
示例#31
0
def dup_zz_zassenhaus(f, K):
    """Factor primitive square-free polynomials in `Z[x]`. """
    n = dup_degree(f)

    if n == 1:
        return [f]

    fc = f[-1]
    A = dup_max_norm(f, K)
    b = dup_LC(f, K)
    B = int(abs(K.sqrt(K(n + 1))*2**n*A*b))
    C = int((n + 1)**(2*n)*A**(2*n - 1))
    gamma = int(_ceil(2*_log(C, 2)))
    bound = int(2*gamma*_log(gamma))
    a = []
    # choose a prime number `p` such that `f` be square free in Z_p
    # if there are many factors in Z_p, choose among a few different `p`
    # the one with fewer factors
    for px in range(3, bound + 1):
        if not isprime(px) or b % px == 0:
            continue

        px = K.convert(px)

        F = gf_from_int_poly(f, px)

        if not gf_sqf_p(F, px, K):
            continue
        fsqfx = gf_factor_sqf(F, px, K)[1]
        a.append((px, fsqfx))
        if len(fsqfx) < 15 or len(a) > 4:
            break
    p, fsqf = min(a, key=lambda x: len(x[1]))

    l = int(_ceil(_log(2*B + 1, p)))

    modular = [gf_to_int_poly(ff, p) for ff in fsqf]

    g = dup_zz_hensel_lift(p, f, modular, l, K)

    sorted_T = range(len(g))
    T = set(sorted_T)
    factors, s = [], 1
    pl = p**l

    while 2*s <= len(T):
        for S in subsets(sorted_T, s):
            # lift the constant coefficient of the product `G` of the factors
            # in the subset `S`; if it is does not divide `fc`, `G` does
            # not divide the input polynomial

            if b == 1:
                q = 1
                for i in S:
                    q = q*g[i][-1]
                q = q % pl
                if not _test_pl(fc, q, pl):
                    continue
            else:
                G = [b]
                for i in S:
                    G = dup_mul(G, g[i], K)
                G = dup_trunc(G, pl, K)
                G = dup_primitive(G, K)[1]
                q = G[-1]
                if q and fc % q != 0:
                    continue

            H = [b]
            S = set(S)
            T_S = T - S

            if b == 1:
                G = [b]
                for i in S:
                    G = dup_mul(G, g[i], K)
                G = dup_trunc(G, pl, K)

            for i in T_S:
                H = dup_mul(H, g[i], K)

            H = dup_trunc(H, pl, K)

            G_norm = dup_l1_norm(G, K)
            H_norm = dup_l1_norm(H, K)

            if G_norm*H_norm <= B:
                T = T_S
                sorted_T = [i for i in sorted_T if i not in S]

                G = dup_primitive(G, K)[1]
                f = dup_primitive(H, K)[1]

                factors.append(G)
                b = dup_LC(f, K)

                break
        else:
            s += 1

    return factors + [f]
示例#32
0
def dup_zz_zassenhaus(f, K):
    """Factor primitive square-free polynomials in `Z[x]`. """
    n = dup_degree(f)

    if n == 1:
        return [f]

    A = dup_max_norm(f, K)
    b = dup_LC(f, K)
    B = int(abs(K.sqrt(K(n + 1)) * 2**n * A * b))
    C = int((n + 1)**(2 * n) * A**(2 * n - 1))
    gamma = int(_ceil(2 * _log(C, 2)))
    bound = int(2 * gamma * _log(gamma))

    for p in xrange(3, bound + 1):
        if not isprime(p) or b % p == 0:
            continue

        p = K.convert(p)

        F = gf_from_int_poly(f, p)

        if gf_sqf_p(F, p, K):
            break

    l = int(_ceil(_log(2 * B + 1, p)))

    modular = []

    for ff in gf_factor_sqf(F, p, K)[1]:
        modular.append(gf_to_int_poly(ff, p))

    g = dup_zz_hensel_lift(p, f, modular, l, K)

    sorted_T = range(len(g))
    T = set(sorted_T)
    factors, s = [], 1

    while 2 * s <= len(T):
        for S in subsets(sorted_T, s):
            G, H = [b], [b]

            S = set(S)
            T_S = T - S

            for i in S:
                G = dup_mul(G, g[i], K)

            for i in T_S:
                H = dup_mul(H, g[i], K)

            G = dup_trunc(G, p**l, K)
            H = dup_trunc(H, p**l, K)

            G_norm = dup_l1_norm(G, K)
            H_norm = dup_l1_norm(H, K)

            if G_norm * H_norm <= B:
                T = T_S
                sorted_T = [i for i in sorted_T if i not in S]

                G = dup_primitive(G, K)[1]
                f = dup_primitive(H, K)[1]

                factors.append(G)
                b = dup_LC(f, K)

                break
        else:
            s += 1

    return factors + [f]
示例#33
0
文件: random.py 项目: moneytech/pyvm
        Handles the case where n has more bits than returned
        by a single call to the underlying generator.
        """

        try:
            getrandbits = self.getrandbits
        except AttributeError:
            pass
        else:
            # Only call self.getrandbits if the original random() builtin method
            # has not been overridden or if a new getrandbits() was supplied.
            # This assures that the two methods correspond.
            if type(self.random) is _BuiltinMethod or type(
                    getrandbits) is _Method:
                k = int(1.00001 + _log(n - 1, 2.0))  # 2**k > n-1 > 2**(k-2)
                r = getrandbits(k)
                while r >= n:
                    r = getrandbits(k)
                return r
        if n >= _maxwidth:
            _warn("Underlying random() generator does not supply \n"
                  "enough bits to choose from a population range this large")
        return int(self.random() * n)

## -------------------- sequence methods  -------------------

    def choice(self, seq):
        """Choose a random element from a non-empty sequence."""
        return seq[int(self.random() *
                       len(seq))]  # raises IndexError if seq is empty
示例#34
0
 def expovariate(self, lambd):
     random = self.random
     u = random()
     while ((u <= 9.9999999999999995e-008)):
         u = random()
     return ((-(_log(u))) / lambd)
示例#35
0
def massPDG(pdgid):
    """Gaussian mass distribution with mass and width of a chosen particle.
    Accept the Particle Data Group ID as the only argument."""
    return gauss(
        pypdt.get(pdgid).mass,
        pypdt.get(pdgid).width / (2 * _sqrt(2 * _log(2))))
示例#36
0
    def sample(self, population, k):
        """Chooses k unique random elements from a population sequence or set.

        Returns a new list containing elements from the population while
        leaving the original population unchanged.  The resulting list is
        in selection order so that all sub-slices will also be valid random
        samples.  This allows raffle winners (the sample) to be partitioned
        into grand prize and second place winners (the subslices).

        Members of the population need not be hashable or unique.  If the
        population contains repeats, then each occurrence is a possible
        selection in the sample.

        To choose a sample in a range of integers, use range as an argument.
        This is especially fast and space efficient for sampling from a
        large population:   sample(range(10000000), 60)
        """

        # Sampling without replacement entails tracking either potential
        # selections (the pool) in a list or previous selections in a set.

        # When the number of selections is small compared to the
        # population, then tracking selections is efficient, requiring
        # only a small set and an occasional reselection.  For
        # a larger number of selections, the pool tracking method is
        # preferred since the list takes less space than the
        # set and it doesn't suffer from frequent reselections.

        # The number of calls to _randbelow() is kept at or near k, the
        # theoretical minimum.  This is important because running time
        # is dominated by _randbelow() and because it extracts the
        # least entropy from the underlying random number generators.

        # Memory requirements are kept to the smaller of a k-length
        # set or an n-length list.

        # There are other sampling algorithms that do not require
        # auxiliary memory, but they were rejected because they made
        # too many calls to _randbelow(), making them slower and
        # causing them to eat more entropy than necessary.

        if isinstance(population, _Set):
            _warn(
                'Sampling from a set deprecated\n'
                'since Python 3.9 and will be removed in a subsequent version.',
                DeprecationWarning, 2)
            population = tuple(population)
        if not isinstance(population, _Sequence):
            raise TypeError(
                "Population must be a sequence.  For dicts or sets, use sorted(d)."
            )
        randbelow = self._randbelow
        n = len(population)
        if not 0 <= k <= n:
            raise ValueError("Sample larger than population or is negative")
        result = [None] * k
        setsize = 21  # size of a small set minus size of an empty list
        if k > 5:
            setsize += 4**_ceil(_log(k * 3, 4))  # table size for big sets
        if n <= setsize:
            # An n-length list is smaller than a k-length set
            pool = list(population)
            for i in range(k):  # invariant:  non-selected at [0,n-i)
                j = randbelow(n - i)
                result[i] = pool[j]
                pool[j] = pool[n - i -
                               1]  # move non-selected item into vacancy
        else:
            selected = set()
            selected_add = selected.add
            for i in range(k):
                j = randbelow(n)
                while j in selected:
                    j = randbelow(n)
                selected_add(j)
                result[i] = population[j]
        return result
示例#37
0
    def sample(self, population: Union[_Set[T], _Sequence[T]],
               k: int) -> List[T]:
        """Chooses k unique random elements from a population sequence or set.

        Returns a new list containing elements from the population while
        leaving the original population unchanged.  The resulting list is
        in selection order so that all sub-slices will also be valid random
        samples.  This allows raffle winners (the sample) to be partitioned
        into grand prize and second place winners (the subslices).

        Members of the population need not be hashable or unique.  If the
        population contains repeats, then each occurrence is a possible
        selection in the sample.

        To choose a sample in a range of integers, use range as an argument.
        This is especially fast and space efficient for sampling from a
        large population:   sample(range(10000000), 60)
        """

        # Sampling without replacement entails tracking either potential
        # selections (the pool) in a list or previous selections in a set.

        # When the number of selections is small compared to the
        # population, then tracking selections is efficient, requiring
        # only a small set and an occasional reselection.  For
        # a larger number of selections, the pool tracking method is
        # preferred since the list takes less space than the
        # set and it doesn't suffer from frequent reselections.

        if isinstance(population, _Set):
            population = list(population)
        if not isinstance(population, _Sequence):
            raise TypeError(
                "Population must be a sequence or set.  For dicts, use list(d)."
            )
        randbelow = self._randbelow
        n = len(population)
        if not (0 <= k and k <= n):
            raise ValueError("Sample larger than population")
        result = [cast(T, None)] * k
        setsize = 21  # size of a small set minus size of an empty list
        if k > 5:
            setsize += 4**_ceil(_log(k * 3, 4))  # table size for big sets
        if n <= setsize:
            # An n-length list is smaller than a k-length set
            pool = list(population)
            for i in range(k):  # invariant:  non-selected at [0,n-i)
                j = randbelow(n - i)
                result[i] = pool[j]
                pool[j] = pool[n - i -
                               1]  # move non-selected item into vacancy
        else:
            selected = set()  # type: Set[int]
            selected_add = selected.add
            for i in range(k):
                j = randbelow(n)
                while j in selected:
                    j = randbelow(n)
                selected_add(j)
                result[i] = population[j]
        return result
 def weibullvariate(self, alpha, beta):
     u = 1.0 - self.random()
     return alpha * pow(-_log(u), 1.0 / beta)
示例#39
0
    def renderArea(self, width_, height_, srs, xmin_, ymin_, xmax_, ymax_, zoom):
        """
        """
        merc = Proj(srs)
        
        # use the center to figure out our UTM zone
        lon, lat = merc((xmin_ + xmax_)/2, (ymin_ + ymax_)/2, inverse=True)
        zone = lon2zone(lon)
        hemi = lat2hemi(lat)

        utm = Proj(proj='utm', zone=zone, datum='WGS84')
        
        # get to UTM coords
        (minlon, minlat), (maxlon, maxlat) = merc(xmin_, ymin_, inverse=1), merc(xmax_, ymax_, inverse=1)
        (xmin, ymin), (xmax, ymax) = utm(minlon, minlat), utm(maxlon, maxlat)

        # figure out how widely-spaced they should be
        pixels = _hypot(width_, height_)            # number of pixels across the image
        units = _hypot(xmax - xmin, ymax - ymin)    # number of UTM units across the image
        
        tick = self.tick * units/pixels             # desired tick length in UTM units
        
        count = pixels / self.spacing               # approximate number of lines across the image
        bound = units / count                       # too-precise step between lines in UTM units
        zeros = int(_ceil(_log(bound) / _log(10)))  # this value gets used again to format numbers
        step = int(_pow(10, zeros))                 # a step that falls right on the 10^n
        
        # and the outer UTM bounds
        xbot, xtop = int(xmin - xmin % step), int(xmax - xmax % step) + 2 * step
        ybot, ytop = int(ymin - ymin % step), int(ymax - xmax % step) + 2 * step
    
        # start doing things in pixels
        img = Image.new('RGBA', (width_, height_), (0xEE, 0xEE, 0xEE, 0x00))
        draw = ImageDraw.ImageDraw(img)
        xform = transform(width_, height_, xmin_, ymax_, xmax_, ymin_)
        
        lines = []
        labels = []
        
        for col in range(xbot, xtop, step):
            # set up the verticals
            utms = [(col, y) for y in range(ybot, ytop, step/10)]
            mercs = [merc(*utm(x, y, inverse=1)) for (x, y) in utms]
            lines.append( [xform(x, y) for (x, y) in mercs] )
            
            # and the tick marks
            for row in range(ybot, ytop, step/10):
                mercs = [merc(*utm(x, y, inverse=1)) for (x, y) in ((col, row), (col - tick, row))]
                lines.append( [xform(x, y) for (x, y) in mercs] )
        
        for row in range(ybot, ytop, step):
            # set up the horizontals
            utms = [(x, row) for x in range(xbot, xtop, step/10)]
            mercs = [merc(*utm(x, y, inverse=1)) for (x, y) in utms]
            lines.append( [xform(x, y) for (x, y) in mercs] )
            
            # and the tick marks
            for col in range(xbot, xtop, step/10):
                mercs = [merc(*utm(x, y, inverse=1)) for (x, y) in ((col, row), (col, row - tick))]
                lines.append( [xform(x, y) for (x, y) in mercs] )

        # set up the intersection labels
        for x in range(xbot, xtop, step):
            for y in range(ybot, ytop, step):
                lon, lat = utm(x, y, inverse=1)
                grid = lonlat2grid(lon, lat)
                point = xform(*merc(lon, lat))
                
                if self.display == 'utm':
                    e = ('%07d' % x)[:-zeros]
                    n = ('%07d' % y)[:-zeros]
                    text = ' '.join( [grid, e, n] )

                elif self.display == 'mgrs':
                    e, n = Proj(proj='utm', zone=lon2zone(lon), datum='WGS84')(lon, lat)
                    text = utm2mgrs(round(e), round(n), grid, zeros)
                
                labels.append( (point, text) )

        # do the drawing bits
        for ((x, y), text) in labels:
            x, y = x + 2, y - 18
            w, h = self.font.getsize(text)
            draw.rectangle((x - 2, y, x + w + 2, y + h), fill=(0xFF, 0xFF, 0xFF, 0x99))

        for line in lines:
            draw.line(line, fill=(0xFF, 0xFF, 0xFF))

        for line in lines:
            draw.line([(x-1, y-1) for (x, y) in line], fill=(0x00, 0x00, 0x00))

        for ((x, y), text) in labels:
            x, y = x + 2, y - 18
            draw.text((x, y), text, fill=(0x00, 0x00, 0x00), font=self.font)

        return img
 def expovariate(self, lambd):
     return -_log(1.0 - self.random()) / lambd
from types import MethodType as _MethodType, BuiltinMethodType as _BuiltinMethodType
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin
from os import urandom as _urandom
from binascii import hexlify as _hexlify
import hashlib as _hashlib
__all__ = [
    'Random', 'seed', 'random', 'uniform', 'randint', 'choice', 'sample',
    'randrange', 'shuffle', 'normalvariate', 'lognormvariate', 'expovariate',
    'vonmisesvariate', 'gammavariate', 'triangular', 'gauss', 'betavariate',
    'paretovariate', 'weibullvariate', 'getstate', 'setstate', 'jumpahead',
    'WichmannHill', 'getrandbits', 'SystemRandom'
]
NV_MAGICCONST = 4 * _exp(-0.5) / _sqrt(2.0)
TWOPI = 2.0 * _pi
LOG4 = _log(4.0)
SG_MAGICCONST = 1.0 + _log(4.5)
BPF = 53
RECIP_BPF = 2**(-BPF)
import _random


class Random(_random.Random):
    VERSION = 3

    def __init__(self, x=None):
        self.seed(x)
        self.gauss_next = None
        return

    def seed(self, a=None):
示例#42
0
    def binomialvariate(self, n=1, p=0.5):
        """Binomial random variable.

        Gives the number of successes for *n* independent trials
        with the probability of success in each trial being *p*:

            sum(random() < p for i in range(n))

        Returns an integer in the range:   0 <= X <= n

        """
        # Error check inputs and handle edge cases
        if n < 0:
            raise ValueError("n must be non-negative")
        if p <= 0.0 or p >= 1.0:
            if p == 0.0:
                return 0
            if p == 1.0:
                return n
            raise ValueError("p must be in the range 0.0 <= p <= 1.0")

        random = self.random

        # Fast path for a common case
        if n == 1:
            return _index(random() < p)

        # Exploit symmetry to establish:  p <= 0.5
        if p > 0.5:
            return n - self.binomialvariate(n, 1.0 - p)

        if n * p < 10.0:
            # BG: Geometric method by Devroye with running time of O(np).
            # https://dl.acm.org/doi/pdf/10.1145/42372.42381
            x = y = 0
            c = _log(1.0 - p)
            if not c:
                return x
            while True:
                y += _floor(_log(random()) / c) + 1
                if y > n:
                    return x
                x += 1

        # BTRS: Transformed rejection with squeeze method by Wolfgang Hörmann
        # https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.47.8407&rep=rep1&type=pdf
        assert n * p >= 10.0 and p <= 0.5
        setup_complete = False

        spq = _sqrt(n * p *
                    (1.0 - p))  # Standard deviation of the distribution
        b = 1.15 + 2.53 * spq
        a = -0.0873 + 0.0248 * b + 0.01 * p
        c = n * p + 0.5
        vr = 0.92 - 4.2 / b

        while True:

            u = random()
            u -= 0.5
            us = 0.5 - _fabs(u)
            k = _floor((2.0 * a / us + b) * u + c)
            if k < 0 or k > n:
                continue

            # The early-out "squeeze" test substantially reduces
            # the number of acceptance condition evaluations.
            v = random()
            if us >= 0.07 and v <= vr:
                return k

            # Acceptance-rejection test.
            # Note, the original paper errorneously omits the call to log(v)
            # when comparing to the log of the rescaled binomial distribution.
            if not setup_complete:
                alpha = (2.83 + 5.1 / b) * spq
                lpq = _log(p / (1.0 - p))
                m = _floor((n + 1) * p)  # Mode of the distribution
                h = _lgamma(m + 1) + _lgamma(n - m + 1)
                setup_complete = True  # Only needs to be done once
            v *= alpha / (a / (us * us) + b)
            if _log(v) <= h - _lgamma(k + 1) - _lgamma(n - k +
                                                       1) + (k - m) * lpq:
                return k
示例#43
0
def log(x, y):
    return _log(x, y)
示例#44
0
_pchar_ = _PTR_(_char_)
_ppchar_ = _PTR_(_pchar_)
_cast_cstr = lambda x: _cast(x, _str_).value.decode()

_gen_str_buffers = lambda sz, n: [_BUF_(sz) for _ in range(n)]
_gen_str_buffers_ptrs = lambda bufs: (_pchar_ * len(bufs))(
    *[_cast(b, _pchar_) for b in bufs])

_map_cstr = _partial(map, _cast_cstr)
_map_dt = _partial(map, TOSDB_DateTime)
_zip_cstr_dt = lambda cstr, dt: zip(_map_cstr(cstr), _map_dt(dt))

DLL_BASE_NAME = "tos-databridge"
DLL_DEPENDS1_NAME = "_tos-databridge"
SYS_ARCH_TYPE = "x64" if (_log(_maxsize * 2, 2) > 33) else "x86"
MIN_MARGIN_OF_SAFETY = 10

_REGEX_NON_ALNUM = _compile("[\W+]")
_REGEX_LETTER = _compile("[a-zA-Z]")
_VER_SFFX = '[\d]{1,2}.[\d]{1,2}'
_REGEX_VER_SFFX = _compile('-' + _VER_SFFX + '-')

_REGEX_DLL_NAME = _compile('^(' + DLL_BASE_NAME + '-)' \
                                + _VER_SFFX + '-' \
                                + SYS_ARCH_TYPE +'(.dll)$')

_REGEX_DBG_DLL_PATH = _compile('^.+(' + DLL_BASE_NAME + '-)' \
                                      + _VER_SFFX + '-' \
                                      + SYS_ARCH_TYPE + '_d(.dll)$')
示例#45
0
    def weibullvariate(self, alpha, beta):
        # Jain, pg. 499; bug fix courtesy Bill Arms

        u = self.random()
        return alpha * pow(-_log(u), 1.0 / beta)
def log(num):
    if(num):
        return _log(num)
    return -25
示例#47
0
import logging

from . import mvt, geojson

try:
    from mapnik import PythonDatasource, Box2d
except ImportError:
    # can still build documentation
    PythonDatasource = object

# earth's diameter in meters
diameter = 2 * pi * 6378137

# zoom of one-meter pixels
meter_zoom = _log(diameter) / _log(2) - 8


def utf8_keys(dictionary):
    ''' Convert dictionary keys to utf8-encoded strings for Mapnik.
    
        By default, json.load() returns dictionaries with unicode keys
        but Mapnik is ultra-whiny about these and rejects them.
    '''
    return dict([(key.encode('utf8'), val)
                 for (key, val) in dictionary.items()])


def list_tiles(query, zoom_adjust):
    ''' Return a list of tiles (z, x, y) dicts for a mapnik Query object.
    
示例#48
0
class RandomDotOrg(Random):
    """Alternate random number generator using random.org as the
    source.

    Requires Internet access."""

    __version__ = '0.1.0'

    _intMin = -1000000000
    _intMax = 1000000000
    _maxWidth = _intMax - _intMin + 1

    _hexMax = int(_floor(_log(_intMax, 16)))
    _bitsMax = _hexMax << 2
    _bitsMaxInt = 2**_bitsMax - 1

    _fetchMax = 10000

    def _fetch(self, service, **kwargs):
        "Fetch data from the Random.org HTTP Interface"
        url = 'https://www.random.org/%s/?' % urlquote(service)
        options = dict(format='plain')
        options.update(kwargs)
        headers = {
            'User-Agent': 'RandomSources.randomDotOrg/%s' % self.__version__
        }

        req = Request(url + urlencode(options), headers=headers)
        return urlopen(req).read().splitlines()

    def fetchHex(self, digits, rnd='new'):
        remainderDigits = digits % self._hexMax
        fullInts = digits // self._hexMax
        remainderFetch = fullInts % self._fetchMax
        fullFetches = fullInts // self._fetchMax

        r = ''
        options = dict(col=1,
                       base=16,
                       min=0,
                       max=self._bitsMaxInt,
                       num=self._fetchMax,
                       rnd=rnd)
        if fullFetches > 0:
            r += ''.join(''.join(self._fetch('integers', **options))
                         for i in xrange(fullFetches))
        if remainderFetch > 0:
            options['num'] = remainderFetch
            r += ''.join(self._fetch('integers', **options))
        if remainderDigits > 0:
            options['max'] = 16**remainderDigits - 1
            options['num'] = 1
            r += self._fetch('integers', **options)[0]
        return r

    def fetchIntegers(self, imin, imax, num, rnd='new'):
        fullFetches = num // self._fetchMax
        remainderFetch = num % self._fetchMax

        r = []
        options = dict(col=1,
                       base=10,
                       min=imin,
                       max=imax,
                       num=self._fetchMax,
                       rnd=rnd)
        for i in xrange(num // self._fetchMax):
            r.extend(map(int, self._fetch('integers', **options)))
        if remainderFetch > 0:
            options['num'] = remainderFetch
            r.extend(map(int, self._fetch('integers', **options)))
        return r

    def checkBitQuota(self):
        return int(self._fetch('quota', format='plain')[0])

    def random(self, n=1):
        if n == 1:
            return self.getrandbits(bitsPerFloat) * 2**-bitsPerFloat
        return [
            x * 2**-bitsPerFloat for x in self.getrandbits(bitsPerFloat, n)
        ]

    random.__doc__ = Random.random.__doc__

    def getrandbits(self, k, n=1):
        "getrandbits(k) -> x. Generates a long int with k random bits."
        if k == 0:
            return 0

        hexString = self.fetchHex((k * n + 3) // 4)
        result = long(hexString, 16)
        filter = 2**k - 1

        if n == 1:
            return result & filter

        r = []
        for i in xrange(n):
            r.append(result & filter)
            result >>= k
        return r

    def _stub(self, *args, **kwargs):
        "Stub method. Not used for a remote random number generator."
        return None

    seed = _stub
    jumpahead = _stub

    def _notimplemented(self, *args, **kwargs):
        "Method should not be called for a remote random number generator."
        raise NotImplementedError('Remote entropy sources do not have state.')

    getstate = _notimplemented
    setstate = _notimplemented

    ## -------------------- integer methods  -------------------

    def randrange(self, start, stop=None, step=1, n=1):
        # This function exactly parallels the code in Random.py,
        # with the one additional feature of fetching multiple
        # requests together; most comments are copied here.

        imin = self._intMin
        maxwidth = self._maxWidth

        # This code is a bit messy to make it fast for the
        # common case while still doing adequate error checking.
        istart = int(start)
        if istart != start:
            raise ValueError('non-integer arg 1 for randrange()')
        if stop is None:
            if istart > 0:
                if istart > maxwidth:
                    if n > 1:
                        return self._randbelow(istart, n)
                    return self._randbelow(istart)
                r = self.fetchIntegers(imin, imin + istart - 1, n)
                if n == 1:
                    return r[0]
                return r
            raise ValueError('empty range for randrange()')

        # stop argument supplied.
        istop = int(stop)
        if istop != stop:
            raise ValueError('non-integer stop for randrange()')
        width = istop - istart
        if step == 1 and width > 0:
            if width >= maxwidth:
                if n > 1:
                    return [int(istart + x) for x in self._randbelow(width, n)]
                return int(istart + self._randbelow(width))
            shift = istart - imin
            r = self.fetchIntegers(imin, imin + width - 1, n)
            if n == 1:
                return shift + r[0]
            return [int(shift + x) for x in r]
        if step == 1:
            raise ValueError('empty range for randrange() (%d,%d, %d)' %
                             (istart, istop, width))

        # Non-unit step argument supplied.
        istep = int(step)
        if istep != step:
            raise ValueError('non-integer step for randrange()')
        if istep > 0:
            size = (width + istep - 1) // istep
        elif istep < 0:
            size = (width + istep + 1) // istep
        else:
            raise ValueError('zero step for randrange()')

        if size <= 0:
            raise ValueError('empty range for randrange()')

        if size >= maxwidth:
            if n > 1:
                return [
                    int(istart + istep * x) for x in self._randbelow(size, n)
                ]
            return int(istart + istep * self._randbelow(size))
        shift = istart - istep * imin
        r = self.fetchIntegers(imin, imin + size - 1, n)
        if n == 1:
            return int(shift + istep * r[0])
        return [int(shift + istep * x) for x in r]

    randrange.__doc__ = Random.randrange.__doc__

    def randint(self, a, b, n=1):
        return self.randrange(a, b + 1, n=n)

    randint.__doc__ = Random.randint.__doc__

    def _randbelow(self, n, num=1, _log=_log, int=int):
        k = int(1.00001 + _log(n - 1, 2.0))  # 2**k > n-1 > 2**(k-2)

        if num == 1:
            r = self.getrandbits(k)
            while r >= n:
                r = self.getrandbits(k)
            return r

        r = []
        filter = (1 << k) - 1
        while num > 0:
            bits = self.getrandbits(k * num)
            for i in xrange(num):
                x = bits & filter
                if x < n:
                    r.append(x)
                    num -= 1
        return r

    _randbelow.__doc__ = Random._randbelow.__doc__

    ## -------------------- sequence methods  -------------------

    def choice(self, seq, n=1):
        length = len(seq)
        if length == 0:
            raise IndexError('list index out of range')

        if n == 1:
            return seq[self.randrange(length)]

        return [seq[i] for i in self.randrange(length, n=n)]

    choice.__doc__ = Random.choice.__doc__

    def shuffle(self, x, random=None):
        if random is not None:
            return Random.shuffle(self, x, random)

        randrange = self.randrange
        for i in reversed(xrange(1, len(x))):
            # pick an element in x[:i+1] with which to exchange x[i]
            j = randrange(i + 1)
            x[i], x[j] = x[j], x[i]

    shuffle.__doc__ = Random.shuffle.__doc__

    def sample(self, population, k):
        # This function exactly parallels the code in Random.py.
        # Comments are therefore omitted, to save space.

        n = len(population)
        if not 0 <= k <= n:
            raise ValueError('sample larger than population')
        randrange = self.randrange
        result = [None] * k
        setsize = 21
        if k > 5:
            setsize += 4**_ceil(_log(k * 3, 4))
        if n <= setsize or hasattr(population, 'keys'):
            pool = list(population)
            for i in xrange(k):
                j = randrange(n - i)
                result[i] = pool[j]
                pool[j] = pool[n - i - 1]
        else:
            try:
                selected = set()
                selected_add = selected.add
                for i in xrange(k):
                    j = randrange(n)
                    while j in selected:
                        j = randrange(n)
                    selected_add(j)
                    result[i] = population[j]
            except (TypeError, KeyError):
                if isinstance(population, list):
                    raise
                return self.sample(tuple(population), k)
        return result

    sample.__doc__ = Random.sample.__doc__
示例#49
0
    "randbytes",
    "randint",
    "random",
    "randrange",
    "sample",
    "seed",
    "setstate",
    "shuffle",
    "triangular",
    "uniform",
    "vonmisesvariate",
    "weibullvariate",
]

NV_MAGICCONST = 4 * _exp(-0.5) / _sqrt(2.0)
LOG4 = _log(4.0)
SG_MAGICCONST = 1.0 + _log(4.5)
BPF = 53        # Number of bits in a float
RECIP_BPF = 2 ** -BPF
_ONE = 1


class Random(_random.Random):
    """Random number generator base class used by bound module functions.

    Used to instantiate instances of Random to get generators that don't
    share state.

    Class Random can also be subclassed if you want to use a different basic
    generator of your own devising: in that case, override the following
    methods:  random(), seed(), getstate(), and setstate().
示例#50
0
    def sample(self, population, k, *, counts=None):
        """Chooses k unique random elements from a population sequence.

        Returns a new list containing elements from the population while
        leaving the original population unchanged.  The resulting list is
        in selection order so that all sub-slices will also be valid random
        samples.  This allows raffle winners (the sample) to be partitioned
        into grand prize and second place winners (the subslices).

        Members of the population need not be hashable or unique.  If the
        population contains repeats, then each occurrence is a possible
        selection in the sample.

        Repeated elements can be specified one at a time or with the optional
        counts parameter.  For example:

            sample(['red', 'blue'], counts=[4, 2], k=5)

        is equivalent to:

            sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)

        To choose a sample from a range of integers, use range() for the
        population argument.  This is especially fast and space efficient
        for sampling from a large population:

            sample(range(10000000), 60)

        """

        # Sampling without replacement entails tracking either potential
        # selections (the pool) in a list or previous selections in a set.

        # When the number of selections is small compared to the
        # population, then tracking selections is efficient, requiring
        # only a small set and an occasional reselection.  For
        # a larger number of selections, the pool tracking method is
        # preferred since the list takes less space than the
        # set and it doesn't suffer from frequent reselections.

        # The number of calls to _randbelow() is kept at or near k, the
        # theoretical minimum.  This is important because running time
        # is dominated by _randbelow() and because it extracts the
        # least entropy from the underlying random number generators.

        # Memory requirements are kept to the smaller of a k-length
        # set or an n-length list.

        # There are other sampling algorithms that do not require
        # auxiliary memory, but they were rejected because they made
        # too many calls to _randbelow(), making them slower and
        # causing them to eat more entropy than necessary.

        if not isinstance(population, _Sequence):
            raise TypeError("Population must be a sequence.  "
                            "For dicts or sets, use sorted(d).")
        n = len(population)
        if counts is not None:
            cum_counts = list(_accumulate(counts))
            if len(cum_counts) != n:
                raise ValueError('The number of counts does not match the population')
            total = cum_counts.pop()
            if not isinstance(total, int):
                raise TypeError('Counts must be integers')
            if total <= 0:
                raise ValueError('Total of counts must be greater than zero')
            selections = self.sample(range(total), k=k)
            bisect = _bisect
            return [population[bisect(cum_counts, s)] for s in selections]
        randbelow = self._randbelow
        if not 0 <= k <= n:
            raise ValueError("Sample larger than population or is negative")
        result = [None] * k
        setsize = 21        # size of a small set minus size of an empty list
        if k > 5:
            setsize += 4 ** _ceil(_log(k * 3, 4))  # table size for big sets
        if n <= setsize:
            # An n-length list is smaller than a k-length set.
            # Invariant:  non-selected at pool[0 : n-i]
            pool = list(population)
            for i in range(k):
                j = randbelow(n - i)
                result[i] = pool[j]
                pool[j] = pool[n - i - 1]  # move non-selected item into vacancy
        else:
            selected = set()
            selected_add = selected.add
            for i in range(k):
                j = randbelow(n)
                while j in selected:
                    j = randbelow(n)
                selected_add(j)
                result[i] = population[j]
        return result
示例#51
0
 def weibullvariate(self, alpha, beta):
     u = self.random()
     return (alpha * pow((-(_log(u))), (1.0 / beta)))
示例#52
0
from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin
from os import urandom as _urandom
from binascii import hexlify as _hexlify
import hashlib as _hashlib

__all__ = [
    "Random", "seed", "random", "uniform", "randint", "choice", "sample",
    "randrange", "shuffle", "normalvariate", "lognormvariate", "expovariate",
    "vonmisesvariate", "gammavariate", "triangular", "gauss", "betavariate",
    "paretovariate", "weibullvariate", "getstate", "setstate", "jumpahead",
    "WichmannHill", "getrandbits", "SystemRandom"
]

NV_MAGICCONST = 4 * _exp(-0.5) / _sqrt(2.0)
TWOPI = 2.0 * _pi
LOG4 = _log(4.0)
SG_MAGICCONST = 1.0 + _log(4.5)
BPF = 53  # Number of bits in a float
RECIP_BPF = 2**-BPF

# Translated by Guido van Rossum from C source provided by
# Adrian Baddeley.  Adapted by Raymond Hettinger for use with
# the Mersenne Twister  and os.urandom() core generators.

import _random


class Random(_random.Random):
    """Random number generator base class used by bound module functions.

    Used to instantiate instances of Random to get generators that don't
示例#53
0
def log10(q: Quaternion or float) -> Quaternion:
    """Return the base-10 logarithm of the quaternion."""
    return (log(q) / _log(10))
示例#54
0
    def sample(self, population, k):
        """Chooses k unique random elements from a population sequence.

        Returns a new list containing elements from the population while
        leaving the original population unchanged.  The resulting list is
        in selection order so that all sub-slices will also be valid random
        samples.  This allows raffle winners (the sample) to be partitioned
        into grand prize and second place winners (the subslices).

        Members of the population need not be hashable or unique.  If the
        population contains repeats, then each occurrence is a possible
        selection in the sample.

        To choose a sample in a range of integers, use xrange as an argument.
        This is especially fast and space efficient for sampling from a
        large population:   sample(xrange(10000000), 60)
        """

        # Sampling without replacement entails tracking either potential
        # selections (the pool) in a list or previous selections in a set.

        # When the number of selections is small compared to the
        # population, then tracking selections is efficient, requiring
        # only a small set and an occasional reselection.  For
        # a larger number of selections, the pool tracking method is
        # preferred since the list takes less space than the
        # set and it doesn't suffer from frequent reselections.

        n = len(population)
        if not 0 <= k <= n:
            raise ValueError("sample larger than population")
        random = self.random
        _int = int
        result = [None] * k
        setsize = 21  # size of a small set minus size of an empty list
        if k > 5:
            setsize += 4**_ceil(_log(k * 3, 4))  # table size for big sets
        if n <= setsize or hasattr(population, "keys"):
            # An n-length list is smaller than a k-length set, or this is a
            # mapping type so the other algorithm wouldn't work.
            pool = list(population)
            for i in xrange(k):  # invariant:  non-selected at [0,n-i)
                j = _int(random() * (n - i))
                result[i] = pool[j]
                pool[j] = pool[n - i -
                               1]  # move non-selected item into vacancy
        else:
            try:
                selected = set()
                selected_add = selected.add
                for i in xrange(k):
                    j = _int(random() * n)
                    while j in selected:
                        j = _int(random() * n)
                    selected_add(j)
                    result[i] = population[j]
            except (TypeError, KeyError):  # handle (at least) sets
                if isinstance(population, list):
                    raise
                return self.sample(tuple(population), k)
        return result
示例#55
0
def zMass(mZ=91.188, wZ=2.495):
    """Return a gaussian distribution. Default has a mean of 91.188 and a 
    width of 2.495."""
    return _gauss(mZ, wZ * (2 * _sqrt(2 * _log(2))))
示例#56
0
    def gammavariate(self, alpha, beta):
        """Gamma distribution.  Not the gamma function!

        Conditions on the parameters are alpha > 0 and beta > 0.

        The probability distribution function is:

                    x ** (alpha - 1) * math.exp(-x / beta)
          pdf(x) =  --------------------------------------
                      math.gamma(alpha) * beta ** alpha

        """

        # alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2

        # Warning: a few older sources define the gamma distribution in terms
        # of alpha > -1.0
        if alpha <= 0.0 or beta <= 0.0:
            raise ValueError, 'gammavariate: alpha and beta must be > 0.0'

        random = self.random
        if alpha > 1.0:

            # Uses R.C.H. Cheng, "The generation of Gamma
            # variables with non-integral shape parameters",
            # Applied Statistics, (1977), 26, No. 1, p71-74

            ainv = _sqrt(2.0 * alpha - 1.0)
            bbb = alpha - LOG4
            ccc = alpha + ainv

            while 1:
                u1 = random()
                if not 1e-7 < u1 < .9999999:
                    continue
                u2 = 1.0 - random()
                v = _log(u1 / (1.0 - u1)) / ainv
                x = alpha * _exp(v)
                z = u1 * u1 * u2
                r = bbb + ccc * v - x
                if r + SG_MAGICCONST - 4.5 * z >= 0.0 or r >= _log(z):
                    return x * beta

        elif alpha == 1.0:
            # expovariate(1)
            u = random()
            while u <= 1e-7:
                u = random()
            return -_log(u) * beta

        else:  # alpha is between 0 and 1 (exclusive)

            # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle

            while 1:
                u = random()
                b = (_e + alpha) / _e
                p = b * u
                if p <= 1.0:
                    x = p**(1.0 / alpha)
                else:
                    x = -_log((b - p) / alpha)
                u1 = random()
                if p > 1.0:
                    if u1 <= x**(alpha - 1.0):
                        break
                elif u1 <= _exp(-x):
                    break
            return x * beta
示例#57
0
    def sample(self, population, k):
        # """Chooses k unique random elements from a population sequence.
        # Returns a new list containing elements from the population while
        # leaving the original population unchanged.  The resulting list is
        # in selection order so that all sub-slices will also be valid random
        # samples.  This allows raffle winners (the sample) to be partitioned
        # into grand prize and second place winners (the subslices).
        #
        # Members of the population need not be hashable or unique.  If the
        # population contains repeats, then each occurrence is a possible
        # selection in the sample.
        #
        # To choose a sample in a range of integers, use xrange as an argument.
        # This is especially fast and space efficient for sampling from a
        # large population:   sample(xrange(10000000), 60)
        # """

        # XXX Although the documentation says `population` is "a sequence",
        # XXX attempts are made to cater to any iterable with a __len__
        # XXX method.  This has had mixed success.  Examples from both
        # XXX sides:  sets work fine, and should become officially supported;
        # XXX dicts are much harder, and have failed in various subtle
        # XXX ways across attempts.  Support for mapping types should probably
        # XXX be dropped (and users should pass mapping.keys() or .values()
        # XXX explicitly).

        # Sampling without replacement entails tracking either potential
        # selections (the pool) in a list or previous selections in a set.

        # When the number of selections is small compared to the
        # population, then tracking selections is efficient, requiring
        # only a small set and an occasional reselection.  For
        # a larger number of selections, the pool tracking method is
        # preferred since the list takes less space than the
        # set and it doesn't suffer from frequent reselections.

        n = len(population)
        if not 0 <= k <= n:
            raise ValueError, "sample larger than population"
        __random = self.random
        _int = int
        result = [None] * k
        setsize = 21  # size of a small set minus size of an empty list
        if k > 5:
            setsize += 4**_ceil(_log(k * 3, 4))  # table size for big sets
        if n <= setsize or hasattr(population, "keys"):
            # An n-length list is smaller than a k-length set, or this is a
            # mapping type so the other algorithm wouldn't work.
            pool = list(population)
            for i in xrange(k):  # invariant:  non-selected at [0,n-i)
                j = _int(__random() * (n - i))
                result[i] = pool[j]
                pool[j] = pool[n - i -
                               1]  # move non-selected item into vacancy
        else:
            try:
                selected = set()
                selected_add = selected.add
                for i in xrange(k):
                    j = _int(__random() * n)
                    while j in selected:
                        j = _int(__random() * n)
                    selected_add(j)
                    result[i] = population[j]
            except (TypeError, KeyError):  # handle (at least) sets
                if isinstance(population, list):
                    raise
                return self.sample(tuple(population), k)
        return result
示例#58
0
 def _randbelow(self, n, generator=None, _log=_log, int=int):
     k = int(1.00001 + _log(n - 1, 2.0))  # 2**k > n-1 > 2**(k-2)
     r = self.getrandbits(k, generator)
     while r >= n:
         r = self.getrandbits(k, generator)
     return r
示例#59
0
def ln(x):
    return _log(x)
示例#60
0
 def expovariate(self, lambd):
     random = self.random
     u = random()
     while u <= 9.9999999999999995e-008:
         u = random()
     return -_log(u) / lambd