natural language toolkit cooper storage for quantifier ambiguity c 20012023 nltk project ewan klein ewaninf ed ac uk url https www nltk org for license information see license txt a container for handling quantifier ambiguity via cooper storage param featstruct the value of the sem node in a tree from parsewithbindops type featstruct featstruct with features core and store return an iterator over the permutations of the input list type lst list rtype iter for perm storeperm in enumerateself permuteself store if trace printpermutation s perm 1 term self core for bindop in storeperm we just want the arguments that are wrapped by the bo predicate quant varex tuplebindop args use var to make an abstraction over the current term and then apply the quantifier to it term applicationexpression quant lambdaexpressionvarex variable term if trace print term term term simplify self readings appendterm def parsewithbindopssentence grammarnone trace0 if not grammar grammar grammarsbookgrammarsstorage fcfg parser loadparsergrammar tracetrace chartclassinstantiatevarschart parse the sentence tokens sentence split return listparser parsetokens def demo from nltk sem import cooperstorage as cs sentence every girl chases a dog sentence a man gives a bone to every dog print printanalysis of sentence s sentence print 50 trees cs parsewithbindopssentence trace0 for tree in trees semrep cs cooperstoretree labelsem print printbinding operators print 15 for s in semrep store prints print printcore print 15 printsemrep core print printsretrieval print 15 semrep sretrievetracetrue printreadings print 15 for i reading in enumeratesemrep readings printfi 1 reading if name main demo natural language toolkit cooper storage for quantifier ambiguity c 2001 2023 nltk project ewan klein ewan inf ed ac uk url https www nltk org for license information see license txt a container for handling quantifier ambiguity via cooper storage param featstruct the value of the sem node in a tree from parse_with_bindops type featstruct featstruct with features core and store return an iterator over the permutations of the input list type lst list rtype iter carry out s retrieval of binding operators in store if hack true serialize the bindop and core as strings and reparse ugh each permutation of the store i e list of binding operators is taken to be a possible scoping of quantifiers we iterate through the binding operators in each permutation and successively apply them to the current term starting with the core semantic representation working from the inside out binding operators are of the form bo p all x man x p x z1 we just want the arguments that are wrapped by the bo predicate use var to make an abstraction over the current term and then apply the quantifier to it use a grammar with binding operators to parse a sentence parse the sentence sentence a man gives a bone to every dog
from nltk.parse import load_parser
from nltk.parse.featurechart import InstantiateVarsChart
from nltk.sem.logic import ApplicationExpression, LambdaExpression, Variable


class CooperStore:
    

    def __init__(self, featstruct):
        
        self.featstruct = featstruct
        self.readings = []
        try:
            self.core = featstruct["CORE"]
            self.store = featstruct["STORE"]
        except KeyError:
            print("%s is not a Cooper storage structure" % featstruct)

    def _permute(self, lst):
        
        remove = lambda lst0, index: lst0[:index] + lst0[index + 1 :]
        if lst:
            for index, x in enumerate(lst):
                for y in self._permute(remove(lst, index)):
                    yield (x,) + y
        else:
            yield ()

    def s_retrieve(self, trace=False):
        r
        for perm, store_perm in enumerate(self._permute(self.store)):
            if trace:
                print("Permutation %s" % (perm + 1))
            term = self.core
            for bindop in store_perm:
                
                quant, varex = tuple(bindop.args)
                
                
                term = ApplicationExpression(
                    quant, LambdaExpression(varex.variable, term)
                )
                if trace:
                    print("  ", term)
                term = term.simplify()
            self.readings.append(term)


def parse_with_bindops(sentence, grammar=None, trace=0):
    
    if not grammar:
        grammar = "grammars/book_grammars/storage.fcfg"
    parser = load_parser(grammar, trace=trace, chart_class=InstantiateVarsChart)
    
    tokens = sentence.split()
    return list(parser.parse(tokens))


def demo():
    from nltk.sem import cooper_storage as cs

    sentence = "every girl chases a dog"
    
    print()
    print("Analysis of sentence '%s'" % sentence)
    print("=" * 50)
    trees = cs.parse_with_bindops(sentence, trace=0)
    for tree in trees:
        semrep = cs.CooperStore(tree.label()["SEM"])
        print()
        print("Binding operators:")
        print("-" * 15)
        for s in semrep.store:
            print(s)
        print()
        print("Core:")
        print("-" * 15)
        print(semrep.core)
        print()
        print("S-Retrieval:")
        print("-" * 15)
        semrep.s_retrieve(trace=True)
        print("Readings:")
        print("-" * 15)

        for i, reading in enumerate(semrep.readings):
            print(f"{i + 1}: {reading}")


if __name__ == "__main__":
    demo()