Search in sources :

Example 31 with GraknTx

use of ai.grakn.GraknTx in project grakn by graknlabs.

the class RelationshipAtom method getExplicitRoles.

private Stream<Role> getExplicitRoles() {
    ReasonerQueryImpl parent = (ReasonerQueryImpl) getParentQuery();
    GraknTx graph = parent.tx();
    return getRelationPlayers().stream().map(RelationPlayer::getRole).flatMap(CommonUtil::optionalToStream).map(VarPatternAdmin::getTypeLabel).flatMap(CommonUtil::optionalToStream).map(graph::<Role>getSchemaConcept);
}
Also used : GraknTx(ai.grakn.GraknTx) VarPatternAdmin(ai.grakn.graql.admin.VarPatternAdmin) RelationPlayer(ai.grakn.graql.admin.RelationPlayer) ReasonerQueryImpl(ai.grakn.graql.internal.reasoner.query.ReasonerQueryImpl)

Example 32 with GraknTx

use of ai.grakn.GraknTx in project grakn by graknlabs.

the class QueryOperationExecutor method create.

private static QueryOperationExecutor create(Collection<VarPatternAdmin> patterns, GraknTx graph, ExecutionType executionType) {
    ImmutableSet<VarAndProperty> properties = patterns.stream().flatMap(pattern -> VarAndProperty.fromPattern(pattern, executionType)).collect(toImmutableSet());
    /*
            We build several many-to-many relations, indicated by a `Multimap<X, Y>`. These are used to represent
            the dependencies between properties and variables.

            `propDependencies.containsEntry(prop, var)` indicates that the property `prop` cannot be inserted until
            the concept represented by the variable `var` is created.

            For example, the property `$x isa $y` depends on the existence of the concept represented by `$y`.
         */
    Multimap<VarAndProperty, Var> propDependencies = HashMultimap.create();
    for (VarAndProperty property : properties) {
        for (Var requiredVar : property.executor().requiredVars()) {
            propDependencies.put(property, requiredVar);
        }
    }
    /*
            `varDependencies.containsEntry(var, prop)` indicates that the concept represented by the variable `var`
            cannot be created until the property `prop` is inserted.

            For example, the concept represented by `$x` will not exist before the property `$x isa $y` is inserted.
         */
    Multimap<Var, VarAndProperty> varDependencies = HashMultimap.create();
    for (VarAndProperty property : properties) {
        for (Var producedVar : property.executor().producedVars()) {
            varDependencies.put(producedVar, property);
        }
    }
    /*
            Equivalent vars are variables that must represent the same concept as another var.

                 $X label movie, sub entity;
                 $Y label movie;
                 $z isa $Y;

            In this example, `$z isa $Y` must not be inserted before `$Y` is. However, `$Y` does not have enough
            information to insert on its own. It also needs a super type!

            We know `$Y` must represent the same concept as `$X`, because they both share the same label property.
            Therefore, we can share their dependencies, such that:

                varDependencies.containsEntry($X, prop) <=> varDependencies.containsEntry($Y, prop)

            Therefore:

                varDependencies.containsEntry($X, `$X sub entity`) => varDependencies.containsEntry($Y, `$X sub entity`)

            Now we know that `$Y` depends on `$X sub entity` as well as `$X label movie`, which is enough information to
            insert the type!
         */
    Partition<Var> equivalentVars = Partition.singletons(Collections.emptyList());
    equivalentProperties(properties).asMap().values().forEach(vars -> {
        // These vars must refer to the same concept, so share their dependencies
        Collection<VarAndProperty> producers = vars.stream().flatMap(var -> varDependencies.get(var).stream()).collect(toList());
        Var first = vars.iterator().next();
        vars.forEach(var -> {
            varDependencies.replaceValues(var, producers);
            equivalentVars.merge(first, var);
        });
    });
    /*
            Together, `propDependencies` and `varDependencies` can be composed into a single many-to-many relation:

                dependencies = propDependencies ∘ varDependencies

            By doing so, we map _directly_ between properties, skipping the vars. For example, if we previously had:

                propDependencies.containsEntry(`$x isa $y`, `$y`);         // `$x isa $y` depends on `$y`
                varDependencies.containsEntry(`$y`, `$y label movie`);     // `$y` depends on `$y label movie`

            Then it follows that:

                dependencies.containsEntry(`$x isa $y`, `$y label movie`); // `$x isa $y` depends on `$y label movie`

            The `dependencies` relation contains all the information to decide what order to execute the properties.
         */
    Multimap<VarAndProperty, VarAndProperty> dependencies = composeMultimaps(propDependencies, varDependencies);
    return new QueryOperationExecutor(graph, properties, equivalentVars, ImmutableMultimap.copyOf(dependencies));
}
Also used : PropertyExecutor(ai.grakn.graql.internal.pattern.property.PropertyExecutor) Concept(ai.grakn.concept.Concept) InsertQuery(ai.grakn.graql.InsertQuery) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) Answer(ai.grakn.graql.admin.Answer) Multimap(com.google.common.collect.Multimap) Multimaps(com.google.common.collect.Multimaps) HashMultimap(com.google.common.collect.HashMultimap) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) Partition(ai.grakn.graql.internal.util.Partition) GraknTx(ai.grakn.GraknTx) Map(java.util.Map) QueryAnswer(ai.grakn.graql.internal.query.QueryAnswer) ImmutableMultimap(com.google.common.collect.ImmutableMultimap) Nullable(javax.annotation.Nullable) CommonUtil.toImmutableSet(ai.grakn.util.CommonUtil.toImmutableSet) Patterns(ai.grakn.graql.internal.pattern.Patterns) VarPropertyInternal(ai.grakn.graql.internal.pattern.property.VarPropertyInternal) GraqlQueryException(ai.grakn.exception.GraqlQueryException) ImmutableSet(com.google.common.collect.ImmutableSet) Logger(org.slf4j.Logger) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) Set(java.util.Set) Maps(com.google.common.collect.Maps) Query(ai.grakn.graql.Query) Sets(com.google.common.collect.Sets) VarProperty(ai.grakn.graql.admin.VarProperty) Collectors.toList(java.util.stream.Collectors.toList) Stream(java.util.stream.Stream) Var(ai.grakn.graql.Var) AutoValue(com.google.auto.value.AutoValue) DefineQuery(ai.grakn.graql.DefineQuery) VarPatternAdmin(ai.grakn.graql.admin.VarPatternAdmin) Optional(java.util.Optional) Queue(java.util.Queue) ArrayDeque(java.util.ArrayDeque) Collections(java.util.Collections) Var(ai.grakn.graql.Var)

