Esempio n. 1
0
def test_spearman_corr():
    prng = SHA256(42)
    x = np.array([2, 4, 6, 8, 10])
    y = np.array([1, 3, 5, 6, 9])
    xorder = np.array([1, 2, 3, 4, 5])
    res1 = corr(xorder, xorder, seed=prng)

    prng = SHA256(42)
    res2 = spearman_corr(x, y, seed=prng)
    assert_equal(res1[0], res2[0])
    assert_equal(res1[1], res2[1])
    assert_array_equal(res1[2], res2[2])
Esempio n. 2
0
 def test_get_permute(self):
     """
         This function is to test get_permute function. For each k, the length of return value should
         be less and equal than k.
     
     """
     r = SHA256(seed=123456)
     self.assertEqual(len(get_permute(5,r=r)), 5)
     self.assertEqual(len(get_permute(360,r=r)), 360)
     self.assertEqual(len(get_permute(77,r=r)), 77)
     r = SHA256(seed=123456)
     self.assertEqual(get_permute(256,r=r)[:5], [True, True, False, False, False])
Esempio n. 3
0
def test_spearman_corr():
    prng = SHA256(42)
    x = np.array([2, 4, 6, 8, 10])
    y = np.array([1, 3, 5, 6, 9])
    xorder = np.array([1, 2, 3, 4, 5])
    res1 = corr(xorder, xorder, seed=prng)
    print("finished test 1 in test_spearman_corr()")

    prng = SHA256(42)
    res2 = spearman_corr(x, y, seed=prng)
    assert res1[0] == res2[0]
    assert res1[1] == res2[1]
    np.testing.assert_array_equal(res1[2], res2[2])
    print("finished test 2 in test_spearman_corr()")
Esempio n. 4
0
def test_corr():
    prng = SHA256(42)
    x = prng.randint(0, 5, size=10)
    y = x
    res1 = corr(x, y, seed=prng)
    res2 = corr(x, y)
    assert len(res1) == 3
    assert len(res2) == 3
    assert res1[0] == 1
    assert res2[0] == 1
    np.testing.assert_almost_equal(res1[1], res2[1], decimal=1)
    print("finished test 1 in test_corr()")

    y = prng.randint(0, 5, size=10)
    res1 = corr(x, y, alternative="less", seed=prng)
    res2 = corr(x, y, alternative="less")
    assert len(res1) == 3
    assert len(res2) == 3
    assert res1[0] == res2[0]
    np.testing.assert_almost_equal(res1[1], res2[1], decimal=1)
    print("finished test 2 in test_corr()")

    res1 = corr(x, y, alternative="two-sided", seed=prng)
    res2 = corr(x, y, alternative="greater")
    assert len(res1) == 3
    assert len(res2) == 3
    assert res1[0] == res2[0]
    np.testing.assert_almost_equal(res1[1], res2[1] * 2, decimal=1)
    print("finished test 3 in test_corr()")
Esempio n. 5
0
    def __init__(self, audit_type, seed, risk_limit, contests):
        """
        Initializes PRNG, computes margins, and returns initial sample
        sizes parameterized by likelihood that the initial sample will confirm the
        election result, assuming no discrpancies.

        Inputs:
            seed - seed used to initialized random functions
            risk_limit - the risk-limit to compute sample sizes from
            contests - dictionary of targeted contests. Maps:
                        {
                            contest: {
                                candidate1: votes,
                                candidate2: votes,
                                ...
                                'ballots': ballots, # total ballots cast
                                'winners': winners # number of winners in this contest
                            }
                            ...
                        }

        Outputs:
        """
        self.seed = seed
        self.prng = SHA256(seed)
        self.contests = contests
        self.margins = self.compute_margins()

        if audit_type == 'BRAVO':
            self.audit = BRAVO(risk_limit)
Esempio n. 6
0
def test_get_random_state():
    prng1 = RandomState(42)
    prng2 = get_prng(42)
    prng3 = get_prng(prng1)
    prng4 = get_prng(prng2)
    prng5 = get_prng()
    prng6 = get_prng(None)
    prng7 = get_prng(np.random)
    prng8 = get_prng(SHA256(42))
    assert (isinstance(prng1, RandomState))
    assert (isinstance(prng2, SHA256))
    assert (isinstance(prng3, RandomState))
    assert (isinstance(prng4, SHA256))
    assert (isinstance(prng5, SHA256))
    assert (isinstance(prng6, SHA256))
    assert (isinstance(prng7, RandomState))
    x1 = prng1.randint(0, 5, size=10)
    x2 = prng2.randint(0, 5, size=10)
    x3 = prng3.randint(0, 5, size=10)
    x4 = prng4.randint(0, 5, size=10)
    x5 = prng5.randint(0, 5, size=10)
    x6 = prng6.randint(0, 5, size=10)
    x7 = prng7.randint(0, 5, size=10)
    x8 = prng8.randint(0, 5, size=10)
    assert_equal(x2, x8)
    assert_equal(prng2.counter, 1)
    assert_equal(prng2.baseseed, 42)
    assert_equal(prng2.baseseed, prng4.baseseed)
    assert_equal(len(x5), 10)
    assert_equal(len(x6), 10)
    assert_equal(len(x7), 10)
