Search in sources :

Example 6 with NullableStatementImpl

use of org.apache.rya.api.utils.NullableStatementImpl in project incubator-rya by apache.

the class SomeValuesFromVisitorTest method testSomeValuesFrom.

@Test
public void testSomeValuesFrom() throws Exception {
    // Configure a mock instance engine with an ontology:
    final InferenceEngine inferenceEngine = mock(InferenceEngine.class);
    Map<Resource, Set<URI>> personSVF = new HashMap<>();
    personSVF.put(gradCourse, Sets.newHashSet(takesCourse));
    personSVF.put(course, Sets.newHashSet(takesCourse));
    personSVF.put(department, Sets.newHashSet(headOf));
    personSVF.put(organization, Sets.newHashSet(worksFor, headOf));
    when(inferenceEngine.getSomeValuesFromByRestrictionType(person)).thenReturn(personSVF);
    // Query for a specific type and rewrite using the visitor:
    StatementPattern originalSP = new StatementPattern(new Var("s"), new Var("p", RDF.TYPE), new Var("o", person));
    final Projection query = new Projection(originalSP, new ProjectionElemList(new ProjectionElem("s", "subject")));
    query.visit(new SomeValuesFromVisitor(conf, inferenceEngine));
    // Expected structure: a union of two elements: one is equal to the original statement
    // pattern, and the other one joins a list of predicate/value type combinations
    // with another join querying for any nodes who are the subject of a triple with that
    // predicate and with an object of that type.
    // 
    // Union(
    // SP(?node a :impliedType),
    // Join(
    // FSP(<?property someValuesFrom ?valueType> {
    // takesCourse/Course;
    // takesCourse/GraduateCourse;
    // headOf/Department;
    // headOf/Organization;
    // worksFor/Organization;
    // }),
    // Join(
    // SP(_:object a ?valueType),
    // SP(?node ?property _:object)
    // )
    // )
    Assert.assertTrue(query.getArg() instanceof Union);
    TupleExpr left = ((Union) query.getArg()).getLeftArg();
    TupleExpr right = ((Union) query.getArg()).getRightArg();
    Assert.assertEquals(originalSP, left);
    Assert.assertTrue(right instanceof Join);
    final Join join = (Join) right;
    Assert.assertTrue(join.getLeftArg() instanceof FixedStatementPattern);
    Assert.assertTrue(join.getRightArg() instanceof Join);
    FixedStatementPattern fsp = (FixedStatementPattern) join.getLeftArg();
    left = ((Join) join.getRightArg()).getLeftArg();
    right = ((Join) join.getRightArg()).getRightArg();
    Assert.assertTrue(left instanceof StatementPattern);
    Assert.assertTrue(right instanceof StatementPattern);
    // Verify expected predicate/type pairs
    Assert.assertTrue(fsp.statements.contains(new NullableStatementImpl(takesCourse, OWL.SOMEVALUESFROM, course)));
    Assert.assertTrue(fsp.statements.contains(new NullableStatementImpl(takesCourse, OWL.SOMEVALUESFROM, gradCourse)));
    Assert.assertTrue(fsp.statements.contains(new NullableStatementImpl(headOf, OWL.SOMEVALUESFROM, department)));
    Assert.assertTrue(fsp.statements.contains(new NullableStatementImpl(headOf, OWL.SOMEVALUESFROM, organization)));
    Assert.assertTrue(fsp.statements.contains(new NullableStatementImpl(worksFor, OWL.SOMEVALUESFROM, organization)));
    Assert.assertEquals(5, fsp.statements.size());
    // Verify pattern for matching instances of each pair: a Join of <_:x rdf:type ?t> and
    // <?s ?p _:x> where p and t are the predicate/type pair and s is the original subject
    // variable.
    StatementPattern leftSP = (StatementPattern) left;
    StatementPattern rightSP = (StatementPattern) right;
    Assert.assertEquals(rightSP.getObjectVar(), leftSP.getSubjectVar());
    Assert.assertEquals(RDF.TYPE, leftSP.getPredicateVar().getValue());
    Assert.assertEquals(fsp.getObjectVar(), leftSP.getObjectVar());
    Assert.assertEquals(originalSP.getSubjectVar(), rightSP.getSubjectVar());
    Assert.assertEquals(fsp.getSubjectVar(), rightSP.getPredicateVar());
}
Also used : ProjectionElemList(org.openrdf.query.algebra.ProjectionElemList) Set(java.util.Set) HashMap(java.util.HashMap) Var(org.openrdf.query.algebra.Var) Resource(org.openrdf.model.Resource) Projection(org.openrdf.query.algebra.Projection) Join(org.openrdf.query.algebra.Join) Union(org.openrdf.query.algebra.Union) TupleExpr(org.openrdf.query.algebra.TupleExpr) FixedStatementPattern(org.apache.rya.rdftriplestore.utils.FixedStatementPattern) StatementPattern(org.openrdf.query.algebra.StatementPattern) NullableStatementImpl(org.apache.rya.api.utils.NullableStatementImpl) ProjectionElem(org.openrdf.query.algebra.ProjectionElem) FixedStatementPattern(org.apache.rya.rdftriplestore.utils.FixedStatementPattern) Test(org.junit.Test)

