Java Code Examples for edu.cornell.cs.nlp.spf.mr.lambda.Literal#getPredicate()

The following examples show how to use edu.cornell.cs.nlp.spf.mr.lambda.Literal#getPredicate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GetMapping.java    From amr with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void visit(LiteralNode node) {
	final Literal resultLiteral = (Literal) currentResult;

	// Predicate.
	currentResult = resultLiteral.getPredicate();
	node.getPredicate().accept(this);

	// Arguments.
	for (int i = 0; i < node.getArgs().size(); ++i) {
		if (fail) {
			return;
		}
		currentResult = resultLiteral.getArg(i);
		node.getArgs().get(i).accept(this);
	}

}
 
Example 2
Source File: GetPredicateCounts.java    From spf with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void visit(Literal literal) {
	if (literal.getPredicate() instanceof LogicalConstant) {
		if (!predicates.containsKey(literal.getPredicate())) {
			predicates.put((LogicalConstant) literal.getPredicate(),
					new Counter());
		}
		predicates.get(literal.getPredicate()).inc();
	}

	literal.getPredicate().accept(this);
	final int len = literal.numArgs();
	for (int i = 0; i < len; ++i) {
		literal.getArg(i).accept(this);
	}
}
 
Example 3
Source File: AMRServices.java    From amr with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the unary typing predicate (if one exists) from a <e,t>-typed lambda
 * term (the body of a skolem term).
 */
public static LogicalConstant getTypingPredicate(Lambda set) {
	if (set.getBody() instanceof Literal) {
		final Literal bodyLiteral = (Literal) set.getBody();
		final int len = bodyLiteral.numArgs();
		if (bodyLiteral.getPredicate()
				.equals(LogicLanguageServices.getConjunctionPredicate())) {
			return getTypingPredicateFromConjunction(bodyLiteral);
		} else if (len == 1
				&& bodyLiteral.getPredicate() instanceof LogicalConstant) {
			return (LogicalConstant) bodyLiteral.getPredicate();
		}
	}
	return null;
}
 
Example 4
Source File: AMRSupervisedFilter.java    From amr with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visit(Literal literal) {
	final int numArgs = literal.numArgs();
	final LogicalExpression predicate = literal
			.getPredicate() instanceof LogicalConstant
					? OverloadedLogicalConstant.getWrapped(
							(LogicalConstant) literal.getPredicate())
					: literal.getPredicate();
	if (numArgs == 2
			&& !LogicLanguageServices.isCoordinationPredicate(predicate)
			&& predicate instanceof LogicalConstant
			&& constantFilter.test((LogicalConstant) predicate)) {
		countRelationalPairs((LogicalConstant) predicate,
				literal.getArg(1));
		if (!isValid) {
			return;
		}
	}

	if (LogicLanguageServices.isCoordinationPredicate(predicate)) {
		// Try to construct the instance-type-related-type triplets as
		// much as possible. We are trying to do as early as possible,
		// even before the skolem term is closed.
		countInstanceTypeRelatedTypeTriplets(literal);
		if (!isValid) {
			return;
		}
	}

	predicate.accept(this);
	for (int i = 0; i < numArgs; ++i) {
		literal.getArg(i).accept(this);
		if (!isValid) {
			return;
		}
	}
}
 
Example 5
Source File: MakeCompositionSplits.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visit(Literal literal) {
	if (literal.getPredicateType() instanceof RecursiveComplexType) {
		// Case recursive predicate, we to extract subsets of its arguments
		splits.addAll(doSplitsForRecursivePredicate(literal));
	}

	// Collect all the free variables. We need one of them to match the
	// outermost variables of the original Lambda expression. The total
	// number has to be less than the threshold. Also, skip literals where
	// the predicate is a variable.
	final Set<Variable> freeVars = GetAllFreeVariables.of(literal);
	if (freeVars.size() <= SplittingServices.MAX_NUM_VARS
			&& freeVars.remove(originalLambda.getArgument())
			&& !(literal.getPredicate() instanceof Variable)) {
		for (final List<Variable> order : SplittingServices
				.allOrders(freeVars)) {
			final SplittingPair split = doSplit(literal, order);
			if (split != null) {
				splits.add(split);
			}
		}
	}

	// NOTE: we do not call literal.getPredicate().accept(this) because we
	// don't want to pull out predicate names
	final int numArgs = literal.numArgs();
	for (int i = 0; i < numArgs; ++i) {
		literal.getArg(i).accept(this);
	}
}
 
