Java Code Examples for edu.cornell.cs.nlp.spf.mr.lambda.Literal

The following examples show how to use edu.cornell.cs.nlp.spf.mr.lambda.Literal. These examples are extracted from open source projects. 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 Project: UDepLambda   Source File: PostProcessLogicalForm.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * From a given logical expression, the main predicates are extracted, make
 * them more readable, link the variables to the sources from which they
 * originated.
 * 
 * @param sentence the source sentence
 * @param parse the logical expression to be processed
 * @param lexicalizePredicates lexicalize predicates by appending the event,
 *        e.g., eat(1:e) ^ arg1(1:e , 1:x) becomes eat.arg1(1:e , 1:x)
 * @return the set of main predicates in readable format
 */
public static Set<String> process(Sentence sentence, LogicalExpression parse,
    boolean lexicalizePredicates) {
  List<Literal> mainPredicates = new ArrayList<>();
  Map<Term, List<Integer>> varToEvents = new HashMap<>();
  Map<Term, List<Integer>> varToEntities = new HashMap<>();
  Map<Term, List<Term>> varToConj = new HashMap<>();
  List<Pair<Term, Term>> equalPairs = new ArrayList<>();
  process(mainPredicates, varToEvents, varToEntities, varToConj, equalPairs,
      sentence, parse);

  // TODO(sivareddyg) handle predicates p_CONJ and p_EQUAL in both varToEvents
  // and varToEntities.
  cleanVarToEntities(varToEntities, sentence);
  cleanVarToEvents(varToEvents, sentence);
  populateConj(varToConj, varToEntities, varToEvents);
  populateEquals(equalPairs, varToEntities, varToEvents);
  Set<String> cleanedPredicates =
      createCleanPredicates(mainPredicates, varToEvents, varToEntities,
          sentence, lexicalizePredicates);
  return cleanedPredicates;
}
 
Example 2
Source Project: UDepLambda   Source File: PostProcessLogicalForm.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the main predicates, i.e., the predicates that start with p_.
 * 
 * @param parse
 * @param predicates
 */
public static void getMainPredicates(LogicalExpression parse,
    List<Literal> predicates) {
  if (parse instanceof Lambda) {
    getMainPredicates(((Lambda) parse).getBody(), predicates);
  } else if (parse instanceof Literal) {
    if (((Literal) parse).getPredicate().toString().startsWith("p_")) {
      // System.out.println(parse);
      predicates.add((Literal) parse);
      ((Literal) parse).getArg(0).hashCode();
    } else {
      for (int i = 0; i < ((Literal) parse).numArgs(); i++) {
        getMainPredicates(((Literal) parse).getArg(i), predicates);
      }
    }
  }
}
 
Example 3
Source Project: spf   Source File: GetPredicateCounts.java    License: 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 4
@Test
public void testCreateArg4() {
	final LogicalExpression resultSubExp = TestServices
			.getCategoryServices().readSemantics("(pred:<e,t> $0:e)");
	final LogicalExpression functionSubExp = TestServices
			.getCategoryServices().readSemantics("($1:<e,t> $0:e)");
	final Variable applicationArg = (Variable) ((Literal) functionSubExp)
			.getPredicate();
	final LogicalExpression expected = TestServices.getCategoryServices()
			.readSemantics("pred:<e,t>");
	final ScopeMapping<Variable, Variable> scope = new ScopeMapping<Variable, Variable>();
	scope.push((Variable) ((Literal) functionSubExp).getArg(0),
			(Variable) ((Literal) resultSubExp).getArg(0));
	Assert.assertEquals(expected, GetApplicationArgument.createArgument(
			resultSubExp, functionSubExp, applicationArg, scope));

}
 
Example 5
@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 6
@Override
public ParseRuleResult<LogicalExpression> apply(
		Category<LogicalExpression> left,
		Category<LogicalExpression> right, SentenceSpan span) {
	final CoordinationSyntax unification = CoordinationServices
			.unifyCategories(left, right);
	if (unification != null) {
		final Category<LogicalExpression> resultCategory = doApply(
				ReplaceFreeVariablesIfPresent.of(left.getSemantics(), right
						.getSemantics().getFreeVariables()),
				(Literal) right.getSemantics(),
				unification.getCoordinatedSyntax(),
				(LogicalConstant) ((Literal) right.getSemantics())
						.getPredicate());
		if (resultCategory != null) {
			return new ParseRuleResult<>(ruleName, resultCategory);
		}
	}

	return null;
}
 
