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

The following examples show how to use edu.cornell.cs.nlp.utils.composites.Pair#of() . 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: AbstractVariableNode.java    From amr with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Pair<Set<LogicalExpression>, Double> getMaxAssignments() {
	if (belief == null) {
		throw new IllegalStateException(
				"Belief not set, can't get max assignments: " + this);
	} else if (assignments.length == 1) {
		final Set<LogicalExpression> maxAssignments = new HashSet<>();
		maxAssignments.add(assignments[0]);
		return Pair.of(maxAssignments, 0.0);
	} else {
		double max = -Double.MAX_VALUE;
		final Set<LogicalExpression> argmax = new HashSet<>();
		for (final LogicalExpression assignment : assignments) {
			final double score = belief.get(MappingPair
					.of(this, assignment));
			if (score == max) {
				argmax.add(assignment);
			} else if (score > max) {
				max = score;
				argmax.clear();
				argmax.add(assignment);
			}
		}
		return Pair.of(argmax, max);
	}
}
 
Example 2
Source File: RecursiveComplexType.java    From spf with GNU General Public License v2.0 6 votes vote down vote up
public static Pair<String, Option> parse(String string) {
	final Matcher m = STRING_PATTERN.matcher(string);
	if (m.matches()) {
		final String type = m.group("type");
		if (m.isCaptured("order")) {
			final boolean isOrderSensitive = m.group("order").equals(
					"+");
			int minArgs;
			if (m.isCaptured("minargs")) {
				minArgs = Integer.valueOf(m.group("minargs"));
			} else {
				minArgs = 2;
			}
			return Pair.of(type, new Option(isOrderSensitive, minArgs));
		} else {
			return Pair.of(type, null);
		}
	} else {
		throw new IllegalArgumentException("Invalid type string");
	}
}
 
Example 3
Source File: Evaluation.java    From spf with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Decomposes a logical expression as a SELECT query.
 *
 * @param exp
 * @return Pair of queried variables and SELECT body. If not a SELECT query,
 *         returns null.
 */
private static Pair<List<Variable>, LogicalExpression> decomposeLogicalExpressionAsSelect(
		LogicalExpression exp) {
	LogicalExpression currentBody = exp;
	final List<Variable> queryVariables = new LinkedList<Variable>();
	while (currentBody instanceof Lambda) {
		final Lambda lambda = (Lambda) currentBody;
		if (lambda.getArgument().getType().isComplex()) {
			// Case argument is complex
			return null;
		} else {
			queryVariables.add(lambda.getArgument());
			currentBody = lambda.getBody();
		}
	}

	if (currentBody.getType().isComplex()) {
		return null;
	} else {
		return Pair.of(queryVariables, currentBody);
	}
}
 
Example 4
Source File: TroveHashVector.java    From spf with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Iterator<Pair<KeyArgs, Double>> iterator() {
	return new Iterator<Pair<KeyArgs, Double>>() {
		private final TObjectDoubleIterator<KeyArgs>	innerIterator	= values.iterator();

		@Override
		public boolean hasNext() {
			return innerIterator.hasNext();
		}

		@Override
		public Pair<KeyArgs, Double> next() {
			if (innerIterator.hasNext()) {
				innerIterator.advance();
				return Pair.of(innerIterator.key(), innerIterator.value());
			} else {
				return null;
			}
		}

		@Override
		public void remove() {
			innerIterator.remove();
		}
	};
}
 
Example 5
Source File: JointDerivation.java    From spf with GNU General Public License v2.0 6 votes vote down vote up
protected Pair<List<InferencePair<MR, ERESULT, IDerivation<MR>>>, Double> createMaxPairs() {
	double maxScore = -Double.MAX_VALUE;
	final List<InferencePair<MR, ERESULT, IDerivation<MR>>> maxPairs = new LinkedList<>();
	for (final InferencePair<MR, ERESULT, IDerivation<MR>> pair : inferencePairs) {
		// Viterbi score is for a linearly-weighted.
		final double score = pair.getBaseDerivation().getScore()
				+ pair.getBaseDerivation().getScore();
		if (score > maxScore) {
			maxScore = score;
			maxPairs.clear();
			maxPairs.add(pair);
		} else if (score == maxScore) {
			maxPairs.add(pair);
		}
	}
	return Pair.of(maxPairs, maxScore);
}
 
Example 6
Source File: Chart.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Pair<Double, Double> minQeueuScore() {
	if (queue.isEmpty()) {
		return null;
	} else {
		final Cell<MR> peek = queue.peek();
		return Pair.of(peek.getPruneScore(),
				peek.getSecondPruneScore());
	}
}
 
