Search in sources :

Example 16 with Unifier

use of ai.grakn.graql.admin.Unifier in project grakn by graknlabs.

the class AtomicTest method exactUnification.

/**
 * checks the correctness and uniqueness of an exact unifier required to unify child query with parent
 * @param parentQuery parent query
 * @param childQuery child query
 * @param checkInverse flag specifying whether the inverse equality u^{-1}=u(parent, child) of the unifier u(child, parent) should be checked
 * @param checkEquality if true the parent and child answers will be checked for equality, otherwise they are checked for containment of child answers in parent
 */
private void exactUnification(ReasonerAtomicQuery parentQuery, ReasonerAtomicQuery childQuery, boolean checkInverse, boolean checkEquality) {
    Atom childAtom = childQuery.getAtom();
    Atom parentAtom = parentQuery.getAtom();
    Unifier unifier = childAtom.getMultiUnifier(parentAtom, UnifierType.EXACT).getUnifier();
    List<Answer> childAnswers = childQuery.getQuery().execute();
    List<Answer> unifiedAnswers = childAnswers.stream().map(a -> a.unify(unifier)).filter(a -> !a.isEmpty()).collect(Collectors.toList());
    List<Answer> parentAnswers = parentQuery.getQuery().execute();
    if (checkInverse) {
        Unifier unifier2 = parentAtom.getUnifier(childAtom);
        assertEquals(unifier.inverse(), unifier2);
        assertEquals(unifier, unifier2.inverse());
    }
    assertTrue(!childAnswers.isEmpty());
    assertTrue(!unifiedAnswers.isEmpty());
    assertTrue(!parentAnswers.isEmpty());
    if (!checkEquality) {
        assertTrue(parentAnswers.containsAll(unifiedAnswers));
    } else {
        assertCollectionsEqual(parentAnswers, unifiedAnswers);
        Unifier inverse = unifier.inverse();
        List<Answer> parentToChild = parentAnswers.stream().map(a -> a.unify(inverse)).collect(Collectors.toList());
        assertCollectionsEqual(parentToChild, childAnswers);
    }
}
Also used : Iterables(com.google.common.collect.Iterables) Atom(ai.grakn.graql.internal.reasoner.atom.Atom) BeforeClass(org.junit.BeforeClass) GraknTestUtil(ai.grakn.util.GraknTestUtil) GraqlTestUtil.assertCollectionsEqual(ai.grakn.util.GraqlTestUtil.assertCollectionsEqual) Role(ai.grakn.concept.Role) Concept(ai.grakn.concept.Concept) Answer(ai.grakn.graql.admin.Answer) Multimap(com.google.common.collect.Multimap) Assert.assertThat(org.junit.Assert.assertThat) HashMultimap(com.google.common.collect.HashMultimap) RuleUtils(ai.grakn.graql.internal.reasoner.rule.RuleUtils) ClassRule(org.junit.ClassRule) RelationshipAtom(ai.grakn.graql.internal.reasoner.atom.binary.RelationshipAtom) Collectors.toSet(java.util.stream.Collectors.toSet) ImmutableSetMultimap(com.google.common.collect.ImmutableSetMultimap) Patterns(ai.grakn.graql.internal.pattern.Patterns) Graql.var(ai.grakn.graql.Graql.var) Matchers.empty(org.hamcrest.Matchers.empty) Conjunction(ai.grakn.graql.admin.Conjunction) ImmutableMap(com.google.common.collect.ImmutableMap) MultiUnifier(ai.grakn.graql.admin.MultiUnifier) Collection(java.util.Collection) Set(java.util.Set) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Collectors(java.util.stream.Collectors) GetQuery(ai.grakn.graql.GetQuery) Sets(com.google.common.collect.Sets) Atomic(ai.grakn.graql.admin.Atomic) List(java.util.List) InferenceRule(ai.grakn.graql.internal.reasoner.rule.InferenceRule) ReasonerQueries(ai.grakn.graql.internal.reasoner.query.ReasonerQueries) EmbeddedGraknTx(ai.grakn.kb.internal.EmbeddedGraknTx) Var(ai.grakn.graql.Var) VarPatternAdmin(ai.grakn.graql.admin.VarPatternAdmin) SampleKBContext(ai.grakn.test.rule.SampleKBContext) Assume.assumeTrue(org.junit.Assume.assumeTrue) ReasonerAtomicQuery(ai.grakn.graql.internal.reasoner.query.ReasonerAtomicQuery) Schema(ai.grakn.util.Schema) Unifier(ai.grakn.graql.admin.Unifier) ResourceAtom(ai.grakn.graql.internal.reasoner.atom.binary.ResourceAtom) Assert.assertEquals(org.junit.Assert.assertEquals) Answer(ai.grakn.graql.admin.Answer) Atom(ai.grakn.graql.internal.reasoner.atom.Atom) RelationshipAtom(ai.grakn.graql.internal.reasoner.atom.binary.RelationshipAtom) ResourceAtom(ai.grakn.graql.internal.reasoner.atom.binary.ResourceAtom) MultiUnifier(ai.grakn.graql.admin.MultiUnifier) Unifier(ai.grakn.graql.admin.Unifier)