Example 7 with NullableStatementImpl

use of org.apache.rya.api.utils.NullableStatementImpl in project incubator-rya by apache.

the class SubPropertyOfVisitor method meetSP.

@Override
protected void meetSP(final StatementPattern node) throws Exception {
    final StatementPattern sp = node.clone();
    final Var predVar = sp.getPredicateVar();
    final URI pred = (URI) predVar.getValue();
    final String predNamespace = pred.getNamespace();
    final Var objVar = sp.getObjectVar();
    final Var cntxtVar = sp.getContextVar();
    if (objVar != null && !RDF.NAMESPACE.equals(predNamespace) && !SESAME.NAMESPACE.equals(predNamespace) && !RDFS.NAMESPACE.equals(predNamespace) && !EXPANDED.equals(cntxtVar)) {
        /**
         * { ?subProp rdfs:subPropertyOf ub:worksFor . ?y ?subProp <http://www.Department0.University0.edu> }\n" +
         *             "       UNION " +
         *             "      { ?y ub:worksFor <http://www.Department0.University0.edu> }
         */
        // String s = UUID.randomUUID().toString();
        // Var subPropVar = new Var(s);
        // StatementPattern subPropOf = new StatementPattern(subPropVar, new Var("c-" + s, SESAME.DIRECTSUBPROPERTYOF), predVar, EXPANDED);
        // StatementPattern subPropOf2 = new StatementPattern(sp.getSubjectVar(), subPropVar, objVar, EXPANDED);
        // InferJoin join = new InferJoin(subPropOf, subPropOf2);
        // join.getProperties().put(InferConstants.INFERRED, InferConstants.TRUE);
        // node.replaceWith(join);
        // Collection<URI> parents = inferenceEngine.findParents(inferenceEngine.subPropertyOfGraph, (URI) predVar.getValue());
        // if (parents != null && parents.size() > 0) {
        // StatementPatterns statementPatterns = new StatementPatterns();
        // statementPatterns.patterns.add(node);
        // Var subjVar = node.getSubjectVar();
        // for (URI u : parents) {
        // statementPatterns.patterns.add(new StatementPattern(subjVar, new Var(predVar.getName(), u), objVar));
        // }
        // node.replaceWith(statementPatterns);
        // }
        // if (parents != null && parents.size() > 0) {
        // VarCollection vc = new VarCollection();
        // vc.setName(predVar.getName());
        // vc.values.add(predVar);
        // for (URI u : parents) {
        // vc.values.add(new Var(predVar.getName(), u));
        // }
        // Var subjVar = node.getSubjectVar();
        // node.replaceWith(new StatementPattern(subjVar, vc, objVar, node.getContextVar()));
        // }
        final URI subprop_uri = (URI) predVar.getValue();
        final Set<URI> parents = InferenceEngine.findParents(inferenceEngine.getSubPropertyOfGraph(), subprop_uri);
        if (parents != null && parents.size() > 0) {
            final String s = UUID.randomUUID().toString();
            final Var typeVar = new Var(s);
            final FixedStatementPattern fsp = new FixedStatementPattern(typeVar, new Var("c-" + s, RDFS.SUBPROPERTYOF), predVar, cntxtVar);
            // fsp.statements.add(new NullableStatementImpl(subprop_uri, RDFS.SUBPROPERTYOF, subprop_uri));
            // add self
            parents.add(subprop_uri);
            for (final URI u : parents) {
                fsp.statements.add(new NullableStatementImpl(u, RDFS.SUBPROPERTYOF, subprop_uri));
            }
            final StatementPattern rdfType = new DoNotExpandSP(sp.getSubjectVar(), typeVar, sp.getObjectVar(), cntxtVar);
            final InferJoin join = new InferJoin(fsp, rdfType);
            join.getProperties().put(InferConstants.INFERRED, InferConstants.TRUE);
            node.replaceWith(join);
        }
    }
}
Also used : FixedStatementPattern(org.apache.rya.rdftriplestore.utils.FixedStatementPattern) StatementPattern(org.openrdf.query.algebra.StatementPattern) NullableStatementImpl(org.apache.rya.api.utils.NullableStatementImpl) Var(org.openrdf.query.algebra.Var) URI(org.openrdf.model.URI) FixedStatementPattern(org.apache.rya.rdftriplestore.utils.FixedStatementPattern)