Example 33 with GraknTx

use of ai.grakn.GraknTx in project grakn by graknlabs.

the class StatisticsTest method addSchemaAndEntities.

private void addSchemaAndEntities() throws InvalidKBException {
    try (GraknTx tx = session.open(GraknTxType.WRITE)) {
        EntityType entityType1 = tx.putEntityType(thing);
        EntityType entityType2 = tx.putEntityType(anotherThing);
        Entity entity1 = entityType1.addEntity();
        Entity entity2 = entityType1.addEntity();
        Entity entity3 = entityType1.addEntity();
        Entity entity4 = entityType2.addEntity();
        entityId1 = entity1.getId();
        entityId2 = entity2.getId();
        entityId3 = entity3.getId();
        entityId4 = entity4.getId();
        Role relation1 = tx.putRole("relation1");
        Role relation2 = tx.putRole("relation2");
        entityType1.plays(relation1).plays(relation2);
        entityType2.plays(relation1).plays(relation2);
        RelationshipType related = tx.putRelationshipType("related").relates(relation1).relates(relation2);
        related.addRelationship().addRolePlayer(relation1, entity1).addRolePlayer(relation2, entity2);
        related.addRelationship().addRolePlayer(relation1, entity2).addRolePlayer(relation2, entity3);
        related.addRelationship().addRolePlayer(relation1, entity2).addRolePlayer(relation2, entity4);
        AttributeType<Double> attribute1 = tx.putAttributeType(resourceType1, AttributeType.DataType.DOUBLE);
        AttributeType<Long> attribute2 = tx.putAttributeType(resourceType2, AttributeType.DataType.LONG);
        AttributeType<Long> attribute3 = tx.putAttributeType(resourceType3, AttributeType.DataType.LONG);
        AttributeType<String> attribute4 = tx.putAttributeType(resourceType4, AttributeType.DataType.STRING);
        AttributeType<Long> attribute5 = tx.putAttributeType(resourceType5, AttributeType.DataType.LONG);
        AttributeType<Double> attribute6 = tx.putAttributeType(resourceType6, AttributeType.DataType.DOUBLE);
        AttributeType<Double> attribute7 = tx.putAttributeType(resourceType7, AttributeType.DataType.DOUBLE);
        entityType1.attribute(attribute1);
        entityType1.attribute(attribute2);
        entityType1.attribute(attribute3);
        entityType1.attribute(attribute4);
        entityType1.attribute(attribute5);
        entityType1.attribute(attribute6);
        entityType1.attribute(attribute7);
        entityType2.attribute(attribute1);
        entityType2.attribute(attribute2);
        entityType2.attribute(attribute3);
        entityType2.attribute(attribute4);
        entityType2.attribute(attribute5);
        entityType2.attribute(attribute6);
        entityType2.attribute(attribute7);
        tx.commit();
    }
}
Also used : EntityType(ai.grakn.concept.EntityType) Role(ai.grakn.concept.Role) GraknTx(ai.grakn.GraknTx) Entity(ai.grakn.concept.Entity) RelationshipType(ai.grakn.concept.RelationshipType)

