index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/aggregate/MedianAggregate.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.aggregate; import ai.grakn.graql.Aggregate; import ai.grakn.graql.Match; import ai.grakn.graql.Var; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.answer.Value; import java.util.Collections; import java.util.List; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; /** * Aggregate that finds median of a {@link Match}. */ class MedianAggregate implements Aggregate<Value> { private final Var varName; MedianAggregate(Var varName) { this.varName = varName; } @Override public List<Value> apply(Stream<? extends ConceptMap> stream) { List<Number> results = stream .map(result -> ((Number) result.get(varName).asAttribute().value())) .sorted() .collect(toList()); int size = results.size(); int halveFloor = Math.floorDiv(size - 1, 2); int halveCeiling = (int) Math.ceil((size - 1) / 2.0); if (size == 0) { return Collections.emptyList(); } else if (size % 2 == 1) { // Take exact middle result return Collections.singletonList(new Value(results.get(halveFloor))); } else { // Take average of middle results Number result = (results.get(halveFloor).doubleValue() + results.get(halveCeiling).doubleValue()) / 2; return Collections.singletonList(new Value(result)); } } @Override public String toString() { return "median " + varName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MedianAggregate that = (MedianAggregate) o; return varName.equals(that.varName); } @Override public int hashCode() { return varName.hashCode(); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/aggregate/MinAggregate.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.aggregate; import ai.grakn.graql.Aggregate; import ai.grakn.graql.Match; import ai.grakn.graql.Var; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.answer.Value; import ai.grakn.graql.internal.util.PrimitiveNumberComparator; import java.util.Collections; import java.util.List; import java.util.stream.Stream; /** * Aggregate that finds minimum of a {@link Match}. */ class MinAggregate implements Aggregate<Value> { private final Var varName; MinAggregate(Var varName) { this.varName = varName; } @Override public List<Value> apply(Stream<? extends ConceptMap> stream) { PrimitiveNumberComparator comparator = new PrimitiveNumberComparator(); Number number = stream.map(this::getValue).min(comparator).orElse(null); if (number == null) return Collections.emptyList(); else return Collections.singletonList(new Value(number)); } @Override public String toString() { return "min " + varName; } private Number getValue(ConceptMap result) { Object value = result.get(varName).asAttribute().value(); if (value instanceof Number) return (Number) value; else throw new RuntimeException("Invalid attempt to compare non-Numbers in Min Aggregate function"); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MinAggregate that = (MinAggregate) o; return varName.equals(that.varName); } @Override public int hashCode() { return varName.hashCode(); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/aggregate/StdAggregate.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.aggregate; import ai.grakn.graql.Aggregate; import ai.grakn.graql.Match; import ai.grakn.graql.Var; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.answer.Value; import java.util.Collections; import java.util.List; import java.util.stream.Stream; import static java.lang.Math.sqrt; /** * Aggregate that finds the unbiased sample standard deviation of a {@link Match}. */ class StdAggregate implements Aggregate<Value> { private final Var varName; StdAggregate(Var varName) { this.varName = varName; } @Override public List<Value> apply(Stream<? extends ConceptMap> stream) { Stream<Double> numStream = stream.map(result -> result.get(varName).<Number>asAttribute().value().doubleValue()); Iterable<Double> data = numStream::iterator; // Online algorithm to calculate unbiased sample standard deviation // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm long n = 0; double mean = 0d; double M2 = 0d; for (double x : data) { n += 1; double delta = x - mean; mean += delta / (double) n; double delta2 = x - mean; M2 += delta*delta2; } if (n < 2) { return Collections.emptyList(); } else { return Collections.singletonList(new Value(sqrt(M2 / (double) (n - 1)))); } } @Override public String toString() { return "std " + varName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StdAggregate that = (StdAggregate) o; return varName.equals(that.varName); } @Override public int hashCode() { return varName.hashCode(); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/aggregate/SumAggregate.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.aggregate; import ai.grakn.graql.Aggregate; import ai.grakn.graql.Match; import ai.grakn.graql.Var; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.answer.Value; import java.util.Collections; import java.util.List; import java.util.stream.Stream; /** * Aggregate that sums results of a {@link Match}. */ class SumAggregate implements Aggregate<Value> { private final Var varName; SumAggregate(Var varName) { this.varName = varName; } @Override public List<Value> apply(Stream<? extends ConceptMap> stream) { // initial value is set to null so that we can return null if there is no Answers to consume Number number = stream.map(result -> (Number) result.get(varName).asAttribute().value()).reduce(null, this::add); if (number == null) return Collections.emptyList(); else return Collections.singletonList(new Value(number)); } private Number add(Number x, Number y) { // if this method is called, then there is at least one number to apply SumAggregate to, thus we set x back to 0 if (x == null) x = 0; // This method is necessary because Number doesn't support '+' because java! if (x instanceof Long && y instanceof Long) { return x.longValue() + y.longValue(); } else if (x instanceof Long) { return x.longValue() + y.doubleValue(); } else if (y instanceof Long) { return x.doubleValue() + y.longValue(); } else { return x.doubleValue() + y.doubleValue(); } } @Override public String toString() { return "sum " + varName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SumAggregate that = (SumAggregate) o; return varName.equals(that.varName); } @Override public int hashCode() { return varName.hashCode(); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/answer/ConceptMapImpl.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.answer; import ai.grakn.concept.Concept; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Graql; import ai.grakn.graql.Var; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.admin.Explanation; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.MultiUnifier; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.Unifier; import ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate; import ai.grakn.graql.internal.reasoner.explanation.JoinExplanation; import ai.grakn.graql.internal.reasoner.explanation.QueryExplanation; import ai.grakn.graql.internal.reasoner.utils.Pair; import ai.grakn.graql.internal.reasoner.utils.ReasonerUtils; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; import java.util.stream.Collectors; import java.util.stream.Stream; /** * * <p> * Wrapper for a query result class {@link ConceptMap}. * </p> * * @author Kasper Piskorski * */ public class ConceptMapImpl implements ConceptMap { private final ImmutableMap<Var, Concept> map; private final Explanation explanation; public ConceptMapImpl(){ this.map = ImmutableMap.of(); this.explanation = new QueryExplanation(); } public ConceptMapImpl(ConceptMap map){ this(map.map().entrySet(), map.explanation()); } public ConceptMapImpl(Collection<Map.Entry<Var, Concept>> mappings, Explanation exp){ this.map = ImmutableMap.<Var, Concept>builder().putAll(mappings).build(); this.explanation = exp; } public ConceptMapImpl(Map<Var, Concept> m, Explanation exp){ this(m.entrySet(), exp); } public ConceptMapImpl(Map<Var, Concept> m){ this(m, new QueryExplanation()); } @Override public ConceptMap asConceptMap() { return this; } @Override public Explanation explanation(){ return explanation; } @Override public ImmutableMap<Var, Concept> map() { return map; } @Override public Set<Var> vars(){ return map.keySet();} @Override public Collection<Concept> concepts(){ return map.values(); } @Override public Concept get(String var) { return get(Graql.var(var)); } @Override public Concept get(Var var) { Concept concept = map.get(var); if (concept == null) throw GraqlQueryException.varNotInQuery(var); return concept; } @Override public boolean containsVar(Var var){ return map.containsKey(var);} @Override public boolean containsAll(ConceptMap map){ return this.map.entrySet().containsAll(map.map().entrySet());} @Override public boolean isEmpty(){ return map.isEmpty();} @Override public int size(){ return map.size();} @Override public String toString(){ return map.entrySet().stream() .sorted(Comparator.comparing(e -> e.getKey().getValue())) .map(e -> "[" + e.getKey() + "/" + e.getValue().id() + "]").collect(Collectors.joining()); } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null || getClass() != obj.getClass()) return false; ConceptMapImpl a2 = (ConceptMapImpl) obj; return map.equals(a2.map); } @Override public int hashCode(){ return map.hashCode();} @Override public void forEach(BiConsumer<Var, Concept> consumer) { map.forEach(consumer); } @Override public ConceptMap merge(ConceptMap map, boolean mergeExplanation){ if(map.isEmpty()) return this; if(this.isEmpty()) return map; Sets.SetView<Var> varUnion = Sets.union(this.vars(), map.vars()); Set<Var> varIntersection = Sets.intersection(this.vars(), map.vars()); Map<Var, Concept> entryMap = Sets.union( this.map.entrySet(), map.map().entrySet() ) .stream() .filter(e -> !varIntersection.contains(e.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); varIntersection .forEach(var -> { Concept concept = this.get(var); Concept otherConcept = map.get(var); if (concept.equals(otherConcept)) entryMap.put(var, concept); else { if (concept.isSchemaConcept() && otherConcept.isSchemaConcept() && !ReasonerUtils.areDisjointTypes(concept.asSchemaConcept(), otherConcept.asSchemaConcept())) { entryMap.put( var, Iterables.getOnlyElement(ReasonerUtils.topOrMeta( Sets.newHashSet( concept.asSchemaConcept(), otherConcept.asSchemaConcept()) ) ) ); } } }); if (!entryMap.keySet().equals(varUnion)) return new ConceptMapImpl(); return new ConceptMapImpl( entryMap, mergeExplanation? this.mergeExplanation(map) : this.explanation() ); } private Explanation mergeExplanation(ConceptMap toMerge) { List<ConceptMap> partialAnswers = new ArrayList<>(); if (this.explanation().isJoinExplanation()) partialAnswers.addAll(this.explanation().getAnswers()); else partialAnswers.add(this); if (toMerge.explanation().isJoinExplanation()) partialAnswers.addAll(toMerge.explanation().getAnswers()); else partialAnswers.add(toMerge); return new JoinExplanation(partialAnswers); } @Override public ConceptMap merge(ConceptMap a2){ return this.merge(a2, false);} @Override public ConceptMap explain(Explanation exp){ return new ConceptMapImpl(this.map.entrySet(), exp.childOf(this)); } @Override public ConceptMap project(Set<Var> vars) { return new ConceptMapImpl( this.map.entrySet().stream() .filter(e -> vars.contains(e.getKey())) .collect(Collectors.toSet()), this.explanation() ); } @Override public ConceptMap unify(Unifier unifier){ if (unifier.isEmpty()) return this; Map<Var, Concept> unified = new HashMap<>(); for(Map.Entry<Var, Concept> e : this.map.entrySet()){ Var var = e.getKey(); Concept con = e.getValue(); Collection<Var> uvars = unifier.get(var); if (uvars.isEmpty() && !unifier.values().contains(var)) { Concept put = unified.put(var, con); if (put != null && !put.equals(con)) return new ConceptMapImpl(); } else { for(Var uv : uvars){ Concept put = unified.put(uv, con); if (put != null && !put.equals(con)) return new ConceptMapImpl(); } } } return new ConceptMapImpl(unified, this.explanation()); } @Override public Stream<ConceptMap> unify(MultiUnifier multiUnifier) { return multiUnifier.stream().map(this::unify); } @Override public Stream<ConceptMap> expandHierarchies(Set<Var> toExpand) { if (toExpand.isEmpty()) return Stream.of(this); List<Set<Pair<Var, Concept>>> entryOptions = map.entrySet().stream() .map(e -> { Var var = e.getKey(); if (toExpand.contains(var)) { Concept c = get(var); if (c.isSchemaConcept()) { return ReasonerUtils.upstreamHierarchy(c.asSchemaConcept()).stream() .map(r -> new Pair<Var, Concept>(var, r)) .collect(Collectors.toSet()); } } return Collections.singleton(new Pair<>(var, get(var))); }).collect(Collectors.toList()); return Sets.cartesianProduct(entryOptions).stream() .map(mappingList -> new ConceptMapImpl(mappingList.stream().collect(Collectors.toMap(Pair::getKey, Pair::getValue)), this.explanation())) .map(ans -> ans.explain(explanation())); } @Override public Set<Atomic> toPredicates(ReasonerQuery parent) { Set<Var> varNames = parent.getVarNames(); return map.entrySet().stream() .filter(e -> varNames.contains(e.getKey())) .map(e -> IdPredicate.create(e.getKey(), e.getValue(), parent)) .collect(Collectors.toSet()); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/executor/AutoValue_QueryOperationExecutor_VarAndProperty.java
package ai.grakn.graql.internal.query.executor; import ai.grakn.graql.Var; import ai.grakn.graql.internal.pattern.property.PropertyExecutor; import ai.grakn.graql.internal.pattern.property.VarPropertyInternal; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_QueryOperationExecutor_VarAndProperty extends QueryOperationExecutor.VarAndProperty { private final Var var; private final VarPropertyInternal property; private final PropertyExecutor executor; AutoValue_QueryOperationExecutor_VarAndProperty( Var var, VarPropertyInternal property, PropertyExecutor executor) { if (var == null) { throw new NullPointerException("Null var"); } this.var = var; if (property == null) { throw new NullPointerException("Null property"); } this.property = property; if (executor == null) { throw new NullPointerException("Null executor"); } this.executor = executor; } @Override Var var() { return var; } @Override VarPropertyInternal property() { return property; } @Override PropertyExecutor executor() { return executor; } @Override public String toString() { return "VarAndProperty{" + "var=" + var + ", " + "property=" + property + ", " + "executor=" + executor + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof QueryOperationExecutor.VarAndProperty) { QueryOperationExecutor.VarAndProperty that = (QueryOperationExecutor.VarAndProperty) o; return (this.var.equals(that.var())) && (this.property.equals(that.property())) && (this.executor.equals(that.executor())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.var.hashCode(); h *= 1000003; h ^= this.property.hashCode(); h *= 1000003; h ^= this.executor.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/executor/ComputeExecutorImpl.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.executor; import ai.grakn.ComputeExecutor; import ai.grakn.GraknComputer; import ai.grakn.concept.AttributeType; import ai.grakn.concept.Concept; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Label; import ai.grakn.concept.LabelId; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.concept.SchemaConcept; import ai.grakn.concept.Thing; import ai.grakn.concept.Type; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.ComputeQuery; import ai.grakn.graql.Graql; import ai.grakn.graql.Pattern; import ai.grakn.graql.answer.Answer; import ai.grakn.graql.answer.ConceptList; import ai.grakn.graql.answer.ConceptSet; import ai.grakn.graql.answer.ConceptSetMeasure; import ai.grakn.graql.answer.Value; import ai.grakn.graql.internal.analytics.ClusterMemberMapReduce; import ai.grakn.graql.internal.analytics.ConnectedComponentVertexProgram; import ai.grakn.graql.internal.analytics.ConnectedComponentsVertexProgram; import ai.grakn.graql.internal.analytics.CorenessVertexProgram; import ai.grakn.graql.internal.analytics.CountMapReduceWithAttribute; import ai.grakn.graql.internal.analytics.CountVertexProgram; import ai.grakn.graql.internal.analytics.DegreeDistributionMapReduce; import ai.grakn.graql.internal.analytics.DegreeStatisticsVertexProgram; import ai.grakn.graql.internal.analytics.DegreeVertexProgram; import ai.grakn.graql.internal.analytics.GraknMapReduce; import ai.grakn.graql.internal.analytics.GraknVertexProgram; import ai.grakn.graql.internal.analytics.KCoreVertexProgram; import ai.grakn.graql.internal.analytics.MaxMapReduce; import ai.grakn.graql.internal.analytics.MeanMapReduce; import ai.grakn.graql.internal.analytics.MedianVertexProgram; import ai.grakn.graql.internal.analytics.MinMapReduce; import ai.grakn.graql.internal.analytics.NoResultException; import ai.grakn.graql.internal.analytics.ShortestPathVertexProgram; import ai.grakn.graql.internal.analytics.StatisticsMapReduce; import ai.grakn.graql.internal.analytics.StdMapReduce; import ai.grakn.graql.internal.analytics.SumMapReduce; import ai.grakn.graql.internal.analytics.Utility; import ai.grakn.kb.internal.EmbeddedGraknTx; import ai.grakn.util.CommonUtil; import ai.grakn.util.GraqlSyntax; import ai.grakn.util.Schema; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import org.apache.tinkerpop.gremlin.process.computer.ComputerResult; import org.apache.tinkerpop.gremlin.process.computer.MapReduce; import org.apache.tinkerpop.gremlin.process.computer.Memory; import org.apache.tinkerpop.gremlin.process.computer.VertexProgram; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.Serializable; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import static ai.grakn.util.GraqlSyntax.Compute.Algorithm.CONNECTED_COMPONENT; import static ai.grakn.util.GraqlSyntax.Compute.Algorithm.DEGREE; import static ai.grakn.util.GraqlSyntax.Compute.Algorithm.K_CORE; import static ai.grakn.util.GraqlSyntax.Compute.Method.CENTRALITY; import static ai.grakn.util.GraqlSyntax.Compute.Method.CLUSTER; import static ai.grakn.util.GraqlSyntax.Compute.Method.COUNT; import static ai.grakn.util.GraqlSyntax.Compute.Method.MAX; import static ai.grakn.util.GraqlSyntax.Compute.Method.MEAN; import static ai.grakn.util.GraqlSyntax.Compute.Method.MEDIAN; import static ai.grakn.util.GraqlSyntax.Compute.Method.MIN; import static ai.grakn.util.GraqlSyntax.Compute.Method.PATH; import static ai.grakn.util.GraqlSyntax.Compute.Method.STD; import static ai.grakn.util.GraqlSyntax.Compute.Method.SUM; /** * A Graql Compute query job executed against a {@link GraknComputer}. * * @author Grakn Warriors */ class ComputeExecutorImpl<T extends Answer> implements ComputeExecutor<T> { private final ComputeQuery<T> query; private static final Logger LOG = LoggerFactory.getLogger(ComputeExecutorImpl.class); private final EmbeddedGraknTx<?> tx; public ComputeExecutorImpl(EmbeddedGraknTx<?> tx, ComputeQuery query) { this.tx = tx; this.query = query; } @Override public void kill() { //todo: to be removed; tx.session().getGraphComputer().killJobs(); } @Override public Stream<T> stream() { GraqlSyntax.Compute.Method<?> method = query.method(); if (method.equals(MIN) || method.equals(MAX) || method.equals(MEDIAN) || method.equals(SUM)) { return (Stream<T>) runComputeMinMaxMedianOrSum(); } else if (method.equals(MEAN)) { return (Stream<T>) runComputeMean(); } else if (method.equals(STD)) { return (Stream<T>) runComputeStd(); } else if (method.equals(COUNT)) { return (Stream<T>) runComputeCount(); } else if (method.equals(PATH)) { return (Stream<T>) runComputePath(); } else if (method.equals(CENTRALITY)) { return (Stream<T>) runComputeCentrality(); } else if (method.equals(CLUSTER)) { return (Stream<T>) runComputeCluster(); } throw GraqlQueryException.invalidComputeQuery_invalidMethod(); } public final ComputerResult compute(@Nullable VertexProgram<?> program, @Nullable MapReduce<?, ?, ?, ?, ?> mapReduce, @Nullable Set<LabelId> scope, Boolean includesRolePlayerEdges) { return tx.session().getGraphComputer().compute(program, mapReduce, scope, includesRolePlayerEdges); } public final ComputerResult compute(@Nullable VertexProgram<?> program, @Nullable MapReduce<?, ?, ?, ?, ?> mapReduce, @Nullable Set<LabelId> scope) { return tx.session().getGraphComputer().compute(program, mapReduce, scope); } /** * The Graql compute min, max, median, or sum query run method * * @return a Answer object containing a Number that represents the answer */ private Stream<Value> runComputeMinMaxMedianOrSum() { Number number = runComputeStatistics(); if (number == null) return Stream.empty(); else return Stream.of(new Value(number)); } /** * The Graql compute mean query run method * * @return a Answer object containing a Number that represents the answer */ private Stream<Value> runComputeMean() { Map<String, Double> meanPair = runComputeStatistics(); if (meanPair == null) return Stream.empty(); Double mean = meanPair.get(MeanMapReduce.SUM) / meanPair.get(MeanMapReduce.COUNT); return Stream.of(new Value(mean)); } /** * The Graql compute std query run method * * @return a Answer object containing a Number that represents the answer */ private Stream<Value> runComputeStd() { Map<String, Double> stdTuple = runComputeStatistics(); if (stdTuple == null) return Stream.empty(); double squareSum = stdTuple.get(StdMapReduce.SQUARE_SUM); double sum = stdTuple.get(StdMapReduce.SUM); double count = stdTuple.get(StdMapReduce.COUNT); Double std = Math.sqrt(squareSum / count - (sum / count) * (sum / count)); return Stream.of(new Value(std)); } /** * The compute statistics base algorithm that is called in every compute statistics query * * @param <S> The return type of {@link StatisticsMapReduce} * @return result of compute statistics algorithm, which will be of type S */ @Nullable private <S> S runComputeStatistics() { AttributeType.DataType<?> targetDataType = validateAndGetTargetDataType(); if (!targetContainsInstance()) return null; Set<LabelId> extendedScopeTypes = convertLabelsToIds(extendedScopeTypeLabels()); Set<LabelId> targetTypes = convertLabelsToIds(targetTypeLabels()); VertexProgram program = initStatisticsVertexProgram(query, targetTypes, targetDataType); StatisticsMapReduce<?> mapReduce = initStatisticsMapReduce(targetTypes, targetDataType); ComputerResult computerResult = compute(program, mapReduce, extendedScopeTypes); if (query.method().equals(MEDIAN)) { Number result = computerResult.memory().get(MedianVertexProgram.MEDIAN); LOG.debug("Median = " + result); return (S) result; } Map<Serializable, S> resultMap = computerResult.memory().get(mapReduce.getClass().getName()); LOG.debug("Result = " + resultMap.get(MapReduce.NullObject.instance())); return resultMap.get(MapReduce.NullObject.instance()); } /** * Helper method to validate that the target types are of one data type, and get that data type * * @return the DataType of the target types */ @Nullable private AttributeType.DataType<?> validateAndGetTargetDataType() { AttributeType.DataType<?> dataType = null; for (Type type : targetTypes()) { // check if the selected type is a attribute type if (!type.isAttributeType()) throw GraqlQueryException.mustBeAttributeType(type.label()); AttributeType<?> attributeType = type.asAttributeType(); if (dataType == null) { // check if the attribute type has data-type LONG or DOUBLE dataType = attributeType.dataType(); if (!dataType.equals(AttributeType.DataType.LONG) && !dataType.equals(AttributeType.DataType.DOUBLE)) { throw GraqlQueryException.attributeMustBeANumber(dataType, attributeType.label()); } } else { // check if all the attribute types have the same data-type if (!dataType.equals(attributeType.dataType())) { throw GraqlQueryException.attributesWithDifferentDataTypes(query.of().get()); } } } return dataType; } /** * Helper method to intialise the vertex program for compute statistics queries * * @param query representing the compute query * @param targetTypes representing the attribute types in which the statistics computation is targeted for * @param targetDataType representing the data type of the target attribute types * @return an object which is a subclass of VertexProgram */ private VertexProgram initStatisticsVertexProgram(ComputeQuery query, Set<LabelId> targetTypes, AttributeType.DataType<?> targetDataType) { if (query.method().equals(MEDIAN)) return new MedianVertexProgram(targetTypes, targetDataType); else return new DegreeStatisticsVertexProgram(targetTypes); } /** * Helper method to initialise the MapReduce algorithm for compute statistics queries * * @param targetTypes representing the attribute types in which the statistics computation is targeted for * @param targetDataType representing the data type of the target attribute types * @return an object which is a subclass of StatisticsMapReduce */ private StatisticsMapReduce<?> initStatisticsMapReduce(Set<LabelId> targetTypes, AttributeType.DataType<?> targetDataType) { GraqlSyntax.Compute.Method<?> method = query.method(); if (method.equals(MIN)) { return new MinMapReduce(targetTypes, targetDataType, DegreeVertexProgram.DEGREE); } else if (method.equals(MAX)) { return new MaxMapReduce(targetTypes, targetDataType, DegreeVertexProgram.DEGREE); } else if (method.equals(MEAN)) { return new MeanMapReduce(targetTypes, targetDataType, DegreeVertexProgram.DEGREE); }else if (method.equals(STD)) { return new StdMapReduce(targetTypes, targetDataType, DegreeVertexProgram.DEGREE); } else if (method.equals(SUM)) { return new SumMapReduce(targetTypes, targetDataType, DegreeVertexProgram.DEGREE); } return null; } /** * Run Graql compute count query * * @return a Answer object containing the count value */ private Stream<Value> runComputeCount() { if (!scopeContainsInstance()) { LOG.debug("Count = 0"); return Stream.of(new Value(0)); } Set<LabelId> typeLabelIds = convertLabelsToIds(scopeTypeLabels()); Map<Integer, Long> count; Set<LabelId> rolePlayerLabelIds = getRolePlayerLabelIds(); rolePlayerLabelIds.addAll(typeLabelIds); ComputerResult result = compute( new CountVertexProgram(), new CountMapReduceWithAttribute(), rolePlayerLabelIds, false); count = result.memory().get(CountMapReduceWithAttribute.class.getName()); long finalCount = count.keySet().stream() .filter(id -> typeLabelIds.contains(LabelId.of(id))) .mapToLong(count::get).sum(); if (count.containsKey(GraknMapReduce.RESERVED_TYPE_LABEL_KEY)) { finalCount += count.get(GraknMapReduce.RESERVED_TYPE_LABEL_KEY); } LOG.debug("Count = " + finalCount); return Stream.of(new Value(finalCount)); } /** * The Graql compute path query run method * * @return a Answer containing the list of shortest paths */ private Stream<ConceptList> runComputePath() { ConceptId fromID = query.from().get(); ConceptId toID = query.to().get(); if (!scopeContainsInstances(fromID, toID)) throw GraqlQueryException.instanceDoesNotExist(); if (fromID.equals(toID)) return Stream.of(new ConceptList(ImmutableList.of(fromID))); Set<LabelId> scopedLabelIds = convertLabelsToIds(scopeTypeLabels()); ComputerResult result = compute(new ShortestPathVertexProgram(fromID, toID), null, scopedLabelIds); Multimap<ConceptId, ConceptId> pathsAsEdgeList = HashMultimap.create(); Map<String, Set<String>> resultFromMemory = result.memory().get(ShortestPathVertexProgram.SHORTEST_PATH); resultFromMemory.forEach((id, idSet) -> idSet.forEach(id2 -> { pathsAsEdgeList.put(ConceptId.of(id), ConceptId.of(id2)); })); List<List<ConceptId>> paths; if (!resultFromMemory.isEmpty()) { paths = getComputePathResultList(pathsAsEdgeList, fromID); if (scopeIncludesAttributes()) { paths = getComputePathResultListIncludingImplicitRelations(paths); } } else { paths = Collections.emptyList(); } return paths.stream().map(ConceptList::new); } /** * The Graql compute centrality query run method * * @return a Answer containing the centrality count map */ private Stream<ConceptSetMeasure> runComputeCentrality() { if (query.using().get().equals(DEGREE)) return runComputeDegree(); if (query.using().get().equals(K_CORE)) return runComputeCoreness(); throw GraqlQueryException.invalidComputeQuery_invalidMethodAlgorithm(query.method()); } /** * The Graql compute centrality using degree query run method * * @return a Answer containing the centrality count map */ private Stream<ConceptSetMeasure> runComputeDegree() { Set<Label> targetTypeLabels; // Check if ofType is valid before returning emptyMap if (!query.of().isPresent() || query.of().get().isEmpty()) { targetTypeLabels = scopeTypeLabels(); } else { targetTypeLabels = query.of().get().stream() .flatMap(typeLabel -> { Type type = tx.getSchemaConcept(typeLabel); if (type == null) throw GraqlQueryException.labelNotFound(typeLabel); return type.subs(); }) .map(SchemaConcept::label) .collect(Collectors.toSet()); } Set<Label> scopeTypeLabels = Sets.union(scopeTypeLabels(), targetTypeLabels); if (!scopeContainsInstance()) { return Stream.empty(); } Set<LabelId> scopeTypeLabelIDs = convertLabelsToIds(scopeTypeLabels); Set<LabelId> targetTypeLabelIDs = convertLabelsToIds(targetTypeLabels); ComputerResult computerResult = compute(new DegreeVertexProgram(targetTypeLabelIDs), new DegreeDistributionMapReduce(targetTypeLabelIDs, DegreeVertexProgram.DEGREE), scopeTypeLabelIDs); Map<Long, Set<ConceptId>> centralityMap = computerResult.memory().get(DegreeDistributionMapReduce.class.getName()); return centralityMap.entrySet().stream() .map(centrality -> new ConceptSetMeasure(centrality.getValue(), centrality.getKey())); } /** * The Graql compute centrality using k-core query run method * * @return a Answer containing the centrality count map */ private Stream<ConceptSetMeasure> runComputeCoreness() { long k = query.where().get().minK().get(); if (k < 2L) throw GraqlQueryException.kValueSmallerThanTwo(); Set<Label> targetTypeLabels; // Check if ofType is valid before returning emptyMap if (!query.of().isPresent() || query.of().get().isEmpty()) { targetTypeLabels = scopeTypeLabels(); } else { targetTypeLabels = query.of().get().stream() .flatMap(typeLabel -> { Type type = tx.getSchemaConcept(typeLabel); if (type == null) throw GraqlQueryException.labelNotFound(typeLabel); if (type.isRelationshipType()) throw GraqlQueryException.kCoreOnRelationshipType(typeLabel); return type.subs(); }) .map(SchemaConcept::label) .collect(Collectors.toSet()); } Set<Label> scopeTypeLabels = Sets.union(scopeTypeLabels(), targetTypeLabels); if (!scopeContainsInstance()) { return Stream.empty(); } ComputerResult result; Set<LabelId> scopeTypeLabelIDs = convertLabelsToIds(scopeTypeLabels); Set<LabelId> targetTypeLabelIDs = convertLabelsToIds(targetTypeLabels); try { result = compute(new CorenessVertexProgram(k), new DegreeDistributionMapReduce(targetTypeLabelIDs, CorenessVertexProgram.CORENESS), scopeTypeLabelIDs); } catch (NoResultException e) { return Stream.empty(); } Map<Long, Set<ConceptId>> centralityMap = result.memory().get(DegreeDistributionMapReduce.class.getName()); return centralityMap.entrySet().stream() .map(centrality -> new ConceptSetMeasure(centrality.getValue(), centrality.getKey())); } private Stream<ConceptSet> runComputeCluster() { if (query.using().get().equals(K_CORE)) return runComputeKCore(); if (query.using().get().equals(CONNECTED_COMPONENT)) return runComputeConnectedComponent(); throw GraqlQueryException.invalidComputeQuery_invalidMethodAlgorithm(query.method()); } private Stream<ConceptSet> runComputeConnectedComponent() { boolean restrictSize = query.where().get().size().isPresent(); if (!scopeContainsInstance()) { LOG.info("Selected types don't have instances"); return Stream.empty(); } Set<LabelId> scopeTypeLabelIDs = convertLabelsToIds(scopeTypeLabels()); GraknVertexProgram<?> vertexProgram; if (query.where().get().contains().isPresent()) { ConceptId conceptId = query.where().get().contains().get(); if (!scopeContainsInstances(conceptId)) { throw GraqlQueryException.instanceDoesNotExist(); } vertexProgram = new ConnectedComponentVertexProgram(conceptId); } else { vertexProgram = new ConnectedComponentsVertexProgram(); } GraknMapReduce<?> mapReduce; if (restrictSize) mapReduce = new ClusterMemberMapReduce(ConnectedComponentsVertexProgram.CLUSTER_LABEL, query.where().get().size().get()); else mapReduce = new ClusterMemberMapReduce(ConnectedComponentsVertexProgram.CLUSTER_LABEL); Memory memory = compute(vertexProgram, mapReduce, scopeTypeLabelIDs).memory(); Map<String, Set<ConceptId>> result = memory.get(mapReduce.getClass().getName()); return result.values().stream().map(ConceptSet::new); // TODO: Enable the following compute cluster-size through a separate compute method // if (!query.where().get().members().get()) { // GraknMapReduce<?> mapReduce; // if (restrictSize) { // mapreduce = new ClusterSizeMapReduce(ConnectedComponentsVertexProgram.CLUSTER_LABEL, query.where().get().size().get()); // } else { // mapReduce = new ClusterSizeMapReduce(ConnectedComponentsVertexProgram.CLUSTER_LABEL); // } // Map<String, Long> result = memory.get(mapReduce.getClass().getName()); // return result.values().stream().map(Value::new); // } } private Stream<ConceptSet> runComputeKCore() { long k = query.where().get().k().get(); if (k < 2L) throw GraqlQueryException.kValueSmallerThanTwo(); if (!scopeContainsInstance()) { return Stream.empty(); } ComputerResult computerResult; Set<LabelId> subLabelIds = convertLabelsToIds(scopeTypeLabels()); try { computerResult = compute( new KCoreVertexProgram(k), new ClusterMemberMapReduce(KCoreVertexProgram.K_CORE_LABEL), subLabelIds); } catch (NoResultException e) { return Stream.empty(); } Map<String, Set<ConceptId>> result = computerResult.memory().get(ClusterMemberMapReduce.class.getName()); return result.values().stream().map(ConceptSet::new); } /** * Helper method to get list of all shortest paths * * @param resultGraph * @param fromID * @return */ private List<List<ConceptId>> getComputePathResultList(Multimap<ConceptId, ConceptId> resultGraph, ConceptId fromID) { List<List<ConceptId>> allPaths = new ArrayList<>(); List<ConceptId> firstPath = new ArrayList<>(); firstPath.add(fromID); Deque<List<ConceptId>> queue = new ArrayDeque<>(); queue.addLast(firstPath); while (!queue.isEmpty()) { List<ConceptId> currentPath = queue.pollFirst(); if (resultGraph.containsKey(currentPath.get(currentPath.size() - 1))) { Collection<ConceptId> successors = resultGraph.get(currentPath.get(currentPath.size() - 1)); Iterator<ConceptId> iterator = successors.iterator(); for (int i = 0; i < successors.size() - 1; i++) { List<ConceptId> extendedPath = new ArrayList<>(currentPath); extendedPath.add(iterator.next()); queue.addLast(extendedPath); } currentPath.add(iterator.next()); queue.addLast(currentPath); } else { allPaths.add(currentPath); } } return allPaths; } /** * Helper method t get the list of all shortest path, but also including the implicit relations that connect * entities and attributes * * @param allPaths * @return */ private List<List<ConceptId>> getComputePathResultListIncludingImplicitRelations(List<List<ConceptId>> allPaths) { List<List<ConceptId>> extendedPaths = new ArrayList<>(); for (List<ConceptId> currentPath : allPaths) { boolean hasAttribute = currentPath.stream().anyMatch(conceptID -> tx.getConcept(conceptID).isAttribute()); if (!hasAttribute) { extendedPaths.add(currentPath); } } // If there exist a path without attributes, we don't need to expand any path // as paths contain attributes would be longer after implicit relations are added int numExtensionAllowed = extendedPaths.isEmpty() ? Integer.MAX_VALUE : 0; for (List<ConceptId> currentPath : allPaths) { List<ConceptId> extendedPath = new ArrayList<>(); int numExtension = 0; // record the number of extensions needed for the current path for (int j = 0; j < currentPath.size() - 1; j++) { extendedPath.add(currentPath.get(j)); ConceptId resourceRelationId = Utility.getResourceEdgeId(tx, currentPath.get(j), currentPath.get(j + 1)); if (resourceRelationId != null) { numExtension++; if (numExtension > numExtensionAllowed) break; extendedPath.add(resourceRelationId); } } if (numExtension == numExtensionAllowed) { extendedPath.add(currentPath.get(currentPath.size() - 1)); extendedPaths.add(extendedPath); } else if (numExtension < numExtensionAllowed) { extendedPath.add(currentPath.get(currentPath.size() - 1)); extendedPaths.clear(); // longer paths are discarded extendedPaths.add(extendedPath); // update the minimum number of extensions needed so all the paths have the same length numExtensionAllowed = numExtension; } } return extendedPaths; } /** * Helper method to get the label IDs of role players in a relationship * * @return a set of type label IDs */ private Set<LabelId> getRolePlayerLabelIds() { return scopeTypes() .filter(Concept::isRelationshipType) .map(Concept::asRelationshipType) .filter(RelationshipType::isImplicit) .flatMap(RelationshipType::roles) .flatMap(Role::players) .map(type -> tx.convertToId(type.label())) .filter(LabelId::isValid) .collect(Collectors.toSet()); } /** * Helper method to get implicit relationship types of attributes * * @param types * @return a set of type Labels */ private static Set<Label> getAttributeImplicitRelationTypeLabes(Set<Type> types) { // If the sub graph contains attributes, we may need to add implicit relations to the path return types.stream() .filter(Concept::isAttributeType) .map(attributeType -> Schema.ImplicitType.HAS.getLabel(attributeType.label())) .collect(Collectors.toSet()); } /** * Helper method to get the types to be included in the query target * * @return a set of Types */ private ImmutableSet<Type> targetTypes() { if (!query.of().isPresent() || query.of().get().isEmpty()) { throw GraqlQueryException.statisticsAttributeTypesNotSpecified(); } return query.of().get().stream() .map((label) -> { Type type = tx.getSchemaConcept(label); if (type == null) throw GraqlQueryException.labelNotFound(label); if (!type.isAttributeType()) throw GraqlQueryException.mustBeAttributeType(type.label()); return type; }) .flatMap(Type::subs) .collect(CommonUtil.toImmutableSet()); } /** * Helper method to get the labels of the type in the query target * * @return a set of type Labels */ private Set<Label> targetTypeLabels() { return targetTypes().stream() .map(SchemaConcept::label) .collect(CommonUtil.toImmutableSet()); } /** * Helper method to check whether the concept types in the target have any instances * * @return true if they exist, false if they don't */ private boolean targetContainsInstance() { for (Label attributeType : targetTypeLabels()) { for (Label type : scopeTypeLabels()) { Boolean patternExist = tx.graql().infer(false).match( Graql.var("x").has(attributeType, Graql.var()), Graql.var("x").isa(Graql.label(type)) ).iterator().hasNext(); if (patternExist) return true; } } return false; //TODO: should use the following ask query when ask query is even lazier // List<Pattern> checkResourceTypes = statisticsResourceTypes.stream() // .map(type -> var("x").has(type, var())).collect(Collectors.toList()); // List<Pattern> checkSubtypes = inTypes.stream() // .map(type -> var("x").isa(Graql.label(type))).collect(Collectors.toList()); // // return tx.get().graql().infer(false) // .match(or(checkResourceTypes), or(checkSubtypes)).aggregate(ask()).execute(); } /** * Helper method to get all the concept types that should scope of compute query, which includes the implicit types * between attributes and entities, if target types were provided. This is used for compute statistics queries. * * @return a set of type labels */ private Set<Label> extendedScopeTypeLabels() { Set<Label> extendedTypeLabels = getAttributeImplicitRelationTypeLabes(targetTypes()); extendedTypeLabels.addAll(scopeTypeLabels()); extendedTypeLabels.addAll(query.of().get()); return extendedTypeLabels; } /** * Helper method to get the types to be included in the query scope * * @return stream of Concept Types */ private Stream<Type> scopeTypes() { // Get all types if query.inTypes() is empty, else get all scoped types of each meta type. // Only include attributes and implicit "has-xxx" relationships when user specifically asked for them. if (!query.in().isPresent() || query.in().get().isEmpty()) { ImmutableSet.Builder<Type> typeBuilder = ImmutableSet.builder(); if (scopeIncludesAttributes()) { tx.admin().getMetaConcept().subs().forEach(typeBuilder::add); } else { tx.admin().getMetaEntityType().subs().forEach(typeBuilder::add); tx.admin().getMetaRelationType().subs() .filter(relationshipType -> !relationshipType.isImplicit()).forEach(typeBuilder::add); } return typeBuilder.build().stream(); } else { Stream<Type> subTypes = query.in().get().stream().map(label -> { Type type = tx.getType(label); if (type == null) throw GraqlQueryException.labelNotFound(label); return type; }).flatMap(Type::subs); if (!scopeIncludesAttributes()) { subTypes = subTypes.filter(relationshipType -> !relationshipType.isImplicit()); } return subTypes; } } /** * Helper method to get the labels of the type in the query scope * * @return a set of Concept Type Labels */ private ImmutableSet<Label> scopeTypeLabels() { return scopeTypes().map(SchemaConcept::label).collect(CommonUtil.toImmutableSet()); } /** * Helper method to check whether the concept types in the scope have any instances * * @return */ private boolean scopeContainsInstance() { if (scopeTypeLabels().isEmpty()) return false; List<Pattern> checkSubtypes = scopeTypeLabels().stream() .map(type -> Graql.var("x").isa(Graql.label(type))).collect(Collectors.toList()); return tx.graql().infer(false).match(Graql.or(checkSubtypes)).iterator().hasNext(); } /** * Helper method to check if concept instances exist in the query scope * * @param ids * @return true if they exist, false if they don't */ private boolean scopeContainsInstances(ConceptId... ids) { for (ConceptId id : ids) { Thing thing = tx.getConcept(id); if (thing == null || !scopeTypeLabels().contains(thing.type().label())) return false; } return true; } /** * Helper method to check whether attribute types should be included in the query scope * * @return true if they exist, false if they don't */ private final boolean scopeIncludesAttributes() { return query.includesAttributes() || scopeIncludesImplicitOrAttributeTypes(); } /** * Helper method to check whether implicit or attribute types are included in the query scope * * @return true if they exist, false if they don't */ private boolean scopeIncludesImplicitOrAttributeTypes() { if (!query.in().isPresent()) return false; return query.in().get().stream().anyMatch(label -> { SchemaConcept type = tx.getSchemaConcept(label); return (type != null && (type.isAttributeType() || type.isImplicit())); }); } /** * Helper method to convert type labels to IDs * * @param labelSet * @return a set of LabelIds */ private Set<LabelId> convertLabelsToIds(Set<Label> labelSet) { return labelSet.stream() .map(tx::convertToId) .filter(LabelId::isValid) .collect(Collectors.toSet()); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/executor/ConceptBuilder.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.executor; import ai.grakn.concept.Attribute; import ai.grakn.concept.AttributeType; import ai.grakn.concept.Concept; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Label; import ai.grakn.concept.Role; import ai.grakn.concept.Rule; import ai.grakn.concept.SchemaConcept; import ai.grakn.concept.Thing; import ai.grakn.concept.Type; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Pattern; import ai.grakn.graql.Var; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.internal.pattern.property.DataTypeProperty; import ai.grakn.graql.internal.pattern.property.IdProperty; import ai.grakn.graql.internal.pattern.property.IsaProperty; import ai.grakn.graql.internal.pattern.property.LabelProperty; import ai.grakn.graql.internal.pattern.property.SubProperty; import ai.grakn.graql.internal.pattern.property.ThenProperty; import ai.grakn.graql.internal.pattern.property.ValueProperty; import ai.grakn.graql.internal.pattern.property.WhenProperty; import ai.grakn.util.CommonUtil; import ai.grakn.util.Schema; import javax.annotation.Nullable; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Function; import static com.google.common.base.Preconditions.checkNotNull; /** * Class for building a {@link Concept}, by providing properties. * <p> * <p> * A {@link ai.grakn.graql.admin.VarProperty} is responsible for inserting itself into the graph. However, * some properties can only operate in <i>combination</i>. For example, to create a {@link Attribute} you need both * an {@link IsaProperty} and a {@link ValueProperty}. * </p> * <p> * Therefore, these properties do not create the {@link Concept} themselves. * instead they provide the necessary information to the {@link ConceptBuilder}, which will create the * {@link Concept} at a later time: * </p> * <pre> * // Executor: * ConceptBuilder builder = ConceptBuilder.of(executor, var); * // IsaProperty: * builder.isa(name); * // ValueProperty: * builder.value("Bob"); * // Executor: * Concept concept = builder.build(); * </pre> * * @author Felix Chapman */ public class ConceptBuilder { private final QueryOperationExecutor executor; private final Var var; /** * A map of parameters that have been specified for this concept. */ private final Map<BuilderParam<?>, Object> preProvidedParams = new HashMap<>(); /** * A set of parameters that were used for building the concept. Modified while executing {@link #build()}. * <p> * This set starts empty. Every time {@link #use(BuilderParam)} or {@link #useOrDefault(BuilderParam, Object)} * is called, the parameter is added to this set. After the concept is built, any parameter not in this set is * considered "unexpected". If it is present in the field {@link #preProvidedParams}, then an error is thrown. * </p> * <p> * <p> * Simplified example of how this operates: * </p> * <p> * <pre> * // preProvidedParams = {LABEL: actor, SUPER_CONCEPT: role, VALUE: "Bob"} * // usedParams = {} * * if (has(LABEL)) { * Label label = expect(LABEL); // usedParams = {LABEL} * // Retrieve SUPER_CONCEPT and adds it to usedParams * SchemaConcept superConcept = expect(SUPER_CONCEPT); // usedParams = {LABEL, SUPER_CONCEPT} * return graph.putEntityType(label).sup(superConcept.asRole()); * } * * // Check for any unexpected parameters * preProvidedParams.forEach((providedParam, value) -> { * if (!usedParams.contains(providedParam)) { * // providedParam = VALUE * // Throws because VALUE was provided, but not used! * } * }); * </pre> */ private final Set<BuilderParam<?>> usedParams = new HashSet<>(); public ConceptBuilder isa(Type type) { return set(TYPE, type); } public ConceptBuilder sub(SchemaConcept superConcept) { return set(SUPER_CONCEPT, superConcept); } public ConceptBuilder isRole() { return set(IS_ROLE, Unit.INSTANCE); } public ConceptBuilder isRule() { return set(IS_RULE, Unit.INSTANCE); } public ConceptBuilder label(Label label) { return set(LABEL, label); } public ConceptBuilder id(ConceptId id) { return set(ID, id); } public ConceptBuilder value(Object value) { return set(VALUE, value); } public ConceptBuilder dataType(AttributeType.DataType<?> dataType) { return set(DATA_TYPE, dataType); } public ConceptBuilder when(Pattern when) { return set(WHEN, when); } public ConceptBuilder then(Pattern then) { return set(THEN, then); } static ConceptBuilder of(QueryOperationExecutor executor, Var var) { return new ConceptBuilder(executor, var); } /** * Build the {@link Concept} and return it, using the properties given. * * @throws GraqlQueryException if the properties provided are inconsistent */ Concept build() { // If a label or ID is provided, attempt to `get` the concept Concept concept = tryGetConcept(); if (concept != null) { return concept; } else { return tryPutConcept(); } } @Nullable private Concept tryGetConcept() { Concept concept = null; if (has(ID)) { concept = executor.tx().getConcept(use(ID)); if (has(LABEL)) { concept.asSchemaConcept().label(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; } 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; } /** * Describes a parameter that can be set on a {@link ConceptBuilder}. * <p> * We could instead just represent these parameters as fields of {@link ConceptBuilder}. Instead, we use a * {@code Map<BuilderParam<?>, Object>}. This allows us to do clever stuff like iterate over the parameters, * or check for unexpected parameters without lots of boilerplate. * </p> */ // The generic is technically unused, but is useful to constrain the values of the parameter @SuppressWarnings("unused") private static final class BuilderParam<T> { private final String name; private BuilderParam(String name) { this.name = name; } String name() { return name; } @Override public String toString() { return name; } static <T> BuilderParam<T> of(String name) { return new BuilderParam<>(name); } } private static final BuilderParam<Type> TYPE = BuilderParam.of(IsaProperty.NAME); private static final BuilderParam<SchemaConcept> SUPER_CONCEPT = BuilderParam.of(SubProperty.NAME); private static final BuilderParam<Label> LABEL = BuilderParam.of(LabelProperty.NAME); private static final BuilderParam<ConceptId> ID = BuilderParam.of(IdProperty.NAME); private static final BuilderParam<Object> VALUE = BuilderParam.of(ValueProperty.NAME); private static final BuilderParam<AttributeType.DataType<?>> DATA_TYPE = BuilderParam.of(DataTypeProperty.NAME); private static final BuilderParam<Pattern> WHEN = BuilderParam.of(WhenProperty.NAME); private static final BuilderParam<Pattern> THEN = BuilderParam.of(ThenProperty.NAME); private static final BuilderParam<Unit> IS_ROLE = BuilderParam.of("role"); private static final BuilderParam<Unit> IS_RULE = BuilderParam.of("rule"); /** * Class with no fields and exactly one instance. * <p> * Similar in use to {@link Void}, but the single instance is {@link Unit#INSTANCE} instead of {@code null}. Useful * when {@code null} is not allowed. * * @see <a href=https://en.wikipedia.org/wiki/Unit_type>Wikipedia</a> */ private static final class Unit { private Unit() { } private static Unit INSTANCE = new Unit(); @Override public String toString() { return ""; } } private ConceptBuilder(QueryOperationExecutor executor, Var var) { this.executor = executor; this.var = var; } private <T> T useOrDefault(BuilderParam<T> param, @Nullable T defaultValue) { usedParams.add(param); // This is safe, assuming we only add to the map with the `set` method //noinspection unchecked T value = (T) preProvidedParams.get(param); if (value == null) value = defaultValue; if (value == null) { throw GraqlQueryException.insertNoExpectedProperty(param.name(), executor.printableRepresentation(var)); } return value; } /** * Called during {@link #build()} whenever a particular parameter is expected in order to build the {@link Concept}. * <p> * This method will return the parameter, if present and also record that it was expected, so that we can later * check for any unexpected properties. * </p> * * @throws GraqlQueryException if the parameter is not present */ private <T> T use(BuilderParam<T> param) { return useOrDefault(param, null); } private boolean has(BuilderParam<?> param) { return preProvidedParams.containsKey(param); } private <T> ConceptBuilder set(BuilderParam<T> param, T value) { if (preProvidedParams.containsKey(param) && !preProvidedParams.get(param).equals(value)) { VarPatternAdmin varPattern = executor.printableRepresentation(var); Object otherValue = preProvidedParams.get(param); throw GraqlQueryException.insertMultipleProperties(varPattern, param.name(), value, otherValue); } preProvidedParams.put(param, checkNotNull(value)); return this; } /** * Check if this pre-existing concept conforms to all specified parameters * * @throws GraqlQueryException if any parameter does not match */ private void validate(Concept concept) { validateParam(concept, TYPE, Thing.class, Thing::type); validateParam(concept, SUPER_CONCEPT, SchemaConcept.class, SchemaConcept::sup); validateParam(concept, LABEL, SchemaConcept.class, SchemaConcept::label); validateParam(concept, ID, Concept.class, Concept::id); validateParam(concept, VALUE, Attribute.class, Attribute::value); validateParam(concept, DATA_TYPE, AttributeType.class, AttributeType::dataType); validateParam(concept, WHEN, Rule.class, Rule::when); validateParam(concept, THEN, Rule.class, Rule::then); } /** * Check if the concept is of the given type and has a property that matches the given parameter. * * @throws GraqlQueryException if the concept does not satisfy the parameter */ private <S extends Concept, T> void validateParam( Concept concept, BuilderParam<T> param, Class<S> conceptType, Function<S, T> getter) { if (has(param)) { T value = use(param); boolean isInstance = conceptType.isInstance(concept); if (!isInstance || !Objects.equals(getter.apply(conceptType.cast(concept)), value)) { throw GraqlQueryException.insertPropertyOnExistingConcept(param.name(), value, concept); } } } private Thing putInstance() { Type type = use(TYPE); if (type.isEntityType()) { return type.asEntityType().create(); } else if (type.isRelationshipType()) { return type.asRelationshipType().create(); } else if (type.isAttributeType()) { return type.asAttributeType().create(use(VALUE)); } else if (type.label().equals(Schema.MetaSchema.THING.getLabel())) { throw GraqlQueryException.createInstanceOfMetaConcept(var, type); } else { throw CommonUtil.unreachableStatement("Can't recognize type " + type); } } private SchemaConcept putSchemaConcept() { SchemaConcept superConcept = use(SUPER_CONCEPT); Label label = use(LABEL); SchemaConcept concept; if (superConcept.isEntityType()) { concept = executor.tx().putEntityType(label); } else if (superConcept.isRelationshipType()) { concept = executor.tx().putRelationshipType(label); } else if (superConcept.isRole()) { concept = executor.tx().putRole(label); } else if (superConcept.isAttributeType()) { AttributeType attributeType = superConcept.asAttributeType(); AttributeType.DataType<?> dataType = useOrDefault(DATA_TYPE, attributeType.dataType()); concept = executor.tx().putAttributeType(label, dataType); } else if (superConcept.isRule()) { concept = executor.tx().putRule(label, use(WHEN), use(THEN)); } else { throw GraqlQueryException.insertMetaType(label, superConcept); } setSuper(concept, superConcept); return concept; } /** * Make the second argument the super of the first argument * * @throws GraqlQueryException if the types are different, or setting the super to be a meta-type */ public static void setSuper(SchemaConcept subConcept, SchemaConcept superConcept) { if (superConcept.isEntityType()) { subConcept.asEntityType().sup(superConcept.asEntityType()); } else if (superConcept.isRelationshipType()) { subConcept.asRelationshipType().sup(superConcept.asRelationshipType()); } else if (superConcept.isRole()) { subConcept.asRole().sup(superConcept.asRole()); } else if (superConcept.isAttributeType()) { subConcept.asAttributeType().sup(superConcept.asAttributeType()); } else if (superConcept.isRule()) { subConcept.asRule().sup(superConcept.asRule()); } else { throw GraqlQueryException.insertMetaType(subConcept.label(), superConcept); } } @Override public String toString() { return "ConceptBuilder{" + "var=" + var + ", preProvidedParams=" + preProvidedParams + ", usedParams=" + usedParams + '}'; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/executor/QueryExecutorImpl.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.executor; import ai.grakn.ComputeExecutor; import ai.grakn.QueryExecutor; import ai.grakn.concept.Concept; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.AggregateQuery; import ai.grakn.graql.ComputeQuery; import ai.grakn.graql.DefineQuery; import ai.grakn.graql.DeleteQuery; import ai.grakn.graql.GetQuery; import ai.grakn.graql.InsertQuery; import ai.grakn.graql.Match; import ai.grakn.graql.UndefineQuery; import ai.grakn.graql.Var; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.answer.Answer; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.answer.ConceptSet; import ai.grakn.graql.internal.util.AdminConverter; import ai.grakn.kb.internal.EmbeddedGraknTx; import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; import java.util.Collection; import java.util.Set; import java.util.stream.Stream; import static ai.grakn.util.CommonUtil.toImmutableList; import static ai.grakn.util.CommonUtil.toImmutableSet; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; /** * A {@link QueryExecutor} that runs queries using a Tinkerpop graph. * * @author Grakn Warriors */ @SuppressWarnings("unused") // accessed via reflection in EmbeddedGraknTx public class QueryExecutorImpl implements QueryExecutor { private final EmbeddedGraknTx<?> tx; private QueryExecutorImpl(EmbeddedGraknTx<?> tx) { this.tx = tx; } public static QueryExecutorImpl create(EmbeddedGraknTx<?> tx) { return new QueryExecutorImpl(tx); } @Override public Stream<ConceptMap> run(GetQuery query) { return query.match().stream().map(result -> result.project(query.vars())).distinct(); } @Override public Stream<ConceptMap> run(InsertQuery query) { Collection<VarPatternAdmin> varPatterns = query.admin().varPatterns().stream() .flatMap(v -> v.innerVarPatterns().stream()) .collect(toImmutableList()); if (query.admin().match() != null) { return runMatchInsert(query.admin().match(), varPatterns); } else { return Stream.of(QueryOperationExecutor.insertAll(varPatterns, tx)); } } private Stream<ConceptMap> runMatchInsert(Match match, Collection<VarPatternAdmin> varPatterns) { Set<Var> varsInMatch = match.admin().getSelectedNames(); Set<Var> varsInInsert = varPatterns.stream().map(VarPatternAdmin::var).collect(toImmutableSet()); Set<Var> projectedVars = Sets.intersection(varsInMatch, varsInInsert); Stream<ConceptMap> answers = match.get(projectedVars).stream(); return answers.map(answer -> QueryOperationExecutor.insertAll(varPatterns, tx, answer)).collect(toList()).stream(); } @Override public Stream<ConceptSet> run(DeleteQuery query) { Stream<ConceptMap> answers = query.admin().match().stream().map(result -> result.project(query.admin().vars())).distinct(); // TODO: We should not need to collect toSet, once we fix ConceptId.id() to not use cache. // Stream.distinct() will then work properly when it calls ConceptImpl.equals() Set<Concept> conceptsToDelete = answers.flatMap(answer -> answer.concepts().stream()).collect(toSet()); conceptsToDelete.forEach(concept -> { if (concept.isSchemaConcept()) { throw GraqlQueryException.deleteSchemaConcept(concept.asSchemaConcept()); } concept.delete(); }); // TODO: return deleted Concepts instead of ConceptIds return Stream.of(new ConceptSet(conceptsToDelete.stream().map(Concept::id).collect(toSet()))); } @Override public Stream<ConceptMap> run(DefineQuery query) { ImmutableList<VarPatternAdmin> allPatterns = AdminConverter.getVarAdmins(query.varPatterns()).stream() .flatMap(v -> v.innerVarPatterns().stream()) .collect(toImmutableList()); ConceptMap defined = QueryOperationExecutor.defineAll(allPatterns, tx); return Stream.of(defined); } @Override public Stream<ConceptMap> run(UndefineQuery query) { ImmutableList<VarPatternAdmin> allPatterns = AdminConverter.getVarAdmins(query.varPatterns()).stream() .flatMap(v -> v.innerVarPatterns().stream()) .collect(toImmutableList()); ConceptMap undefined = QueryOperationExecutor.undefineAll(allPatterns, tx); return Stream.of(undefined); } @Override public <T extends Answer> Stream<T> run(AggregateQuery<T> query) { return query.aggregate().apply(query.match().stream()).stream(); } @Override public <T extends Answer> ComputeExecutor<T> run(ComputeQuery<T> query) { return new ComputeExecutorImpl<>(tx, query); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/executor/QueryOperationExecutor.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.executor; import ai.grakn.GraknTx; import ai.grakn.concept.Concept; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.DefineQuery; import ai.grakn.graql.InsertQuery; import ai.grakn.graql.Query; import ai.grakn.graql.Var; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.admin.VarProperty; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.internal.pattern.Patterns; import ai.grakn.graql.internal.pattern.property.PropertyExecutor; import ai.grakn.graql.internal.pattern.property.VarPropertyInternal; import ai.grakn.graql.internal.query.answer.ConceptMapImpl; import ai.grakn.graql.internal.util.Partition; import com.google.auto.value.AutoValue; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import com.google.common.collect.Sets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.util.ArrayDeque; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Queue; import java.util.Set; import java.util.stream.Stream; import static ai.grakn.util.CommonUtil.toImmutableSet; import static java.util.stream.Collectors.toList; /** * A class for executing {@link PropertyExecutor}s on {@link VarProperty}s within {@link Query}s. * Multiple query types share this class, such as {@link InsertQuery} and {@link DefineQuery}. */ public class QueryOperationExecutor { protected final Logger LOG = LoggerFactory.getLogger(QueryOperationExecutor.class); private final GraknTx tx; // A mutable map associating each `Var` to the `Concept` in the graph it refers to. private final Map<Var, Concept> concepts = new HashMap<>(); // A mutable map of concepts "under construction" that require more information before they can be built private final Map<Var, ConceptBuilder> conceptBuilders = new HashMap<>(); // An immutable set of all properties private final ImmutableSet<VarAndProperty> properties; // A partition (disjoint set) indicating which `Var`s should refer to the same concept private final Partition<Var> equivalentVars; // A map, where `dependencies.containsEntry(x, y)` implies that `y` must be inserted before `x` is inserted. private final ImmutableMultimap<VarAndProperty, VarAndProperty> dependencies; private QueryOperationExecutor(GraknTx tx, ImmutableSet<VarAndProperty> properties, Partition<Var> equivalentVars, ImmutableMultimap<VarAndProperty, VarAndProperty> dependencies) { this.tx = tx; this.properties = properties; this.equivalentVars = equivalentVars; this.dependencies = dependencies; } /** * Insert all the Vars */ static ConceptMap insertAll(Collection<VarPatternAdmin> patterns, GraknTx graph) { return create(patterns, graph, ExecutionType.INSERT).insertAll(new ConceptMapImpl()); } /** * Insert all the Vars * @param results the result after inserting */ static ConceptMap insertAll(Collection<VarPatternAdmin> patterns, GraknTx graph, ConceptMap results) { return create(patterns, graph, ExecutionType.INSERT).insertAll(results); } static ConceptMap defineAll(Collection<VarPatternAdmin> patterns, GraknTx graph) { return create(patterns, graph, ExecutionType.DEFINE).insertAll(new ConceptMapImpl()); } static ConceptMap undefineAll(ImmutableList<VarPatternAdmin> patterns, GraknTx tx) { return create(patterns, tx, ExecutionType.UNDEFINE).insertAll(new ConceptMapImpl()); } private static QueryOperationExecutor create( Collection<VarPatternAdmin> patterns, GraknTx graph, ExecutionType executionType ) { ImmutableSet<VarAndProperty> properties = patterns.stream() .flatMap(pattern -> VarAndProperty.fromPattern(pattern, executionType)) .collect(toImmutableSet()); /* We build several many-to-many relations, indicated by a `Multimap<X, Y>`. These are used to represent the dependencies between properties and variables. `propDependencies.containsEntry(prop, var)` indicates that the property `prop` cannot be inserted until the concept represented by the variable `var` is created. For example, the property `$x isa $y` depends on the existence of the concept represented by `$y`. */ Multimap<VarAndProperty, Var> propDependencies = HashMultimap.create(); for (VarAndProperty property : properties) { for (Var requiredVar : property.executor().requiredVars()) { propDependencies.put(property, requiredVar); } } /* `varDependencies.containsEntry(var, prop)` indicates that the concept represented by the variable `var` cannot be created until the property `prop` is inserted. For example, the concept represented by `$x` will not exist before the property `$x isa $y` is inserted. */ Multimap<Var, VarAndProperty> varDependencies = HashMultimap.create(); for (VarAndProperty property : properties) { for (Var producedVar : property.executor().producedVars()) { varDependencies.put(producedVar, property); } } /* Equivalent vars are variables that must represent the same concept as another var. $X label movie, sub entity; $Y label movie; $z isa $Y; In this example, `$z isa $Y` must not be inserted before `$Y` is. However, `$Y` does not have enough information to insert on its own. It also needs a super type! We know `$Y` must represent the same concept as `$X`, because they both share the same label property. Therefore, we can share their dependencies, such that: varDependencies.containsEntry($X, prop) <=> varDependencies.containsEntry($Y, prop) Therefore: varDependencies.containsEntry($X, `$X sub entity`) => varDependencies.containsEntry($Y, `$X sub entity`) Now we know that `$Y` depends on `$X sub entity` as well as `$X label movie`, which is enough information to insert the type! */ Partition<Var> equivalentVars = Partition.singletons(Collections.emptyList()); equivalentProperties(properties).asMap().values().forEach(vars -> { // These vars must refer to the same concept, so share their dependencies Collection<VarAndProperty> producers = vars.stream().flatMap(var -> varDependencies.get(var).stream()).collect(toList()); Var first = vars.iterator().next(); vars.forEach(var -> { varDependencies.replaceValues(var, producers); equivalentVars.merge(first, var); }); }); /* Together, `propDependencies` and `varDependencies` can be composed into a single many-to-many relation: dependencies = propDependencies ∘ varDependencies By doing so, we map _directly_ between properties, skipping the vars. For example, if we previously had: propDependencies.containsEntry(`$x isa $y`, `$y`); // `$x isa $y` depends on `$y` varDependencies.containsEntry(`$y`, `$y label movie`); // `$y` depends on `$y label movie` Then it follows that: dependencies.containsEntry(`$x isa $y`, `$y label movie`); // `$x isa $y` depends on `$y label movie` The `dependencies` relation contains all the information to decide what order to execute the properties. */ Multimap<VarAndProperty, VarAndProperty> dependencies = composeMultimaps(propDependencies, varDependencies); return new QueryOperationExecutor(graph, properties, equivalentVars, ImmutableMultimap.copyOf(dependencies)); } private static Multimap<VarProperty, Var> equivalentProperties(Set<VarAndProperty> properties) { Multimap<VarProperty, Var> equivalentProperties = HashMultimap.create(); for (VarAndProperty varAndProperty : properties) { if (varAndProperty.uniquelyIdentifiesConcept()) { equivalentProperties.put(varAndProperty.property(), varAndProperty.var()); } } return equivalentProperties; } /** * <a href=https://en.wikipedia.org/wiki/Composition_of_relations>Compose</a> two {@link Multimap}s together, * treating them like many-to-many relations. */ private static <K, T, V> Multimap<K, V> composeMultimaps(Multimap<K, T> map1, Multimap<T, V> map2) { Multimap<K, V> composed = HashMultimap.create(); for (Map.Entry<K, T> entry1 : map1.entries()) { K key = entry1.getKey(); T intermediateValue = entry1.getValue(); for (V value : map2.get(intermediateValue)) { composed.put(key, value); } } return composed; } private ConceptMap insertAll(ConceptMap map) { concepts.putAll(map.map()); for (VarAndProperty property : sortProperties()) { property.executor().execute(this); } conceptBuilders.forEach(this::buildConcept); ImmutableMap.Builder<Var, Concept> allConcepts = ImmutableMap.<Var, Concept>builder().putAll(concepts); // Make sure to include all equivalent vars in the result for (Var var: equivalentVars.getNodes()) { allConcepts.put(var, concepts.get(equivalentVars.componentOf(var))); } Map<Var, Concept> namedConcepts = Maps.filterKeys(allConcepts.build(), Var::isUserDefinedName); return new ConceptMapImpl(namedConcepts); } private Concept buildConcept(Var var, ConceptBuilder builder) { Concept concept = builder.build(); assert concept != null : String.format("build() should never return null. var: %s", var); concepts.put(var, concept); return concept; } /** * Produce a valid ordering of the properties by using the given dependency information. * * <p> * This method uses a topological sort (Kahn's algorithm) in order to find a valid ordering. * </p> */ private ImmutableList<VarAndProperty> sortProperties() { ImmutableList.Builder<VarAndProperty> sorted = ImmutableList.builder(); // invertedDependencies is intended to just be a 'view' on dependencies, so when dependencies is modified // we should always also modify invertedDependencies (and vice-versa). Multimap<VarAndProperty, VarAndProperty> dependencies = HashMultimap.create(this.dependencies); Multimap<VarAndProperty, VarAndProperty> invertedDependencies = HashMultimap.create(); Multimaps.invertFrom(dependencies, invertedDependencies); Queue<VarAndProperty> propertiesWithoutDependencies = new ArrayDeque<>(Sets.filter(properties, property -> dependencies.get(property).isEmpty())); VarAndProperty property; // Retrieve the next property without any dependencies while ((property = propertiesWithoutDependencies.poll()) != null) { sorted.add(property); // We copy this into a new list because the underlying collection gets modified during iteration Collection<VarAndProperty> dependents = Lists.newArrayList(invertedDependencies.get(property)); for (VarAndProperty dependent : dependents) { // Because the property has been removed, the dependent no longer needs to depend on it dependencies.remove(dependent, property); invertedDependencies.remove(property, dependent); boolean hasNoDependencies = dependencies.get(dependent).isEmpty(); if (hasNoDependencies) { propertiesWithoutDependencies.add(dependent); } } } if (!dependencies.isEmpty()) { // This means there must have been a loop. Pick an arbitrary remaining var to display Var var = dependencies.keys().iterator().next().var(); throw GraqlQueryException.insertRecursive(printableRepresentation(var)); } return sorted.build(); } /** * Return a {@link ConceptBuilder} for given {@link Var}. This can be used to provide information for how to create * the concept that the variable represents. * * <p> * This method is expected to be called from implementations of * {@link VarPropertyInternal#insert(Var)}, provided they return the given {@link Var} in the * response to {@link PropertyExecutor#producedVars()}. * </p> * <p> * For example, a property may call {@code executor.builder(var).isa(type);} in order to provide a type for a var. * </p> * * @throws GraqlQueryException if the concept in question has already been created */ public ConceptBuilder builder(Var var) { return tryBuilder(var).orElseThrow(() -> { Concept concept = concepts.get(equivalentVars.componentOf(var)); return GraqlQueryException.insertExistingConcept(printableRepresentation(var), concept); }); } /** * Return a {@link ConceptBuilder} for given {@link Var}. This can be used to provide information for how to create * the concept that the variable represents. * * <p> * This method is expected to be called from implementations of * {@link VarPropertyInternal#insert(Var)}, provided they return the given {@link Var} in the * response to {@link PropertyExecutor#producedVars()}. * </p> * <p> * For example, a property may call {@code executor.builder(var).isa(type);} in order to provide a type for a var. * </p> * <p> * If the concept has already been created, this will return empty. * </p> */ public Optional<ConceptBuilder> tryBuilder(Var var) { var = equivalentVars.componentOf(var); if (concepts.containsKey(var)) { return Optional.empty(); } ConceptBuilder builder = conceptBuilders.get(var); if (builder != null) { return Optional.of(builder); } builder = ConceptBuilder.of(this, var); conceptBuilders.put(var, builder); return Optional.of(builder); } /** * Return a {@link Concept} for a given {@link Var}. * * <p> * This method is expected to be called from implementations of * {@link VarPropertyInternal#insert(Var)}, provided they return the given {@link Var} in the * response to {@link PropertyExecutor#requiredVars()}. * </p> */ public Concept get(Var var) { var = equivalentVars.componentOf(var); assert var != null; @Nullable Concept concept = concepts.get(var); if (concept == null) { @Nullable ConceptBuilder builder = conceptBuilders.remove(var); if (builder != null) { concept = buildConcept(var, builder); } } if (concept != null) { return concept; } LOG.debug("Could not build concept for {}\nconcepts = {}\nconceptBuilders = {}", var, concepts, conceptBuilders); throw GraqlQueryException.insertUndefinedVariable(printableRepresentation(var)); } VarPatternAdmin printableRepresentation(Var var) { ImmutableSet.Builder<VarProperty> propertiesOfVar = ImmutableSet.builder(); // This could be faster if we built a dedicated map Var -> VarPattern // However, this method is only used for displaying errors, so it's not worth the cost for (VarAndProperty vp : properties) { if (vp.var().equals(var)) { propertiesOfVar.add(vp.property()); } } return Patterns.varPattern(var, propertiesOfVar.build()); } GraknTx tx() { return tx; } /** * Represents a pairing of a {@link VarProperty} and its subject {@link Var}. * <p> * e.g. {@code $x} and {@code isa $y}, together are {@code $x isa $y}. * </p> */ @AutoValue static abstract class VarAndProperty { abstract Var var(); abstract VarPropertyInternal property(); abstract PropertyExecutor executor(); private static VarAndProperty of(Var var, VarProperty property, PropertyExecutor executor) { VarPropertyInternal propertyInternal = VarPropertyInternal.from(property); return new AutoValue_QueryOperationExecutor_VarAndProperty(var, propertyInternal, executor); } private static Stream<VarAndProperty> all(Var var, VarProperty property, ExecutionType executionType) { VarPropertyInternal propertyInternal = VarPropertyInternal.from(property); return executionType.executors(propertyInternal, var).stream() .map(executor -> VarAndProperty.of(var, property, executor)); } static Stream<VarAndProperty> fromPattern(VarPatternAdmin pattern, ExecutionType executionType) { return pattern.getProperties().flatMap(prop -> VarAndProperty.all(pattern.var(), prop, executionType)); } boolean uniquelyIdentifiesConcept() { return property().uniquelyIdentifiesConcept(); } } private enum ExecutionType { INSERT { Collection<PropertyExecutor> executors(VarPropertyInternal property, Var var) { return property.insert(var); } }, DEFINE { Collection<PropertyExecutor> executors(VarPropertyInternal property, Var var) { return property.define(var); } }, UNDEFINE { Collection<PropertyExecutor> executors(VarPropertyInternal property, Var var) { return property.undefine(var); } }; abstract Collection<PropertyExecutor> executors(VarPropertyInternal property, Var var); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/match/AbstractMatch.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.match; import ai.grakn.GraknTx; import ai.grakn.graql.Aggregate; import ai.grakn.graql.AggregateQuery; import ai.grakn.graql.DeleteQuery; import ai.grakn.graql.GetQuery; import ai.grakn.graql.Graql; import ai.grakn.graql.InsertQuery; import ai.grakn.graql.Match; import ai.grakn.graql.Order; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.answer.Answer; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.admin.MatchAdmin; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.internal.pattern.property.VarPropertyInternal; import ai.grakn.graql.internal.query.Queries; import ai.grakn.graql.internal.util.AdminConverter; import ai.grakn.kb.internal.EmbeddedGraknTx; import com.google.common.collect.ImmutableMultiset; import com.google.common.collect.ImmutableSet; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import static ai.grakn.graql.Order.asc; @SuppressWarnings("UnusedReturnValue") abstract class AbstractMatch implements MatchAdmin { @Override public final MatchAdmin admin() { return this; } /** * Execute the query using the given graph. * @param tx the graph to use to execute the query * @return a stream of results */ public abstract Stream<ConceptMap> stream(EmbeddedGraknTx<?> tx); @Override public final Stream<ConceptMap> stream() { return stream(null); } /** * @param tx the {@link GraknTx} against which the pattern should be validated */ void validatePattern(GraknTx tx){ for (VarPatternAdmin var : getPattern().varPatterns()) { var.getProperties().forEach(property -> ((VarPropertyInternal) property).checkValid(tx, var));} } @Override public final Match withTx(GraknTx tx) { return new MatchTx(tx, this); } @Override public final Match limit(long limit) { return new MatchLimit(this, limit); } @Override public final Match offset(long offset) { return new MatchOffset(this, offset); } @Override public final <S extends Answer> AggregateQuery<S> aggregate(Aggregate<S> aggregate) { return Queries.aggregate(admin(), aggregate); } @Override public GetQuery get() { return get(getPattern().commonVars()); } @Override public GetQuery get(String var, String... vars) { Set<Var> varSet = Stream.concat(Stream.of(var), Stream.of(vars)).map(Graql::var).collect(Collectors.toSet()); return get(varSet); } @Override public GetQuery get(Var var, Var... vars) { Set<Var> varSet = new HashSet<>(Arrays.asList(vars)); varSet.add(var); return get(varSet); } @Override public GetQuery get(Set<Var> vars) { if (vars.isEmpty()) vars = getPattern().commonVars(); return Queries.get(this, ImmutableSet.copyOf(vars)); } @Override public final InsertQuery insert(VarPattern... vars) { return insert(Arrays.asList(vars)); } @Override public final InsertQuery insert(Collection<? extends VarPattern> vars) { ImmutableMultiset<VarPatternAdmin> varAdmins = ImmutableMultiset.copyOf(AdminConverter.getVarAdmins(vars)); return Queries.insert(admin(), varAdmins); } @Override public DeleteQuery delete() { return delete(getPattern().commonVars()); } @Override public final DeleteQuery delete(String var, String... vars) { Set<Var> varSet = Stream.concat(Stream.of(var), Arrays.stream(vars)).map(Graql::var).collect(Collectors.toSet()); return delete(varSet); } @Override public final DeleteQuery delete(Var var, Var... vars) { Set<Var> varSet = new HashSet<>(Arrays.asList(vars)); varSet.add(var); return delete(varSet); } @Override public final DeleteQuery delete(Set<Var> vars) { if (vars.isEmpty()) vars = getPattern().commonVars(); return Queries.delete(this, vars); } @Override public final Match orderBy(String varName) { return orderBy(varName, asc); } @Override public final Match orderBy(Var varName) { return orderBy(varName, asc); } @Override public final Match orderBy(String varName, Order order) { return orderBy(Graql.var(varName), order); } @Override public final Match orderBy(Var varName, Order order) { return new MatchOrder(this, Ordering.of(varName, order)); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/match/AutoValue_Ordering.java
package ai.grakn.graql.internal.query.match; import ai.grakn.graql.Order; import ai.grakn.graql.Var; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_Ordering extends Ordering { private final Var var; private final Order order; AutoValue_Ordering( Var var, Order order) { if (var == null) { throw new NullPointerException("Null var"); } this.var = var; if (order == null) { throw new NullPointerException("Null order"); } this.order = order; } @Override Var var() { return var; } @Override Order order() { return order; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof Ordering) { Ordering that = (Ordering) o; return (this.var.equals(that.var())) && (this.order.equals(that.order())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.var.hashCode(); h *= 1000003; h ^= this.order.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/match/MatchBase.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.match; import ai.grakn.GraknTx; import ai.grakn.concept.Concept; import ai.grakn.concept.SchemaConcept; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Match; import ai.grakn.graql.Var; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.admin.Conjunction; import ai.grakn.graql.admin.PatternAdmin; import ai.grakn.graql.internal.gremlin.GraqlTraversal; import ai.grakn.graql.internal.gremlin.GreedyTraversalPlan; import ai.grakn.graql.internal.query.answer.ConceptMapImpl; import ai.grakn.kb.internal.EmbeddedGraknTx; import com.google.common.collect.Sets; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Element; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Stream; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toSet; /** * Base {@link Match} implementation that executes the gremlin traversal * * @author Grakn Warriors */ public class MatchBase extends AbstractMatch { protected final Logger LOG = LoggerFactory.getLogger(MatchBase.class); private final Conjunction<PatternAdmin> pattern; /** * @param pattern a pattern to match in the graph */ public MatchBase(Conjunction<PatternAdmin> pattern) { if (pattern.getPatterns().size() == 0) { throw GraqlQueryException.noPatterns(); } this.pattern = pattern; } @Override public Stream<ConceptMap> stream(EmbeddedGraknTx<?> tx) { if (tx == null) throw GraqlQueryException.noTx(); validatePattern(tx); GraqlTraversal graqlTraversal = GreedyTraversalPlan.createTraversal(pattern, tx); return streamWithTraversal(this.getPattern().commonVars(), tx, graqlTraversal); } /** * @param commonVars set of variables of interest * @param tx the graph to get results from * @param graqlTraversal gral traversal corresponding to the provided pattern * @return resulting answer stream */ public static Stream<ConceptMap> streamWithTraversal( Set<Var> commonVars, EmbeddedGraknTx<?> tx, GraqlTraversal graqlTraversal ) { Set<Var> vars = Sets.filter(commonVars, Var::isUserDefinedName); GraphTraversal<Vertex, Map<String, Element>> traversal = graqlTraversal.getGraphTraversal(tx, vars); return traversal.toStream() .map(elements -> makeResults(vars, tx, elements)) .distinct() .sequential() .map(ConceptMapImpl::new); } /** * @param vars set of variables of interest * @param tx the graph to get results from * @param elements a map of vertices and edges where the key is the variable name * @return a map of concepts where the key is the variable name */ private static Map<Var, Concept> makeResults( Set<Var> vars, EmbeddedGraknTx<?> tx, Map<String, Element> elements) { Map<Var, Concept> map = new HashMap<>(); for (Var var : vars) { Element element = elements.get(var.name()); if (element == null) { throw GraqlQueryException.unexpectedResult(var); } else { Concept concept = buildConcept(tx, element); map.put(var, concept); } } return map; } private static Concept buildConcept(EmbeddedGraknTx<?> tx, Element element) { if (element instanceof Vertex) { return tx.buildConcept((Vertex) element); } else { return tx.buildConcept((Edge) element); } } @Override public Set<SchemaConcept> getSchemaConcepts(GraknTx tx) { return pattern.varPatterns().stream() .flatMap(v -> v.innerVarPatterns().stream()) .flatMap(v -> v.getTypeLabels().stream()) .map(tx::<SchemaConcept>getSchemaConcept) .filter(Objects::nonNull) .collect(toSet()); } @Override public Set<SchemaConcept> getSchemaConcepts() { throw GraqlQueryException.noTx(); } @Override public Conjunction<PatternAdmin> getPattern() { return pattern; } @Override public GraknTx tx() { return null; } @Override public final Set<Var> getSelectedNames() { return pattern.commonVars(); } @Override public final Boolean inferring() { return false; } @Override public String toString() { return "match " + pattern.getPatterns().stream().map(p -> p + ";").collect(joining(" ")); } public final Match infer() { return new MatchInfer(this); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MatchBase maps = (MatchBase) o; return pattern.equals(maps.pattern); } @Override public int hashCode() { return pattern.hashCode(); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/match/MatchInfer.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.match; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Match; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.admin.Conjunction; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.internal.reasoner.query.ReasonerQueries; import ai.grakn.graql.internal.reasoner.rule.RuleUtils; import ai.grakn.kb.internal.EmbeddedGraknTx; import java.util.Iterator; import java.util.stream.Stream; /** * Modifier that specifies the graph to execute the {@link Match} with. * * @author Grakn Warriors */ class MatchInfer extends MatchModifier { MatchInfer(AbstractMatch inner) { super(inner); } @Override public Stream<ConceptMap> stream(EmbeddedGraknTx<?> tx) { // If the tx is not embedded, treat it like there is no transaction // TODO: this is dodgy - when queries don't contain transactions this can be fixed EmbeddedGraknTx<?> embeddedTx; if (tx != null) { embeddedTx = tx; } else if (inner.tx() instanceof EmbeddedGraknTx) { embeddedTx = (EmbeddedGraknTx) inner.tx(); } else { throw GraqlQueryException.noTx(); } if (!RuleUtils.hasRules(embeddedTx)) return inner.stream(embeddedTx); validatePattern(embeddedTx); try { Iterator<Conjunction<VarPatternAdmin>> conjIt = getPattern().getDisjunctiveNormalForm().getPatterns().iterator(); Conjunction<VarPatternAdmin> conj = conjIt.next(); ReasonerQuery conjQuery = ReasonerQueries.create(conj, embeddedTx).rewrite(); conjQuery.checkValid(); Stream<ConceptMap> answerStream = conjQuery.isRuleResolvable() ? conjQuery.resolve() : embeddedTx.graql().infer(false).match(conj).stream(); while (conjIt.hasNext()) { conj = conjIt.next(); conjQuery = ReasonerQueries.create(conj, embeddedTx).rewrite(); Stream<ConceptMap> localStream = conjQuery.isRuleResolvable() ? conjQuery.resolve() : embeddedTx.graql().infer(false).match(conj).stream(); answerStream = Stream.concat(answerStream, localStream); } return answerStream.map(result -> result.project(getSelectedNames())); } catch (GraqlQueryException e) { System.err.println(e.getMessage()); return Stream.empty(); } } @Override public final Boolean inferring() { return true; } @Override protected String modifierString() { return ""; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/match/MatchLimit.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.match; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Match; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.kb.internal.EmbeddedGraknTx; import java.util.stream.Stream; /** * "Limit" modifier for {@link Match} that limits the results of a query. * * @author Grakn Warriors */ class MatchLimit extends MatchModifier { private final long limit; MatchLimit(AbstractMatch inner, long limit) { super(inner); if (limit <= 0) { throw GraqlQueryException.nonPositiveLimit(limit); } this.limit = limit; } @Override public Stream<ConceptMap> stream(EmbeddedGraknTx<?> tx) { return inner.stream(tx).limit(limit); } @Override protected String modifierString() { return " limit " + limit + ";"; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/match/MatchModifier.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.match; import ai.grakn.GraknTx; import ai.grakn.concept.SchemaConcept; import ai.grakn.graql.Match; import ai.grakn.graql.Var; import ai.grakn.graql.admin.Conjunction; import ai.grakn.graql.admin.PatternAdmin; import java.util.Set; /** * A {@link Match} implementation, which contains an 'inner' {@link Match}. * * This class behaves like a singly-linked list, referencing another {@link Match} until it reaches a {@link MatchBase}. * * Query modifiers should extend this class and implement a stream() method that modifies the inner query. * * @author Grakn Warriors */ abstract class MatchModifier extends AbstractMatch { final AbstractMatch inner; MatchModifier(AbstractMatch inner) { this.inner = inner; } @Override public final Set<SchemaConcept> getSchemaConcepts(GraknTx tx) { return inner.getSchemaConcepts(tx); } @Override public final Conjunction<PatternAdmin> getPattern() { return inner.getPattern(); } @Override public GraknTx tx() { return inner.tx(); } @Override public Set<SchemaConcept> getSchemaConcepts() { return inner.getSchemaConcepts(); } @Override public final Set<Var> getSelectedNames() { return inner.getSelectedNames(); } /** * @return a string representation of this modifier */ protected abstract String modifierString(); @Override public Boolean inferring() { return inner.inferring(); } @Override public final String toString() { return inner.toString() + modifierString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MatchModifier maps = (MatchModifier) o; return inner.equals(maps.inner); } @Override public int hashCode() { return inner.hashCode(); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/match/MatchOffset.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.match; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Match; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.kb.internal.EmbeddedGraknTx; import java.util.stream.Stream; /** * "Offset" modifier for {@link Match} that offsets (skips) some number of results. * * @author Grakn Warriors */ class MatchOffset extends MatchModifier { private final long offset; MatchOffset(AbstractMatch inner, long offset) { super(inner); if (offset < 0) { throw GraqlQueryException.negativeOffset(offset); } this.offset = offset; } @Override public Stream<ConceptMap> stream(EmbeddedGraknTx<?> tx) { return inner.stream(tx).skip(offset); } @Override protected String modifierString() { return " offset " + offset + ";"; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/match/MatchOrder.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.match; import ai.grakn.graql.Match; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.kb.internal.EmbeddedGraknTx; import java.util.stream.Stream; /** * "Order" modify that orders the underlying {@link Match} * * @author Grakn Warriors */ class MatchOrder extends MatchModifier { private final Ordering order; MatchOrder(AbstractMatch inner, Ordering order) { super(inner); this.order = order; } @Override public Stream<ConceptMap> stream(EmbeddedGraknTx<?> tx) { return order.orderStream(inner.stream(tx)); } @Override protected String modifierString() { return " " + order.toString() + ";"; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/match/MatchTx.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.match; import ai.grakn.GraknTx; import ai.grakn.concept.SchemaConcept; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Match; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.kb.internal.EmbeddedGraknTx; import java.util.Set; import java.util.stream.Stream; /** * Modifier that specifies the graph to execute the {@link Match} with. * * @author Grakn Warriors */ class MatchTx extends MatchModifier { private final GraknTx tx; MatchTx(GraknTx tx, AbstractMatch inner) { super(inner); this.tx = tx; } @Override public Stream<ConceptMap> stream(EmbeddedGraknTx<?> tx) { // TODO: This is dodgy. We need to refactor the code to remove this behavior if (tx != null) throw GraqlQueryException.multipleTxs(); // TODO: This cast is unsafe - this is fixed if queries don't contain transactions return inner.stream((EmbeddedGraknTx<?>) this.tx); } @Override public GraknTx tx() { return tx; } @Override public Set<SchemaConcept> getSchemaConcepts() { return inner.getSchemaConcepts(tx); } @Override protected String modifierString() { return ""; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; MatchTx maps = (MatchTx) o; return tx.equals(maps.tx); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + tx.hashCode(); return result; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/match/Ordering.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.match; import ai.grakn.graql.Match; import ai.grakn.graql.Order; import ai.grakn.graql.Var; import ai.grakn.graql.answer.ConceptMap; import com.google.auto.value.AutoValue; import java.util.Comparator; import java.util.stream.Stream; /** * A class for handling ordering {@link Match}es. * * @author Felix Chapman */ @AutoValue abstract class Ordering { abstract Var var(); abstract Order order(); static Ordering of(Var var, Order order) { return new AutoValue_Ordering(var, order); } /** * Order the stream * @param stream the stream to order */ Stream<ConceptMap> orderStream(Stream<ConceptMap> stream) { return stream.sorted(comparator()); } private Comparator<ConceptMap> comparator() { Comparator<ConceptMap> comparator = Comparator.comparing(this::getOrderValue); return (order() == Order.desc) ? comparator.reversed() : comparator; } // All data types are comparable, so this is safe @SuppressWarnings("unchecked") private Comparable<? super Comparable> getOrderValue(ConceptMap result) { return (Comparable<? super Comparable>) result.get(var()).asAttribute().value(); } @Override public String toString() { return "order by " + var() + " "; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/predicate/AutoValue_RegexPredicate.java
package ai.grakn.graql.internal.query.predicate; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_RegexPredicate extends RegexPredicate { private final String pattern; AutoValue_RegexPredicate( String pattern) { if (pattern == null) { throw new NullPointerException("Null pattern"); } this.pattern = pattern; } @Override String pattern() { return pattern; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof RegexPredicate) { RegexPredicate that = (RegexPredicate) o; return (this.pattern.equals(that.pattern())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.pattern.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/predicate/ComparatorPredicate.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.predicate; import ai.grakn.concept.AttributeType.DataType; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.ValuePredicate; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.util.Schema; import ai.grakn.util.StringUtil; import org.apache.tinkerpop.gremlin.process.traversal.P; import org.apache.tinkerpop.gremlin.process.traversal.Traversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; import java.util.Optional; import java.util.UUID; import java.util.stream.Stream; abstract class ComparatorPredicate implements ValuePredicate { // Exactly one of these fields will be present private final Optional<Object> value; private final Optional<VarPatternAdmin> var; private static final String[] VALUE_PROPERTIES = DataType.SUPPORTED_TYPES.values().stream() .map(DataType::getVertexProperty) .distinct() .map(Enum::name) .toArray(String[]::new); /** * @param value the value that this predicate is testing against */ ComparatorPredicate(Object value) { if (value instanceof VarPattern) { this.value = Optional.empty(); this.var = Optional.of(((VarPattern) value).admin()); } else { // Convert integers to longs for consistency if (value instanceof Integer) { value = ((Integer) value).longValue(); } this.value = Optional.of(value); this.var = Optional.empty(); } } /** * @param var the variable that this predicate is testing against */ ComparatorPredicate(VarPattern var) { this.value = Optional.empty(); this.var = Optional.of(var.admin()); } protected abstract String getSymbol(); abstract <V> P<V> gremlinPredicate(V value); final Optional<Object> persistedValue() { return value().map(value -> { // Convert values to how they are stored in the graph DataType dataType = DataType.SUPPORTED_TYPES.get(value.getClass().getName()); if (dataType == null) { throw GraqlQueryException.invalidValueClass(value); } // We can trust the `SUPPORTED_TYPES` map to store things with the right type //noinspection unchecked return dataType.getPersistenceValue(value); }); } final Optional<Object> value() { return value; } public String toString() { // If there is no value, then there must be a var //noinspection OptionalGetWithoutIsPresent String argument = persistedValue().map(StringUtil::valueToString).orElseGet(() -> var.get().getPrintableName()); return getSymbol() + " " + argument; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ComparatorPredicate that = (ComparatorPredicate) o; return persistedValue().equals(that.persistedValue()); } @Override public boolean isCompatibleWith(ValuePredicate predicate) { ComparatorPredicate that = (ComparatorPredicate) predicate; Object val = this.value().orElse(null); Object thatVal = that.value().orElse(null); if (val == null || thatVal == null) return true; //checks for !=/= contradiction return ((!val.equals(thatVal)) || ((!(this instanceof EqPredicate) || !(that instanceof NeqPredicate)) && (!(that instanceof NeqPredicate) || !(this instanceof EqPredicate)))) && (this.gremlinPredicate(val).test(thatVal) || that.gremlinPredicate(thatVal).test(val)); } @Override public int hashCode() { return persistedValue().hashCode(); } @Override public Optional<P<Object>> getPredicate() { return persistedValue().map(this::gremlinPredicate); } @Override public Optional<VarPatternAdmin> getInnerVar() { return var; } @Override public final <S, E> GraphTraversal<S, E> applyPredicate(GraphTraversal<S, E> traversal) { var.ifPresent(theVar -> { // Compare to another variable String thisVar = UUID.randomUUID().toString(); Var otherVar = theVar.var(); String otherValue = UUID.randomUUID().toString(); Traversal[] traversals = Stream.of(VALUE_PROPERTIES) .map(prop -> __.values(prop).as(otherValue).select(thisVar).values(prop).where(gremlinPredicate(otherValue))) .toArray(Traversal[]::new); traversal.as(thisVar).select(otherVar.name()).or(traversals).select(thisVar); }); persistedValue().ifPresent(theValue -> { // Compare to a given value DataType<?> dataType = DataType.SUPPORTED_TYPES.get(value().get().getClass().getTypeName()); Schema.VertexProperty property = dataType.getVertexProperty(); traversal.has(property.name(), gremlinPredicate(theValue)); }); return traversal; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/predicate/ContainsPredicate.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.predicate; import ai.grakn.graql.admin.VarPatternAdmin; import org.apache.tinkerpop.gremlin.process.traversal.P; class ContainsPredicate extends ComparatorPredicate { /** * @param substring the value that this predicate is testing against */ ContainsPredicate(String substring) { super(substring); } /** * @param var the variable that this predicate is testing against */ ContainsPredicate(VarPatternAdmin var) { super(var); } @Override protected String getSymbol() { return "contains"; } @Override <V> P<V> gremlinPredicate(V value) { return new P<>((v, s) -> ((String) v).contains((String) s), value); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/predicate/EqPredicate.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.predicate; import ai.grakn.util.StringUtil; import org.apache.tinkerpop.gremlin.process.traversal.P; import java.util.Optional; class EqPredicate extends ComparatorPredicate { /** * @param value the value that this predicate is testing against */ EqPredicate(Object value) { super(value); } @Override protected String getSymbol() { return "=="; } @Override <V> P<V> gremlinPredicate(V value) { return P.eq(value); } @Override public boolean isSpecific() { return !getInnerVar().isPresent(); } @Override public String toString() { Optional<Object> value = value(); if (value.isPresent()) { // Omit the `=` if we're using a literal value, not a var return StringUtil.valueToString(value.get()); } else { return super.toString(); } } @Override public Optional<Object> equalsValue() { return value(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return super.equals(o); } @Override public int hashCode() { return super.hashCode() + 37; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/predicate/GtPredicate.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.predicate; import org.apache.tinkerpop.gremlin.process.traversal.P; class GtPredicate extends ComparatorPredicate { /** * @param value the value that this predicate is testing against */ GtPredicate(Object value) { super(value); } @Override protected String getSymbol() { return ">"; } @Override <V> P<V> gremlinPredicate(V value) { return P.gt(value); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/predicate/GtePredicate.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.predicate; import org.apache.tinkerpop.gremlin.process.traversal.P; class GtePredicate extends ComparatorPredicate { /** * @param value the value that this predicate is testing against */ GtePredicate(Object value) { super(value); } @Override protected String getSymbol() { return ">="; } @Override <V> P<V> gremlinPredicate(V value) { return P.gte(value); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/predicate/LtPredicate.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.predicate; import org.apache.tinkerpop.gremlin.process.traversal.P; class LtPredicate extends ComparatorPredicate { /** * @param value the value that this predicate is testing against */ LtPredicate(Object value) { super(value); } @Override protected String getSymbol() { return "<"; } @Override <V> P<V> gremlinPredicate(V value) { return P.lt(value); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/predicate/LtePredicate.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.predicate; import org.apache.tinkerpop.gremlin.process.traversal.P; class LtePredicate extends ComparatorPredicate { /** * @param value the value that this predicate is testing against */ LtePredicate(Object value) { super(value); } @Override protected String getSymbol() { return "<="; } @Override <V> P<V> gremlinPredicate(V value) { return P.lte(value); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/predicate/NeqPredicate.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.predicate; import org.apache.tinkerpop.gremlin.process.traversal.P; class NeqPredicate extends ComparatorPredicate { /** * @param value the value that this predicate is testing against */ NeqPredicate(Object value) { super(value); } @Override protected String getSymbol() { return "!=="; } @Override <V> P<V> gremlinPredicate(V value) { return P.neq(value); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/predicate/Predicates.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.predicate; import ai.grakn.graql.ValuePredicate; import ai.grakn.graql.admin.VarPatternAdmin; /** * Factory method for {@link ValuePredicate} implementations. * * @author Felix Chapman */ public class Predicates { private Predicates() {} public static ValuePredicate regex(String pattern) { return RegexPredicate.of(pattern); } public static ValuePredicate neq(Object value) { return new NeqPredicate(value); } public static ValuePredicate lt(Object value) { return new LtPredicate(value); } public static ValuePredicate lte(Object value) { return new LtePredicate(value); } public static ValuePredicate gt(Object value) { return new GtPredicate(value); } public static ValuePredicate gte(Object value) { return new GtePredicate(value); } public static ValuePredicate eq(Object value) { return new EqPredicate(value); } public static ValuePredicate contains(String substring) { return new ContainsPredicate(substring); } public static ValuePredicate contains(VarPatternAdmin var) { return new ContainsPredicate(var); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/query/predicate/RegexPredicate.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.query.predicate; import ai.grakn.graql.ValuePredicate; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.util.Schema; import com.google.auto.value.AutoValue; import org.apache.tinkerpop.gremlin.process.traversal.P; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import java.util.Optional; import java.util.function.BiPredicate; import java.util.regex.Pattern; @AutoValue abstract class RegexPredicate implements ValuePredicate { abstract String pattern(); /** * @param pattern the regex pattern that this predicate is testing against */ static RegexPredicate of(String pattern) { return new AutoValue_RegexPredicate(pattern); } private P<Object> regexPredicate() { BiPredicate<Object, Object> predicate = (value, p) -> Pattern.matches((String) p, (String) value); return new P<>(predicate, pattern()); } @Override public Optional<P<Object>> getPredicate() { return Optional.of(regexPredicate()); } @Override public Optional<VarPatternAdmin> getInnerVar() { return Optional.empty(); } @Override public <S, E> GraphTraversal<S, E> applyPredicate(GraphTraversal<S, E> traversal) { return traversal.has(Schema.VertexProperty.VALUE_STRING.name(), regexPredicate()); } @Override public String toString() { return "/" + pattern().replaceAll("/", "\\\\/") + "/"; } @Override public boolean isCompatibleWith(ValuePredicate predicate){ if (!(predicate instanceof EqPredicate)) return false; EqPredicate p = (EqPredicate) predicate; Object pVal = p.equalsValue().orElse(null); return pVal == null || regexPredicate().test(pVal); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/MultiUnifierImpl.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Var; import ai.grakn.graql.admin.MultiUnifier; import ai.grakn.graql.admin.Unifier; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.UnmodifiableIterator; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nonnull; /** * * <p> * Implementation of the {@link MultiUnifier} interface. * * Special cases: * * Identity unifier: contains a single trivial unifier. * Unifier doesn't exist: unifier is an empty set. * * </p> * * @author Kasper Piskorski * */ public class MultiUnifierImpl implements MultiUnifier{ private final ImmutableSet<Unifier> multiUnifier; public MultiUnifierImpl(Set<Unifier> us){ this.multiUnifier = ImmutableSet.copyOf(us); } public MultiUnifierImpl(Unifier u){ this.multiUnifier = ImmutableSet.of(u); } /** * identity multiunifier: single trivial unifier */ public MultiUnifierImpl(){ this.multiUnifier = ImmutableSet.of(new UnifierImpl()); } public static MultiUnifierImpl trivial(){ return new MultiUnifierImpl();} public static MultiUnifierImpl nonExistent(){ return new MultiUnifierImpl(new HashSet<>());} @SafeVarargs MultiUnifierImpl(ImmutableMultimap<Var, Var>... maps){ this.multiUnifier = ImmutableSet.<Unifier>builder() .addAll(Stream.of(maps).map(UnifierImpl::new).iterator()) .build(); } @Override public boolean equals(Object obj){ if (obj == null || this.getClass() != obj.getClass()) return false; if (obj == this) return true; MultiUnifierImpl u2 = (MultiUnifierImpl) obj; return this.multiUnifier.equals(u2.multiUnifier); } @Override public int hashCode(){ return multiUnifier.hashCode(); } @Override public String toString(){ return multiUnifier.toString(); } @Override public Stream<Unifier> stream() { return multiUnifier.stream(); } @Nonnull @Override public Iterator<Unifier> iterator() { return multiUnifier.iterator(); } @Override public Unifier getUnifier() { return Iterables.getOnlyElement(multiUnifier); } @Override public Unifier getAny() { //TODO add a check it's a structural one UnmodifiableIterator<Unifier> iterator = multiUnifier.iterator(); if (!iterator.hasNext()){ throw GraqlQueryException.nonExistentUnifier(); } return iterator.next(); } @Override public ImmutableSet<Unifier> unifiers() { return multiUnifier;} @Override public boolean isEmpty() { return multiUnifier.isEmpty(); } public boolean contains(Unifier u2) { return unifiers().stream().anyMatch(u -> u.containsAll(u2)); } @Override public boolean containsAll(MultiUnifier mu) { return mu.unifiers().stream() .allMatch(this::contains); } @Override public MultiUnifier inverse() { return new MultiUnifierImpl( multiUnifier.stream() .map(Unifier::inverse) .collect(Collectors.toSet()) ); } @Override public int size() { return multiUnifier.size(); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/ResolutionIterator.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.internal.query.answer.ConceptMapImpl; import ai.grakn.graql.internal.reasoner.cache.SimpleQueryCache; import ai.grakn.graql.internal.reasoner.iterator.ReasonerQueryIterator; import ai.grakn.graql.internal.reasoner.query.ReasonerAtomicQuery; import ai.grakn.graql.internal.reasoner.query.ReasonerQueryImpl; import ai.grakn.graql.internal.reasoner.state.ResolutionState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashSet; import java.util.NoSuchElementException; import java.util.Set; import java.util.Stack; /** * * <p> * Iterator for query answers maintaining the iterative behaviour of the QSQ scheme. * </p> * * @author Kasper Piskorski * */ public class ResolutionIterator extends ReasonerQueryIterator { private int iter = 0; private long oldAns = 0; private final ReasonerQueryImpl query; private final Set<ConceptMap> answers = new HashSet<>(); private final SimpleQueryCache<ReasonerAtomicQuery> cache = new SimpleQueryCache<>(); private final Stack<ResolutionState> states = new Stack<>(); private ConceptMap nextAnswer = null; private final boolean reiterationRequired; private static final Logger LOG = LoggerFactory.getLogger(ResolutionIterator.class); public ResolutionIterator(ReasonerQueryImpl q){ this.query = q; this.reiterationRequired = q.requiresReiteration(); states.push(query.subGoal(new ConceptMapImpl(), new UnifierImpl(), null, new HashSet<>(), cache)); } private ConceptMap findNextAnswer(){ while(!states.isEmpty()) { ResolutionState state = states.pop(); LOG.trace("state: " + state); if (state.isAnswerState() && state.isTopState()) { return state.getSubstitution(); } ResolutionState newState = state.generateSubGoal(); if (newState != null) { if (!state.isAnswerState()) states.push(state); states.push(newState); } else { LOG.trace("new state: NULL"); } } return null; } @Override public ConceptMap next(){ if (nextAnswer == null) throw new NoSuchElementException(); answers.add(nextAnswer); return nextAnswer; } /** * check whether answers available, if answers not fully computed compute more answers * @return true if answers available */ @Override public boolean hasNext() { nextAnswer = findNextAnswer(); if (nextAnswer != null) return true; //iter finished if (reiterationRequired) { long dAns = answers.size() - oldAns; if (dAns != 0 || iter == 0) { LOG.debug("iter: " + iter + " answers: " + answers.size() + " dAns = " + dAns); iter++; states.push(query.subGoal(new ConceptMapImpl(), new UnifierImpl(), null, new HashSet<>(), cache)); oldAns = answers.size(); return hasNext(); } } return false; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/UnifierImpl.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner; import ai.grakn.graql.Var; import ai.grakn.graql.admin.Unifier; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import java.util.AbstractMap; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * * <p> * Implementation of the {@link Unifier} interface. * </p> * * @author Kasper Piskorski * */ public class UnifierImpl implements Unifier { private final ImmutableSetMultimap<Var, Var> unifier; /** * Identity unifier. */ public UnifierImpl(){ this.unifier = ImmutableSetMultimap.of(); } public UnifierImpl(ImmutableMultimap<Var, Var> map){ this(map.entries());} public UnifierImpl(Multimap<Var, Var> map){ this(map.entries());} public UnifierImpl(Map<Var, Var> map){ this(map.entrySet());} private UnifierImpl(Collection<Map.Entry<Var, Var>> mappings){ this.unifier = ImmutableSetMultimap.<Var, Var>builder().putAll(mappings).build(); } public static UnifierImpl trivial(){return new UnifierImpl();} public static UnifierImpl nonExistent(){ return null;} @Override public String toString(){ return unifier.toString(); } @Override public boolean equals(Object obj){ if (obj == null || this.getClass() != obj.getClass()) return false; if (obj == this) return true; UnifierImpl u2 = (UnifierImpl) obj; return this.unifier.equals(u2.unifier); } @Override public int hashCode(){ return unifier.hashCode(); } @Override public boolean isEmpty() { return unifier.isEmpty(); } @Override public Set<Var> keySet() { return unifier.keySet(); } @Override public Collection<Var> values() { return unifier.values(); } @Override public ImmutableSet<Map.Entry<Var, Var>> mappings(){ return unifier.entries();} @Override public Collection<Var> get(Var key) { return unifier.get(key); } @Override public boolean containsKey(Var key) { return unifier.containsKey(key); } @Override public boolean containsAll(Unifier u) { return mappings().containsAll(u.mappings());} @Override public Unifier merge(Unifier d) { return new UnifierImpl( Sets.union( this.mappings(), d.mappings()) ); } @Override public Unifier inverse() { return new UnifierImpl( unifier.entries().stream() .map(e -> new AbstractMap.SimpleImmutableEntry<>(e.getValue(), e.getKey())) .collect(Collectors.toSet()) ); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/UnifierType.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner; import ai.grakn.concept.SchemaConcept; import ai.grakn.concept.Type; import ai.grakn.graql.Var; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.UnifierComparison; import ai.grakn.graql.internal.reasoner.atom.binary.ResourceAtom; import ai.grakn.graql.internal.reasoner.query.ReasonerQueryEquivalence; import java.util.HashMap; import java.util.Map; import java.util.Set; import static ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.areDisjointTypes; import static ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.isEquivalentCollection; /** * * <p> * Class defining different unifier types. * </p> * * @author Kasper Piskorski * */ public enum UnifierType implements UnifierComparison { /** * * Exact unifier, requires type and id predicate bindings to match. * Used in {@link ai.grakn.graql.internal.reasoner.cache.QueryCache} comparisons. * An EXACT unifier between two queries can only exists iff they are alpha-equivalent {@link ai.grakn.graql.internal.reasoner.query.ReasonerQueryEquivalence}. * . */ EXACT { private final ReasonerQueryEquivalence equivalence = ReasonerQueryEquivalence.AlphaEquivalence; @Override public boolean typePlayability(ReasonerQuery query, Var var, Type type) { return true; } @Override public boolean typeCompatibility(SchemaConcept parent, SchemaConcept child) { return !areDisjointTypes(parent, child); } @Override public boolean idCompatibility(Atomic parent, Atomic child) { return (parent == null && child == null) || (parent != null && equivalence.atomicEquivalence().equivalent(parent, child)); } @Override public boolean valueCompatibility(Atomic parent, Atomic child) { return (parent == null && child == null) || (parent != null && equivalence.atomicEquivalence().equivalent(parent, child)); } @Override public boolean attributeValueCompatibility(Set<Atomic> parent, Set<Atomic> child) { return isEquivalentCollection(parent, child, this::valueCompatibility); } }, /** * * Similar to the exact one with addition to allowing id predicates to differ. * Used in {@link ai.grakn.graql.internal.reasoner.cache.StructuralCache} comparisons. * A STRUCTURAL unifier between two queries can only exists iff they are structurally-equivalent {@link ai.grakn.graql.internal.reasoner.query.ReasonerQueryEquivalence}. * */ STRUCTURAL { private final ReasonerQueryEquivalence equivalence = ReasonerQueryEquivalence.StructuralEquivalence; @Override public boolean typePlayability(ReasonerQuery query, Var var, Type type) { return true; } @Override public boolean typeCompatibility(SchemaConcept parent, SchemaConcept child) { return ((child == null ) == (parent == null)) && !areDisjointTypes(parent, child); } @Override public boolean idCompatibility(Atomic parent, Atomic child) { return (parent == null) == (child == null); } @Override public boolean valueCompatibility(Atomic parent, Atomic child) { return (parent == null && child == null) || (parent != null && equivalence.atomicEquivalence().equivalent(parent, child)); } @Override public boolean attributeValueCompatibility(Set<Atomic> parent, Set<Atomic> child) { return isEquivalentCollection(parent, child, this::valueCompatibility); } }, /** * * Rule unifier, found between queries and rule heads, allows rule heads to be more specific than matched queries. * Used in rule matching. * * If two queries are alpha-equivalent they are rule-unifiable. * Rule unification relaxes restrictions of exact unification in that it merely * requires an existence of a semantic overlap between the parent and child queries, i. e. * the answer set of the child and the parent queries need to have a non-zero intersection. * * For predicates it corresponds to changing the alpha-equivalence requirement to compatibility. * * As a result, two queries may be rule-unifiable and not alpha-equivalent, e.q. * * P: $x has age >= 10 * Q: $x has age 10 * */ RULE { @Override public boolean typePlayability(ReasonerQuery query, Var var, Type type) { return query.isTypeRoleCompatible(var, type); } @Override public boolean typeCompatibility(SchemaConcept parent, SchemaConcept child) { return child == null || !areDisjointTypes(parent, child); } @Override public boolean idCompatibility(Atomic parent, Atomic child) { return child == null || parent == null || parent.isCompatibleWith(child); } @Override public boolean valueCompatibility(Atomic parent, Atomic child) { return child == null || parent == null || parent.isCompatibleWith(child); } @Override public boolean attributeValueCompatibility(Set<Atomic> parent, Set<Atomic> child) { return parent.isEmpty() || child.stream().allMatch(cp -> parent.stream().anyMatch(pp -> valueCompatibility(pp, cp))); } @Override public boolean attributeCompatibility(ReasonerQuery parent, ReasonerQuery child, Var parentVar, Var childVar){ Map<SchemaConcept, ResourceAtom> parentRes = new HashMap<>(); parent.getAtoms(ResourceAtom.class).filter(at -> at.getVarName().equals(parentVar)).forEach(r -> parentRes.put(r.getSchemaConcept(), r)); Map<SchemaConcept, ResourceAtom> childRes = new HashMap<>(); child.getAtoms(ResourceAtom.class).filter(at -> at.getVarName().equals(childVar)).forEach(r -> childRes.put(r.getSchemaConcept(), r)); return childRes.values().stream() .allMatch(r -> !parentRes.containsKey(r.getSchemaConcept()) || r.isUnifiableWith(parentRes.get(r.getSchemaConcept()))); } } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/Atom.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.atom; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Rule; import ai.grakn.concept.SchemaConcept; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Var; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.MultiUnifier; import ai.grakn.graql.admin.Unifier; import ai.grakn.graql.admin.UnifierComparison; import ai.grakn.graql.admin.VarProperty; import ai.grakn.graql.internal.pattern.property.IsaExplicitProperty; import ai.grakn.graql.internal.query.answer.ConceptMapImpl; import ai.grakn.graql.internal.reasoner.MultiUnifierImpl; import ai.grakn.graql.internal.reasoner.atom.binary.IsaAtom; import ai.grakn.graql.internal.reasoner.atom.binary.OntologicalAtom; import ai.grakn.graql.internal.reasoner.atom.binary.RelationshipAtom; import ai.grakn.graql.internal.reasoner.atom.binary.ResourceAtom; import ai.grakn.graql.internal.reasoner.atom.binary.TypeAtom; import ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate; import ai.grakn.graql.internal.reasoner.atom.predicate.Predicate; import ai.grakn.graql.internal.reasoner.rule.InferenceRule; import ai.grakn.graql.internal.reasoner.rule.RuleUtils; import ai.grakn.util.ErrorMessage; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Stream; import javax.annotation.Nullable; import static ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.typesCompatible; import static java.util.stream.Collectors.toSet; /** * * <p> * {@link AtomicBase} extension defining specialised functionalities. * </p> * * @author Kasper Piskorski * */ public abstract class Atom extends AtomicBase { //NB: protected to be able to assign it when copying protected Set<InferenceRule> applicableRules = null; public RelationshipAtom toRelationshipAtom(){ throw GraqlQueryException.illegalAtomConversion(this, RelationshipAtom.class); } public IsaAtom toIsaAtom(){ throw GraqlQueryException.illegalAtomConversion(this, IsaAtom.class); } public abstract boolean isUnifiableWith(Atom atom); @Override public boolean isAtom(){ return true;} public boolean isRuleResolvable() { return getApplicableRules().findFirst().isPresent(); } public boolean isRecursive(){ if (isResource() || getSchemaConcept() == null) return false; SchemaConcept schemaConcept = getSchemaConcept(); return getApplicableRules() .filter(rule -> rule.getBody().selectAtoms() .filter(at -> Objects.nonNull(at.getSchemaConcept())) .anyMatch(at -> typesCompatible(schemaConcept, at.getSchemaConcept()))) .anyMatch(this::isRuleApplicable); } /** * @return true if the atom is ground (all variables are bound) */ public boolean isGround(){ Set<Var> mappedVars = Stream.concat(getPredicates(), getInnerPredicates()) .map(AtomicBase::getVarName) .collect(toSet()); return getVarNames().stream() .allMatch(mappedVars::contains); } /** * @return true if this atom is bounded - via substitution/specific resource or schema */ public boolean isBounded(){ return isResource() && ((ResourceAtom) this).isSpecific() || this instanceof OntologicalAtom || isGround(); } /** * @return true if this atom is disconnected (doesn't have neighbours) */ public boolean isDisconnected(){ return isSelectable() && getParentQuery().getAtoms(Atom.class) .filter(Atomic::isSelectable) .filter(at -> !at.equals(this)) .allMatch(at -> Sets.intersection(at.getVarNames(), this.getVarNames()).isEmpty()); } /** * @return true if this atom requires direct schema lookups */ public boolean requiresSchema(){ return getSchemaConcept() == null || this instanceof OntologicalAtom; } public abstract Class<? extends VarProperty> getVarPropertyClass(); @Override public Set<String> validateAsRuleHead(Rule rule){ Set<String> errors = new HashSet<>(); Set<Atomic> parentAtoms = getParentQuery().getAtoms(Atomic.class).filter(at -> !at.equals(this)).collect(toSet()); Set<Var> varNames = Sets.difference( getVarNames(), this.getInnerPredicates().map(Atomic::getVarName).collect(toSet()) ); boolean unboundVariables = varNames.stream() .anyMatch(var -> parentAtoms.stream().noneMatch(at -> at.getVarNames().contains(var))); if (unboundVariables) { errors.add(ErrorMessage.VALIDATION_RULE_ILLEGAL_HEAD_ATOM_WITH_UNBOUND_VARIABLE.getMessage(rule.then(), rule.label())); } SchemaConcept schemaConcept = getSchemaConcept(); if (schemaConcept == null){ errors.add(ErrorMessage.VALIDATION_RULE_ILLEGAL_HEAD_ATOM_WITH_AMBIGUOUS_SCHEMA_CONCEPT.getMessage(rule.then(), rule.label())); } else if (schemaConcept.isImplicit()){ errors.add(ErrorMessage.VALIDATION_RULE_ILLEGAL_HEAD_ATOM_WITH_IMPLICIT_SCHEMA_CONCEPT.getMessage(rule.then(), rule.label())); } return errors; } /** * @return var properties this atom (its pattern) contains */ public Stream<VarProperty> getVarProperties(){ return getCombinedPattern().admin().varPatterns().stream().flatMap(vp -> vp.getProperties(getVarPropertyClass())); } /** * @return partial substitutions for this atom (NB: instances) */ public Stream<IdPredicate> getPartialSubstitutions(){ return Stream.empty();} /** * @return set of variables that need to be have their roles expanded */ public Set<Var> getRoleExpansionVariables(){ return new HashSet<>();} private boolean isRuleApplicable(InferenceRule child){ return isRuleApplicableViaAtom(child.getRuleConclusionAtom()); } protected abstract boolean isRuleApplicableViaAtom(Atom headAtom); /** * @return set of potentially applicable rules - does shallow (fast) check for applicability */ public Stream<Rule> getPotentialRules(){ boolean isDirect = getPattern().admin().getProperties(IsaExplicitProperty.class).findFirst().isPresent(); return getPossibleTypes().stream() .flatMap(type -> RuleUtils.getRulesWithType(type, isDirect, tx())) .distinct(); } /** * @return set of applicable rules - does detailed (slow) check for applicability */ public Stream<InferenceRule> getApplicableRules() { if (applicableRules == null) { applicableRules = new HashSet<>(); getPotentialRules() .map(rule -> tx().ruleCache().getRule(rule, () -> new InferenceRule(rule, tx()))) .filter(this::isRuleApplicable) .map(r -> r.rewrite(this)) .forEach(applicableRules::add); } return applicableRules.stream(); } /** * @return true if the atom requires materialisation in order to be referenced */ public boolean requiresMaterialisation(){ return false; } /** * @return true if the atom requires role expansion */ public boolean requiresRoleExpansion(){ return false; } /** * @return if this atom requires decomposition into a set of atoms */ public boolean requiresDecomposition(){ return this.getPotentialRules() .map(r -> tx().ruleCache().getRule(r, () -> new InferenceRule(r, tx()))) .anyMatch(InferenceRule::isAppendRule); } /** * @return corresponding type if any */ public abstract SchemaConcept getSchemaConcept(); /** * @return type id of the corresponding type if any */ public abstract ConceptId getTypeId(); /** * @return value variable name */ public abstract Var getPredicateVariable(); public abstract Stream<Predicate> getInnerPredicates(); /** * @param type the class of {@link Predicate} to return * @param <T> the type of {@link Predicate} to return * @return stream of predicates relevant to this atom */ public <T extends Predicate> Stream<T> getInnerPredicates(Class<T> type){ return getInnerPredicates().filter(type::isInstance).map(type::cast); } /** * @return set of types relevant to this atom */ public Stream<TypeAtom> getTypeConstraints(){ return getParentQuery().getAtoms(TypeAtom.class) .filter(atom -> atom != this) .filter(atom -> containsVar(atom.getVarName())); } /** * @param type the class of {@link Predicate} to return * @param <T> the type of neighbour {@link Atomic} to return * @return neighbours of this atoms, i.e. atoms connected to this atom via shared variable */ public <T extends Atomic> Stream<T> getNeighbours(Class<T> type){ return getParentQuery().getAtoms(type) .filter(atom -> atom != this) .filter(atom -> !Sets.intersection(this.getVarNames(), atom.getVarNames()).isEmpty()); } /** * @return set of constraints of this atom (predicates + types) that are not selectable */ public Stream<Atomic> getNonSelectableConstraints() { return Stream.concat( Stream.concat( getPredicates(), getPredicates().flatMap(AtomicBase::getPredicates) ), getTypeConstraints().filter(at -> !at.isSelectable()) ); } @Override public Atom inferTypes(){ return inferTypes(new ConceptMapImpl()); } @Override public Atom inferTypes(ConceptMap sub){ return this; } /** * @return list of types this atom can take */ public ImmutableList<SchemaConcept> getPossibleTypes(){ return ImmutableList.of(getSchemaConcept());} /** * @param sub partial substitution * @return list of possible atoms obtained by applying type inference */ public List<Atom> atomOptions(ConceptMap sub){ return Lists.newArrayList(inferTypes(sub));} /** * @param type to be added to this {@link Atom} * @return new {@link Atom} with specified type */ public Atom addType(SchemaConcept type){ return this;} public Stream<ConceptMap> materialise(){ return Stream.empty();} /** * @return set of atoms this atom can be decomposed to */ public Set<Atom> rewriteToAtoms(){ return Sets.newHashSet(this);} /** * rewrites the atom to user-defined type variable * @param parentAtom parent atom that triggers rewrite * @return rewritten atom */ public Atom rewriteWithTypeVariable(Atom parentAtom){ if (parentAtom.getPredicateVariable().isUserDefinedName() && !this.getPredicateVariable().isUserDefinedName() && this.getClass() == parentAtom.getClass() ){ return rewriteWithTypeVariable(); } return this; } /** * rewrites the atom to one with suitably user-defined names depending on provided parent * @param parentAtom parent atom that triggers rewrite * @return rewritten atom */ public abstract Atom rewriteToUserDefined(Atom parentAtom); public abstract Atom rewriteWithTypeVariable(); /** * rewrites the atom to one with user defined relation variable * @return rewritten atom */ public Atom rewriteWithRelationVariable(){ return this;} /** * attempt to find a UNIQUE unifier with the parent atom * @param parentAtom atom to be unified with * @param unifierType type of unifier to be computed * @return corresponding unifier */ @Nullable public abstract Unifier getUnifier(Atom parentAtom, UnifierComparison unifierType); /** * find the (multi) unifier with parent atom * @param parentAtom atom to be unified with * @param unifierType type of unifier to be computed * @return multiunifier */ public MultiUnifier getMultiUnifier(Atom parentAtom, UnifierComparison unifierType){ //NB only for relations we can have non-unique unifiers Unifier unifier = this.getUnifier(parentAtom, unifierType); return unifier != null? new MultiUnifierImpl(unifier) : MultiUnifierImpl.nonExistent(); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/AtomicBase.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.atom; import ai.grakn.concept.Rule; import ai.grakn.graql.Pattern; import ai.grakn.graql.Var; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.internal.query.answer.ConceptMapImpl; import ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate; import ai.grakn.graql.internal.reasoner.atom.predicate.Predicate; import ai.grakn.kb.internal.EmbeddedGraknTx; import ai.grakn.util.ErrorMessage; import com.google.common.collect.Sets; import java.util.Collections; import java.util.Set; import java.util.stream.Stream; import javax.annotation.Nullable; /** * * <p> * Base {@link Atomic} implementation providing basic functionalities. * </p> * * @author Kasper Piskorski * */ public abstract class AtomicBase implements Atomic { @Override public void checkValid(){} @Override public Set<String> validateAsRuleHead(Rule rule) { return Sets.newHashSet(ErrorMessage.VALIDATION_RULE_ILLEGAL_ATOMIC_IN_HEAD.getMessage(rule.then(), rule.label())); } @Override public String toString(){ return getPattern().toString(); } boolean containsVar(Var name){ return getVarNames().contains(name);} public boolean isUserDefined(){ return getVarName().isUserDefinedName();} /** * @return set of predicates relevant to this atomic */ public Stream<Predicate> getPredicates() { return getPredicates(Predicate.class); } /** * @param type the class of {@link Predicate} to return * @param <T> the type of {@link Predicate} to return * @return stream of predicates relevant to this atomic */ public <T extends Predicate> Stream<T> getPredicates(Class<T> type) { return getParentQuery().getAtoms(type).filter(atom -> !Sets.intersection(this.getVarNames(), atom.getVarNames()).isEmpty()); } /** * @param var variable of interest * @return id predicate referring to prescribed variable */ @Nullable public IdPredicate getIdPredicate(Var var){ return getPredicate(var, IdPredicate.class); } /** * @param var variable the predicate refers to * @param type predicate type * @param <T> predicate type generic * @return specific predicate referring to provided variable */ @Nullable public <T extends Predicate> T getPredicate(Var var, Class<T> type){ return getPredicates(type).filter(p -> p.getVarName().equals(var)).findFirst().orElse(null); } @Override public Set<Var> getVarNames(){ Var varName = getVarName(); return varName.isUserDefinedName()? Sets.newHashSet(varName) : Collections.emptySet(); } protected Pattern createCombinedPattern(){ return getPattern();} @Override public Pattern getCombinedPattern(){ return createCombinedPattern(); } @Override public Atomic inferTypes(){ return inferTypes(new ConceptMapImpl()); } public Atomic inferTypes(ConceptMap sub){ return this; } /** * @return GraknTx this atomic is defined in */ protected EmbeddedGraknTx<?> tx(){ // TODO: This cast is unsafe - ReasonerQuery should return an EmbeddedGraknTx return (EmbeddedGraknTx<?>) getParentQuery().tx(); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/AtomicEquivalence.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.atom; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.internal.reasoner.utils.ReasonerUtils; import com.google.common.base.Equivalence; import java.util.Collection; import java.util.SortedSet; import java.util.TreeSet; import java.util.stream.Stream; /** * * <p> * Static class defining different equivalence comparisons for {@link Atomic}s : * * - Equality: two {@link Atomic}s are equal if they are equal including all their corresponding variables. * * - Alpha-equivalence: two {@link Atomic}s are alpha-equivalent if they are equal up to the choice of free variables. * * - Structural equivalence: * Two atomics are structurally equivalent if they are equal up to the choice of free variables and partial substitutions (id predicates {@link ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate}). * Hence: * - any two IdPredicates are structurally equivalent * - structural equivalence check on queries is done by looking at {@link Atom}s. As a result: * * connected predicates are assessed together with atoms they are connected to * * dangling predicates are ignored * * </p> * * @author Kasper Piskorski * */ public abstract class AtomicEquivalence extends Equivalence<Atomic> { abstract public String name(); public static <B extends Atomic, S extends B> boolean equivalence(Collection<S> a1, Collection<S> a2, Equivalence<B> equiv){ return ReasonerUtils.isEquivalentCollection(a1, a2, equiv); } public static <B extends Atomic, S extends B> int equivalenceHash(Stream<S> atoms, Equivalence<B> equiv){ int hashCode = 1; SortedSet<Integer> hashes = new TreeSet<>(); atoms.forEach(atom -> hashes.add(equiv.hash(atom))); for (Integer hash : hashes) hashCode = hashCode * 37 + hash; return hashCode; } public static <B extends Atomic, S extends B> int equivalenceHash(Collection<S> atoms, Equivalence<B> equiv){ return equivalenceHash(atoms.stream(), equiv); } public final static AtomicEquivalence Equality = new AtomicEquivalence(){ @Override public String name(){ return "Equality";} @Override protected boolean doEquivalent(Atomic a, Atomic b) { return a.equals(b); } @Override protected int doHash(Atomic a) { return a.hashCode(); } }; public final static AtomicEquivalence AlphaEquivalence = new AtomicEquivalence(){ @Override public String name(){ return "AlphaEquivalence";} @Override protected boolean doEquivalent(Atomic a, Atomic b) { return a.isAlphaEquivalent(b); } @Override protected int doHash(Atomic a) { return a.alphaEquivalenceHashCode(); } }; public final static AtomicEquivalence StructuralEquivalence = new AtomicEquivalence(){ @Override public String name(){ return "StructuralEquivalence";} @Override protected boolean doEquivalent(Atomic a, Atomic b) { return a.isStructurallyEquivalent(b); } @Override protected int doHash(Atomic a) { return a.structuralEquivalenceHashCode(); } }; }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/AtomicFactory.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.atom; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.Conjunction; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.VarPatternAdmin; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; /** * * <p> * Factory class for creating {@link Atomic} objects. * </p> * * @author Kasper Piskorski * */ public class AtomicFactory { /** * @param pattern conjunction of patterns to be converted to atoms * @param parent query the created atoms should belong to * @return set of atoms */ public static Stream<Atomic> createAtoms(Conjunction<VarPatternAdmin> pattern, ReasonerQuery parent) { Set<Atomic> atoms = pattern.varPatterns().stream() .flatMap(var -> var.getProperties() .map(vp -> vp.mapToAtom(var, pattern.varPatterns(), parent)) .filter(Objects::nonNull)) .collect(Collectors.toSet()); return atoms.stream() .filter(at -> atoms.stream() .filter(Atom.class::isInstance) .map(Atom.class::cast) .flatMap(Atom::getInnerPredicates) .noneMatch(at::equals) ); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/binary/$AutoValue_HasAtom.java
package ai.grakn.graql.internal.reasoner.atom.binary; import ai.grakn.concept.ConceptId; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.internal.reasoner.utils.IgnoreHashEquals; import javax.annotation.CheckReturnValue; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("com.google.auto.value.processor.AutoValueProcessor") abstract class $AutoValue_HasAtom extends HasAtom { private final Var varName; private final ConceptId typeId; private final Var predicateVariable; private final VarPattern pattern; private final ReasonerQuery parentQuery; $AutoValue_HasAtom( Var varName, @Nullable ConceptId typeId, Var predicateVariable, VarPattern pattern, ReasonerQuery parentQuery) { if (varName == null) { throw new NullPointerException("Null varName"); } this.varName = varName; this.typeId = typeId; if (predicateVariable == null) { throw new NullPointerException("Null predicateVariable"); } this.predicateVariable = predicateVariable; if (pattern == null) { throw new NullPointerException("Null pattern"); } this.pattern = pattern; if (parentQuery == null) { throw new NullPointerException("Null parentQuery"); } this.parentQuery = parentQuery; } @CheckReturnValue @Override public Var getVarName() { return varName; } @Nullable @Override public ConceptId getTypeId() { return typeId; } @IgnoreHashEquals @Override public Var getPredicateVariable() { return predicateVariable; } @IgnoreHashEquals @Override public VarPattern getPattern() { return pattern; } @IgnoreHashEquals @Override public ReasonerQuery getParentQuery() { return parentQuery; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof HasAtom) { HasAtom that = (HasAtom) o; return (this.varName.equals(that.getVarName())) && ((this.typeId == null) ? (that.getTypeId() == null) : this.typeId.equals(that.getTypeId())) && (this.predicateVariable.equals(that.getPredicateVariable())) && (this.pattern.equals(that.getPattern())) && (this.parentQuery.equals(that.getParentQuery())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.varName.hashCode(); h *= 1000003; h ^= (typeId == null) ? 0 : this.typeId.hashCode(); h *= 1000003; h ^= this.predicateVariable.hashCode(); h *= 1000003; h ^= this.pattern.hashCode(); h *= 1000003; h ^= this.parentQuery.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/binary/$AutoValue_IsaAtom.java
package ai.grakn.graql.internal.reasoner.atom.binary; import ai.grakn.concept.ConceptId; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import javax.annotation.CheckReturnValue; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("com.google.auto.value.processor.AutoValueProcessor") abstract class $AutoValue_IsaAtom extends IsaAtom { private final Var varName; private final ConceptId typeId; private final Var predicateVariable; private final VarPattern pattern; private final ReasonerQuery parentQuery; $AutoValue_IsaAtom( Var varName, @Nullable ConceptId typeId, Var predicateVariable, VarPattern pattern, ReasonerQuery parentQuery) { if (varName == null) { throw new NullPointerException("Null varName"); } this.varName = varName; this.typeId = typeId; if (predicateVariable == null) { throw new NullPointerException("Null predicateVariable"); } this.predicateVariable = predicateVariable; if (pattern == null) { throw new NullPointerException("Null pattern"); } this.pattern = pattern; if (parentQuery == null) { throw new NullPointerException("Null parentQuery"); } this.parentQuery = parentQuery; } @CheckReturnValue @Override public Var getVarName() { return varName; } @Nullable @Override public ConceptId getTypeId() { return typeId; } @Override public Var getPredicateVariable() { return predicateVariable; } @Override public VarPattern getPattern() { return pattern; } @Override public ReasonerQuery getParentQuery() { return parentQuery; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/binary/$AutoValue_PlaysAtom.java
package ai.grakn.graql.internal.reasoner.atom.binary; import ai.grakn.concept.ConceptId; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.internal.reasoner.utils.IgnoreHashEquals; import javax.annotation.CheckReturnValue; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("com.google.auto.value.processor.AutoValueProcessor") abstract class $AutoValue_PlaysAtom extends PlaysAtom { private final Var varName; private final ConceptId typeId; private final Var predicateVariable; private final VarPattern pattern; private final ReasonerQuery parentQuery; $AutoValue_PlaysAtom( Var varName, @Nullable ConceptId typeId, Var predicateVariable, VarPattern pattern, ReasonerQuery parentQuery) { if (varName == null) { throw new NullPointerException("Null varName"); } this.varName = varName; this.typeId = typeId; if (predicateVariable == null) { throw new NullPointerException("Null predicateVariable"); } this.predicateVariable = predicateVariable; if (pattern == null) { throw new NullPointerException("Null pattern"); } this.pattern = pattern; if (parentQuery == null) { throw new NullPointerException("Null parentQuery"); } this.parentQuery = parentQuery; } @CheckReturnValue @Override public Var getVarName() { return varName; } @Nullable @Override public ConceptId getTypeId() { return typeId; } @IgnoreHashEquals @Override public Var getPredicateVariable() { return predicateVariable; } @IgnoreHashEquals @Override public VarPattern getPattern() { return pattern; } @IgnoreHashEquals @Override public ReasonerQuery getParentQuery() { return parentQuery; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof PlaysAtom) { PlaysAtom that = (PlaysAtom) o; return (this.varName.equals(that.getVarName())) && ((this.typeId == null) ? (that.getTypeId() == null) : this.typeId.equals(that.getTypeId())) && (this.predicateVariable.equals(that.getPredicateVariable())) && (this.pattern.equals(that.getPattern())) && (this.parentQuery.equals(that.getParentQuery())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.varName.hashCode(); h *= 1000003; h ^= (typeId == null) ? 0 : this.typeId.hashCode(); h *= 1000003; h ^= this.predicateVariable.hashCode(); h *= 1000003; h ^= this.pattern.hashCode(); h *= 1000003; h ^= this.parentQuery.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/binary/$AutoValue_RelatesAtom.java
package ai.grakn.graql.internal.reasoner.atom.binary; import ai.grakn.concept.ConceptId; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.internal.reasoner.utils.IgnoreHashEquals; import javax.annotation.CheckReturnValue; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("com.google.auto.value.processor.AutoValueProcessor") abstract class $AutoValue_RelatesAtom extends RelatesAtom { private final Var varName; private final ConceptId typeId; private final Var predicateVariable; private final VarPattern pattern; private final ReasonerQuery parentQuery; $AutoValue_RelatesAtom( Var varName, @Nullable ConceptId typeId, Var predicateVariable, VarPattern pattern, ReasonerQuery parentQuery) { if (varName == null) { throw new NullPointerException("Null varName"); } this.varName = varName; this.typeId = typeId; if (predicateVariable == null) { throw new NullPointerException("Null predicateVariable"); } this.predicateVariable = predicateVariable; if (pattern == null) { throw new NullPointerException("Null pattern"); } this.pattern = pattern; if (parentQuery == null) { throw new NullPointerException("Null parentQuery"); } this.parentQuery = parentQuery; } @CheckReturnValue @Override public Var getVarName() { return varName; } @Nullable @Override public ConceptId getTypeId() { return typeId; } @IgnoreHashEquals @Override public Var getPredicateVariable() { return predicateVariable; } @IgnoreHashEquals @Override public VarPattern getPattern() { return pattern; } @IgnoreHashEquals @Override public ReasonerQuery getParentQuery() { return parentQuery; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof RelatesAtom) { RelatesAtom that = (RelatesAtom) o; return (this.varName.equals(that.getVarName())) && ((this.typeId == null) ? (that.getTypeId() == null) : this.typeId.equals(that.getTypeId())) && (this.predicateVariable.equals(that.getPredicateVariable())) && (this.pattern.equals(that.getPattern())) && (this.parentQuery.equals(that.getParentQuery())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.varName.hashCode(); h *= 1000003; h ^= (typeId == null) ? 0 : this.typeId.hashCode(); h *= 1000003; h ^= this.predicateVariable.hashCode(); h *= 1000003; h ^= this.pattern.hashCode(); h *= 1000003; h ^= this.parentQuery.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/binary/$AutoValue_RelationshipAtom.java
package ai.grakn.graql.internal.reasoner.atom.binary; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Label; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.RelationPlayer; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import javax.annotation.CheckReturnValue; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("com.google.auto.value.processor.AutoValueProcessor") abstract class $AutoValue_RelationshipAtom extends RelationshipAtom { private final Var varName; private final VarPattern pattern; private final ReasonerQuery parentQuery; private final Var predicateVariable; private final ConceptId typeId; private final ImmutableList<RelationPlayer> relationPlayers; private final ImmutableSet<Label> roleLabels; $AutoValue_RelationshipAtom( Var varName, VarPattern pattern, ReasonerQuery parentQuery, Var predicateVariable, @Nullable ConceptId typeId, ImmutableList<RelationPlayer> relationPlayers, ImmutableSet<Label> roleLabels) { if (varName == null) { throw new NullPointerException("Null varName"); } this.varName = varName; if (pattern == null) { throw new NullPointerException("Null pattern"); } this.pattern = pattern; if (parentQuery == null) { throw new NullPointerException("Null parentQuery"); } this.parentQuery = parentQuery; if (predicateVariable == null) { throw new NullPointerException("Null predicateVariable"); } this.predicateVariable = predicateVariable; this.typeId = typeId; if (relationPlayers == null) { throw new NullPointerException("Null relationPlayers"); } this.relationPlayers = relationPlayers; if (roleLabels == null) { throw new NullPointerException("Null roleLabels"); } this.roleLabels = roleLabels; } @CheckReturnValue @Override public Var getVarName() { return varName; } @CheckReturnValue @Override public VarPattern getPattern() { return pattern; } @Override public ReasonerQuery getParentQuery() { return parentQuery; } @Override public Var getPredicateVariable() { return predicateVariable; } @Nullable @Override public ConceptId getTypeId() { return typeId; } @Override public ImmutableList<RelationPlayer> getRelationPlayers() { return relationPlayers; } @Override public ImmutableSet<Label> getRoleLabels() { return roleLabels; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/binary/$AutoValue_SubAtom.java
package ai.grakn.graql.internal.reasoner.atom.binary; import ai.grakn.concept.ConceptId; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.internal.reasoner.utils.IgnoreHashEquals; import javax.annotation.CheckReturnValue; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("com.google.auto.value.processor.AutoValueProcessor") abstract class $AutoValue_SubAtom extends SubAtom { private final Var varName; private final ConceptId typeId; private final Var predicateVariable; private final VarPattern pattern; private final ReasonerQuery parentQuery; $AutoValue_SubAtom( Var varName, @Nullable ConceptId typeId, Var predicateVariable, VarPattern pattern, ReasonerQuery parentQuery) { if (varName == null) { throw new NullPointerException("Null varName"); } this.varName = varName; this.typeId = typeId; if (predicateVariable == null) { throw new NullPointerException("Null predicateVariable"); } this.predicateVariable = predicateVariable; if (pattern == null) { throw new NullPointerException("Null pattern"); } this.pattern = pattern; if (parentQuery == null) { throw new NullPointerException("Null parentQuery"); } this.parentQuery = parentQuery; } @CheckReturnValue @Override public Var getVarName() { return varName; } @Nullable @Override public ConceptId getTypeId() { return typeId; } @IgnoreHashEquals @Override public Var getPredicateVariable() { return predicateVariable; } @IgnoreHashEquals @Override public VarPattern getPattern() { return pattern; } @IgnoreHashEquals @Override public ReasonerQuery getParentQuery() { return parentQuery; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof SubAtom) { SubAtom that = (SubAtom) o; return (this.varName.equals(that.getVarName())) && ((this.typeId == null) ? (that.getTypeId() == null) : this.typeId.equals(that.getTypeId())) && (this.predicateVariable.equals(that.getPredicateVariable())) && (this.pattern.equals(that.getPattern())) && (this.parentQuery.equals(that.getParentQuery())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.varName.hashCode(); h *= 1000003; h ^= (typeId == null) ? 0 : this.typeId.hashCode(); h *= 1000003; h ^= this.predicateVariable.hashCode(); h *= 1000003; h ^= this.pattern.hashCode(); h *= 1000003; h ^= this.parentQuery.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/binary/AutoValue_HasAtom.java
package ai.grakn.graql.internal.reasoner.atom.binary; import ai.grakn.concept.ConceptId; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import java.lang.Object; import java.lang.Override; final class AutoValue_HasAtom extends $AutoValue_HasAtom { AutoValue_HasAtom(Var varName, ConceptId typeId, Var predicateVariable, VarPattern pattern, ReasonerQuery parentQuery) { super(varName, typeId, predicateVariable, pattern, parentQuery); } @Override public final boolean equals(Object o) { if (o == this) { return true; } if (o instanceof HasAtom) { HasAtom that = (HasAtom) o; return (this.getVarName().equals(that.getVarName())) && ((this.getTypeId() == null) ? (that.getTypeId() == null) : this.getTypeId().equals(that.getTypeId())); } return false; } @Override public final int hashCode() { int h = 1; h *= 1000003; h ^= this.getVarName().hashCode(); h *= 1000003; h ^= (getTypeId() == null) ? 0 : this.getTypeId().hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/binary/AutoValue_IsaAtom.java
package ai.grakn.graql.internal.reasoner.atom.binary; import ai.grakn.concept.ConceptId; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import java.lang.Override; import javax.annotation.Generated; @Generated("com.google.auto.value.extension.memoized.MemoizeExtension") final class AutoValue_IsaAtom extends $AutoValue_IsaAtom { private volatile int hashCode; private volatile boolean hashCode$Memoized; AutoValue_IsaAtom(Var varName$, ConceptId typeId$, Var predicateVariable$, VarPattern pattern$, ReasonerQuery parentQuery$) { super(varName$, typeId$, predicateVariable$, pattern$, parentQuery$); } @Override public int hashCode() { if (!hashCode$Memoized) { synchronized (this) { if (!hashCode$Memoized) { hashCode = super.hashCode(); hashCode$Memoized = true; } } } return hashCode; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/binary/AutoValue_PlaysAtom.java
package ai.grakn.graql.internal.reasoner.atom.binary; import ai.grakn.concept.ConceptId; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import java.lang.Object; import java.lang.Override; final class AutoValue_PlaysAtom extends $AutoValue_PlaysAtom { AutoValue_PlaysAtom(Var varName, ConceptId typeId, Var predicateVariable, VarPattern pattern, ReasonerQuery parentQuery) { super(varName, typeId, predicateVariable, pattern, parentQuery); } @Override public final boolean equals(Object o) { if (o == this) { return true; } if (o instanceof PlaysAtom) { PlaysAtom that = (PlaysAtom) o; return (this.getVarName().equals(that.getVarName())) && ((this.getTypeId() == null) ? (that.getTypeId() == null) : this.getTypeId().equals(that.getTypeId())); } return false; } @Override public final int hashCode() { int h = 1; h *= 1000003; h ^= this.getVarName().hashCode(); h *= 1000003; h ^= (getTypeId() == null) ? 0 : this.getTypeId().hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/binary/AutoValue_RelatesAtom.java
package ai.grakn.graql.internal.reasoner.atom.binary; import ai.grakn.concept.ConceptId; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import java.lang.Object; import java.lang.Override; final class AutoValue_RelatesAtom extends $AutoValue_RelatesAtom { AutoValue_RelatesAtom(Var varName, ConceptId typeId, Var predicateVariable, VarPattern pattern, ReasonerQuery parentQuery) { super(varName, typeId, predicateVariable, pattern, parentQuery); } @Override public final boolean equals(Object o) { if (o == this) { return true; } if (o instanceof RelatesAtom) { RelatesAtom that = (RelatesAtom) o; return (this.getVarName().equals(that.getVarName())) && ((this.getTypeId() == null) ? (that.getTypeId() == null) : this.getTypeId().equals(that.getTypeId())); } return false; } @Override public final int hashCode() { int h = 1; h *= 1000003; h ^= this.getVarName().hashCode(); h *= 1000003; h ^= (getTypeId() == null) ? 0 : this.getTypeId().hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/binary/AutoValue_RelationshipAtom.java
package ai.grakn.graql.internal.reasoner.atom.binary; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Label; import ai.grakn.concept.Role; import ai.grakn.concept.Type; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.RelationPlayer; import ai.grakn.graql.internal.reasoner.atom.predicate.NeqPredicate; import ai.grakn.graql.internal.reasoner.atom.predicate.ValuePredicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; import java.lang.Override; import java.lang.String; import javax.annotation.Generated; @Generated("com.google.auto.value.extension.memoized.MemoizeExtension") final class AutoValue_RelationshipAtom extends $AutoValue_RelationshipAtom { private volatile int hashCode; private volatile boolean hashCode$Memoized; private volatile Multimap<Role, String> getRoleConceptIdMap; private volatile Multimap<Role, ValuePredicate> getRoleValueMap; private volatile Multimap<Role, NeqPredicate> getRoleNeqPredicateMap; private volatile Multimap<Role, Type> getRoleTypeMap; private volatile Multimap<Role, Var> getRoleVarMap; AutoValue_RelationshipAtom(Var varName$, VarPattern pattern$, ReasonerQuery parentQuery$, Var predicateVariable$, ConceptId typeId$, ImmutableList<RelationPlayer> relationPlayers$, ImmutableSet<Label> roleLabels$) { super(varName$, pattern$, parentQuery$, predicateVariable$, typeId$, relationPlayers$, roleLabels$); } @Override public int hashCode() { if (!hashCode$Memoized) { synchronized (this) { if (!hashCode$Memoized) { hashCode = super.hashCode(); hashCode$Memoized = true; } } } return hashCode; } @Override public Multimap<Role, String> getRoleConceptIdMap() { if (getRoleConceptIdMap == null) { synchronized (this) { if (getRoleConceptIdMap == null) { getRoleConceptIdMap = super.getRoleConceptIdMap(); if (getRoleConceptIdMap == null) { throw new NullPointerException("getRoleConceptIdMap() cannot return null"); } } } } return getRoleConceptIdMap; } @Override public Multimap<Role, ValuePredicate> getRoleValueMap() { if (getRoleValueMap == null) { synchronized (this) { if (getRoleValueMap == null) { getRoleValueMap = super.getRoleValueMap(); if (getRoleValueMap == null) { throw new NullPointerException("getRoleValueMap() cannot return null"); } } } } return getRoleValueMap; } @Override public Multimap<Role, NeqPredicate> getRoleNeqPredicateMap() { if (getRoleNeqPredicateMap == null) { synchronized (this) { if (getRoleNeqPredicateMap == null) { getRoleNeqPredicateMap = super.getRoleNeqPredicateMap(); if (getRoleNeqPredicateMap == null) { throw new NullPointerException("getRoleNeqPredicateMap() cannot return null"); } } } } return getRoleNeqPredicateMap; } @Override public Multimap<Role, Type> getRoleTypeMap() { if (getRoleTypeMap == null) { synchronized (this) { if (getRoleTypeMap == null) { getRoleTypeMap = super.getRoleTypeMap(); if (getRoleTypeMap == null) { throw new NullPointerException("getRoleTypeMap() cannot return null"); } } } } return getRoleTypeMap; } @Override public Multimap<Role, Var> getRoleVarMap() { if (getRoleVarMap == null) { synchronized (this) { if (getRoleVarMap == null) { getRoleVarMap = super.getRoleVarMap(); if (getRoleVarMap == null) { throw new NullPointerException("getRoleVarMap() cannot return null"); } } } } return getRoleVarMap; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/binary/AutoValue_ResourceAtom.java
package ai.grakn.graql.internal.reasoner.atom.binary; import ai.grakn.concept.ConceptId; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.internal.reasoner.atom.predicate.ValuePredicate; import com.google.common.collect.ImmutableSet; import javax.annotation.CheckReturnValue; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_ResourceAtom extends ResourceAtom { private final Var varName; private final VarPattern pattern; private final ReasonerQuery parentQuery; private final Var predicateVariable; private final ConceptId typeId; private final Var relationVariable; private final ImmutableSet<ValuePredicate> multiPredicate; AutoValue_ResourceAtom( Var varName, VarPattern pattern, ReasonerQuery parentQuery, Var predicateVariable, @Nullable ConceptId typeId, Var relationVariable, ImmutableSet<ValuePredicate> multiPredicate) { if (varName == null) { throw new NullPointerException("Null varName"); } this.varName = varName; if (pattern == null) { throw new NullPointerException("Null pattern"); } this.pattern = pattern; if (parentQuery == null) { throw new NullPointerException("Null parentQuery"); } this.parentQuery = parentQuery; if (predicateVariable == null) { throw new NullPointerException("Null predicateVariable"); } this.predicateVariable = predicateVariable; this.typeId = typeId; if (relationVariable == null) { throw new NullPointerException("Null relationVariable"); } this.relationVariable = relationVariable; if (multiPredicate == null) { throw new NullPointerException("Null multiPredicate"); } this.multiPredicate = multiPredicate; } @CheckReturnValue @Override public Var getVarName() { return varName; } @CheckReturnValue @Override public VarPattern getPattern() { return pattern; } @Override public ReasonerQuery getParentQuery() { return parentQuery; } @Override public Var getPredicateVariable() { return predicateVariable; } @Nullable @Override public ConceptId getTypeId() { return typeId; } @Override public Var getRelationVariable() { return relationVariable; } @Override public ImmutableSet<ValuePredicate> getMultiPredicate() { return multiPredicate; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/binary/AutoValue_SubAtom.java
package ai.grakn.graql.internal.reasoner.atom.binary; import ai.grakn.concept.ConceptId; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import java.lang.Object; import java.lang.Override; final class AutoValue_SubAtom extends $AutoValue_SubAtom { AutoValue_SubAtom(Var varName, ConceptId typeId, Var predicateVariable, VarPattern pattern, ReasonerQuery parentQuery) { super(varName, typeId, predicateVariable, pattern, parentQuery); } @Override public final boolean equals(Object o) { if (o == this) { return true; } if (o instanceof SubAtom) { SubAtom that = (SubAtom) o; return (this.getVarName().equals(that.getVarName())) && ((this.getTypeId() == null) ? (that.getTypeId() == null) : this.getTypeId().equals(that.getTypeId())); } return false; } @Override public final int hashCode() { int h = 1; h *= 1000003; h ^= this.getVarName().hashCode(); h *= 1000003; h ^= (getTypeId() == null) ? 0 : this.getTypeId().hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/binary/Binary.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.atom.binary; import ai.grakn.concept.ConceptId; import ai.grakn.concept.SchemaConcept; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Pattern; import ai.grakn.graql.Var; import ai.grakn.graql.admin.PatternAdmin; import ai.grakn.graql.admin.Unifier; import ai.grakn.graql.admin.UnifierComparison; import ai.grakn.graql.internal.pattern.Patterns; import ai.grakn.graql.internal.pattern.property.IsaExplicitProperty; import ai.grakn.graql.internal.reasoner.UnifierImpl; import ai.grakn.graql.internal.reasoner.atom.Atom; import ai.grakn.graql.internal.reasoner.atom.AtomicEquivalence; import ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate; import ai.grakn.graql.internal.reasoner.atom.predicate.NeqPredicate; import ai.grakn.graql.internal.reasoner.atom.predicate.Predicate; import ai.grakn.graql.internal.reasoner.atom.predicate.ValuePredicate; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import java.util.stream.Stream; import javax.annotation.Nullable; import java.util.HashSet; import java.util.Objects; import java.util.Set; /** * * <p> * Implementation for binary atoms with single id typePredicate for a schema concept. Binary atoms take the form: * * <>($varName, $predicateVariable), type($predicateVariable) * * </p> * * @author Kasper Piskorski * */ public abstract class Binary extends Atom { public abstract Var getPredicateVariable(); @Nullable @Override public abstract ConceptId getTypeId(); private SchemaConcept type = null; private IdPredicate typePredicate = null; @Nullable public IdPredicate getTypePredicate(){ if (typePredicate == null && getTypeId() != null) { typePredicate = IdPredicate.create(getPredicateVariable().id(getTypeId()), getParentQuery()); } return typePredicate; } @Nullable @Override public SchemaConcept getSchemaConcept(){ if (type == null && getTypeId() != null) { SchemaConcept concept = tx().getConcept(getTypeId()); if (concept == null) throw GraqlQueryException.idNotFound(getTypeId()); type = concept; } return type; } @Override public void checkValid() { if (getTypePredicate() != null) getTypePredicate().checkValid(); } public boolean isDirect(){ return getPattern().admin().getProperties(IsaExplicitProperty.class).findFirst().isPresent(); } @Override public boolean isAlphaEquivalent(Object obj) { if (obj == this) return true; if (obj == null || this.getClass() != obj.getClass()) return false; Binary that = (Binary) obj; return (this.isUserDefined() == that.isUserDefined()) && this.isDirect() == that.isDirect() && Objects.equals(this.getTypeId(), that.getTypeId()) && this.predicateBindingsEquivalent(that, AtomicEquivalence.AlphaEquivalence); } @Override public int alphaEquivalenceHashCode() { int hashCode = 1; hashCode = hashCode * 37 + (this.getTypeId() != null? this.getTypeId().hashCode() : 0); return hashCode; } @Override public boolean isStructurallyEquivalent(Object obj) { if (obj == this) return true; if (obj == null || this.getClass() != obj.getClass()) return false; Binary that = (Binary) obj; return (this.isUserDefined() == that.isUserDefined()) && this.isDirect() == that.isDirect() && Objects.equals(this.getTypeId(), that.getTypeId()) && this.predicateBindingsEquivalent(that, AtomicEquivalence.StructuralEquivalence); } @Override public int structuralEquivalenceHashCode() { return alphaEquivalenceHashCode(); } boolean predicateBindingsEquivalent(Binary that, AtomicEquivalence equiv) { //check if there is a substitution for varName IdPredicate thisVarPredicate = this.getIdPredicate(this.getVarName()); IdPredicate varPredicate = that.getIdPredicate(that.getVarName()); NeqPredicate thisVarNeqPredicate = this.getPredicate(this.getVarName(), NeqPredicate.class); NeqPredicate varNeqPredicate = that.getPredicate(that.getVarName(), NeqPredicate.class); IdPredicate thisTypePredicate = this.getTypePredicate(); IdPredicate typePredicate = that.getTypePredicate(); NeqPredicate thisTypeNeqPredicate = this.getPredicate(this.getPredicateVariable(), NeqPredicate.class); NeqPredicate typeNeqPredicate = that.getPredicate(that.getPredicateVariable(), NeqPredicate.class); ValuePredicate thisValuePredicate = this.getPredicate(this.getVarName(), ValuePredicate.class); ValuePredicate valuePredicate = that.getPredicate(that.getVarName(), ValuePredicate.class); ValuePredicate thisTypeValuePredicate = this.getPredicate(this.getPredicateVariable(), ValuePredicate.class); ValuePredicate typeValuePredicate = that.getPredicate(that.getPredicateVariable(), ValuePredicate.class); return ((thisVarPredicate == null && varPredicate == null || thisVarPredicate != null && equiv.equivalent(thisVarPredicate, varPredicate))) && (thisVarNeqPredicate == null && varNeqPredicate == null || thisVarNeqPredicate != null && equiv.equivalent(thisVarNeqPredicate, varNeqPredicate)) && (thisTypePredicate == null && typePredicate == null || thisTypePredicate != null && equiv.equivalent(thisTypePredicate, typePredicate)) && (thisTypeNeqPredicate == null && typeNeqPredicate == null || thisTypeNeqPredicate != null && equiv.equivalent(thisTypeNeqPredicate, typeNeqPredicate)) && (thisValuePredicate == null && valuePredicate == null || thisValuePredicate != null && equiv.equivalent(thisValuePredicate, valuePredicate)) && (thisTypeValuePredicate == null && typeValuePredicate == null || thisTypeValuePredicate != null && equiv.equivalent(thisTypeValuePredicate, typeValuePredicate)); } @Override protected Pattern createCombinedPattern(){ Set<PatternAdmin> vars = Sets.newHashSet(getPattern().admin()); if (getTypePredicate() != null) vars.add(getTypePredicate().getPattern().admin()); return Patterns.conjunction(vars); } @Override public Set<Var> getVarNames() { Set<Var> vars = new HashSet<>(); if (getVarName().isUserDefinedName()) vars.add(getVarName()); if (getPredicateVariable().isUserDefinedName()) vars.add(getPredicateVariable()); return vars; } @Override public Stream<Predicate> getInnerPredicates(){ return getTypePredicate() != null? Stream.of(getTypePredicate()) : Stream.empty(); } @Override public Unifier getUnifier(Atom parentAtom, UnifierComparison unifierType) { if (!(parentAtom instanceof Binary)) { throw GraqlQueryException.unificationAtomIncompatibility(); } if( !unifierType.typeCompatibility(parentAtom.getSchemaConcept(), this.getSchemaConcept()) ) return UnifierImpl.nonExistent(); Multimap<Var, Var> varMappings = HashMultimap.create(); Var childVarName = this.getVarName(); Var parentVarName = parentAtom.getVarName(); Var childPredicateVarName = this.getPredicateVariable(); Var parentPredicateVarName = parentAtom.getPredicateVariable(); //check for incompatibilities if( !unifierType.idCompatibility(parentAtom.getIdPredicate(parentVarName), this.getIdPredicate(childVarName)) || !unifierType.idCompatibility(parentAtom.getIdPredicate(parentPredicateVarName), this.getIdPredicate(childPredicateVarName)) || !unifierType.valueCompatibility(parentAtom.getPredicate(parentVarName, ValuePredicate.class), this.getPredicate(childVarName, ValuePredicate.class)) || !unifierType.valueCompatibility(parentAtom.getPredicate(parentPredicateVarName, ValuePredicate.class), this.getPredicate(childPredicateVarName, ValuePredicate.class))){ return UnifierImpl.nonExistent(); } if (parentVarName.isUserDefinedName() && childVarName.isUserDefinedName()) { varMappings.put(childVarName, parentVarName); } if (parentPredicateVarName.isUserDefinedName() && childPredicateVarName.isUserDefinedName()) { varMappings.put(childPredicateVarName, parentPredicateVarName); } return new UnifierImpl(varMappings); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/binary/HasAtom.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.atom.binary; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Label; import ai.grakn.graql.Graql; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.VarProperty; import ai.grakn.graql.internal.pattern.property.HasAttributeTypeProperty; import ai.grakn.graql.internal.reasoner.utils.IgnoreHashEquals; import com.google.auto.value.AutoValue; /** * * <p> * TypeAtom corresponding to graql a {@link HasAttributeTypeProperty} property. * </p> * * @author Kasper Piskorski * */ @AutoValue public abstract class HasAtom extends OntologicalAtom { @Override @IgnoreHashEquals public abstract Var getPredicateVariable(); @Override @IgnoreHashEquals public abstract VarPattern getPattern(); @Override @IgnoreHashEquals public abstract ReasonerQuery getParentQuery(); public static HasAtom create(VarPattern pattern, Var predicateVar, ConceptId predicateId, ReasonerQuery parent) { return new AutoValue_HasAtom(pattern.admin().var(), predicateId, predicateVar, pattern, parent); } public static HasAtom create(Var var, Var predicateVar, ConceptId predicateId, ReasonerQuery parent) { Label label = parent.tx().getConcept(predicateId).asType().label(); return create(var.has(Graql.label(label)), predicateVar, predicateId, parent); } private static HasAtom create(TypeAtom a, ReasonerQuery parent) { return create(a.getVarName(), a.getPredicateVariable(), a.getTypeId(), parent); } @Override OntologicalAtom createSelf(Var var, Var predicateVar, ConceptId predicateId, ReasonerQuery parent) { return HasAtom.create(var, predicateVar, predicateId, parent); } @Override public Atomic copy(ReasonerQuery parent){ return create(this, parent); } @Override public Class<? extends VarProperty> getVarPropertyClass() { return HasAttributeTypeProperty.class;} }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/binary/IsaAtom.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.atom.binary; import ai.grakn.concept.Concept; import ai.grakn.concept.ConceptId; import ai.grakn.concept.EntityType; import ai.grakn.concept.SchemaConcept; import ai.grakn.concept.Type; import ai.grakn.graql.Pattern; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.VarProperty; import ai.grakn.graql.internal.pattern.property.IsaExplicitProperty; import ai.grakn.graql.internal.pattern.property.IsaProperty; import ai.grakn.graql.internal.query.answer.ConceptMapImpl; import ai.grakn.graql.internal.reasoner.atom.Atom; import ai.grakn.graql.internal.reasoner.atom.predicate.Predicate; import ai.grakn.graql.internal.reasoner.utils.ReasonerUtils; import ai.grakn.kb.internal.concept.EntityTypeImpl; import com.google.auto.value.AutoValue; import com.google.auto.value.extension.memoized.Memoized; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nullable; import static ai.grakn.util.CommonUtil.toImmutableList; /** * * <p> * TypeAtom corresponding to graql a {@link ai.grakn.graql.internal.pattern.property.IsaProperty} property. * </p> * * @author Kasper Piskorski * */ @AutoValue public abstract class IsaAtom extends IsaAtomBase { @Override public abstract Var getPredicateVariable(); @Override public abstract VarPattern getPattern(); @Override public abstract ReasonerQuery getParentQuery(); public static IsaAtom create(Var var, Var predicateVar, VarPattern pattern, @Nullable ConceptId predicateId, ReasonerQuery parent) { return new AutoValue_IsaAtom(var, predicateId, predicateVar, pattern, parent); } public static IsaAtom create(Var var, Var predicateVar, @Nullable ConceptId predicateId, boolean isDirect, ReasonerQuery parent) { VarPatternAdmin pattern = isDirect ? var.isaExplicit(predicateVar).admin() : var.isa(predicateVar).admin(); return new AutoValue_IsaAtom(var, predicateId, predicateVar, pattern, parent); } public static IsaAtom create(Var var, Var predicateVar, SchemaConcept type, boolean isDirect, ReasonerQuery parent) { VarPatternAdmin pattern = isDirect ? var.isaExplicit(predicateVar).admin() : var.isa(predicateVar).admin(); return new AutoValue_IsaAtom(var, type.id(), predicateVar, pattern, parent); } private static IsaAtom create(IsaAtom a, ReasonerQuery parent) { IsaAtom atom = create(a.getVarName(), a.getPredicateVariable(), a.getPattern(), a.getTypeId(), parent); atom.applicableRules = a.applicableRules; return atom; } @Override public Atomic copy(ReasonerQuery parent){ return create(this, parent); } @Override public Class<? extends VarProperty> getVarPropertyClass() { return isDirect()? IsaExplicitProperty.class : IsaProperty.class;} //NB: overriding as these require a derived property @Override public final boolean equals(Object obj) { if (obj == this) return true; if (obj == null || this.getClass() != obj.getClass()) return false; IsaAtom that = (IsaAtom) obj; return this.getVarName().equals(that.getVarName()) && this.isDirect() == that.isDirect() && ((this.getTypeId() == null) ? (that.getTypeId() == null) : this.getTypeId().equals(that.getTypeId())); } @Memoized @Override public int hashCode() { int hashCode = 1; hashCode = hashCode * 37 + getVarName().hashCode(); hashCode = hashCode * 37 + (getTypeId() != null ? getTypeId().hashCode() : 0); return hashCode; } @Override public String toString(){ String typeString = (getSchemaConcept() != null? getSchemaConcept().label() : "") + "(" + getVarName() + ")"; return typeString + (getPredicateVariable().isUserDefinedName()? "(" + getPredicateVariable() + ")" : "") + (isDirect()? "!" : "") + getPredicates().map(Predicate::toString).collect(Collectors.joining("")); } @Override protected Pattern createCombinedPattern(){ if (getPredicateVariable().isUserDefinedName()) return super.createCombinedPattern(); return getSchemaConcept() == null? getVarName().isa(getPredicateVariable()) : isDirect()? getVarName().isaExplicit(getSchemaConcept().label().getValue()) : getVarName().isa(getSchemaConcept().label().getValue()) ; } @Override public IsaAtom addType(SchemaConcept type) { if (getTypeId() != null) return this; return create(getVarName(), getPredicateVariable(), type.id(), this.isDirect(), this.getParentQuery()); } private IsaAtom inferEntityType(ConceptMap sub){ if (getTypePredicate() != null) return this; if (sub.containsVar(getPredicateVariable())) return addType(sub.get(getPredicateVariable()).asType()); return this; } private ImmutableList<SchemaConcept> inferPossibleTypes(ConceptMap sub){ if (getSchemaConcept() != null) return ImmutableList.of(this.getSchemaConcept()); if (sub.containsVar(getPredicateVariable())) return ImmutableList.of(sub.get(getPredicateVariable()).asType()); //determine compatible types from played roles Set<Type> typesFromRoles = getParentQuery().getAtoms(RelationshipAtom.class) .filter(r -> r.getVarNames().contains(getVarName())) .flatMap(r -> r.getRoleVarMap().entries().stream() .filter(e -> e.getValue().equals(getVarName())) .map(Map.Entry::getKey)) .map(role -> role.players().collect(Collectors.toSet())) .reduce(Sets::intersection) .orElse(Sets.newHashSet()); Set<Type> typesFromTypes = getParentQuery().getAtoms(IsaAtom.class) .filter(at -> at.getVarNames().contains(getVarName())) .filter(at -> at != this) .map(Binary::getSchemaConcept) .filter(Objects::nonNull) .filter(Concept::isType) .map(Concept::asType) .collect(Collectors.toSet()); Set<Type> types = typesFromTypes.isEmpty()? typesFromRoles : typesFromRoles.isEmpty()? typesFromTypes: Sets.intersection(typesFromRoles, typesFromTypes); return !types.isEmpty()? ImmutableList.copyOf(ReasonerUtils.top(types)) : tx().admin().getMetaConcept().subs().collect(toImmutableList()); } @Override public IsaAtom inferTypes(ConceptMap sub) { return this .inferEntityType(sub); } @Override public ImmutableList<SchemaConcept> getPossibleTypes() { return inferPossibleTypes(new ConceptMapImpl()); } @Override public List<Atom> atomOptions(ConceptMap sub) { return this.inferPossibleTypes(sub).stream() .map(this::addType) .sorted(Comparator.comparing(Atom::isRuleResolvable)) .collect(Collectors.toList()); } @Override public Stream<ConceptMap> materialise(){ EntityType entityType = getSchemaConcept().asEntityType(); return Stream.of( getParentQuery().getSubstitution() .merge(new ConceptMapImpl(ImmutableMap.of(getVarName(), EntityTypeImpl.from(entityType).addEntityInferred()))) ); } @Override public Atom rewriteWithTypeVariable() { return create(getVarName(), getPredicateVariable().asUserDefined(), getTypeId(), this.isDirect(), getParentQuery()); } @Override public Atom rewriteToUserDefined(Atom parentAtom) { return this.rewriteWithTypeVariable(parentAtom); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/binary/IsaAtomBase.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.atom.binary; import ai.grakn.graql.Var; import ai.grakn.graql.admin.Unifier; import java.util.Collection; import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; /** * * <p> * Base class for isa atoms. * </p> * * @author Kasper Piskorski * */ public abstract class IsaAtomBase extends TypeAtom{ @Override public Set<TypeAtom> unify(Unifier u){ Collection<Var> vars = u.get(getVarName()); return vars.isEmpty()? Collections.singleton(this) : vars.stream().map(v -> IsaAtom.create(v, getPredicateVariable(), getTypeId(), this.isDirect(), this.getParentQuery())).collect(Collectors.toSet()); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/binary/OntologicalAtom.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.atom.binary; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Rule; import ai.grakn.graql.Var; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.Unifier; import ai.grakn.graql.internal.reasoner.atom.Atom; import ai.grakn.graql.internal.reasoner.rule.InferenceRule; import ai.grakn.util.ErrorMessage; import com.google.common.collect.Sets; import java.util.Collection; import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; /** * * <p> * Base class for defining ontological {@link Atom} - ones referring to ontological elements. * </p> * * @author Kasper Piskorski * */ public abstract class OntologicalAtom extends TypeAtom { abstract OntologicalAtom createSelf(Var var, Var predicateVar, ConceptId predicateId, ReasonerQuery parent); @Override public boolean isSelectable() { return true; } @Override public Stream<Rule> getPotentialRules(){ return Stream.empty();} @Override public Stream<InferenceRule> getApplicableRules() { return Stream.empty();} @Override public Set<String> validateAsRuleHead(Rule rule) { return Sets.newHashSet(ErrorMessage.VALIDATION_RULE_ILLEGAL_ATOMIC_IN_HEAD.getMessage(rule.then(), rule.label())); } @Override public Set<TypeAtom> unify(Unifier u){ Collection<Var> vars = u.get(getVarName()); return vars.isEmpty()? Collections.singleton(this) : vars.stream().map(v -> createSelf(v, getPredicateVariable(), getTypeId(), this.getParentQuery())).collect(Collectors.toSet()); } @Override public Atom rewriteWithTypeVariable() { return createSelf(getVarName(), getPredicateVariable().asUserDefined(), getTypeId(), getParentQuery()); } @Override public Atom rewriteToUserDefined(Atom parentAtom) { return parentAtom.getPredicateVariable().isUserDefinedName()? createSelf(getVarName(), getPredicateVariable().asUserDefined(), getTypeId(), getParentQuery()) : this; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/binary/PlaysAtom.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.atom.binary; import ai.grakn.concept.ConceptId; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.VarProperty; import ai.grakn.graql.internal.pattern.property.PlaysProperty; import ai.grakn.graql.internal.reasoner.utils.IgnoreHashEquals; import com.google.auto.value.AutoValue; /** * * <p> * TypeAtom corresponding to graql a {@link ai.grakn.graql.internal.pattern.property.PlaysProperty} property. * </p> * * @author Kasper Piskorski * */ @AutoValue public abstract class PlaysAtom extends OntologicalAtom { @Override @IgnoreHashEquals public abstract Var getPredicateVariable(); @Override @IgnoreHashEquals public abstract VarPattern getPattern(); @Override @IgnoreHashEquals public abstract ReasonerQuery getParentQuery(); public static PlaysAtom create(Var var, Var predicateVar, ConceptId predicateId, ReasonerQuery parent) { return new AutoValue_PlaysAtom(var, predicateId, predicateVar, var.plays(predicateVar), parent); } private static PlaysAtom create(PlaysAtom a, ReasonerQuery parent) { return create(a.getVarName(), a.getPredicateVariable(), a.getTypeId(), parent); } @Override OntologicalAtom createSelf(Var var, Var predicateVar, ConceptId predicateId, ReasonerQuery parent) { return PlaysAtom.create(var, predicateVar, predicateId, parent); } @Override public Atomic copy(ReasonerQuery parent){ return create(this, parent); } @Override public Class<? extends VarProperty> getVarPropertyClass() {return PlaysProperty.class;} }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/binary/RelatesAtom.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.atom.binary; import ai.grakn.concept.ConceptId; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.VarProperty; import ai.grakn.graql.internal.pattern.property.RelatesProperty; import ai.grakn.graql.internal.reasoner.utils.IgnoreHashEquals; import com.google.auto.value.AutoValue; /** * * <p> * TypeAtom corresponding to a graql {@link ai.grakn.graql.internal.pattern.property.RelatesProperty} property. * </p> * * @author Kasper Piskorski * */ @AutoValue public abstract class RelatesAtom extends OntologicalAtom { @Override @IgnoreHashEquals public abstract Var getPredicateVariable(); @Override @IgnoreHashEquals public abstract VarPattern getPattern(); @Override @IgnoreHashEquals public abstract ReasonerQuery getParentQuery(); public static RelatesAtom create(Var var, Var predicateVar, ConceptId predicateId, ReasonerQuery parent) { return new AutoValue_RelatesAtom(var, predicateId, predicateVar, var.relates(predicateVar), parent); } private static RelatesAtom create(RelatesAtom a, ReasonerQuery parent) { return create(a.getVarName(), a.getPredicateVariable(), a.getTypeId(), parent); } @Override OntologicalAtom createSelf(Var var, Var predicateVar, ConceptId predicateId, ReasonerQuery parent) { return RelatesAtom.create(var, predicateVar, predicateId, parent); } @Override public Atomic copy(ReasonerQuery parent){ return create(this, parent); } @Override public Class<? extends VarProperty> getVarPropertyClass() { return RelatesProperty.class;} }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/binary/RelationshipAtom.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.atom.binary; import ai.grakn.GraknTx; import ai.grakn.concept.Concept; import ai.grakn.concept.ConceptId; import ai.grakn.concept.EntityType; import ai.grakn.concept.Label; import ai.grakn.concept.Relationship; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.concept.Rule; import ai.grakn.concept.SchemaConcept; import ai.grakn.concept.Type; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Graql; import ai.grakn.graql.Pattern; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.MultiUnifier; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.RelationPlayer; import ai.grakn.graql.admin.Unifier; import ai.grakn.graql.admin.UnifierComparison; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.admin.VarProperty; import ai.grakn.graql.internal.pattern.property.IsaProperty; import ai.grakn.graql.internal.pattern.property.RelationshipProperty; import ai.grakn.graql.internal.query.answer.ConceptMapImpl; import ai.grakn.graql.internal.reasoner.MultiUnifierImpl; import ai.grakn.graql.internal.reasoner.UnifierImpl; import ai.grakn.graql.internal.reasoner.UnifierType; import ai.grakn.graql.internal.reasoner.atom.Atom; import ai.grakn.graql.internal.reasoner.atom.AtomicEquivalence; import ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate; import ai.grakn.graql.internal.reasoner.atom.predicate.NeqPredicate; import ai.grakn.graql.internal.reasoner.atom.predicate.Predicate; import ai.grakn.graql.internal.reasoner.atom.predicate.ValuePredicate; import ai.grakn.graql.internal.reasoner.query.ReasonerQueryImpl; import ai.grakn.graql.internal.reasoner.utils.Pair; import ai.grakn.graql.internal.reasoner.utils.ReasonerUtils; import ai.grakn.graql.internal.reasoner.utils.conversion.RoleConverter; import ai.grakn.graql.internal.reasoner.utils.conversion.TypeConverter; import ai.grakn.kb.internal.concept.RelationshipTypeImpl; import ai.grakn.util.CommonUtil; import ai.grakn.util.ErrorMessage; import ai.grakn.util.Schema; import com.google.auto.value.AutoValue; import com.google.auto.value.extension.memoized.Memoized; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import java.util.function.BiFunction; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import static ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.compatibleRelationTypesWithRoles; import static ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.compatibleRoles; import static ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.multimapIntersection; import static ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.supers; import static ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.top; import static java.util.stream.Collectors.toSet; /** * * <p> * Atom implementation defining a relation atom corresponding to a combined {@link RelationshipProperty} * and (optional) {@link IsaProperty}. The relation atom is a {@link TypeAtom} with relationship players. * </p> * * @author Kasper Piskorski * */ @AutoValue public abstract class RelationshipAtom extends IsaAtomBase { public abstract ImmutableList<RelationPlayer> getRelationPlayers(); public abstract ImmutableSet<Label> getRoleLabels(); private ImmutableList<SchemaConcept> possibleTypes = null; public static RelationshipAtom create(VarPattern pattern, Var predicateVar, @Nullable ConceptId predicateId, ReasonerQuery parent) { List<RelationPlayer> rps = new ArrayList<>(); pattern.admin() .getProperty(RelationshipProperty.class) .ifPresent(prop -> prop.relationPlayers().stream() .sorted(Comparator.comparing(Object::hashCode)) .forEach(rps::add) ); ImmutableList<RelationPlayer> relationPlayers = ImmutableList.copyOf(rps); ImmutableSet<Label> roleLabels = ImmutableSet.<Label>builder().addAll( relationPlayers.stream() .map(RelationPlayer::getRole) .flatMap(CommonUtil::optionalToStream) .map(VarPatternAdmin::getTypeLabel) .flatMap(CommonUtil::optionalToStream) .iterator() ).build(); return new AutoValue_RelationshipAtom(pattern.admin().var(), pattern, parent, predicateVar, predicateId, relationPlayers, roleLabels); } private static RelationshipAtom create(VarPattern pattern, Var predicateVar, @Nullable ConceptId predicateId, @Nullable ImmutableList<SchemaConcept> possibleTypes, ReasonerQuery parent) { RelationshipAtom atom = create(pattern, predicateVar, predicateId, parent); atom.possibleTypes = possibleTypes; return atom; } private static RelationshipAtom create(RelationshipAtom a, ReasonerQuery parent) { RelationshipAtom atom = new AutoValue_RelationshipAtom( a.getVarName(), a.getPattern(), parent, a.getPredicateVariable(), a.getTypeId(), a.getRelationPlayers(), a.getRoleLabels()); atom.applicableRules = a.applicableRules; atom.possibleTypes = a.possibleTypes; return atom; } //NB: overriding as these require a derived property @Override public final boolean equals(Object obj) { if (obj == this) return true; if (obj == null || this.getClass() != obj.getClass()) return false; RelationshipAtom that = (RelationshipAtom) obj; return Objects.equals(this.getTypeId(), that.getTypeId()) && this.isUserDefined() == that.isUserDefined() && this.isDirect() == that.isDirect() && this.getVarNames().equals(that.getVarNames()) && this.getRelationPlayers().equals(that.getRelationPlayers()); } @Memoized @Override public int hashCode() { int hashCode = 1; hashCode = hashCode * 37 + (getTypeId() != null ? getTypeId().hashCode() : 0); hashCode = hashCode * 37 + getVarNames().hashCode(); hashCode = hashCode * 37 + getRelationPlayers().hashCode(); return hashCode; } @Override public Class<? extends VarProperty> getVarPropertyClass(){ return RelationshipProperty.class;} @Override public void checkValid(){ super.checkValid(); getRoleLabels().stream() .filter(label -> tx().getRole(label.getValue()) == null) .findFirst() .ifPresent(label -> { throw GraqlQueryException.labelNotFound(label); }); } @Override public RelationshipAtom toRelationshipAtom(){ return this;} @Override public IsaAtom toIsaAtom(){ return IsaAtom.create(getVarName(), getPredicateVariable(), getTypeId(), false, getParentQuery()); } @Override public Set<Atom> rewriteToAtoms(){ return this.getRelationPlayers().stream() .map(rp -> create(relationPattern(getVarName(), Sets.newHashSet(rp)), getPredicateVariable(), getTypeId(), null, this.getParentQuery())) .collect(toSet()); } @Override public String toString(){ String typeString = getSchemaConcept() != null? getSchemaConcept().label().getValue() : "{" + inferPossibleTypes(new ConceptMapImpl()).stream().map(rt -> rt.label().getValue()).collect(Collectors.joining(", ")) + "}"; String relationString = (isUserDefined()? getVarName() + " ": "") + typeString + (getPredicateVariable().isUserDefinedName()? "(" + getPredicateVariable() + ")" : "") + (isDirect()? "!" : "") + getRelationPlayers().toString(); return relationString + getPredicates(Predicate.class).map(Predicate::toString).collect(Collectors.joining("")); } @Override public Set<Var> getVarNames() { Set<Var> vars = super.getVarNames(); vars.addAll(getRolePlayers()); vars.addAll(getRoleVariables()); return vars; } /** * @return set constituting the role player var names */ private Set<Var> getRolePlayers() { return getRelationPlayers().stream().map(c -> c.getRolePlayer().var()).collect(toSet()); } /** * @return set of user defined role variables if any */ private Set<Var> getRoleVariables(){ return getRelationPlayers().stream() .map(RelationPlayer::getRole) .flatMap(CommonUtil::optionalToStream) .map(VarPatternAdmin::var) .filter(Var::isUserDefinedName) .collect(Collectors.toSet()); } private ConceptMap getRoleSubstitution(){ Map<Var, Concept> roleSub = new HashMap<>(); getRolePredicates().forEach(p -> roleSub.put(p.getVarName(), tx().getConcept(p.getPredicate()))); return new ConceptMapImpl(roleSub); } @Override public Atomic copy(ReasonerQuery parent) { return create(this, parent); } @Override protected Pattern createCombinedPattern(){ if (getPredicateVariable().isUserDefinedName()) return super.createCombinedPattern(); return getSchemaConcept() == null? relationPattern() : isDirect()? relationPattern().isaExplicit(getSchemaConcept().label().getValue()): relationPattern().isa(getSchemaConcept().label().getValue()); } private VarPattern relationPattern() { return relationPattern(getVarName(), getRelationPlayers()); } /** * construct a $varName (rolemap) isa $typeVariable relation * @param varName variable name * @param relationPlayers collection of rolePlayer-roleType mappings * @return corresponding {@link VarPatternAdmin} */ private VarPattern relationPattern(Var varName, Collection<RelationPlayer> relationPlayers) { VarPattern var = varName; for (RelationPlayer rp : relationPlayers) { VarPatternAdmin rolePattern = rp.getRole().orElse(null); var = rolePattern != null? var.rel(rolePattern, rp.getRolePlayer()) : var.rel(rp.getRolePlayer()); } return var.admin(); } private boolean isBaseEquivalent(Object obj){ if (obj == null || this.getClass() != obj.getClass()) return false; if (obj == this) return true; RelationshipAtom that = (RelationshipAtom) obj; return this. isUserDefined() == that.isUserDefined() && this.getPredicateVariable().isUserDefinedName() == that.getPredicateVariable().isUserDefinedName() && this.isDirect() == that.isDirect() && Objects.equals(this.getTypeId(), that.getTypeId()) //check relation players equivalent && this.getRolePlayers().size() == that.getRolePlayers().size() && this.getRelationPlayers().size() == that.getRelationPlayers().size() && this.getRoleLabels().equals(that.getRoleLabels()); } private int baseHashCode(){ int baseHashCode = 1; baseHashCode = baseHashCode * 37 + (this.getTypeId() != null ? this.getTypeId().hashCode() : 0); baseHashCode = baseHashCode * 37 + this.getRoleLabels().hashCode(); return baseHashCode; } @Override public boolean isAlphaEquivalent(Object obj) { if (!isBaseEquivalent(obj) || !super.isAlphaEquivalent(obj)) return false; RelationshipAtom that = (RelationshipAtom) obj; //check role-type and id predicate bindings return this.getRoleTypeMap().equals(that.getRoleTypeMap()) && this.predicateBindingsAlphaEquivalent(that); } @Override public int alphaEquivalenceHashCode() { int equivalenceHashCode = baseHashCode(); equivalenceHashCode = equivalenceHashCode * 37 + this.getRoleTypeMap().hashCode(); equivalenceHashCode = equivalenceHashCode * 37 + this.getRoleConceptIdMap().hashCode(); return equivalenceHashCode; } private boolean predicateBindingsEquivalent(RelationshipAtom atom, BiFunction<String, String, Boolean> conceptComparison, AtomicEquivalence equivalence) { Multimap<Role, String> thisIdMap = this.getRoleConceptIdMap(); Multimap<Role, String> thatIdMap = atom.getRoleConceptIdMap(); Multimap<Role, NeqPredicate> thisNeqMap = this.getRoleNeqPredicateMap(); Multimap<Role, NeqPredicate> thatNeqMap = atom.getRoleNeqPredicateMap(); Multimap<Role, ValuePredicate> thisValueMap = this.getRoleValueMap(); Multimap<Role, ValuePredicate> thatValueMap = atom.getRoleValueMap(); return thisIdMap.keySet().equals(thatIdMap.keySet()) && thisIdMap.keySet().stream().allMatch(k -> ReasonerUtils.isEquivalentCollection(thisIdMap.get(k), thatIdMap.get(k), conceptComparison)) && thisNeqMap.keySet().equals(thatNeqMap.keySet()) && thisNeqMap.keySet().stream().allMatch(k -> ReasonerUtils.isEquivalentCollection(thisNeqMap.get(k), thatNeqMap.get(k), equivalence)) && thisValueMap.keySet().equals(thatValueMap.keySet()) && thisValueMap.keySet().stream().allMatch(k -> ReasonerUtils.isEquivalentCollection(thisValueMap.get(k), thatValueMap.get(k), equivalence)); } private boolean predicateBindingsAlphaEquivalent(RelationshipAtom atom) { return predicateBindingsEquivalent(atom, String::equals, AtomicEquivalence.AlphaEquivalence); } private boolean predicateBindingsStructurallyEquivalent(RelationshipAtom atom) { return predicateBindingsEquivalent(atom, (a, b) -> true, AtomicEquivalence.StructuralEquivalence); } @Override public boolean isStructurallyEquivalent(Object obj) { if (!isBaseEquivalent(obj) || !super.isStructurallyEquivalent(obj)) return false; RelationshipAtom that = (RelationshipAtom) obj; // check bindings return this.getRoleTypeMap(false).equals(that.getRoleTypeMap(false)) && this.predicateBindingsStructurallyEquivalent(that); } @Override public int structuralEquivalenceHashCode() { int equivalenceHashCode = baseHashCode(); equivalenceHashCode = equivalenceHashCode * 37 + this.getRoleTypeMap(false).hashCode(); equivalenceHashCode = equivalenceHashCode * 37 + this.getRoleConceptIdMap().keySet().hashCode(); return equivalenceHashCode; } @Override public boolean isRelation() { return true; } @Override public boolean isSelectable() { return true; } @Override public boolean isType() { return getSchemaConcept() != null; } @Override public boolean requiresMaterialisation() { return isUserDefined(); } @Override public boolean requiresRoleExpansion() { return !getRoleVariables().isEmpty(); } @Override public Set<String> validateAsRuleHead(Rule rule){ //can form a rule head if type is specified, type is not implicit and all relation players are insertable return Sets.union(super.validateAsRuleHead(rule), validateRelationPlayers(rule)); } private Set<String> validateRelationPlayers(Rule rule){ Set<String> errors = new HashSet<>(); getRelationPlayers().forEach(rp -> { VarPatternAdmin role = rp.getRole().orElse(null); if (role == null){ errors.add(ErrorMessage.VALIDATION_RULE_ILLEGAL_HEAD_RELATION_WITH_AMBIGUOUS_ROLE.getMessage(rule.then(), rule.label())); } else { Label roleLabel = role.getTypeLabel().orElse(null); if (roleLabel == null){ errors.add(ErrorMessage.VALIDATION_RULE_ILLEGAL_HEAD_RELATION_WITH_AMBIGUOUS_ROLE.getMessage(rule.then(), rule.label())); } else { if (Schema.MetaSchema.isMetaLabel(roleLabel)) { errors.add(ErrorMessage.VALIDATION_RULE_ILLEGAL_HEAD_RELATION_WITH_AMBIGUOUS_ROLE.getMessage(rule.then(), rule.label())); } Role roleType = tx().getRole(roleLabel.getValue()); if (roleType != null && roleType.isImplicit()) { errors.add(ErrorMessage.VALIDATION_RULE_ILLEGAL_HEAD_RELATION_WITH_IMPLICIT_ROLE.getMessage(rule.then(), rule.label())); } } } }); return errors; } @Override public Set<String> validateOntologically() { Set<String> errors = new HashSet<>(); SchemaConcept type = getSchemaConcept(); if (type != null && !type.isRelationshipType()){ errors.add(ErrorMessage.VALIDATION_RULE_INVALID_RELATION_TYPE.getMessage(type.label())); return errors; } //check role-type compatibility Map<Var, Type> varTypeMap = getParentQuery().getVarTypeMap(); for (Map.Entry<Role, Collection<Var>> e : getRoleVarMap().asMap().entrySet() ){ Role role = e.getKey(); if (!Schema.MetaSchema.isMetaLabel(role.label())) { //check whether this role can be played in this relation if (type != null && type.asRelationshipType().roles().noneMatch(r -> r.equals(role))) { errors.add(ErrorMessage.VALIDATION_RULE_ROLE_CANNOT_BE_PLAYED.getMessage(role.label(), type.label())); } //check whether the role player's type allows playing this role for (Var player : e.getValue()) { Type playerType = varTypeMap.get(player); if (playerType != null && playerType.playing().noneMatch(plays -> plays.equals(role))) { errors.add(ErrorMessage.VALIDATION_RULE_TYPE_CANNOT_PLAY_ROLE.getMessage(playerType.label(), role.label(), type == null? "" : type.label())); } } } } return errors; } @Override public Stream<IdPredicate> getPartialSubstitutions() { Set<Var> varNames = getVarNames(); return getPredicates(IdPredicate.class) .filter(pred -> varNames.contains(pred.getVarName())); } public Stream<IdPredicate> getRolePredicates(){ return getRelationPlayers().stream() .map(RelationPlayer::getRole) .flatMap(CommonUtil::optionalToStream) .filter(var -> var.var().isUserDefinedName()) .filter(vp -> vp.getTypeLabel().isPresent()) .map(vp -> { Label label = vp.getTypeLabel().orElse(null); return IdPredicate.create(vp.var(), tx().getRole(label.getValue()), getParentQuery()); }); } private <T extends Predicate> Multimap<Role, T> getRolePredicateMap(Class<T> type) { HashMultimap<Role, T> rolePredicateMap = HashMultimap.create(); HashMultimap<Var, T> predicateMap = HashMultimap.create(); getPredicates(type).forEach(p -> p.getVarNames().forEach(v -> predicateMap.put(v, p))); Multimap<Role, Var> roleMap = getRoleVarMap(); roleMap.entries().stream() .filter(e -> predicateMap.containsKey(e.getValue())) .forEach(e -> rolePredicateMap.putAll(e.getKey(), predicateMap.get(e.getValue()))); return rolePredicateMap; } /** * @return map of pairs role type - Id predicate describing the role player playing this role (substitution) */ @Memoized public Multimap<Role, String> getRoleConceptIdMap() { ImmutableMultimap.Builder<Role, String> builder = ImmutableMultimap.builder(); getRolePredicateMap(IdPredicate.class) .entries() .forEach(e -> builder.put(e.getKey(), e.getValue().getPredicateValue())); return builder.build(); } @Memoized public Multimap<Role, ValuePredicate> getRoleValueMap() { ImmutableMultimap.Builder<Role, ValuePredicate> builder = ImmutableMultimap.builder(); getRolePredicateMap(ValuePredicate.class) .entries() .forEach(e -> builder.put(e.getKey(), e.getValue())); return builder.build(); } @Memoized public Multimap<Role, NeqPredicate> getRoleNeqPredicateMap() { ImmutableMultimap.Builder<Role, NeqPredicate> builder = ImmutableMultimap.builder(); getRolePredicateMap(NeqPredicate.class) .entries() .forEach(e -> builder.put(e.getKey(), e.getValue())); return builder.build(); } @Memoized public Multimap<Role, Type> getRoleTypeMap() { return getRoleTypeMap(false); } public Multimap<Role, Type> getRoleTypeMap(boolean inferTypes) { ImmutableMultimap.Builder<Role, Type> builder = ImmutableMultimap.builder(); Multimap<Role, Var> roleMap = getRoleVarMap(); Map<Var, Type> varTypeMap = getParentQuery().getVarTypeMap(); roleMap.entries().stream() .filter(e -> varTypeMap.containsKey(e.getValue())) .filter(e -> { return inferTypes || getParentQuery().getAtoms(TypeAtom.class) .filter(t -> t.getVarName().equals(e.getValue())) .filter(t -> Objects.nonNull(t.getSchemaConcept())) .anyMatch(t -> t.getSchemaConcept().equals(varTypeMap.get(e.getValue()))); }) .sorted(Comparator.comparing(e -> varTypeMap.get(e.getValue()).label())) .forEach(e -> builder.put(e.getKey(), varTypeMap.get(e.getValue()))); return builder.build(); } private Stream<Role> getExplicitRoles() { ReasonerQueryImpl parent = (ReasonerQueryImpl) getParentQuery(); GraknTx graph = parent.tx(); return getRelationPlayers().stream() .map(RelationPlayer::getRole) .flatMap(CommonUtil::optionalToStream) .map(VarPatternAdmin::getTypeLabel) .flatMap(CommonUtil::optionalToStream) .map(graph::<Role>getSchemaConcept); } @Override public boolean isUnifiableWith(Atom atom){ //findbugs complains about cast without it if (!(atom instanceof RelationshipAtom)) return false; RelationshipAtom that = (RelationshipAtom) atom; //rule head atom is applicable if it is unifiable return !this.getRelationPlayerMappings(that).isEmpty(); } @Override public boolean isRuleApplicableViaAtom(Atom ruleAtom) { if (!(ruleAtom instanceof RelationshipAtom)) return isRuleApplicableViaAtom(ruleAtom.toRelationshipAtom()); RelationshipAtom atomWithType = this.addType(ruleAtom.getSchemaConcept()).inferRoles(new ConceptMapImpl()); return ruleAtom.isUnifiableWith(atomWithType); } @Override public RelationshipAtom addType(SchemaConcept type) { if (getTypeId() != null) return this; //NB: do not cache possible types return create(this.getPattern(), this.getPredicateVariable(), type.id(), this.getParentQuery()); } /** * infer {@link RelationshipType}s that this {@link RelationshipAtom} can potentially have * NB: {@link EntityType}s and link {@link Role}s are treated separately as they behave differently: * {@link EntityType}s only play the explicitly defined {@link Role}s (not the relevant part of the hierarchy of the specified {@link Role}) and the {@link Role} inherited from parent * @return list of {@link RelationshipType}s this atom can have ordered by the number of compatible {@link Role}s */ private Set<Type> inferPossibleEntityTypePlayers(ConceptMap sub){ return inferPossibleRelationConfigurations(sub).asMap().entrySet().stream() .flatMap(e -> { Set<Role> rs = e.getKey().roles().collect(toSet()); rs.removeAll(e.getValue()); return rs.stream().flatMap(Role::players); }).collect(Collectors.toSet()); } /** * @return a map of relationships and corresponding roles that could be played by this atom */ private Multimap<RelationshipType, Role> inferPossibleRelationConfigurations(ConceptMap sub){ Set<Role> roles = getExplicitRoles().filter(r -> !Schema.MetaSchema.isMetaLabel(r.label())).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.roles().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; } //no types from roles -> roles correspond to mutually exclusive relations else if(compatibleTypesFromRoles.isEmpty() || types.isEmpty()){ compatibleTypes = compatibleTypesFromRoles; } else { compatibleTypes = multimapIntersection(compatibleTypesFromTypes, compatibleTypesFromRoles); } return compatibleTypes; } @Override public ImmutableList<SchemaConcept> getPossibleTypes(){ return inferPossibleTypes(new ConceptMapImpl());} /** * infer {@link RelationshipType}s that this {@link RelationshipAtom} can potentially have * NB: {@link EntityType}s and link {@link Role}s are treated separately as they behave differently: * NB: Not using Memoized as memoized methods can't have parameters * {@link EntityType}s only play the explicitly defined {@link Role}s (not the relevant part of the hierarchy of the specified {@link Role}) and the {@link Role} inherited from parent * @return list of {@link RelationshipType}s this atom can have ordered by the number of compatible {@link Role}s */ private ImmutableList<SchemaConcept> inferPossibleTypes(ConceptMap sub) { if (possibleTypes == null) { if (getSchemaConcept() != null) return ImmutableList.of(getSchemaConcept()); Multimap<RelationshipType, Role> compatibleConfigurations = inferPossibleRelationConfigurations(sub); Set<Var> untypedRoleplayers = Sets.difference(getRolePlayers(), getParentQuery().getVarTypeMap().keySet()); Set<RelationshipAtom> untypedNeighbours = getNeighbours(RelationshipAtom.class) .filter(at -> !Sets.intersection(at.getVarNames(), untypedRoleplayers).isEmpty()) .collect(toSet()); ImmutableList.Builder<SchemaConcept> builder = ImmutableList.builder(); //prioritise relations with higher chance of yielding answers compatibleConfigurations.asMap().entrySet().stream() //prioritise relations with more allowed roles .sorted(Comparator.comparing(e -> -e.getValue().size())) //prioritise relations with number of roles equal to arity .sorted(Comparator.comparing(e -> e.getKey().roles().count() != getRelationPlayers().size())) //prioritise relations having more instances .sorted(Comparator.comparing(e -> -tx().getShardCount(e.getKey()))) //prioritise relations with highest number of possible types played by untyped role players .map(e -> { if (untypedNeighbours.isEmpty()) return new Pair<>(e.getKey(), 0L); Iterator<RelationshipAtom> neighbourIterator = untypedNeighbours.iterator(); Set<Type> typesFromNeighbour = neighbourIterator.next().inferPossibleEntityTypePlayers(sub); while (neighbourIterator.hasNext()) { typesFromNeighbour = Sets.intersection(typesFromNeighbour, neighbourIterator.next().inferPossibleEntityTypePlayers(sub)); } Set<Role> rs = e.getKey().roles().collect(toSet()); rs.removeAll(e.getValue()); return new Pair<>( e.getKey(), rs.stream().flatMap(Role::players).filter(typesFromNeighbour::contains).count() ); }) .sorted(Comparator.comparing(p -> -p.getValue())) //prioritise non-implicit relations .sorted(Comparator.comparing(e -> e.getKey().isImplicit())) .map(Pair::getKey) //retain super types only .filter(t -> Sets.intersection(supers(t), compatibleConfigurations.keySet()).isEmpty()) .forEach(builder::add); //TODO need to add THING and meta relation type as well to make it complete this.possibleTypes = builder.build(); } return possibleTypes; } /** * attempt to infer the relation type of this relationship * @param sub extra instance information to aid entity type inference * @return either this if relation type can't be inferred or a fresh relationship with inferred relationship type */ private RelationshipAtom inferRelationshipType(ConceptMap sub){ if (getTypePredicate() != null) return this; if (sub.containsVar(getPredicateVariable())) return addType(sub.get(getPredicateVariable()).asType()); List<SchemaConcept> relationshipTypes = inferPossibleTypes(sub); if (relationshipTypes.size() == 1) return addType(Iterables.getOnlyElement(relationshipTypes)); return this; } @Override public RelationshipAtom inferTypes(ConceptMap sub) { return this .inferRelationshipType(sub) .inferRoles(sub); } @Override public List<Atom> atomOptions(ConceptMap sub) { return this.inferPossibleTypes(sub).stream() .map(this::addType) .map(at -> at.inferRoles(sub)) //order by number of distinct roles .sorted(Comparator.comparing(at -> -at.getRoleLabels().size())) .sorted(Comparator.comparing(Atom::isRuleResolvable)) .collect(Collectors.toList()); } @Override public Set<Var> getRoleExpansionVariables(){ return getRelationPlayers().stream() .map(RelationPlayer::getRole) .flatMap(CommonUtil::optionalToStream) .filter(p -> p.var().isUserDefinedName()) .filter(p -> !p.getTypeLabel().isPresent()) .map(VarPatternAdmin::var) .collect(Collectors.toSet()); } @Override public Stream<Predicate> getInnerPredicates(){ return Stream.concat( super.getInnerPredicates(), getRelationPlayers().stream() .map(RelationPlayer::getRole) .flatMap(CommonUtil::optionalToStream) .filter(vp -> vp.var().isUserDefinedName()) .map(vp -> new Pair<>(vp.var(), vp.getTypeLabel().orElse(null))) .filter(p -> Objects.nonNull(p.getValue())) .map(p -> IdPredicate.create(p.getKey(), p.getValue(), getParentQuery())) ); } /** * 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(ConceptMap 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.label())); 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.roles().collect(toSet()) : inferPossibleTypes(sub).stream() .filter(Concept::isRelationshipType) .map(Concept::asRelationshipType) .flatMap(RelationshipType::roles).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.label()).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.label()).admin() : Graql.var().label(metaRole.label()).admin(); inferredRelationPlayers.add(RelationPlayer.of(rolePattern, varName.admin())); }); VarPattern relationPattern = relationPattern(getVarName(), inferredRelationPlayers); VarPatternAdmin newPattern = (isDirect()? relationPattern.isaExplicit(getPredicateVariable()) : relationPattern.isa(getPredicateVariable()) ).admin(); return create(newPattern, this.getPredicateVariable(), this.getTypeId(), this.getPossibleTypes(), this.getParentQuery()); } /** * @return map containing roleType - (rolePlayer var - rolePlayer type) pairs */ @Memoized public Multimap<Role, Var> getRoleVarMap() { ImmutableMultimap.Builder<Role, Var> builder = ImmutableMultimap.builder(); GraknTx graph = getParentQuery().tx(); getRelationPlayers().forEach(c -> { Var varName = c.getRolePlayer().var(); VarPatternAdmin rolePattern = c.getRole().orElse(null); if (rolePattern != null) { //try directly Label typeLabel = rolePattern.getTypeLabel().orElse(null); Role role = typeLabel != null ? graph.getRole(typeLabel.getValue()) : null; //try indirectly if (role == null && rolePattern.var().isUserDefinedName()) { IdPredicate rolePredicate = getIdPredicate(rolePattern.var()); if (rolePredicate != null){ Role r = graph.getConcept(rolePredicate.getPredicate()); if (r == null) throw GraqlQueryException.idNotFound(rolePredicate.getPredicate()); role = r; } } if (role != null) builder.put(role, varName); } }); return builder.build(); } private Multimap<Role, RelationPlayer> getRoleRelationPlayerMap(){ Multimap<Role, RelationPlayer> roleRelationPlayerMap = ArrayListMultimap.create(); Multimap<Role, Var> roleVarMap = getRoleVarMap(); List<RelationPlayer> relationPlayers = getRelationPlayers(); roleVarMap.asMap().forEach((role, value) -> { Label roleLabel = role.label(); relationPlayers.stream() .filter(rp -> rp.getRole().isPresent()) .forEach(rp -> { VarPatternAdmin roleTypeVar = rp.getRole().orElse(null); Label rl = roleTypeVar != null ? roleTypeVar.getTypeLabel().orElse(null) : null; if (roleLabel != null && roleLabel.equals(rl)) { roleRelationPlayerMap.put(role, rp); } }); }); return roleRelationPlayerMap; } private Set<List<Pair<RelationPlayer, RelationPlayer>>> getRelationPlayerMappings(RelationshipAtom parentAtom) { return getRelationPlayerMappings(parentAtom, UnifierType.RULE); } /** * @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(!matchType.equals(UnifierType.STRUCTURAL)); Map<Var, Type> parentVarTypeMap = parentAtom.getParentQuery().getVarTypeMap(!matchType.equals(UnifierType.STRUCTURAL)); //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() //check for inter-type compatibility .filter(crp -> { Var childVar = crp.getRolePlayer().var(); Type childType = childVarTypeMap.get(childVar); return matchType.typePlayability(childQuery, childVar, parentType) && matchType.typeCompatibility(parentType, childType); }) //check for substitution compatibility .filter(crp -> { IdPredicate parentId = parentAtom.getIdPredicate(prp.getRolePlayer().var()); IdPredicate childId = this.getIdPredicate(crp.getRolePlayer().var()); return matchType.idCompatibility(parentId, childId); }) //check for value predicate compatibility .filter(crp -> { ValuePredicate parentVP = parentAtom.getPredicate(prp.getRolePlayer().var(), ValuePredicate.class); ValuePredicate childVP = this.getPredicate(crp.getRolePlayer().var(), ValuePredicate.class); return matchType.valueCompatibility(parentVP, childVP); }) //check linked resources .filter(crp -> { Var parentVar = prp.getRolePlayer().var(); Var childVar = crp.getRolePlayer().var(); return matchType.attributeCompatibility(parentAtom.getParentQuery(), this.getParentQuery(), parentVar, childVar); }) .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()) //check the same child rp is not mapped to multiple parent rps .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(); }) //check all parent rps mapped .filter(list -> { List<RelationPlayer> listParentRps = list.stream().map(Pair::getValue).collect(Collectors.toList()); return listParentRps.containsAll(parentAtom.getRelationPlayers()); }) .collect(toSet()); } @Override public Unifier getUnifier(Atom pAtom, UnifierComparison unifierType){ return getMultiUnifier(pAtom, unifierType).getUnifier(); } @Override public MultiUnifier getMultiUnifier(Atom pAtom, UnifierComparison unifierType) { Unifier baseUnifier = super.getUnifier(pAtom, unifierType); if (baseUnifier == null){ return MultiUnifierImpl.nonExistent();} Set<Unifier> unifiers = new HashSet<>(); if (pAtom.isRelation()) { RelationshipAtom parentAtom = pAtom.toRelationshipAtom(); //NB: if two atoms are equal and their sub and type mappings are equal we return the identity unifier //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 MultiUnifierImpl.trivial(); } 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); } @Override public Stream<ConceptMap> materialise(){ RelationshipType relationType = getSchemaConcept().asRelationshipType(); Multimap<Role, Var> roleVarMap = getRoleVarMap(); ConceptMap substitution = getParentQuery().getSubstitution(); //if the relation already exists, only assign roleplayers, otherwise create a new relation Relationship relationship = substitution.containsVar(getVarName())? substitution.get(getVarName()).asRelationship() : RelationshipTypeImpl.from(relationType).addRelationshipInferred(); roleVarMap.asMap().forEach((key, value) -> value.forEach(var -> relationship.assign(key, substitution.get(var).asThing()))); ConceptMap relationSub = getRoleSubstitution().merge( getVarName().isUserDefinedName()? new ConceptMapImpl(ImmutableMap.of(getVarName(), relationship)) : new ConceptMapImpl() ); return Stream.of(substitution.merge(relationSub)); } /** * if any {@link Role} variable of the parent is user defined rewrite ALL {@link Role} variables to user defined (otherwise unification is problematic) * @param parentAtom parent atom that triggers rewrite * @return new relation atom with user defined {@link Role} variables if necessary or this */ private RelationshipAtom rewriteWithVariableRoles(Atom parentAtom){ if (!parentAtom.requiresRoleExpansion()) return this; VarPattern relVar = getPattern().admin().getProperty(IsaProperty.class) .map(prop -> getVarName().isa(prop.type())).orElse(getVarName()); for (RelationPlayer rp: getRelationPlayers()) { VarPatternAdmin rolePattern = rp.getRole().orElse(null); if (rolePattern != null) { Var roleVar = rolePattern.var(); Label roleLabel = rolePattern.getTypeLabel().orElse(null); relVar = relVar.rel(roleVar.asUserDefined().label(roleLabel), rp.getRolePlayer()); } else { relVar = relVar.rel(rp.getRolePlayer()); } } return create(relVar.admin(), this.getPredicateVariable(), this.getTypeId(), this.getPossibleTypes(), this.getParentQuery()); } /** * @param parentAtom parent atom that triggers rewrite * @return new relation atom with user defined name if necessary or this */ private RelationshipAtom rewriteWithRelationVariable(Atom parentAtom){ if (this.getVarName().isUserDefinedName() || !parentAtom.getVarName().isUserDefinedName()) return this; return rewriteWithRelationVariable(); } @Override public RelationshipAtom rewriteWithRelationVariable(){ VarPattern newVar = Graql.var().asUserDefined(); VarPattern relVar = getPattern().admin().getProperty(IsaProperty.class) .map(prop -> newVar.isa(prop.type())) .orElse(newVar); for (RelationPlayer c: getRelationPlayers()) { VarPatternAdmin roleType = c.getRole().orElse(null); if (roleType != null) { relVar = relVar.rel(roleType, c.getRolePlayer()); } else { relVar = relVar.rel(c.getRolePlayer()); } } return create(relVar.admin(), this.getPredicateVariable(), this.getTypeId(), this.getPossibleTypes(), this.getParentQuery()); } @Override public RelationshipAtom rewriteWithTypeVariable(){ return create(this.getPattern(), this.getPredicateVariable().asUserDefined(), this.getTypeId(), this.getPossibleTypes(), this.getParentQuery()); } @Override public Atom rewriteToUserDefined(Atom parentAtom){ return this .rewriteWithRelationVariable(parentAtom) .rewriteWithVariableRoles(parentAtom) .rewriteWithTypeVariable(parentAtom); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/binary/ResourceAtom.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.atom.binary; import ai.grakn.GraknTx; import ai.grakn.concept.Attribute; import ai.grakn.concept.Concept; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Label; import ai.grakn.concept.Rule; import ai.grakn.concept.SchemaConcept; import ai.grakn.concept.Type; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Graql; import ai.grakn.graql.Pattern; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.UnifierComparison; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.Unifier; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.admin.VarProperty; import ai.grakn.graql.internal.pattern.Patterns; import ai.grakn.graql.internal.pattern.property.HasAttributeProperty; import ai.grakn.graql.internal.query.answer.ConceptMapImpl; import ai.grakn.graql.internal.reasoner.UnifierImpl; import ai.grakn.graql.internal.reasoner.atom.Atom; import ai.grakn.graql.internal.reasoner.atom.AtomicEquivalence; import ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate; import ai.grakn.graql.internal.reasoner.atom.predicate.Predicate; import ai.grakn.graql.internal.reasoner.atom.predicate.ValuePredicate; import ai.grakn.graql.internal.reasoner.query.ReasonerQueryImpl; import ai.grakn.kb.internal.concept.AttributeImpl; import ai.grakn.kb.internal.concept.AttributeTypeImpl; import ai.grakn.kb.internal.concept.EntityImpl; import ai.grakn.kb.internal.concept.RelationshipImpl; import ai.grakn.util.ErrorMessage; import ai.grakn.util.Schema; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import java.util.stream.Stream; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import static ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.areDisjointTypes; import static ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.isEquivalentCollection; /** * * <p> * Atom implementation defining a resource atom corresponding to a {@link HasAttributeProperty}. * The resource structure is the following: * * has($varName, $predicateVariable = resource variable), type($predicateVariable) * * or in graql terms: * * $varName has <type> $predicateVariable; $predicateVariable isa <type>; * * </p> * * @author Kasper Piskorski * */ @AutoValue public abstract class ResourceAtom extends Binary{ public abstract Var getRelationVariable(); public abstract ImmutableSet<ValuePredicate> getMultiPredicate(); public static ResourceAtom create(VarPattern pattern, Var attributeVar, Var relationVariable, ConceptId predicateId, Set<ValuePredicate> ps, ReasonerQuery parent) { return new AutoValue_ResourceAtom(pattern.admin().var(), pattern, parent, attributeVar, predicateId, relationVariable, ImmutableSet.copyOf(ps)); } private static ResourceAtom create(ResourceAtom a, ReasonerQuery parent) { ResourceAtom atom = create(a.getPattern(), a.getPredicateVariable(), a.getRelationVariable(), a.getTypeId(), a.getMultiPredicate(), parent); atom.applicableRules = a.applicableRules; return atom; } @Override public Atomic copy(ReasonerQuery parent){ return create(this, parent);} @Override public Class<? extends VarProperty> getVarPropertyClass() { return HasAttributeProperty.class;} @Override public RelationshipAtom toRelationshipAtom(){ SchemaConcept type = getSchemaConcept(); if (type == null) throw GraqlQueryException.illegalAtomConversion(this, RelationshipAtom.class); GraknTx tx = getParentQuery().tx(); Label typeLabel = Schema.ImplicitType.HAS.getLabel(type.label()); return RelationshipAtom.create( Graql.var() .rel(Schema.ImplicitType.HAS_OWNER.getLabel(type.label()).getValue(), getVarName()) .rel(Schema.ImplicitType.HAS_VALUE.getLabel(type.label()).getValue(), getPredicateVariable()) .isa(typeLabel.getValue()) .admin(), getPredicateVariable(), tx.getSchemaConcept(typeLabel).id(), getParentQuery() ); } /** * NB: this is somewhat ambiguous cause from {$x has resource $r;} we can extract: * - $x isa ???; * - $r isa resource; * We pick the latter as the type information is available. * * @return corresponding isa atom */ @Override public IsaAtom toIsaAtom(){ return IsaAtom.create(getPredicateVariable(), Graql.var(), getTypeId(), false, getParentQuery()); } @Override public String toString(){ String multiPredicateString = getMultiPredicate().isEmpty()? getPredicateVariable().toString() : getMultiPredicate().stream().map(Predicate::getPredicate).collect(Collectors.toSet()).toString(); return getVarName() + " has " + getSchemaConcept().label() + " " + multiPredicateString + getPredicates(Predicate.class).map(Predicate::toString).collect(Collectors.joining("")) + (getRelationVariable().isUserDefinedName()? "(" + getRelationVariable() + ")" : ""); } @Override public final boolean equals(Object obj) { if (obj == null || this.getClass() != obj.getClass()) return false; if (obj == this) return true; ResourceAtom a2 = (ResourceAtom) obj; return Objects.equals(this.getTypeId(), a2.getTypeId()) && this.getVarName().equals(a2.getVarName()) && this.multiPredicateEquivalent(a2, AtomicEquivalence.Equality); } private boolean multiPredicateEquivalent(ResourceAtom that, AtomicEquivalence equiv){ return isEquivalentCollection(this.getMultiPredicate(), that.getMultiPredicate(), equiv); } @Override public final int hashCode() { int hashCode = this.alphaEquivalenceHashCode(); hashCode = hashCode * 37 + this.getVarName().hashCode(); return hashCode; } @Override public int alphaEquivalenceHashCode() { int hashCode = 1; hashCode = hashCode * 37 + (this.getTypeId() != null? this.getTypeId().hashCode() : 0); hashCode = hashCode * 37 + AtomicEquivalence.equivalenceHash(this.getMultiPredicate(), AtomicEquivalence.AlphaEquivalence); return hashCode; } @Override boolean predicateBindingsEquivalent(Binary at, AtomicEquivalence equiv) { if (!(at instanceof ResourceAtom && super.predicateBindingsEquivalent(at, equiv))) return false; ResourceAtom that = (ResourceAtom) at; if (!multiPredicateEquivalent(that, equiv)) return false; IdPredicate thisPredicate = this.getIdPredicate(this.getPredicateVariable()); IdPredicate predicate = that.getIdPredicate(that.getPredicateVariable()); return thisPredicate == null && predicate == null || thisPredicate != null && equiv.equivalent(thisPredicate, predicate); } @Override protected Pattern createCombinedPattern(){ Set<VarPatternAdmin> vars = getMultiPredicate().stream() .map(Atomic::getPattern) .map(VarPattern::admin) .collect(Collectors.toSet()); vars.add(getPattern().admin()); return Patterns.conjunction(vars); } @Override public boolean isRuleApplicableViaAtom(Atom ruleAtom) { //findbugs complains about cast without it if (!(ruleAtom instanceof ResourceAtom)) return false; ResourceAtom childAtom = (ResourceAtom) ruleAtom; return childAtom.isUnifiableWith(this); } @Override public boolean isUnifiableWith(Atom atom) { //findbugs complains about cast without it if (!(atom instanceof ResourceAtom)) return false; ResourceAtom parent = (ResourceAtom) atom; ReasonerQueryImpl childQuery = (ReasonerQueryImpl) this.getParentQuery(); //check type bindings compatibility Type childType = childQuery.getVarTypeMap().get(this.getVarName()); Type parentType = parent.getParentQuery().getVarTypeMap().get(parent.getVarName()); if (childType != null && parentType != null && areDisjointTypes(childType, parentType) || !childQuery.isTypeRoleCompatible(this.getVarName(), parentType)) return false; //check value predicate compatibility return parent.getMultiPredicate().isEmpty() || this.getMultiPredicate().isEmpty() || this.getMultiPredicate().stream().allMatch(childPredicate -> parent.getMultiPredicate().stream().anyMatch(parentPredicate -> parentPredicate.isCompatibleWith(childPredicate))); } @Override public boolean isResource(){ return true;} @Override public boolean isSelectable(){ return true;} public boolean isSpecific(){ return getMultiPredicate().stream().anyMatch(p -> p.getPredicate().isSpecific());} @Override public boolean requiresMaterialisation(){ return true;} @Override public Set<String> validateAsRuleHead(Rule rule){ Set<String> errors = super.validateAsRuleHead(rule); if (getSchemaConcept() == null || getMultiPredicate().size() > 1){ errors.add(ErrorMessage.VALIDATION_RULE_ILLEGAL_HEAD_RESOURCE_WITH_AMBIGUOUS_PREDICATES.getMessage(rule.then(), rule.label())); } if (getMultiPredicate().isEmpty()){ boolean predicateBound = getParentQuery().getAtoms(Atom.class) .filter(at -> !at.equals(this)) .anyMatch(at -> at.getVarNames().contains(getPredicateVariable())); if (!predicateBound) { errors.add(ErrorMessage.VALIDATION_RULE_ILLEGAL_HEAD_ATOM_WITH_UNBOUND_VARIABLE.getMessage(rule.then(), rule.label())); } } getMultiPredicate().stream() .filter(p -> !p.getPredicate().isSpecific()) .forEach( p -> errors.add(ErrorMessage.VALIDATION_RULE_ILLEGAL_HEAD_RESOURCE_WITH_NONSPECIFIC_PREDICATE.getMessage(rule.then(), rule.label())) ); return errors; } @Override public Set<Var> getVarNames() { Set<Var> varNames = super.getVarNames(); getMultiPredicate().stream().flatMap(p -> p.getVarNames().stream()).forEach(varNames::add); if (getRelationVariable().isUserDefinedName()) varNames.add(getRelationVariable()); return varNames; } @Override public Set<String> validateOntologically() { SchemaConcept type = getSchemaConcept(); Set<String> errors = new HashSet<>(); if (type == null) return errors; if (!type.isAttributeType()){ errors.add(ErrorMessage.VALIDATION_RULE_INVALID_ATTRIBUTE_TYPE.getMessage(type.label())); return errors; } Type ownerType = getParentQuery().getVarTypeMap().get(getVarName()); if (ownerType != null && ownerType.attributes().noneMatch(rt -> rt.equals(type.asAttributeType()))){ errors.add(ErrorMessage.VALIDATION_RULE_ATTRIBUTE_OWNER_CANNOT_HAVE_ATTRIBUTE.getMessage(type.label(), ownerType.label())); } return errors; } @Override public Unifier getUnifier(Atom parentAtom, UnifierComparison unifierType) { if (!(parentAtom instanceof ResourceAtom)) { if (parentAtom instanceof IsaAtom){ return this.toIsaAtom().getUnifier(parentAtom, unifierType); } else { throw GraqlQueryException.unificationAtomIncompatibility(); } } ResourceAtom parent = (ResourceAtom) parentAtom; Unifier unifier = super.getUnifier(parentAtom, unifierType); if (unifier == null || !unifierType.attributeValueCompatibility(new HashSet<>(parent.getMultiPredicate()), new HashSet<>(this.getMultiPredicate())) ){ return UnifierImpl.nonExistent(); } //unify relation vars Var childRelationVarName = this.getRelationVariable(); Var parentRelationVarName = parent.getRelationVariable(); if (parentRelationVarName.isUserDefinedName() && !childRelationVarName.equals(parentRelationVarName)){ unifier = unifier.merge(new UnifierImpl(ImmutableMap.of(childRelationVarName, parentRelationVarName))); } return unifier; } @Override public Stream<Predicate> getInnerPredicates(){ return Stream.concat(super.getInnerPredicates(), getMultiPredicate().stream()); } private void attachAttribute(Concept owner, Attribute attribute){ if (owner.isEntity()){ EntityImpl.from(owner.asEntity()).attributeInferred(attribute); } else if (owner.isRelationship()){ RelationshipImpl.from(owner.asRelationship()).attributeInferred(attribute); } else if (owner.isAttribute()){ AttributeImpl.from(owner.asAttribute()).attributeInferred(attribute); } } @Override public Stream<ConceptMap> materialise(){ ConceptMap substitution = getParentQuery().getSubstitution(); AttributeTypeImpl attributeType = AttributeTypeImpl.from(getSchemaConcept().asAttributeType()); Concept owner = substitution.get(getVarName()); Var resourceVariable = getPredicateVariable(); //if the attribute already exists, only attach a new link to the owner, otherwise create a new attribute Attribute attribute; if(this.isSpecific()){ Object value = Iterables.getOnlyElement(getMultiPredicate()).getPredicate().equalsValue().orElse(null); Attribute existingAttribute = attributeType.attribute(value); attribute = existingAttribute == null? attributeType.putAttributeInferred(value) : existingAttribute; } else { attribute = substitution.containsVar(resourceVariable)? substitution.get(resourceVariable).asAttribute() : null; } attachAttribute(owner, attribute); return Stream.of(substitution.merge(new ConceptMapImpl(ImmutableMap.of(resourceVariable, attribute)))); } /** * rewrites the atom to one with relation variable * @param parentAtom parent atom that triggers rewrite * @return rewritten atom */ private ResourceAtom rewriteWithRelationVariable(Atom parentAtom){ if (parentAtom.isResource() && ((ResourceAtom) parentAtom).getRelationVariable().isUserDefinedName()) return rewriteWithRelationVariable(); return this; } @Override public ResourceAtom rewriteWithRelationVariable(){ Var attributeVariable = getPredicateVariable(); Var relationVariable = getRelationVariable().asUserDefined(); VarPattern newVar = getVarName().has(getSchemaConcept().label(), attributeVariable, relationVariable); return create(newVar.admin(), attributeVariable, relationVariable, getTypeId(), getMultiPredicate(), getParentQuery()); } @Override public Atom rewriteWithTypeVariable() { return create(getPattern(), getPredicateVariable().asUserDefined(), getRelationVariable(), getTypeId(), getMultiPredicate(), getParentQuery()); } @Override public Atom rewriteToUserDefined(Atom parentAtom){ return this .rewriteWithRelationVariable(parentAtom) .rewriteWithTypeVariable(parentAtom); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/binary/SubAtom.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.atom.binary; import ai.grakn.concept.ConceptId; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.VarProperty; import ai.grakn.graql.internal.pattern.property.SubProperty; import ai.grakn.graql.internal.reasoner.atom.predicate.Predicate; import ai.grakn.graql.internal.reasoner.utils.IgnoreHashEquals; import com.google.auto.value.AutoValue; import java.util.stream.Collectors; /** * * <p> * TypeAtom corresponding to graql a {@link ai.grakn.graql.internal.pattern.property.SubProperty} property. * </p> * * @author Kasper Piskorski * */ @AutoValue public abstract class SubAtom extends OntologicalAtom { @Override @IgnoreHashEquals public abstract Var getPredicateVariable(); @Override @IgnoreHashEquals public abstract VarPattern getPattern(); @Override @IgnoreHashEquals public abstract ReasonerQuery getParentQuery(); public static SubAtom create(Var var, Var predicateVar, ConceptId predicateId, ReasonerQuery parent) { return new AutoValue_SubAtom(var, predicateId, predicateVar, var.sub(predicateVar), parent); } private static SubAtom create(SubAtom a, ReasonerQuery parent) { return create(a.getVarName(), a.getPredicateVariable(), a.getTypeId(), parent); } @Override OntologicalAtom createSelf(Var var, Var predicateVar, ConceptId predicateId, ReasonerQuery parent) { return SubAtom.create(var, predicateVar, predicateId, parent); } @Override public Atomic copy(ReasonerQuery parent){ return create(this, parent); } @Override public Class<? extends VarProperty> getVarPropertyClass() {return SubProperty.class;} @Override public String toString(){ String typeString = "sub"+ "(" + getVarName() + ", " + getPredicateVariable() +")"; return typeString + getPredicates().map(Predicate::toString).collect(Collectors.joining("")); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/binary/TypeAtom.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.atom.binary; import ai.grakn.graql.admin.Unifier; import ai.grakn.graql.internal.pattern.property.HasAttributeTypeProperty; import ai.grakn.graql.internal.pattern.property.IsaProperty; import ai.grakn.graql.internal.reasoner.atom.Atom; import java.util.Set; /** * * <p> * Atom implementation defining type atoms of the general form: * * {isa|sub|plays|relates|has}($varName, $predicateVariable) * * Type atoms correspond to the following respective graql properties: * {@link IsaProperty}, * {@link ai.grakn.graql.internal.pattern.property.SubProperty}, * {@link ai.grakn.graql.internal.pattern.property.PlaysProperty} * {@link ai.grakn.graql.internal.pattern.property.RelatesProperty} * {@link HasAttributeTypeProperty} * </p> * * @author Kasper Piskorski * */ public abstract class TypeAtom extends Binary{ @Override public boolean isType(){ return true;} @Override public boolean isUnifiableWith(Atom atom) { return atom.getSchemaConcept() == null || //ensure not ontological atom query (atom instanceof IsaAtomBase) && atom.getSchemaConcept().subs().anyMatch(sub -> sub.equals(this.getSchemaConcept())); } @Override public boolean isRuleApplicableViaAtom(Atom ruleAtom) { if (!(ruleAtom instanceof IsaAtom)) return this.isRuleApplicableViaAtom(ruleAtom.toIsaAtom()); return ruleAtom.isUnifiableWith(this); } @Override public boolean isSelectable() { return getTypePredicate() == null //disjoint atom || !this.getNeighbours(Atom.class).findFirst().isPresent() || getPotentialRules().findFirst().isPresent(); } @Override public boolean requiresMaterialisation() { return isUserDefined() && getSchemaConcept() != null && getSchemaConcept().isRelationshipType(); } /** * @param u unifier to be applied * @return set of type atoms resulting from applying the unifier */ public abstract Set<TypeAtom> unify(Unifier u); }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/predicate/$AutoValue_IdPredicate.java
package ai.grakn.graql.internal.reasoner.atom.predicate; import ai.grakn.concept.ConceptId; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.internal.reasoner.utils.IgnoreHashEquals; import javax.annotation.CheckReturnValue; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") abstract class $AutoValue_IdPredicate extends IdPredicate { private final Var varName; private final VarPattern pattern; private final ReasonerQuery parentQuery; private final ConceptId predicate; $AutoValue_IdPredicate( Var varName, VarPattern pattern, ReasonerQuery parentQuery, ConceptId predicate) { if (varName == null) { throw new NullPointerException("Null varName"); } this.varName = varName; if (pattern == null) { throw new NullPointerException("Null pattern"); } this.pattern = pattern; if (parentQuery == null) { throw new NullPointerException("Null parentQuery"); } this.parentQuery = parentQuery; if (predicate == null) { throw new NullPointerException("Null predicate"); } this.predicate = predicate; } @CheckReturnValue @Override public Var getVarName() { return varName; } @IgnoreHashEquals @Override public VarPattern getPattern() { return pattern; } @IgnoreHashEquals @Override public ReasonerQuery getParentQuery() { return parentQuery; } @Override public ConceptId getPredicate() { return predicate; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof IdPredicate) { IdPredicate that = (IdPredicate) o; return (this.varName.equals(that.getVarName())) && (this.pattern.equals(that.getPattern())) && (this.parentQuery.equals(that.getParentQuery())) && (this.predicate.equals(that.getPredicate())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.varName.hashCode(); h *= 1000003; h ^= this.pattern.hashCode(); h *= 1000003; h ^= this.parentQuery.hashCode(); h *= 1000003; h ^= this.predicate.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/predicate/$AutoValue_NeqPredicate.java
package ai.grakn.graql.internal.reasoner.atom.predicate; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.internal.reasoner.utils.IgnoreHashEquals; import javax.annotation.CheckReturnValue; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") abstract class $AutoValue_NeqPredicate extends NeqPredicate { private final Var varName; private final VarPattern pattern; private final ReasonerQuery parentQuery; private final Var predicate; $AutoValue_NeqPredicate( Var varName, VarPattern pattern, ReasonerQuery parentQuery, Var predicate) { if (varName == null) { throw new NullPointerException("Null varName"); } this.varName = varName; if (pattern == null) { throw new NullPointerException("Null pattern"); } this.pattern = pattern; if (parentQuery == null) { throw new NullPointerException("Null parentQuery"); } this.parentQuery = parentQuery; if (predicate == null) { throw new NullPointerException("Null predicate"); } this.predicate = predicate; } @CheckReturnValue @Override public Var getVarName() { return varName; } @IgnoreHashEquals @Override public VarPattern getPattern() { return pattern; } @IgnoreHashEquals @Override public ReasonerQuery getParentQuery() { return parentQuery; } @Override public Var getPredicate() { return predicate; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof NeqPredicate) { NeqPredicate that = (NeqPredicate) o; return (this.varName.equals(that.getVarName())) && (this.pattern.equals(that.getPattern())) && (this.parentQuery.equals(that.getParentQuery())) && (this.predicate.equals(that.getPredicate())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.varName.hashCode(); h *= 1000003; h ^= this.pattern.hashCode(); h *= 1000003; h ^= this.parentQuery.hashCode(); h *= 1000003; h ^= this.predicate.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/predicate/$AutoValue_ValuePredicate.java
package ai.grakn.graql.internal.reasoner.atom.predicate; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.internal.reasoner.utils.IgnoreHashEquals; import javax.annotation.CheckReturnValue; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") abstract class $AutoValue_ValuePredicate extends ValuePredicate { private final Var varName; private final VarPattern pattern; private final ReasonerQuery parentQuery; private final ai.grakn.graql.ValuePredicate predicate; $AutoValue_ValuePredicate( Var varName, VarPattern pattern, ReasonerQuery parentQuery, ai.grakn.graql.ValuePredicate predicate) { if (varName == null) { throw new NullPointerException("Null varName"); } this.varName = varName; if (pattern == null) { throw new NullPointerException("Null pattern"); } this.pattern = pattern; if (parentQuery == null) { throw new NullPointerException("Null parentQuery"); } this.parentQuery = parentQuery; if (predicate == null) { throw new NullPointerException("Null predicate"); } this.predicate = predicate; } @CheckReturnValue @Override public Var getVarName() { return varName; } @IgnoreHashEquals @Override public VarPattern getPattern() { return pattern; } @IgnoreHashEquals @Override public ReasonerQuery getParentQuery() { return parentQuery; } @Override public ai.grakn.graql.ValuePredicate getPredicate() { return predicate; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof ValuePredicate) { ValuePredicate that = (ValuePredicate) o; return (this.varName.equals(that.getVarName())) && (this.pattern.equals(that.getPattern())) && (this.parentQuery.equals(that.getParentQuery())) && (this.predicate.equals(that.getPredicate())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.varName.hashCode(); h *= 1000003; h ^= this.pattern.hashCode(); h *= 1000003; h ^= this.parentQuery.hashCode(); h *= 1000003; h ^= this.predicate.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/predicate/AutoValue_IdPredicate.java
package ai.grakn.graql.internal.reasoner.atom.predicate; import ai.grakn.concept.ConceptId; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import java.lang.Object; import java.lang.Override; final class AutoValue_IdPredicate extends $AutoValue_IdPredicate { AutoValue_IdPredicate(Var varName, VarPattern pattern, ReasonerQuery parentQuery, ConceptId predicate) { super(varName, pattern, parentQuery, predicate); } @Override public final boolean equals(Object o) { if (o == this) { return true; } if (o instanceof IdPredicate) { IdPredicate that = (IdPredicate) o; return (this.getVarName().equals(that.getVarName())) && (this.getPredicate().equals(that.getPredicate())); } return false; } @Override public final int hashCode() { int h = 1; h *= 1000003; h ^= this.getVarName().hashCode(); h *= 1000003; h ^= this.getPredicate().hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/predicate/AutoValue_NeqPredicate.java
package ai.grakn.graql.internal.reasoner.atom.predicate; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import java.lang.Object; import java.lang.Override; final class AutoValue_NeqPredicate extends $AutoValue_NeqPredicate { AutoValue_NeqPredicate(Var varName, VarPattern pattern, ReasonerQuery parentQuery, Var predicate) { super(varName, pattern, parentQuery, predicate); } @Override public final boolean equals(Object o) { if (o == this) { return true; } if (o instanceof NeqPredicate) { NeqPredicate that = (NeqPredicate) o; return (this.getVarName().equals(that.getVarName())) && (this.getPredicate().equals(that.getPredicate())); } return false; } @Override public final int hashCode() { int h = 1; h *= 1000003; h ^= this.getVarName().hashCode(); h *= 1000003; h ^= this.getPredicate().hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/predicate/AutoValue_ValuePredicate.java
package ai.grakn.graql.internal.reasoner.atom.predicate; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import java.lang.Object; import java.lang.Override; final class AutoValue_ValuePredicate extends $AutoValue_ValuePredicate { AutoValue_ValuePredicate(Var varName, VarPattern pattern, ReasonerQuery parentQuery, ai.grakn.graql.ValuePredicate predicate) { super(varName, pattern, parentQuery, predicate); } @Override public final boolean equals(Object o) { if (o == this) { return true; } if (o instanceof ValuePredicate) { ValuePredicate that = (ValuePredicate) o; return (this.getVarName().equals(that.getVarName())) && (this.getPredicate().equals(that.getPredicate())); } return false; } @Override public final int hashCode() { int h = 1; h *= 1000003; h ^= this.getVarName().hashCode(); h *= 1000003; h ^= this.getPredicate().hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/predicate/IdPredicate.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.atom.predicate; import ai.grakn.GraknTx; import ai.grakn.concept.Concept; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Label; import ai.grakn.concept.SchemaConcept; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.internal.pattern.property.IdProperty; import ai.grakn.graql.internal.reasoner.utils.IgnoreHashEquals; import com.google.auto.value.AutoValue; /** * * <p> * Predicate implementation specialising it to be an id predicate. Corresponds to {@link IdProperty}. * </p> * * @author Kasper Piskorski * */ @AutoValue public abstract class IdPredicate extends Predicate<ConceptId>{ @Override @IgnoreHashEquals public abstract VarPattern getPattern(); @Override @IgnoreHashEquals public abstract ReasonerQuery getParentQuery(); //need to have it explicitly here cause autovalue gets confused with the generic public abstract ConceptId getPredicate(); public static IdPredicate create(VarPattern pattern, ReasonerQuery parent) { return new AutoValue_IdPredicate(pattern.admin().var(), pattern, parent, extractPredicate(pattern)); } public static IdPredicate create(Var varName, Label label, ReasonerQuery parent) { return create(createIdVar(varName.asUserDefined(), label, parent.tx()), parent); } public static IdPredicate create(Var varName, ConceptId id, ReasonerQuery parent) { return create(createIdVar(varName.asUserDefined(), id), parent); } public static IdPredicate create(Var varName, Concept con, ReasonerQuery parent) { return create(createIdVar(varName.asUserDefined(), con.id()), parent); } private static IdPredicate create(IdPredicate a, ReasonerQuery parent) { return create(a.getPattern(), parent); } private static ConceptId extractPredicate(VarPattern var){ return var.admin().getProperty(IdProperty.class).map(IdProperty::id).orElse(null); } private static VarPattern createIdVar(Var varName, ConceptId typeId){ return varName.id(typeId); } private static VarPattern createIdVar(Var varName, Label label, GraknTx graph){ SchemaConcept schemaConcept = graph.getSchemaConcept(label); if (schemaConcept == null) throw GraqlQueryException.labelNotFound(label); return varName.id(schemaConcept.id()); } @Override public boolean isStructurallyEquivalent(Object obj){ if (obj == null || this.getClass() != obj.getClass()) return false; if (obj == this) return true; return true; } @Override public int structuralEquivalenceHashCode() { return 1; } @Override public Atomic copy(ReasonerQuery parent){ return create(this, parent); } @Override public void checkValid() { ConceptId conceptId = getPredicate(); if (tx().getConcept(conceptId) == null){ throw GraqlQueryException.idNotFound(conceptId); } } @Override public String toString(){ return "[" + getVarName() + "/" + getPredicateValue() + "]"; } @Override public String getPredicateValue() { return getPredicate().getValue();} }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/predicate/NeqPredicate.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.atom.predicate; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.internal.pattern.property.NeqProperty; import ai.grakn.graql.internal.reasoner.atom.AtomicEquivalence; import ai.grakn.graql.internal.reasoner.utils.IgnoreHashEquals; import com.google.auto.value.AutoValue; import com.google.common.base.Equivalence; import java.util.Set; /** * * <p> * Predicate implementation specialising it to be an inequality predicate. Corresponds to graql {@link NeqProperty}. * </p> * * @author Kasper Piskorski * */ @AutoValue public abstract class NeqPredicate extends Predicate<Var> { @Override @IgnoreHashEquals public abstract VarPattern getPattern(); @Override @IgnoreHashEquals public abstract ReasonerQuery getParentQuery(); //need to have it explicitly here cause autovalue gets confused with the generic public abstract Var getPredicate(); public static NeqPredicate create(VarPattern pattern, ReasonerQuery parent) { return new AutoValue_NeqPredicate(pattern.admin().var(), pattern, parent, extractPredicate(pattern)); } public static NeqPredicate create(Var varName, NeqProperty prop, ReasonerQuery parent) { VarPatternAdmin pattern = varName.neq(prop.var().var()).admin(); return create(pattern, parent); } public static NeqPredicate create(NeqPredicate a, ReasonerQuery parent) { return create(a.getPattern(), parent); } private static Var extractPredicate(VarPattern pattern) { return pattern.admin().getProperties(NeqProperty.class).iterator().next().var().var(); } private boolean predicateBindingsEquivalent(NeqPredicate that, Equivalence<Atomic> equiv){ IdPredicate thisPredicate = this.getIdPredicate(this.getVarName()); IdPredicate thatPredicate = that.getIdPredicate(that.getVarName()); IdPredicate thisRefPredicate = this.getIdPredicate(this.getPredicate()); IdPredicate thatRefPredicate = that.getIdPredicate(that.getPredicate()); return ( (thisPredicate == null) ? (thisPredicate == thatPredicate) : equiv.equivalent(thisPredicate, thatPredicate) ) && ( (thisRefPredicate == null) ? (thisRefPredicate == thatRefPredicate) : equiv.equivalent(thisRefPredicate, thatRefPredicate) ); } private int bindingHash(Equivalence<Atomic> equiv){ int hashCode = 1; IdPredicate idPredicate = this.getIdPredicate(this.getVarName()); IdPredicate refIdPredicate = this.getIdPredicate(this.getPredicate()); hashCode = hashCode * 37 + (idPredicate != null? equiv.hash(idPredicate) : 0); hashCode = hashCode * 37 + (refIdPredicate != null? equiv.hash(refIdPredicate) : 0); return hashCode; } @Override public boolean isAlphaEquivalent(Object obj){ if (obj == null || this.getClass() != obj.getClass()) return false; if (obj == this) return true; NeqPredicate that = (NeqPredicate) obj; return predicateBindingsEquivalent(that, AtomicEquivalence.AlphaEquivalence); } @Override public int alphaEquivalenceHashCode() { return bindingHash(AtomicEquivalence.AlphaEquivalence); } @Override public boolean isStructurallyEquivalent(Object obj){ if (obj == null || this.getClass() != obj.getClass()) return false; if (obj == this) return true; NeqPredicate that = (NeqPredicate) obj; return predicateBindingsEquivalent(that, AtomicEquivalence.StructuralEquivalence); } @Override public int structuralEquivalenceHashCode() { return bindingHash(AtomicEquivalence.StructuralEquivalence); } @Override public Atomic copy(ReasonerQuery parent) { return create(this, parent);} @Override public String toString(){ IdPredicate idPredicate = this.getIdPredicate(this.getVarName()); IdPredicate refIdPredicate = this.getIdPredicate(this.getPredicate()); return "[" + getVarName() + "!=" + getPredicate() + "]" + (idPredicate != null? idPredicate : "" ) + (refIdPredicate != null? refIdPredicate : ""); } @Override public String getPredicateValue() { return getPredicate().getValue(); } @Override public Set<Var> getVarNames(){ Set<Var> vars = super.getVarNames(); vars.add(getPredicate()); return vars; } /** * @param sub substitution to be checked against the predicate * @return true if provided subsitution satisfies the predicate */ public boolean isSatisfied(ConceptMap sub) { return !sub.containsVar(getVarName()) || !sub.containsVar(getPredicate()) || !sub.get(getVarName()).equals(sub.get(getPredicate())); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/predicate/Predicate.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.atom.predicate; import ai.grakn.concept.Rule; import ai.grakn.graql.internal.reasoner.atom.AtomicBase; import ai.grakn.util.ErrorMessage; import com.google.common.collect.Sets; import java.util.Set; /** * * <p> * {@link AtomicBase} extension serving as base class for predicate implementations. * </p> * * @param <T> the type of the predicate on a concept * * @author Kasper Piskorski * */ public abstract class Predicate<T> extends AtomicBase { public abstract T getPredicate(); public abstract String getPredicateValue(); @Override public Set<String> validateAsRuleHead(Rule rule) { return Sets.newHashSet(ErrorMessage.VALIDATION_RULE_ILLEGAL_ATOMIC_IN_HEAD.getMessage(rule.then(), rule.label())); } @Override public boolean isAlphaEquivalent(Object obj){ if (obj == null || this.getClass() != obj.getClass()) return false; if (obj == this) return true; Predicate a2 = (Predicate) obj; return this.getPredicateValue().equals(a2.getPredicateValue()); } @Override public int alphaEquivalenceHashCode() { int hashCode = 1; hashCode = hashCode * 37 + this.getPredicateValue().hashCode(); return hashCode; } @Override public boolean isStructurallyEquivalent(Object obj) { return isAlphaEquivalent(obj); } @Override public int structuralEquivalenceHashCode() { return alphaEquivalenceHashCode(); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/predicate/ValuePredicate.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.atom.predicate; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.Unifier; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.internal.pattern.property.ValueProperty; import ai.grakn.graql.internal.reasoner.utils.IgnoreHashEquals; import com.google.auto.value.AutoValue; import org.apache.tinkerpop.gremlin.process.traversal.P; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Set; import java.util.stream.Collectors; /** * * <p> * Predicate implementation specialising it to be an value predicate. Corresponds to {@link ValueProperty}. * </p> * * @author Kasper Piskorski * */ @AutoValue public abstract class ValuePredicate extends Predicate<ai.grakn.graql.ValuePredicate> { @Override @IgnoreHashEquals public abstract VarPattern getPattern(); @Override @IgnoreHashEquals public abstract ReasonerQuery getParentQuery(); //need to have it explicitly here cause autovalue gets confused with the generic public abstract ai.grakn.graql.ValuePredicate getPredicate(); public static ValuePredicate create(VarPattern pattern, ReasonerQuery parent) { return new AutoValue_ValuePredicate(pattern.admin().var(), pattern, parent, extractPredicate(pattern)); } public static ValuePredicate create(Var varName, ai.grakn.graql.ValuePredicate pred, ReasonerQuery parent) { return create(createValueVar(varName, pred), parent); } private static ValuePredicate create(ValuePredicate pred, ReasonerQuery parent) { return create(pred.getPattern(), parent); } public static VarPattern createValueVar(Var name, ai.grakn.graql.ValuePredicate pred) { return name.val(pred);} private static ai.grakn.graql.ValuePredicate extractPredicate(VarPattern pattern) { Iterator<ValueProperty> properties = pattern.admin().getProperties(ValueProperty.class).iterator(); ValueProperty property = properties.next(); if (properties.hasNext()) { throw GraqlQueryException.valuePredicateAtomWithMultiplePredicates(); } return property.predicate(); } @Override public Atomic copy(ReasonerQuery parent) { return create(this, parent); } @Override public String toString(){ return "[" + getVarName() + " val " + getPredicate() + "]"; } public Set<ValuePredicate> unify(Unifier u){ Collection<Var> vars = u.get(getVarName()); return vars.isEmpty()? Collections.singleton(this) : vars.stream().map(v -> create(v, getPredicate(), this.getParentQuery())).collect(Collectors.toSet()); } @Override public boolean isAlphaEquivalent(Object obj){ if (obj == null || this.getClass() != obj.getClass()) return false; if (obj == this) return true; ValuePredicate p2 = (ValuePredicate) obj; return this.getPredicate().getClass().equals(p2.getPredicate().getClass()) && this.getPredicateValue().equals(p2.getPredicateValue()); } @Override public int alphaEquivalenceHashCode() { int hashCode = super.alphaEquivalenceHashCode(); hashCode = hashCode * 37 + this.getPredicate().getClass().getName().hashCode(); return hashCode; } @Override public boolean isCompatibleWith(Object obj) { if (this.isAlphaEquivalent(obj)) return true; if (obj == null || this.getClass() != obj.getClass()) return false; if (obj == this) return true; ValuePredicate p2 = (ValuePredicate) obj; return getPredicate().isCompatibleWith(p2.getPredicate()); } @Override public String getPredicateValue() { return getPredicate().getPredicate().map(P::getValue).map(Object::toString).orElse(""); } @Override public Set<Var> getVarNames(){ Set<Var> vars = super.getVarNames(); VarPatternAdmin innerVar = getPredicate().getInnerVar().orElse(null); if(innerVar != null && innerVar.var().isUserDefinedName()) vars.add(innerVar.var()); return vars; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/property/$AutoValue_DataTypeAtom.java
package ai.grakn.graql.internal.reasoner.atom.property; import ai.grakn.concept.AttributeType; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.internal.reasoner.utils.IgnoreHashEquals; import javax.annotation.CheckReturnValue; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") abstract class $AutoValue_DataTypeAtom extends DataTypeAtom { private final Var varName; private final VarPattern pattern; private final ReasonerQuery parentQuery; private final AttributeType.DataType<?> dataType; $AutoValue_DataTypeAtom( Var varName, VarPattern pattern, ReasonerQuery parentQuery, AttributeType.DataType<?> dataType) { if (varName == null) { throw new NullPointerException("Null varName"); } this.varName = varName; if (pattern == null) { throw new NullPointerException("Null pattern"); } this.pattern = pattern; if (parentQuery == null) { throw new NullPointerException("Null parentQuery"); } this.parentQuery = parentQuery; if (dataType == null) { throw new NullPointerException("Null dataType"); } this.dataType = dataType; } @CheckReturnValue @Override public Var getVarName() { return varName; } @IgnoreHashEquals @Override public VarPattern getPattern() { return pattern; } @IgnoreHashEquals @Override public ReasonerQuery getParentQuery() { return parentQuery; } @Override public AttributeType.DataType<?> getDataType() { return dataType; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof DataTypeAtom) { DataTypeAtom that = (DataTypeAtom) o; return (this.varName.equals(that.getVarName())) && (this.pattern.equals(that.getPattern())) && (this.parentQuery.equals(that.getParentQuery())) && (this.dataType.equals(that.getDataType())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.varName.hashCode(); h *= 1000003; h ^= this.pattern.hashCode(); h *= 1000003; h ^= this.parentQuery.hashCode(); h *= 1000003; h ^= this.dataType.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/property/$AutoValue_IsAbstractAtom.java
package ai.grakn.graql.internal.reasoner.atom.property; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.internal.reasoner.utils.IgnoreHashEquals; import javax.annotation.CheckReturnValue; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") abstract class $AutoValue_IsAbstractAtom extends IsAbstractAtom { private final Var varName; private final VarPattern pattern; private final ReasonerQuery parentQuery; $AutoValue_IsAbstractAtom( Var varName, VarPattern pattern, ReasonerQuery parentQuery) { if (varName == null) { throw new NullPointerException("Null varName"); } this.varName = varName; if (pattern == null) { throw new NullPointerException("Null pattern"); } this.pattern = pattern; if (parentQuery == null) { throw new NullPointerException("Null parentQuery"); } this.parentQuery = parentQuery; } @CheckReturnValue @Override public Var getVarName() { return varName; } @IgnoreHashEquals @Override public VarPattern getPattern() { return pattern; } @IgnoreHashEquals @Override public ReasonerQuery getParentQuery() { return parentQuery; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof IsAbstractAtom) { IsAbstractAtom that = (IsAbstractAtom) o; return (this.varName.equals(that.getVarName())) && (this.pattern.equals(that.getPattern())) && (this.parentQuery.equals(that.getParentQuery())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.varName.hashCode(); h *= 1000003; h ^= this.pattern.hashCode(); h *= 1000003; h ^= this.parentQuery.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/property/$AutoValue_RegexAtom.java
package ai.grakn.graql.internal.reasoner.atom.property; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.internal.reasoner.utils.IgnoreHashEquals; import javax.annotation.CheckReturnValue; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") abstract class $AutoValue_RegexAtom extends RegexAtom { private final Var varName; private final VarPattern pattern; private final ReasonerQuery parentQuery; private final String regex; $AutoValue_RegexAtom( Var varName, VarPattern pattern, ReasonerQuery parentQuery, String regex) { if (varName == null) { throw new NullPointerException("Null varName"); } this.varName = varName; if (pattern == null) { throw new NullPointerException("Null pattern"); } this.pattern = pattern; if (parentQuery == null) { throw new NullPointerException("Null parentQuery"); } this.parentQuery = parentQuery; if (regex == null) { throw new NullPointerException("Null regex"); } this.regex = regex; } @CheckReturnValue @Override public Var getVarName() { return varName; } @IgnoreHashEquals @Override public VarPattern getPattern() { return pattern; } @IgnoreHashEquals @Override public ReasonerQuery getParentQuery() { return parentQuery; } @Override public String getRegex() { return regex; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof RegexAtom) { RegexAtom that = (RegexAtom) o; return (this.varName.equals(that.getVarName())) && (this.pattern.equals(that.getPattern())) && (this.parentQuery.equals(that.getParentQuery())) && (this.regex.equals(that.getRegex())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.varName.hashCode(); h *= 1000003; h ^= this.pattern.hashCode(); h *= 1000003; h ^= this.parentQuery.hashCode(); h *= 1000003; h ^= this.regex.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/property/AutoValue_DataTypeAtom.java
package ai.grakn.graql.internal.reasoner.atom.property; import ai.grakn.concept.AttributeType; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import java.lang.Object; import java.lang.Override; final class AutoValue_DataTypeAtom extends $AutoValue_DataTypeAtom { AutoValue_DataTypeAtom(Var varName, VarPattern pattern, ReasonerQuery parentQuery, AttributeType.DataType<?> dataType) { super(varName, pattern, parentQuery, dataType); } @Override public final boolean equals(Object o) { if (o == this) { return true; } if (o instanceof DataTypeAtom) { DataTypeAtom that = (DataTypeAtom) o; return (this.getVarName().equals(that.getVarName())) && (this.getDataType().equals(that.getDataType())); } return false; } @Override public final int hashCode() { int h = 1; h *= 1000003; h ^= this.getVarName().hashCode(); h *= 1000003; h ^= this.getDataType().hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/property/AutoValue_IsAbstractAtom.java
package ai.grakn.graql.internal.reasoner.atom.property; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import java.lang.Object; import java.lang.Override; final class AutoValue_IsAbstractAtom extends $AutoValue_IsAbstractAtom { AutoValue_IsAbstractAtom(Var varName, VarPattern pattern, ReasonerQuery parentQuery) { super(varName, pattern, parentQuery); } @Override public final boolean equals(Object o) { if (o == this) { return true; } if (o instanceof IsAbstractAtom) { IsAbstractAtom that = (IsAbstractAtom) o; return (this.getVarName().equals(that.getVarName())); } return false; } @Override public final int hashCode() { int h = 1; h *= 1000003; h ^= this.getVarName().hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/property/AutoValue_RegexAtom.java
package ai.grakn.graql.internal.reasoner.atom.property; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.ReasonerQuery; import java.lang.Object; import java.lang.Override; import java.lang.String; final class AutoValue_RegexAtom extends $AutoValue_RegexAtom { AutoValue_RegexAtom(Var varName, VarPattern pattern, ReasonerQuery parentQuery, String regex) { super(varName, pattern, parentQuery, regex); } @Override public final boolean equals(Object o) { if (o == this) { return true; } if (o instanceof RegexAtom) { RegexAtom that = (RegexAtom) o; return (this.getVarName().equals(that.getVarName())) && (this.getRegex().equals(that.getRegex())); } return false; } @Override public final int hashCode() { int h = 1; h *= 1000003; h ^= this.getVarName().hashCode(); h *= 1000003; h ^= this.getRegex().hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/property/DataTypeAtom.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.atom.property; import ai.grakn.concept.AttributeType; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.internal.pattern.property.DataTypeProperty; import ai.grakn.graql.internal.reasoner.atom.AtomicBase; import ai.grakn.graql.internal.reasoner.utils.IgnoreHashEquals; import com.google.auto.value.AutoValue; /** * * <p> * Atomic corresponding to {@link DataTypeProperty}. * </p> * * @author Kasper Piskorski * */ @AutoValue public abstract class DataTypeAtom extends AtomicBase { @Override @IgnoreHashEquals public abstract VarPattern getPattern(); @Override @IgnoreHashEquals public abstract ReasonerQuery getParentQuery(); public abstract AttributeType.DataType<?> getDataType(); public static DataTypeAtom create(Var varName, DataTypeProperty prop, ReasonerQuery parent) { return new AutoValue_DataTypeAtom(varName, varName.datatype(prop.dataType()).admin(), parent, prop.dataType()); } private static DataTypeAtom create(DataTypeAtom a, ReasonerQuery parent) { return new AutoValue_DataTypeAtom(a.getVarName(), a.getPattern(), parent, a.getDataType()); } @Override public Atomic copy(ReasonerQuery parent) { return create(this, parent);} @Override public boolean isAlphaEquivalent(Object obj) { if (obj == null || this.getClass() != obj.getClass()) return false; if (obj == this) return true; DataTypeAtom a2 = (DataTypeAtom) obj; return this.getDataType().equals(a2.getDataType()); } @Override public int alphaEquivalenceHashCode() { int hashCode = 1; hashCode = hashCode * 37 + this.getDataType().hashCode(); return hashCode; } @Override public boolean isStructurallyEquivalent(Object obj) { return isAlphaEquivalent(obj); } @Override public int structuralEquivalenceHashCode() { return alphaEquivalenceHashCode(); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/property/IsAbstractAtom.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.atom.property; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.internal.reasoner.atom.AtomicBase; import ai.grakn.graql.internal.reasoner.utils.IgnoreHashEquals; import com.google.auto.value.AutoValue; /** * * <p> * Atomic corresponding to {@link ai.grakn.graql.internal.pattern.property.IsAbstractProperty}. * </p> * * @author Kasper Piskorski * */ @AutoValue public abstract class IsAbstractAtom extends AtomicBase { @Override @IgnoreHashEquals public abstract VarPattern getPattern(); @Override @IgnoreHashEquals public abstract ReasonerQuery getParentQuery(); public static IsAbstractAtom create(Var varName, ReasonerQuery parent) { return new AutoValue_IsAbstractAtom(varName, varName.isAbstract().admin(), parent); } private static IsAbstractAtom create(IsAbstractAtom a, ReasonerQuery parent) { return new AutoValue_IsAbstractAtom(a.getVarName(), a.getPattern(), parent); } @Override public Atomic copy(ReasonerQuery parent) { return create(this, parent); } @Override public boolean isAlphaEquivalent(Object obj) { return !(obj == null || this.getClass() != obj.getClass()); } @Override public int alphaEquivalenceHashCode() { return 1;} @Override public boolean isStructurallyEquivalent(Object obj) { return isAlphaEquivalent(obj); } @Override public int structuralEquivalenceHashCode() { return alphaEquivalenceHashCode(); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/atom/property/RegexAtom.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.atom.property; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.internal.pattern.property.RegexProperty; import ai.grakn.graql.internal.reasoner.atom.AtomicBase; import ai.grakn.graql.internal.reasoner.utils.IgnoreHashEquals; import com.google.auto.value.AutoValue; /** * * <p> * Atomic corresponding to {@link RegexProperty}. * </p> * * @author Kasper Piskorski * */ @AutoValue public abstract class RegexAtom extends AtomicBase { @Override @IgnoreHashEquals public abstract VarPattern getPattern(); @Override @IgnoreHashEquals public abstract ReasonerQuery getParentQuery(); public abstract String getRegex(); public static RegexAtom create(Var varName, RegexProperty prop, ReasonerQuery parent) { return new AutoValue_RegexAtom(varName, varName.regex(prop.regex()).admin(), parent, prop.regex()); } private static RegexAtom create(RegexAtom a, ReasonerQuery parent) { return new AutoValue_RegexAtom(a.getVarName(), a.getPattern(), parent, a.getRegex()); } @Override public Atomic copy(ReasonerQuery parent) { return create(this, parent);} @Override public boolean isAlphaEquivalent(Object obj) { if (obj == null || this.getClass() != obj.getClass()) return false; if (obj == this) return true; RegexAtom a2 = (RegexAtom) obj; return this.getRegex().equals(a2.getRegex()); } @Override public int alphaEquivalenceHashCode() { int hashCode = 1; hashCode = hashCode * 37 + this.getRegex().hashCode(); return hashCode; } @Override public boolean isStructurallyEquivalent(Object obj) { return isAlphaEquivalent(obj); } @Override public int structuralEquivalenceHashCode() { return alphaEquivalenceHashCode();} }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/cache/CacheEntry.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.cache; import ai.grakn.graql.internal.reasoner.query.ReasonerQueryImpl; /** * * <p> * Simple class for defining query entries. * </p> * * @param <Q> query type the entry corresponds to * @param <T> corresponding element to be cached * * @author Kasper Piskorski * */ class CacheEntry<Q extends ReasonerQueryImpl, T> { private final Q query; private final T cachedElement; CacheEntry(Q query, T element){ this.query = query; this.cachedElement = element; } public Q query(){ return query;} public T cachedElement(){ return cachedElement;} }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/cache/LazyQueryCache.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.cache; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.admin.MultiUnifier; import ai.grakn.graql.internal.reasoner.MultiUnifierImpl; import ai.grakn.graql.internal.reasoner.explanation.LookupExplanation; import ai.grakn.graql.internal.reasoner.iterator.LazyAnswerIterator; import ai.grakn.graql.internal.reasoner.query.ReasonerQueryImpl; import ai.grakn.graql.internal.reasoner.utils.Pair; import java.util.stream.Stream; /** * * <p> * Lazy container class for storing performed query resolutions. * NB: For the GET operation, in the case the entry is not found, a RECORD operation is performed. * </p> * * @param <Q> the type of query that is being cached * * @author Kasper Piskorski * */ public class LazyQueryCache<Q extends ReasonerQueryImpl> extends QueryCacheBase<Q, LazyAnswerIterator> { public LazyQueryCache(){ super();} @Override public ConceptMap record(Q query, ConceptMap answer) { record(query, Stream.of(answer)); return answer; } @Override public LazyAnswerIterator record(Q query, LazyAnswerIterator answers) { CacheEntry<Q, LazyAnswerIterator> match = this.getEntry(query); if (match != null) { Q equivalentQuery = match.query(); Stream<ConceptMap> unifiedStream = answers.unify(query.getMultiUnifier(equivalentQuery)).stream(); //NB: entry overwrite this.putEntry(match.query(), match.cachedElement().merge(unifiedStream)); return getAnswers(query); } this.putEntry(query, answers); return answers; } @Override public Stream<ConceptMap> record(Q query, Stream<ConceptMap> answers) { return recordRetrieveLazy(query, answers).stream(); } /** * record answer stream for a specific query and retrieve the updated stream in a lazy iterator * @param query to be recorded * @param answers answer stream of the query * @return lazy iterator of updated answers */ public LazyAnswerIterator recordRetrieveLazy(Q query, Stream<ConceptMap> answers){ CacheEntry<Q, LazyAnswerIterator> match = this.getEntry(query); if (match!= null) { Q equivalentQuery = match.query(); MultiUnifier multiUnifier = query.getMultiUnifier(equivalentQuery); Stream<ConceptMap> unifiedStream = answers.flatMap(a -> a.unify(multiUnifier)); //NB: entry overwrite this.putEntry(match.query(), match.cachedElement().merge(unifiedStream)); return getAnswers(query); } LazyAnswerIterator liter = new LazyAnswerIterator(answers); this.putEntry(query, liter); return liter; } @Override public LazyAnswerIterator getAnswers(Q query) { return getAnswersWithUnifier(query).getKey(); } @Override public Stream<ConceptMap> getAnswerStream(Q query){ return getAnswerStreamWithUnifier(query).getKey(); } @Override public Pair<LazyAnswerIterator, MultiUnifier> getAnswersWithUnifier(Q query) { CacheEntry<Q, LazyAnswerIterator> match = this.getEntry(query); if (match != null) { Q equivalentQuery = match.query(); MultiUnifier multiUnifier = equivalentQuery.getMultiUnifier(query); LazyAnswerIterator unified = match.cachedElement().unify(multiUnifier); return new Pair<>(unified, multiUnifier); } Stream<ConceptMap> answerStream = record( query, query.getQuery().stream().map(a -> a.explain(new LookupExplanation(query))) ); return new Pair<>(new LazyAnswerIterator(answerStream), new MultiUnifierImpl()); } @Override public Pair<Stream<ConceptMap>, MultiUnifier> getAnswerStreamWithUnifier(Q query) { CacheEntry<Q, LazyAnswerIterator> match = this.getEntry(query); if (match != null) { Q equivalentQuery = match.query(); MultiUnifier multiUnifier = equivalentQuery.getMultiUnifier(query); Stream<ConceptMap> unified = match.cachedElement().stream().flatMap(a -> a.unify(multiUnifier)); return new Pair<>(unified, multiUnifier); } Stream<ConceptMap> answerStream = record( query, query.getQuery().stream().map(a -> a.explain(new LookupExplanation(query))) ); return new Pair<>(answerStream, new MultiUnifierImpl()); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/cache/QueryCache.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.cache; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.internal.reasoner.query.ReasonerQueryImpl; import java.util.Set; import java.util.stream.Stream; /** * * <p> * Generic interface query caches. * * Defines two basic operations: * - GET(Query) * - RECORD(Query, Answer). * * </p> * * @param <Q> the type of query that is being cached * @param <S> the type of answer being cached * * @author Kasper Piskorski * */ public interface QueryCache<Q extends ReasonerQueryImpl, S extends Iterable<ConceptMap>>{ /** * record answer iterable for a specific query and retrieve the updated answers * @param query to be recorded * @param answers to this query * @return updated answer iterable */ S record(Q query, S answers); /** * record answer stream for a specific query and retrieve the updated stream * @param query to be recorded * @param answers answer stream of the query * @return updated answer stream */ Stream<ConceptMap> record(Q query, Stream<ConceptMap> answers); /** * record single answer to a specific query * @param query of interest * @param answer to this query * @return recorded answer */ ConceptMap record(Q query, ConceptMap answer); /** * retrieve (possibly) cached answers for provided query * @param query for which to retrieve answers * @return unified cached answers */ S getAnswers(Q query); Stream<ConceptMap> getAnswerStream(Q query); /** * Query cache containment check * @param query to be checked for containment * @return true if cache contains the query */ boolean contains(Q query); /** * @return all queries contained in this cache */ Set<Q> getQueries(); /** * Perform cache union * @param c2 union right operand */ void merge(QueryCacheBase<Q, S> c2); /** * Clear the cache */ void clear(); }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/cache/QueryCacheBase.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.cache; import ai.grakn.graql.admin.MultiUnifier; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.internal.reasoner.query.ReasonerQueryImpl; import ai.grakn.graql.internal.reasoner.utils.Pair; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.stream.Stream; /** * * <p> * Base class for storing query resolutions based on alpha-equivalence. * A one-to-one mapping is ensured between queries and entries. * On retrieval, a relevant entry is identified by means of a query alpha-equivalence check. * * </p> * * @param <Q> the type of query that is being cached * @param <S> the type of answer being cached * * @author Kasper Piskorski * */ public abstract class QueryCacheBase<Q extends ReasonerQueryImpl, S extends Iterable<ConceptMap>> implements QueryCache<Q, S>{ private final Map<Q, CacheEntry<Q, S>> cache = new HashMap<>(); private final StructuralCache<Q> sCache = new StructuralCache<>(); private final RuleCache ruleCache = new RuleCache(); QueryCacheBase(){ } @Override public boolean contains(Q query){ return cache.containsKey(query);} @Override public Set<Q> getQueries(){ return cache.keySet();} @Override public void merge(QueryCacheBase<Q, S> c2){ c2.cache.keySet().forEach( q -> this.record(q, c2.getAnswers(q))); } @Override public void clear(){ cache.clear();} /** * @return structural cache of this cache */ StructuralCache<Q> structuralCache(){ return sCache;} public RuleCache ruleCache(){ return ruleCache;} public abstract Pair<S, MultiUnifier> getAnswersWithUnifier(Q query); public abstract Pair<Stream<ConceptMap>, MultiUnifier> getAnswerStreamWithUnifier(Q query); /** * @param query for which the entry is to be retrieved * @return corresponding cache entry if any or null */ CacheEntry<Q, S> getEntry(Q query){ return cache.get(query);} /** * Associates the specified answers with the specified query in this cache adding an (query) -> (answers) entry * @param query of the association * @param answers of the association * @return previous value if any or null */ CacheEntry<Q, S> putEntry(Q query, S answers){ return cache.put(query, new CacheEntry<>(query, answers));} }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/cache/RuleCache.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.cache; import ai.grakn.concept.Rule; import ai.grakn.graql.admin.Unifier; import ai.grakn.graql.internal.reasoner.atom.Atom; import ai.grakn.graql.internal.reasoner.rule.InferenceRule; import ai.grakn.graql.internal.reasoner.utils.Pair; import java.util.Comparator; import java.util.HashSet; import java.util.Set; import java.util.stream.Stream; /** * Introduces rule cache that wraps around the atom matching rule retrieval to ensure resolution of fruitless rules is not pursued. * * @author Kasper Piskorski * */ public class RuleCache { private final Set<Rule> fruitlessRules = new HashSet<>(); private final Set<Rule> checkedRules = new HashSet<>(); /** * @param atom of interest * @return stream of rules applicable to this atom */ public Stream<InferenceRule> getApplicableRules(Atom atom){ return atom.getApplicableRules() .filter( r -> { if (fruitlessRules.contains(r.getRule())) return false; if (r.getBody().isRuleResolvable() || checkedRules.contains(r.getRule())) return true; boolean fruitless = !r.getBody().getQuery().stream().findFirst().isPresent(); if (fruitless) { fruitlessRules.add(r.getRule()); return false; } checkedRules.add(r.getRule()); return true; }); } /** * @param atom of interest * @return stream of all rules applicable to this atom including permuted cases when the role types are meta roles */ public Stream<Pair<InferenceRule, Unifier>> getRuleStream(Atom atom){ return getApplicableRules(atom) .flatMap(r -> r.getMultiUnifier(atom).stream().map(unifier -> new Pair<>(r, unifier))) .sorted(Comparator.comparing(rt -> -rt.getKey().resolutionPriority())); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/cache/SimpleQueryCache.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.cache; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Var; import ai.grakn.graql.admin.MultiUnifier; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.internal.query.answer.ConceptMapImpl; import ai.grakn.graql.internal.reasoner.MultiUnifierImpl; import ai.grakn.graql.internal.reasoner.query.QueryAnswers; import ai.grakn.graql.internal.reasoner.query.ReasonerQueries; import ai.grakn.graql.internal.reasoner.query.ReasonerQueryImpl; import ai.grakn.graql.internal.reasoner.utils.Pair; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nullable; /** * * <p> * Container class for storing performed query resolutions. * * Cache operations are handled in the following way: * - GET(Query) - retrieve an entry corresponding to a provided query, if entry doesn't exist return db lookup result of the query. * - RECORD(Query) - if the query entry exists, update the entry, otherwise create a new entry. In each case return an up-to-date entry. * * </p> * * @param <Q> the type of query that is being cached * * @author Kasper Piskorski * */ public class SimpleQueryCache<Q extends ReasonerQueryImpl> extends QueryCacheBase<Q, QueryAnswers> { public SimpleQueryCache(){ super(); } @Override public QueryAnswers record(Q query, QueryAnswers answers) { CacheEntry<Q, QueryAnswers> match = this.getEntry(query); if (match != null) { Q equivalentQuery = match.query(); QueryAnswers unifiedAnswers = answers.unify(query.getMultiUnifier(equivalentQuery)); this.getEntry(query).cachedElement().addAll(unifiedAnswers); return getAnswers(query); } this.putEntry(query, answers); return answers; } @Override public Stream<ConceptMap> record(Q query, Stream<ConceptMap> answerStream) { //NB: stream collection! QueryAnswers newAnswers = new QueryAnswers(answerStream.collect(Collectors.toSet())); return record(query, newAnswers).stream(); } /** * record a specific answer to a given query * @param query to which an answer is to be recorded * @param answer specific answer to the query * @return recorded answer */ @Override public ConceptMap record(Q query, ConceptMap answer){ return record(query, answer, null); } /** * record a specific answer to a given query with a known cache unifier * @param query to which an answer is to be recorded * @param answer answer specific answer to the query * @param unifier between the cached and input query * @return recorded answer */ public ConceptMap record(Q query, ConceptMap answer, @Nullable MultiUnifier unifier){ if(answer.isEmpty()) return answer; CacheEntry<Q, QueryAnswers> match = this.getEntry(query); if (match != null) { Q equivalentQuery = match.query(); QueryAnswers answers = match.cachedElement(); MultiUnifier multiUnifier = unifier == null? query.getMultiUnifier(equivalentQuery) : unifier; Set<Var> cacheVars = answers.isEmpty()? new HashSet<>() : answers.iterator().next().vars(); multiUnifier.stream() .map(answer::unify) .peek(ans -> { if (!ans.vars().containsAll(cacheVars)){ throw GraqlQueryException.invalidQueryCacheEntry(equivalentQuery); } }) .forEach(answers::add); } else { if (!answer.vars().containsAll(query.getVarNames())){ throw GraqlQueryException.invalidQueryCacheEntry(query); } this.putEntry(query, new QueryAnswers(answer)); } return answer; } @Override public QueryAnswers getAnswers(Q query) { return getAnswersWithUnifier(query).getKey(); } @Override public Stream<ConceptMap> getAnswerStream(Q query) { return getAnswerStreamWithUnifier(query).getKey(); } @Override public Pair<QueryAnswers, MultiUnifier> getAnswersWithUnifier(Q query) { Pair<Stream<ConceptMap>, MultiUnifier> answerStreamWithUnifier = getAnswerStreamWithUnifier(query); return new Pair<>( new QueryAnswers(answerStreamWithUnifier.getKey().collect(Collectors.toSet())), answerStreamWithUnifier.getValue() ); } @Override public Pair<Stream<ConceptMap>, MultiUnifier> getAnswerStreamWithUnifier(Q query) { CacheEntry<Q, QueryAnswers> match = this.getEntry(query); if (match != null) { Q equivalentQuery = match.query(); QueryAnswers answers = match.cachedElement(); MultiUnifier multiUnifier = equivalentQuery.getMultiUnifier(query); //NB: this is not lazy //lazy version would be answers.stream().flatMap(ans -> ans.unify(multiUnifier)) return new Pair<>(answers.unify(multiUnifier).stream(), multiUnifier); } return new Pair<>( structuralCache().get(query), new MultiUnifierImpl() ); } /** * find specific answer to a query in the cache * @param query input query * @param ans sought specific answer to the query * @return found answer if any, otherwise empty answer */ public ConceptMap getAnswer(Q query, ConceptMap ans){ if(ans.isEmpty()) return ans; CacheEntry<Q, QueryAnswers> match = this.getEntry(query); if (match != null) { Q equivalentQuery = match.query(); MultiUnifier multiUnifier = equivalentQuery.getMultiUnifier(query); //NB: only used when checking for materialised answer duplicates ConceptMap answer = match.cachedElement().stream() .flatMap(a -> a.unify(multiUnifier)) .filter(a -> a.containsAll(ans)) .findFirst().orElse(null); if (answer != null) return answer; } //TODO should it create a cache entry? List<ConceptMap> answers = ReasonerQueries.create(query, ans).getQuery().execute(); return answers.isEmpty()? new ConceptMapImpl() : answers.iterator().next(); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/cache/StructuralCache.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.cache; import ai.grakn.concept.ConceptId; import ai.grakn.graql.Var; import ai.grakn.graql.admin.MultiUnifier; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.admin.Unifier; import ai.grakn.graql.internal.gremlin.GraqlTraversal; import ai.grakn.graql.internal.gremlin.GreedyTraversalPlan; import ai.grakn.graql.internal.query.match.MatchBase; import ai.grakn.graql.internal.reasoner.UnifierType; import ai.grakn.graql.internal.reasoner.explanation.LookupExplanation; import ai.grakn.graql.internal.reasoner.query.ReasonerQueryEquivalence; import ai.grakn.graql.internal.reasoner.query.ReasonerQueryImpl; import ai.grakn.kb.internal.EmbeddedGraknTx; import com.google.common.base.Equivalence; import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; /** * * <p> * Container class allowing to store similar graql traversals with similarity measure based on structural query equivalence. * * On cache hit a concept map between provided query and the one contained in the cache is constructed. Based on that mapping, * id predicates of the cached query are transformed. * * The returned stream is a stream of the transformed cached query unified with the provided query. * </p> * * @param <Q> the type of query that is being cached * * @author Kasper Piskorski * */ class StructuralCache<Q extends ReasonerQueryImpl>{ private final ReasonerQueryEquivalence equivalence = ReasonerQueryEquivalence.StructuralEquivalence; private final Map<Equivalence.Wrapper<Q>, CacheEntry<Q, GraqlTraversal>> structCache; StructuralCache(){ this.structCache = new HashMap<>(); } /** * @param query to be retrieved * @return answer stream of provided query */ public Stream<ConceptMap> get(Q query){ Equivalence.Wrapper<Q> structQuery = equivalence.wrap(query); EmbeddedGraknTx<?> tx = query.tx(); CacheEntry<Q, GraqlTraversal> match = structCache.get(structQuery); if (match != null){ Q equivalentQuery = match.query(); GraqlTraversal traversal = match.cachedElement(); MultiUnifier multiUnifier = equivalentQuery.getMultiUnifier(query, UnifierType.STRUCTURAL); if(multiUnifier.isEmpty()){ System.out.println(); } Unifier unifier = multiUnifier.getAny(); Map<Var, ConceptId> idTransform = equivalentQuery.idTransform(query, unifier); ReasonerQueryImpl transformedQuery = equivalentQuery.transformIds(idTransform); return MatchBase.streamWithTraversal(transformedQuery.getPattern().commonVars(), tx, traversal.transform(idTransform)) .map(ans -> ans.unify(unifier)) .map(a -> a.explain(new LookupExplanation(query))); } GraqlTraversal traversal = GreedyTraversalPlan.createTraversal(query.getPattern(), tx); structCache.put(structQuery, new CacheEntry<>(query, traversal)); return MatchBase.streamWithTraversal(query.getPattern().commonVars(), tx, traversal) .map(a -> a.explain(new LookupExplanation(query))); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/explanation/JoinExplanation.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.explanation; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.admin.Explanation; import ai.grakn.graql.internal.reasoner.query.ReasonerQueries; import ai.grakn.graql.internal.reasoner.query.ReasonerQueryImpl; import ai.grakn.graql.internal.reasoner.utils.ReasonerUtils; import java.util.List; import java.util.stream.Collectors; /** * * <p> * Explanation class for a join explanation - resulting from merging atoms in a conjunction. * </p> * * @author Kasper Piskorski * */ public class JoinExplanation extends QueryExplanation { public JoinExplanation(List<ConceptMap> answers){ super(answers);} public JoinExplanation(ReasonerQueryImpl q, ConceptMap mergedAnswer){ super(q, q.selectAtoms() .map(at -> at.inferTypes(mergedAnswer.project(at.getVarNames()))) .map(ReasonerQueries::atomic) .map(aq -> mergedAnswer.project(aq.getVarNames()).explain(new LookupExplanation(aq))) .collect(Collectors.toList()) ); } @Override public Explanation childOf(ConceptMap ans) { return new JoinExplanation(ReasonerUtils.listUnion(this.getAnswers(), ans.explanation().getAnswers())); } @Override public boolean isJoinExplanation(){ return true;} }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/explanation/LookupExplanation.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.explanation; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.admin.Explanation; import ai.grakn.graql.admin.ReasonerQuery; import java.util.List; /** * * <p> * Explanation class for db lookup. * </p> * * @author Kasper Piskorski * */ public class LookupExplanation extends QueryExplanation { public LookupExplanation(ReasonerQuery q){ super(q);} private LookupExplanation(ReasonerQuery q, List<ConceptMap> answers){ super(q, answers); } @Override public Explanation setQuery(ReasonerQuery q){ return new LookupExplanation(q); } @Override public Explanation childOf(ConceptMap ans) { return new LookupExplanation(getQuery(), ans.explanation().getAnswers()); } @Override public boolean isLookupExplanation(){ return true;} }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/explanation/QueryExplanation.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.explanation; import ai.grakn.graql.admin.Explanation; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.answer.ConceptMap; import com.google.common.collect.ImmutableList; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** * * <p> * Base class for explanation classes. * </p> * * @author Kasper Piskorski * */ public class QueryExplanation implements Explanation { private final ReasonerQuery query; private final ImmutableList<ConceptMap> answers; public QueryExplanation(){ this.query = null; this.answers = ImmutableList.of();} QueryExplanation(ReasonerQuery q, List<ConceptMap> ans){ this.query = q; this.answers = ImmutableList.copyOf(ans); } QueryExplanation(ReasonerQuery q){ this(q, new ArrayList<>()); } QueryExplanation(List<ConceptMap> ans){ this(null, ans); } @Override public Explanation setQuery(ReasonerQuery q){ return new QueryExplanation(q); } @Override public Explanation childOf(ConceptMap ans) { return new QueryExplanation(getQuery(), ans.explanation().getAnswers()); } @Override public ImmutableList<ConceptMap> getAnswers(){ return answers;} @Override public Set<ConceptMap> explicit(){ return deductions().stream().filter(ans -> ans.explanation().isLookupExplanation()).collect(Collectors.toSet()); } @Override public Set<ConceptMap> deductions(){ Set<ConceptMap> answers = new HashSet<>(this.getAnswers()); this.getAnswers().forEach(ans -> answers.addAll(ans.explanation().deductions())); return answers; } @Override public boolean isLookupExplanation(){ return false;} @Override public boolean isRuleExplanation(){ return false;} @Override public boolean isJoinExplanation(){ return false;} @Override public boolean isEmpty() { return !isLookupExplanation() && !isRuleExplanation() && getAnswers().isEmpty();} @Override public ReasonerQuery getQuery(){ return query;} }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/explanation/RuleExplanation.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.explanation; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.admin.Explanation; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.internal.reasoner.rule.InferenceRule; import ai.grakn.graql.internal.reasoner.utils.ReasonerUtils; import java.util.Collections; import java.util.List; /** * * <p> * Explanation class for rule application. * </p> * * @author Kasper Piskorski * */ public class RuleExplanation extends QueryExplanation { private final InferenceRule rule; public RuleExplanation(ReasonerQuery q, InferenceRule rl){ super(q); this.rule = rl; } private RuleExplanation(ReasonerQuery q, List<ConceptMap> answers, InferenceRule rl){ super(q, answers); this.rule = rl; } @Override public Explanation setQuery(ReasonerQuery q){ return new RuleExplanation(q, getRule()); } @Override public Explanation childOf(ConceptMap ans) { Explanation explanation = ans.explanation(); return new RuleExplanation(getQuery(), ReasonerUtils.listUnion(this.getAnswers(), explanation.isLookupExplanation()? Collections.singletonList(ans) : explanation.getAnswers()), getRule()); } @Override public boolean isRuleExplanation(){ return true;} public InferenceRule getRule(){ return rule;} }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/iterator/LazyAnswerIterator.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.iterator; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.admin.MultiUnifier; import java.util.Iterator; import java.util.stream.Stream; /** * * <p> * Specific iterator for iterating over graql answers. * </p> * * @author Kasper Piskorski * */ public class LazyAnswerIterator extends LazyIterator<ConceptMap> { public LazyAnswerIterator(Stream<ConceptMap> stream){ super(stream);} private LazyAnswerIterator(Iterator<ConceptMap> iterator){ super(iterator);} public LazyAnswerIterator unify(MultiUnifier unifier){ if (unifier.isEmpty()) return this; return new LazyAnswerIterator(stream().flatMap(a -> a.unify(unifier)).iterator()); } public LazyAnswerIterator merge (Stream<ConceptMap> stream){ return new LazyAnswerIterator(Stream.concat(this.stream(), stream)); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/iterator/LazyIterator.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.iterator; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.stream.Stream; import java.util.stream.StreamSupport; /** * * <p> * Lazy iterator class allowing for rewinding streams by accumulating consumed results. * </p> * * @param <T> the type of element that this iterator will iterate over * * @author Kasper Piskorski * */ public class LazyIterator<T> implements Iterable<T>{ private final Iterator<T> iterator; private final List<T> accumulator = new ArrayList<>(); public LazyIterator(){iterator = Collections.emptyIterator();} public LazyIterator(Stream<T> stream){ this.iterator = stream.distinct().iterator(); } public LazyIterator(Iterator<T> iterator){ this.iterator = iterator;} @Override public Iterator<T> iterator() { return new Iterator<T>(){ int index = 0; @Override public boolean hasNext() { return index < accumulator.size() || iterator.hasNext(); } @Override public T next() { if (index >= accumulator.size()){ T elem = iterator.next(); accumulator.add(elem); } T elem = accumulator.get(index); index++; return elem; } }; } public Stream<T> stream() { return StreamSupport.stream(this.spliterator(), false).distinct(); } public long size(){ return accumulator.size();} }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/iterator/ReasonerQueryIterator.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.iterator; import ai.grakn.graql.answer.ConceptMap; import java.util.Iterator; import java.util.stream.Stream; import java.util.stream.StreamSupport; /** * * <p> * Convenience base class for reasoner iterators. * </p> * * @author Kasper Piskorski * */ public abstract class ReasonerQueryIterator implements Iterator<ConceptMap> { public Stream<ConceptMap> hasStream(){ Iterable<ConceptMap> iterable = () -> this; return StreamSupport.stream(iterable.spliterator(), false).distinct(); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/plan/GraqlTraversalPlanner.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.plan; import ai.grakn.concept.ConceptId; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.Conjunction; import ai.grakn.graql.admin.PatternAdmin; import ai.grakn.graql.admin.VarProperty; import ai.grakn.graql.internal.gremlin.GraqlTraversal; import ai.grakn.graql.internal.gremlin.GreedyTraversalPlan; import ai.grakn.graql.internal.gremlin.fragment.Fragment; import ai.grakn.graql.internal.pattern.Patterns; import ai.grakn.graql.internal.reasoner.atom.Atom; import ai.grakn.graql.internal.reasoner.atom.binary.OntologicalAtom; import ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate; import ai.grakn.graql.internal.reasoner.query.ReasonerQueryImpl; import ai.grakn.kb.internal.EmbeddedGraknTx; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; /** * * <p> * Resolution planner using {@link GreedyTraversalPlan} to establish optimal resolution order.. * </p> * * @author Kasper Piskorski * */ public class GraqlTraversalPlanner { /** * * Refined plan procedure: * - establish a list of starting atom candidates based on their substitutions * - create a plan using {@link GreedyTraversalPlan} * - if the graql plan picks an atom that is not a candidate * - pick an optimal candidate * - call the procedure on atoms with removed candidate * - otherwise return * * @param query for which the plan should be constructed * @return list of atoms in order they should be resolved using a refined {@link GraqlTraversal} procedure. */ public static ImmutableList<Atom> plan(ReasonerQueryImpl query) { List<Atom> startCandidates = query.getAtoms(Atom.class) .filter(Atomic::isSelectable) .collect(Collectors.toList()); Set<IdPredicate> subs = query.getAtoms(IdPredicate.class).collect(Collectors.toSet()); return ImmutableList.copyOf(refinePlan(query, startCandidates, subs)); } @Nullable private static Atom optimalCandidate(List<Atom> candidates){ return candidates.stream() .sorted(Comparator.comparing(at -> !at.isGround())) .sorted(Comparator.comparing(at -> -at.getPredicates().count())) .findFirst().orElse(null); } private static String PLACEHOLDER_ID = "placeholderId"; /** * @param query top level query for which the plan is constructed * @param atoms list of current atoms of interest * @param subs extra substitutions * @return an optimally ordered list of provided atoms */ private static List<Atom> refinePlan(ReasonerQueryImpl query, List<Atom> atoms, Set<IdPredicate> subs){ List<Atom> candidates = subs.isEmpty()? atoms : atoms.stream() .filter(at -> at.getPredicates(IdPredicate.class).findFirst().isPresent()) .collect(Collectors.toList()); ImmutableList<Atom> initialPlan = planFromTraversal(atoms, atomsToPattern(atoms, subs), query.tx()); if (candidates.contains(initialPlan.get(0)) || candidates.isEmpty()) { return initialPlan; } else { Atom first = optimalCandidate(candidates); List<Atom> atomsToPlan = new ArrayList<>(atoms); if(first != null){ atomsToPlan.remove(first); Set<IdPredicate> extraSubs = first.getVarNames().stream() .filter(v -> subs.stream().noneMatch(s -> s.getVarName().equals(v))) .map(v -> IdPredicate.create(v, ConceptId.of(PLACEHOLDER_ID), query)) .collect(Collectors.toSet()); return Stream.concat( Stream.of(first), refinePlan(query, atomsToPlan, Sets.union(subs, extraSubs)).stream() ).collect(Collectors.toList()); } else { return refinePlan(query, atomsToPlan, subs); } } } /** * @param atoms of interest * @param subs extra substitutions in the form of id predicates * @return conjunctive pattern composed of atoms + their constraints + subs */ private static Conjunction<PatternAdmin> atomsToPattern(List<Atom> atoms, Set<IdPredicate> subs){ return Patterns.conjunction( Stream.concat( atoms.stream().flatMap(at -> Stream.concat(Stream.of(at), at.getNonSelectableConstraints())), subs.stream() ) .map(Atomic::getCombinedPattern) .flatMap(p -> p.admin().varPatterns().stream()) .collect(Collectors.toSet()) ); } /** * * @param atoms list of current atoms of interest * @param queryPattern corresponding pattern * @return an optimally ordered list of provided atoms */ private static ImmutableList<Atom> planFromTraversal(List<Atom> atoms, PatternAdmin queryPattern, EmbeddedGraknTx<?> tx){ Multimap<VarProperty, Atom> propertyMap = HashMultimap.create(); atoms.stream() .filter(at -> !(at instanceof OntologicalAtom)) .forEach(at -> at.getVarProperties().forEach(p -> propertyMap.put(p, at))); Set<VarProperty> properties = propertyMap.keySet(); GraqlTraversal graqlTraversal = GreedyTraversalPlan.createTraversal(queryPattern, tx); ImmutableList<Fragment> fragments = graqlTraversal.fragments().iterator().next(); List<Atom> atomList = new ArrayList<>(); atoms.stream().filter(at -> at instanceof OntologicalAtom).forEach(atomList::add); fragments.stream() .map(Fragment::varProperty) .filter(Objects::nonNull) .filter(properties::contains) .distinct() .flatMap(p -> propertyMap.get(p).stream()) .distinct() .forEach(atomList::add); //add any unlinked items (disconnected and indexed for instance) propertyMap.values().stream() .filter(at -> !atomList.contains(at)) .forEach(atomList::add); return ImmutableList.copyOf(atomList); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/plan/QueryCollection.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.plan; import ai.grakn.graql.internal.reasoner.query.ReasonerQueryEquivalence; import ai.grakn.graql.internal.reasoner.query.ReasonerQueryImpl; import com.google.common.base.Equivalence; import java.util.Collection; import java.util.stream.Stream; /** * * <p> * Helper class for collections of {@link ReasonerQueryImpl} queries with equality comparison {@link ReasonerQueryEquivalence}. * </p> * * @param <T> unwrapped collection type * @param <W> wrapped collection type * * @author Kasper Piskorski * */ public abstract class QueryCollection<T extends Collection<ReasonerQueryImpl>, W extends Collection<Equivalence.Wrapper<ReasonerQueryImpl>>> extends QueryCollectionBase{ T collection; W wrappedCollection; @Override public Stream<Equivalence.Wrapper<ReasonerQueryImpl>> wrappedStream(){ return wrappedCollection.stream(); } @Override public Stream<ReasonerQueryImpl> stream() { return collection.stream(); } @Override public String toString(){ return collection.toString();} public T toCollection(){ return collection;} public W toWrappedCollection(){ return wrappedCollection;} public boolean contains(ReasonerQueryImpl q){ return this.contains(equality().wrap(q)); } public boolean contains(Equivalence.Wrapper<ReasonerQueryImpl> q){ return wrappedCollection.contains(q); } public boolean containsAll(QueryCollection<T, W> queries){ return queries.wrappedStream().allMatch(this::contains); } public boolean add(ReasonerQueryImpl q){ return collection.add(q) && wrappedCollection.add(equality().wrap(q)); } public boolean add(Equivalence.Wrapper<ReasonerQueryImpl> q){ return collection.add(q.get()) && wrappedCollection.add(q); } public int size(){ return collection.size();} public boolean isEmpty(){ return collection.isEmpty() && wrappedCollection.isEmpty();} }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/plan/QueryCollectionBase.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.plan; import ai.grakn.graql.Var; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.internal.reasoner.query.ReasonerQueryEquivalence; import ai.grakn.graql.internal.reasoner.query.ReasonerQueryImpl; import com.google.common.base.Equivalence; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import java.util.Collection; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.Stack; import java.util.stream.Collectors; import java.util.stream.Stream; /** * * <p> * Base class for collections of {@link ReasonerQueryImpl} queries with equality comparison {@link ReasonerQueryEquivalence}. * </p> * * @author Kasper Piskorski * */ public abstract class QueryCollectionBase{ public abstract Stream<ReasonerQueryImpl> stream(); public abstract Stream<Equivalence.Wrapper<ReasonerQueryImpl>> wrappedStream(); Equivalence<ReasonerQuery> equality(){ return ReasonerQueryEquivalence.Equality;} private boolean isQueryDisconnected(Equivalence.Wrapper<ReasonerQueryImpl> query){ return getImmediateNeighbours(query).isEmpty(); } /** * @param query of interest * @return true if query is disconnected wrt queries of this collection */ public boolean isQueryDisconnected(ReasonerQueryImpl query){ return isQueryDisconnected(equality().wrap(query)); } private Set<ReasonerQueryImpl> getImmediateNeighbours(ReasonerQueryImpl query){ return getImmediateNeighbours(equality().wrap(query)) .stream() .map(Equivalence.Wrapper::get) .filter(Objects::nonNull) .collect(Collectors.toSet()); } private Set<Equivalence.Wrapper<ReasonerQueryImpl>> getImmediateNeighbours(Equivalence.Wrapper<ReasonerQueryImpl> query){ ReasonerQueryImpl unwrappedQuery = query.get(); Set<Var> vars = unwrappedQuery != null? unwrappedQuery.getVarNames() : new HashSet<>(); return this.wrappedStream() .filter(q2 -> !query.equals(q2)) .map(Equivalence.Wrapper::get) .filter(Objects::nonNull) .filter(q2 -> !Sets.intersection(vars, q2.getVarNames()).isEmpty()) .map(q2 -> equality().wrap(q2)) .collect(Collectors.toSet()); } private Multimap<ReasonerQueryImpl, ReasonerQueryImpl> immediateNeighbourMap(){ Multimap<ReasonerQueryImpl, ReasonerQueryImpl> neighbourMap = HashMultimap.create(); this.stream().forEach(q -> neighbourMap.putAll(q, getImmediateNeighbours(q))); return neighbourMap; } private boolean isQueryReachable(Equivalence.Wrapper<ReasonerQueryImpl> query, Collection<Equivalence.Wrapper<ReasonerQueryImpl>> target){ return isQueryReachable(query.get(), target.stream().map(Equivalence.Wrapper::get).collect(Collectors.toList())); } private boolean isQueryReachable(ReasonerQueryImpl query, Collection<ReasonerQueryImpl> target){ Set<Var> queryVars = getAllNeighbours(query).stream() .flatMap(q -> q.getVarNames().stream()) .collect(Collectors.toSet()); return target.stream() .anyMatch(tq -> !Sets.intersection(tq.getVarNames(), queryVars).isEmpty()); } private Set<ReasonerQueryImpl> getAllNeighbours(ReasonerQueryImpl entryQuery) { Set<ReasonerQueryImpl> neighbours = new HashSet<>(); Set<Equivalence.Wrapper<ReasonerQueryImpl>> visitedQueries = new HashSet<>(); Stack<Equivalence.Wrapper<ReasonerQueryImpl>> queryStack = new Stack<>(); Multimap<ReasonerQueryImpl, ReasonerQueryImpl> neighbourMap = immediateNeighbourMap(); neighbourMap.get(entryQuery).stream().map(q -> equality().wrap(q)).forEach(queryStack::push); while (!queryStack.isEmpty()) { Equivalence.Wrapper<ReasonerQueryImpl> wrappedQuery = queryStack.pop(); ReasonerQueryImpl query = wrappedQuery.get(); if (!visitedQueries.contains(wrappedQuery) && query != null) { neighbourMap.get(query).stream() .peek(neighbours::add) .flatMap(q -> neighbourMap.get(q).stream()) .map(q -> equality().wrap(q)) .filter(q -> !visitedQueries.contains(q)) .filter(q -> !queryStack.contains(q)) .forEach(queryStack::add); visitedQueries.add(wrappedQuery); } } return neighbours; } /** * @param entryQuery query for which candidates are to be determined * @param plan current plan * @return set of candidate queries for this query */ public QuerySet getCandidates(ReasonerQueryImpl entryQuery, QueryList plan){ Equivalence.Wrapper<ReasonerQueryImpl> query = equality().wrap(entryQuery); Set<Equivalence.Wrapper<ReasonerQueryImpl>> availableQueries = this.wrappedStream() .filter(q -> !(plan.contains(q) || q.equals(query))) .collect(Collectors.toSet()); Set<Equivalence.Wrapper<ReasonerQueryImpl>> availableImmediateNeighbours = this.getImmediateNeighbours(query).stream() .filter(availableQueries::contains) .collect(Collectors.toSet()); Set<Var> subbedVars = plan.stream() .flatMap(q -> q.getVarNames().stream()) .collect(Collectors.toSet()); Set<Equivalence.Wrapper<ReasonerQueryImpl>> availableImmediateNeighboursFromSubs = availableQueries.stream() .map(Equivalence.Wrapper::get) .filter(Objects::nonNull) .filter(q -> !Sets.intersection(q.getVarNames(), subbedVars).isEmpty()) .map(q -> equality().wrap(q)) .collect(Collectors.toSet()); return QuerySet.create( this.isQueryDisconnected(query)? availableQueries : this.isQueryReachable(query, availableQueries)? Sets.union(availableImmediateNeighbours, availableImmediateNeighboursFromSubs): availableQueries ); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/reasoner/plan/QueryList.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.graql.internal.reasoner.plan; import ai.grakn.graql.internal.reasoner.query.ReasonerQueryEquivalence; import ai.grakn.graql.internal.reasoner.query.ReasonerQueryImpl; import com.google.common.base.Equivalence; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; /** * * <p> * Helper class for lists of {@link ReasonerQueryImpl} queries with equality comparison {@link ReasonerQueryEquivalence}. * </p> * * @author Kasper Piskorski * */ class QueryList extends QueryCollection<List<ReasonerQueryImpl>, List<Equivalence.Wrapper<ReasonerQueryImpl>>> { QueryList(){ this.collection = new ArrayList<>(); this.wrappedCollection = new ArrayList<>(); } QueryList(Collection<ReasonerQueryImpl> queries){ this.collection = new ArrayList<>(queries); this.wrappedCollection = queries.stream().map(q -> equality().wrap(q)).collect(Collectors.toList()); } }