Example 17 with Unifier

use of ai.grakn.graql.admin.Unifier in project grakn by graknlabs.

the class RelationshipAtom method getMultiUnifier.

@Override
public MultiUnifier getMultiUnifier(Atom pAtom, UnifierComparison unifierType) {
    Unifier baseUnifier = super.getUnifier(pAtom);
    Set<Unifier> unifiers = new HashSet<>();
    if (pAtom.isRelation()) {
        // This is safe due to the check above
        assert (pAtom instanceof RelationshipAtom);
        RelationshipAtom parentAtom = (RelationshipAtom) pAtom;
        // this is important for cases like unifying ($r1: $x, $r2: $y) with itself
        if (this.equals(parentAtom) && this.getPartialSubstitutions().collect(toSet()).equals(parentAtom.getPartialSubstitutions().collect(toSet())) && this.getTypeConstraints().collect(toSet()).equals(parentAtom.getTypeConstraints().collect(toSet()))) {
            return new MultiUnifierImpl();
        }
        boolean unifyRoleVariables = parentAtom.getRelationPlayers().stream().map(RelationPlayer::getRole).flatMap(CommonUtil::optionalToStream).anyMatch(rp -> rp.var().isUserDefinedName());
        getRelationPlayerMappings(parentAtom, unifierType).forEach(mappingList -> {
            Multimap<Var, Var> varMappings = HashMultimap.create();
            mappingList.forEach(rpm -> {
                // add role player mapping
                varMappings.put(rpm.getKey().getRolePlayer().var(), rpm.getValue().getRolePlayer().var());
                // add role var mapping if needed
                VarPattern childRolePattern = rpm.getKey().getRole().orElse(null);
                VarPattern parentRolePattern = rpm.getValue().getRole().orElse(null);
                if (parentRolePattern != null && childRolePattern != null && unifyRoleVariables) {
                    varMappings.put(childRolePattern.admin().var(), parentRolePattern.admin().var());
                }
            });
            unifiers.add(baseUnifier.merge(new UnifierImpl(varMappings)));
        });
    } else {
        unifiers.add(baseUnifier);
    }
    return new MultiUnifierImpl(unifiers);
}
Also used : Var(ai.grakn.graql.Var) VarPattern(ai.grakn.graql.VarPattern) MultiUnifierImpl(ai.grakn.graql.internal.reasoner.MultiUnifierImpl) UnifierImpl(ai.grakn.graql.internal.reasoner.UnifierImpl) MultiUnifierImpl(ai.grakn.graql.internal.reasoner.MultiUnifierImpl) RelationPlayer(ai.grakn.graql.admin.RelationPlayer) MultiUnifier(ai.grakn.graql.admin.MultiUnifier) Unifier(ai.grakn.graql.admin.Unifier) HashSet(java.util.HashSet)

Example 18 with Unifier

use of ai.grakn.graql.admin.Unifier in project grakn by graknlabs.

the class ReasonerQueryImpl method queryStateIterator.

/**
 * @param parent parent state
 * @param subGoals set of visited sub goals
 * @param cache query cache
 * @return query state iterator (db iter + unifier + state iter) for this query
 */