Example 8 with NullableStatementImpl

use of org.apache.rya.api.utils.NullableStatementImpl in project incubator-rya by apache.

the class SameAsVisitor method meetSP.

@Override
protected void meetSP(StatementPattern node) throws Exception {
    StatementPattern sp = node.clone();
    final Var predVar = sp.getPredicateVar();
    boolean shouldExpand = true;
    if (predVar.hasValue()) {
        URI pred = (URI) predVar.getValue();
        String predNamespace = pred.getNamespace();
        shouldExpand = !pred.equals(OWL.SAMEAS) && !RDF.NAMESPACE.equals(predNamespace) && !SESAME.NAMESPACE.equals(predNamespace) && !RDFS.NAMESPACE.equals(predNamespace);
    }
    final Var objVar = sp.getObjectVar();
    final Var subjVar = sp.getSubjectVar();
    final Var cntxtVar = sp.getContextVar();
    if (shouldExpand && !EXPANDED.equals(cntxtVar) && !(objVar == null) && !(subjVar == null)) {
        if (objVar.getValue() == null) {
            Value subjVarValue = subjVar.getValue();
            if (subjVarValue instanceof Resource) {
                Set<Resource> uris = inferenceEngine.findSameAs((Resource) subjVar.getValue(), getVarValue(cntxtVar));
                if (uris.size() > 1) {
                    InferJoin join = getReplaceJoin(uris, true, subjVar, objVar, predVar, cntxtVar);
                    node.replaceWith(join);
                }
            }
        } else if (subjVar.getValue() == null) {
            Value objVarValue = objVar.getValue();
            if (objVarValue instanceof Resource) {
                Set<Resource> uris = inferenceEngine.findSameAs((Resource) objVar.getValue(), getVarValue(cntxtVar));
                if (uris.size() > 1) {
                    InferJoin join = getReplaceJoin(uris, false, subjVar, objVar, predVar, cntxtVar);
                    node.replaceWith(join);
                }
            }
        } else {
            // both subj and pred are set and should be expanded
            Set<Resource> subjURIs = new HashSet<Resource>();
            Set<Resource> objURIs = new HashSet<Resource>();
            // TODO I don't like these checks -- is there a better way to do this?
            Value objVarValue = objVar.getValue();
            if (objVarValue instanceof Resource) {
                objURIs = inferenceEngine.findSameAs((Resource) objVar.getValue(), getVarValue(cntxtVar));
            }
            Value subjVarValue = subjVar.getValue();
            if (subjVarValue instanceof Resource) {
                subjURIs = inferenceEngine.findSameAs((Resource) subjVar.getValue(), getVarValue(cntxtVar));
            }
            InferJoin finalJoin = null;
            // expand subj first
            if (subjURIs.size() > 1) {
                finalJoin = getReplaceJoin(subjURIs, true, subjVar, objVar, predVar, cntxtVar);
            }
            // now expand the obj
            if (objURIs.size() > 1) {
                // if we already expanded the subj
                if (finalJoin != null) {
                    // we know what this is since we created it
                    DoNotExpandSP origStatement = (DoNotExpandSP) finalJoin.getRightArg();
                    String s = UUID.randomUUID().toString();
                    Var dummyVar = new Var(s);
                    StatementPattern origDummyStatement = new DoNotExpandSP(origStatement.getSubjectVar(), origStatement.getPredicateVar(), dummyVar, cntxtVar);
                    FixedStatementPattern fsp = new FixedStatementPattern(dummyVar, new Var("c-" + s, OWL.SAMEAS), objVar, cntxtVar);
                    for (Resource sameAs : objURIs) {
                        NullableStatementImpl newStatement = new NullableStatementImpl(sameAs, OWL.SAMEAS, (Resource) objVar.getValue(), getVarValue(cntxtVar));
                        fsp.statements.add(newStatement);
                    }
                    InferJoin interimJoin = new InferJoin(fsp, origDummyStatement);
                    finalJoin = new InferJoin(finalJoin.getLeftArg(), interimJoin);
                } else {
                    finalJoin = getReplaceJoin(objURIs, false, subjVar, objVar, predVar, cntxtVar);
                }
            }
            if (finalJoin != null) {
                node.replaceWith(finalJoin);
            }
        }
    }
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) Var(org.openrdf.query.algebra.Var) Resource(org.openrdf.model.Resource) URI(org.openrdf.model.URI) FixedStatementPattern(org.apache.rya.rdftriplestore.utils.FixedStatementPattern) StatementPattern(org.openrdf.query.algebra.StatementPattern) NullableStatementImpl(org.apache.rya.api.utils.NullableStatementImpl) Value(org.openrdf.model.Value) FixedStatementPattern(org.apache.rya.rdftriplestore.utils.FixedStatementPattern)

