def assign_semantics(ccg_tree, semantic_index, tokens): """ Visit recursively the CCG tree in depth-first order, assigning lambda expressions (semantics) to each node. """ category = ccg_tree.attrib['category'] if len(ccg_tree) == 0: semantics = semantic_index.get_semantic_representation(ccg_tree, tokens) ccg_tree.set('sem', str(semantics)) return if len(ccg_tree) == 1: assign_semantics(ccg_tree[0], semantic_index, tokens) semantics = semantic_index.get_semantic_representation(ccg_tree, tokens) ccg_tree.set('sem', str(semantics)) return for child in ccg_tree: assign_semantics(child, semantic_index, tokens) combine_children_exprs(ccg_tree, tokens, semantic_index) return
def combine_children_exprs(ccg_tree, tokens, semantic_index): """ Perform forward/backward function application/combination. """ assert len(ccg_tree) >= 2, \ 'There should be at least two children to combine expressions: {0}'\ .format(ccg_tree) # Assign coq types. coq_types_left = ccg_tree[0].attrib.get('coq_type', "") coq_types_right = ccg_tree[1].attrib.get('coq_type', "") if coq_types_left and coq_types_right: coq_types = coq_types_left + ' ||| ' + coq_types_right elif coq_types_left: coq_types = coq_types_left else: coq_types = coq_types_right ccg_tree.set('coq_type', coq_types) semantics = semantic_index.get_semantic_representation(ccg_tree, tokens) if semantics: ccg_tree.set('sem', str(semantics)) return None # Back-off mechanism in case no semantic templates are available: if is_forward_operation(ccg_tree): function_index, argument_index = 0, 1 else: function_index, argument_index = 1, 0 function = lexpr(ccg_tree[function_index].attrib['sem']) argument = lexpr(ccg_tree[argument_index].attrib['sem']) combination_operation = get_combination_op(ccg_tree) if combination_operation == 'function_application': evaluation = function(argument).simplify() elif combination_operation == 'function_combination': num_arguments = get_num_args(ccg_tree) type_raised_function = type_raise(function, num_arguments) evaluation = type_raised_function(argument).simplify() else: assert False, 'This node should be a function application or combination'\ .format(etree.tostring(ccg_tree, pretty_print=True)) ccg_tree.set('sem', str(evaluation)) return None