edu.cornell.cs.nlp.spf.mr.lambda.Variable Java Examples

The following examples show how to use edu.cornell.cs.nlp.spf.mr.lambda.Variable. 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: LogicalExpressionSimpleIndenter.java    From UDepLambda with Apache License 2.0 6 votes vote down vote up
@Override
public void visit(Variable variable) {
	if (variable instanceof SkolemId) {
		if (!skolemIds.containsKey(variable)) {
			skolemIds.put((SkolemId) variable,
					((SkolemId) variable).getName(skolemIdCounter++));
		}
		outputString.append(skolemIds.get(variable));
	} else {
		outputString.append(getVariableName(variable));
		if (!definedVariables.contains(variable)) {
			outputString.append(Term.TYPE_SEPARATOR);
			outputString.append(variable.getType().getName());
			definedVariables.add(variable);
		}
	}
}
 
Example #2
Source File: GetAmrSubExpressions.java    From amr with GNU General Public License v2.0 6 votes vote down vote up
/**
 * For a given expression, create new expressions by potentially extracting
 * out a single skolem term and wrapping with a {@link Lambda} term. Only
 * extract entities from {@link Lambda} terms. For any other expression,
 * simply return a singleton set with that expression.
 */
private static Set<LogicalExpression> extractEntities(
		LogicalExpression expression) {
	final Set<LogicalExpression> entities = GetAllSkolemTerms.of(
			expression, true);
	final Set<LogicalExpression> expressions = new HashSet<>();
	expressions.add(expression);

	if (expression instanceof Lambda
			&& ((Lambda) expression)
					.getComplexType()
					.getRange()
					.equals(LogicLanguageServices.getTypeRepository()
							.getTruthValueType())) {
		for (final LogicalExpression entity : entities) {
			final Variable variable = new Variable(entity.getType());
			expressions.add(new Lambda(variable, ReplaceExpression.of(
					expression, entity, variable)));
		}
	}

	return expressions;
}
 
Example #3
Source File: IsTypeConsistent.java    From spf with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Verify the argument type against the signature type.
 */
private boolean verifyLiteralArgTyping(LogicalExpression arg,
		Type signatureType) {
	if (arg instanceof Variable) {
		// Case variable: check according to historical type and allow more
		// flexibility.
		return verifyVariableType((Variable) arg, signatureType);
	} else {
		// If the signature expects an array, the argument must be an array.
		// The relation between the signature type and the argument type
		// should be along the inheritance relation, but can be in either
		// direction.
		final boolean literalWellTyped = signatureType.isArray() == arg
				.getType().isArray()
				&& arg.getType().isExtendingOrExtendedBy(signatureType);
		if (!literalWellTyped) {
			message = "Array argument expected, or provided array argument doesn't extend signature array type";
		}
		return literalWellTyped;
	}
}
 
Example #4
Source File: LogicalExpressionApplicationTest.java    From spf with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test1() {
	final Variable variable = new Variable(LogicLanguageServices
			.getTypeRepository().getEntityType());
	final LogicalExpression e1 = new Lambda(variable, new Literal(
			LogicalConstant.read("boo:<e,<<e,t>,t>>"), ArrayUtils.create(
					variable,
					new Lambda(variable,
							new Literal(LogicalConstant.read("goo:<e,t>"),
									ArrayUtils.create(variable))))));
	final LogicalExpression e2 = LogicalExpression
			.read("(lambda $0:e (boo:<e,<<e,t>,t>> $0 (lambda $1:e (goo:<e,t> $1))))");
	Assert.assertEquals(e2, e1);

	final LogicalExpression result1 = TestServices.getCategoryServices()
			.apply(e1, LogicalConstant.read("foo:e"));
	final LogicalExpression result2 = TestServices.getCategoryServices()
			.apply(e2, LogicalConstant.read("foo:e"));
	Assert.assertEquals(result1, result2);
	System.out.println(result1);
}
 
Example #5
Source File: LogicalExpressionToIndentedString.java    From spf with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void visit(Variable variable) {
	if (variable instanceof SkolemId) {
		if (!skolemIds.containsKey(variable)) {
			skolemIds.put((SkolemId) variable,
					((SkolemId) variable).getName(skolemIdCounter++));
		}
		outputString.append(skolemIds.get(variable));
	} else {
		outputString.append(getVariableName(variable));
		if (!definedVariables.contains(variable)) {
			outputString.append(Term.TYPE_SEPARATOR);
			outputString.append(variable.getType().getName());
			definedVariables.add(variable);
		}
	}
}
 