public Pair<Iterator<ResolutionState>, MultiUnifier> queryStateIterator(QueryStateBase parent, Set<ReasonerAtomicQuery> subGoals, QueryCache<ReasonerAtomicQuery> cache) {
    Iterator<AnswerState> dbIterator;
    Iterator<QueryStateBase> subGoalIterator;
    if (!this.isRuleResolvable()) {
        dbIterator = this.getQuery().stream().map(ans -> ans.explain(new JoinExplanation(this, ans))).map(ans -> new AnswerState(ans, parent.getUnifier(), parent)).iterator();
        subGoalIterator = Collections.emptyIterator();
    } else {
        dbIterator = Collections.emptyIterator();
        LinkedList<ReasonerQueryImpl> subQueries = new ResolutionPlan(this).queryPlan();
        LOG.trace("CQ plan:\n" + subQueries.stream().map(sq -> sq.toString() + (sq.isRuleResolvable() ? "*" : "")).collect(Collectors.joining("\n")));
        subGoalIterator = Iterators.singletonIterator(new CumulativeState(subQueries, new QueryAnswer(), parent.getUnifier(), parent, subGoals, cache));
    }
    return new Pair<>(Iterators.concat(dbIterator, subGoalIterator), new MultiUnifierImpl());
}
Also used : PatternAdmin(ai.grakn.graql.admin.PatternAdmin) Pair(ai.grakn.graql.internal.reasoner.utils.Pair) Atom(ai.grakn.graql.internal.reasoner.atom.Atom) LoggerFactory(org.slf4j.LoggerFactory) Type(ai.grakn.concept.Type) ResolutionIterator(ai.grakn.graql.internal.reasoner.ResolutionIterator) QueryStateBase(ai.grakn.graql.internal.reasoner.state.QueryStateBase) MultiUnifierImpl(ai.grakn.graql.internal.reasoner.MultiUnifierImpl) ResolutionState(ai.grakn.graql.internal.reasoner.state.ResolutionState) QueryAnswerStream.join(ai.grakn.graql.internal.reasoner.query.QueryAnswerStream.join) Map(java.util.Map) IsaAtom(ai.grakn.graql.internal.reasoner.atom.binary.IsaAtom) RuleUtils(ai.grakn.graql.internal.reasoner.rule.RuleUtils) ConceptId(ai.grakn.concept.ConceptId) Graql.var(ai.grakn.graql.Graql.var) ImmutableSet(com.google.common.collect.ImmutableSet) NeqPredicate(ai.grakn.graql.internal.reasoner.atom.predicate.NeqPredicate) Conjunction(ai.grakn.graql.admin.Conjunction) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) ConjunctiveState(ai.grakn.graql.internal.reasoner.state.ConjunctiveState) QueryAnswerStream.joinWithInverse(ai.grakn.graql.internal.reasoner.query.QueryAnswerStream.joinWithInverse) Set(java.util.Set) IdPredicate(ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate) Collectors(java.util.stream.Collectors) LazyQueryCache(ai.grakn.graql.internal.reasoner.cache.LazyQueryCache) Sets(com.google.common.collect.Sets) Objects(java.util.Objects) Atomic(ai.grakn.graql.admin.Atomic) List(java.util.List) Cache(ai.grakn.graql.internal.reasoner.cache.Cache) Stream(java.util.stream.Stream) InferenceRule(ai.grakn.graql.internal.reasoner.rule.InferenceRule) Var(ai.grakn.graql.Var) AtomicBase(ai.grakn.graql.internal.reasoner.atom.AtomicBase) UnifierType(ai.grakn.graql.internal.reasoner.UnifierType) Concept(ai.grakn.concept.Concept) HashMap(java.util.HashMap) Answer(ai.grakn.graql.admin.Answer) CumulativeState(ai.grakn.graql.internal.reasoner.state.CumulativeState) JoinExplanation(ai.grakn.graql.internal.reasoner.explanation.JoinExplanation) Iterators(com.google.common.collect.Iterators) QueryAnswerStream.nonEqualsFilter(ai.grakn.graql.internal.reasoner.query.QueryAnswerStream.nonEqualsFilter) HashSet(java.util.HashSet) Lists(com.google.common.collect.Lists) QueryAnswer(ai.grakn.graql.internal.query.QueryAnswer) LinkedList(java.util.LinkedList) RelationshipAtom(ai.grakn.graql.internal.reasoner.atom.binary.RelationshipAtom) Nullable(javax.annotation.Nullable) LinkedHashSet(java.util.LinkedHashSet) QueryCache(ai.grakn.graql.internal.reasoner.cache.QueryCache) Patterns(ai.grakn.graql.internal.pattern.Patterns) GraqlQueryException(ai.grakn.exception.GraqlQueryException) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) AnswerState(ai.grakn.graql.internal.reasoner.state.AnswerState) MultiUnifier(ai.grakn.graql.admin.MultiUnifier) IsaAtomBase(ai.grakn.graql.internal.reasoner.atom.binary.IsaAtomBase) GetQuery(ai.grakn.graql.GetQuery) AtomicFactory(ai.grakn.graql.internal.reasoner.atom.AtomicFactory) ReasonerQuery(ai.grakn.graql.admin.ReasonerQuery) UnifierComparison(ai.grakn.graql.admin.UnifierComparison) EmbeddedGraknTx(ai.grakn.kb.internal.EmbeddedGraknTx) VarPatternAdmin(ai.grakn.graql.admin.VarPatternAdmin) Schema(ai.grakn.util.Schema) Unifier(ai.grakn.graql.admin.Unifier) ResolutionPlan(ai.grakn.graql.internal.reasoner.plan.ResolutionPlan) Collections(java.util.Collections) JoinExplanation(ai.grakn.graql.internal.reasoner.explanation.JoinExplanation) MultiUnifierImpl(ai.grakn.graql.internal.reasoner.MultiUnifierImpl) CumulativeState(ai.grakn.graql.internal.reasoner.state.CumulativeState) QueryStateBase(ai.grakn.graql.internal.reasoner.state.QueryStateBase) QueryAnswer(ai.grakn.graql.internal.query.QueryAnswer) AnswerState(ai.grakn.graql.internal.reasoner.state.AnswerState) ResolutionPlan(ai.grakn.graql.internal.reasoner.plan.ResolutionPlan) Pair(ai.grakn.graql.internal.reasoner.utils.Pair)

