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

The following examples show how to use edu.cornell.cs.nlp.spf.mr.lambda.Literal#getArg() . 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: IsTypeConsistent.java    From spf with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void visit(Literal literal) {
	literal.getPredicate().accept(this);
	// Check the arguments match the type of the function.
	final int len = literal.numArgs();
	for (int i = 0; i < len; ++i) {
		final LogicalExpression arg = literal.getArg(i);

		// Visit the argument.
		arg.accept(this);

		// Match the type of the argument with the signature type.
		final Type signatureType = literal.getArgSignature(i);
		wellTyped = wellTyped && verifyLiteralArgTyping(arg, signatureType);

		if (!wellTyped) {
			LOG.debug(
					"Literal %s is not well-typed. Mismatch between signature type %s to argument %s.",
					literal, signatureType, arg);
			return;
		}
	}
}
 
Example 2
Source File: IncSimplifier.java    From spf with GNU General Public License v2.0 6 votes vote down vote up
@Override
public LogicalExpression simplify(LogicalExpression exp) {
	if (exp instanceof Literal) {
		final Literal literal = (Literal) exp;
		if (literal.numArgs() == 1
				&& literal.getArg(0) instanceof LogicalConstant
				&& literal.getArg(0).getType() == LogicLanguageServices
						.getTypeRepository().getIndexType()) {
			// If we have a single argument and it's a constant of type
			// index, replace it with a new constant
			final int i = LogicLanguageServices
					.indexConstantToInt((LogicalConstant) literal.getArg(0));
			return LogicLanguageServices.intToIndexConstant(i + 1);
		}
	}
	return exp;
}
 
Example 3
Source File: DummyEntityServices.java    From amr with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Given a lambda term (e.g., (lambda $0:e (and:<t*,t> ...))), return 'true'
 * iff its body contains relation literals and at least one of them has a
 * dummy entity.
 */
public static boolean hasDummyEntity(Lambda lambda) {
	if (lambda.getBody() instanceof Literal) {
		final Literal bodyLiteral = (Literal) lambda.getBody();
		if (LogicLanguageServices.getConjunctionPredicate().equals(
				bodyLiteral.getPredicate())) {
			final int len = bodyLiteral.numArgs();
			for (int i = 0; i < len; ++i) {
				final LogicalExpression arg = bodyLiteral.getArg(i);
				if (arg instanceof Literal) {
					if (isRelationWithDummy((Literal) arg)) {
						return true;
					}
				}
			}
		} else if (isRelationWithDummy(bodyLiteral)) {
			return true;
		}
	}
	return false;

}
 
Example 4
Source File: DummyEntityServices.java    From amr with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Given a skolem term (i.e., (a:<<e,t>,<id,e>> na:id (lambda $0:e
 * (and:<t*,t> .... (pred:<e,<e,t>> $0 DUMMY:e) .... )))), removes the
 * literal that includes the DUMMY:e entity as second argument, and returns
 * its predicate. If the dummy entity appears more than once, fail.
 *
 * @return Pair of stripped skolem term (in first position) and the
 *         predicate of the relation with the stripped dummy argument
 *         (second position).
 */
public static Pair<Literal, LogicalConstant> stripDummy(Literal literal) {
	if (AMRServices.isSkolemTerm(literal) && literal.numArgs() == 2
			&& literal.getArg(1) instanceof Lambda) {
		final Pair<Lambda, LogicalConstant> pair = stripDummy((Lambda) literal
				.getArg(1));
		if (pair != null) {
			return Pair.of(AMRServices.skolemize(pair.first()),
					pair.second());
		}
	}
	return null;
}
 
