Esempio n. 1
0
    def _read_depgraph(node, depgraph, label_counter=None, parent=None):
        if not label_counter:
            label_counter = Counter()

        if node['rel'].lower() in ['spec', 'punct']:
            # the value of a 'spec' entry is a word, not an FStructure
            return (node['word'], node['tag'])

        else:
            fstruct = FStructure()
            fstruct.pred = None
            fstruct.label = FStructure._make_label(label_counter.get())

            fstruct.parent = parent

            word, tag = node['word'], node['tag']
            if tag[:2] == 'VB':
                if tag[2:3] == 'D':
                    fstruct.safeappend('tense', ('PAST', 'tense'))
                fstruct.pred = (word, tag[:2])

            if not fstruct.pred:
                fstruct.pred = (word, tag)

            children = [
                depgraph.nodes[idx] for idx in chain(*node['deps'].values())
            ]
            for child in children:
                fstruct.safeappend(
                    child['rel'],
                    FStructure._read_depgraph(child, depgraph, label_counter,
                                              fstruct),
                )

            return fstruct
Esempio n. 2
0
 def skolemise(self):
     """
     Perform a simple Skolemisation operation.  Existential quantifiers are
     simply dropped and all variables they introduce are renamed so that
     they are unique.
     """
     return self._skolemise(set(), Counter())
Esempio n. 3
0
    def _read_depgraph(node, depgraph, label_counter=None, parent=None):
        if not label_counter:
            label_counter = Counter()

        if node["rel"].lower() in ["spec", "punct"]:
            # the value of a 'spec' entry is a word, not an FStructure
            return (node["word"], node["tag"])

        else:
            fstruct = FStructure()
            fstruct.pred = None
            fstruct.label = FStructure._make_label(label_counter.get())

            fstruct.parent = parent

            word, tag = node["word"], node["tag"]
            if tag[:2] == "VB":
                if tag[2:3] == "D":
                    fstruct.safeappend("tense", ("PAST", "tense"))
                fstruct.pred = (word, tag[:2])

            if not fstruct.pred:
                fstruct.pred = (word, tag)

            children = [
                depgraph.nodes[idx] for idx in chain(*node["deps"].values())
            ]
            for child in children:
                fstruct.safeappend(
                    child["rel"],
                    FStructure._read_depgraph(child, depgraph, label_counter,
                                              fstruct),
                )

            return fstruct
Esempio n. 4
0
 def compile(self, counter=None):
     """From Iddo Lev's PhD Dissertation p108-109"""
     if not counter:
         counter = Counter()
     (compiled_glue,
      new_forms) = self.glue.simplify().compile_pos(counter, self.__class__)
     return new_forms + [
         self.__class__(self.meaning, compiled_glue, set([counter.get()]))
     ]
Esempio n. 5
0
 def to_glueformula_list(self, depgraph, node=None, counter=None, verbose=False):
     if node is None:
         top = depgraph.nodelist[0]
         root = depgraph.nodelist[top['deps'][0]]
         return self.to_glueformula_list(depgraph, root, Counter(), verbose)
     
     glueformulas = self.lookup(node, depgraph, counter)
     for dep_idx in node['deps']:
         dep = depgraph.nodelist[dep_idx]
         glueformulas.extend(self.to_glueformula_list(depgraph, dep, counter, verbose))
     return glueformulas
Esempio n. 6
0
    def gfl_to_compiled(self, gfl):
        index_counter = Counter()
        return_list = []
        for gf in gfl:
            return_list.extend(gf.compile(index_counter))

        if self.verbose:
            print("Compiled Glue Premises:")
            for cgf in return_list:
                print(cgf)

        return return_list
Esempio n. 7
0
    def to_glueformula_list(self, depgraph, node=None, counter=None, verbose=False):
        if node is None:
            # TODO: should it be depgraph.root? Is this code tested?
            top = depgraph.nodes[0]
            depList = sum(list(top['deps'].values()), [])
            root = depgraph.nodes[depList[0]]

            return self.to_glueformula_list(depgraph, root, Counter(), verbose)

        glueformulas = self.lookup(node, depgraph, counter)
        for dep_idx in sum(list(node['deps'].values()), []):
            dep = depgraph.nodes[dep_idx]
            glueformulas.extend(self.to_glueformula_list(depgraph, dep, counter, verbose))
        return glueformulas
Esempio n. 8
0
    def to_glueformula_list(self,
                            depgraph,
                            node=None,
                            counter=None,
                            verbose=False):
        if node is None:
            top = depgraph.nodes[0]
            depList = sum(list(top['deps'].values()), [])
            root = depgraph.nodes[depList[0]]
            #print (root)
            return self.to_glueformula_list(depgraph, root, Counter(), verbose)

        glueformulas = self.lookup(node, depgraph, counter)
        for dep_idx in sum(list(node['deps'].values()), []):
            dep = depgraph.nodes[dep_idx]
            glueformulas.extend(
                self.to_glueformula_list(depgraph, dep, counter, verbose))
        return glueformulas
