org.openrdf.query.algebra.Var Java Examples

The following examples show how to use org.openrdf.query.algebra.Var. 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: StatementUnifier.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
/***
 * Returns null if both terms cant be unified, a neutralsubstition if they
 * are already equal, or a singleton subtitution otherwise.
 * 
 * @param term1
 * @param term2
 * @return
 */
public static Substitution getUnifier(Var term1, Var term2) {
	Var left = !term1.isConstant() ? term1 : term2;
	Var right = !term1.isConstant() ? term2 : term1;

	if (term1.equals(term2))
		return new NeutralSubstitution();

	if (left.isConstant() && right.isConstant()) {
		if (left.getValue().equals(right.getValue())) {
			return new NeutralSubstitution();
		}
		return null;
	}
	else if (right.isConstant())// left is always a variable
		return new SingletonSubstituion(left, right);
	else
		// both not equal variables, substition right for left (priority for
		// original names).
		return new SingletonSubstituion(right, left);
}
 
Example #2
Source File: CumulusQueryOptimizer.java    From cumulusrdf with Apache License 2.0 6 votes vote down vote up
public OrderByModifier(final TupleExpr tupleExpr, final Order order) {
	_tupleExpr = tupleExpr;
	_order = order;
	_variables = new HashMap<Var, Boolean>();

	List<OrderElem> elems = order.getElements();
	Iterator<OrderElem> iter = elems.iterator();

	while (iter.hasNext()) {
		OrderElem ele = iter.next();
		boolean ascending = ele.isAscending();
		ValueExpr ex = ele.getExpr();

		if (ex instanceof Var) {
			_variables.put((Var) ex, new Boolean(ascending));
		}
	}
}
 
Example #3
Source File: SubstitutionImpl.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean compose(Var original, Var substitution) {
	Substitution unifier = StatementUnifier.getUnifier(original, substitution);
	Set<Var> trivialRemove = new HashSet<Var>();

	if (unifier == null)
		return false;
	if (unifier instanceof NeutralSubstitution)
		return true;
	for (Var key : map.keySet()) {
		Var value = map.get(key);
		if (value.equals(original))
			if (key.equals(substitution)) {
				// existing substitition now trivial, remove it.
				trivialRemove.add(key);
			} else {
				map.put(key, substitution);
			}
	}
	map.put(original, substitution);
	map.keySet().removeAll(trivialRemove);
	return true;
}
 
Example #4
Source File: InverseObjectProperties.java    From neo4j-sparql-extension with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Transform a statement pattern according to OWL-2 inverse properties
 * axiom.
 *
 * @param node the node to transform
 * @return list of nodes to visit next
 */
@Override
public List<QueryModelNode> apply(StatementPattern node) {
	List<QueryModelNode> next = newNextList();
	Var s = node.getSubjectVar();
	Var p = node.getPredicateVar();
	Var o = node.getObjectVar();
	Var c = node.getContextVar();
	URI uri = (URI) p.getValue();
	String op = uri.stringValue();
	Var p2;
	// check if need to replace with op1 or op2
	if (op.equals(op1)) {
		p2 = new ConstVar(vf.createURI(op2));
	} else {
		p2 = new ConstVar(vf.createURI(op1));
	}
	StatementPattern left = node.clone();
	// switch subject and object and replace predicate
	StatementPattern right = new StatementPattern(o, p2, s, c);
	node.replaceWith(new Union(left, right));
	next.add(left);
	next.add(right);
	return next;
}
 
Example #5
Source File: StatementUnifier.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Computes the Most General Unifier (MGU) for two n-ary atoms.
 * 
 * @param first
 * @param second
 * @return the substitution corresponding to this unification.
 */
public static Substitution getMGU(StatementPattern st1, StatementPattern st2) {

	Var term1;
	Var term2;

	Substitution mgu = new SubstitutionImpl();

	for (int i = 0; i < 3; i++) {
		term1 = st1.getVarList().get(i);
		term2 = st2.getVarList().get(i);
		Substitution s = getUnifier(term1, term2);
		if (s == null)
			return null;
		if (s instanceof NeutralSubstitution)
			continue;

		SingletonSubstituion ss = (SingletonSubstituion) s;
		mgu.compose(ss.original, ss.substition);

		st1 = st1.clone();
		st2 = st2.clone();

		applySubstitution(mgu, st1);
		applySubstitution(mgu, st2);
	}
	if (mgu.isEmpty())
		return new NeutralSubstitution();
	
	return mgu;

}
 