Example 5
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 6
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 7
Source File: NotSimplifier.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Override
public LogicalExpression simplify(LogicalExpression exp) {
	if (exp instanceof Literal) {
		// If the argument is a literal with 'not:t' predicate, return the
		// argument for the inner literal
		final Literal literal = (Literal) exp;

		// If we have more than one argument, don't do anything, this
		// expression is one bad apple
		if (literal.numArgs() == 1) {
			if (literal.getArg(0) instanceof Literal
					&& ((Literal) literal.getArg(0)).getPredicate().equals(
							literal.getPredicate())) {
				// Case the only argument is a 'not:t' literal, so return
				// its
				// single argument
				final Literal subNot = (Literal) literal.getArg(0);
				if (subNot.numArgs() == 1) {
					return subNot.getArg(0);
				}
			} else if (literal.getArg(0) == LogicLanguageServices.getTrue()) {
				// If the single argument is 'true:t' constant, return
				// 'false:t'
				return LogicLanguageServices.getFalse();
			} else if (literal.getArg(0) == LogicLanguageServices
					.getFalse()) {
				// If the single argument is 'false:t' constant, return
				// 'true:t'
				return LogicLanguageServices.getTrue();
			}

		}
		// Case didn't change anything
		return exp;
	} else {
		return exp;
	}
}
 
Example 8
Source File: AllConstrainedSubExpressions.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visit(Literal literal) {
	addSubExpression(literal);

	// Add the literal
	addSubExpression(literal.getPredicate());

	final int numArgs = literal.numArgs();
	if (numArgs == 1) {
		// Case single argument, continue to visit arguments
		for (int i = 0; i < numArgs; ++i) {
			literal.getArg(i).accept(this);
		}
	} else {
		// Case multiple arguments, don't traverse deeper into the logical
		// expression. Add the arguments as sub-expressions.

		// Add the first arg to the set of subexpressions and get its
		// sub-expressions, to look for shared sub-expressions
		final LogicalExpression firstArg = literal.getArg(0);
		addSubExpression(firstArg);
		final Set<LogicalExpression> sharedSubExpressions = new HashSet<LogicalExpression>(
				AllSubExpressions.of(firstArg));

		// Iterate over the rest of the expressions
		for (int i = 1; i < numArgs; ++i) {
			final LogicalExpression arg = literal.getArg(i);
			addSubExpression(arg);
			sharedSubExpressions.retainAll(AllSubExpressions.of(arg));
		}

		// Add shared sub-expressions
		for (final LogicalExpression sharedSub : sharedSubExpressions) {
			addSubExpression(sharedSub);
		}
	}
}
 
Example 9
Source File: LogicalExpressionToAmr.java    From amr with GNU General Public License v2.0 5 votes vote down vote up
private static Literal getTypingLiteral(Literal literal) {
	final int len = literal.numArgs();
	for (int i = 0; i < len; i++) {
		final LogicalExpression arg = literal.getArg(i);
		if (arg instanceof Literal
				&& ((Literal) arg).numArgs() == 1
				&& ((Literal) arg).getPredicate() instanceof LogicalConstant) {
			return (Literal) arg;
		}
	}
	return null;
}
 
Example 10
Source File: DummyEntityServices.java    From amr with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Given a skolem term (i.e., (a:<<e,t>,<id,e>> na:id (lambda $0:e ....))),
 * return 'true' iff it has a relation to a dummy entity.
 */
public static boolean hasDummyEntity(Literal literal) {
	if (AMRServices.isSkolemTerm(literal) && literal.numArgs() == 2
			&& literal.getArg(1) instanceof Lambda) {
		return hasDummyEntity((Lambda) literal.getArg(1));
	} else {
		return false;
	}
}
 
Example 11
Source File: CoordinationServices.java    From amr with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Given a coordination skolem term, return all the coordinated elements
 * (i.e., the second arguments in all c_opX binary literals in the upper
 * most conjunction).
 */
