Esempio n. 1
0
    def m_vectors(alms, l):
        """
        Get multipole vectors in spherical coordinates for a multipole given a map.

        Args:
            alms (complex array): multipole moments from a map (Healpy indexing).
            l (int): multipole.

        Returns:
            Float array [theta, phi] in radians.
        """

        # Context for MPSolve:
        ctx = mp.Context()
        poly = mp.MonomialPoly(ctx, 2 * l)

        # Get maximum multipole moment given an array.
        lmax = hp.sphtfunc.Alm.getlmax(len(alms))

        # Polynomial indexes:
        m_array = np.arange(-l, l + 1, 1)  # m values.
        neg_m = m_array[0:l]  # Negative m values.
        pos_m = m_array[l:]  # Positive m values.

        # Binomial terms:
        binom_term = [sqrt(bincoef(2 * l, l + i)) for i in range(-l, l + 1)]

        # Indexes for all alms list:
        index = hp.sphtfunc.Alm.getidx(lmax, l, abs(m_array))
        alm_ell_real = np.real(alms[index])
        alm_ell_imag = np.imag(alms[index])

        # Negative imaginary part for m:
        neg_rea_m_term = [(-1)**int(i) for i in neg_m]
        # Positive imaginary part for m:
        neg_imag_m_term = [-((-1)**int(i)) for i in neg_m]

        # Join all real signs:
        rea_sign = np.concatenate((neg_rea_m_term, np.ones(l + 1)))
        # Join all imaginary signs:
        imag_sign = np.concatenate((neg_imag_m_term, np.ones(l + 1)))

        rea = rea_sign * alm_ell_real * binom_term  # Real terms.
        ima = imag_sign * alm_ell_imag * binom_term  # Imaginary terms.

        # Set coefficients:
        [
            poly.set_coefficient(i, str(rea[i]), str(ima[i]))
            for i in range(2 * l + 1)
        ]

        # Getting roots:
        ctx.solve(poly, algorithm=mp.Algorithm.SECULAR_GA)
        roots = np.array(ctx.get_roots())

        phi = np.angle(roots)
        r = np.absolute(roots)
        theta = 2 * np.arctan(1 / r)

        return np.vstack((theta, phi)).T
Esempio n. 2
0
def calcPopDistribution(size, totalSize):
    popDistribution = np.zeros(size)
    for state in range(0, size):
        binomialCoef = gmpy2.bincoef(int(size - 1), state)
        popDistribution[state] = totalSize * (binomialCoef /
                                              (math.pow(2, size)))
    if not np.sum(popDistribution) == totalSize:
        factor = totalSize / np.sum(popDistribution)
        for i in range(0, len(popDistribution)):
            popDistribution[i] = popDistribution[i] * factor
    return popDistribution
Esempio n. 3
0
def proba(N, K, W, L, P, EPS):
    s = mpz(0)
    for p in range(0, P + 2, 2):
        P1 = p // 2
        P2 = p - P1
        N1 = (K + L) // 2
        N2 = K + L - N1

        for i1 in range(P1 + 1):
            for i2 in range(P2 + 1):
                s += bincoef(N1 - EPS, P1 - i1) * bincoef(
                    N2 - EPS, P2 - i2) * bincoef(2 * EPS, i1 + i2) * bincoef(
                        N - K - L, W - p)
    if bincoef(N, W) < 2**(N - K):
        s /= bincoef(N, W)
    else:
        s /= 2**(N - K)
    return s
