Exemplo n.º 1
0
def demo():
    print('='*20 + 'TEST PARSE' + '='*20)
    dexpr = DrtExpression.fromstring
    print(dexpr(r'([x,y],[sees(x,y)])'))
    print(dexpr(r'([x],[man(x), walks(x)])'))
    print(dexpr(r'\x.\y.([],[sees(x,y)])'))
    print(dexpr(r'\x.([],[walks(x)])(john)'))
    print(dexpr(r'(([x],[walks(x)]) + ([y],[runs(y)]))'))
    print(dexpr(r'(([],[walks(x)]) -> ([],[runs(x)]))'))
    print(dexpr(r'([x],[PRO(x), sees(John,x)])'))
    print(dexpr(r'([x],[man(x), -([],[walks(x)])])'))
    print(dexpr(r'([],[(([x],[man(x)]) -> ([],[walks(x)]))])'))

    print('='*20 + 'Test fol()' + '='*20)
    print(dexpr(r'([x,y],[sees(x,y)])').fol())

    print('='*20 + 'Test alpha conversion and lambda expression equality' + '='*20)
    e1 = dexpr(r'\x.([],[P(x)])')
    print(e1)
    e2 = e1.alpha_convert(Variable('z'))
    print(e2)
    print(e1 == e2)

    print('='*20 + 'Test resolve_anaphora()' + '='*20)
    print(resolve_anaphora(dexpr(r'([x,y,z],[dog(x), cat(y), walks(z), PRO(z)])')))
    print(resolve_anaphora(dexpr(r'([],[(([x],[dog(x)]) -> ([y],[walks(y), PRO(y)]))])')))
    print(resolve_anaphora(dexpr(r'(([x,y],[]) + ([],[PRO(x)]))')))

    print('='*20 + 'Test pprint()' + '='*20)
    dexpr(r"([],[])").pprint()
    dexpr(r"([],[([x],[big(x), dog(x)]) -> ([],[bark(x)]) -([x],[walk(x)])])").pprint()
    dexpr(r"([x,y],[x=y]) + ([z],[dog(z), walk(z)])").pprint()
    dexpr(r"([],[([x],[]) | ([y],[]) | ([z],[dog(z), walk(z)])])").pprint()
    dexpr(r"\P.\Q.(([x],[]) + P(x) + Q(x))(\x.([],[dog(x)]))").pprint()
Exemplo n.º 2
0
    def _exampleList_store_selection(self, index):
        self._curExample = index
        example = self._examples[index]

        self._exampleList.selection_clear(0, 'end')
        if example:
            cache = self._readingCache[index]
            if cache:
                if isinstance(cache, list):
                    self._readings = cache
                    self._error = None
                else:
                    self._readings = []
                    self._error = cache
            else:
                try:
                    self._readings = self._glue.parse_to_meaning(example)
                    self._error = None
                    self._readingCache[index] = self._readings
                except Exception as e:
                    self._readings = []
                    self._error = DrtVariableExpression(Variable('Error: ' + str(e)))
                    self._readingCache[index] = self._error

                    #add a star to the end of the example
                    self._exampleList.delete(index)
                    self._exampleList.insert(index, ('  %s *' % example))
                    self._exampleList.config(height=min(len(self._examples), 25), width=40)

            self._populate_readingListbox()

            self._exampleList.selection_set(index)

            self._drs = None
            self._redraw()
Exemplo n.º 3
0
    def applyto(self, arg):
        """self = (\\x.(walk x), (subj -o f))
        arg  = (john        ,  subj)
        returns ((walk john),          f)
        """
        if self.indices & arg.indices:  # if the sets are NOT disjoint
            raise linearlogic.LinearLogicApplicationException(
                f"'{self}' applied to '{arg}'.  Indices are not disjoint."
            )
        else:  # if the sets ARE disjoint
            return_indices = self.indices | arg.indices

        try:
            return_glue = linearlogic.ApplicationExpression(
                self.glue, arg.glue, arg.indices
            )
        except linearlogic.LinearLogicApplicationException as e:
            raise linearlogic.LinearLogicApplicationException(
                f"'{self.simplify()}' applied to '{arg.simplify()}'"
            ) from e

        arg_meaning_abstracted = arg.meaning
        if return_indices:
            for dep in self.glue.simplify().antecedent.dependencies[
                ::-1
            ]:  # if self.glue is (A -o B), dep is in A.dependencies
                arg_meaning_abstracted = self.make_LambdaExpression(
                    Variable("v%s" % dep), arg_meaning_abstracted
                )
        return_meaning = self.meaning.applyto(arg_meaning_abstracted)

        return self.__class__(return_meaning, return_glue, return_indices)
Exemplo n.º 4
0
def combine_signatures_or_rename_preds(signatures, exprs, preferred_sig=None):
    """
    `signatures` is a list of dictionaries. Each dictionary has key-value
      pairs where key is a predicate name, and value is a type object.
    `exprs` are logical formula objects.
    This function return a single signature dictionary with merged signatures.
    If there is a predicate for which there are differing types, then the
    predicate is renamed and each version is associated to a different type
    in the signature dictionary. The target predicate is also renamed in
    the logical expressions.
    """
    assert len(signatures) == len(exprs)
    signatures_merged = {}
    exprs_new = []
    for i, (signature, expr) in enumerate(zip(signatures, exprs)):
        expr_new = expr
        for pred, typ in signature.items():
            if preferred_sig is not None and pred in preferred_sig:
                continue
            if pred not in signatures_merged:
                signatures_merged[pred] = typ
            else:
                if typ != signatures_merged[pred]:
                    pred_new = pred + '_' + str(i)
                    signatures_merged[pred_new] = typ
                    expr_new = expr_new.replace(Variable(pred),
                                                lexpr(pred_new))
        exprs_new.append(expr_new)
    return signatures_merged, exprs_new