Example 7
Source File: Chart.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Pair<Double, Double> minQeueuScore() {
	if (nonLexicalQueue.isEmpty()) {
		return null;
	} else {
		final Cell<MR> peek = nonLexicalQueue.peek();
		return Pair.of(peek.getPruneScore(),
				peek.getSecondPruneScore());
	}
}
 
Example 8
Source File: MaxSemanticsJointExecution.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Pair<MR, ERESULT> getResult() {
	return Pair.of(
			jointDerivation.getMaxSemantics().size() == 1 ? jointDerivation
					.getMaxSemantics().get(0) : null, jointDerivation
					.getResult());
}
 
Example 9
Source File: AbstractAmrParser.java    From amr with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Do LBP inference for the factor graph and extract the
 * {@link EvaluationResult}s.
 *
 *
 * @return Pair with list of {@link EvaluationResult} and an inference flag
 *         (if the flag is 'true', there were too many max-scoring
 *         evaluations and none were returned).
 */
private Pair<List<EvaluationResult>, Boolean> doLoopyBPInference(
		FactorGraph graph,
		IJointDataItemModel<LogicalExpression, LogicalExpression> model,
		boolean sloppyInference) {
	// Loopy BP inference
	LoopyBP.of(graph, bpConvergenceThreshold, bpMaxIterations, bpMaxTime);

	// Get the max configurations.
	final List<EvaluationResult> argmax = new LinkedList<>(
			GetMaxEvaluations.of(graph, maxLimit, model, sloppyInference));
	return Pair.of(argmax, !argmax.isEmpty());
}
 
Example 10
Source File: Variable.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Reads a variable definition into a pair of a {@link Variable} and a
 * {@link String} (its name).
 */
static Pair<String, Variable> readVariableDefintion(String string,
		TypeRepository typeRepository) {
	final String[] split = string.split(Term.TYPE_SEPARATOR);
	if (split.length == 2) {
		final Type type = typeRepository.getTypeCreateIfNeeded(split[1]);
		if (type == null) {
			throw new LogicalExpressionRuntimeException(
					"Invalid type for variable: " + string);
		}
		return Pair.of(split[0], new Variable(type));
	} else {
		return null;
	}
}
 
Example 11
Source File: AbstractAmrParser.java    From amr with GNU General Public License v2.0 5 votes vote down vote up
private static Pair<List<EvaluationResult>, Boolean> doFactorGraphDummyInference(
		FactorGraph graph) {
	// Get the logical expression at the base of the graph as
	// the evaluation result. This will include the Skolem IDs
	// and any closure that was applied.
	return Pair.of(ListUtils.createSingletonList(new EvaluationResult(0.0,
			HashVectorFactory.create(), graph.getRoot().getExpression())),
			true);
}
 
Example 12
Source File: AToExists.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visit(Lambda lambda) {
	lambda.getBody().accept(this);
	if (result.first() != lambda.getBody()) {
		// Case body changed
		result = Pair.of(new Lambda(lambda.getArgument(), result.first()),
				result.second());
	} else {
		result = Pair.of(lambda, result.second());
	}
}
 
Example 13
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 14
Source File: AlignmentServices.java    From amr with GNU General Public License v2.0 5 votes vote down vote up
public static Pair<Pair<Integer, Integer>, String> readAlignment(
		String string) {
	final String[] alignmentSplit = string.split("\\|");
	if (alignmentSplit.length != 2) {
		System.out.println("boo");
	}
	final String tokenRange = alignmentSplit[0];
	final String graphIndices = alignmentSplit[1];
	final String[] rangeSplit = tokenRange.split("-");
	final int start = Integer.valueOf(rangeSplit[0]);
	final int end = Integer.valueOf(rangeSplit[1]);
	return Pair.of(Pair.of(start, end), graphIndices);
}
 
Example 15
Source File: SituatedValidationPerceptron.java    From spf with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Split the list parses to valid and invalid ones.
 *
 * @param dataItem
 * @param parseResults
 * @return Pair of (good parses, bad parses)
 */