Example 7
Source Project: amr   Source File: CoordinationC2Rule.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected ParseRuleResult<LogicalExpression> doApply(
		LogicalExpression left, Literal right, CoordinationSyntax syntax) {
	final Type baseType = right.getType();

	// Create the argument list and the new semantic form.
	final int numArgs = right.numArgs();
	final LogicalExpression[] arguments = new LogicalExpression[numArgs + 1];
	// Make sure there's no free variable overlap.
	arguments[0] = ReplaceFreeVariablesIfPresent.of(left,
			right.getFreeVariables());
	right.copyArgsIntoArray(arguments, 0, 1, numArgs);

	// Create the return category, including the syntactic
	// component.
	final Category<LogicalExpression> resultCategory = Category
			.<LogicalExpression> create(syntax, CoordinationServices
					.createLiteral(((LogicalConstant) right.getPredicate())
							.getBaseName(), arguments, baseType));

	return new ParseRuleResult<>(ruleName, resultCategory);
}
 
Example 8
@Override
public void visit(Literal literal) {
	increaseDepth();
	boolean literalHasOnlyVariables = true;
	literal.getPredicate().accept(this);
	literalHasOnlyVariables &= variablesOnly;
	final int len = literal.numArgs();
	for (int i = 0; i < len; ++i) {
		literal.getArg(i).accept(this);
		literalHasOnlyVariables &= variablesOnly;
	}
	--depth;

	if (!literalHasOnlyVariables
			&& (!skipCoordinations || !LogicLanguageServices
					.isCoordinationPredicate(literal.getPredicate()))) {
		addCurrent(literal);
	}
}
 
Example 9
Source Project: amr   Source File: NounPhraseWithDummy.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public ParseRuleResult<LogicalExpression> apply(
		Category<LogicalExpression> category, SentenceSpan span) {
	if (isValidArgument(category, span)) {
		final Pair<Literal, LogicalConstant> pair = DummyEntityServices
				.stripDummy((Literal) category.getSemantics());
		if (pair != null) {
			final LogicalConstant inversedRelation = AMRServices
					.makeRelationPassive(pair.second(), true);
			if (inversedRelation != null) {
				return new ParseRuleResult<>(name, Category.create(
						targetSyntax, categoryServices.apply(
								categoryServices.apply(helperCategory,
										inversedRelation), pair.first())));
			}
		}
	}
	return null;
}
 