Exemplo n.º 5
0
 def make_VariableExpression(self, name):
     if ":" in name:
         prefix = name.split(":")[0]
         if prefix in self._constant_type_prefixes:
             return TypedConstantExpression(Variable(name), self._constant_type_prefixes[prefix])
         else:
             raise RuntimeError(f"Unknown prefix: {prefix}. Did you forget to pass it to the constructor?")
     return super(DynamicTypeLogicParser, self).make_VariableExpression(name)
    def satisfiers(self, parsed, varex, g, trace=None, nesting=0):
        """
        Generate the entities from the model's domain that satisfy an open formula.

        :param parsed: an open formula
        :type parsed: Expression
        :param varex: the relevant free individual variable in ``parsed``.
        :type varex: VariableExpression or str
        :param g: a variable assignment
        :type g:  Assignment
        :return: a set of the entities that satisfy ``parsed``.
        """

        spacer = '   '
        indent = spacer + (spacer * nesting)
        candidates = []

        if isinstance(varex, string_types):
            var = Variable(varex)
        else:
            var = varex

        if var in parsed.free():
            if trace:
                print()
                print((spacer * nesting) +
                      "Open formula is '%s' with assignment %s" % (parsed, g))
            for u in self.domain:
                new_g = g.copy()
                new_g.add(var.name, u)
                if trace and trace > 1:
                    lowtrace = trace - 1
                else:
                    lowtrace = 0
                value = self.satisfy(parsed, new_g, lowtrace)

                if trace:
                    print(indent + "(trying assignment %s)" % new_g)

                # parsed == False under g[u/var]?
                if value == False:
                    if trace:
                        print(indent + "value of '%s' under %s is False" %
                              (parsed, new_g))

                # so g[u/var] is a satisfying assignment
                else:
                    candidates.append(u)
                    if trace:
                        print(indent + "value of '%s' under %s is %s" %
                              (parsed, new_g, value))

            result = set(c for c in candidates)
        # var isn't free in parsed
        else:
            raise Undefined("%s is not free in %s" % (var.name, parsed))

        return result
Exemplo n.º 7
0
 def interpret(self, ex):
     """
     :param ex: ``AbstractBoxerDrs``
     :return: ``AbstractDrs``
     """
     if isinstance(ex, BoxerDrs):
         drs = DRS([Variable('x%d' % r) for r in ex.refs],
                   map(self.interpret, ex.conds))
         if ex.label is not None:
             drs.label = Variable('x%d' % ex.label)
         if ex.consequent is not None:
             drs.consequent = self.interpret(ex.consequent)
         return drs
     elif isinstance(ex, BoxerNot):
         return DrtNegatedExpression(self.interpret(ex.drs))
     elif isinstance(ex, BoxerPred):
         pred = self._add_occur_indexing('%s_%s' % (ex.pos, ex.name), ex)
         return self._make_atom(pred, 'x%d' % ex.var)
     elif isinstance(ex, BoxerNamed):
         pred = self._add_occur_indexing('ne_%s_%s' % (ex.type, ex.name),
                                         ex)
         return self._make_atom(pred, 'x%d' % ex.var)
     elif isinstance(ex, BoxerRel):
         pred = self._add_occur_indexing('%s' % (ex.rel), ex)
         return self._make_atom(pred, 'x%d' % ex.var1, 'x%d' % ex.var2)
     elif isinstance(ex, BoxerProp):
         return DrtProposition(Variable('x%d' % ex.var),
                               self.interpret(ex.drs))
     elif isinstance(ex, BoxerEq):
         return DrtEqualityExpression(
             DrtVariableExpression(Variable('x%d' % ex.var1)),
             DrtVariableExpression(Variable('x%d' % ex.var2)))
     elif isinstance(ex, BoxerCard):
         pred = self._add_occur_indexing('card_%s_%s' % (ex.type, ex.value),
                                         ex)
         return self._make_atom(pred, 'x%d' % ex.var)
     elif isinstance(ex, BoxerOr):
         return DrtOrExpression(self.interpret(ex.drs1),
                                self.interpret(ex.drs2))
     elif isinstance(ex, BoxerWhq):
         drs1 = self.interpret(ex.drs1)
         drs2 = self.interpret(ex.drs2)
         return DRS(drs1.refs + drs2.refs, drs1.conds + drs2.conds)
     assert False, '%s: %s' % (ex.__class__.__name__, ex)
Exemplo n.º 8
0
def rename_guided(expr, resolution_guide):
    """
    resolution_guide is a dictionary whose keys are expressions
    and values are tuples (previous_pred, new_pred) that guide
    the renaming.
    """
    replacements = resolution_guide.get(expr, [])
    for prev_pred, new_pred in replacements:
        expr = expr.replace(Variable(prev_pred), lexpr(new_pred))
    return expr