Example 9 with NullableStatementImpl

use of org.apache.rya.api.utils.NullableStatementImpl in project incubator-rya by apache.

the class AllValuesFromVisitor method meetSP.

/**
 * Checks whether the StatementPattern is a type query whose solutions could be inferred
 * by allValuesFrom inference, and if so, replaces the node with a union of itself and any
 * possible inference.
 */
@Override
protected void meetSP(StatementPattern node) throws Exception {
    final Var subjVar = node.getSubjectVar();
    final Var predVar = node.getPredicateVar();
    final Var objVar = node.getObjectVar();
    // Only applies to type queries where the type is defined
    if (predVar != null && RDF.TYPE.equals(predVar.getValue()) && objVar != null && objVar.getValue() instanceof Resource) {
        final Resource typeToInfer = (Resource) objVar.getValue();
        Map<Resource, Set<URI>> relevantAvfRestrictions = inferenceEngine.getAllValuesFromByValueType(typeToInfer);
        if (!relevantAvfRestrictions.isEmpty()) {
            // We can infer the queried type if, for an allValuesFrom restriction type
            // associated  with the queried type, some anonymous neighboring node belongs to the
            // restriction type and has the node in question (subjVar) as a value for the
            // restriction's property.
            final Var avfTypeVar = new Var("t-" + UUID.randomUUID());
            final Var avfPredVar = new Var("p-" + UUID.randomUUID());
            final Var neighborVar = new Var("n-" + UUID.randomUUID());
            neighborVar.setAnonymous(true);
            final StatementPattern membershipPattern = new DoNotExpandSP(neighborVar, new Var(RDF.TYPE.stringValue(), RDF.TYPE), avfTypeVar);
            final StatementPattern valuePattern = new StatementPattern(neighborVar, avfPredVar, subjVar);
            final InferJoin avfPattern = new InferJoin(membershipPattern, valuePattern);
            // Use a FixedStatementPattern to contain the appropriate (restriction, predicate)
            // pairs, and check each one against the general pattern.
            final FixedStatementPattern avfPropertyTypes = new FixedStatementPattern(avfTypeVar, new Var(OWL.ONPROPERTY.stringValue(), OWL.ONPROPERTY), avfPredVar);
            for (Resource avfRestrictionType : relevantAvfRestrictions.keySet()) {
                for (URI avfProperty : relevantAvfRestrictions.get(avfRestrictionType)) {
                    avfPropertyTypes.statements.add(new NullableStatementImpl(avfRestrictionType, OWL.ONPROPERTY, avfProperty));
                }
            }
            final InferJoin avfInferenceQuery = new InferJoin(avfPropertyTypes, avfPattern);
            node.replaceWith(new InferUnion(node.clone(), avfInferenceQuery));
        }
    }
}
Also used : FixedStatementPattern(org.apache.rya.rdftriplestore.utils.FixedStatementPattern) StatementPattern(org.openrdf.query.algebra.StatementPattern) NullableStatementImpl(org.apache.rya.api.utils.NullableStatementImpl) Set(java.util.Set) Var(org.openrdf.query.algebra.Var) Resource(org.openrdf.model.Resource) URI(org.openrdf.model.URI) FixedStatementPattern(org.apache.rya.rdftriplestore.utils.FixedStatementPattern)

Example 10 with NullableStatementImpl

use of org.apache.rya.api.utils.NullableStatementImpl in project incubator-rya by apache.

the class DomainRangeVisitor method meetSP.

/**
 * Checks whether this statement pattern might be inferred using domain and/or range knowledge,
 * and, if so, replaces the statement pattern with a union of itself and any possible
 * derivations.
 */
