Search in sources :

Example 71 with Var

use of ai.grakn.graql.Var in project grakn by graknlabs.

the class RelationshipAtom method getMultiUnifier.

@Override
public MultiUnifier getMultiUnifier(Atom pAtom, UnifierComparison unifierType) {
    Unifier baseUnifier = super.getUnifier(pAtom);
    Set<Unifier> unifiers = new HashSet<>();
    if (pAtom.isRelation()) {
        // This is safe due to the check above
        assert (pAtom instanceof RelationshipAtom);
        RelationshipAtom parentAtom = (RelationshipAtom) pAtom;
        // this is important for cases like unifying ($r1: $x, $r2: $y) with itself
        if (this.equals(parentAtom) && this.getPartialSubstitutions().collect(toSet()).equals(parentAtom.getPartialSubstitutions().collect(toSet())) && this.getTypeConstraints().collect(toSet()).equals(parentAtom.getTypeConstraints().collect(toSet()))) {
            return new MultiUnifierImpl();
        }
        boolean unifyRoleVariables = parentAtom.getRelationPlayers().stream().map(RelationPlayer::getRole).flatMap(CommonUtil::optionalToStream).anyMatch(rp -> rp.var().isUserDefinedName());
        getRelationPlayerMappings(parentAtom, unifierType).forEach(mappingList -> {
            Multimap<Var, Var> varMappings = HashMultimap.create();
            mappingList.forEach(rpm -> {
                // add role player mapping
                varMappings.put(rpm.getKey().getRolePlayer().var(), rpm.getValue().getRolePlayer().var());
                // add role var mapping if needed
                VarPattern childRolePattern = rpm.getKey().getRole().orElse(null);
                VarPattern parentRolePattern = rpm.getValue().getRole().orElse(null);
                if (parentRolePattern != null && childRolePattern != null && unifyRoleVariables) {
                    varMappings.put(childRolePattern.admin().var(), parentRolePattern.admin().var());
                }
            });
            unifiers.add(baseUnifier.merge(new UnifierImpl(varMappings)));
        });
    } else {
        unifiers.add(baseUnifier);
    }
    return new MultiUnifierImpl(unifiers);
}
Also used : Var(ai.grakn.graql.Var) VarPattern(ai.grakn.graql.VarPattern) MultiUnifierImpl(ai.grakn.graql.internal.reasoner.MultiUnifierImpl) UnifierImpl(ai.grakn.graql.internal.reasoner.UnifierImpl) MultiUnifierImpl(ai.grakn.graql.internal.reasoner.MultiUnifierImpl) RelationPlayer(ai.grakn.graql.admin.RelationPlayer) MultiUnifier(ai.grakn.graql.admin.MultiUnifier) Unifier(ai.grakn.graql.admin.Unifier) HashSet(java.util.HashSet)

Example 72 with Var

use of ai.grakn.graql.Var 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 73 with Var

use of ai.grakn.graql.Var in project grakn by graknlabs.

the class ReasonerQueryImpl method getSubstitution.

/**
 * @return substitution obtained from all id predicates (including internal) in the query
 */
