Java Code Examples for edu.cornell.cs.nlp.utils.composites.Pair#first()

The following examples show how to use edu.cornell.cs.nlp.utils.composites.Pair#first() . 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: MultiCKYParser.java    From spf with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void loggedRun() {
	LOG.debug("%s Lexical job started", split.span);

	final Pair<Collection<Cell<MR>>, Boolean> processingPair = generateLexicalCells(
			split.start, split.end, chart, lexicon, model,
			pruningFilter);

	// Add all the valid cells under a span lock.
	lock.lock(split.start, split.end);
	for (final Cell<MR> newCell : processingPair.first()) {
		chart.add(newCell);
	}
	if (processingPair.second()) {
		chart.externalPruning(split.start, split.end);
	}
	lock.unlock(split.start, split.end);

	LOG.debug("%s: Lexical job completed, tried to add %d entries",
			split.span, processingPair.first().size());

	// Signal the job is complete.
	listener.jobComplete(this);
}
 
Example 2
Source File: GetMaxEvaluations.java    From amr with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visit(LiteralNode node) {
	node.getPredicate().accept(this);
	final List<Pair<LogicalExpression, Map<INode, LogicalExpression>>> predicateMaxes = maxes;
	int numAssignments = predicateMaxes.size();
	final List<List<Pair<LogicalExpression, Map<INode, LogicalExpression>>>> argMaxes = new ArrayList<>(
			node.getArgs().size());
	for (final IBaseNode argNode : node.getArgs()) {
		argNode.accept(this);
		numAssignments *= maxes.size();
		if (numAssignments == 0 || numAssignments > limit) {
			LOG.debug("Too many evaluation for: %s", node);
			maxes = Collections.emptyList();
			return;
		}
		argMaxes.add(maxes);
	}

	// Create the max literal assignments.
	maxes = new LinkedList<>();
	for (final Pair<LogicalExpression, Map<INode, LogicalExpression>> predicate : predicateMaxes) {
		for (final List<Pair<LogicalExpression, Map<INode, LogicalExpression>>> argPairs : CollectionUtils
				.cartesianProduct(argMaxes)) {
			final Map<INode, LogicalExpression> mapping = new HashMap<>(
					predicate.second());
			final LogicalExpression[] args = new LogicalExpression[argPairs
					.size()];
			for (int i = 0; i < args.length; ++i) {
				final Pair<LogicalExpression, Map<INode, LogicalExpression>> pair = argPairs
						.get(i);
				mapping.putAll(pair.second());
				args[i] = pair.first();
			}
			maxes.add(Pair.of(new Literal(predicate.first(), args), mapping));
		}
	}
}
 
Example 3
Source File: MultiCKYParser.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void loggedRun() {
	LOG.debug("%s: Split job started", split);

	final Pair<List<Cell<MR>>, Boolean> processingPair = preChartPruning
			? processSplitAndPrune(split.start, split.end, split.split,
					sentenceLength, chart, cellFactory, pruningFilter,
					chart.getBeamSize(), model)
			: processSplit(split.start, split.end, split.split,
					sentenceLength, chart, cellFactory, pruningFilter,
					model);

	final List<Cell<MR>> newCells = processingPair.first();

	LOG.debug("%s: %d new cells", split, newCells.size());

	// Add all the valid cells under a span lock
	lock.lock(split.start, split.end);
	for (final Cell<MR> newCell : newCells) {
		chart.add(newCell);
	}
	if (processingPair.second()) {
		chart.externalPruning(split.start, split.end);
	}
	lock.unlock(split.start, split.end);

	LOG.debug("%s: Split job completed", split);

	// Signal the job is complete
	listener.jobComplete(this);
}
 
Example 4
Source File: MultiCKYParser.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void loggedRun() {
	LOG.debug("%s: Unary span job started", split.span);

	final Pair<List<Cell<MR>>, Boolean> processingPair = preChartPruning
			? unaryProcessSpanAndPrune(split.start, split.end,
					sentenceLength, chart, cellFactory, pruningFilter,
					chart.getBeamSize(), model)
			: unaryProcessSpan(split.start, split.end, sentenceLength,
					chart, cellFactory, pruningFilter, model);

	final List<Cell<MR>> newCells = processingPair.first();

	LOG.debug("%s: %d new cells", split, newCells.size());

	// Add all the valid cells under a span lock.
	lock.lock(split.start, split.end);
	for (final Cell<MR> newCell : newCells) {
		chart.add(newCell);
	}
	if (processingPair.second()) {
		chart.externalPruning(split.start, split.end);
	}
	lock.unlock(split.start, split.end);

	LOG.debug("%s: Unary span job completed", split);

	// Signal the job is complete
	listener.jobComplete(this);
}
 