private Pair<List<IJointDerivation<MR, ERESULT>>, List<IJointDerivation<MR, ERESULT>>> createValidInvalidSets(
		DI dataItem,
		Collection<? extends IJointDerivation<MR, ERESULT>> parses) {
	final List<IJointDerivation<MR, ERESULT>> validParses = new LinkedList<IJointDerivation<MR, ERESULT>>();
	final List<IJointDerivation<MR, ERESULT>> invalidParses = new LinkedList<IJointDerivation<MR, ERESULT>>();
	double validScore = -Double.MAX_VALUE;
	for (final IJointDerivation<MR, ERESULT> parse : parses) {
		if (validate(dataItem, parse.getResult())) {
			if (hardUpdates) {
				// Case using hard updates, only keep the highest scored
				// valid ones
				if (parse.getViterbiScore() > validScore) {
					validScore = parse.getViterbiScore();
					validParses.clear();
					validParses.add(parse);
				} else if (parse.getViterbiScore() == validScore) {
					validParses.add(parse);
				}
			} else {
				validParses.add(parse);
			}
		} else {
			invalidParses.add(parse);
		}
	}
	return Pair.of(validParses, invalidParses);
}
 
Example 16
Source File: AbstractCKYParser.java    From spf with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Apply unary rules to all cells in the span. The cells generated combine
 * the unary step and the binary step that lead to it, so they don't depend
 * on cells in the same span (which might be pruned). Assumes the span was
 * already processed completely with binary or lexical rules.
 */
protected Pair<List<Cell<MR>>, Boolean> unaryProcessSpan(int start, int end,
		int sentenceLength, Chart<MR> chart,
		AbstractCellFactory<MR> cellFactory,
		Predicate<ParsingOp<MR>> pruningFilter, IDataItemModel<MR> model) {
	LOG.debug("Unary processing span (%d, %d) with %d  cells", start, end,
			chart.spanSize(start, end));

	final SentenceSpan span = new SentenceSpan(start, end, sentenceLength);

	// Create a list from left cells. This will allow the stream() to
	// distribute better.
	final Iterator<Cell<MR>> iterator = chart.getSpanIterator(start, end);
	final List<Cell<MR>> cells = new ArrayList<>();
	while (iterator.hasNext()) {
		cells.add(iterator.next());
	}

	final AtomicInteger counter = new AtomicInteger(0);
	final int numRules = unaryRules.length;
	final List<Cell<MR>> newCells = StreamSupport
			.stream(Spliterators.spliterator(cells, Spliterator.IMMUTABLE),
					LOG.getLogLevel() == LogLevel.DEBUG ? false : true)
			.map(cell -> {
				LOG.debug("Processing: cell=%d", cell.hashCode());
				for (int ruleIndex = 0; ruleIndex < numRules; ++ruleIndex) {
					final ParseRuleResult<MR> prr = unaryRules[ruleIndex]
							.apply(cell, span);
					if (prr != null) {
						counter.addAndGet(cell.numSteps());
						// Filter cells, only keep cells that pass pruning
						// over the
						// semantics, if there's a pruning filter and they
						// have
						// semantics.
						if (!prune(pruningFilter,
								new ParsingOp<MR>(prr.getResultCategory(),
										span, prr.getRuleName()),
								false)) {
							// Create combined parse step. Each step combine
							// all
							// binary steps that lead to this cell, and the
							// unary
							// step just created.
							for (final IWeightedCKYStep<MR> step : cell
									.getSteps()) {
								// Create the combined parse step and the
								// new cell.
								final Cell<MR> newCell = cellFactory
										.create(step.overloadWithUnary(prr,
												isFullParse(span,
														prr.getResultCategory()),
												model));
								LOG.debug("Created new cell: %s", newCell);
								return newCell;
							}
						}
					}
				}
				return null;
			}).filter(c -> c != null).collect(Collectors.toList());

	LOG.debug(
			"Finished unary processing span (%d, %d), generated %d cells, returning %d cells",
			start, end, counter.get(), newCells.size());

	return Pair.of(newCells, false);
}
 
Example 17
Source File: FactoringServices.java    From spf with GNU General Public License v2.0 4 votes vote down vote up
private static Pair<List<String>, Syntax> abstractSyntaxAttributes(
		Syntax syntax) {
	final List<String> indexedAttributes = new LinkedList<String>();
	return Pair.of(indexedAttributes,
			abstractSyntaxAttributes(syntax, indexedAttributes));
}
 
Example 18
Source File: AToExists.java    From spf with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void visit(LogicalConstant logicalConstant) {
	// Nothing to do
	result = Pair.of(logicalConstant, EMPTY_STACK);
}
 
Example 19
Source File: AToExists.java    From spf with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void visit(Variable variable) {
	// Nothing to do
	result = Pair.of(variable, EMPTY_STACK);
}
 
Example 20
Source File: IsTypeConsistent.java    From spf with GNU General Public License v2.0 4 votes vote down vote up
public static Pair<Boolean, String> ofVerbose(LogicalExpression exp) {
	final IsTypeConsistent visitor = new IsTypeConsistent();
	visitor.visit(exp);
	return Pair.of(visitor.wellTyped, visitor.message);
}