diff --git a/cfg_utils.py b/cfg_utils.py index 8eb1795eb86b2fecab3c461f85ac009af5c7f49f..bf4c9b52926ca6b5abf372288d519fc389bc26ad 100644 --- a/cfg_utils.py +++ b/cfg_utils.py @@ -1,5 +1,4 @@ import collections - import functools import random from enum import * @@ -504,6 +503,29 @@ class CFGBoltzmann: # Now we do generation of the strings. + # This returns an *index* (not the item at the index) from a list, weighted + # by the integer at each element. + + def normalized_choice(self, inlist): + total_weight = sum(inlist) + weights = [x / total_weight for x in inlist] + choice = random.choices(range(len(inlist)), weights=weights) + return choice + + + # Similar to Fzero and Fprim, we have Gzero and Gprim. + + def Gzero(self, nonterminal_index, requested_length): + possibilities = self.Fzero(nonterminal_index, requested_length) + chosen_production = self.normalized_choice(possibilities) + generated_string - self.Gprim(nonterminal_index, chosen_production, 1, requested_length) + + + + + + + z = CFGBoltzmann(rules, list_of_nonterminals, list_of_terminals)