public static List<LogicalExpression> getCoordinatedItems(
		Literal coordination) {
	final LogicalExpression coordinationBody = ((Lambda) coordination
			.getArg(1)).getBody();
	if (coordinationBody instanceof Literal
			&& LogicLanguageServices
					.isCoordinationPredicate(((Literal) coordinationBody)
							.getPredicate())) {
		final Literal coordinationBodyLiteral = (Literal) coordinationBody;
		final int coordinationBodyLiteralNumArgs = coordinationBodyLiteral
				.numArgs();
		final List<LogicalExpression> items = new ArrayList<>(
				coordinationBodyLiteralNumArgs);
		for (int i = 0; i < coordinationBodyLiteralNumArgs; ++i) {
			final LogicalExpression arg = coordinationBodyLiteral.getArg(i);
			if (arg instanceof Literal
					&& ((Literal) arg).numArgs() == 2
					&& ((Literal) arg).getPredicate() instanceof LogicalConstant
					&& isCOpPredicate((LogicalConstant) ((Literal) arg)
							.getPredicate())) {
				items.add(((Literal) arg).getArg(1));
			}
		}
		return items;
	} else {
		return Collections.emptyList();
	}
}
 
Example 12
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 13
Source File: AMRServices.java    From amr with GNU General Public License v2.0 5 votes vote down vote up
public static boolean isNamedEntityBody(Lambda entityBody) {
	if (entityBody.getComplexType().getDomain()
			.equals(LogicLanguageServices.getTypeRepository()
					.getEntityType())
			&& entityBody.getComplexType().getRange()
					.equals(LogicLanguageServices.getTypeRepository()
							.getTruthValueType())
			&& entityBody.getBody() instanceof Literal) {
		final Literal bodyLiteral = (Literal) entityBody.getBody();
		if (bodyLiteral.getPredicate()
				.equals(LogicLanguageServices.getConjunctionPredicate())) {
			final int len = bodyLiteral.numArgs();
			for (int i = 0; i < len; ++i) {
				final LogicalExpression arg = bodyLiteral.getArg(i);
				if (arg instanceof Literal && ((Literal) arg).numArgs() == 2
						&& ((Literal) arg).getArg(1) instanceof Literal
						&& isSkolemTerm(
								(Literal) ((Literal) arg).getArg(1))) {
					if (INSTANCE.nameInstancePredicate
							.equals(getTypingPredicate(
									(Literal) ((Literal) arg).getArg(1)))) {
						return true;
					}
				}
			}
		}
	}
	return false;
}
 
Example 14
Source File: AMRServices.java    From amr with GNU General Public License v2.0 5 votes vote down vote up
public static boolean isNamedEntity(Literal skolemTerm) {
	if (skolemTerm.numArgs() == 2
			&& skolemTerm.getArg(1) instanceof Lambda) {
		return isNamedEntityBody((Lambda) skolemTerm.getArg(1));
	}

	return false;
}
 
Example 15
Source File: AMRServices.java    From amr with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Given a skolem term, return the unary predicate that defines its type, if
 * such exist.
 */
public static LogicalConstant getTypingPredicate(Literal skolemTerm) {
	if (skolemTerm.numArgs() == 2
			&& skolemTerm.getArg(1) instanceof Lambda) {
		return getTypingPredicate((Lambda) skolemTerm.getArg(1));
	}
	return null;
}
 