Exemplo n.º 9
0
def get_rc_rules(rc, mainrole, mainnum, rc_index, bindings, inflections):
    s = ''
    rtype = rc['rtype']
    relrole = rc['role']
    relevent = rc['event'].name
    reltense = rc['event'].tense
    relpol = rc['event'].pol
    relpolx = rc['event'].polx
    relaspect = rc['event'].aspect
    if relrole == 'patient':
        if 'agent' in rc['event'].participants:
            ag = rc['event'].participants['agent']
            nps, rc_index, bindings = get_np_rules('%srelagent' % mainrole, ag,
                                                   rc_index, bindings,
                                                   inflections)
            s += nps
        if rtype == 'src':
            s += "RC[ROLE='%s']-> T VP[VOICE='passive',ASPECT = '%s',NUM=?nrc%s,HEAD='%s',POL='%s'] NP[ROLE='%srelagent']\n"\
            %(mainrole,relaspect,rc_index,relevent,relpol,mainrole)
            rcnum = mainnum
        elif rtype == 'orc':
            s += "RC[ROLE='%s']-> T NP[ROLE='%srelagent'] VP[VOICE='active',ASPECT = '%s',NUM=?nrc%s,HEAD='%s',POL='%s']\n"\
            %(mainrole,mainrole,relaspect,rc_index,relevent,relpol)
            rcnum = ag.num
    elif relrole == 'agent':
        if 'patient' in rc['event'].participants:
            pa = rc['event'].participants['patient']
            nps, rc_index, bindings = get_np_rules('%srelpatient' % mainrole,
                                                   pa, rc_index, bindings,
                                                   inflections)
            s += nps
            if rtype == 'src':
                s += "RC[ROLE='%s']-> T VP[VOICE='active',ASPECT = '%s',NUM=?nrc%s,HEAD='%s',POL='%s'] NP[ROLE='%srelpatient']\n"\
                %(mainrole,relaspect,rc_index,relevent,relpol,mainrole)
                rcnum = mainnum
            elif rtype == 'orc':
                s += "RC[ROLE='%s']->T NP[ROLE='%srelpatient'] VP[VOICE='passive',ASPECT='%s',NUM=?nrc%s,HEAD='%s',POL='%s'] \n"\
                %(mainrole,mainrole,relaspect,rc_index,relevent,relpol)
                rcnum = pa.num
        elif rc['event'].frame == 'intransitive':
            s += "RC[ROLE='%s']-> T VP[VOICE='active',ASPECT = '%s',NUM=?nrc%s,HEAD='%s',POL='%s']\n"\
            %(mainrole,relaspect,rc_index,relevent,relpol)
            rcnum = mainnum

    vps = get_vp_rules(relevent, reltense, relpol, relpolx, rel_index=rc_index)
    s += vps

    vrs = get_verb_rules(relevent, inflections)
    s += vrs

    bindings[Variable('?nrc%s' % rc_index)] = rcnum
    rc_index += 1

    return s, rc_index, bindings
Exemplo n.º 10
0
    def find_answers(self, verbose=False):
        self.prove(verbose)

        answers = set()
        answer_ex = VariableExpression(Variable(ResolutionProver.ANSWER_KEY))
        for clause in self._clauses:
            for term in clause:
                if isinstance(term, ApplicationExpression) and\
                   term.function == answer_ex and\
                   not isinstance(term.argument, IndividualVariableExpression):
                    answers.add(term.argument)
        return answers
Exemplo n.º 11
0
def test_valid_lambda_expr():
    """
  Regression test: valid_lambda_expr was rejecting this good sub-expression at c720b4
  """
    ontology = _make_mock_ontology()
    eq_(
        ontology._valid_lambda_expr(
            Expression.fromstring(r"\b.ltzero(cmp_pos(ax_x,a,b))"),
            ctx_bound_vars=()), False)
    eq_(
        ontology._valid_lambda_expr(
            Expression.fromstring(r"\b.ltzero(cmp_pos(ax_x,a,b))"),
            ctx_bound_vars=(Variable('a'), )), True)
Exemplo n.º 12
0
 def _attempt_proof_app(self, current, context, agenda, accessible_vars, atoms, debug):
     f, args = current.uncurry()
     for i, arg in enumerate(args):
         if not TableauProver.is_atom(arg):
             ctx = f
             nv = Variable('X%s' % _counter.get())
             for j,a in enumerate(args):
                 ctx = (ctx(VariableExpression(nv)) if i == j else ctx(a))
             if context:
                 ctx = context(ctx).simplify()
             ctx = LambdaExpression(nv, ctx)
             agenda.put(arg, ctx)
             return self._attempt_proof(agenda, accessible_vars, atoms, debug+1)
     raise Exception('If this method is called, there must be a non-atomic argument')
Exemplo n.º 13
0
def replace_function_names(expr, resolution_guide, active=None):
    if active is None:
        active = {}
    else:
        active = dict(active)
    if expr in resolution_guide:
        for prev_pred, new_pred in resolution_guide[expr]:
            active[prev_pred] = new_pred
    if isinstance(expr, ConstantExpression) or \
       isinstance(expr, AbstractVariableExpression) or \
       isinstance(expr, Variable):
        return expr
    elif isinstance(expr, NegatedExpression):
        expr.term = replace_function_names(expr.term, resolution_guide, active)
        return expr
    elif isinstance(expr, BinaryExpression):
        child_exprs = [expr.first, expr.second]
        exprs = [
            replace_function_names(e, resolution_guide, active)
            for e in child_exprs
        ]
        expr.first = exprs[0]
        expr.second = exprs[1]
    elif isinstance(expr, ApplicationExpression):
        func, args = expr.uncurry()
        if str(func) in active:
            func = type(func)(Variable(active[str(func)]))
        args_exprs = [
            replace_function_names(e, resolution_guide, active) for e in args
        ]
        exprs = [func] + args_exprs
        expr = functools.reduce(lambda f, a: ApplicationExpression(f, a),
                                exprs)
    elif isinstance(expr, VariableBinderExpression):
        child_exprs = [expr.variable, expr.term]
        exprs = [
            replace_function_names(e, resolution_guide, active)
            for e in child_exprs
        ]
        expr.variable = exprs[0]
        expr.term = exprs[1]
    else:
        raise NotImplementedError(
            'Expression not recognized: {0}, type: {1}'.format(
                expr, type(expr)))
    return expr