Example 5
Source File: ScopeMappingOverlay.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
public void applyToBase() {
	for (final Pair<K, Iterator<V>> entry : map) {
		final Iterator<V> stackIterator = entry.second();
		final K key = entry.first();
		while (stackIterator.hasNext()) {
			base.push(key, stackIterator.next());
		}
	}
	map.clear();
	reverseMapping.clear();
}
 
Example 6
Source File: AToExists.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
private LogicalExpression noUpperLevelWrapIfPossible(LogicalExpression exp,
		Stack<Pair<Variable, ? extends LogicalExpression>> stack) {
	if (stack.size() == 1
			&& exp.equals(stack.peek().first())
			&& LogicLanguageServices.getTypeRepository()
					.getTruthValueType()
					.equals(stack.peek().second().getType())) {
		final Pair<Variable, ? extends LogicalExpression> pop = stack.pop();
		final LogicalExpression[] args = new LogicalExpression[1];
		args[0] = new Lambda(pop.first(), pop.second());
		return new Literal(existsPredicate, args);
	} else {
		return exp;
	}
}
 
Example 7
Source File: TypeRepository.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
private ComplexType createComplexTypeFromString(String string) {
	// Case complex functional type
	final String innerString = string.substring(1, string.length() - 1)
			.trim();
	int i = 0;
	final StringBuilder domainStringBuilder = new StringBuilder();
	char c;
	int parenthesisCounter = 0;
	while (i < innerString.length()
			&& !((c = innerString.charAt(i)) == ComplexType.COMPLEX_TYPE_SEP && parenthesisCounter == 0)) {
		++i;
		domainStringBuilder.append(c);
		if (c == ComplexType.COMPLEX_TYPE_OPEN_PAREN) {
			++parenthesisCounter;
		} else if (c == ComplexType.COMPLEX_TYPE_CLOSE_PAREN) {
			--parenthesisCounter;
		}
	}
	++i;
	final String rangeString = innerString.substring(i).trim();
	final String domainString = domainStringBuilder.toString().trim();

	// Check if the domain indicates to a RecursiveComplexType, and if so
	// trim the indication to parse it and raise a flag
	final Pair<String, RecursiveComplexType.Option> prefixOption = RecursiveComplexType.Option
			.parse(domainString);
	final RecursiveComplexType.Option option = prefixOption.second();
	final String domainStringTrimmed = prefixOption.first();

	final Type domain = getTypeCreateIfNeeded(domainStringTrimmed);
	final Type range = getTypeCreateIfNeeded(rangeString);

	return ComplexType.create(string, domain, range, option);
}
 
Example 8
Source File: LogicalExpressionCategoryServices.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Override
public LogicalExpression readSemantics(String string, boolean checkType) {
	final LogicalExpression exp = LogicalExpression.read(string);
	if (checkType) {

		final Pair<Boolean, String> typeChecking = IsTypeConsistent
				.ofVerbose(exp);
		if (!typeChecking.first()) {
			throw new IllegalStateException("Semantics not well typed ["
					+ typeChecking.second() + "]: " + string);
		}
	}
	return Simplify.of(exp);
}
 
Example 9
Source File: FactoringServices.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
public static List<FactoredLexicalEntry> factor(
		final LexicalEntry<LogicalExpression> entry, boolean doMaximal,
		boolean doPartial, int maxConstantsInPartial) {

	// Abstract syntactic attributes.
	final Pair<List<String>, Syntax> syntaxAbstractionPair = abstractSyntaxAttributes(
			entry.getCategory().getSyntax());
	final List<String> indexedAttributes = syntaxAbstractionPair.first();
	final Category<LogicalExpression> category;
	if (syntaxAbstractionPair.second() == entry.getCategory().getSyntax()) {
		category = INSTANCE.preprocessor.apply(entry.getCategory());
	} else {
		category = INSTANCE.preprocessor
				.apply(Category.create(syntaxAbstractionPair.second(),
						entry.getCategory().getSemantics()));
	}

	final List<Pair<List<LogicalConstant>, LexicalTemplate>> factoring = FactoringServices
			.doFactoring(category, doMaximal, doPartial,
					maxConstantsInPartial, entry.getProperties(),
					indexedAttributes.size());

	return ListUtils.map(factoring,
			obj -> new FactoredLexicalEntry(entry.getTokens(),
					entry.getCategory(),
					new Lexeme(entry.getTokens(), obj.first(),
							indexedAttributes, entry.getProperties()),
			obj.second(), entry.isDynamic(), entry.getProperties()));
}
 
Example 10
Source File: JointDerivation.java    From spf with GNU General Public License v2.0 4 votes vote down vote up
public JointDerivation<MR, ERESULT> build() {
	final Pair<List<InferencePair<MR, ERESULT, IDerivation<MR>>>, Double> maxPair = createMaxPairs();
	return new JointDerivation<MR, ERESULT>(maxPair.first(),
			inferencePairs, result, maxPair.second());
}
 
Example 11
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());

}