Example 16
Source File: CoordinationCX4Rule.java    From amr with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected Category<LogicalExpression> doApply(LogicalExpression first,
		Literal rest, Syntax resultSyntax,
		LogicalConstant coordinationWrapper) {
	// Get the variables of the first argument and strip it from lambda
	// terms.
	LogicalExpression firstElement = first;
	final List<Variable> commonVariables = new LinkedList<>();
	while (firstElement instanceof Lambda) {
		commonVariables.add(((Lambda) firstElement).getArgument());
		firstElement = ((Lambda) firstElement).getBody();
	}

	// Extract the upper-most e-typed element from the first element.
	final Result extraction = ExtractTypedSubExpression.of(firstElement,
			extractionPlaceholder, LogicLanguageServices
					.getTypeRepository().getEntityType(), false);
	if (extraction == null) {
		return null;
	}
	firstElement = extraction.getExtractedSubExpression();
	final LogicalExpression remainder = extraction
			.getExpressionWithPlaceholder();

	// The remaining expression is used collectively over the coordination
	// entity we are creating. If this expression includes other entities,
	// return null. This avoids "swallowing" repeating entities.
	if (ContainsConstantType.of(remainder,
			AMRServices.getTypingPredicateType())) {
		return null;
	}

	// For each of the remaining arguments, strip all lambdas using
	// applications, extract the sub-expression and verify the remainder is
	// identical.
	final int restNumArgs = rest.numArgs();
	final LogicalExpression[] coordinationArguments = new LogicalExpression[restNumArgs + 1];
	coordinationArguments[0] = firstElement;
	for (int i = 0; i < restNumArgs; ++i) {
		LogicalExpression strippedArg = rest.getArg(i);
		for (final Variable variable : commonVariables) {
			strippedArg = categoryServices.apply(strippedArg, variable);
			if (strippedArg == null) {
				return null;
			}
		}
		final Result argExtraction = ExtractTypedSubExpression.of(
				strippedArg, extractionPlaceholder, LogicLanguageServices
						.getTypeRepository().getEntityType(), false);
		if (argExtraction == null
				|| !argExtraction.getExpressionWithPlaceholder().equals(
						remainder)) {
			return null;
		}
		coordinationArguments[i + 1] = argExtraction
				.getExtractedSubExpression();
	}

	// Create the AMR coordination.
	final LogicalExpression coordination = CoordinationServices
			.createCoordination(coordinationArguments,
					LogicLanguageServices.getTypeRepository()
							.getEntityType(), coordinationWrapper);
	if (coordination == null) {
		return null;
	}

	// Place the coordination inside the remainder.
	final LogicalExpression finalBody = ReplaceExpression.of(remainder,
			extractionPlaceholder, AMRServices.skolemize(coordination));

	// Wrap with lambda terms for the common variables and create the
	// category.
	final LogicalExpression finalSemantics = wrapWithLambdas(finalBody,
			commonVariables);
	return Category
			.<LogicalExpression> create(resultSyntax, finalSemantics);
}
 
Example 17
Source File: AMRSupervisedFilter.java    From amr with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @see CollectStats#typeRelatedTypeTriplets
 * @see TypeRelatedTypeTriplet
 */
private void countInstanceTypeRelatedTypeTriplets(
		Literal conjunctionLiteral) {
	// Can collect triplets only from conjunctions with multiple
	// conjuncts.
	final int conjLiteralNumArgs = conjunctionLiteral.numArgs();
	if (conjLiteralNumArgs > 1) {
		// Try to get the typing predicate if one exists.
		final LogicalConstant typingPredicate = OverloadedLogicalConstant
				.getWrapped(
						AMRServices.getTypingPredicateFromConjunction(
								conjunctionLiteral));
		if (typingPredicate == null
				|| !constantFilter.test(typingPredicate)) {
			return;
		}

		// For every binary relation, create a triplet if the second
		// argument has no free variables.
		for (int i = 0; i < conjLiteralNumArgs; ++i) {
			final LogicalExpression arg = conjunctionLiteral.getArg(i);
			if (arg instanceof Literal && ((Literal) arg).numArgs() == 2
					&& ((Literal) arg)
							.getPredicate() instanceof LogicalConstant
					&& !HasFreeVariables.of(((Literal) arg).getArg(1),
							true)) {
				final LogicalExpression arg2 = ((Literal) arg)
						.getArg(1);
				final LogicalConstant relation = OverloadedLogicalConstant
						.getWrapped((LogicalConstant) ((Literal) arg)
								.getPredicate());
				if (arg2 instanceof Literal
						&& AMRServices.isSkolemTerm((Literal) arg2)) {
					final LogicalConstant arg2TypingPredicate = OverloadedLogicalConstant
							.getWrapped(AMRServices.getTypingPredicate(
									(Literal) arg2));
					if (arg2TypingPredicate != null && constantFilter
							.test(arg2TypingPredicate)) {
						count(new TypeRelatedTypeTriplet(
								typingPredicate, relation,
								arg2TypingPredicate),
								typeRelatedTypeTriplets,
								typeRelatedTypeTripletsRef);
						if (!isValid) {
							return;
						}
					}
				} else if (arg2 instanceof LogicalConstant) {
					final LogicalConstant arg2Const = OverloadedLogicalConstant
							.getWrapped((LogicalConstant) arg2);
					if (constantFilter.test(arg2Const)) {
						count(new TypeRelatedTypeTriplet(
								typingPredicate, relation, arg2Const),
								typeRelatedTypeTriplets,
								typeRelatedTypeTripletsRef);
						if (!isValid) {
							return;
						}
					}
				} else if (arg2 instanceof Literal
						&& AMRServices.isRefPredicate(
								((Literal) arg2).getPredicate())) {
					count(new TypeRelatedTypeTriplet(typingPredicate,
							relation, ((Literal) arg2).getPredicate()),
							typeRelatedTypeTriplets,
							typeRelatedTypeTripletsRef);
					if (!isValid) {
						return;
					}
				}
			}
		}
	}
}
 