Example #6
Source File: RangeStatementPattern.java    From cumulusrdf with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a statement pattern that matches a subject-, predicate- and
 * object variable against statements from all contexts.
 */
public RangeStatementPattern(Var subject, Var predicate, Var object, Literal lowerBound, boolean equal_lower, Literal upperBound,
		boolean equal_upper, Literal equals) {

	super(Scope.DEFAULT_CONTEXTS, subject, predicate, object);

	_lowerBound = lowerBound;
	_upperBound = upperBound;

	_equals = equals;

	_equal_lower = equal_lower;
	_equal_upper = equal_upper;
}
 
Example #7
Source File: SubstitutionApplier.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void meet(Var var) {
	Var replacement = s.get(var);
	if (replacement == null)
		return;
	var.setName(replacement.getName());
	var.setConstant(replacement.isConstant());
	var.setValue(replacement.getValue());
}
 
Example #8
Source File: PredicateVariable.java    From neo4j-sparql-extension with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns true if this rule is applicable to a node.
 *
 * @param node to a node
 * @return true if the rule is applicable, false otherwise
 */
@Override
public boolean canApply(StatementPattern node) {
	Var p = node.getPredicateVar();
	// check if predicate is variable
	return !(predicates.isEmpty() || p.isConstant());
}
 
Example #9
Source File: AbstractRule.java    From neo4j-sparql-extension with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns the URI of a constant {@link Var} object.
 *
 * @param v the {@link Var} object
 * @return URI as string if it is a URI, null otherwise
 */
protected String getURIString(Var v) {
	if (v.isConstant()) {
		Value val = v.getValue();
		if (val instanceof URI) {
			URI uri = (URI) val;
			return uri.stringValue();
		}
	}
	return null;
}
 
Example #10
Source File: ObjectPropertyChain.java    From neo4j-sparql-extension with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Transform a statement pattern according to OWL-2 property chain
 * axiom.
 * 
 * @param node the node to transform
 * @return list of nodes to visit next
 */
@Override
public List<QueryModelNode> apply(StatementPattern node) {
	List<QueryModelNode> next = newNextList();
	Var s = node.getSubjectVar();
	Var o = node.getObjectVar();
	Var c = node.getContextVar();
	TupleExpr left  = node.clone();
	TupleExpr right = getChain(s, o, c);
	node.replaceWith(new Union(left, right));
	next.add(left);
	next.add(right);
	return next;
}
 
Example #11
Source File: Rule.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
public Rule getFreshRule() throws Exception {
		StatementPattern consequentClone = consequent.clone();
		TupleExpr antecedentClone = antecedent.clone();

		Set<Var> vars = new HashSet<Var>();
		// vars.addAll(consequentClone.getVarList());
		VarCollector vis = new VarCollector();

		antecedentClone.visit(vis);
		consequentClone.visit(vis);

		vars.addAll(vis.getCollectedVars());

		for (Var var : vars) {
			if (var.isConstant())
				continue;

//			Var newVar = new Var();
			UUID id = UUID.randomUUID();
			
//			String uniqueStringForValue = Integer.toString(id.toString());
			String uniqueStringForValue = Integer.toHexString(id.toString().hashCode());
			
//			newVar.setName(var.getName() + "_" + uniqueStringForValue.toString());
//			newVar.setAnonymous(var.isAnonymous());

			VarRenamer renamer = new VarRenamer(var.getName(), var.getName() + "_" + uniqueStringForValue);
			antecedentClone.visit(renamer);
			consequentClone.visit(renamer);
		}

		Rule result = new Rule();
		result.antecedent = antecedentClone;
		result.consequent = consequentClone;
		return result;
		

	}
 
Example #12
Source File: NeutralSubstitution.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Var get(Var var) {
	return null;
}
 
Example #13
Source File: SingletonSubstituion.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
public Var getSubstition() {
	return substition;
}
 
Example #14
Source File: NeutralSubstitution.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Map<Var, Var> getMap() {
	return new HashMap<Var, Var>();
}
 