Example #6
Source File: GetApplicationFunctionTest.java    From spf with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testSubExp12() {
	final LogicalExpression appArg = TestServices
			.getCategoryServices()
			.readSemantics(
					"(lambda $0:e (lambda $1:e (lambda $2:e (and:<t*,t> (b:<e,t> $2) (a:<e,t> P:e) (boo:<e,<e,t>> $0 $1)))))");
	final LogicalExpression subExp = TestServices
			.getCategoryServices()
			.readSemantics(
					"(and:<t*,t> (b:<e,t> doo:e) (a:<e,t> P:e) (boo:<e,<e,t>> koo:e loo:e))");
	final Variable replacementVariable = new Variable(LogicLanguageServices
			.getTypeRepository().getType("<e,<e,<e,t>>>"));
	final LogicalExpression expected = new Literal(replacementVariable,
			ArrayUtils.create(
					TestServices.getCategoryServices().readSemantics(
							"koo:e"),
					TestServices.getCategoryServices().readSemantics(
							"loo:e"),
					TestServices.getCategoryServices().readSemantics(
							"doo:e")));
	Assert.assertEquals(expected, GetApplicationFunction.processSubExp(
			subExp, appArg, replacementVariable));
}
 
Example #7
Source File: MakeApplicationSplits.java    From spf with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Replace subExpression in originalExpression with replacementExpression
 * and wrap the result with a Lambda operator with the variable newVariable.
 *
 * @param originalExpression
 * @param subExpression
 *            Assumed to be a sub-expression of originalExpression.
 * @param replacementExpression
 * @param newVariable
 *            replacementExpression already contains this variable.
 * @param index
 *            if 'null', will replace all occurrences of subExpression in
 *            originalExpression. Otherwise will replace the n-th occurrence
 *            only.
 * @return
 */
private static LogicalExpression createFunctor(
		LogicalExpression originalExpression,
		LogicalExpression subExpression,
		LogicalExpression replacementExpression, Variable newVariable,
		Integer index) {
	final LogicalExpression newBody;
	if (index == null) {
		// Case replace all
		newBody = ReplaceExpression.of(originalExpression, subExpression,
				replacementExpression);
	} else {
		// Case replace only a single occurrence
		newBody = ReplaceNthExpression.of(originalExpression,
				subExpression, replacementExpression, index);
	}
	return new Lambda(newVariable, newBody);
}
 
Example #8
Source File: GetApplicationFunctionTest.java    From spf with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testSubExp11() {
	final LogicalExpression appArg = TestServices
			.getCategoryServices()
			.readSemantics(
					"(lambda $1:e (a:<<e,t>,e> (lambda $0:e (and:<t*,t> (b:<e,t> A:e) (a:<e,t> P:e) (pred:<e,<e,t>> $1 $0)))))");
	final Variable replacementVariable = new Variable(LogicLanguageServices
			.getTypeRepository().getType("<e,e>"));
	final LogicalExpression subExp = TestServices
			.getCategoryServices()
			.readSemantics(
					"(a:<<e,t>,e> (lambda $0:e (and:<t*,t> (b:<e,t> A:e) (pred:<e,<e,t>> boo:e $0) (a:<e,t> P:e))))");
	final LogicalExpression expected = new Literal(replacementVariable,
			ArrayUtils.create(TestServices.getCategoryServices()
					.readSemantics("boo:e")));
	Assert.assertEquals(expected, GetApplicationFunction.processSubExp(
			subExp, appArg, replacementVariable));
}
 
Example #9
Source File: GetApplicationFunctionTest.java    From spf with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testSubExp14() {
	final LogicalExpression appArg = TestServices
			.getCategoryServices()
			.readSemantics(
					"(lambda $0:e (lambda $1:e (lambda $2:e (and:<t*,t> (b:<e,t> $2) (a:<e,t> P:e) (boo:<e,<e,t>> $0 $1)))))");
	final LogicalExpression subExp = TestServices
			.getCategoryServices()
			.readSemantics(
					"(and:<t*,t> (a:<e,t> P:e) (boo:<e,<e,t>> koo:e loo:e))");
	final Variable replacementVariable = new Variable(LogicLanguageServices
			.getTypeRepository().getType("<e,<e,<e,t>>>"));
	final LogicalExpression expected = null;
	Assert.assertEquals(expected, GetApplicationFunction.processSubExp(
			subExp, appArg, replacementVariable));
}
 