def main():

    # Test local versions of libraries

    utils.test_python_version()
    utils.test_gmpy2_version()

    # Parse command line arguments

    parser = argparse.ArgumentParser(
        description=
        "From a table of draws, output a seed of appropriate length.")

    parser.add_argument("input_draw_file", help="""Text file with draws.""")
    parser.add_argument(
        "output_seed_file",
        help=
        """JSON file where we can store the seed computed from the draws.""")
    parser.add_argument(
        "entropy_to_gather",
        help="""Minimum entropy to extract before drawing lone bits.""")
    parser.add_argument("--nbr_lone_bits",
                        type=int,
                        help="""Number of lone bits to extract.""",
                        default=0)

    args = parser.parse_args()

    # Check arguments

    output_seed_file = args.output_seed_file
    if os.path.exists(output_seed_file):
        utils.exit_error("The output file '%s' already exists. Exiting." %
                         (output_seed_file))

    # Declare a few important variables

    two_pow_entropy_to_gather = (1 << int(args.entropy_to_gather))

    seed = 0
    L = 1  # before lone bits are drawn, seed lies in [0,L - 1]

    lone_bits_part = 0
    nbr_lone_bits = args.nbr_lone_bits

    # Scan the input file, construct the seed

    with open(args.input_draw_file, "r") as f:

        for line in f:

            if not line or line.strip() == "" or line.startswith("#"):
                continue

            (draw_id, m, n, draw) = re.split("\s+", line.strip(), maxsplit=3)

            if draw == "None":
                continue

            m = int(m)
            n = int(n)
            draw = [int(x) for x in draw.split(",")]
            index = index_from_draw(draw, m)

            if L < two_pow_entropy_to_gather:

                print("Draw %s used to extract entropy" % (draw_id))
                seed = gmpy2.bincoef(n, m) * seed + index
                L *= gmpy2.bincoef(n, m)

            else:

                print("Draw %s used to extract a lone bit" % (draw_id))
                b = index & 1
                seed += L * (b << (args.nbr_lone_bits - nbr_lone_bits))
                nbr_lone_bits -= 1

            if L >= two_pow_entropy_to_gather and nbr_lone_bits == 0:
                break

    if nbr_lone_bits > 0 or L < two_pow_entropy_to_gather:
        utils.exit_error(
            "There wasn't enough draws to collect to request quantity of entropy and lone bits."
        )

    seed_upper_bound = L * 2**(args.nbr_lone_bits)
    seed_entropy = math.floor(gmpy2.log2(seed_upper_bound))
    print(
        "The seed contains more than %d bits of entropy (including the %s lone bits)."
        % (seed_entropy, args.nbr_lone_bits))
    print("The seed is %d" % (seed))

    print("Saving the seed to %s" % (output_seed_file))
    with open(output_seed_file, "w") as f:
        json.dump(
            {
                "seed": int(seed),
                "seed_upper_bound": int(seed_upper_bound),
                "approx_seed_entropy": int(seed_entropy),
                "lone_bits": int(args.nbr_lone_bits)
            },
            f,
            sort_keys=True)
def index_from_draw(draw, m):
    index = 0
    draw = sorted(draw)
    for i in range(m):
        index += gmpy2.bincoef(draw[i] - 1, i + 1)
    return index
Esempio n. 6
0
from gmpy2 import bincoef
from gmpy2 import next_prime

numbers = set()
for n in range(50):
    for i in range(n + 1):
        numbers.add(bincoef(n, i))
maxnum = max(numbers)

p = 2
while p * p < max(numbers):
    numbers = [x for x in numbers if x % (p * p) != 0]
    p = next_prime(p)
