Search in sources :

Example 81 with Role

use of ai.grakn.concept.Role in project grakn by graknlabs.

the class ConceptMethods method fromGrpc.

public static ConceptMethod<?> fromGrpc(GrpcConceptConverter converter, GrpcConcept.ConceptMethod conceptMethod) {
    Role[] roles;
    switch(conceptMethod.getConceptMethodCase()) {
        case GETVALUE:
            return GET_VALUE;
        case GETDATATYPEOFTYPE:
            return GET_DATA_TYPE_OF_TYPE;
        case GETDATATYPEOFATTRIBUTE:
            return GET_DATA_TYPE_OF_ATTRIBUTE;
        case GETLABEL:
            return GET_LABEL;
        case SETLABEL:
            return setLabel(convert(conceptMethod.getSetLabel()));
        case ISIMPLICIT:
            return IS_IMPLICIT;
        case ISINFERRED:
            return IS_INFERRED;
        case ISABSTRACT:
            return IS_ABSTRACT;
        case GETWHEN:
            return GET_WHEN;
        case GETTHEN:
            return GET_THEN;
        case GETREGEX:
            return GET_REGEX;
        case GETROLEPLAYERS:
            return GET_ROLE_PLAYERS;
        case GETATTRIBUTETYPES:
            return GET_ATTRIBUTE_TYPES;
        case SETATTRIBUTETYPE:
            return setAttributeType(converter.convert(conceptMethod.getSetAttributeType()).asAttributeType());
        case UNSETATTRIBUTETYPE:
            return unsetAttributeType(converter.convert(conceptMethod.getUnsetAttributeType()).asAttributeType());
        case GETKEYTYPES:
            return GET_KEY_TYPES;
        case GETDIRECTTYPE:
            return GET_DIRECT_TYPE;
        case GETDIRECTSUPERCONCEPT:
            return GET_DIRECT_SUPER;
        case SETDIRECTSUPERCONCEPT:
            GrpcConcept.Concept setDirectSuperConcept = conceptMethod.getSetDirectSuperConcept();
            SchemaConcept schemaConcept = converter.convert(setDirectSuperConcept).asSchemaConcept();
            return setDirectSuperConcept(schemaConcept);
        case UNSETROLEPLAYER:
            return removeRolePlayer(converter.convert(conceptMethod.getUnsetRolePlayer()));
        case DELETE:
            return DELETE;
        case GETATTRIBUTE:
            return getAttribute(convert(conceptMethod.getGetAttribute()));
        case GETOWNERS:
            return GET_OWNERS;
        case GETTYPESTHATPLAYROLE:
            return GET_TYPES_THAT_PLAY_ROLE;
        case GETROLESPLAYEDBYTYPE:
            return GET_ROLES_PLAYED_BY_TYPE;
        case GETINSTANCES:
            return GET_INSTANCES;
        case GETRELATEDROLES:
            return GET_RELATED_ROLES;
        case GETATTRIBUTES:
            return GET_ATTRIBUTES;
        case GETSUPERCONCEPTS:
            return GET_SUPER_CONCEPTS;
        case GETRELATIONSHIPTYPESTHATRELATEROLE:
            return GET_RELATIONSHIP_TYPES_THAT_RELATE_ROLE;
        case GETATTRIBUTESBYTYPES:
            GrpcConcept.Concepts getAttributeTypes = conceptMethod.getGetAttributesByTypes();
            AttributeType<?>[] attributeTypes = convert(converter, getAttributeTypes).toArray(AttributeType[]::new);
            return getAttributesByTypes(attributeTypes);
        case GETRELATIONSHIPS:
            return GET_RELATIONSHIPS;
        case GETSUBCONCEPTS:
            return GET_SUB_CONCEPTS;
        case GETRELATIONSHIPSBYROLES:
            roles = convert(converter, conceptMethod.getGetRelationshipsByRoles()).toArray(Role[]::new);
            return getRelationshipsByRoles(roles);
        case GETROLESPLAYEDBYTHING:
            return GET_ROLES_PLAYED_BY_THING;
        case GETKEYS:
            return GET_KEYS;
        case GETKEYSBYTYPES:
            GrpcConcept.Concepts getKeyTypes = conceptMethod.getGetAttributesByTypes();
            AttributeType<?>[] keyTypes = convert(converter, getKeyTypes).toArray(AttributeType[]::new);
            return getKeysByTypes(keyTypes);
        case GETROLEPLAYERSBYROLES:
            roles = convert(converter, conceptMethod.getGetRolePlayersByRoles()).toArray(Role[]::new);
            return getRolePlayersByRoles(roles);
        case SETKEYTYPE:
            return setKeyType(converter.convert(conceptMethod.getSetKeyType()).asAttributeType());
        case UNSETKEYTYPE:
            return unsetKeyType(converter.convert(conceptMethod.getUnsetKeyType()).asAttributeType());
        case SETABSTRACT:
            return setAbstract(conceptMethod.getSetAbstract());
        case SETROLEPLAYEDBYTYPE:
            return setRolePlayedByType(converter.convert(conceptMethod.getSetRolePlayedByType()).asRole());
        case UNSETROLEPLAYEDBYTYPE:
            return unsetRolePlayedByType(converter.convert(conceptMethod.getUnsetRolePlayedByType()).asRole());
        case ADDENTITY:
            return ADD_ENTITY;
        case SETRELATEDROLE:
            return setRelatedRole(converter.convert(conceptMethod.getSetRelatedRole()).asRole());
        case UNSETRELATEDROLE:
            return unsetRelatedRole(converter.convert(conceptMethod.getUnsetRelatedRole()).asRole());
        case PUTATTRIBUTE:
            return putAttribute(convert(conceptMethod.getPutAttribute()));
        case SETREGEX:
            return setRegex(convert(conceptMethod.getSetRegex()));
        case SETATTRIBUTE:
            return setAttribute(converter.convert(conceptMethod.getSetAttribute()).asAttribute());
        case UNSETATTRIBUTE:
            return unsetAttribute(converter.convert(conceptMethod.getUnsetAttribute()).asAttribute());
        case ADDRELATIONSHIP:
            return ADD_RELATIONSHIP;
        case SETROLEPLAYER:
            return setRolePlayer(converter.convert(conceptMethod.getSetRolePlayer()));
        default:
        case CONCEPTMETHOD_NOT_SET:
            throw new IllegalArgumentException("Unrecognised " + conceptMethod);
    }
}
Also used : Role(ai.grakn.concept.Role) GrpcConcept(ai.grakn.rpc.generated.GrpcConcept) AttributeType(ai.grakn.concept.AttributeType) SchemaConcept(ai.grakn.concept.SchemaConcept)