Esempio n. 7
0
def test_corr():
    prng = SHA256(42)
    x = prng.randint(0, 5, size=10)
    y = x
    res1 = corr(x, y, seed=prng)
    res2 = corr(x, y)
    assert_equal(len(res1), 3)
    assert_equal(len(res2), 3)
    assert_equal(res1[0], 1)
    assert_equal(res2[0], 1)
    assert_almost_equal(res1[1], res2[1], decimal=1)

    y = prng.randint(0, 5, size=10)
    res1 = corr(x, y, alternative="less", seed=prng)
    res2 = corr(x, y, alternative="less")
    assert_equal(len(res1), 3)
    assert_equal(len(res2), 3)
    assert_equal(res1[0], res2[0])
    assert_almost_equal(res1[1], res2[1], decimal=1)

    res1 = corr(x, y, alternative="two-sided", seed=prng)
    res2 = corr(x, y, alternative="greater")
    assert_equal(len(res1), 3)
    assert_equal(len(res2), 3)
    assert_equal(res1[0], res2[0])
    assert_almost_equal(res1[1], res2[1] * 2, decimal=1)
Esempio n. 8
0
def get_prng(seed=None):
    """Turn seed into a cryptorandom instance

    Parameters
    ----------
    seed : {None, int, str, RandomState}
        If seed is None, return generate a pseudo-random 63-bit seed using np.random
        and return a new SHA256 instance seeded with it.
        If seed is a number or str, return a new cryptorandom instance seeded with seed.
        If seed is already a numpy.random RandomState or SHA256 instance, return it.
        Otherwise raise ValueError.

    Returns
    -------
    RandomState
    """
    if seed is None:
        seed = np.random.randint(0, 10**10)  # generate an integer
    if seed is np.random:
        return np.random.mtrand._rand
    if isinstance(seed, (int, np.integer, float, str)):
        return SHA256(seed)
    if isinstance(seed, (np.random.RandomState, SHA256)):
        return seed
    raise ValueError('%r cannot be used to seed cryptorandom' % seed)
Esempio n. 9
0
def test_geometric_generation():
    ss = SHA256(12345)
    runifs = ss.random(10000)
    p = 0.5
    rvs = list(map(lambda u: int(1 + np.log(u) / np.log(1 - p)), runifs))
    np.testing.assert_almost_equal(np.mean(rvs), 1 / p,
                                   1)  # expected value of geometric(p)
Esempio n. 10
0
def test_get_random_state():
    """Random State Test."""
    prng1 = np.random.RandomState(42)
    prng2 = get_prng(42)
    prng3 = get_prng(prng1)
    prng4 = get_prng(prng2)
    prng5 = get_prng()
    prng6 = get_prng(None)
    prng7 = get_prng(np.random)
    prng8 = get_prng(SHA256(42))
    assert (isinstance(prng1, np.random.RandomState))
    assert (isinstance(prng2, SHA256))
    assert (isinstance(prng3, np.random.RandomState))
    assert (isinstance(prng4, SHA256))
    assert (isinstance(prng5, SHA256))
    assert (isinstance(prng6, SHA256))
    assert (isinstance(prng7, np.random.RandomState))
    x1 = prng1.randint(0, 5, size=10)
    x2 = prng2.randint(0, 5, size=10)
    x3 = prng3.randint(0, 5, size=10)
    x4 = prng4.randint(0, 5, size=10)
    x5 = prng5.randint(0, 5, size=10)
    x6 = prng6.randint(0, 5, size=10)
    x7 = prng7.randint(0, 5, size=10)
    x8 = prng8.randint(0, 5, size=10)
    np.testing.assert_equal(x2, x8)
    assert prng2.counter == 1
    assert prng2.baseseed == 42
    assert prng2.baseseed == prng4.baseseed
    assert len(x5) == 10
    assert len(x6) == 10
    assert len(x7) == 10