Exemplo n.º 14
0
def demo():
    print '=' * 20 + 'TEST PARSE' + '=' * 20
    parser = DrtParser()
    print parser.parse(r'([x,y],[sees(x,y)])')
    print parser.parse(r'([x],[man(x), walks(x)])')
    print parser.parse(r'\x.\y.([],[sees(x,y)])')
    print parser.parse(r'\x.([],[walks(x)])(john)')
    print parser.parse(r'(([x],[walks(x)]) + ([y],[runs(y)]))')
    print parser.parse(r'(([],[walks(x)]) -> ([],[runs(x)]))')
    print parser.parse(r'([x],[PRO(x), sees(John,x)])')
    print parser.parse(r'([x],[man(x), -([],[walks(x)])])')
    print parser.parse(r'([],[(([x],[man(x)]) -> ([],[walks(x)]))])')

    print '=' * 20 + 'Test fol()' + '=' * 20
    print parser.parse(r'([x,y],[sees(x,y)])').fol()

    print '=' * 20 + 'Test alpha conversion and lambda expression equality' + '=' * 20
    e1 = parser.parse(r'\x.([],[P(x)])')
    print e1
    e2 = e1.alpha_convert(Variable('z'))
    print e2
    print e1 == e2

    print '=' * 20 + 'Test resolve_anaphora()' + '=' * 20
    print resolve_anaphora(
        parser.parse(r'([x,y,z],[dog(x), cat(y), walks(z), PRO(z)])'))
    print resolve_anaphora(
        parser.parse(r'([],[(([x],[dog(x)]) -> ([y],[walks(y), PRO(y)]))])'))
    print resolve_anaphora(parser.parse(r'(([x,y],[]) + ([],[PRO(x)]))'))

    print '=' * 20 + 'Test pprint()' + '=' * 20
    parser.parse(r"([],[])").pprint()
    parser.parse(
        r"([],[([x],[big(x), dog(x)]) -> ([],[bark(x)]) -([x],[walk(x)])])"
    ).pprint()
    parser.parse(r"([x,y],[x=y]) + ([z],[dog(z), walk(z)])").pprint()
    parser.parse(
        r"([],[([x],[]) | ([y],[]) | ([z],[dog(z), walk(z)])])").pprint()
    parser.parse(r"\P.\Q.(([x],[]) + P(x) + Q(x))(\x.([],[dog(x)]))").pprint()
Exemplo n.º 15
0
    def readings(self, trail=[]):

        state_reference_point = None
        index = trail[-1].conds.index(self)
        #state reference point in case there are no previous events
        for drs in (ancestor for ancestor in ReverseIterator(trail)
                    if isinstance(ancestor, DRS)):

            search_list = drs.refs

            if drs is trail[-1]:

                #Described eventuality in the object's referents?
                #Take refs' list up to described eventuality

                search_list = drs.refs[:drs.refs.index(self.argument.variable)]

            for ref in ReverseIterator(search_list):
                #search for the most recent reference
                refex = DrtVariableExpression(ref)

                if isinstance(refex, DrtEventVariableExpression) and \
                not (refex == self.argument) and not self.function.variable.name == DrtTokens.PERF:

                    if isinstance(self.argument, DrtEventVariableExpression):
                        #In case given eventuality is an event, return earlier
                        return [
                            Binding([
                                (trail[-1],
                                 ConditionReplacer(index, [
                                     self._combine(DrtTokens.EARLIER, refex,
                                                   self.argument)
                                 ]))
                            ])
                        ], False

                    elif isinstance(self.argument, DrtStateVariableExpression):
                        #In case given eventuality is a state, return include
                        return [
                            Binding([
                                (trail[-1],
                                 ConditionReplacer(index, [
                                     self._combine(DrtTokens.INCLUDE,
                                                   self.argument, refex)
                                 ]))
                            ])
                        ], False


                elif not state_reference_point and \
                    isinstance(refex, DrtStateVariableExpression) and \
                    not (refex == self.argument):
                    #In case no event is found, locate the most recent state
                    state_reference_point = refex

        if state_reference_point:

            if self.function.variable.name == DrtTokens.PERF:
                #in case we are dealing with PERF
                if isinstance(self.argument, DrtEventVariableExpression):

                    #Reference point is a state and described eventuality an event,
                    #return event abuts on state

                    return [
                        Binding([
                            (trail[-1],
                             ConditionReplacer(index, [
                                 self._combine(DrtTokens.ABUT, self.argument,
                                               state_reference_point)
                             ]))
                        ])
                    ], False

                elif isinstance(self.argument, DrtStateVariableExpression):
                    #Reference point is a state and described eventuality a state,
                    #then add an event referent to the ancestor's refs list and two conditions
                    #that that event is the end of eventuality and
                    #that event abuts on ref.state. Function object needed.
                    termination_point = unique_variable(Variable("e"))
                    conds = [
                        DrtEqualityExpression(
                            DrtEventVariableExpression(termination_point),
                            DrtApplicationExpression(
                                self.make_ConstantExpression(DrtTokens.END),
                                self.argument)),
                        self._combine(
                            DrtTokens.ABUT,
                            DrtEventVariableExpression(termination_point),
                            state_reference_point)
                    ]
                    return [
                        Binding([
                            (trail[-1],
                             DrtFindEventualityExpression.ConditionReplacer(
                                 index, conds, termination_point))
                        ])
                    ], False

            elif isinstance(self.argument, DrtStateVariableExpression):
                #Reference point is a state and given eventuality is also a state,
                #return overlap

                return [
                    Binding([(trail[-1],
                              ConditionReplacer(index, [
                                  self._combine(DrtTokens.OVERLAP,
                                                state_reference_point,
                                                self.argument)
                              ]))])
                ], False

            elif isinstance(self.argument, DrtEventVariableExpression):
                #Reference point is a state and given eventuality is an event,
                #return include
                return [
                    Binding([(trail[-1],
                              ConditionReplacer(index, [
                                  self._combine(DrtTokens.INCLUDE,
                                                state_reference_point,
                                                self.argument)
                              ]))])
                ], False

        else:
            #no suitable reference found
            return [Binding([(trail[-1], ConditionRemover(index))])], False