Example #15
Source File: ResolutionEngine.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
/****
 * If the visited pattern unifies with rule, and the node has not been
 * visited, it will replace the node (in the nodes parent) with a union
 * consisting of the node unified with the body of all the rules that
 * unified with the node.
 */
@Override
public void meet(StatementPattern node) {

	if (visited.contains(node))
		return;

	visited.add(node);
	QueryModelNode parent = node.getParentNode();

	List<TupleExpr> nodeAlternatives = new LinkedList<TupleExpr>();
	nodeAlternatives.add(node);

	for (Rule rule : rules) {
		
		try {
			rule = rule.getFreshRule();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} 
		
		Substitution s = StatementUnifier.getMGU(node, rule.consequent);
		if (s == null)
			continue;

		// The rule matches the node, replacing (executing a resolution
		// step)

		// Preparing the body of the rule
		TupleExpr body = rule.antecedent;
		SubstitutionApplier app = new SubstitutionApplier(s);
		body.visit(app);
		
		/* If the substitution affects any variables in the domain of the original query
		then we need to add a BIND(...) element, using extensions, for example. If x is in 
		the original query, and we have the substition x/<example.org> we need the 
		extension BIND(<example.org> as ?x)
		*/
		Extension ex = new Extension();
		for (Var var: s.getMap().keySet()) {
			String name = var.getName();
			if (!queryBindingNames.contains(name)) {
				continue;
			}
			
			Var expr = s.get(var);
			ex.addElement(new ExtensionElem(expr, name));
		}
		
		TupleExpr newExpression;
		
		if (!ex.getElements().isEmpty()) {
			ex.setArg(body);
			newExpression = ex;
		} else {
			newExpression = body;
		}
		
		nodeAlternatives.add(newExpression);
	}

	if (nodeAlternatives.size() == 1) {
		// There was no resolution, no change
		return;
	}

	// constructing UNION operator, a binary tree, removing 2 at a time
	Union union = null;
	while (!nodeAlternatives.isEmpty()) {
		Union newunion = null;
		if (union == null) {
			newunion = new Union(nodeAlternatives.remove(0), nodeAlternatives.remove(0));

		} else {
			newunion = new Union(nodeAlternatives.remove(0), union);
		}
		union = newunion;
	}

	// replacing the node with the constructed union
	parent.replaceChildNode(node, union);
	
	
	producedChange = true;

}
 
Example #16
Source File: Rule.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
private void extractConsequent(TupleExpr constructQuery, Projection projection, Extension extension) {
	StatementPattern consequent = new StatementPattern();
	Var sub = new Var();
	Var pred = new Var();
	Var obj = new Var();
	
	HashMap<String, ValueConstant> index = new HashMap<String, ValueConstant>();
	for (ExtensionElem extElem: extension.getElements()) {
		try {
			index.put(extElem.getName(), (ValueConstant) extElem.getExpr());
		} catch (ClassCastException e) {
			e.printStackTrace();
			throw new RuntimeException("Unsupported construct query rule: \n" + constructQuery.toString());
		}
	}
	
	for (ProjectionElem elem: projection.getProjectionElemList().getElements()) {
		Var currentComponent = null;
		if (elem.getTargetName().equals("subject")) {
			currentComponent = sub;
		} else if (elem.getTargetName().equals("predicate")) {
			currentComponent = pred;
		} else if (elem.getTargetName().equals("object")) {
			currentComponent = obj;
		} else {
			throw new RuntimeException("Unsupported construct query rule: " + constructQuery.toString());
		}
		
		ValueConstant valueConstant = index.get(elem.getSourceName());
		if (valueConstant != null) {
			currentComponent.setConstant(true);
			currentComponent.setValue(valueConstant.getValue());
			currentComponent.setName(elem.getSourceName());
		} else {
			currentComponent.setConstant(false);
			currentComponent.setName(elem.getSourceName());
		}
	}
	
	consequent.setSubjectVar(sub);
	consequent.setPredicateVar(pred);
	consequent.setObjectVar(obj);

	this.consequent = consequent;
}
 
Example #17
Source File: Rule.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void meet(Var var) {
	collectedVars.add(var);
}
 