Example #10
Source File: ReplaceFreeVariablesIfPresent.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visit(Variable variable) {
	if (variables.contains(variable)) {
		if (!oldVariablesToNew.containsKey(variable)) {
			oldVariablesToNew.put(variable,
					new Variable(variable.getType()));
		}
		result = oldVariablesToNew.get(variable);
	} else {
		result = variable;
	}
}
 
Example #11
Source File: HasFreeVariables.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
public static boolean of(LogicalExpression exp, boolean ignoreSkolemIds) {
	if (ignoreSkolemIds && exp.numFreeVariables() != 0) {
		for (final Variable variable : exp.getFreeVariables()) {
			if (!(variable instanceof SkolemId)) {
				return true;
			}
		}
		return false;
	} else {
		return exp.numFreeVariables() != 0;
	}

}
 
Example #12
Source File: ReplaceExpression.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visit(Variable variable) {
	if (subExp.equals(variable)) {
		result = replacement;
	} else {
		result = variable;
	}
}
 
Example #13
Source File: LogicalExpressionToString.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
private void processVariable(Variable variable, boolean lambdaArg) {
	if (lambdaArg || !variableIds.containsKey(variable)) {
		// Push the variable name.
		final String name = Variable.PREFIX
				+ String.valueOf(variableIdCounter++);
		variableIds.push(variable, name);
		outputString.append(name);
		outputString.append(Term.TYPE_SEPARATOR);
		outputString.append(variable.getType().getName());
		definedVariables.add(variable);
	} else {
		outputString.append(variableIds.peek(variable));
	}
}
 
Example #14
Source File: GetApplicationFunctionTest.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testSubExp2() {
	final LogicalExpression appArg = TestServices.getCategoryServices()
			.readSemantics("boo:e");
	final LogicalExpression subExp = TestServices.getCategoryServices()
			.readSemantics("foo:e");
	final Variable replacementVariable = new Variable(LogicLanguageServices
			.getTypeRepository().getType("e"));
	final LogicalExpression expected = null;
	Assert.assertEquals(expected, GetApplicationFunction.processSubExp(
			subExp, appArg, replacementVariable));
}
 
Example #15
Source File: MakeCompositionSplits.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Extract the entire subExpression
 *
 * @param subExpression
 * @param argumentOrder
 *            The free variables in subExpression except the first variables
 *            in originalLambda, which is assumed to be in subExpression as
 *            well.
 * @return
 */
private SplittingPair doSplit(LogicalExpression subExpression,
		List<Variable> argumentOrder) {

	// The h expression
	final Variable rootArg = originalLambda.getArgument();

	// Create variables for the objects we will pull out
	final List<Variable> newVars = new LinkedList<Variable>();
	// The variable x, such that h = \lambda x f(g(x))
	newVars.add(rootArg);
	// The rest of the arguments to the function g
	newVars.addAll(argumentOrder);

	// Create g, such that h = \lambda x f(g(x))
	final LogicalExpression g = SplittingServices.makeExpression(newVars,
			subExpression);

	// Create f, such that h = \lambda x f(g(x))
	newVars.remove(rootArg);
	final Variable compositionArgument = new Variable(LogicLanguageServices
			.getTypeRepository().generalizeType(g.getType().getRange()));
	final LogicalExpression embeddedApplication = SplittingServices
			.makeAssignment(newVars, compositionArgument);
	final LogicalExpression newBody = ReplaceExpression.of(
			originalLambda.getBody(), subExpression, embeddedApplication);
	final Lambda f = new Lambda(compositionArgument, newBody);

	// Verify that f has no free arguments. Can happen if rootArg appears in
	// another part of the expression.
	if (GetAllFreeVariables.of(f).size() == 0) {
		// Create the splitting pair and return it
		return createSplittingPair(f, g);
	} else {
		return null;
	}
}
 