Exemplo n.º 16
0
 def make_VariableExpression(self, name):
     return DrtVariableExpression(Variable(name))
Exemplo n.º 17
0
def mainLogic(doc):
    departFlag = False
    departVpFlag = False
    arriveFlag = False
    sourceVpFlag = False
    destVpFlag = False
    busNameNpFlag = False
    destNpFlag = False
    d = ''
    t = ''
    a = ''
    time = ''
    nameDepart = ''
    nameArrive = ''
    bVar = ''
    h_BusName = ''
    busName = ''
    timeDepart = ''
    cityTokenText = ['Hồ_Chí_Minh', 'Hà_Nội', 'Huế', 'Đà_nẵng', 'Đà_Nẵng']
    busTokenText = ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8']
    cityTokenDep = ['compound', 'nmod', 'obl']

    (f, typeWh) = ('f2', 'WHICH1') if (
        subtree_matcher(doc, 'det', text='nào') != []) else ('h1', 'HOWLONG1')

    if (typeWh == 'WHICH1'):
        gap = f
    else:
        #Runtime (HOWLONG1 case)
        gap = 'r2'

    if (gap == 'f2'):
        if subtree_matcher(doc, 'case', text='đến') != [] or subtree_matcher(
                doc, 'ccomp', text='đến') != []:
            arriveFlag = True
            a = 'a3'
            # time=subtree_matcher(doc,'nummod')[0] if (len(subtree_matcher(doc,'nummod'))==1) else subtree_matcher(doc,'nummod')
            # print([i.text for i in searchChild(doc,'ROOT')])
            try:
                time = [
                    i.text for i in searchChild(doc, 'ROOT') if 'HR' in i.text
                ][0]
            except:
                time = ''
            if time != '':
                t = 't2'
            else:
                t = '?t'
            ################################################
            if subtree_matcher(doc, 'ROOT', text='đi') != []:
                departFlag = True
                d = 'd3'
                for cT in cityTokenText:
                    for cD in cityTokenDep:
                        temp = subtree_matcher(doc, cD, cT)
                        tempHead = checkHead(doc, temp)
                        try:
                            tempChild = [i.text for i in searchChild(doc, cD)]
                        except:
                            tempChild = ''

                        if (temp != []) and (tempHead != 'đi'):
                            destVpFlag = True
                            nameArrive = temp
                        elif (temp != []) and (tempHead
                                               == 'đi') and ('từ'
                                                             in tempChild):
                            sourceVpFlag = True
                            nameDepart = temp
                        elif (temp != []) and (tempHead
                                               == 'đi') and ('đến'
                                                             in tempChild):
                            destVpFlag = True
                            nameArrive = temp
            # elif subtree_matcher(doc,'ROOT',text='xuất_phát')!=[]:
            #     departFlag=True
            #     d='d3'
            #     for cT in cityTokenText:
            #         for cD in cityTokenDep:
            #             temp=subtree_matcher(doc,cD,cT)
            #             tempHead=checkHead(doc,temp)
            #             # try:
            #             #     tempChild=[i.text for i in searchChild(doc,cD)]
            #             # except:
            #             #     tempChild=''
            #             if (temp !=[]) and (tempHead!='xuất_phát'):
            #                 destVpFlag=True
            #                 nameDepart= temp
            #             # elif (temp !=[]) and (tempHead=='xuất_phát') and ('từ' in tempChild):
            #             #     sourceVpFlag=True
            #             #     nameDepart= temp
            #             # elif (temp !=[]) and (tempHead=='xuất_phát') and ('đến' in tempChild):
            #             #     destVpFlag=True
            #             #     nameArrive= temp
            else:
                for cT in cityTokenText:
                    for cD in cityTokenDep:
                        temp = subtree_matcher(doc, cD, cT)
                        if temp != []:
                            destNpFlag = True
                            nameArrive = temp
                            break
                    else:
                        # Continue if the inner loop wasn't broken.
                        continue
                        # Inner loop was broken, break the outer.
                    break
        elif subtree_matcher(doc, 'ROOT', text='xuất_phát') != []:
            departFlag = True
            d = 'd3'
            for cT in cityTokenText:
                for cD in cityTokenDep:
                    temp = subtree_matcher(doc, cD, cT)
                    tempHead = checkHead(doc, temp)
                    # try:
                    #     tempChild=[i.text for i in searchChild(doc,cD)]
                    # except:
                    #     tempChild=''
                    if (temp != []) and (tempHead != 'xuất_phát'):
                        departVpFlag = True
                        nameDepart = temp
                    # elif (temp !=[]) and (tempHead=='xuất_phát') and ('từ' in tempChild):
                    #     sourceVpFlag=True
                    #     nameDepart= temp
                    # elif (temp !=[]) and (tempHead=='xuất_phát') and ('đến' in tempChild):
                    #     destVpFlag=True
                    #     nameArrive= temp
        # print(destNpFlag)
        # Variable('?hDest'),name=Variable('?nameDest')
    elif (gap == 'r2'):
        if (subtree_matcher(doc, 'ROOT', text='đến')) != []:
            arriveFlag = True
            a = 'a3'

            time = '?time'
            t = '?t'

            nameArrive = subtree_matcher(doc, 'obj')[0] if (len(
                subtree_matcher(doc, 'obj')) == 1) else subtree_matcher(
                    doc, 'obj')
            if type(nameArrive) == list:
                for obj in nameArrive:
                    if obj in cityTokenText:
                        nameArrive = obj
                        break

            if nameArrive != '':
                h = 'h4'
                destVpFlag = True
            else:
                h = '?h'

            if subtree_matcher(doc, 'case', text='từ') != []:
                d = 'd3'
                nameDepart = checkHead(doc, 'từ')
                if (nameDepart != ''):
                    sourceVpFlag
            listObj = subtree_matcher(doc, 'obj')
            listCompound = subtree_matcher(doc, 'compound')

            for sub in listObj:
                if sub in busTokenText:
                    busName = sub

            if busName == '':
                for sub in listCompound:
                    if sub in busTokenText:
                        busName = sub

            if busName != '':
                busNameNpFlag = True
                bVar = 'f2'
                h_BusName = 'h3'

    if arriveFlag and not (destVpFlag) and not (sourceVpFlag):
        vp = FeatStruct(
            arrive=FeatStruct(a=a, f=f, t=FeatStruct(t_var=t, time_var=time)))
    elif departFlag and departVpFlag:
        vp = FeatStruct(
            depart=FeatStruct(d='d3',
                              f='f1',
                              t=FeatStruct(t_var=t, time_var=time)),
            source=FeatStruct(bus='h3',
                              sourceName=FeatStruct(f=Variable('?h'),
                                                    name=nameDepart)))
    else:
        vp = FeatStruct(
            depart=FeatStruct(d='d3',
                              f='f1',
                              t=FeatStruct(t_var=t, time_var=time)),
            source=FeatStruct(bus='h4',
                              sourceName=FeatStruct(f=Variable('?h'),
                                                    name=nameDepart)),
            arrive=FeatStruct(a='a3',
                              f='f2',
                              t=FeatStruct(t_var=t, time_var=time)),
            dest=FeatStruct(destName=FeatStruct(
                f=Variable('?f'), name=FeatStruct(h='h6', name=nameArrive))))

    if destNpFlag and not (busNameNpFlag):
        np = FeatStruct(dest=FeatStruct(
            bus=Variable('?f'),
            dest=FeatStruct(f=Variable('?f'),
                            name=FeatStruct(h='h3', name=nameArrive))))
    else:
        np = FeatStruct(the=FeatStruct(
            bus=bVar, busname=FeatStruct(h=h_BusName, name=busName)))

    wh = FeatStruct(whType=FeatStruct(f=f, type=typeWh))
    sem = FeatStruct(query=FeatStruct(vp=vp, np=np, wh=wh))
    var = Variable('?a')

    result = featStruct(gap,
                        sem,
                        var,
                        arriveFlag=arriveFlag,
                        destVpFlag=destVpFlag,
                        sourceVpFlag=sourceVpFlag,
                        busNameNpFlag=busNameNpFlag,
                        destNpFlag=destNpFlag,
                        departFlag=departFlag,
                        departVpFlag=departVpFlag)
    print(result)
    return result