Example 10
@Test
public void testSubExp13() {
	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) (b:<e,t> doo: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 11
@Override
public void setFeatures(IParseStep<LogicalExpression> step,
		IHashVector feats, DI dataItem) {
	if (step instanceof IOverloadedParseStep) {
		final UnaryRuleName rule = ((IOverloadedParseStep<LogicalExpression>) step)
				.getRuleName().getUnaryRule();
		final LogicalExpression semantics = ((IOverloadedParseStep<LogicalExpression>) step)
				.getIntermediate().getSemantics();
		if (semantics != null) {
			final LogicalConstant instanceType;
			if (AMRServices.isSkolemTerm(semantics)) {
				instanceType = AMRServices
						.getTypingPredicate((Literal) semantics);
			} else if (AMRServices.isSkolemTermBody(semantics)) {
				instanceType = AMRServices
						.getTypingPredicate((Lambda) semantics);
			} else {
				return;
			}
			if (instanceType != null) {
				feats.set(tag, rule.toString(), instanceType.getBaseName(),
						1.0 * scale);
			}
		}
	}
}
 
Example 12
Source Project: spf   Source File: Evaluation.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected boolean isPartialLiteral(Literal literal) {
	// Count number of arguments on predicate type
	Type type = literal.getPredicateType();
	int numArgs = 0;
	while (type.isComplex()) {
		if (type instanceof RecursiveComplexType) {
			numArgs += ((RecursiveComplexType) type).getMinArgs();
			type = ((RecursiveComplexType) type).getFinalRange();
		} else {
			++numArgs;
			type = type.getRange();
		}
	}

	return literal.numArgs() < numArgs;
}
 
Example 13
@SuppressWarnings("unchecked")
public AMRSupervisedFilterFactory(
		Predicate<LogicalConstant> constantsFilter) {
	this.constantFilter = (Serializable & Predicate<LogicalConstant>) constant -> !(LogicLanguageServices
			.isCollpasibleConstant(constant)
			|| LogicLanguageServices.isArrayIndexPredicate(constant)
			|| constant.getType().equals(SkolemServices.getIDType())
			|| constant.equals(AMRServices.getDummyEntity())
			|| CoordinationServices.isCoordinator(constant))
			&& constantsFilter.test(constant);
	this.baseFilterFactory = new SupervisedFilterFactory<>(
			this.constantFilter,
			(Serializable & Predicate<LogicalExpression>) (
					arg) -> !(arg instanceof Literal && (DummyEntityServices
							.isRelationWithDummy((Literal) arg)
							|| ((Literal) arg).numArgs() == 2
									&& ((Literal) arg)
											.getArg(1) instanceof Variable)),
			(Serializable & UnaryOperator<LogicalConstant>) c -> OverloadedLogicalConstant
					.getWrapped(c));
}
 
Example 14
@Test
public void test5() {
	final LogicalExpression exp = TestServices
			.getCategoryServices()
			.readSemantics(
					"(lambda $0:<e,t> (lambda $1:e (and:<t*,t> (do:<e,<e,<e,t>>> roo:e $1 (a:<<e,t>,e> (lambda $0:e (boo:<e,<e,t>> $0 too:e)))) ($0 $1) (boo:<e,<e,t>> $1 goo:e))))");
	final Result result = ExtractTypedSubExpression.of(exp, LogicalConstant
			.read("p:t"), LogicLanguageServices.getTypeRepository()
			.getTypeCreateIfNeeded("t"), true);
	Assert.assertNotNull(result);
	final LogicalExpression expectedSubExp = ((Literal) ((Lambda) ((Lambda) exp)
			.getBody()).getBody()).getArg(0);
	final LogicalExpression expectedRemainder = TestServices
			.getCategoryServices()
			.readSemantics(
					"(lambda $0:<e,t> (lambda $1:e (and:<t*,t> p:t ($0 $1) (boo:<e,<e,t>> $1 goo:e))))");
	Assert.assertEquals(expectedRemainder,
			result.getExpressionWithPlaceholder());
	Assert.assertEquals(expectedSubExp, result.getExtractedSubExpression());
}
 
Example 15
@Test
public void test6() {
	final LogicalExpression exp = TestServices
			.getCategoryServices()
			.readSemantics(
					"(lambda $0:<e,t> (lambda $1:e (and:<t*,t> ($0 $1) (boo:<e,<e,t>> $1 goo:e))))");
	final Result result = ExtractTypedSubExpression.of(exp, LogicalConstant
			.read("p:t"), LogicLanguageServices.getTypeRepository()
			.getTypeCreateIfNeeded("t"), true);
	Assert.assertNotNull(result);
	final LogicalExpression expectedSubExp = ((Literal) ((Lambda) ((Lambda) exp)
			.getBody()).getBody()).getArg(1);
	final LogicalExpression expectedRemainder = TestServices
			.getCategoryServices()
			.readSemantics(
					"(lambda $0:<e,t> (lambda $1:e (and:<t*,t> ($0 $1) p:t)))");
	Assert.assertEquals(expectedRemainder,
			result.getExpressionWithPlaceholder());
	Assert.assertEquals(expectedSubExp, result.getExtractedSubExpression());
}
 
Example 16
@Test
public void testSubExp7() {
	final LogicalExpression appArg = TestServices
			.getCategoryServices()
			.readSemantics(
					"(lambda $0:e (lambda $1:e (lambda $2:e (boo:<e,<e,<e,t>>> $0 $1 $2))))");
	final LogicalExpression subExp = TestServices.getCategoryServices()
			.readSemantics("(boo:<e,<e,<e,t>>> koo:e loo:e doo: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 17
Source Project: spf   Source File: IncSimplifier.java    License: 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 18
Source Project: UDepLambda   Source File: PostProcessLogicalForm.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a literal expression by appending the given predicates in
 * conjunction, i.e., (and:c expr1 expr2 .. )
 * 
 * @param predicates
 * @return
 */
@SuppressWarnings("unused")
private Literal createLiteralExpresison(List<LogicalExpression> predicates) {
  LogicalExpression[] predicatesList =
      new LogicalExpression[predicates.size()];
  LogicalExpression and = SimpleLogicalExpressionReader.read("and:c");
  return new Literal(and, predicates.toArray(predicatesList));
}
 
Example 19
Source Project: amr   Source File: GetAllSkolemTerms.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visit(Literal literal) {
	final boolean isSkolemTerm = AMRServices.isSkolemTerm(literal);
	if (isSkolemTerm) {
		skolemTerms.add(literal);
	}

	if (!shallow || !isSkolemTerm) {
		literal.getPredicate().accept(this);
		final int len = literal.numArgs();
		for (int i = 0; i < len; ++i) {
			literal.getArg(i).accept(this);
		}
	}
}
 
Example 20
@Override
public void visit(Literal literal) {
	literal.getPredicate().accept(this);
	if (!result) {
		return;
	}

	final int numArgs = literal.numArgs();
	for (int i = 0; i < numArgs; ++i) {
		literal.getArg(i).accept(this);
		if (!result) {
			return;
		}
	}
}
 
Example 21
@Test
public void testSubExp5() {
	final LogicalExpression appArg = TestServices.getCategoryServices()
			.readSemantics("(lambda $0:e (boo:<e,t> $0))");
	final LogicalExpression subExp = TestServices.getCategoryServices()
			.readSemantics("(boo:<e,t> koo:e)");
	final Variable replacementVariable = new Variable(LogicLanguageServices
			.getTypeRepository().getType("<e,t>"));
	final LogicalExpression expected = new Literal(replacementVariable,
			ArrayUtils.create(TestServices.getCategoryServices()
					.readSemantics("koo:e")));
	Assert.assertEquals(expected, GetApplicationFunction.processSubExp(
			subExp, appArg, replacementVariable));
}
 
Example 22
private static Literal createBinaryLiteral(String predicateName,
		LogicalExpression arg1, LogicalExpression arg2, Type returnType) {
	return createBinaryLiteral(
			createConstant(
					predicateName,
					LogicLanguageServices.getTypeRepository()
							.getTypeCreateIfNeeded(
									LogicLanguageServices
											.getTypeRepository()
											.getTypeCreateIfNeeded(
													returnType,
													arg2.getType()),
									arg1.getType())), arg1, arg2);
}
 
Example 23
Source Project: spf   Source File: GetAllPredicates.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visit(Literal literal) {
	literal.getPredicate().accept(this);
	final int len = literal.numArgs();
	for (int i = 0; i < len; ++i) {
		literal.getArg(i).accept(this);
	}
}
 
Example 24
@Override
public void visit(Literal literal) {
	final String predicateString = GetHeadString
			.of(literal.getPredicate());
	// Only observe pairs.
	for (final List<LogicalExpression> subset : new AllPairs<LogicalExpression>(
			literal.argumentCopy())) {
		assert subset
				.size() == 2 : "Subset must be a pair -- probably a bug in PowerSetWithFixedSize";
		final String first = GetHeadString.of(subset.get(0));
		final String second = GetHeadString.of(subset.get(1));
		if (first.compareTo(second) >= 0) {
			features.set(FEATURE_TAG, "ARGARG", first, second,
					1.0 * scale);
		} else {
			features.set(FEATURE_TAG, "ARGARG", second, first,
					1.0 * scale);
		}
	}

	final int len = literal.numArgs();
	for (int i = 0; i < len; ++i) {
		final LogicalExpression arg = literal.getArg(i);
		arg.accept(this);

		final String argString = GetHeadString.of(arg);
		features.set(FEATURE_TAG, "PREDARG", predicateString, argString,
				1.0 * scale);
	}
}
 
Example 25
Source Project: spf   Source File: ApplyAndSimplify.java    License: 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 26
@Override
public void visit(LogicalConstant logicalConstant) {
	if (skolemIDs.containsKey(logicalConstant)) {
		final SkolemId referenceID = skolemIDs.get(logicalConstant)
				.first();
		tempReturn = new Literal(
				AMRServices.createRefPredicate(skolemIDs.get(
						logicalConstant).second()),
				ArrayUtils.create(referenceID));
	} else {
		tempReturn = logicalConstant;
	}
}
 
Example 27
Source Project: amr   Source File: LogicalExpressionToAmr.java    License: 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 28
Source Project: amr   Source File: AMRServices.java    License: 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 29
@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 30
Source Project: amr   Source File: AMRServices.java    License: 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;
}