Example 6
Source File: ApplyAndSimplify.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
private static LogicalExpression literalApplication(Literal literal,
		LogicalExpression arg) {
	final int len = literal.numArgs();
	final LogicalExpression[] newArgs = new LogicalExpression[len + 1];
	literal.copyArgsIntoArray(newArgs, 0, 0, len);
	// Append the argument to the list of arguments in the literal, verify
	// that it doesn't contain any variables (identical objects) from the
	// literal.
	newArgs[len] = arg;
	return new Literal(literal.getPredicate(), newArgs);
}
 
Example 7
Source File: AbstrcatSimplify.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Try to fold the lambda operator. Handles the case where the lambda
 * operator is redundant. For example: (lambda $0:e (foo:<e,<e,t>> dada:e
 * $0)) --> (foo:<e,<e,t>> dada:e)
 *
 * @param lambdaVariable
 * @param lambdaBody
 * @return 'null' if can't remove the Lambda operator, else return the
 *         modified body, which replaces the entire Lambda expression.
 */
private static LogicalExpression stripRedundantLambda(Variable lambdaArg,
		LogicalExpression lambdaBody) {
	if (!(lambdaBody instanceof Literal)) {
		// Only remove Lambda operators when the body is a single literal
		return null;
	}
	final Literal literal = (Literal) lambdaBody;

	// Check if we can fold the lambda operators.
	final int len = literal.numArgs();
	if (!(literal.getPredicateType() instanceof RecursiveComplexType)
			&& literal.getArg(len - 1) == lambdaArg) {
		// Verify that the variable is not used in any other place in
		// the expression (except as the last argument in the literal)
		boolean usedElsewehre = IsContainingVariable.of(
				literal.getPredicate(), lambdaArg);
		if (!usedElsewehre) {
			for (int i = 0; i < len - 1 && !usedElsewehre; ++i) {
				usedElsewehre |= IsContainingVariable.of(literal.getArg(i),
						lambdaArg);
			}
		}

		if (usedElsewehre) {
			return null;
		} else if (len == 1) {
			return literal.getPredicate();
		} else {
			return new Literal(literal.getPredicate(),
					literal.argumentCopy(0, len - 1));
		}
	} else {
		return null;
	}
}
 
Example 8
Source File: GetApplicationArgument.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
private void visitConventionalLiteral(Literal sourceLiteral,
		final Literal resultLiteral) {
	final int len = sourceLiteral.numArgs();
	final boolean noPriorArgument = argument == null;
	if (len == resultLiteral.numArgs()) {
		applicationResult = resultLiteral.getPredicate();
		sourceLiteral.getPredicate().accept(this);
		if (isValid) {
			for (int i = 0; i < len; ++i) {
				applicationResult = resultLiteral.getArg(i);
				sourceLiteral.getArg(i).accept(this);
				if (!isValid) {
					break;
				}

			}
		}
	} else {
		isValid = false;
	}

	if (!isValid) {
		final LogicalExpression newArgument = createArgument(resultLiteral,
				sourceLiteral, applicationArgument, scope);
		if (newArgument != null) {
			if (noPriorArgument) {
				argument = newArgument;
				isValid = true;
			} else if (!argument.equals(newArgument)) {
				isValid = false;
			}
		}
	}
}
 
Example 9
Source File: SingleSentencePartialCreditTestingStatistics.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visit(Literal literal) {
	// Visit the predicate
	literal.getPredicate().accept(this);

	final LogicalExpression pred = literal.getPredicate();
	final int numArgs = literal.numArgs();
	if (!LogicLanguageServices.isCoordinationPredicate(pred)
			&& !LogicLanguageServices.isArrayIndexPredicate(pred)
			&& !LogicLanguageServices.isArraySubPredicate(pred)
			&& literal.getPredicate() instanceof LogicalConstant) {
		if (numArgs == 1
				&& !(literal.getArg(0) instanceof LogicalConstant)) {
			// Unary predicates
			predConstPairs.add(Pair.of(literal.getPredicate(),
					(LogicalExpression) null));
			return;
		} else if (numArgs == 2
				&& !(literal.getArg(0) instanceof LogicalConstant)
				&& IsExtendedConstant.of(literal.getArg(1))) {
			// Binary predicate
			predConstPairs.add(Pair.of(literal.getPredicate(),
					literal.getArg(1)));
			return;
		}
	}

	// Just visit the arguments and predicate
	for (int i = 0; i < numArgs; ++i) {
		literal.getArg(i).accept(this);
	}
}
 
