def testInverse(self):
        random_variable = probability.DiscreteRandomVariable({
            1: 1,
            2: 3,
            3: 4
        })
        inverse = random_variable.inverse(probability.DiscreteEvent({1, 3}))
        self.assertEqual(inverse.values, {1, 2})

        random_variable = probability.DiscreteRandomVariable({1: 1, 2: 1})
        inverse = random_variable.inverse(probability.DiscreteEvent({1, 5}))
        self.assertEqual(inverse.values, {1, 2})
 def testCall(self):
     random_variable = probability.DiscreteRandomVariable({
         1: 1,
         2: 3,
         3: 4
     })
     forwards = random_variable(probability.DiscreteEvent({1, 3}))
     self.assertEqual(forwards.values, {1, 4})
Esempio n. 3
0
def _sample_letter_bag(is_train, min_total):
    """Samples a "container of letters" and returns info on it."""
    while True:
        num_distinct_letters = random.randint(1, _MAX_DISTINCT_LETTERS)
        num_letters_total = random.randint(
            max(num_distinct_letters, min_total),
            min(_MAX_TOTAL_LETTERS, num_distinct_letters * _MAX_LETTER_REPEAT))
        letter_counts = combinatorics.uniform_positive_integers_with_sum(
            num_distinct_letters, num_letters_total)

        # Test/train split.
        if (is_train is None or train_test_split.is_train(
                sorted(letter_counts)) == is_train):
            break

    letters_distinct = random.sample(_LETTERS, num_distinct_letters)
    weights = {i: 1 for i in range(num_letters_total)}

    letters_with_repetition = []
    for letter, count in zip(letters_distinct, letter_counts):
        letters_with_repetition += [letter] * count
    random.shuffle(letters_with_repetition)

    random_variable = probability.DiscreteRandomVariable(
        {i: letter
         for i, letter in enumerate(letters_with_repetition)})

    if random.choice([False, True]):
        bag_contents = ''.join(letters_with_repetition)
    else:
        letters_and_counts = [
            '{}: {}'.format(letter, count)
            for letter, count in zip(letters_distinct, letter_counts)
        ]
        bag_contents = '{' + ', '.join(letters_and_counts) + '}'

    return LetterBag(weights=weights,
                     random_variable=random_variable,
                     letters_distinct=letters_distinct,
                     bag_contents=bag_contents)
 def _random_variable(self):
     rv1 = probability.DiscreteRandomVariable({1: 'a', 2: 'b', 3: 'c'})
     rv2 = probability.DiscreteRandomVariable({1: 'x', 2: 'y', 3: 'x'})
     return probability.FiniteProductRandomVariable((rv1, rv2))