Exemplo n.º 18
0
def featStruct(gapUp,
               semUp,
               varUp,
               arriveFlag=False,
               destVpFlag=False,
               sourceVpFlag=False,
               busNameNpFlag=False,
               destNpFlag=False,
               departFlag=False,
               departVpFlag=False):
    gap = Variable('?gap')

    if arriveFlag and not (destVpFlag) and not (sourceVpFlag):
        vp = FeatStruct(arrive=FeatStruct(
            a=Variable('?a'),
            f=Variable('?f'),
            t=FeatStruct(t_var=Variable('?t'), time_var=Variable('?time'))))
    elif departFlag and departVpFlag:
        vp = FeatStruct(depart=FeatStruct(
            d=Variable('?d'),
            f=Variable('?fDep'),
            t=FeatStruct(t_var=Variable('?t_var_dep'),
                         time_var=Variable('?timeDepart'))),
                        source=FeatStruct(bus=Variable('?h'),
                                          sourceName=FeatStruct(
                                              f=Variable('?h'),
                                              name=Variable('?nameSource'))))
    else:
        vp = FeatStruct(
            depart=FeatStruct(d=Variable('?d'),
                              f=Variable('?fDep'),
                              t=FeatStruct(t_var=Variable('?t_var_dep'),
                                           time_var=Variable('?timeDepart'))),
            source=FeatStruct(bus=Variable('?h'),
                              sourceName=FeatStruct(
                                  f=Variable('?h'),
                                  name=Variable('?nameSource'))),
            arrive=FeatStruct(a=Variable('?a'),
                              f=Variable('?fArr'),
                              t=FeatStruct(t_var=Variable('?t_var_arr'),
                                           time_var=Variable('?timeArrive'))),
            dest=FeatStruct(destName=FeatStruct(
                f=Variable('?f'),
                name=FeatStruct(h=Variable('?hDest'),
                                name=Variable('?nameDest')))))

    if destNpFlag and not (busNameNpFlag):
        np = FeatStruct(dest=FeatStruct(
            bus=Variable('?f'),
            dest=FeatStruct(f=Variable('?f'),
                            name=FeatStruct(h=Variable('?h'),
                                            name=Variable('?name')))))
    else:
        np = FeatStruct(
            the=FeatStruct(bus=Variable('?b'),
                           busname=FeatStruct(h=Variable('?h_BusName'),
                                              name=Variable('?busName'))))

    wh = FeatStruct(
        whType=FeatStruct(f=Variable('?f'), type=Variable('?type')))
    sem = FeatStruct(query=FeatStruct(vp=vp, np=np, wh=wh))
    var = Variable('?a')

    para = FeatStruct(gap=gap, sem=sem, var=var)
    paraUpdate = FeatStruct(gap=gapUp, sem=semUp, var=varUp)
    # print('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$')
    # print(paraUpdate)
    # paraUpdate.unify(para)['sem']['query']['vp']['arrive']['f']
    return paraUpdate.unify(para)