Example 10
Source File: DummyEntityServices.java    From amr with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test if this literal depicts a relation with a dummy entity (i.e., of the
 * form (pred:<e,<e,t>> k:e DUMMY:e)).
 */
public static boolean isRelationWithDummy(Literal literal) {
	return literal.numArgs() == 2
			&& literal.getPredicate() instanceof LogicalConstant
			&& literal.getArg(1).equals(AMRServices.getDummyEntity());
}
 
Example 11
Source File: MakeCompositionSplits.java    From spf with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Create splits for a literal with a order-insensitive recursive predicate.
 *
 * @param literal
 * @return
 */
private Set<SplittingPair> doSplitsForRecursiveOrderInsensitivePredicate(
		Literal literal) {
	final int numArgs = literal.numArgs();
	final RecursiveComplexType predicateType = (RecursiveComplexType) literal
			.getPredicateType();
	final Set<SplittingPair> newSplits = new HashSet<SplittingServices.SplittingPair>();

	// Variable for x in \lambda x . f(g(x))
	final Variable rootArg = originalLambda.getArgument();

	// Iterate over all subsets of arguments
	for (final List<LogicalExpression> argsSubset : new PowerSet<LogicalExpression>(
			literal.argumentCopy())) {
		final int size = argsSubset.size();
		if (size >= predicateType.getMinArgs()
				&& size < SplittingServices.MAX_NUM_SUBS && size < numArgs) {
			// Case the subset of arguments is within the size limits. Not
			// too small (the single argument is dealt with separately) and
			// not too big (need to leave something behind).

			// Body of g
			final Literal gBody = new Literal(literal.getPredicate(),
					argsSubset.toArray(new LogicalExpression[argsSubset
							.size()]));
			final Set<Variable> gFreeVars = GetAllFreeVariables.of(gBody);
			if (gFreeVars.size() <= SplittingServices.MAX_NUM_VARS
					&& gFreeVars.remove(rootArg)) {
				// Case the number of free variables is under the threshold
				// and the set of free variables contains the root argument,
				// otherwise skip this subset. Also remove the root argument
				// from the free variables, so we an glue at the prefix
				// of the lambda expression we will create.

				// Iterate over all possible variable orderings
				for (final List<Variable> newArgOrder : SplittingServices
						.allOrders(gFreeVars)) {

					// Construct the variables list
					final List<Variable> newVars = new LinkedList<Variable>();
					// Put the root argument at the beginning of the
					// variables list (this is the variable x, such that h =
					// \lambda x f(g(x))).
					newVars.add(rootArg);
					// And the rest of the variables
					newVars.addAll(newArgOrder);

					// Create the new function g, to extract
					final LogicalExpression g = SplittingServices
							.makeExpression(newVars, gBody);

					// Create f, such that h = \lambda x f(g(x))
					newVars.remove(rootArg);
					final Variable compositionArg = new Variable(
							LogicLanguageServices.getTypeRepository()
									.generalizeType(g.getType().getRange()));
					final LogicalExpression embeddedApplication = SplittingServices
							.makeAssignment(newVars, compositionArg);
					// Remove the subset of arguments we extracted
					final boolean[] newLiteralFlags = new boolean[numArgs + 1];
					for (final LogicalExpression gone : argsSubset) {
						for (int i = 0; i < numArgs; ++i) {
							if (!newLiteralFlags[i]
									&& literal.getArg(i).equals(gone)) {
								newLiteralFlags[i] = true;
								break;
							}
						}
					}
					final LogicalExpression[] newLiteralArguments = new LogicalExpression[numArgs + 1];
					literal.copyArgsIntoArray(newLiteralArguments, 0, 0,
							numArgs);
					// Add the embedded application instead
					newLiteralArguments[numArgs] = embeddedApplication;
					final LogicalExpression newLiteral = new Literal(
							literal.getPredicate(), ArrayUtils.remove(
									newLiteralArguments, newLiteralFlags,
									LogicalExpression.class));
					// Replace the original literal with the new one. Only
					// support replaceing all occurrences.
					final LogicalExpression fBody = ReplaceExpression.of(
							originalLambda.getBody(), literal, newLiteral);

					final Lambda f = new Lambda(compositionArg, fBody);

					// Verify that f has no free variables (can happen if
					// rootArg appears in other places)
					if (GetAllFreeVariables.of(f).size() == 0) {
						newSplits.add(createSplittingPair(f, g));
					}
				}
			}
		}
	}
	return newSplits;
}
 