Esempio n. 9
0
class InstantiateVarsChart(Chart):
    """
    A specialized chart that 'instantiates' variables whose names
    start with '@', by replacing them with unique new variables.
    In particular, whenever a complete edge is added to the chart, any
    variables in the edge's C{lhs} whose names start with '@' will be
    replaced by unique new L{IndVariable}s.
    """
    def __init__(self, tokens):
        Chart.__init__(self, tokens)
        self._instantiated = set()

    def insert(self, edge, child_pointer_list):
        if edge in self._instantiated: return False
        edge = self.instantiate_edge(edge)
        return Chart.insert(self, edge, child_pointer_list)

    def instantiate_edge(self, edge):
        # If the edge is a leaf, or is not complete, or is
        # already in the chart, then just return it as-is.
        if not isinstance(edge, FeatureTreeEdge): return edge
        if not edge.is_complete(): return edge
        if edge in self._edge_to_cpls: return edge

        # Get a list of variables that need to be instantiated.
        # If there are none, then return the edge as-is.
        inst_vars = self.inst_vars(edge)
        if not inst_vars: return edge

        # Instantiate the edge!
        self._instantiated.add(edge)
        lhs = edge.lhs().substitute_bindings(inst_vars)
        return FeatureTreeEdge(edge.span(), lhs, edge.rhs(), edge.dot(),
                               edge.bindings())

    counter = Counter(100)

    def inst_vars(self, edge):
        return dict((var, unique_variable(self.counter).variable)
                    for var in edge.lhs().variables()
                    if var.name.startswith('@'))
Esempio n. 10
0
    AllExpression,
    NegatedExpression,
    ExistsExpression,
    Variable,
    ImpExpression,
    AndExpression,
    unique_variable,
    LambdaExpression,
    IffExpression,
    OrExpression,
    FunctionVariableExpression,
)

from nltk.inference.api import Prover, BaseProverCommand

_counter = Counter()


class ProverParseError(Exception):
    pass


class TableauProver(Prover):
    _assume_false = False

    def _prove(self, goal=None, assumptions=None, verbose=False):
        if not assumptions:
            assumptions = []

        result = None
        try:
Esempio n. 11
0
 def parse(self, data, signature=None):
     self._label_counter = Counter(-1)
     return DrtParser.parse(self, data, signature)
Esempio n. 12
0
class VariableBinderExpression(Expression):
    """A variable binding expression: e.g. \\x.M."""

    # for generating "unique" variable names during alpha conversion.
    _counter = Counter()

    def __init__(self, variable, term):
        Expression.__init__(self)
        assert isinstance(variable, Variable)
        assert isinstance(term, Expression)
        self.variable = variable
        self.term = term
        self.prefix = self.__class__.PREFIX.rstrip()
        self.binder = (self.prefix, self.variable.name)
        self.body = str(self.term)

    # nb: __ne__ defined by Expression
    def __eq__(self, other):
        r"""
        Defines equality modulo alphabetic variance.

        If we are comparing \x.M  and \y.N, then
        check equality of M and N[x/y].
        """
        if self.__class__ == other.__class__:
            if self.variable == other.variable:
                return self.term == other.term
            else:
                # Comparing \x.M  and \y.N.
                # Relabel y in N with x and continue.
                relabeled = self._relabel(other)
                return self.term == relabeled
        else:
            return False

    def _relabel(self, other):
        """
        Relabel C{other}'s bound variables to be the same as C{self}'s
        variable.
        """
        var = VariableExpression(self.variable)
        return other.term.replace(other.variable, var)

    def variables(self):
        vars = [self.variable]
        for var in self.term.variables():
            if var not in vars: vars.append(var)
        return vars

    def free(self):
        return self.term.free().difference(set([self.variable]))

    def subterms(self):
        return self.term.subterms().union([self])

    def replace(self, variable, expression, replace_bound=False):
        if self.variable == variable:
            if not replace_bound: return self
            else:
                return self.__class__(
                    expression, self.term.replace(variable, expression, True))
        if replace_bound or self.variable in expression.free():
            v = 'z' + str(self._counter.get())
            if not replace_bound: self = self.alpha_convert(Variable(v))
        return self.__class__(
            self.variable,
            self.term.replace(variable, expression, replace_bound))

    def alpha_convert(self, newvar):
        """
        Rename all occurrences of the variable introduced by this variable
        binder in the expression to @C{newvar}.
        """
        term = self.term.replace(self.variable, VariableExpression(newvar))
        return self.__class__(newvar, term)

    def simplify(self):
        return self.__class__(self.variable, self.term.simplify())

    def infixify(self):
        return self.__class__(self.variable, self.term.infixify())

    def __str__(self, continuation=0):
        # Print \x.\y.M as \x y.M.
        if continuation:
            prefix = ' '
        else:
            prefix = self.__class__.PREFIX
        if self.term.__class__ == self.__class__:
            return '%s%s%s' % (prefix, self.variable, self.term.__str__(1))
        else:
            return '%s%s.%s' % (prefix, self.variable, self.term)

    def __hash__(self):
        return hash(str(self.normalize()))