Example 82 with Role

use of ai.grakn.concept.Role in project grakn by graknlabs.

the class RelationshipAtom method getRelationPlayerMappings.

/**
 * @param parentAtom reference atom defining the mapping
 * @param matchType type of match to be performed
 * @return set of possible COMPLETE mappings between this (child) and parent relation players
 */
private Set<List<Pair<RelationPlayer, RelationPlayer>>> getRelationPlayerMappings(RelationshipAtom parentAtom, UnifierComparison matchType) {
    Multimap<Role, RelationPlayer> childRoleRPMap = this.getRoleRelationPlayerMap();
    Map<Var, Type> childVarTypeMap = this.getParentQuery().getVarTypeMap();
    Map<Var, Type> parentVarTypeMap = parentAtom.getParentQuery().getVarTypeMap();
    // establish compatible castings for each parent casting
    List<Set<Pair<RelationPlayer, RelationPlayer>>> compatibleMappingsPerParentRP = new ArrayList<>();
    ReasonerQueryImpl childQuery = (ReasonerQueryImpl) getParentQuery();
    Set<Role> childRoles = childRoleRPMap.keySet();
    parentAtom.getRelationPlayers().stream().filter(prp -> prp.getRole().isPresent()).forEach(prp -> {
        VarPatternAdmin parentRolePattern = prp.getRole().orElse(null);
        if (parentRolePattern == null) {
            throw GraqlQueryException.rolePatternAbsent(this);
        }
        Label parentRoleLabel = parentRolePattern.getTypeLabel().orElse(null);
        if (parentRoleLabel != null) {
            Var parentRolePlayer = prp.getRolePlayer().var();
            Type parentType = parentVarTypeMap.get(parentRolePlayer);
            Set<Role> compatibleRoles = compatibleRoles(tx().getSchemaConcept(parentRoleLabel), parentType, childRoles);
            List<RelationPlayer> compatibleRelationPlayers = new ArrayList<>();
            compatibleRoles.stream().filter(childRoleRPMap::containsKey).forEach(role -> childRoleRPMap.get(role).stream().filter(crp -> {
                Var childVar = crp.getRolePlayer().var();
                Type childType = childVarTypeMap.get(childVar);
                return matchType.typePlayability(childQuery, childVar, parentType) && matchType.typeCompatibility(parentType, childType);
            }).filter(crp -> {
                IdPredicate parentId = parentAtom.getIdPredicate(prp.getRolePlayer().var());
                IdPredicate childId = this.getIdPredicate(crp.getRolePlayer().var());
                return matchType.atomicCompatibility(parentId, childId);
            }).filter(crp -> {
                ValuePredicate parentVP = parentAtom.getPredicate(prp.getRolePlayer().var(), ValuePredicate.class);
                ValuePredicate childVP = this.getPredicate(crp.getRolePlayer().var(), ValuePredicate.class);
                return matchType.atomicCompatibility(parentVP, childVP);
            }).forEach(compatibleRelationPlayers::add));
            if (!compatibleRelationPlayers.isEmpty()) {
                compatibleMappingsPerParentRP.add(compatibleRelationPlayers.stream().map(crp -> new Pair<>(crp, prp)).collect(Collectors.toSet()));
            }
        } else {
            compatibleMappingsPerParentRP.add(getRelationPlayers().stream().map(crp -> new Pair<>(crp, prp)).collect(Collectors.toSet()));
        }
    });
    return Sets.cartesianProduct(compatibleMappingsPerParentRP).stream().filter(list -> !list.isEmpty()).filter(list -> {
        List<RelationPlayer> listChildRps = list.stream().map(Pair::getKey).collect(Collectors.toList());
        // NB: this preserves cardinality instead of removing all occuring instances which is what we want
        return ReasonerUtils.subtract(listChildRps, this.getRelationPlayers()).isEmpty();
    }).filter(list -> {
        List<RelationPlayer> listParentRps = list.stream().map(Pair::getValue).collect(Collectors.toList());
        return listParentRps.containsAll(parentAtom.getRelationPlayers());
    }).collect(toSet());
}
Also used : ArrayListMultimap(com.google.common.collect.ArrayListMultimap) Pair(ai.grakn.graql.internal.reasoner.utils.Pair) Atom(ai.grakn.graql.internal.reasoner.atom.Atom) VarPattern(ai.grakn.graql.VarPattern) RelationshipProperty(ai.grakn.graql.internal.pattern.property.RelationshipProperty) RelationshipTypeImpl(ai.grakn.kb.internal.concept.RelationshipTypeImpl) Graql(ai.grakn.graql.Graql) ReasonerUtils.top(ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.top) Type(ai.grakn.concept.Type) MultiUnifierImpl(ai.grakn.graql.internal.reasoner.MultiUnifierImpl) EntityType(ai.grakn.concept.EntityType) HashMultimap(com.google.common.collect.HashMultimap) Label(ai.grakn.concept.Label) RelationshipType(ai.grakn.concept.RelationshipType) GraknTx(ai.grakn.GraknTx) Map(java.util.Map) ReasonerUtils.supers(ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.supers) RoleConverter(ai.grakn.graql.internal.reasoner.utils.conversion.RoleConverter) ConceptId(ai.grakn.concept.ConceptId) Collectors.toSet(java.util.stream.Collectors.toSet) ImmutableSet(com.google.common.collect.ImmutableSet) ValuePredicate(ai.grakn.graql.internal.reasoner.atom.predicate.ValuePredicate) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) Set(java.util.Set) IdPredicate(ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) Objects(java.util.Objects) Atomic(ai.grakn.graql.admin.Atomic) List(java.util.List) Stream(java.util.stream.Stream) Var(ai.grakn.graql.Var) AutoValue(com.google.auto.value.AutoValue) ReasonerUtils.compatibleRoles(ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.compatibleRoles) UnifierType(ai.grakn.graql.internal.reasoner.UnifierType) Iterables(com.google.common.collect.Iterables) ReasonerQueryImpl(ai.grakn.graql.internal.reasoner.query.ReasonerQueryImpl) Role(ai.grakn.concept.Role) Concept(ai.grakn.concept.Concept) SchemaConcept(ai.grakn.concept.SchemaConcept) ReasonerUtils.compatibleRelationTypesWithRoles(ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.compatibleRelationTypesWithRoles) HashMap(java.util.HashMap) Answer(ai.grakn.graql.admin.Answer) Multimap(com.google.common.collect.Multimap) Rule(ai.grakn.concept.Rule) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ReasonerUtils.multimapIntersection(ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.multimapIntersection) ImmutableList(com.google.common.collect.ImmutableList) CommonUtil(ai.grakn.util.CommonUtil) Predicate(ai.grakn.graql.internal.reasoner.atom.predicate.Predicate) Relationship(ai.grakn.concept.Relationship) QueryAnswer(ai.grakn.graql.internal.query.QueryAnswer) ImmutableMultimap(com.google.common.collect.ImmutableMultimap) TypeConverter(ai.grakn.graql.internal.reasoner.utils.conversion.TypeConverter) Nullable(javax.annotation.Nullable) ErrorMessage(ai.grakn.util.ErrorMessage) GraqlQueryException(ai.grakn.exception.GraqlQueryException) Iterator(java.util.Iterator) Memoized(com.google.auto.value.extension.memoized.Memoized) MultiUnifier(ai.grakn.graql.admin.MultiUnifier) UnifierImpl(ai.grakn.graql.internal.reasoner.UnifierImpl) ReasonerUtils(ai.grakn.graql.internal.reasoner.utils.ReasonerUtils) VarProperty(ai.grakn.graql.admin.VarProperty) ReasonerQuery(ai.grakn.graql.admin.ReasonerQuery) IsaProperty(ai.grakn.graql.internal.pattern.property.IsaProperty) UnifierComparison(ai.grakn.graql.admin.UnifierComparison) RelationPlayer(ai.grakn.graql.admin.RelationPlayer) VarPatternAdmin(ai.grakn.graql.admin.VarPatternAdmin) Schema(ai.grakn.util.Schema) Pattern(ai.grakn.graql.Pattern) Comparator(java.util.Comparator) Unifier(ai.grakn.graql.admin.Unifier) Collectors.toSet(java.util.stream.Collectors.toSet) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) HashSet(java.util.HashSet) IdPredicate(ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate) VarPatternAdmin(ai.grakn.graql.admin.VarPatternAdmin) Var(ai.grakn.graql.Var) ArrayList(java.util.ArrayList) Label(ai.grakn.concept.Label) Role(ai.grakn.concept.Role) Type(ai.grakn.concept.Type) EntityType(ai.grakn.concept.EntityType) RelationshipType(ai.grakn.concept.RelationshipType) UnifierType(ai.grakn.graql.internal.reasoner.UnifierType) ValuePredicate(ai.grakn.graql.internal.reasoner.atom.predicate.ValuePredicate) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) RelationPlayer(ai.grakn.graql.admin.RelationPlayer) ReasonerQueryImpl(ai.grakn.graql.internal.reasoner.query.ReasonerQueryImpl) Pair(ai.grakn.graql.internal.reasoner.utils.Pair)