Example 12
Source File: MakeCompositionSplits.java    From spf with GNU General Public License v2.0 4 votes vote down vote up
private Set<SplittingPair> doSplitsForRecursiveOrderSensitivePredicate(
		Literal literal) {
	final RecursiveComplexType predicateType = (RecursiveComplexType) literal
			.getPredicateType();
	final Set<SplittingPair> newSplits = new HashSet<SplittingServices.SplittingPair>();
	final int numArgs = literal.numArgs();

	// Variable for x in \lambda x . f(g(x))
	final Variable rootArg = originalLambda.getArgument();

	// Iterate over all span lengths
	for (int length = predicateType.getMinArgs(); length <= SplittingServices.MAX_NUM_SUBS; length++) {
		// Iterate over all spans of the given length
		for (int begin = 0; begin < numArgs - length; begin++) {
			// The current span of arguments
			final LogicalExpression[] argsSublist = literal.argumentCopy(
					begin, begin + length);

			// Body of g
			final Literal gBody = new Literal(literal.getPredicate(),
					argsSublist);
			final Set<Variable> gFreeVars = GetAllFreeVariables.of(gBody);
			if (gFreeVars.size() <= SplittingServices.MAX_NUM_VARS
					&& gFreeVars.remove(rootArg)) {
				// Case the number of free variables is under the threshold
				// and the set of free variables contains the root argument,
				// otherwise skip this subset. Also remove the root argument
				// from the free variables, so we an glue at the prefix
				// of the lambda expression we will create.

				// Iterate over all possible variable orderings
				for (final List<Variable> newArgOrder : SplittingServices
						.allOrders(gFreeVars)) {

					// Construct the variables list
					final List<Variable> newVars = new LinkedList<Variable>();
					// Put the root argument at the beginning of the
					// variables list (this is the variable x, such that h =
					// \lambda x f(g(x))).
					newVars.add(rootArg);
					// And the rest of the variables
					newVars.addAll(newArgOrder);

					// Create the new function g, to extract
					final LogicalExpression g = SplittingServices
							.makeExpression(newVars, gBody);

					// Create f, such that h = \lambda x f(g(x))
					newVars.remove(rootArg);
					final Variable compositionArg = new Variable(
							LogicLanguageServices.getTypeRepository()
									.generalizeType(g.getType().getRange()));
					final LogicalExpression embeddedApplication = SplittingServices
							.makeAssignment(newVars, compositionArg);
					final List<LogicalExpression> newLiteralArguments = Arrays
							.asList(literal.argumentCopy());
					// Remove the sub-list of arguments we extracted
					for (int i = 0; i < length; i++) {
						newLiteralArguments.remove(begin);
					}
					// Add the embedded application instead
					newLiteralArguments.add(begin, embeddedApplication);
					final LogicalExpression newLiteral = new Literal(
							literal.getPredicate(),
							newLiteralArguments
									.toArray(new LogicalExpression[newLiteralArguments
											.size()]));
					// Replace the original literal with the new one. Only
					// support replacing all occurrences.
					final LogicalExpression fBody = ReplaceExpression.of(
							originalLambda.getBody(), literal, newLiteral);

					final Lambda f = new Lambda(compositionArg, fBody);

					// Verify that f has no free variables (can happen if
					// rootArg appears in other places)
					if (GetAllFreeVariables.of(f).size() == 0) {
						newSplits.add(createSplittingPair(f, g));
					}
				}
			}
		}
	}
	return newSplits;
}
 