@Override
protected void meetSP(StatementPattern node) throws Exception {
    final Var subjVar = node.getSubjectVar();
    final Var predVar = node.getPredicateVar();
    final Var objVar = node.getObjectVar();
    final Var contextVar = node.getContextVar();
    // Only applies to statement patterns that query for members of a defined type.
    if (predVar != null && RDF.TYPE.equals(predVar.getValue()) && objVar != null && objVar.getValue() instanceof URI) {
        final URI inferredType = (URI) objVar.getValue();
        // Preserve the original node so explicit type assertions are still matched:
        TupleExpr currentNode = node.clone();
        // If there are any properties with this type as domain, check for appropriate triples:
        final Set<URI> domainProperties = inferenceEngine.getPropertiesWithDomain(inferredType);
        if (!domainProperties.isEmpty()) {
            Var domainPredVar = new Var("p-" + UUID.randomUUID());
            Var domainObjVar = new Var("o-" + UUID.randomUUID());
            domainObjVar.setAnonymous(true);
            Var domainVar = new Var(RDFS.DOMAIN.stringValue(), RDFS.DOMAIN);
            StatementPattern domainSP = new DoNotExpandSP(subjVar, domainPredVar, domainObjVar, contextVar);
            // Enumerate predicates having this type as domain
            FixedStatementPattern domainFSP = new FixedStatementPattern(domainPredVar, domainVar, objVar);
            for (URI property : domainProperties) {
                domainFSP.statements.add(new NullableStatementImpl(property, RDFS.DOMAIN, inferredType));
            }
            // For each such predicate, any triple <subjVar predicate _:any> implies the type
            currentNode = new InferUnion(currentNode, new InferJoin(domainFSP, domainSP));
        }
        // If there are any properties with this type as range, check for appropriate triples:
        final Set<URI> rangeProperties = inferenceEngine.getPropertiesWithRange(inferredType);
        if (!rangeProperties.isEmpty()) {
            Var rangePredVar = new Var("p-" + UUID.randomUUID());
            Var rangeSubjVar = new Var("s-" + UUID.randomUUID());
            rangeSubjVar.setAnonymous(true);
            Var rangeVar = new Var(RDFS.RANGE.stringValue(), RDFS.RANGE);
            StatementPattern rangeSP = new DoNotExpandSP(rangeSubjVar, rangePredVar, subjVar, contextVar);
            // Enumerate predicates having this type as range
            FixedStatementPattern rangeFSP = new FixedStatementPattern(rangePredVar, rangeVar, objVar);
            for (URI property : rangeProperties) {
                rangeFSP.statements.add(new NullableStatementImpl(property, RDFS.RANGE, inferredType));
            }
            // For each such predicate, any triple <_:any predicate subjVar> implies the type
            currentNode = new InferUnion(currentNode, new InferJoin(rangeFSP, rangeSP));
        }
        node.replaceWith(currentNode);
    }
}
Also used : FixedStatementPattern(org.apache.rya.rdftriplestore.utils.FixedStatementPattern) StatementPattern(org.openrdf.query.algebra.StatementPattern) NullableStatementImpl(org.apache.rya.api.utils.NullableStatementImpl) Var(org.openrdf.query.algebra.Var) URI(org.openrdf.model.URI) TupleExpr(org.openrdf.query.algebra.TupleExpr) FixedStatementPattern(org.apache.rya.rdftriplestore.utils.FixedStatementPattern)

Aggregations

NullableStatementImpl (org.apache.rya.api.utils.NullableStatementImpl)12 Var (org.openrdf.query.algebra.Var)12 FixedStatementPattern (org.apache.rya.rdftriplestore.utils.FixedStatementPattern)11 Resource (org.openrdf.model.Resource)9 StatementPattern (org.openrdf.query.algebra.StatementPattern)9 URI (org.openrdf.model.URI)8 Set (java.util.Set)7 TupleExpr (org.openrdf.query.algebra.TupleExpr)4 HashMap (java.util.HashMap)3 Value (org.openrdf.model.Value)3 HashSet (java.util.HashSet)2 Map (java.util.Map)2 Test (org.junit.Test)2 Statement (org.openrdf.model.Statement)2 Join (org.openrdf.query.algebra.Join)2 Projection (org.openrdf.query.algebra.Projection)2 ProjectionElem (org.openrdf.query.algebra.ProjectionElem)2 ProjectionElemList (org.openrdf.query.algebra.ProjectionElemList)2 Union (org.openrdf.query.algebra.Union)2 ConvertingIteration (info.aduna.iteration.ConvertingIteration)1