Exemplo n.º 19
0
    def _attempt_proof_n_app(self, current, context, agenda, accessible_vars, atoms, debug):
        f, args = current.term.uncurry()
        for i, arg in enumerate(args):
            if not TableauProver.is_atom(arg):
                ctx = f
                nv = Variable('X%s' % _counter.get())
                for j,a in enumerate(args):
                    if i==j:
                    ctx = (ctx(VariableExpression(nv)) if i == j else ctx(a))
                if context:
                    #combine new context with existing
                    ctx = context(ctx).simplify()
                ctx = LambdaExpression(nv, -ctx)
                agenda.put(-arg, ctx)
                return self._attempt_proof(agenda, accessible_vars, atoms, debug+1)
        raise Exception('If this method is called, there must be a non-atomic argument')

    def _attempt_proof_n_eq(self, current, context, agenda, accessible_vars, atoms, debug):
        ###########################################################################
        # Since 'current' is of type '~(a=b)', the path is closed if 'a' == 'b'
        ###########################################################################
        if current.term.first == current.term.second:
            debug.line('CLOSED', 1)
            return True

        agenda[Categories.N_EQ].add((current,context))
        current._exhausted = True
        return self._attempt_proof(agenda, accessible_vars|set([current.term.first, current.term.second]), atoms, debug+1)

    def _attempt_proof_d_neg(self, current, context, agenda, accessible_vars, atoms, debug):
        agenda.put(current.term.term, context)
        return self._attempt_proof(agenda, accessible_vars, atoms, debug+1)

    def _attempt_proof_n_all(self, current, context, agenda, accessible_vars, atoms, debug):
        agenda[Categories.EXISTS].add((ExistsExpression(current.term.variable, -current.term.term), context))
        return self._attempt_proof(agenda, accessible_vars, atoms, debug+1)

    def _attempt_proof_n_some(self, current, context, agenda, accessible_vars, atoms, debug):
        agenda[Categories.ALL].add((AllExpression(current.term.variable, -current.term.term), context))
        return self._attempt_proof(agenda, accessible_vars, atoms, debug+1)

    def _attempt_proof_and(self, current, context, agenda, accessible_vars, atoms, debug):
        agenda.put(current.first, context)
        agenda.put(current.second, context)
        return self._attempt_proof(agenda, accessible_vars, atoms, debug+1)

    def _attempt_proof_n_or(self, current, context, agenda, accessible_vars, atoms, debug):
        agenda.put(-current.term.first, context)
        agenda.put(-current.term.second, context)
        return self._attempt_proof(agenda, accessible_vars, atoms, debug+1)

    def _attempt_proof_n_imp(self, current, context, agenda, accessible_vars, atoms, debug):
        agenda.put(current.term.first, context)
        agenda.put(-current.term.second, context)
        return self._attempt_proof(agenda, accessible_vars, atoms, debug+1)

    def _attempt_proof_or(self, current, context, agenda, accessible_vars, atoms, debug):
        new_agenda = agenda.clone()
        agenda.put(current.first, context)
        new_agenda.put(current.second, context)
        return self._attempt_proof(agenda, accessible_vars, atoms, debug+1) and \
                self._attempt_proof(new_agenda, accessible_vars, atoms, debug+1)

    def _attempt_proof_imp(self, current, context, agenda, accessible_vars, atoms, debug):
        new_agenda = agenda.clone()
        agenda.put(-current.first, context)
        new_agenda.put(current.second, context)
        return self._attempt_proof(agenda, accessible_vars, atoms, debug+1) and \
                self._attempt_proof(new_agenda, accessible_vars, atoms, debug+1)

    def _attempt_proof_n_and(self, current, context, agenda, accessible_vars, atoms, debug):
        new_agenda = agenda.clone()
        agenda.put(-current.term.first, context)
        new_agenda.put(-current.term.second, context)
        return self._attempt_proof(agenda, accessible_vars, atoms, debug+1) and \
                self._attempt_proof(new_agenda, accessible_vars, atoms, debug+1)

    def _attempt_proof_iff(self, current, context, agenda, accessible_vars, atoms, debug):
        new_agenda = agenda.clone()
        agenda.put(current.first, context)
        agenda.put(current.second, context)
        new_agenda.put(-current.first, context)
        new_agenda.put(-current.second, context)
        return self._attempt_proof(agenda, accessible_vars, atoms, debug+1) and \
                self._attempt_proof(new_agenda, accessible_vars, atoms, debug+1)

    def _attempt_proof_n_iff(self, current, context, agenda, accessible_vars, atoms, debug):
        new_agenda = agenda.clone()
        agenda.put(current.term.first, context)
        agenda.put(-current.term.second, context)
        new_agenda.put(-current.term.first, context)
        new_agenda.put(current.term.second, context)
        return self._attempt_proof(agenda, accessible_vars, atoms, debug+1) and \
                self._attempt_proof(new_agenda, accessible_vars, atoms, debug+1)

    def _attempt_proof_eq(self, current, context, agenda, accessible_vars, atoms, debug):
        #########################################################################
        # Since 'current' is of the form '(a = b)', replace ALL free instances
        # of 'a' with 'b'
        #########################################################################
        agenda.put_atoms(atoms)
        agenda.replace_all(current.first, current.second)
        accessible_vars.discard(current.first)
        agenda.mark_neqs_fresh();
        return self._attempt_proof(agenda, accessible_vars, set(), debug+1)

    def _attempt_proof_some(self, current, context, agenda, accessible_vars, atoms, debug):
        new_unique_variable = VariableExpression(unique_variable())
        agenda.put(current.term.replace(current.variable, new_unique_variable), context)
        agenda.mark_alls_fresh()
        return self._attempt_proof(agenda, accessible_vars|set([new_unique_variable]), atoms, debug+1)

    def _attempt_proof_all(self, current, context, agenda, accessible_vars, atoms, debug):
        try:
            current._used_vars
        except AttributeError:
            current._used_vars = set()

        #if there are accessible_vars on the path
        if accessible_vars:
            # get the set of bound variables that have not be used by this AllExpression
            bv_available = accessible_vars - current._used_vars

            if bv_available:
                variable_to_use = list(bv_available)[0]
                debug.line('--> Using \'%s\'' % variable_to_use, 2)
                current._used_vars |= set([variable_to_use])
                agenda.put(current.term.replace(current.variable, variable_to_use), context)
                agenda[Categories.ALL].add((current,context))
                return self._attempt_proof(agenda, accessible_vars, atoms, debug+1)

            else:
                #no more available variables to substitute
                debug.line('--> Variables Exhausted', 2)
                current._exhausted = True
                agenda[Categories.ALL].add((current,context))
                return self._attempt_proof(agenda, accessible_vars, atoms, debug+1)

        else:
            new_unique_variable = VariableExpression(unique_variable())
            debug.line('--> Using \'%s\'' % new_unique_variable, 2)
            current._used_vars |= set([new_unique_variable])
            agenda.put(current.term.replace(current.variable, new_unique_variable), context)
            agenda[Categories.ALL].add((current,context))
            agenda.mark_alls_fresh()
            return self._attempt_proof(agenda, accessible_vars|set([new_unique_variable]), atoms, debug+1)

    @staticmethod
    def is_atom(e):
        if isinstance(e, NegatedExpression):
            e = e.term

        if isinstance(e, ApplicationExpression):
            for arg in e.args:
                if not TableauProver.is_atom(arg):
                    return False
            return True
        elif isinstance(e, AbstractVariableExpression) or \
             isinstance(e, LambdaExpression):
            return True
        else:
            return False