Example 19 with Unifier

use of ai.grakn.graql.admin.Unifier in project grakn by graknlabs.

the class AtomicState method consumeAnswer.

@Override
Answer consumeAnswer(AnswerState state) {
    Answer answer;
    ReasonerAtomicQuery query = getQuery();
    Answer baseAnswer = state.getSubstitution();
    InferenceRule rule = state.getRule();
    Unifier unifier = state.getUnifier();
    if (rule == null)
        answer = state.getSubstitution();
    else {
        answer = rule.requiresMaterialisation(query.getAtom()) ? materialisedAnswer(baseAnswer, rule, unifier) : ruleAnswer(baseAnswer, rule, unifier);
    }
    return getCache().recordAnswerWithUnifier(query, answer, getCacheUnifier());
}
Also used : Answer(ai.grakn.graql.admin.Answer) QueryAnswer(ai.grakn.graql.internal.query.QueryAnswer) InferenceRule(ai.grakn.graql.internal.reasoner.rule.InferenceRule) ReasonerAtomicQuery(ai.grakn.graql.internal.reasoner.query.ReasonerAtomicQuery) Unifier(ai.grakn.graql.admin.Unifier)

Example 20 with Unifier

use of ai.grakn.graql.admin.Unifier in project grakn by graknlabs.

the class ResourceAtom method getUnifier.

@Override
public Unifier getUnifier(Atom parentAtom) {
    if (!(parentAtom instanceof ResourceAtom)) {
        return new UnifierImpl(ImmutableMap.of(this.getPredicateVariable(), parentAtom.getVarName()));
    }
    Unifier unifier = super.getUnifier(parentAtom);
    ResourceAtom parent = (ResourceAtom) parentAtom;
    // unify relation vars
    Var childRelationVarName = this.getRelationVariable();
    Var parentRelationVarName = parent.getRelationVariable();
    if (parentRelationVarName.isUserDefinedName() && !childRelationVarName.equals(parentRelationVarName)) {
        unifier = unifier.merge(new UnifierImpl(ImmutableMap.of(childRelationVarName, parentRelationVarName)));
    }
    return unifier;
}
Also used : Var(ai.grakn.graql.Var) UnifierImpl(ai.grakn.graql.internal.reasoner.UnifierImpl) Unifier(ai.grakn.graql.admin.Unifier)

Aggregations

Unifier (ai.grakn.graql.admin.Unifier)28 MultiUnifier (ai.grakn.graql.admin.MultiUnifier)23 Test (org.junit.Test)18 ReasonerAtomicQuery (ai.grakn.graql.internal.reasoner.query.ReasonerAtomicQuery)17 VarPatternAdmin (ai.grakn.graql.admin.VarPatternAdmin)16 Answer (ai.grakn.graql.admin.Answer)13 Var (ai.grakn.graql.Var)11 Atom (ai.grakn.graql.internal.reasoner.atom.Atom)9 InferenceRule (ai.grakn.graql.internal.reasoner.rule.InferenceRule)7 EmbeddedGraknTx (ai.grakn.kb.internal.EmbeddedGraknTx)7 Concept (ai.grakn.concept.Concept)6 Atomic (ai.grakn.graql.admin.Atomic)6 Conjunction (ai.grakn.graql.admin.Conjunction)6 QueryAnswer (ai.grakn.graql.internal.query.QueryAnswer)6 RelationshipAtom (ai.grakn.graql.internal.reasoner.atom.binary.RelationshipAtom)6 ResourceAtom (ai.grakn.graql.internal.reasoner.atom.binary.ResourceAtom)6 Sets (com.google.common.collect.Sets)6 List (java.util.List)6 Set (java.util.Set)6 Collectors (java.util.stream.Collectors)6