Example #16
Source File: AllConstrainedSubExpressions.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
private boolean addSubExpression(LogicalExpression sub) {
	if (sub instanceof Variable) {
		return false;
	} else {
		return subExpressions.add(sub);
	}
}
 
Example #17
Source File: SkolemIdInstanceWrapper.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean equals(LogicalExpression exp,
		ScopeMapping<Variable, Variable> mapping) {
	if (exp instanceof SkolemIdInstanceWrapper) {
		return base == ((SkolemIdInstanceWrapper) exp).base;
	} else {
		return base == exp;
	}
}
 
Example #18
Source File: LambdaWrapped.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Assumes the type of exp is complex.
 *
 * @param exp
 * @return
 */
private static Lambda wrap(LogicalExpression exp) {
	final Variable newVariable = new Variable(LogicLanguageServices
			.getTypeRepository().generalizeType(exp.getType().getDomain()));
	final LogicalExpression[] args = new LogicalExpression[1];
	args[0] = newVariable;
	LogicalExpression newLiteral = new Literal(exp, args);
	if (newLiteral.getType().isComplex()) {
		newLiteral = wrap(newLiteral);
	} else {
		newLiteral = Simplify.of(newLiteral);
	}
	return new Lambda(newVariable, newLiteral);
}
 
Example #19
Source File: LogicalExpressionEqualsTest.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test7() {
	final Variable variable = new Variable(LogicLanguageServices
			.getTypeRepository().getEntityType());
	final LogicalExpression e1 = new Lambda(variable, new Literal(
			LogicalConstant.read("boo:<e,<<e,t>,t>>"), ArrayUtils.create(
					variable,
					new Lambda(variable,
							new Literal(LogicalConstant.read("goo:<e,t>"),
									ArrayUtils.create(variable))))));
	final LogicalExpression e2 = LogicalExpression
			.read("(lambda $0:e (boo:<e,<<e,t>,t>> $0 (lambda $1:e (goo:<e,t> $1))))");
	Assert.assertEquals(e2, e1);
}
 
Example #20
Source File: SloppyAmrClosure.java    From amr with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visit(Variable variable) {
	if (!boundVariables.contains(variable)
			&& !variable.getType().isComplex()) {
		result = null;
	} else {
		result = variable;
	}
}
 
