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

The following examples show how to use edu.cornell.cs.nlp.spf.mr.lambda.LogicalConstant. 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: SentenceWithDummy.java    From amr with 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<Lambda, LogicalConstant> pair = DummyEntityServices
				.stripDummy((Lambda) 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 #2
Source File: ExtractTypedSubExpressionTest.java    From amr with GNU General Public License v2.0 6 votes vote down vote up
@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 #3
Source File: AMRSupervisedFilterFactory.java    From amr with GNU General Public License v2.0 6 votes vote down vote up
@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 #4
Source File: SpecificationMapping.java    From amr with GNU General Public License v2.0 6 votes vote down vote up
public boolean isUnderspecified(LogicalConstant constant) {
	final String baseName = OverloadedLogicalConstant.getWrapped(constant)
			.getBaseName();

	// Case of underspecified relation.
	if (assignmentMapping.containsKey(baseName)) {
		return true;
	}

	// Case of underspecified PropBank predicate.
	if (underspecifyPropBank && baseName.endsWith(PROPBANK_ROLE_WILDCARD)
			&& !AMRServices
					.getPropBankFrames(baseName.substring(0,
							baseName.length()
									- PROPBANK_ROLE_WILDCARD.length()))
					.isEmpty()) {
		return true;
	}

	return false;
}
 
Example #5
Source File: AmrToLogicalExpressionConverter.java    From amr with GNU General Public License v2.0 6 votes vote down vote up
public LogicalExpression read(String amr) throws IOException {
	try (StringReader reader = new StringReader(amr)) {
		final String firstToken = getNextToken(reader);
		if (!firstToken.equals("(")) {
			throw new IllegalStateException("AMR doesn't start with '(': "
					+ amr);
		}
		final Map<LogicalConstant, Pair<SkolemId, Type>> skolemIDs = new HashMap<>();
		final LogicalExpression instance = parseInstance(reader,
				new HashMap<String, Variable>(), skolemIDs);

		// Replace all dummy logical constants with the proper skolem IDs.
		final SetReferences visitor = new SetReferences(skolemIDs);
		visitor.visit(instance);
		return visitor.tempReturn;
	}
}
 
Example #6
Source File: AMRServices.java    From amr with GNU General Public License v2.0 6 votes vote down vote up
public static LogicalConstant createTextConstant(List<String> tokens) {
	final String TEXT_STRING_SEP = "++";
	final String escapedString = LogicalConstant
			.escapeString(tokens.stream().map(token -> {
				final StringBuilder modifiedToken = new StringBuilder(
						token);
				if (modifiedToken.charAt(0) == '"') {
					modifiedToken.deleteCharAt(0);
				}
				if (modifiedToken
						.charAt(modifiedToken.length() - 1) == '"') {
					modifiedToken.deleteCharAt(modifiedToken.length() - 1);
				}
				return modifiedToken.toString();
			}).collect(Collectors.joining(TEXT_STRING_SEP)));
	return LogicalConstant.create(escapedString, INSTANCE.textType, true);
}
 
Example #7
Source File: CoordinationC2Rule.java    From amr with 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
Source File: ExtractTypedSubExpressionTest.java    From amr with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test2() {
	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:<e,<e,t>>"), LogicLanguageServices.getTypeRepository()
			.getTypeCreateIfNeeded("<e,<e,t>>"), false);
	Assert.assertNotNull(result);
	final LogicalExpression expectedSubExp = LogicalConstant
			.read("boo:<e,<e,t>>");
	final LogicalExpression expectedRemainder = TestServices
			.getCategoryServices()
			.readSemantics(
					"(lambda $0:<e,t> (lambda $1:e (and:<t*,t> ($0 $1) (p:<e,<e,t>> $1 goo:e))))");
	Assert.assertEquals(expectedRemainder,
			result.getExpressionWithPlaceholder());
	Assert.assertEquals(expectedSubExp, result.getExtractedSubExpression());
}
 
Example #9
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 #10
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 #11
Source File: ExtractTypedSubExpressionTest.java    From amr with GNU General Public License v2.0 6 votes vote down vote up
@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 #12
Source File: LogicalExpressionCoordinationServices.java    From spf with GNU General Public License v2.0 6 votes vote down vote up
@Override
public LogicalExpression createPartialCoordination(
		LogicalExpression coordinated, LogicalExpression coordinator) {
	// Create a binary predicate from coordinator
	if (!isBaseCoordinator(coordinator)) {
		return null;
	}

	// The type of the coordinated element is generalized to create the
	// coordination predicate
	final Type argType = LogicLanguageServices.getTypeRepository()
			.generalizeType(coordinated.getType());
	final LogicalConstant coordinationPredicate = createPredicate(
			(LogicalConstant) coordinator, 2, argType);

	// Create a literal using the predicate, with a variable as the
	// first argument and 'coordinated' as the second, and wrap the literal
	// with a lambda expression binding the varaible.
	final LogicalExpression[] arguments = new LogicalExpression[2];
	final Variable variable = new Variable(argType);
	arguments[0] = variable;
	arguments[1] = coordinated;
	return new Lambda(variable, new Literal(coordinationPredicate,
			arguments));
}
 
