Search in sources :

Example 41 with Label

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

the class ValidateGlobalRules method validateRelationTypesToRolesSchema.

/**
 * @param relationshipType the {@link RelationshipType} to be validated
 * @return Error messages if the role type sub structure does not match the {@link RelationshipType} sub structure
 */
static Set<String> validateRelationTypesToRolesSchema(RelationshipType relationshipType) {
    RelationshipTypeImpl superRelationType = (RelationshipTypeImpl) relationshipType.sup();
    if (Schema.MetaSchema.isMetaLabel(superRelationType.getLabel()) || superRelationType.isAbstract()) {
        // If super type is a meta type no validation needed
        return Collections.emptySet();
    }
    Set<String> errorMessages = new HashSet<>();
    Collection<Role> superRelates = superRelationType.relates().collect(Collectors.toSet());
    Collection<Role> relates = relationshipType.relates().collect(Collectors.toSet());
    Set<Label> relatesLabels = relates.stream().map(SchemaConcept::getLabel).collect(Collectors.toSet());
    // Check 1) Every role of relationTypes is the sub of a role which is in the relates of it's supers
    if (!superRelationType.isAbstract()) {
        Set<Label> allSuperRolesPlayed = new HashSet<>();
        superRelationType.sups().forEach(rel -> rel.relates().forEach(roleType -> allSuperRolesPlayed.add(roleType.getLabel())));
        for (Role relate : relates) {
            boolean validRoleTypeFound = SchemaConceptImpl.from(relate).sups().anyMatch(superRole -> allSuperRolesPlayed.contains(superRole.getLabel()));
            if (!validRoleTypeFound) {
                errorMessages.add(VALIDATION_RELATION_TYPES_ROLES_SCHEMA.getMessage(relate.getLabel(), relationshipType.getLabel(), "super", "super", superRelationType.getLabel()));
            }
        }
    }
    // Check 2) Every role of superRelationType has a sub role which is in the relates of relationTypes
    for (Role superRelate : superRelates) {
        boolean subRoleNotFoundInRelates = superRelate.subs().noneMatch(sub -> relatesLabels.contains(sub.getLabel()));
        if (subRoleNotFoundInRelates) {
            errorMessages.add(VALIDATION_RELATION_TYPES_ROLES_SCHEMA.getMessage(superRelate.getLabel(), superRelationType.getLabel(), "sub", "sub", relationshipType.getLabel()));
        }
    }
    return errorMessages;
}
Also used : Role(ai.grakn.concept.Role) RuleImpl(ai.grakn.kb.internal.concept.RuleImpl) Iterables(com.google.common.collect.Iterables) VALIDATION_CASTING(ai.grakn.util.ErrorMessage.VALIDATION_CASTING) VALIDATION_REQUIRED_RELATION(ai.grakn.util.ErrorMessage.VALIDATION_REQUIRED_RELATION) Role(ai.grakn.concept.Role) SchemaConcept(ai.grakn.concept.SchemaConcept) RelationshipTypeImpl(ai.grakn.kb.internal.concept.RelationshipTypeImpl) Type(ai.grakn.concept.Type) Rule(ai.grakn.concept.Rule) Attribute(ai.grakn.concept.Attribute) TypeImpl(ai.grakn.kb.internal.concept.TypeImpl) HashSet(java.util.HashSet) Label(ai.grakn.concept.Label) RelationshipType(ai.grakn.concept.RelationshipType) GraknTx(ai.grakn.GraknTx) CommonUtil(ai.grakn.util.CommonUtil) Map(java.util.Map) Relationship(ai.grakn.concept.Relationship) GraknTxOperationException(ai.grakn.exception.GraknTxOperationException) ErrorMessage(ai.grakn.util.ErrorMessage) VALIDATION_RELATION_TYPES_ROLES_SCHEMA(ai.grakn.util.ErrorMessage.VALIDATION_RELATION_TYPES_ROLES_SCHEMA) SchemaConceptImpl(ai.grakn.kb.internal.concept.SchemaConceptImpl) Conjunction(ai.grakn.graql.admin.Conjunction) VALIDATION_RELATION_TYPE(ai.grakn.util.ErrorMessage.VALIDATION_RELATION_TYPE) Collection(java.util.Collection) Set(java.util.Set) VALIDATION_ROLE_TYPE_MISSING_RELATION_TYPE(ai.grakn.util.ErrorMessage.VALIDATION_ROLE_TYPE_MISSING_RELATION_TYPE) Collectors(java.util.stream.Collectors) Atomic(ai.grakn.graql.admin.Atomic) ReasonerQuery(ai.grakn.graql.admin.ReasonerQuery) Stream(java.util.stream.Stream) Thing(ai.grakn.concept.Thing) VALIDATION_RELATION_CASTING_LOOP_FAIL(ai.grakn.util.ErrorMessage.VALIDATION_RELATION_CASTING_LOOP_FAIL) Casting(ai.grakn.kb.internal.structure.Casting) VarPatternAdmin(ai.grakn.graql.admin.VarPatternAdmin) Optional(java.util.Optional) Schema(ai.grakn.util.Schema) Pattern(ai.grakn.graql.Pattern) Collections(java.util.Collections) VALIDATION_NOT_EXACTLY_ONE_KEY(ai.grakn.util.ErrorMessage.VALIDATION_NOT_EXACTLY_ONE_KEY) RelationshipTypeImpl(ai.grakn.kb.internal.concept.RelationshipTypeImpl) Label(ai.grakn.concept.Label) HashSet(java.util.HashSet)

Example 42 with Label

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

the class TxCache method remove.

/**
 * @param concept The concept to no longer track
 */
@SuppressWarnings("SuspiciousMethodCalls")
public void remove(Concept concept) {
    modifiedThings.remove(concept);
    modifiedRoles.remove(concept);
    modifiedRelationshipTypes.remove(concept);
    modifiedRules.remove(concept);
    if (concept.isAttribute()) {
        newAttributes.remove(AttributeImpl.from(concept.asAttribute()).getIndex());
    }
    if (concept.isRelationship()) {
        newRelationships.remove(concept.asRelationship());
    }
    conceptCache.remove(concept.getId());
    if (concept.isSchemaConcept()) {
        Label label = concept.asSchemaConcept().getLabel();
        schemaConceptCache.remove(label);
        labelCache.remove(label);
    }
}
Also used : Label(ai.grakn.concept.Label)

Example 43 with Label

use of ai.grakn.concept.Label 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 44 with Label

use of ai.grakn.concept.Label 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 45 with Label

use of ai.grakn.concept.Label 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

Label (ai.grakn.concept.Label)87 Test (org.junit.Test)41 Role (ai.grakn.concept.Role)25 GraknTx (ai.grakn.GraknTx)22 ConceptId (ai.grakn.concept.ConceptId)21 Concept (ai.grakn.concept.Concept)20 Set (java.util.Set)20 RelationshipType (ai.grakn.concept.RelationshipType)19 SchemaConcept (ai.grakn.concept.SchemaConcept)19 AttributeType (ai.grakn.concept.AttributeType)17 EntityType (ai.grakn.concept.EntityType)17 Relationship (ai.grakn.concept.Relationship)14 HashSet (java.util.HashSet)14 Collectors (java.util.stream.Collectors)13 Type (ai.grakn.concept.Type)12 Stream (java.util.stream.Stream)12 VarPatternAdmin (ai.grakn.graql.admin.VarPatternAdmin)11 Schema (ai.grakn.util.Schema)11 Collection (java.util.Collection)11 Pattern (ai.grakn.graql.Pattern)10