Example 18
Source File: AbstractCoordinationCXRaisedApply.java    From amr with GNU General Public License v2.0 4 votes vote down vote up
protected Category<LogicalExpression> doApply(
		ComplexCategory<LogicalExpression> function,
		Category<LogicalExpression> coordiantedArguments) {
	if (coordiantedArguments.getSyntax() instanceof CoordinationSyntax
			&& function
					.getSyntax()
					.getRight()
					.equals(((CoordinationSyntax) coordiantedArguments
							.getSyntax()).getCoordinatedSyntax())
			&& coordiantedArguments.getSemantics() instanceof Literal
			&& ((Literal) coordiantedArguments.getSemantics())
					.getPredicate() instanceof LogicalConstant
			&& ((Literal) coordiantedArguments.getSemantics()).numArgs() >= 2) {
		// Get all the arguments, apply the function to each one of them,
		// and try to coordinate them. The output syntax is the functor
		// syntax following the application.
		final Literal coordinationLiteral = (Literal) coordiantedArguments
				.getSemantics();
		LogicalExpression arg0 = null;
		final int coordLiteralNumArgs = coordinationLiteral.numArgs();
		final LogicalExpression[] appliedArgs = new LogicalExpression[coordLiteralNumArgs - 1];
		// Accumulate all variables to make sure we don't duplicate any.
		Type argType = null;
		final LogicalExpression func = ReplaceFreeVariablesIfPresent.of(
				function.getSemantics(),
				coordinationLiteral.getFreeVariables());
		for (int i = 0; i < coordLiteralNumArgs; ++i) {
			final LogicalExpression arg = coordinationLiteral.getArg(i);
			final LogicalExpression appliedArg = categoryServices.apply(
					func, arg);
			if (appliedArg == null) {
				return null;
			} else {
				if (i == 0) {
					arg0 = appliedArg;
				} else {
					appliedArgs[i - 1] = appliedArg;
				}
				if (argType == null
						|| appliedArg.getType().isExtending(argType)) {
					argType = appliedArg.getType();
				}
			}
		}
		return cxRule.doApply(arg0, CoordinationServices.createLiteral(
				((LogicalConstant) coordinationLiteral.getPredicate())
						.getBaseName(), appliedArgs, argType), function
				.getSyntax().getLeft(),
				(LogicalConstant) ((Literal) coordiantedArguments
						.getSemantics()).getPredicate());
	}
	return null;
}
 
Example 19
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 20
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());

}