Example 83 with Role

use of ai.grakn.concept.Role in project grakn by graknlabs.

the class InsertQueryTest method whenInsertingMultipleRolePlayers_BothRolePlayersAreAdded.

@Test
public void whenInsertingMultipleRolePlayers_BothRolePlayersAreAdded() {
    List<Answer> results = qb.match(var("g").has("title", "Godfather"), var("m").has("title", "The Muppets")).insert(var("c").isa("cluster").has("name", "2"), var("r").rel("cluster-of-production", "c").rel("production-with-cluster", "g").rel("production-with-cluster", "m").isa("has-cluster")).execute();
    Thing cluster = results.get(0).get("c").asThing();
    Thing godfather = results.get(0).get("g").asThing();
    Thing muppets = results.get(0).get("m").asThing();
    Relationship relationship = results.get(0).get("r").asRelationship();
    Role clusterOfProduction = movieKB.tx().getRole("cluster-of-production");
    Role productionWithCluster = movieKB.tx().getRole("production-with-cluster");
    assertEquals(relationship.rolePlayers().collect(toSet()), ImmutableSet.of(cluster, godfather, muppets));
    assertEquals(relationship.rolePlayers(clusterOfProduction).collect(toSet()), ImmutableSet.of(cluster));
    assertEquals(relationship.rolePlayers(productionWithCluster).collect(toSet()), ImmutableSet.of(godfather, muppets));
}
Also used : Role(ai.grakn.concept.Role) Answer(ai.grakn.graql.admin.Answer) Relationship(ai.grakn.concept.Relationship) Thing(ai.grakn.concept.Thing) Test(org.junit.Test)

