Search in sources :

Example 76 with RelationshipType

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

the class GreedyTraversalPlan method inferRelationshipTypes.

private static void inferRelationshipTypes(EmbeddedGraknTx<?> tx, Set<Fragment> allFragments) {
    Map<Var, Type> labelVarTypeMap = getLabelVarTypeMap(tx, allFragments);
    if (labelVarTypeMap.isEmpty())
        return;
    Multimap<Var, Type> instanceVarTypeMap = getInstanceVarTypeMap(allFragments, labelVarTypeMap);
    Multimap<Var, Var> relationshipRolePlayerMap = getRelationshipRolePlayerMap(allFragments, instanceVarTypeMap);
    if (relationshipRolePlayerMap.isEmpty())
        return;
    // for each type, get all possible relationship type it could be in
    Multimap<Type, RelationshipType> relationshipMap = HashMultimap.create();
    labelVarTypeMap.values().stream().distinct().forEach(type -> addAllPossibleRelationships(relationshipMap, type));
    // inferred labels should be kept separately, even if they are already in allFragments set
    Map<Label, Var> inferredLabels = new HashMap<>();
    relationshipRolePlayerMap.asMap().forEach((relationshipVar, rolePlayerVars) -> {
        Set<Type> possibleRelationshipTypes = rolePlayerVars.stream().filter(instanceVarTypeMap::containsKey).map(rolePlayer -> getAllPossibleRelationshipTypes(instanceVarTypeMap.get(rolePlayer), relationshipMap)).reduce(Sets::intersection).orElse(Collections.emptySet());
        // TODO: if possibleRelationshipTypes here is empty, the query will not match any data
        if (possibleRelationshipTypes.size() == 1) {
            Type relationshipType = possibleRelationshipTypes.iterator().next();
            Label label = relationshipType.getLabel();
            // add label fragment if this label has not been inferred
            if (!inferredLabels.containsKey(label)) {
                Var labelVar = var();
                inferredLabels.put(label, labelVar);
                Fragment labelFragment = Fragments.label(LabelProperty.of(label), labelVar, ImmutableSet.of(label));
                allFragments.add(labelFragment);
            }
            // finally, add inferred isa fragments
            Var labelVar = inferredLabels.get(label);
            IsaProperty isaProperty = IsaProperty.of(labelVar.admin());
            EquivalentFragmentSet isaEquivalentFragmentSet = EquivalentFragmentSets.isa(isaProperty, relationshipVar, labelVar, relationshipType.isImplicit());
            allFragments.addAll(isaEquivalentFragmentSet.fragments());
        }
    });
}
Also used : HashMap(java.util.HashMap) Var(ai.grakn.graql.Var) IsaProperty(ai.grakn.graql.internal.pattern.property.IsaProperty) RelationshipType(ai.grakn.concept.RelationshipType) Label(ai.grakn.concept.Label) InSubFragment(ai.grakn.graql.internal.gremlin.fragment.InSubFragment) InIsaFragment(ai.grakn.graql.internal.gremlin.fragment.InIsaFragment) OutRolePlayerFragment(ai.grakn.graql.internal.gremlin.fragment.OutRolePlayerFragment) Fragment(ai.grakn.graql.internal.gremlin.fragment.Fragment) LabelFragment(ai.grakn.graql.internal.gremlin.fragment.LabelFragment) Type(ai.grakn.concept.Type) RelationshipType(ai.grakn.concept.RelationshipType)

Example 77 with RelationshipType

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

the class RelationshipTypePropertyTest method whenDeletingARelatedRole_TheDirectSuperTypeRelatedRolesAreUnchanged.

@Property
public void whenDeletingARelatedRole_TheDirectSuperTypeRelatedRolesAreUnchanged(@NonMeta RelationshipType subType, @FromTx Role role) {
    RelationshipType superType = subType.sup();
    Set<Role> previousHasRoles = superType.relates().collect(toSet());
    subType.deleteRelates(role);
    Set<Role> newHasRoles = superType.relates().collect(toSet());
    assertEquals(previousHasRoles, newHasRoles);
}
Also used : Role(ai.grakn.concept.Role) RelationshipType(ai.grakn.concept.RelationshipType) Property(com.pholser.junit.quickcheck.Property)

Example 78 with RelationshipType

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

the class RelationshipAtom method inferPossibleRelationConfigurations.

/**
 * @return a map of relationships and corresponding roles that could be played by this atom
 */