Example 34 with GraknTx

use of ai.grakn.GraknTx in project grakn by graknlabs.

the class StatisticsTest method testStd.

@Test
public void testStd() throws Exception {
    Optional<Double> result;
    // resource-type has no instance
    addSchemaAndEntities();
    try (GraknTx graph = session.open(GraknTxType.READ)) {
        result = Graql.compute().std().of(resourceType1).in(Collections.emptyList()).withTx(graph).execute();
        assertFalse(result.isPresent());
        result = Graql.compute().std().of(resourceType1).withTx(graph).execute();
        assertFalse(result.isPresent());
        result = Graql.compute().withTx(graph).std().of(resourceType1).execute();
        assertFalse(result.isPresent());
        result = Graql.compute().std().withTx(graph).of(resourceType1).execute();
        assertFalse(result.isPresent());
        result = graph.graql().compute().std().of(resourceType2).execute();
        assertFalse(result.isPresent());
        result = graph.graql().compute().std().of(resourceType2, resourceType5).execute();
        assertFalse(result.isPresent());
        result = graph.graql().compute().std().of(resourceType2).withTx(graph).execute();
        assertFalse(result.isPresent());
        result = graph.graql().compute().withTx(graph).std().of(resourceType2).execute();
        assertFalse(result.isPresent());
    }
    // add resources, but resources are not connected to any entities
    addResourcesInstances();
    try (GraknTx graph = session.open(GraknTxType.READ)) {
        result = Graql.compute().std().of(resourceType1).withTx(graph).execute();
        assertFalse(result.isPresent());
        result = Graql.compute().std().of(resourceType1).in().withTx(graph).execute();
        assertFalse(result.isPresent());
        result = graph.graql().compute().std().of(resourceType2).in(thing, anotherThing).execute();
        assertFalse(result.isPresent());
        result = Graql.compute().std().of(resourceType2).withTx(graph).in(anotherThing).execute();
        assertFalse(result.isPresent());
    }
    // connect entity and resources
    addResourceRelations();
    try (GraknTx graph = session.open(GraknTxType.READ)) {
        result = Graql.compute().std().of(resourceType1).withTx(graph).execute();
        assertEquals(Math.sqrt(0.18 / 3), result.get(), delta);
        result = Graql.compute().std().of(resourceType2).withTx(graph).in(anotherThing).execute();
        assertEquals(Math.sqrt(0D), result.get(), delta);
        result = graph.graql().compute().std().of(resourceType1, resourceType6).execute();
        assertEquals(Math.sqrt(54.18 / 6), result.get(), delta);
        result = graph.graql().compute().std().of(resourceType2, resourceType5).in(thing, anotherThing).execute();
        assertEquals(Math.sqrt(110.0 / 6), result.get(), delta);
        result = graph.graql().compute().std().of(resourceType2).in(thing).execute();
        assertEquals(2.5, result.get(), delta);
    }
    List<Long> list = new ArrayList<>();
    long workerNumber = 3L;
    if (GraknTestUtil.usingTinker())
        workerNumber = 1;
    for (long i = 0L; i < workerNumber; i++) {
        list.add(i);
    }
    List<Double> numberList = list.parallelStream().map(i -> {
        try (GraknTx graph = session.open(GraknTxType.READ)) {
            return graph.graql().compute().std().of(resourceType2).in(thing).execute().get();
        }
    }).collect(Collectors.toList());
    numberList.forEach(value -> assertEquals(2.5D, value.doubleValue(), delta));
}
Also used : InvalidKBException(ai.grakn.exception.InvalidKBException) GraknTestUtil(ai.grakn.util.GraknTestUtil) Role(ai.grakn.concept.Role) Entity(ai.grakn.concept.Entity) Graql(ai.grakn.graql.Graql) Supplier(java.util.function.Supplier) EntityType(ai.grakn.concept.EntityType) ArrayList(java.util.ArrayList) Attribute(ai.grakn.concept.Attribute) SessionContext(ai.grakn.test.rule.SessionContext) Label(ai.grakn.concept.Label) AttributeType(ai.grakn.concept.AttributeType) RelationshipType(ai.grakn.concept.RelationshipType) GraknTx(ai.grakn.GraknTx) ConceptId(ai.grakn.concept.ConceptId) ClassRule(org.junit.ClassRule) Before(org.junit.Before) GraknTxType(ai.grakn.GraknTxType) GraqlQueryException(ai.grakn.exception.GraqlQueryException) GraknSession(ai.grakn.GraknSession) Set(java.util.Set) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) List(java.util.List) Assert.assertFalse(org.junit.Assert.assertFalse) Optional(java.util.Optional) Schema(ai.grakn.util.Schema) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) GraknTx(ai.grakn.GraknTx) ArrayList(java.util.ArrayList) Test(org.junit.Test)