Example 13
Source File: GetApplicationFunction.java    From spf with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void visit(Literal literal) {
	if (isDirectlyMatched(literal)) {
		return;
	}

	final int len = literal.numArgs();
	if (!(argument instanceof Literal)
			|| ((Literal) argument).numArgs() != len) {
		result = false;
		return;
	}

	final Literal argLiteral = (Literal) argument;

	if (literal.getPredicateType().isOrderSensitive()) {
		// Case order sensitive literal.
		argument = argLiteral.getPredicate();
		literal.getPredicate().accept(this);
		if (!result) {
			return;
		}
		for (int i = 0; i < len; ++i) {
			argument = argLiteral.getArg(i);
			literal.getArg(i).accept(this);
			if (!result) {
				return;
			}
		}
	} else {
		// Case order insensitive literal. Similar to how we compare
		// Literal objects.

		final ScopeMapping<Variable, Variable> originalScopeMapping = scope;
		final Map<Variable, LogicalExpression> originalExternalVariableMapping = externalVariableMapping;

		final LogicalExpression[] otherArgsCopy = argLiteral
				.argumentCopy();
		for (int j = 0; j < len; ++j) {
			boolean found = false;
			for (int i = 0; i < len; ++i) {
				if (otherArgsCopy[i] != null) {
					scope = new ScopeMappingOverlay<Variable, Variable>(
							originalScopeMapping,
							new IdentityFastStackMap<Variable, Variable>(),
							new IdentityFastStackMap<Variable, Variable>());
					final HashMap<Variable, LogicalExpression> temporaryMap = new HashMap<Variable, LogicalExpression>(
							originalExternalVariableMapping);
					externalVariableMapping = temporaryMap;
					argument = otherArgsCopy[i];
					literal.getArg(j).accept(this);
					externalVariableMapping = originalExternalVariableMapping;
					if (result) {
						found = true;
						otherArgsCopy[i] = null;
						((ScopeMappingOverlay<Variable, Variable>) scope)
								.applyToBase();
						originalExternalVariableMapping
								.putAll(temporaryMap);
						break;
					} else {
						// Reset the result.
						result = true;
					}
				}
			}
			if (!found) {
				result = false;
				return;
			}
		}
		scope = originalScopeMapping;
	}
}
 
Example 14
Source File: AToExists.java    From spf with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void visit(Literal literal) {
	final int len = literal.numArgs();
	if (aPredicate.equals(literal.getPredicate())) {
		if (len == 1) {
			final Lambda innerLambda = makeEntityToTruthLambda(literal
					.getArg(0));
			if (innerLambda == null) {
				throw new IllegalStateException("Invalid A expression: "
						+ literal);
			}
			innerLambda.getBody().accept(this);
			final Stack<Pair<Variable, ? extends LogicalExpression>> currentStack = new Stack<Pair<Variable, ? extends LogicalExpression>>();
			// To avoid the case of variables shared through various
			// structures, replace the current variable with a new one in
			// the inner body. This is a safe and simple way to solve this
			// problem. More efficient solutions are possible.
			final Variable newVariable = new Variable(innerLambda
					.getArgument().getType());
			// The result contains in the first place the processed body of
			// the inner lambda.
			currentStack.push(Pair.of(
					newVariable,
					ReplaceExpression.of(result.first(),
							innerLambda.getArgument(), newVariable)));
			// Append stack from sub tree
			currentStack.addAll(result.second());
			result = Pair.of(newVariable, currentStack);
		} else {
			throw new IllegalStateException("invalid A expression: "
					+ literal);
		}
	} else {
		literal.getPredicate().accept(this);
		final Pair<? extends LogicalExpression, Stack<Pair<Variable, ? extends LogicalExpression>>> newPredPair = result;

		final LogicalExpression[] newArgs = new LogicalExpression[len];
		final List<Stack<Pair<Variable, ? extends LogicalExpression>>> newStacks = new ArrayList<Stack<Pair<Variable, ? extends LogicalExpression>>>(
				len);
		boolean argsChanged = false;
		for (int i = 0; i < len; ++i) {
			final LogicalExpression arg = literal.getArg(i);
			arg.accept(this);
			newArgs[i] = result.first();
			newStacks.add(result.second());
			if (arg != result.first()) {
				argsChanged = true;
			}
		}

		// Merge stacks returned from all arguments.
		final Stack<Pair<Variable, ? extends LogicalExpression>> mergedStack = new Stack<Pair<Variable, ? extends LogicalExpression>>();
		for (final Stack<Pair<Variable, ? extends LogicalExpression>> stack : newStacks) {
			mergedStack.addAll(stack);
		}

		if (argsChanged || newPredPair.first() != literal.getPredicate()) {
			result = Pair.of(new Literal(newPredPair.first(), newArgs),
					mergedStack);
		} else {
			result = Pair.of(literal, mergedStack);
		}
	}

	// Try to wrap the literal with existential quantifiers.
	result = Pair.of(wrapIfPossible(result.first(), result.second()),
			result.second());

}