private Multimap<RelationshipType, Role> inferPossibleRelationConfigurations(Answer sub) {
    Set<Role> roles = getExplicitRoles().filter(r -> !Schema.MetaSchema.isMetaLabel(r.getLabel())).collect(toSet());
    Map<Var, Type> varTypeMap = getParentQuery().getVarTypeMap(sub);
    Set<Type> types = getRolePlayers().stream().filter(varTypeMap::containsKey).map(varTypeMap::get).collect(toSet());
    if (roles.isEmpty() && types.isEmpty()) {
        RelationshipType metaRelationType = tx().admin().getMetaRelationType();
        Multimap<RelationshipType, Role> compatibleTypes = HashMultimap.create();
        metaRelationType.subs().filter(rt -> !rt.equals(metaRelationType)).forEach(rt -> compatibleTypes.putAll(rt, rt.relates().collect(toSet())));
        return compatibleTypes;
    }
    // intersect relation types from roles and types
    Multimap<RelationshipType, Role> compatibleTypes;
    Multimap<RelationshipType, Role> compatibleTypesFromRoles = compatibleRelationTypesWithRoles(roles, new RoleConverter());
    Multimap<RelationshipType, Role> compatibleTypesFromTypes = compatibleRelationTypesWithRoles(types, new TypeConverter());
    if (roles.isEmpty()) {
        compatibleTypes = compatibleTypesFromTypes;
    } else // no types from roles -> roles correspond to mutually exclusive relations
    if (compatibleTypesFromRoles.isEmpty() || types.isEmpty()) {
        compatibleTypes = compatibleTypesFromRoles;
    } else {
        compatibleTypes = multimapIntersection(compatibleTypesFromTypes, compatibleTypesFromRoles);
    }
    return compatibleTypes;
}
Also used : Role(ai.grakn.concept.Role) 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) TypeConverter(ai.grakn.graql.internal.reasoner.utils.conversion.TypeConverter) Type(ai.grakn.concept.Type) EntityType(ai.grakn.concept.EntityType) RelationshipType(ai.grakn.concept.RelationshipType) UnifierType(ai.grakn.graql.internal.reasoner.UnifierType) Var(ai.grakn.graql.Var) RoleConverter(ai.grakn.graql.internal.reasoner.utils.conversion.RoleConverter) RelationshipType(ai.grakn.concept.RelationshipType)

Example 79 with RelationshipType

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

the class RelationshipAtom method inferRoles.

/**
 * attempt to infer role types of this relation and return a fresh relationship with inferred role types
 * @return either this if nothing/no roles can be inferred or fresh relation with inferred role types
 */
private RelationshipAtom inferRoles(Answer sub) {
    // return if all roles known and non-meta
    List<Role> explicitRoles = getExplicitRoles().collect(Collectors.toList());
    Map<Var, Type> varTypeMap = getParentQuery().getVarTypeMap(sub);
    boolean allRolesMeta = explicitRoles.stream().allMatch(role -> Schema.MetaSchema.isMetaLabel(role.getLabel()));
    boolean roleRecomputationViable = allRolesMeta && (!sub.isEmpty() || !Sets.intersection(varTypeMap.keySet(), getRolePlayers()).isEmpty());
    if (explicitRoles.size() == getRelationPlayers().size() && !roleRecomputationViable)
        return this;
    GraknTx graph = getParentQuery().tx();
    Role metaRole = graph.admin().getMetaRole();
    List<RelationPlayer> allocatedRelationPlayers = new ArrayList<>();
    RelationshipType relType = getSchemaConcept() != null ? getSchemaConcept().asRelationshipType() : null;
    // explicit role types from castings
    List<RelationPlayer> inferredRelationPlayers = new ArrayList<>();
    getRelationPlayers().forEach(rp -> {
        Var varName = rp.getRolePlayer().var();
        VarPatternAdmin rolePattern = rp.getRole().orElse(null);
        if (rolePattern != null) {
            Label roleLabel = rolePattern.getTypeLabel().orElse(null);
            // allocate if variable role or if label non meta
            if (roleLabel == null || !Schema.MetaSchema.isMetaLabel(roleLabel)) {
                inferredRelationPlayers.add(RelationPlayer.of(rolePattern, varName.admin()));
                allocatedRelationPlayers.add(rp);
            }
        }
    });
    // remaining roles
    // role types can repeat so no matter what has been allocated still the full spectrum of possibilities is present
    // TODO make restrictions based on cardinality constraints
    Set<Role> possibleRoles = relType != null ? relType.relates().collect(toSet()) : inferPossibleTypes(sub).stream().filter(Concept::isRelationshipType).map(Concept::asRelationshipType).flatMap(RelationshipType::relates).collect(toSet());
    // possible role types for each casting based on its type
    Map<RelationPlayer, Set<Role>> mappings = new HashMap<>();
    getRelationPlayers().stream().filter(rp -> !allocatedRelationPlayers.contains(rp)).forEach(rp -> {
        Var varName = rp.getRolePlayer().var();
        Type type = varTypeMap.get(varName);
        mappings.put(rp, top(type != null ? compatibleRoles(type, possibleRoles) : possibleRoles));
    });
    // allocate all unambiguous mappings
    mappings.entrySet().stream().filter(entry -> entry.getValue().size() == 1).forEach(entry -> {
        RelationPlayer rp = entry.getKey();
        Var varName = rp.getRolePlayer().var();
        Role role = Iterables.getOnlyElement(entry.getValue());
        VarPatternAdmin rolePattern = Graql.var().label(role.getLabel()).admin();
        inferredRelationPlayers.add(RelationPlayer.of(rolePattern, varName.admin()));
        allocatedRelationPlayers.add(rp);
    });
    // fill in unallocated roles with metarole
    getRelationPlayers().stream().filter(rp -> !allocatedRelationPlayers.contains(rp)).forEach(rp -> {
        Var varName = rp.getRolePlayer().var();
        VarPatternAdmin rolePattern = rp.getRole().orElse(null);
        rolePattern = rolePattern != null ? rolePattern.var().label(metaRole.getLabel()).admin() : Graql.var().label(metaRole.getLabel()).admin();
        inferredRelationPlayers.add(RelationPlayer.of(rolePattern, varName.admin()));
    });
    VarPattern relationPattern = relationPattern(getVarName(), inferredRelationPlayers);
    VarPatternAdmin newPattern = (isDirect() ? relationPattern.directIsa(getPredicateVariable()) : relationPattern.isa(getPredicateVariable())).admin();
    return create(newPattern, getPredicateVariable(), getTypeId(), getParentQuery());
}
Also used : Concept(ai.grakn.concept.Concept) SchemaConcept(ai.grakn.concept.SchemaConcept) 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) VarPatternAdmin(ai.grakn.graql.admin.VarPatternAdmin) HashMap(java.util.HashMap) Var(ai.grakn.graql.Var) ArrayList(java.util.ArrayList) RelationshipType(ai.grakn.concept.RelationshipType) Label(ai.grakn.concept.Label) Role(ai.grakn.concept.Role) GraknTx(ai.grakn.GraknTx) Type(ai.grakn.concept.Type) EntityType(ai.grakn.concept.EntityType) RelationshipType(ai.grakn.concept.RelationshipType) UnifierType(ai.grakn.graql.internal.reasoner.UnifierType) VarPattern(ai.grakn.graql.VarPattern) RelationPlayer(ai.grakn.graql.admin.RelationPlayer)