Example #13
Source File: TemplateCoarseGenlex.java    From spf with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public TemplateCoarseGenlex<DI> create(Parameters params,
		IResourceRepository repo) {
	final Builder<DI> builder = new Builder<DI>(
			params.getAsInteger("maxTokens"),
			(IParser<Sentence, LogicalExpression>) repo
					.get(params.get("parser")),
			params.getAsInteger("beam"),
			params.getAsBoolean("mark", false));

	builder.addConstants((Iterable<LogicalConstant>) repo
			.get(params.get("ontology")));

	if (params.contains("origin")) {
		builder.setOrigin(params.get("origin"));
	}

	return builder.build();
}
 
Example #14
Source File: SupervisedFilterFactory.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean test(LogicalConstant constant) {
	return !(LogicLanguageServices.isCollpasibleConstant(constant)
			|| LogicLanguageServices.isArrayIndexPredicate(constant)
			|| constant.getType().equals(SkolemServices.getIDType()))
			&& baseFilter.test(constant);
}
 
Example #15
Source File: UnaryBiasFeatures.java    From amr with GNU General Public License v2.0 5 votes vote down vote up
private static String toFeatureString(LogicalExpression exp) {
	if (exp instanceof LogicalConstant) {
		return ((LogicalConstant) exp).getBaseName();
	} else if (exp != null) {
		return exp.toString();
	} else {
		return "null";
	}
}
 
Example #16
Source File: GetAllSimpleLogicalConstants.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visit(LogicalConstant logicalConstant) {
	final Type type = logicalConstant.getType();
	if (!type.isArray() && !type.isComplex()) {
		constants.add(logicalConstant);
	}
}
 
Example #17
Source File: RefControlFeatureSet.java    From amr with GNU General Public License v2.0 5 votes vote down vote up
private static String toFeatureString(LogicalExpression exp) {
	if (exp instanceof LogicalConstant) {
		return ((LogicalConstant) exp).getBaseName();
	} else if (exp != null) {
		return exp.toString();
	} else {
		return "null";
	}
}
 
Example #18
Source File: LogicalExpressionCoordinationServices.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
public LogicalExpressionCoordinationServices(
		LogicalConstant baseConjunctionConstant,
		LogicalConstant baseDisjunctionConstant,
		ICategoryServices<LogicalExpression> categoryServices) {
	this.baseConjunctionConstant = baseConjunctionConstant;
	this.baseDisjunctionConstant = baseDisjunctionConstant;
	this.categoryServices = categoryServices;
	this.baseConjunctionName = baseConjunctionConstant.getBaseName();
	this.baseDisjunctionName = baseDisjunctionConstant.getBaseName();
}
 
Example #19
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 #20
Source File: ReplaceNthExpression.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visit(LogicalConstant logicalConstant) {
	if (subExp.equals(logicalConstant)) {
		numTimesSeen++;
		if (numTimesSeen == n) {
			result = replacement;
			return;
		}
	}
	result = logicalConstant;
}
 
Example #21
Source File: CoordinationServices.java    From amr with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create an AMR coordination, e.g., (lambda $0:e (and:<t*,t> (C:<e,t> $0)
 * (c_op1:<e,<e,t>> $0 a1) ... (c_opn:<e,<e,t>> $0 an))).
 *
 * @param coordinatedElements
 *            The entities being coordinated a1,...,an, where the type of
 *            each ai is baseType.
 * @param baseType
 *            The type of all coordinated entities.
 * @param coordinationWrapper
 *            The wrapping predicate that packed this coordination, as
 *            initialized by {@link CoordinationC1Rule}. C is inferred from
 *            this wrapper.
 * @return <e,t>-typed logical expression.
 */
public static LogicalExpression createCoordination(
		LogicalExpression[] coordinatedElements, Type baseType,
		LogicalConstant coordinationWrapper) {
	// Create coordination variable.
	final Variable coordinationVariable = new Variable(
			LogicLanguageServices.getTypeRepository().getEntityType());

	final LogicalExpression[] conjunctionElements = new LogicalExpression[coordinatedElements.length + 1];

	// Wrap each coordinated element with a c_op predicate and get the
	// common type.
	Type commonType = null;
	for (int i = 0; i < coordinatedElements.length; ++i) {
		final LogicalExpression element = coordinatedElements[i];
		if (commonType == null || element.getType().isExtending(commonType)) {
			commonType = element.getType();
		} else if (!commonType.isExtending(element.getType())) {
			return null;
		}
		conjunctionElements[i + 1] = new Literal(createpCOpPredicate(i + 1,
				baseType), ArrayUtils.create(coordinationVariable, element));
	}

	/*
	 * Create the coordination instance, the conjunction of all the c_op
	 * literals and the instance unary literal.
	 */
	final LogicalConstant predicate = getCoordinationPredicate(
			coordinationWrapper.getBaseName(), commonType);
	if (predicate == null) {
		return null;
	}
	conjunctionElements[0] = new Literal(predicate,
			ArrayUtils.create(coordinationVariable));

	return new Lambda(coordinationVariable, new Literal(
			LogicLanguageServices.getConjunctionPredicate(),
			conjunctionElements));
}
 