Example 84 with Role

use of ai.grakn.concept.Role in project grakn by graknlabs.

the class MatchTest method testGraqlPlaysSemanticsMatchGraphAPI.

@Test
public void testGraqlPlaysSemanticsMatchGraphAPI() {
    GraknTx tx = emptyKB.tx();
    QueryBuilder qb = tx.graql();
    Label a = Label.of("a");
    Label b = Label.of("b");
    Label c = Label.of("c");
    Label d = Label.of("d");
    Label e = Label.of("e");
    Label f = Label.of("f");
    qb.define(Graql.label(c).sub(Graql.label(b).sub(Graql.label(a).sub("entity"))), Graql.label(f).sub(Graql.label(e).sub(Graql.label(d).sub("role"))), Graql.label(b).plays(Graql.label(e))).execute();
    Stream.of(a, b, c, d, e, f).forEach(type -> {
        Set<Concept> graqlPlays = qb.match(Graql.label(type).plays(x)).get(x).collect(Collectors.toSet());
        Collection<Role> graphAPIPlays;
        SchemaConcept schemaConcept = tx.getSchemaConcept(type);
        if (schemaConcept.isType()) {
            graphAPIPlays = schemaConcept.asType().plays().collect(toSet());
        } else {
            graphAPIPlays = Collections.EMPTY_SET;
        }
        assertEquals(graqlPlays, graphAPIPlays);
    });
    Stream.of(d, e, f).forEach(type -> {
        Set<Concept> graqlPlayedBy = qb.match(x.plays(Graql.label(type))).get(x).collect(toSet());
        Collection<Type> graphAPIPlayedBy = tx.<Role>getSchemaConcept(type).playedByTypes().collect(toSet());
        assertEquals(graqlPlayedBy, graphAPIPlayedBy);
    });
}
Also used : Concept(ai.grakn.concept.Concept) MatchableConcept(ai.grakn.matcher.MatchableConcept) SchemaConcept(ai.grakn.concept.SchemaConcept) Role(ai.grakn.concept.Role) GraknTx(ai.grakn.GraknTx) EntityType(ai.grakn.concept.EntityType) RelationshipType(ai.grakn.concept.RelationshipType) AttributeType(ai.grakn.concept.AttributeType) GraknMatchers.hasType(ai.grakn.matcher.GraknMatchers.hasType) Type(ai.grakn.concept.Type) Label(ai.grakn.concept.Label) SchemaConcept(ai.grakn.concept.SchemaConcept) QueryBuilder(ai.grakn.graql.QueryBuilder) Test(org.junit.Test)