Example 80 with RelationshipType

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

the class CorenessTest method addSchemaAndEntities.

private void addSchemaAndEntities() throws InvalidKBException {
    try (GraknTx graph = session.open(GraknTxType.WRITE)) {
        EntityType entityType1 = graph.putEntityType(thing);
        EntityType entityType2 = graph.putEntityType(anotherThing);
        Role role1 = graph.putRole("role1");
        Role role2 = graph.putRole("role2");
        RelationshipType relationshipType1 = graph.putRelationshipType(related).relates(role1).relates(role2);
        Role role3 = graph.putRole("role3");
        Role role4 = graph.putRole("role4");
        RelationshipType relationshipType2 = graph.putRelationshipType(veryRelated).relates(role3).relates(role4);
        entityType1.plays(role1).plays(role2).plays(role3).plays(role4);
        entityType2.plays(role1).plays(role2).plays(role3).plays(role4);
        Entity entity1 = entityType1.addEntity();
        Entity entity2 = entityType1.addEntity();
        Entity entity3 = entityType2.addEntity();
        Entity entity4 = entityType2.addEntity();
        relationshipType1.addRelationship().addRolePlayer(role1, entity1).addRolePlayer(role2, entity2);
        relationshipType1.addRelationship().addRolePlayer(role1, entity2).addRolePlayer(role2, entity3);
        relationshipType1.addRelationship().addRolePlayer(role1, entity3).addRolePlayer(role2, entity4);
        relationshipType1.addRelationship().addRolePlayer(role1, entity4).addRolePlayer(role2, entity1);
        relationshipType2.addRelationship().addRolePlayer(role3, entity1).addRolePlayer(role4, entity3);
        relationshipType2.addRelationship().addRolePlayer(role3, entity2).addRolePlayer(role4, entity4);
        entityId1 = entity1.getId();
        entityId2 = entity2.getId();
        entityId3 = entity3.getId();
        entityId4 = entity4.getId();
        graph.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)

Aggregations

RelationshipType (ai.grakn.concept.RelationshipType)127 Role (ai.grakn.concept.Role)105 Test (org.junit.Test)91 EntityType (ai.grakn.concept.EntityType)80 Entity (ai.grakn.concept.Entity)52 GraknTx (ai.grakn.GraknTx)39 Relationship (ai.grakn.concept.Relationship)25 ConceptId (ai.grakn.concept.ConceptId)23 Label (ai.grakn.concept.Label)21 HashSet (java.util.HashSet)20 Set (java.util.Set)20 AttributeType (ai.grakn.concept.AttributeType)17 Thing (ai.grakn.concept.Thing)17 Attribute (ai.grakn.concept.Attribute)16 Schema (ai.grakn.util.Schema)12 Collectors (java.util.stream.Collectors)12 List (java.util.List)11 GraknSession (ai.grakn.GraknSession)10 GraknTxType (ai.grakn.GraknTxType)10 Concept (ai.grakn.concept.Concept)10