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);
}
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());
}
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;
}
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;
}
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());
}
Aggregations