Search in sources :

Example 66 with Concept

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

the class AtomicTest method testUnification_RelationWithMetaRolesAndIds.

@Test
public void testUnification_RelationWithMetaRolesAndIds() {
    EmbeddedGraknTx<?> graph = unificationTestSet.tx();
    Concept instance = graph.graql().<GetQuery>parse("match $x isa subRoleEntity; get;").execute().iterator().next().get(var("x"));
    String relation = "{(role: $x, role: $y) isa binary; $y id '" + instance.getId().getValue() + "';}";
    String relation2 = "{(role: $z, role: $v) isa binary; $z id '" + instance.getId().getValue() + "';}";
    String relation3 = "{(role: $z, role: $v) isa binary; $v id '" + instance.getId().getValue() + "';}";
    exactUnification(relation, relation2, true, true, graph);
    exactUnification(relation, relation3, true, true, graph);
    exactUnification(relation2, relation3, true, true, graph);
}
Also used : Concept(ai.grakn.concept.Concept) GetQuery(ai.grakn.graql.GetQuery) Test(org.junit.Test)

Example 67 with Concept

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

the class TinkerComputeQueryRunner method run.

public TinkerComputeJob<List<List<Concept>>> run(PathsQuery query) {
    return runCompute(query, tinkerComputeQuery -> {
        ConceptId sourceId = query.from();
        ConceptId destinationId = query.to();
        if (!tinkerComputeQuery.verticesExistInSubgraph(sourceId, destinationId)) {
            throw GraqlQueryException.instanceDoesNotExist();
        }
        if (sourceId.equals(destinationId)) {
            return Collections.singletonList(Collections.singletonList(tx.getConcept(sourceId)));
        }
        ComputerResult result;
        Set<LabelId> subLabelIds = convertLabelsToIds(tinkerComputeQuery.subLabels());
        try {
            result = tinkerComputeQuery.compute(new ShortestPathVertexProgram(sourceId, destinationId), null, subLabelIds);
        } catch (NoResultException e) {
            return Collections.emptyList();
        }
        Multimap<Concept, Concept> predecessorMapFromSource = tinkerComputeQuery.getPredecessorMap(result);
        List<List<Concept>> allPaths = tinkerComputeQuery.getAllPaths(predecessorMapFromSource, sourceId);
        if (tinkerComputeQuery.isAttributeIncluded()) {
            // this can be slow
            return tinkerComputeQuery.getExtendedPaths(allPaths);
        }
        LOG.info("Number of paths: " + allPaths.size());
        return allPaths;
    });
}
Also used : Concept(ai.grakn.concept.Concept) SchemaConcept(ai.grakn.concept.SchemaConcept) ShortestPathVertexProgram(ai.grakn.graql.internal.analytics.ShortestPathVertexProgram) ComputerResult(org.apache.tinkerpop.gremlin.process.computer.ComputerResult) List(java.util.List) LabelId(ai.grakn.concept.LabelId) NoResultException(ai.grakn.graql.internal.analytics.NoResultException) ConceptId(ai.grakn.concept.ConceptId)

Example 68 with Concept

use of ai.grakn.concept.Concept 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 69 with Concept

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

the class ConceptBuilder method tryGetConcept.

@Nullable
private Concept tryGetConcept() {
    Concept concept = null;
    if (has(ID)) {
        concept = executor.tx().getConcept(use(ID));
        if (has(LABEL)) {
            concept.asSchemaConcept().setLabel(use(LABEL));
        }
    } else if (has(LABEL)) {
        concept = executor.tx().getSchemaConcept(use(LABEL));
    }
    if (concept != null) {
        // The super can be changed on an existing concept
        if (has(SUPER_CONCEPT)) {
            SchemaConcept superConcept = use(SUPER_CONCEPT);
            setSuper(concept.asSchemaConcept(), superConcept);
        }
        validate(concept);
    }
    return concept;
}
Also used : Concept(ai.grakn.concept.Concept) SchemaConcept(ai.grakn.concept.SchemaConcept) SchemaConcept(ai.grakn.concept.SchemaConcept) Nullable(javax.annotation.Nullable)

Example 70 with Concept

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

the class ConceptBuilder method tryPutConcept.

private Concept tryPutConcept() {
    usedParams.clear();
    Concept concept;
    if (has(IS_ROLE)) {
        use(IS_ROLE);
        Label label = use(LABEL);
        Role role = executor.tx().putRole(label);
        if (has(SUPER_CONCEPT)) {
            setSuper(role, use(SUPER_CONCEPT));
        }
        concept = role;
    } else if (has(IS_RULE)) {
        use(IS_RULE);
        Label label = use(LABEL);
        Pattern when = use(WHEN);
        Pattern then = use(THEN);
        Rule rule = executor.tx().putRule(label, when, then);
        if (has(SUPER_CONCEPT)) {
            setSuper(rule, use(SUPER_CONCEPT));
        }
        concept = rule;
    } else if (has(SUPER_CONCEPT)) {
        concept = putSchemaConcept();
    } else if (has(TYPE)) {
        concept = putInstance();
    } else {
        throw GraqlQueryException.insertUndefinedVariable(executor.printableRepresentation(var));
    }
    // Check for any unexpected parameters
    preProvidedParams.forEach((param, value) -> {
        if (!usedParams.contains(param)) {
            throw GraqlQueryException.insertUnexpectedProperty(param.name(), value, concept);
        }
    });
    return concept;
}
Also used : Concept(ai.grakn.concept.Concept) SchemaConcept(ai.grakn.concept.SchemaConcept) Role(ai.grakn.concept.Role) Pattern(ai.grakn.graql.Pattern) Label(ai.grakn.concept.Label) Rule(ai.grakn.concept.Rule)

Aggregations

Concept (ai.grakn.concept.Concept)91 Test (org.junit.Test)56 ConceptId (ai.grakn.concept.ConceptId)26 GraknTx (ai.grakn.GraknTx)25 Answer (ai.grakn.graql.admin.Answer)25 SchemaConcept (ai.grakn.concept.SchemaConcept)19 Label (ai.grakn.concept.Label)18 GrpcConcept (ai.grakn.rpc.generated.GrpcConcept)18 QueryBuilder (ai.grakn.graql.QueryBuilder)17 Var (ai.grakn.graql.Var)15 Set (java.util.Set)15 Role (ai.grakn.concept.Role)14 QueryAnswer (ai.grakn.graql.internal.query.QueryAnswer)14 HashSet (java.util.HashSet)13 List (java.util.List)12 AttributeType (ai.grakn.concept.AttributeType)11 EntityType (ai.grakn.concept.EntityType)11 Schema (ai.grakn.util.Schema)10 Collectors (java.util.stream.Collectors)10 Stream (java.util.stream.Stream)10