Esempio n. 11
0
def test_permute_rows():
    prng = SHA256(42)

    x = prng.randint(0, 10, size=20).reshape(2, 10)
    actual = permute_rows(x, prng)
    expected = np.array([[9, 1, 8, 6, 9, 1, 5, 4, 3, 6],
                         [1, 7, 2, 1, 9, 7, 8, 7, 8, 1]])
    np.testing.assert_array_equal(actual, expected)

    a = permute_rows(x)
    np.testing.assert_equal(a.max(), 9)
    np.testing.assert_equal(a.min(), 1)
Esempio n. 12
0
def test_permute():
    prng = SHA256(42)

    x = prng.randint(0, 10, size=20)
    actual = permute(x, prng)
    expected = np.array(
        [6, 9, 5, 1, 3, 1, 4, 7, 6, 9, 8, 7, 2, 1, 9, 7, 8, 1, 8, 1])
    np.testing.assert_array_equal(actual, expected)

    actual = permute(x)
    np.testing.assert_equal(actual.max(), 9)
    np.testing.assert_equal(actual.min(), 1)
Esempio n. 13
0
def test_sim_corr():
    prng = SHA256(42)
    x = prng.random(10)
    y = x
    group = prng.randint(0, 3, size=10)
    res1 = sim_corr(x, y, group, seed=prng, reps=100)
    res2 = sim_corr(x, y, group, seed=prng, alternative='less', reps=100)
    res3 = sim_corr(x, y, group, seed=prng, alternative='two-sided', reps=100)
    
    np.testing.assert_almost_equal(res1[0], 1-res2[0])
    assert res1[1] == res2[1]
    assert res1[1] == res3[1]
    assert 2*res1[0] == res3[0]
Esempio n. 14
0
def test_permute_within_group():
    """Group Permute Test."""
    x = np.repeat([1, 2, 3] * 3, 3)
    group = np.repeat([1, 2, 3], 9)

    res1 = permute_within_groups(x, group, seed=42)
    res2 = permute_within_groups(x, group, seed=SHA256(42))
    np.testing.assert_equal(res1, res2)

    res3 = permute_within_groups(x, group)
    np.testing.assert_equal(res3.max(), 3)
    res3.sort()
    np.testing.assert_equal(group, res3)
Esempio n. 15
0
def test_permute_within_group():
    x = np.repeat([1, 2, 3] * 3, 3)
    group = np.repeat([1, 2, 3], 9)
    #response = np.zeros_like(group)
    #response[[0,  1,  3,  9, 10, 11, 18, 19, 20]] = 1

    res1 = permute_within_groups(x, group, seed=42)
    res2 = permute_within_groups(x, group, seed=SHA256(42))
    np.testing.assert_equal(res1, res2)

    res3 = permute_within_groups(x, group)
    np.testing.assert_equal(res3.max(), 3)
    res3.sort()
    np.testing.assert_equal(group, res3)
def get_permute(k=360, r=SHA256(seed=123456)):
    """
        Args:
        k: number of the Bernoulli trials.
        r: random seed.
        Return:
        a list of boolean that indicate whether the nth YearMonth need to be permute or not
        """
    # generate an integer with k random bits.
    p = r.getrandbits(k)
    # split into a list of binary string
    binary = list(bin(p))[2:]

    # change into list of integer first in order to change it into boolean
    integer_list = list(map(int, binary))
    # change into list of boolean
    boolean = list(map(bool, integer_list))
    # length check, if it is smaller than k, there are 0s in the beginning so we manually add 0s
    while len(boolean) < k:
        boolean = [False] + boolean
    return boolean
Esempio n. 17
0
def geometric_skipping(population, p, seed):
    if isinstance(seed, int):
        ss = SHA256(seed)
    else:
        raise ValueError('%r cannot be used to seed SHA256 instance' % seed)

    n = len(population)
    sample = []
    m = int(n * p)
    #    rvs = geom.rvs(p=p, size=m) # this is what we'd do if we were using numpy.random
    runifs = ss.random(m)
    rvs = list(map(lambda u: int(1 + np.log(u) / np.log(1 - p)), runifs))
    val = np.cumsum(rvs) - 1
    for i in range(m):
        if val[i] < n:
            sample.append(population[val[i]])
        else:
            return sample
    index = val[-1]
    while index < (n - 1):
        index += int(1 + np.log(ss.random()) / np.log(1 - p))
        if index < n:
            sample.append(population[index])
    return sample
Esempio n. 18
0
 def SHA(x):
     v = SHA256(x)
     v = v.random(self.length_1)
     v = v[-(np.random.randint(0, len(v), 1))[0]]
     return v