Example #21
Source File: ApplyAndSimplify.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This constructor is private as a small part of the logic is in the static
 * {@link #of(LogicalExpression, LogicalExpression, boolean, boolean)}
 * method. Therefore, this visitor is not independent.
 */
private ApplyAndSimplify(LogicalExpression appliedToArg,
		Variable rootVariable) {
	super(false);
	this.appliedToArg = appliedToArg;
	this.rootVariable = rootVariable;
}
 
Example #22
Source File: SplittingServices.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
public static LogicalExpression makeAssignment(List<Variable> argVars,
		Variable newVar) {

	if (argVars == null || newVar == null) {
		return null;
	}
	if (argVars.size() == 0) {
		return newVar;
	}

	// Wrapping the list, so we can use it to create a literal. Ugly
	// solution, but welcome to the wonderful world of Java generics.
	return new Literal(newVar,
			argVars.toArray(new LogicalExpression[argVars.size()]));
}
 
Example #23
Source File: AbstractTypeRaising.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
private static LogicalExpression raiseSemantics(LogicalExpression sem,
		Type finalResultSemanticType) {
	final Variable variable = new Variable(LogicLanguageServices
			.getTypeRepository().getTypeCreateIfNeeded(
					LogicLanguageServices.getTypeRepository()
							.generalizeType(finalResultSemanticType),
					LogicLanguageServices.getTypeRepository()
							.generalizeType(sem.getType())));
	return new Lambda(variable, new Literal(variable,
			ArrayUtils.create(sem)));
}
 
Example #24
Source File: ReplaceNthExpression.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visit(Variable variable) {
	if (subExp.equals(variable)) {
		numTimesSeen++;
		if (numTimesSeen == n) {
			result = replacement;
			return;
		}
	}
	result = variable;
}
 
Example #25
Source File: StripSkolemIds.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visit(Variable variable) {
	if (variable instanceof SkolemId) {
		result = placeholder;
	} else {
		result = variable;
	}
}
 
Example #26
Source File: SententialAdverbialTypeShifting.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Set<Category<LogicalExpression>> reverseApply(
		Category<LogicalExpression> result, SentenceSpan span) {
	final Unification syntaxUnification = result.getSyntax().unify(
			S_FS_AP_SYNTAX);
	if (result instanceof ComplexCategory && syntaxUnification != null) {
		// Create an argument category with semantics of (lambda $0:x
		// true:t). Consuming this as argument and simplifying should
		// reverse the shifting safely (and somewhat efficiently).
		final LogicalExpression semantics = result.getSemantics();
		if (semantics instanceof Lambda) {
			final Variable argument = ((Lambda) semantics).getArgument();
			if (argument.getType().isComplex()
					&& LogicLanguageServices.getTypeRepository()
							.getTruthValueType()
							.equals(argument.getType().getRange())) {
				final LogicalExpression reversedSemantics = categoryServices
						.apply(semantics, new Lambda(new Variable(argument
								.getType().getDomain()),
								LogicLanguageServices.getTrue()));
				if (reversedSemantics != null) {
					return SetUtils.createSingleton(Category.create(
							((ComplexSyntax) syntaxUnification
									.getUnifiedSyntax()).getLeft(),
							reversedSemantics));
				}
			}
		}

	}
	return Collections.emptySet();
}
 
Example #27
Source File: IsTypeConsistent.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Verifies consistency between a variable and its usage in a literal. If
 * the variable's historic type is unknown, it's a free variable -- treat it
 * like a constant. Therefore, this method shouldn't be called when
 * encountering the variables definition, but only its usage.
 */
private boolean verifyVariableType(Variable variable, Type signatureType) {
	final Type historicaltype = variableTypes.get(variable);
	if (historicaltype == null) {
		// Case not historical type, treat like a constant -- check it's
		// extending or extended by. Also, add to variableTypes. This
		// variable will never be removed from types, since its scoping is
		// global.
		variableTypes.put(variable, variable.getType());
		final boolean goodArg = variable.getType().isExtendingOrExtendedBy(
				signatureType);
		if (!goodArg) {
			message = "Argument type is incompatible with signature type (not extending or extended by signature type)";
		}
		return goodArg;
	} else {
		if (signatureType.isExtending(historicaltype)) {
			// Case the current signature type is a narrower instance of the
			// historical type, so remember it and return 'true'.
			variableTypes.put(variable, signatureType);
			return true;
		} else {
			// Return 'true' if the signature type is a narrower instance of
			// the historical type, so just return 'true'.
			final boolean extendingHistorical = historicaltype
					.isExtending(signatureType);
			if (!extendingHistorical) {
				message = "Mismatch between different uses of the same variable (e.g., one instance casts a specific type that another doesn't extend)";
			}
			return extendingHistorical;
		}
	}
}
 
Example #28
Source File: AttachmentFeatures.java    From amr with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visit(Variable variable) {
	// Substituting a functional variable may change how elements are
	// relating to each other and the features computed, so we reset the
	// current typing predicate.
	if (variable.getType().isComplex()) {
		nestedTypingConstants.clear();
	}
}
 
Example #29
Source File: GetApplicationArgumentTest.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testCreateArg3() {
	final LogicalExpression resultSubExp = TestServices
			.getCategoryServices().readSemantics("(pred:<e,t> boo:e)");
	final LogicalExpression function = TestServices.getCategoryServices()
			.readSemantics("(lambda $0:<e,t> ($0 boo:e))");
	final Variable applicationArg = ((Lambda) function).getArgument();
	final LogicalExpression expected = TestServices.getCategoryServices()
			.readSemantics("pred:<e,t>");
	Assert.assertEquals(expected,
			GetApplicationArgument.createArgument(resultSubExp,
					((Lambda) function).getBody(), applicationArg,
					new ScopeMapping<Variable, Variable>()));

}
 
Example #30
Source File: LogicalExpressionSimpleIndenter.java    From UDepLambda with Apache License 2.0 5 votes vote down vote up
private String getVariableName(Variable variable) {
	int num = 0;
	for (final Variable namedVariable : variablesNamingList) {
		if (namedVariable == variable) {
			return "$" + String.valueOf(num);
		}
		++num;
	}
	variablesNamingList.add(variable);
	return "$" + String.valueOf(num);
}