Example #18
Source File: Rule.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * @return Returns the collectedVars.
 */
public Set<Var> getCollectedVars() {
	return collectedVars;
}
 
Example #19
Source File: SubstitutionImpl.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Var get(Var var) {
	return map.get(var);
}
 
Example #20
Source File: SubstitutionImpl.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Map<Var, Var> getMap() {
	return map;
}
 
Example #21
Source File: VarRenamer.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void meet(Var var) {
	if (var.getName().equals(oldName)) {
		var.setName(newName);
	}
}
 
Example #22
Source File: SingletonSubstituion.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public boolean compose(Var original, Var substituion) {
	throw new UnsupportedOperationException();

}
 
Example #23
Source File: NegatedPropertySet.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @return Returns the subjectVar.
 */
public Var getSubjectVar() {
	return subjectVar;
}
 
Example #24
Source File: NegatedPropertySet.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @return Returns the contextVar.
 */
public Var getContextVar() {
	return contextVar;
}
 
Example #25
Source File: CumulusQueryOptimizer.java    From cumulusrdf with Apache License 2.0 4 votes vote down vote up
public RangeStatementModifier(final TupleExpr tupleExpr, final CompareOp comp, final Var var, final Literal bound) {
	_tupleExpr = tupleExpr;
	_comp = comp;
	_var = var;
	_bound = bound;
}
 
Example #26
Source File: RangeEvaluationStrategy.java    From cumulusrdf with Apache License 2.0 4 votes vote down vote up
public CloseableIteration<BindingSet, QueryEvaluationException> evaluate(RangeStatementPattern sp, final BindingSet bindings)
		throws QueryEvaluationException {

	CloseableIteration<? extends Statement, QueryEvaluationException> stIter = null;

	if (tripleSource instanceof CumulusRDFSailConnection.CumulusRDFTripleSource) {

		final Var subjVar = sp.getSubjectVar();
		final Var predVar = sp.getPredicateVar();
		final Var objVar = sp.getObjectVar();
		final Var conVar = sp.getContextVar();

		final boolean upper_equals = sp.getUpperBoundEquals(), lower_equals = sp.getLowerBoundEquals();

		final Value subjValue = getVarValue(subjVar, bindings);
		final Value predValue = getVarValue(predVar, bindings);

		final boolean reverse = !sp.isAscending();

		stIter = ((CumulusRDFSailConnection.CumulusRDFTripleSource) tripleSource).getRangeStatements((Resource) subjValue, (URI) predValue,
				sp.getLowerBound(), lower_equals, sp.getUpperBound(), upper_equals, sp.getEquals(), reverse);

		return new ConvertingIteration<Statement, BindingSet, QueryEvaluationException>(stIter) {

			@Override
			protected BindingSet convert(Statement st) {
				QueryBindingSet result = new QueryBindingSet(bindings);

				if (subjVar != null && !result.hasBinding(subjVar.getName())) {
					result.addBinding(subjVar.getName(), st.getSubject());
				}
				if (predVar != null && !result.hasBinding(predVar.getName())) {
					result.addBinding(predVar.getName(), st.getPredicate());
				}
				if (objVar != null && !result.hasBinding(objVar.getName())) {
					result.addBinding(objVar.getName(), st.getObject());
				}
				if (conVar != null && !result.hasBinding(conVar.getName()) && st.getContext() != null) {
					result.addBinding(conVar.getName(), st.getContext());
				}

				return result;
			}
		};

	} else {
		throw new UnsupportedOperationException("RangeEvaluationStrategy can only be used with CumulusRdfStore!");
	}

}
 
Example #27
Source File: SeenVisitor.java    From neo4j-sparql-extension with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void meet(Var node) throws RuntimeException {
	setSeen(node);
	super.meet(node);
}
 
Example #28
Source File: ConsistencyVisitor.java    From neo4j-sparql-extension with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void meet(Var node) throws RuntimeException {
	check(node);
	super.meet(node);
}
 
Example #29
Source File: SingletonSubstituion.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
public SingletonSubstituion(Var original, Var substituion) {
	this.original = original;
	this.substition = substituion;
}
 
Example #30
Source File: NeutralSubstitution.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public boolean compose(Var original, Var substituion) {
	throw new UnsupportedOperationException();
}