Example 85 with Role

use of ai.grakn.concept.Role in project grakn by graknlabs.

the class MatchTest method whenQueryingForHas_AllowReferringToTheImplicitRelation.

@Test
public void whenQueryingForHas_AllowReferringToTheImplicitRelation() {
    Label title = Label.of("title");
    RelationshipType hasTitle = movieKB.tx().getType(HAS.getLabel(title));
    Role titleOwner = movieKB.tx().getSchemaConcept(HAS_OWNER.getLabel(title));
    Role titleValue = movieKB.tx().getSchemaConcept(HAS_VALUE.getLabel(title));
    Relationship implicitRelation = hasTitle.instances().iterator().next();
    ConceptId owner = implicitRelation.rolePlayers(titleOwner).iterator().next().getId();
    ConceptId value = implicitRelation.rolePlayers(titleValue).iterator().next().getId();
    Match query = qb.match(x.id(owner).has(title, y.id(value), r));
    assertThat(query, variable(r, contains(MatchableConcept.of(implicitRelation))));
}
Also used : Role(ai.grakn.concept.Role) Relationship(ai.grakn.concept.Relationship) Label(ai.grakn.concept.Label) RelationshipType(ai.grakn.concept.RelationshipType) ConceptId(ai.grakn.concept.ConceptId) Match(ai.grakn.graql.Match) Test(org.junit.Test)

Aggregations

Role (ai.grakn.concept.Role)189 Test (org.junit.Test)124 RelationshipType (ai.grakn.concept.RelationshipType)114 EntityType (ai.grakn.concept.EntityType)92 Entity (ai.grakn.concept.Entity)55 GraknTx (ai.grakn.GraknTx)48 Relationship (ai.grakn.concept.Relationship)37 Set (java.util.Set)36 ConceptId (ai.grakn.concept.ConceptId)33 Label (ai.grakn.concept.Label)33 Thing (ai.grakn.concept.Thing)32 HashSet (java.util.HashSet)31 Var (ai.grakn.graql.Var)25 AttributeType (ai.grakn.concept.AttributeType)21 Concept (ai.grakn.concept.Concept)20 Schema (ai.grakn.util.Schema)17 Collectors (java.util.stream.Collectors)17 Attribute (ai.grakn.concept.Attribute)16 SchemaConcept (ai.grakn.concept.SchemaConcept)16 Type (ai.grakn.concept.Type)16