Search in sources :

Example 11 with QueryAnswer

use of ai.grakn.graql.internal.query.QueryAnswer in project grakn by graknlabs.

the class ExplanationBuilderTest method whenExplainInferred_returnsLinkedExplanation.

// NOTE: This test ix expected to be slower than average.
@Test
public void whenExplainInferred_returnsLinkedExplanation() {
    Label person = Label.of("person");
    Label siblings = Label.of("siblings");
    Label parentship = Label.of("parentship");
    String mainQuery = "match ($x, $y) isa cousins; limit 15; get;";
    genealogyKB.tx().graql().infer(true).parser().<GetQuery>parseQuery(mainQuery).forEach(answer -> {
        String cousin1 = answer.get("x").getId().getValue();
        String cousin2 = answer.get("y").getId().getValue();
        String specificQuery = "match " + "$x id " + cousin1 + ";" + "$y id " + cousin2 + ";" + "(cousin: $x, cousin: $y) isa cousins; limit 1;get;";
        GetQuery query = genealogyKB.tx().graql().infer(true).parse(specificQuery);
        ai.grakn.graql.admin.Answer specificAnswer = query.execute().stream().findFirst().orElse(new QueryAnswer());
        Set<ConceptId> originalEntityIds = specificAnswer.getExplanation().getAnswers().stream().flatMap(ans -> ans.concepts().stream()).map(ai.grakn.concept.Concept::getId).collect(Collectors.toSet());
        List<Answer> explanation = ExplanationBuilder.buildExplanation(specificAnswer);
        Set<ConceptId> entityIds = explanation.stream().flatMap(exp -> exp.conceptMap().values().stream()).filter(c -> c.baseType().equals("ENTITY")).map(Concept::id).collect(Collectors.toSet());
        // ensure we deal with the same entities
        assertEquals(originalEntityIds, entityIds);
        assertEquals(3, explanation.size());
        explanation.forEach(explanationAnswer -> {
            explanationAnswer.conceptMap().values().forEach(concept -> {
                Schema.BaseType baseType = Schema.BaseType.valueOf(concept.baseType());
                Label typeLabel = ((Thing) concept).type().label();
                switch(baseType) {
                    case ENTITY:
                        assertEquals(person, typeLabel);
                        break;
                    case RELATIONSHIP:
                        assertTrue(typeLabel.equals(siblings) || typeLabel.equals(parentship));
                        break;
                }
            });
        });
    });
}
Also used : GenealogyKB(ai.grakn.test.kbs.GenealogyKB) Set(java.util.Set) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Collectors(java.util.stream.Collectors) GetQuery(ai.grakn.graql.GetQuery) List(java.util.List) Label(ai.grakn.concept.Label) SampleKBContext(ai.grakn.test.rule.SampleKBContext) Schema(ai.grakn.util.Schema) ConceptId(ai.grakn.concept.ConceptId) QueryAnswer(ai.grakn.graql.internal.query.QueryAnswer) ClassRule(org.junit.ClassRule) Assert.assertEquals(org.junit.Assert.assertEquals) Schema(ai.grakn.util.Schema) Label(ai.grakn.concept.Label) ConceptId(ai.grakn.concept.ConceptId) QueryAnswer(ai.grakn.graql.internal.query.QueryAnswer) QueryAnswer(ai.grakn.graql.internal.query.QueryAnswer) GetQuery(ai.grakn.graql.GetQuery) Test(org.junit.Test)

Example 12 with QueryAnswer

use of ai.grakn.graql.internal.query.QueryAnswer in project grakn by graknlabs.

the class GrpcServerTest method whenExecutingAQueryRemotely_AResultIsReturned.