public Answer getSubstitution() {
    if (substitution == null) {
        Set<Var> varNames = getVarNames();
        Set<IdPredicate> predicates = getAtoms(IsaAtomBase.class).map(IsaAtomBase::getTypePredicate).filter(Objects::nonNull).filter(p -> varNames.contains(p.getVarName())).collect(Collectors.toSet());
        getAtoms(IdPredicate.class).forEach(predicates::add);
        HashMap<Var, Concept> answerMap = new HashMap<>();
        predicates.forEach(p -> {
            Concept concept = tx().getConcept(p.getPredicate());
            if (concept == null)
                throw GraqlQueryException.idNotFound(p.getPredicate());
            answerMap.put(p.getVarName(), concept);
        });
        substitution = new QueryAnswer(answerMap);
    }
    return substitution;
}
Also used : PatternAdmin(ai.grakn.graql.admin.PatternAdmin) Pair(ai.grakn.graql.internal.reasoner.utils.Pair) Atom(ai.grakn.graql.internal.reasoner.atom.Atom) LoggerFactory(org.slf4j.LoggerFactory) Type(ai.grakn.concept.Type) ResolutionIterator(ai.grakn.graql.internal.reasoner.ResolutionIterator) QueryStateBase(ai.grakn.graql.internal.reasoner.state.QueryStateBase) MultiUnifierImpl(ai.grakn.graql.internal.reasoner.MultiUnifierImpl) ResolutionState(ai.grakn.graql.internal.reasoner.state.ResolutionState) QueryAnswerStream.join(ai.grakn.graql.internal.reasoner.query.QueryAnswerStream.join) Map(java.util.Map) IsaAtom(ai.grakn.graql.internal.reasoner.atom.binary.IsaAtom) RuleUtils(ai.grakn.graql.internal.reasoner.rule.RuleUtils) ConceptId(ai.grakn.concept.ConceptId) Graql.var(ai.grakn.graql.Graql.var) ImmutableSet(com.google.common.collect.ImmutableSet) NeqPredicate(ai.grakn.graql.internal.reasoner.atom.predicate.NeqPredicate) Conjunction(ai.grakn.graql.admin.Conjunction) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) ConjunctiveState(ai.grakn.graql.internal.reasoner.state.ConjunctiveState) QueryAnswerStream.joinWithInverse(ai.grakn.graql.internal.reasoner.query.QueryAnswerStream.joinWithInverse) Set(java.util.Set) IdPredicate(ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate) Collectors(java.util.stream.Collectors) LazyQueryCache(ai.grakn.graql.internal.reasoner.cache.LazyQueryCache) Sets(com.google.common.collect.Sets) Objects(java.util.Objects) Atomic(ai.grakn.graql.admin.Atomic) List(java.util.List) Cache(ai.grakn.graql.internal.reasoner.cache.Cache) Stream(java.util.stream.Stream) InferenceRule(ai.grakn.graql.internal.reasoner.rule.InferenceRule) Var(ai.grakn.graql.Var) AtomicBase(ai.grakn.graql.internal.reasoner.atom.AtomicBase) UnifierType(ai.grakn.graql.internal.reasoner.UnifierType) Concept(ai.grakn.concept.Concept) HashMap(java.util.HashMap) Answer(ai.grakn.graql.admin.Answer) CumulativeState(ai.grakn.graql.internal.reasoner.state.CumulativeState) JoinExplanation(ai.grakn.graql.internal.reasoner.explanation.JoinExplanation) Iterators(com.google.common.collect.Iterators) QueryAnswerStream.nonEqualsFilter(ai.grakn.graql.internal.reasoner.query.QueryAnswerStream.nonEqualsFilter) HashSet(java.util.HashSet) Lists(com.google.common.collect.Lists) QueryAnswer(ai.grakn.graql.internal.query.QueryAnswer) LinkedList(java.util.LinkedList) RelationshipAtom(ai.grakn.graql.internal.reasoner.atom.binary.RelationshipAtom) Nullable(javax.annotation.Nullable) LinkedHashSet(java.util.LinkedHashSet) QueryCache(ai.grakn.graql.internal.reasoner.cache.QueryCache) Patterns(ai.grakn.graql.internal.pattern.Patterns) GraqlQueryException(ai.grakn.exception.GraqlQueryException) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) AnswerState(ai.grakn.graql.internal.reasoner.state.AnswerState) MultiUnifier(ai.grakn.graql.admin.MultiUnifier) IsaAtomBase(ai.grakn.graql.internal.reasoner.atom.binary.IsaAtomBase) GetQuery(ai.grakn.graql.GetQuery) AtomicFactory(ai.grakn.graql.internal.reasoner.atom.AtomicFactory) ReasonerQuery(ai.grakn.graql.admin.ReasonerQuery) UnifierComparison(ai.grakn.graql.admin.UnifierComparison) EmbeddedGraknTx(ai.grakn.kb.internal.EmbeddedGraknTx) VarPatternAdmin(ai.grakn.graql.admin.VarPatternAdmin) Schema(ai.grakn.util.Schema) Unifier(ai.grakn.graql.admin.Unifier) ResolutionPlan(ai.grakn.graql.internal.reasoner.plan.ResolutionPlan) Collections(java.util.Collections) Concept(ai.grakn.concept.Concept) QueryAnswer(ai.grakn.graql.internal.query.QueryAnswer) IdPredicate(ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate) HashMap(java.util.HashMap) Var(ai.grakn.graql.Var) Objects(java.util.Objects)

Example 74 with Var

use of ai.grakn.graql.Var in project grakn by graknlabs.

the class ReasonerQueryImpl method idTransform.

/**
 * returns id transform that would convert this query to a query alpha-equivalent to the query,
 * provided they are structurally equivalent
 * @param query for which the transform is to be constructed
 * @param unifier between this query and provided query
 * @return id transform
 */
public Map<Var, ConceptId> idTransform(ReasonerQueryImpl query, Unifier unifier) {
    Map<Var, ConceptId> transform = new HashMap<>();
    this.getAtoms(IdPredicate.class).forEach(thisP -> {
        Collection<Var> vars = unifier.get(thisP.getVarName());
        Var var = !vars.isEmpty() ? Iterators.getOnlyElement(vars.iterator()) : thisP.getVarName();
        IdPredicate p2 = query.getIdPredicate(var);
        if (p2 != null)
            transform.put(thisP.getVarName(), p2.getPredicate());
    });
    return transform;
}
Also used : IdPredicate(ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate) HashMap(java.util.HashMap) Var(ai.grakn.graql.Var) ConceptId(ai.grakn.concept.ConceptId)

Example 75 with Var

use of ai.grakn.graql.Var in project grakn by graknlabs.

the class ResourceAtom method rewriteWithRelationVariable.

@Override
public ResourceAtom rewriteWithRelationVariable() {
    Var attributeVariable = getPredicateVariable();
    Var relationVariable = getRelationVariable().asUserDefined();
    VarPattern newVar = getVarName().has(getSchemaConcept().getLabel(), attributeVariable, relationVariable);
    return create(newVar.admin(), attributeVariable, relationVariable, getTypeId(), getMultiPredicate(), getParentQuery());
}
Also used : Var(ai.grakn.graql.Var) VarPattern(ai.grakn.graql.VarPattern)

Aggregations

Var (ai.grakn.graql.Var)100 Test (org.junit.Test)29 Answer (ai.grakn.graql.admin.Answer)28 ConceptId (ai.grakn.concept.ConceptId)26 Concept (ai.grakn.concept.Concept)25 Role (ai.grakn.concept.Role)25 VarPatternAdmin (ai.grakn.graql.admin.VarPatternAdmin)24 HashSet (java.util.HashSet)24 Set (java.util.Set)24 VarPattern (ai.grakn.graql.VarPattern)21 IdPredicate (ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate)21 Sets (com.google.common.collect.Sets)20 Map (java.util.Map)20 Stream (java.util.stream.Stream)20 GraqlQueryException (ai.grakn.exception.GraqlQueryException)19 ImmutableSet (com.google.common.collect.ImmutableSet)19 HashMap (java.util.HashMap)19 QueryAnswer (ai.grakn.graql.internal.query.QueryAnswer)18 List (java.util.List)18 SchemaConcept (ai.grakn.concept.SchemaConcept)17