Example 35 with GraknTx

use of ai.grakn.GraknTx in project grakn by graknlabs.

the class StatisticsTest method testSum.

@Test
public void testSum() throws Exception {
    Optional<Number> result;
    // resource-type has no instance
    addSchemaAndEntities();
    try (GraknTx graph = session.open(GraknTxType.READ)) {
        result = Graql.compute().sum().of(resourceType1).in(Collections.emptyList()).withTx(graph).execute();
        assertFalse(result.isPresent());
        result = Graql.compute().sum().of(resourceType1).withTx(graph).execute();
        assertFalse(result.isPresent());
        result = Graql.compute().withTx(graph).sum().of(resourceType1).execute();
        assertFalse(result.isPresent());
        result = Graql.compute().sum().withTx(graph).of(resourceType1).execute();
        assertFalse(result.isPresent());
        result = graph.graql().compute().sum().of(resourceType2).execute();
        assertFalse(result.isPresent());
        result = graph.graql().compute().sum().of(resourceType2, resourceType5).execute();
        assertFalse(result.isPresent());
        result = graph.graql().compute().sum().of(resourceType2).withTx(graph).execute();
        assertFalse(result.isPresent());
        result = graph.graql().compute().withTx(graph).sum().of(resourceType2).execute();
        assertFalse(result.isPresent());
    }
    // add resources, but resources are not connected to any entities
    addResourcesInstances();
    try (GraknTx graph = session.open(GraknTxType.READ)) {
        result = Graql.compute().sum().of(resourceType1).withTx(graph).execute();
        assertFalse(result.isPresent());
        result = Graql.compute().sum().of(resourceType1).in().withTx(graph).execute();
        assertFalse(result.isPresent());
        result = graph.graql().compute().sum().of(resourceType2).in(thing, anotherThing).execute();
        assertFalse(result.isPresent());
        result = Graql.compute().sum().of(resourceType2).withTx(graph).in(anotherThing).execute();
        assertFalse(result.isPresent());
    }
    // connect entity and resources
    addResourceRelations();
    try (GraknTx graph = session.open(GraknTxType.READ)) {
        result = Graql.compute().sum().of(resourceType1).withTx(graph).execute();
        assertEquals(4.5, result.get().doubleValue(), delta);
        result = Graql.compute().sum().of(resourceType2).in(thing).withTx(graph).execute();
        assertEquals(3L, result.get());
        result = graph.graql().compute().sum().of(resourceType1, resourceType6).execute();
        assertEquals(27.0, result.get().doubleValue(), delta);
        result = graph.graql().compute().sum().of(resourceType2, resourceType5).in(thing, anotherThing).execute();
        assertEquals(-18L, result.get());
        result = graph.graql().compute().sum().of(resourceType2, resourceType5).in(thing).execute();
        assertEquals(-11L, result.get());
    }
}
Also used : GraknTx(ai.grakn.GraknTx) Test(org.junit.Test)

Aggregations

GraknTx (ai.grakn.GraknTx)243 Test (org.junit.Test)189 EntityType (ai.grakn.concept.EntityType)54 GetQuery (ai.grakn.graql.GetQuery)52 Entity (ai.grakn.concept.Entity)51 QueryBuilder (ai.grakn.graql.QueryBuilder)49 Role (ai.grakn.concept.Role)48 RelationshipType (ai.grakn.concept.RelationshipType)46 Answer (ai.grakn.graql.admin.Answer)44 Set (java.util.Set)44 EmbeddedGraknTx (ai.grakn.kb.internal.EmbeddedGraknTx)33 Label (ai.grakn.concept.Label)28 Attribute (ai.grakn.concept.Attribute)27 Concept (ai.grakn.concept.Concept)27 HashSet (java.util.HashSet)26 GraknSession (ai.grakn.GraknSession)22 AttributeType (ai.grakn.concept.AttributeType)22 ConceptId (ai.grakn.concept.ConceptId)22 List (java.util.List)19 GraknTxType (ai.grakn.GraknTxType)17