@Test
public void whenExecutingAQueryRemotely_AResultIsReturned() throws InterruptedException {
    Concept conceptX = mock(Concept.class, RETURNS_DEEP_STUBS);
    when(conceptX.getId()).thenReturn(ConceptId.of("V123"));
    when(conceptX.isRelationship()).thenReturn(true);
    when(conceptX.asRelationship().type().getLabel()).thenReturn(Label.of("L123"));
    Concept conceptY = mock(Concept.class, RETURNS_DEEP_STUBS);
    when(conceptY.getId()).thenReturn(ConceptId.of("V456"));
    when(conceptY.isAttribute()).thenReturn(true);
    when(conceptY.asAttribute().type().getLabel()).thenReturn(Label.of("L456"));
    ImmutableList<Answer> answers = ImmutableList.of(new QueryAnswer(ImmutableMap.of(Graql.var("x"), conceptX)), new QueryAnswer(ImmutableMap.of(Graql.var("y"), conceptY)));
    // TODO: reduce wtf
    when(query.results(any())).thenAnswer(params -> query.stream().map(params.<GrpcConverter>getArgument(0)::convert));
    when(query.stream()).thenAnswer(params -> answers.stream());
    try (TxGrpcCommunicator tx = TxGrpcCommunicator.create(stub)) {
        tx.send(openRequest(MYKS, GraknTxType.WRITE));
        tx.receive();
        tx.send(execQueryRequest(QUERY, null));
        IteratorId iterator = tx.receive().ok().getIteratorId();
        tx.send(nextRequest(iterator));
        TxResponse response1 = tx.receive().ok();
        GrpcConcept.Concept rpcX = GrpcConcept.Concept.newBuilder().setId(V123).setBaseType(BaseType.Relationship).build();
        GrpcGrakn.Answer.Builder answerX = GrpcGrakn.Answer.newBuilder().putAnswer("x", rpcX);
        QueryResult.Builder resultX = QueryResult.newBuilder().setAnswer(answerX);
        assertEquals(TxResponse.newBuilder().setQueryResult(resultX).build(), response1);
        tx.send(nextRequest(iterator));
        TxResponse response2 = tx.receive().ok();
        GrpcConcept.Concept rpcY = GrpcConcept.Concept.newBuilder().setId(V456).setBaseType(BaseType.Attribute).build();
        GrpcGrakn.Answer.Builder answerY = GrpcGrakn.Answer.newBuilder().putAnswer("y", rpcY);
        QueryResult.Builder resultY = QueryResult.newBuilder().setAnswer(answerY);
        assertEquals(TxResponse.newBuilder().setQueryResult(resultY).build(), response2);
        tx.send(nextRequest(iterator));
        TxResponse response3 = tx.receive().ok();
        TxResponse expected = doneResponse();
        assertEquals(expected, response3);
        tx.send(stopRequest(iterator));
    }
}
Also used : GrpcConcept(ai.grakn.rpc.generated.GrpcConcept) Concept(ai.grakn.concept.Concept) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Answer(ai.grakn.graql.admin.Answer) QueryAnswer(ai.grakn.graql.internal.query.QueryAnswer) QueryAnswer(ai.grakn.graql.internal.query.QueryAnswer) QueryResult(ai.grakn.rpc.generated.GrpcGrakn.QueryResult) IteratorId(ai.grakn.rpc.generated.GrpcIterator.IteratorId) GrpcConcept(ai.grakn.rpc.generated.GrpcConcept) TxGrpcCommunicator(ai.grakn.grpc.TxGrpcCommunicator) TxResponse(ai.grakn.rpc.generated.GrpcGrakn.TxResponse) Test(org.junit.Test)

Example 13 with QueryAnswer

use of ai.grakn.graql.internal.query.QueryAnswer in project grakn by graknlabs.

the class ReasonerQueryImpl method getRoleSubstitution.

public Answer getRoleSubstitution() {
    Map<Var, Concept> roleSub = new HashMap<>();
    getAtoms(RelationshipAtom.class).flatMap(RelationshipAtom::getRolePredicates).forEach(p -> {
        Concept concept = tx().getConcept(p.getPredicate());
        if (concept == null)
            throw GraqlQueryException.idNotFound(p.getPredicate());
        roleSub.put(p.getVarName(), concept);
    });
    return new QueryAnswer(roleSub);
}
Also used : Concept(ai.grakn.concept.Concept) QueryAnswer(ai.grakn.graql.internal.query.QueryAnswer) HashMap(java.util.HashMap) Var(ai.grakn.graql.Var)

Example 14 with QueryAnswer

use of ai.grakn.graql.internal.query.QueryAnswer in project grakn by graknlabs.

the class AtomicState method materialisedAnswer.