Example #22
Source File: CoordinationServices.java    From amr with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Given a list of arguments, a type and a predicate base name create a
 * literal. The type of the predicate is <type,...,<type,type>...>.
 */
public static Literal createLiteral(String name,
		LogicalExpression[] arguments, Type type) {

	// Create the type of the predicate.
	ComplexType predicateType = LogicLanguageServices.getTypeRepository()
			.getTypeCreateIfNeeded(type, type);
	for (int i = 1; i < arguments.length; i++) {
		predicateType = LogicLanguageServices.getTypeRepository()
				.getTypeCreateIfNeeded(predicateType, type);
	}

	return new Literal(LogicalConstant.create(name, predicateType, true),
			arguments);
}
 
Example #23
Source File: FactoringServices.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
private LogicalConstant makeConstant(Type type) {
	final Type generalType = LogicLanguageServices
			.getTypeRepository().generalizeType(type);

	return LogicalConstant.createDynamic("#"
			+ (counters.containsKey(generalType)
					? counters.get(generalType).value() : 0)
			+ generalType, generalType, true);
}
 
Example #24
Source File: LexConstants.java    From amr with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visit(LogicalConstant logicalConstant) {
	externalLambda = false;
	if (AMRServices.isUnderspecified(logicalConstant)
			&& AMRServices.isAmrRelation(logicalConstant)) {
		// Append the tokens to the name of the constant.
		result = OverloadedLogicalConstant.wrap(logicalConstant,
				tokens);
	} else {
		result = logicalConstant;
	}
}
 
Example #25
Source File: LambdaWrapped.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visit(LogicalConstant logicalConstant) {
	if (logicalConstant.getType().isComplex()) {
		wrap(logicalConstant).accept(this);
	} else {
		tempReturn = logicalConstant;
	}
}
 
Example #26
Source File: PluralTypeShifting.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
public PluralTypeShifting(
		ICategoryServices<LogicalExpression> categoryServices, String name) {
	this.name = UnaryRuleName.create(name);
	this.eToT = LogicLanguageServices.getTypeRepository()
			.getTypeCreateIfNeeded("<e,t>");
	this.aPred = (LogicalConstant) categoryServices
			.readSemantics("a:<<e,t>,e>");
}
 
Example #27
Source File: OverloadedLogicalConstant.java    From amr with GNU General Public License v2.0 5 votes vote down vote up
/**
 * If the constant is a {@link OverloadedLogicalConstant} returns the
 * wrapped constant, otherwise returns the constant itself.
 */
public static LogicalConstant getWrapped(LogicalConstant constant) {
	if (constant instanceof OverloadedLogicalConstant) {
		return ((OverloadedLogicalConstant) constant).getWrappedConstant();
	} else {
		return constant;
	}
}
 
Example #28
Source File: AMRServices.java    From amr with GNU General Public License v2.0 5 votes vote down vote up
public static List<String> textConstantToStrings(LogicalConstant constant) {
	final String[] split = LogicalConstant
			.unescapeString(constant.getBaseName()).split("\\+\\+");
	for (int i = 0; i < split.length; ++i) {
		split[i] = "\"" + split[i] + "\"";
	}
	return Arrays.asList(split);
}
 
Example #29
Source File: AMRServices.java    From amr with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Given a passive relation, returns its active form. Otherwise, returns
 * null.
 *
 * @param underspecified
 *            The output should be underspecified or not.
 */
public static LogicalExpression makeRelationActive(LogicalConstant constant,
		boolean underspecified) {
	if (isAmrRelation(constant)) {
		String baseName;
		boolean overload;
		if (constant instanceof OverloadedLogicalConstant) {
			baseName = ((OverloadedLogicalConstant) constant)
					.getWrappedConstant().getBaseName();
			overload = true;
		} else {
			baseName = constant.getBaseName();
			overload = false;
		}

		if (baseName.endsWith(INVERSE_RELATION_SUFFIX)) {
			final LogicalConstant activeConstant = underspecified
					? (LogicalConstant) underspecify(LogicalConstant.create(
							baseName.substring(0, baseName.length()
									- INVERSE_RELATION_SUFFIX.length()),
							constant.getType(), true))
					: LogicalConstant.create(
							baseName.substring(0, baseName.length()
									- INVERSE_RELATION_SUFFIX.length()),
							constant.getType(), true);
			if (overload) {
				return ((OverloadedLogicalConstant) constant)
						.cloneWrapper(activeConstant);
			} else {
				return activeConstant;
			}
		}
	}
	return null;
}
 
Example #30
Source File: ReplaceExpression.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visit(LogicalConstant logicalConstant) {
	if (subExp.equals(logicalConstant)) {
		result = replacement;
	} else {
		result = logicalConstant;
	}
}