Exemplo n.º 20
0
 def _make_atom(self, pred, *args):
     accum = DrtVariableExpression(Variable(pred))
     for arg in args:
         accum = DrtApplicationExpression(
             accum, DrtVariableExpression(Variable(arg)))
     return accum
Exemplo n.º 21
0
def fill_details(event_input, nxlist, voice=None, nx=None, dv=False):
    event = deepcopy(event_input)
    if not event.tense: event.tense = choice(['past', 'pres'])
    if not event.aspect: event.aspect = choice(['prog', 'neut'], p=[.3, .7])
    if not event.voice:
        if voice: event.voice = voice
        else: event.voice = choice(helper_dicts.voices[event.frame])
    if not event.pol: event.pol = choice(['pos', 'neg'], p=[.8, .2])
    # if event.pol == 'neg' and nx and not event.polx:
    if nx and not event.polx:
        num_extras = max(0, min(nx, int(round(1 * np.random.randn() + 1))))
        if num_extras > 0:
            advlist = copy(nxlist)
            random.shuffle(advlist)
            px = ' , '.join(advlist[:num_extras])
            #take the first num_extras of them and add them in order as the content for polx
            event.polx = px

    #TODO remove this line if we take care of populating frame elsewhere
    if not event.frame: event.frame = frames[event.name]
    for part in event.participants:
        if not event.participants[part].num:
            event.participants[part].num = choice(['sg', 'pl'])
        if not event.participants[part].det:
            if dv:
                predet = choice(['def', 'indef'])
                event.participants[part].det = helper_dicts.defnum2det[predet][
                    event.participants[part].num]
            else:
                event.participants[part].det = 'the'
        event.bindings[Variable('?n%s' % part)] = event.participants[part].num
        if 'rc' in event.participants[part].attributes:
            fr = event.participants[part].attributes['rc']['event'].frame
            if not event.participants[part].attributes['rc'][
                    'rtype'] and not event.participants[part].attributes['rc'][
                        'event'].voice:
                #for now, try to avoid ORC with hostrole as agent, since eg "the professor that the company was called by" is a bit extreme
                if event.participants[part].attributes['rc'][
                        'role'] == 'agent':
                    event.participants[part].attributes['rc'][
                        'rtype'] = choice(['orc', 'src'], p=[.05, .95])
                else:
                    event.participants[part].attributes['rc'][
                        'rtype'] = choice(['orc', 'src'])
                #voice in RC is deterministic from hostrole and rtype, so set that here
                chosen_role = event.participants[part].attributes['rc']['role']
                chosen_rtype = event.participants[part].attributes['rc'][
                    'rtype']
                event.participants[part].attributes['rc'][
                    'event'].voice = helper_dicts.rolertype2voice[chosen_role][
                        chosen_rtype]
            elif not event.participants[part].attributes['rc'][
                    'rtype'] and event.participants[part].attributes['rc'][
                        'event'].voice:
                chosen_role = event.participants[part].attributes['rc']['role']
                chosen_voice = event.participants[part].attributes['rc'][
                    'event'].voice
                event.participants[part].attributes['rc'][
                    'rtype'] = helper_dicts.rolevoice2rtype[chosen_role][
                        chosen_voice]

            rcevent = fill_details(
                event.participants[part].attributes['rc']['event'],
                nxlist,
                nx=nx,
                dv=dv)
            event.participants[part].attributes['rc']['event'] = rcevent

    return event
Exemplo n.º 22
0
def test_as_ec_sexpr_function():
  ont = _make_mock_ontology()
  expr = FunctionVariableExpression(Variable("and_", ont.types["boolean", "boolean", "boolean"]))
  eq_(ont.as_ec_sexpr(expr), "(lambda (lambda (and_ $1 $0)))")
Exemplo n.º 23
0
 def make_ConstantExpression(self, name):
     return DrtConstantExpression(Variable(name))