private Answer materialisedAnswer(Answer baseAnswer, InferenceRule rule, Unifier unifier) {
    Answer answer = baseAnswer;
    ReasonerAtomicQuery query = getQuery();
    QueryCache<ReasonerAtomicQuery> cache = getCache();
    ReasonerAtomicQuery subbedQuery = ReasonerQueries.atomic(query, answer);
    ReasonerAtomicQuery ruleHead = ReasonerQueries.atomic(rule.getHead(), answer);
    Set<Var> queryVars = query.getVarNames().size() < ruleHead.getVarNames().size() ? unifier.keySet() : ruleHead.getVarNames();
    boolean queryEquivalentToHead = subbedQuery.isEquivalent(ruleHead);
    // check if the specific answer to ruleHead already in cache/db
    Answer headAnswer = cache.getAnswer(ruleHead, answer).project(queryVars).unify(unifier);
    // if not and query different than rule head do the same with the query
    Answer queryAnswer = headAnswer.isEmpty() && queryEquivalentToHead ? cache.getAnswer(query, answer) : new QueryAnswer();
    // ensure no duplicates created - only materialise answer if it doesn't exist in the db
    if (headAnswer.isEmpty() && queryAnswer.isEmpty()) {
        Answer materialisedSub = ruleHead.materialise(answer).findFirst().orElse(null);
        if (!queryEquivalentToHead)
            cache.recordAnswer(ruleHead, materialisedSub);
        answer = materialisedSub.project(queryVars).unify(unifier);
    } else {
        answer = headAnswer.isEmpty() ? queryAnswer : headAnswer;
    }
    if (answer.isEmpty())
        return answer;
    return answer.merge(query.getSubstitution()).explain(new RuleExplanation(query, rule));
}
Also used : Answer(ai.grakn.graql.admin.Answer) QueryAnswer(ai.grakn.graql.internal.query.QueryAnswer) QueryAnswer(ai.grakn.graql.internal.query.QueryAnswer) Var(ai.grakn.graql.Var) RuleExplanation(ai.grakn.graql.internal.reasoner.explanation.RuleExplanation) ReasonerAtomicQuery(ai.grakn.graql.internal.reasoner.query.ReasonerAtomicQuery)

Example 15 with QueryAnswer

use of ai.grakn.graql.internal.query.QueryAnswer in project grakn by graknlabs.

the class GraqlPrinterTest method testEmptyResult.

@Test
public void testEmptyResult() {
    Printer printer = Printers.graql(true);
    Answer emptyResult = new QueryAnswer();
    assertEquals("{}", printer.graqlString(emptyResult));
}
Also used : Answer(ai.grakn.graql.admin.Answer) QueryAnswer(ai.grakn.graql.internal.query.QueryAnswer) QueryAnswer(ai.grakn.graql.internal.query.QueryAnswer) Printer(ai.grakn.graql.Printer) Test(org.junit.Test)

Aggregations

QueryAnswer (ai.grakn.graql.internal.query.QueryAnswer)29 Answer (ai.grakn.graql.admin.Answer)15 Concept (ai.grakn.concept.Concept)13 Test (org.junit.Test)13 ReasonerAtomicQuery (ai.grakn.graql.internal.reasoner.query.ReasonerAtomicQuery)9 Var (ai.grakn.graql.Var)8 GetQuery (ai.grakn.graql.GetQuery)6 MultiUnifier (ai.grakn.graql.admin.MultiUnifier)5 VarPatternAdmin (ai.grakn.graql.admin.VarPatternAdmin)5 ConceptId (ai.grakn.concept.ConceptId)4 Type (ai.grakn.concept.Type)4 Unifier (ai.grakn.graql.admin.Unifier)4 MultiUnifierImpl (ai.grakn.graql.internal.reasoner.MultiUnifierImpl)4 Atom (ai.grakn.graql.internal.reasoner.atom.Atom)4 IdPredicate (ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate)4 GraqlQueryException (ai.grakn.exception.GraqlQueryException)3 RelationshipAtom (ai.grakn.graql.internal.reasoner.atom.binary.RelationshipAtom)3 ImmutableMap (com.google.common.collect.ImmutableMap)3 List (java.util.List)3 Set (java.util.Set)3