total = sum(numbers)
print(total)
def main():

    # Test local versions of libraries

    utils.test_python_version()
    utils.test_gmpy2_version()

    # Parse command line arguments
    
    parser = argparse.ArgumentParser(description="From a table of draws, output a seed of appropriate length.")

    parser.add_argument("input_draw_file", help="""Text file with draws.""")
    parser.add_argument("output_seed_file", help="""JSON file where we can store the seed computed from the draws.""")
    parser.add_argument("entropy_to_gather", help="""Minimum entropy to extract before drawing lone bits.""")
    parser.add_argument("--nbr_lone_bits", type=int, help="""Number of lone bits to extract.""", default=0)
    
    args = parser.parse_args()


    # Check arguments
    
    output_seed_file = args.output_seed_file
    if os.path.exists(output_seed_file):
        utils.exit_error("The output file '%s' already exists. Exiting."%(output_seed_file))


    # Declare a few important variables
    
    two_pow_entropy_to_gather = (1<<int(args.entropy_to_gather))
    
    seed = 0
    L = 1 # before lone bits are drawn, seed lies in [0,L - 1]

    lone_bits_part = 0
    nbr_lone_bits = args.nbr_lone_bits


    # Scan the input file, construct the seed
    
    with open(args.input_draw_file, "r") as f:
        
        for line in f:

            if not line or line.strip() == "" or line.startswith("#"):
                continue

            (draw_id, m, n, draw) = re.split("\s+", line.strip(), maxsplit=3)

            if draw == "None":
                continue
            
            m = int(m)
            n = int(n)
            draw = [ int(x) for x in draw.split(",") ]
            index = index_from_draw(draw,m)

            if L < two_pow_entropy_to_gather:
                
                print("Draw %s used to extract entropy"%(draw_id))
                seed = gmpy2.bincoef(n,m)*seed + index
                L *= gmpy2.bincoef(n,m)
                
            else:
                
                print("Draw %s used to extract a lone bit"%(draw_id))
                b = index & 1
                seed += L * (b << (args.nbr_lone_bits - nbr_lone_bits))
                nbr_lone_bits -= 1

            if L >= two_pow_entropy_to_gather and nbr_lone_bits == 0:
                break

    if nbr_lone_bits > 0 or L < two_pow_entropy_to_gather:
        utils.exit_error("There wasn't enough draws to collect to request quantity of entropy and lone bits.")

    seed_upper_bound = L * 2**(args.nbr_lone_bits)
    seed_entropy = math.floor(gmpy2.log2(seed_upper_bound))
    print("The seed contains more than %d bits of entropy (including the %s lone bits)."%(seed_entropy,args.nbr_lone_bits))
    print("The seed is %d"%(seed))

    print("Saving the seed to %s"%(output_seed_file))
    with open(output_seed_file, "w") as f:
        json.dump({"seed": int(seed),
                   "seed_upper_bound": int(seed_upper_bound),
                   "approx_seed_entropy": int(seed_entropy),
                   "lone_bits": int(args.nbr_lone_bits)}, 
                  f,
                  sort_keys=True)
def index_from_draw(draw,m):
    index = 0
    draw = sorted(draw)
    for i in range(m):
        index += gmpy2.bincoef(draw[i]-1, i+1)
    return index
Esempio n. 9
0
 def __call__(self, i):
     return gmpy2.mpz(gmpy2.round_away(gmpy2.bincoef(2 * i, i) / (i + 1)))
Esempio n. 10
0
from gmpy2 import bincoef

count_greater = 0
for n in range(1, 101):
    for r in range(n):
        if bincoef(n, r) > 10**6:
            count_greater += 1
print(count_greater)
Esempio n. 11
0
# -*- coding: utf-8 -*-

#from decimal import Decimal, getcontext

#getcontext().prec = 1000000

#print sum(1/Decimal(16)**k *
#(Decimal(4)/(8*k+1) -
#Decimal(2)/(8*k+4) -
#Decimal(1)/(8*k+5) -
#Decimal(1)/(8*k+6)) for k in range(100))

import gmpy2
# See https://gmpy2.readthedocs.org/en/latest/mpfr.html
gmpy2.get_context().precision = 10000
pi = 0
for n in range(1000000):
    # Formula from http://en.wikipedia.org/wiki/Calculating_pi#Arctangent
    numer = pow(2, n + 1)
    denom = gmpy2.bincoef(n + n, n) * (n + n + 1)
    frac = gmpy2.mpq(numer, denom)
    pi += frac
    # Print every 1000 iterations
    if n % 1000 == 0:
        print(gmpy2.mpfr(pi))