From 92ea3f3b032ad64c2ae39230fcf570b03b910b8c Mon Sep 17 00:00:00 2001 From: Kia <kia@special-circumstanc.es> Date: Mon, 17 Aug 2020 13:34:03 -0600 Subject: [PATCH] Gzero and normalized_choice --- cfg_utils.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/cfg_utils.py b/cfg_utils.py index 8eb1795..bf4c9b5 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) -- GitLab