index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/sets/SubFragmentSet.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.gremlin.sets; import ai.grakn.graql.Var; import ai.grakn.graql.admin.VarProperty; import ai.grakn.graql.internal.gremlin.EquivalentFragmentSet; import ai.grakn.graql.internal.gremlin.fragment.Fragment; import ai.grakn.graql.internal.gremlin.fragment.Fragments; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import java.util.Set; import static ai.grakn.graql.internal.gremlin.sets.EquivalentFragmentSets.fragmentSetOfType; import static ai.grakn.graql.internal.gremlin.sets.EquivalentFragmentSets.labelOf; /** * @see EquivalentFragmentSets#sub(VarProperty, Var, Var) * * @author Felix Chapman */ @AutoValue abstract class SubFragmentSet extends EquivalentFragmentSet { @Override public final Set<Fragment> fragments() { return ImmutableSet.of( Fragments.outSub(varProperty(), subConcept(), superConcept()), Fragments.inSub(varProperty(), superConcept(), subConcept()) ); } abstract Var subConcept(); abstract Var superConcept(); /** * A query can avoid navigating the sub hierarchy when the following conditions are met: * * <ol> * <li>There is a {@link SubFragmentSet} {@code $X-[sub]->$Y} * <li>There is a {@link LabelFragmentSet} {@code $Y[label:foo,bar]} * </ol> * * <p> * In this case, the {@link SubFragmentSet} can be replaced with a {@link LabelFragmentSet} * {@code $X[label:foo,...]} that is the <b>intersection</b> of all the subs of {@code foo} and {@code bar}. * </p> * * <p> * However, we still keep the old {@link LabelFragmentSet} in case it is connected to anything. * {@link LabelFragmentSet#REDUNDANT_LABEL_ELIMINATION_OPTIMISATION} will eventually remove it if it is not. * </p> */ static final FragmentSetOptimisation SUB_TRAVERSAL_ELIMINATION_OPTIMISATION = (fragmentSets, tx) -> { Iterable<SubFragmentSet> subSets = fragmentSetOfType(SubFragmentSet.class, fragmentSets)::iterator; for (SubFragmentSet subSet : subSets) { LabelFragmentSet labelSet = labelOf(subSet.superConcept(), fragmentSets); if (labelSet == null) continue; LabelFragmentSet newLabelSet = labelSet.tryExpandSubs(subSet.subConcept(), tx); // Disable this optimisation if there isn't exactly one possible label. // This is because JanusGraph doesn't optimise P.within correctly when the property is indexed. // TODO: Remove this if JanusGraph fixes this issue if (newLabelSet != null && newLabelSet.labels().size() != 1) { continue; } if (newLabelSet != null) { fragmentSets.remove(subSet); fragmentSets.add(newLabelSet); return true; } } return false; }; }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/sets/ValueFragmentSet.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.gremlin.sets; import ai.grakn.graql.ValuePredicate; import ai.grakn.graql.Var; import ai.grakn.graql.admin.VarProperty; import ai.grakn.graql.internal.gremlin.EquivalentFragmentSet; import ai.grakn.graql.internal.gremlin.fragment.Fragment; import ai.grakn.graql.internal.gremlin.fragment.Fragments; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import java.util.Set; /** * @see EquivalentFragmentSets#value(VarProperty, Var, ValuePredicate) * * @author Felix Chapman */ @AutoValue abstract class ValueFragmentSet extends EquivalentFragmentSet { @Override public final Set<Fragment> fragments() { return ImmutableSet.of(Fragments.value(varProperty(), var(), predicate())); } abstract Var var(); abstract ValuePredicate predicate(); }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/spanningtree/Arborescence.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.gremlin.spanningtree; import ai.grakn.graql.internal.gremlin.spanningtree.graph.DirectedEdge; import com.google.common.base.Objects; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * An arborescence is a directed graph in which, for the root and any other vertex, * there is exactly one directed path between them. * (https://en.wikipedia.org/wiki/Arborescence_(graph_theory)) * * @param <V> the type of the nodes * @author Jason Liu */ public class Arborescence<V> { /** * In an arborescence, each node (other than the root) has exactly one parent. This is the map * from each node to its parent. */ private final ImmutableMap<V, V> parents; private final V root; private Arborescence(ImmutableMap<V, V> parents, V root) { this.parents = parents; this.root = root; } public static <T> Arborescence<T> of(ImmutableMap<T, T> parents) { if (parents != null && !parents.isEmpty()) { HashSet<T> allParents = Sets.newHashSet(parents.values()); allParents.removeAll(parents.keySet()); if (allParents.size() == 1) { return new Arborescence<>(parents, allParents.iterator().next()); } } return new Arborescence<>(parents, null); } public static <T> Arborescence<T> empty() { return Arborescence.of(ImmutableMap.<T, T>of()); } public boolean contains(DirectedEdge<V> e) { final V dest = e.destination; return parents.containsKey(dest) && parents.get(dest).equals(e.source); } public V getRoot() { return root; } public ImmutableMap<V, V> getParents() { return parents; } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); parents.forEach((key, value) -> stringBuilder.append(value).append(" -> ").append(key).append("; ")); return stringBuilder.toString(); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; final Arborescence that = (Arborescence) other; Set<Map.Entry<V, V>> myEntries = parents.entrySet(); Set thatEntries = that.parents.entrySet(); return myEntries.size() == thatEntries.size() && myEntries.containsAll(thatEntries); } @Override public int hashCode() { return Objects.hashCode(parents); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/spanningtree/AutoValue_EdgeQueueMap_QueueAndReplace.java
package ai.grakn.graql.internal.gremlin.spanningtree; import ai.grakn.graql.internal.gremlin.spanningtree.graph.DirectedEdge; import ai.grakn.graql.internal.gremlin.spanningtree.util.Weighted; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_EdgeQueueMap_QueueAndReplace<V> extends EdgeQueueMap.QueueAndReplace<V> { private final EdgeQueueMap.EdgeQueue<V> queue; private final Weighted<DirectedEdge<V>> replace; AutoValue_EdgeQueueMap_QueueAndReplace( EdgeQueueMap.EdgeQueue<V> queue, Weighted<DirectedEdge<V>> replace) { if (queue == null) { throw new NullPointerException("Null queue"); } this.queue = queue; if (replace == null) { throw new NullPointerException("Null replace"); } this.replace = replace; } @Override EdgeQueueMap.EdgeQueue<V> queue() { return queue; } @Override Weighted<DirectedEdge<V>> replace() { return replace; } @Override public String toString() { return "QueueAndReplace{" + "queue=" + queue + ", " + "replace=" + replace + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof EdgeQueueMap.QueueAndReplace) { EdgeQueueMap.QueueAndReplace<?> that = (EdgeQueueMap.QueueAndReplace<?>) o; return (this.queue.equals(that.queue())) && (this.replace.equals(that.replace())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.queue.hashCode(); h *= 1000003; h ^= this.replace.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/spanningtree/ChuLiuEdmonds.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.gremlin.spanningtree; import ai.grakn.graql.internal.gremlin.spanningtree.graph.DirectedEdge; import ai.grakn.graql.internal.gremlin.spanningtree.graph.WeightedGraph; import ai.grakn.graql.internal.gremlin.spanningtree.util.Weighted; import ai.grakn.graql.internal.util.Partition; import com.google.common.collect.ImmutableMap; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import static ai.grakn.graql.internal.gremlin.spanningtree.util.Weighted.weighted; import static com.google.common.base.Predicates.and; import static com.google.common.base.Predicates.not; /** * Chu-Liu-Edmonds' algorithm for finding a maximum branching in a complete, directed graph in O(n^2) time. * Implementation is based on Tarjan's "Finding Optimum Branchings" paper: * http://cw.felk.cvut.cz/lib/exe/fetch.php/courses/a4m33pal/cviceni/tarjan-finding-optimum-branchings.pdf * * @author Jason Liu */ public class ChuLiuEdmonds { /** * Represents the subgraph that gets iteratively built up in the CLE algorithm. */ static class PartialSolution<V> { // Partition representing the strongly connected components (SCCs). private final Partition<V> stronglyConnected; // Partition representing the weakly connected components (WCCs). private final Partition<V> weaklyConnected; // An invariant of the CLE algorithm is that each SCC always has at most one incoming edge. // You can think of these edges as implicitly defining a graph with SCCs as nodes. private final Map<V, Weighted<DirectedEdge<V>>> incomingEdgeByScc; // History of edges we've added, and for each, a list of edges it would exclude. // More recently added edges get priority over less recently added edges when reconstructing the final tree. private final Deque<ExclusiveEdge<V>> edgesAndWhatTheyExclude; // a priority queue of incoming edges for each SCC that we haven't chosen an incoming edge for yet. final EdgeQueueMap<V> unseenIncomingEdges; // running sum of weights. // edge weights are adjusted as we go to take into account the fact that we have an extra edge in each cycle private double score; private PartialSolution(Partition<V> stronglyConnected, Partition<V> weaklyConnected, Map<V, Weighted<DirectedEdge<V>>> incomingEdgeByScc, Deque<ExclusiveEdge<V>> edgesAndWhatTheyExclude, EdgeQueueMap<V> unseenIncomingEdges, double score) { this.stronglyConnected = stronglyConnected; this.weaklyConnected = weaklyConnected; this.incomingEdgeByScc = incomingEdgeByScc; this.edgesAndWhatTheyExclude = edgesAndWhatTheyExclude; this.unseenIncomingEdges = unseenIncomingEdges; this.score = score; } public static <T> PartialSolution<T> initialize(WeightedGraph<T> graph) { final Partition<T> stronglyConnected = Partition.singletons(graph.getNodes()); final HashMap<T, Weighted<DirectedEdge<T>>> incomingByScc = new HashMap<>(); final Deque<ExclusiveEdge<T>> exclusiveEdges = new ArrayDeque<>(); // group edges by their destination component final EdgeQueueMap<T> incomingEdges = new EdgeQueueMap<>(stronglyConnected); for (T destinationNode : graph.getNodes()) { for (Weighted<DirectedEdge<T>> inEdge : graph.getIncomingEdges(destinationNode)) { if (inEdge.weight != Double.NEGATIVE_INFINITY) { incomingEdges.addEdge(inEdge); } } } return new PartialSolution<T>( stronglyConnected, Partition.singletons(graph.getNodes()), incomingByScc, exclusiveEdges, incomingEdges, 0.0 ); } public Set<V> getNodes() { return stronglyConnected.getNodes(); } /** * Given an edge that completes a cycle, merge all SCCs on that cycle into one SCC. * Returns the new component. */ private V merge(Weighted<DirectedEdge<V>> newEdge, EdgeQueueMap<V> unseenIncomingEdges) { // Find edges connecting SCCs on the path from newEdge.destination to newEdge.source final List<Weighted<DirectedEdge<V>>> cycle = getCycle(newEdge); // build up list of queues that need to be merged, with the edge they would exclude final List<EdgeQueueMap.QueueAndReplace<V>> queuesToMerge = new ArrayList<>(cycle.size()); for (Weighted<DirectedEdge<V>> currentEdge : cycle) { final V destination = stronglyConnected.componentOf(currentEdge.val.destination); final EdgeQueueMap.EdgeQueue<V> queue = unseenIncomingEdges.queueByDestination.get(destination); // if we choose an edge in `queue`, we'll have to throw out `currentEdge` at the end // (each SCC can have only one incoming edge). queuesToMerge.add(EdgeQueueMap.QueueAndReplace.of(queue, currentEdge)); unseenIncomingEdges.queueByDestination.remove(destination); } // Merge all SCCs on the cycle into one for (Weighted<DirectedEdge<V>> e : cycle) { stronglyConnected.merge(e.val.source, e.val.destination); } V component = stronglyConnected.componentOf(newEdge.val.destination); // merge the queues and put the merged queue back into our map under the new component unseenIncomingEdges.merge(component, queuesToMerge); // keep our implicit graph of SCCs up to date: // we just created a cycle, so all in-edges have sources inside the new component // i.e. there is no edge with source outside component, and destination inside component incomingEdgeByScc.remove(component); return component; } /** * Gets the cycle of edges between SCCs that newEdge creates */ private List<Weighted<DirectedEdge<V>>> getCycle(Weighted<DirectedEdge<V>> newEdge) { final List<Weighted<DirectedEdge<V>>> cycle = new ArrayList<>(); // circle around backward until you get back to where you started Weighted<DirectedEdge<V>> edge = newEdge; cycle.add(edge); while (!stronglyConnected.sameComponent(edge.val.source, newEdge.val.destination)) { edge = incomingEdgeByScc.get(stronglyConnected.componentOf(edge.val.source)); cycle.add(edge); } return cycle; } /** * Adds the given edge to this subgraph, merging SCCs if necessary * * @return the new SCC if adding edge created a cycle */ public Optional<V> addEdge(ExclusiveEdge<V> wEdgeAndExcludes) { final DirectedEdge<V> edge = wEdgeAndExcludes.edge; final double weight = wEdgeAndExcludes.weight; final Weighted<DirectedEdge<V>> wEdge = weighted(edge, weight); score += weight; final V destinationScc = stronglyConnected.componentOf(edge.destination); edgesAndWhatTheyExclude.addFirst(wEdgeAndExcludes); incomingEdgeByScc.put(destinationScc, wEdge); if (!weaklyConnected.sameComponent(edge.source, edge.destination)) { // Edge connects two different WCCs. Including it won't create a new cycle weaklyConnected.merge(edge.source, edge.destination); return Optional.empty(); } else { // Edge is contained within one WCC. Including it will create a new cycle. return Optional.of(merge(wEdge, unseenIncomingEdges)); } } /** * Recovers the optimal arborescence. * <p> * Each SCC can only have 1 edge entering it: the edge that we added most recently. * So we work backwards, adding edges unless they conflict with edges we've already added. * Runtime is O(n^2) in the worst case. */ private Weighted<Arborescence<V>> recoverBestArborescence() { final ImmutableMap.Builder<V, V> parents = ImmutableMap.builder(); final Set<DirectedEdge> excluded = new HashSet<>(); // start with the most recent while (!edgesAndWhatTheyExclude.isEmpty()) { final ExclusiveEdge<V> edgeAndWhatItExcludes = edgesAndWhatTheyExclude.pollFirst(); final DirectedEdge<V> edge = edgeAndWhatItExcludes.edge; if (!excluded.contains(edge)) { excluded.addAll(edgeAndWhatItExcludes.excluded); parents.put(edge.destination, edge.source); } } return weighted(Arborescence.of(parents.build()), score); } public Optional<ExclusiveEdge<V>> popBestEdge(V component) { return popBestEdge(component, Arborescence.empty()); } /** * Always breaks ties in favor of edges in `best` */ public Optional<ExclusiveEdge<V>> popBestEdge(V component, Arborescence<V> best) { return unseenIncomingEdges.popBestEdge(component, best); } } /** * Find an optimal arborescence of the given graph `graph`, rooted in the given node `root`. */ public static <V> Weighted<Arborescence<V>> getMaxArborescence(WeightedGraph<V> graph, V root) { // remove all edges incoming to `root`. resulting arborescence is then forced to be rooted at `root`. return getMaxArborescence(graph.filterEdges(not(DirectedEdge.hasDestination(root)))); } static <V> Weighted<Arborescence<V>> getMaxArborescence(WeightedGraph<V> graph, Set<DirectedEdge<V>> required, Set<DirectedEdge<V>> banned) { return getMaxArborescence(graph.filterEdges(and(not(DirectedEdge.competesWith(required)), not(DirectedEdge.isIn(banned))))); } /** * Find an optimal arborescence of the given graph. */ public static <V> Weighted<Arborescence<V>> getMaxArborescence(WeightedGraph<V> graph) { final PartialSolution<V> partialSolution = PartialSolution.initialize(graph.filterEdges(not(DirectedEdge.isAutoCycle()))); // In the beginning, subgraph has no edges, so no SCC has in-edges. final Deque<V> componentsWithNoInEdges = new ArrayDeque<>(partialSolution.getNodes()); // Work our way through all componentsWithNoInEdges, in no particular order while (!componentsWithNoInEdges.isEmpty()) { final V component = componentsWithNoInEdges.poll(); // find maximum edge entering 'component' from outside 'component'. final Optional<ExclusiveEdge<V>> oMaxInEdge = partialSolution.popBestEdge(component); if (!oMaxInEdge.isPresent()) continue; // No in-edges left to consider for this component. Done with it! final ExclusiveEdge<V> maxInEdge = oMaxInEdge.get(); // add the new edge to subgraph, merging SCCs if necessary final Optional<V> newComponent = partialSolution.addEdge(maxInEdge); if (newComponent.isPresent()) { // addEdge created a cycle/component, which means the new component doesn't have any incoming edges componentsWithNoInEdges.add(newComponent.get()); } } // Once no component has incoming edges left to consider, it's time to recover the optimal branching. return partialSolution.recoverBestArborescence(); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/spanningtree/EdgeQueueMap.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.gremlin.spanningtree; import ai.grakn.graql.internal.gremlin.spanningtree.datastructure.FibonacciQueue; import ai.grakn.graql.internal.gremlin.spanningtree.graph.DirectedEdge; import ai.grakn.graql.internal.gremlin.spanningtree.util.Weighted; import ai.grakn.graql.internal.util.Partition; import com.google.auto.value.AutoValue; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; /** * A priority queue of incoming edges for each strongly connected component that we haven't chosen * an incoming edge for yet. * * @param <V> the type of the nodes stored * @author Jason Liu */ class EdgeQueueMap<V> { final Partition<V> partition; public final Map<V, EdgeQueue<V>> queueByDestination; public static class EdgeQueue<V> { private final V component; public final FibonacciQueue<ExclusiveEdge<V>> edges; private final Partition<V> partition; private EdgeQueue(V component, Partition<V> partition) { this.component = component; this.edges = FibonacciQueue.create(Collections.reverseOrder()); // highest weight edges first this.partition = partition; } public static <T> EdgeQueue<T> create(T component, Partition<T> partition) { return new EdgeQueue<>(component, partition); } public void addEdge(ExclusiveEdge<V> exclusiveEdge) { // only add if source is external to SCC if (partition.componentOf(exclusiveEdge.edge.source).equals(component)) return; edges.add(exclusiveEdge); } /** * Always breaks ties in favor of edges in bestArborescence */ public Optional<ExclusiveEdge<V>> popBestEdge(Arborescence<V> bestArborescence) { if (edges.isEmpty()) return Optional.empty(); final LinkedList<ExclusiveEdge<V>> candidates = Lists.newLinkedList(); do { candidates.addFirst(edges.poll()); } while (!edges.isEmpty() && edges.comparator().compare(candidates.getFirst(), edges.peek()) == 0 // has to be tied for best && !bestArborescence.contains(candidates.getFirst().edge)); // break if we've found one in `bestArborescence` // at this point all edges in `candidates` have equal weight, and if one of them is in `bestArborescence` // it will be first final ExclusiveEdge<V> bestEdge = candidates.removeFirst(); // edges.addAll(candidates); // add back all the edges we looked at but didn't pick edges.addAll(candidates); return Optional.of(bestEdge); } } @AutoValue abstract static class QueueAndReplace<V> { abstract EdgeQueue<V> queue(); abstract Weighted<DirectedEdge<V>> replace(); static <V> QueueAndReplace<V> of(EdgeQueueMap.EdgeQueue<V> queue, Weighted<DirectedEdge<V>> replace) { return new AutoValue_EdgeQueueMap_QueueAndReplace<>(queue, replace); } } EdgeQueueMap(Partition<V> partition) { this.partition = partition; this.queueByDestination = Maps.newHashMap(); } public void addEdge(Weighted<DirectedEdge<V>> edge) { final V destination = partition.componentOf(edge.val.destination); if (!queueByDestination.containsKey(destination)) { queueByDestination.put(destination, EdgeQueue.create(destination, partition)); } final List<DirectedEdge<V>> replaces = Lists.newLinkedList(); queueByDestination.get(destination).addEdge(ExclusiveEdge.of(edge.val, replaces, edge.weight)); } /** * Always breaks ties in favor of edges in best */ public Optional<ExclusiveEdge<V>> popBestEdge(V component, Arborescence<V> best) { if (!queueByDestination.containsKey(component)) return Optional.empty(); return queueByDestination.get(component).popBestEdge(best); } public EdgeQueue merge(V component, Iterable<QueueAndReplace<V>> queuesToMerge) { final EdgeQueue<V> result = EdgeQueue.create(component, partition); for (QueueAndReplace<V> queueAndReplace : queuesToMerge) { final EdgeQueue<V> queue = queueAndReplace.queue(); final Weighted<DirectedEdge<V>> replace = queueAndReplace.replace(); for (ExclusiveEdge<V> wEdgeAndExcluded : queue.edges) { final List<DirectedEdge<V>> replaces = wEdgeAndExcluded.excluded; replaces.add(replace.val); result.addEdge(ExclusiveEdge.of( wEdgeAndExcluded.edge, replaces, wEdgeAndExcluded.weight - replace.weight)); } } queueByDestination.put(component, result); return result; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/spanningtree/ExclusiveEdge.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.gremlin.spanningtree; import ai.grakn.graql.internal.gremlin.spanningtree.graph.DirectedEdge; import java.util.List; /** * An edge, together with a list of edges that can't be in the final answer if 'edge' is. * * @param <V> nodes * @author Jason Liu */ public class ExclusiveEdge<V> implements Comparable<ExclusiveEdge<V>> { public final DirectedEdge<V> edge; public final List<DirectedEdge<V>> excluded; public final double weight; private ExclusiveEdge(DirectedEdge<V> edge, List<DirectedEdge<V>> excluded, double weight) { this.edge = edge; this.excluded = excluded; this.weight = weight; } public static <T> ExclusiveEdge<T> of(DirectedEdge<T> edge, List<DirectedEdge<T>> excluded, double weight) { return new ExclusiveEdge<>(edge, excluded, weight); } @Override public int compareTo(ExclusiveEdge<V> exclusiveEdge) { return Double.compare(weight, exclusiveEdge.weight); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final ExclusiveEdge that = (ExclusiveEdge) o; return edge != null && edge.equals(that.edge) && excluded != null && excluded.equals(that.excluded) && Double.compare(weight, that.weight) == 0; } @Override public int hashCode() { int result = edge != null ? edge.hashCode() : 0; result = result * 31 + (excluded != null ? excluded.hashCode() : 0); result = result * 31 + Double.valueOf(weight).hashCode(); return result; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/spanningtree
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/spanningtree/datastructure/FibonacciHeap.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.gremlin.spanningtree.datastructure; import com.google.common.base.Preconditions; import com.google.common.collect.Ordering; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * A Fibonacci heap (due to Fredman and Tarjan). * * @param <V> the type of the values stored in the heap * @param <P> the type of the priorities * @author Grakn Warriors */ public class FibonacciHeap<V, P> implements Iterable<FibonacciHeap<V, P>.Entry> { private final static int MAX_CAPACITY = Integer.MAX_VALUE; // the largest degree of any root list entry is guaranteed to be <= log_phi(MAX_CAPACITY) = 45 private final static int MAX_DEGREE = 45; private Entry oMinEntry = null; private int size = 0; private final Comparator<? super P> comparator; class Entry { public final V value; private P priority; private Entry oParent = null; private Entry oFirstChild = null; private Entry previous; private Entry next; private int degree = 0; // Whether this entry has had a child cut since it was added to its parent. // An entry can only have one child cut before it has to be cut itself. private boolean isMarked = false; private Entry(V value, P priority) { this.value = value; this.priority = priority; previous = next = this; } } private FibonacciHeap(Comparator<? super P> comparator) { // we'll use nulls to force a node to the top when we delete it this.comparator = Ordering.from(comparator).nullsFirst(); } public static <T, C> FibonacciHeap<T, C> create(Comparator<? super C> comparator) { return new FibonacciHeap<>(comparator); } /** * Create a new FibonacciHeap based on the natural ordering on `C` */ public static <T, C extends Comparable> FibonacciHeap<T, C> create() { return FibonacciHeap.create(Ordering.<C>natural()); } /** * Returns the comparator used to order the elements in this * queue. */ public Comparator<? super P> comparator() { return comparator; } /** * Removes all elements from the heap. * Runtime: O(1) */ public void clear() { oMinEntry = null; size = 0; } /** * Decreases the priority for an entry. * Runtime: O(1) (amortized) */ public void decreasePriority(Entry entry, P newPriority) { Preconditions.checkArgument( comparator.compare(newPriority, entry.priority) <= 0, "Cannot increase priority" ); assert oMinEntry != null; entry.priority = newPriority; Entry oParent = entry.oParent; if (oParent != null && (comparator.compare(newPriority, oParent.priority) < 0)) { cutAndMakeRoot(entry); } if (comparator.compare(newPriority, oMinEntry.priority) < 0) { oMinEntry = entry; } } /** * Deletes `entry` from the heap. The heap will be consolidated, if necessary. * Runtime: O(log n) amortized */ public void remove(Entry entry) { entry.priority = null; cutAndMakeRoot(entry); oMinEntry = entry; poll(); } /** * Returns true if the heap is empty, false otherwise. * Runtime: O(1) */ public boolean isEmpty() { return oMinEntry == null; } /** * Inserts a new entry into the heap and returns the entry if heap is not full. Returns absent otherwise. * No heap consolidation is performed. * Runtime: O(1) */ public Entry add(V value, P priority) { Preconditions.checkNotNull(value); Preconditions.checkNotNull(priority); if (size >= MAX_CAPACITY) return null; final Entry result = new Entry(value, priority); // add as a root oMinEntry = mergeLists(result, oMinEntry); size++; return result; } /** * Returns the entry with the minimum priority, or absent if empty. * Runtime: O(1) */ public Entry peek() { return oMinEntry; } /** * Removes the smallest element from the heap. This will cause * the trees in the heap to be consolidated, if necessary. * Runtime: O(log n) amortized */ public V poll() { if (oMinEntry == null) return null; final Entry minEntry = oMinEntry; // move minEntry's children to the root list Entry oFirstChild = minEntry.oFirstChild; if (oFirstChild != null) { for (Entry childOfMin : getCycle(oFirstChild)) { childOfMin.oParent = null; } mergeLists(oMinEntry, oFirstChild); } // remove minEntry from root list if (size == 1) { oMinEntry = null; } else { final Entry next = minEntry.next; unlinkFromNeighbors(minEntry); oMinEntry = consolidate(next); } size--; return minEntry.value; } /** * Returns the number of elements in the heap. * Runtime: O(1) */ public int size() { return size; } /** * Joins two Fibonacci heaps into a new one. No heap consolidation is * performed; the two root lists are just spliced together. * Runtime: O(1) */ public static <U, P> FibonacciHeap<U, P> merge(FibonacciHeap<U, P> a, FibonacciHeap<U, P> b) { Preconditions.checkArgument(a.comparator().equals(b.comparator()), "Heaps that use different comparators can't be merged."); final FibonacciHeap<U, P> result = FibonacciHeap.create(a.comparator); result.oMinEntry = a.mergeLists(a.oMinEntry, b.oMinEntry); result.size = a.size + b.size; return result; } /** * Returns every entry in this heap, in no particular order. */ @Override public Iterator<Entry> iterator() { return siblingsAndBelow(oMinEntry).iterator(); } /** * Depth-first iteration */ private List<Entry> siblingsAndBelow(Entry oEntry) { if (oEntry == null) return Collections.emptyList(); List<Entry> output = new LinkedList<>(); for (Entry entry : getCycle(oEntry)) { if (entry != null) { output.add(entry); output.addAll(siblingsAndBelow(entry.oFirstChild)); } } return output; } private List<Entry> getCycle(Entry start) { final List<Entry> results = new ArrayList<>(); Entry current = start; do { results.add(current); current = current.next; } while (!current.equals(start)); return results; } /** * Merge two doubly-linked circular lists, given a pointer into each. * Return the smaller of the two arguments. */ private Entry mergeLists(Entry a, Entry b) { if (a == null) return b; if (b == null) return a; // splice the two circular lists together like a Mobius strip final Entry aOldNext = a.next; a.next = b.next; a.next.previous = a; b.next = aOldNext; b.next.previous = b; return comparator.compare(a.priority, b.priority) < 0 ? a : b; } /** * Cuts this entry from its parent and adds it to the root list, and then * does the same for its parent, and so on up the tree. * Runtime: O(log n) */ private void cutAndMakeRoot(Entry entry) { Entry oParent = entry.oParent; if (oParent == null) return; // already a root oParent.degree--; entry.isMarked = false; // update parent's `oFirstChild` pointer Entry oFirstChild = oParent.oFirstChild; assert oFirstChild != null; if (oFirstChild.equals(entry)) { if (oParent.degree == 0) { oParent.oFirstChild = null; } else { oParent.oFirstChild = entry.next; } } entry.oParent = null; unlinkFromNeighbors(entry); // add to root list mergeLists(entry, oMinEntry); if (oParent.oParent != null) { if (oParent.isMarked) { cutAndMakeRoot(oParent); } else { oParent.isMarked = true; } } } /** * Attaches `entry` as a child of `parent`. Returns `parent`. */ private Entry setParent(Entry entry, Entry parent) { unlinkFromNeighbors(entry); entry.oParent = parent; parent.oFirstChild = mergeLists(entry, parent.oFirstChild); parent.degree++; entry.isMarked = false; return parent; } private static void unlinkFromNeighbors(FibonacciHeap.Entry entry) { entry.previous.next = entry.next; entry.next.previous = entry.previous; entry.previous = entry; entry.next = entry; } /** * Consolidates the trees in the heap by joining trees of equal * degree until there are no more trees of equal degree in the * root list. Returns the new minimum root. * Runtime: O(log n) (amortized) */ private Entry consolidate(Entry someRoot) { Entry minRoot = someRoot; // `rootsByDegree[d]` will hold the best root we've looked at so far with degree `d`. final Object[] rootsByDegree = new Object[MAX_DEGREE]; for (Entry currRoot : getCycle(someRoot)) { // Put `currRoot` into `rootsByDegree`. If there's already something in its spot, // merge them into a new tree of degree `degree + 1`. Keep merging until we find an // empty spot. Entry mergedRoot = currRoot; for (int degree = currRoot.degree; rootsByDegree[degree] != null; degree++) { @SuppressWarnings("unchecked") Entry oldRoot = (Entry) rootsByDegree[degree]; // move the worse root beneath the better root if (comparator.compare(mergedRoot.priority, oldRoot.priority) < 0) { mergedRoot = setParent(oldRoot, mergedRoot); } else { mergedRoot = setParent(mergedRoot, oldRoot); } rootsByDegree[degree] = null; } rootsByDegree[mergedRoot.degree] = mergedRoot; if (comparator.compare(mergedRoot.priority, minRoot.priority) <= 0) { minRoot = mergedRoot; } } return minRoot; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/spanningtree
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/spanningtree/datastructure/FibonacciQueue.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.gremlin.spanningtree.datastructure; import com.google.common.collect.Iterators; import java.util.AbstractQueue; import java.util.Comparator; import java.util.Iterator; import java.util.function.Function; /** * A PriorityQueue built on top of a FibonacciHeap * * @param <E> the type of the values stored * @author Grakn Warriors */ public class FibonacciQueue<E> extends AbstractQueue<E> { private final FibonacciHeap<E, E> heap; private final Function<FibonacciHeap<E, ?>.Entry, E> getValue = input -> { assert input != null; return input.value; }; private FibonacciQueue(FibonacciHeap<E, E> heap) { this.heap = heap; } public static <C> FibonacciQueue<C> create(Comparator<? super C> comparator) { return new FibonacciQueue<>(FibonacciHeap.create(comparator)); } public static <C extends Comparable> FibonacciQueue<C> create() { return new FibonacciQueue<>(FibonacciHeap.create()); } public Comparator<? super E> comparator() { return heap.comparator(); } @Override public E peek() { return heap.peek().value; } @Override public boolean offer(E e) { return heap.add(e, e) != null; } @Override public E poll() { return heap.poll(); } @Override public int size() { return heap.size(); } @Override public Iterator<E> iterator() { return Iterators.transform(heap.iterator(), getValue::apply); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/spanningtree
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/spanningtree/graph/DenseWeightedGraph.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.gremlin.spanningtree.graph; import ai.grakn.graql.internal.gremlin.spanningtree.util.Weighted; import com.google.common.base.Preconditions; import com.google.common.collect.ContiguousSet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import static com.google.common.collect.DiscreteDomain.integers; import static com.google.common.collect.Range.closedOpen; /** * @param <V> the type of the nodes stored * @author Jason Liu */ public class DenseWeightedGraph<V> extends WeightedGraph<V> { final private ArrayList<V> nodes; final private Map<V, Integer> indexOf; final private double[][] weights; private DenseWeightedGraph(ArrayList<V> nodes, Map<V, Integer> indexOf, double[][] weights) { this.nodes = nodes; this.indexOf = indexOf; this.weights = weights; } public static <V> DenseWeightedGraph<V> from(Iterable<V> nodes, double[][] weights) { final ArrayList<V> nodeList = Lists.newArrayList(nodes); Preconditions.checkArgument(nodeList.size() == weights.length); final Map<V, Integer> indexOf = Maps.newHashMap(); for (int i = 0; i < nodeList.size(); i++) { indexOf.put(nodeList.get(i), i); } return new DenseWeightedGraph<>(nodeList, indexOf, weights); } public static DenseWeightedGraph<Integer> from(double[][] weights) { final Set<Integer> nodes = ContiguousSet.create(closedOpen(0, weights.length), integers()); return DenseWeightedGraph.from(nodes, weights); } @Override public Collection<V> getNodes() { return nodes; } @Override public double getWeightOf(V source, V dest) { if (!indexOf.containsKey(source) || !indexOf.containsKey(dest)) return Double.NEGATIVE_INFINITY; return weights[indexOf.get(source)][indexOf.get(dest)]; } @Override public Collection<Weighted<DirectedEdge<V>>> getIncomingEdges(V destinationNode) { if (!indexOf.containsKey(destinationNode)) return Collections.emptySet(); final int dest = indexOf.get(destinationNode); List<Weighted<DirectedEdge<V>>> results = Lists.newArrayList(); for (int src = 0; src < nodes.size(); src++) { results.add(Weighted.weighted(DirectedEdge.from(nodes.get(src)).to(destinationNode), weights[src][dest])); } return results; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/spanningtree
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/spanningtree/graph/DirectedEdge.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.gremlin.spanningtree.graph; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableMap; import java.util.Map; import java.util.Set; /** * An edge in a directed graph. * * @param <V> the type of the node * @author Jason Liu */ public class DirectedEdge<V> { public final V source; public final V destination; public DirectedEdge(V source, V destination) { this.source = source; this.destination = destination; } /** * @param <V> the type of the node */ public static class EdgeBuilder<V> { public final V source; private EdgeBuilder(V source) { this.source = source; } public DirectedEdge<V> to(V destination) { return new DirectedEdge<>(source, destination); } } public static <T> EdgeBuilder<T> from(T source) { return new EdgeBuilder<>(source); } @Override public int hashCode() { return Objects.hashCode(source, destination); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("source", source) .add("destination", destination).toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DirectedEdge other = (DirectedEdge) o; return this.source.equals(other.source) && this.destination.equals(other.destination); } //// Edge Predicates public static <T> Predicate<DirectedEdge<T>> hasDestination(final T node) { return input -> { assert input != null; return input.destination.equals(node); }; } public static <T> Predicate<DirectedEdge<T>> competesWith(final Set<DirectedEdge<T>> required) { final ImmutableMap.Builder<T, T> requiredSourceByDestinationBuilder = ImmutableMap.builder(); for (DirectedEdge<T> edge : required) { requiredSourceByDestinationBuilder.put(edge.destination, edge.source); } final Map<T, T> requiredSourceByDest = requiredSourceByDestinationBuilder.build(); return input -> { assert input != null; return (requiredSourceByDest.containsKey(input.destination) && !input.source.equals(requiredSourceByDest.get(input.destination))); }; } public static <T> Predicate<DirectedEdge<T>> isAutoCycle() { return input -> { assert input != null; return input.source.equals(input.destination); }; } public static <T> Predicate<DirectedEdge<T>> isIn(final Set<DirectedEdge<T>> banned) { return input -> banned.contains(input); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/spanningtree
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/spanningtree/graph/Node.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.gremlin.spanningtree.graph; import ai.grakn.graql.Var; import ai.grakn.graql.internal.gremlin.fragment.Fragment; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * An node in a directed graph. * * @author Grakn Warriors */ public class Node { private final NodeId nodeId; private boolean isValidStartingPoint = true; private double fixedFragmentCost = 0; private Double nodeWeight = null; private Double branchWeight = null; private Set<Fragment> fragmentsWithoutDependency = new HashSet<>(); private Set<Fragment> fragmentsWithDependency = new HashSet<>(); private Set<Fragment> fragmentsWithDependencyVisited = new HashSet<>(); private Set<Fragment> dependants = new HashSet<>(); private Node(NodeId nodeId) { this.nodeId = nodeId; } public static Node addIfAbsent(NodeId.NodeType nodeType, Var var, Map<NodeId, Node> nodes) { NodeId nodeId = new NodeId(nodeType, var); if (!nodes.containsKey(nodeId)) { nodes.put(nodeId, new Node(nodeId)); } return nodes.get(nodeId); } public static Node addIfAbsent(NodeId.NodeType nodeType, Set<Var> vars, Map<NodeId, Node> nodes) { NodeId nodeId = new NodeId(nodeType, vars); if (!nodes.containsKey(nodeId)) { nodes.put(nodeId, new Node(nodeId)); } return nodes.get(nodeId); } public Set<Fragment> getFragmentsWithoutDependency() { return fragmentsWithoutDependency; } public Set<Fragment> getFragmentsWithDependency() { return fragmentsWithDependency; } public Set<Fragment> getFragmentsWithDependencyVisited() { return fragmentsWithDependencyVisited; } public Set<Fragment> getDependants() { return dependants; } public boolean isValidStartingPoint() { return isValidStartingPoint; } public void setInvalidStartingPoint() { isValidStartingPoint = false; } public double getFixedFragmentCost() { return fixedFragmentCost; } public void setFixedFragmentCost(double fixedFragmentCost) { if (this.fixedFragmentCost < fixedFragmentCost) { this.fixedFragmentCost = fixedFragmentCost; } } public Double getNodeWeight() { return nodeWeight; } public void setNodeWeight(Double nodeWeight) { this.nodeWeight = nodeWeight; } public Double getBranchWeight() { return branchWeight; } public void setBranchWeight(Double branchWeight) { this.branchWeight = branchWeight; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Node that = (Node) o; return nodeId.equals(that.nodeId); } @Override public int hashCode() { return nodeId.hashCode(); } @Override public String toString() { return nodeId.toString(); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/spanningtree
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/spanningtree/graph/NodeId.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.gremlin.spanningtree.graph; import ai.grakn.graql.Var; import java.util.Collections; import java.util.Set; /** * The unique id of a node. * * @author Jason Liu */ public class NodeId { /** * The type of a node. * If the node contains a var from the query, its type is VAR. * If the node is an edge from the query, its type is the type of the fragment. **/ public enum NodeType { ISA, PLAYS, RELATES, SUB, VAR } private final NodeType nodeType; private final Set<Var> vars; public NodeId(NodeType nodeType, Set<Var> vars) { this.nodeType = nodeType; this.vars = vars; } public NodeId(NodeType nodeType, Var var) { this(nodeType, Collections.singleton(var)); } @Override public int hashCode() { int result = nodeType == null ? 0 : nodeType.hashCode(); result = 31 * result + (vars == null ? 0 : vars.hashCode()); return result; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NodeId that = (NodeId) o; return (nodeType != null ? nodeType.equals(that.nodeType) : that.nodeType == null) && (vars != null ? vars.equals(that.vars) : that.vars == null); } @Override public String toString() { return nodeType + vars.toString(); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/spanningtree
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/spanningtree/graph/SparseWeightedGraph.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.gremlin.spanningtree.graph; import ai.grakn.graql.internal.gremlin.spanningtree.util.Weighted; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import java.util.Collection; import java.util.Map; import java.util.Set; /** * @param <V> the type of the nodes stored * @author Jason Liu */ public class SparseWeightedGraph<V> extends WeightedGraph<V> { final private Set<V> nodes; final private Map<V, Map<V, Weighted<DirectedEdge<V>>>> incomingEdges; private SparseWeightedGraph(Set<V> nodes, Map<V, Map<V, Weighted<DirectedEdge<V>>>> incomingEdges) { this.nodes = nodes; this.incomingEdges = incomingEdges; } public static <T> SparseWeightedGraph<T> from(Iterable<T> nodes, Iterable<Weighted<DirectedEdge<T>>> edges) { final Map<T, Map<T, Weighted<DirectedEdge<T>>>> incomingEdges = Maps.newHashMap(); for (Weighted<DirectedEdge<T>> edge : edges) { if (!incomingEdges.containsKey(edge.val.destination)) { incomingEdges.put(edge.val.destination, Maps.newHashMap()); } incomingEdges.get(edge.val.destination).put(edge.val.source, edge); } return new SparseWeightedGraph<>(ImmutableSet.copyOf(nodes), incomingEdges); } public static <T> SparseWeightedGraph<T> from(Iterable<Weighted<DirectedEdge<T>>> edges) { final Set<T> nodes = Sets.newHashSet(); for (Weighted<DirectedEdge<T>> edge : edges) { nodes.add(edge.val.source); nodes.add(edge.val.destination); } return SparseWeightedGraph.from(nodes, edges); } @Override public Collection<V> getNodes() { return nodes; } @Override public double getWeightOf(V source, V dest) { if (!incomingEdges.containsKey(dest)) return Double.NEGATIVE_INFINITY; final Map<V, Weighted<DirectedEdge<V>>> inEdges = incomingEdges.get(dest); if (!inEdges.containsKey(source)) return Double.NEGATIVE_INFINITY; return inEdges.get(source).weight; } @Override public Collection<Weighted<DirectedEdge<V>>> getIncomingEdges(V destinationNode) { if (!incomingEdges.containsKey(destinationNode)) return ImmutableSet.of(); return incomingEdges.get(destinationNode).values(); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/spanningtree
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/spanningtree/graph/WeightedGraph.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.gremlin.spanningtree.graph; import ai.grakn.graql.internal.gremlin.spanningtree.util.Weighted; import com.google.common.base.Predicate; import com.google.common.collect.Lists; import java.util.Collection; import java.util.List; /** * @param <V> the type of the nodes stored * @author Jason Liu */ public abstract class WeightedGraph<V> { public abstract Collection<V> getNodes(); public abstract double getWeightOf(V source, V dest); public abstract Collection<Weighted<DirectedEdge<V>>> getIncomingEdges(V destinationNode); public WeightedGraph<V> filterEdges(Predicate<DirectedEdge<V>> predicate) { final List<Weighted<DirectedEdge<V>>> allEdges = Lists.newArrayList(); for (V node : getNodes()) { final Collection<Weighted<DirectedEdge<V>>> incomingEdges = getIncomingEdges(node); for (Weighted<DirectedEdge<V>> edge : incomingEdges) { if (predicate.apply(edge.val)) { allEdges.add(edge); } } } return SparseWeightedGraph.from(getNodes(), allEdges); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/spanningtree
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/gremlin/spanningtree/util/Weighted.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.gremlin.spanningtree.util; import com.google.common.base.Objects; import com.google.common.collect.ComparisonChain; import static com.google.common.base.Preconditions.checkNotNull; /** * Add a weight to anything! * * @param <T> the type of object * @author Jason Liu */ public class Weighted<T> implements Comparable<Weighted<T>> { public final T val; public final double weight; public Weighted(T val, double weight) { checkNotNull(val); checkNotNull(weight); this.val = val; this.weight = weight; } /** * Convenience static constructor */ public static <T> Weighted<T> weighted(T value, double weight) { return new Weighted<>(value, weight); } /** * High weights first, use val.hashCode to break ties */ public int compareTo(Weighted<T> other) { return ComparisonChain.start() .compare(other.weight, weight) .compare(Objects.hashCode(other.val), Objects.hashCode(val)) .result(); } @Override public boolean equals(Object other) { if (!(other instanceof Weighted)) return false; final Weighted wOther = (Weighted) other; return Objects.equal(val, wOther.val) && Objects.equal(weight, wOther.weight); } @Override public int hashCode() { return Objects.hashCode(val, weight); } @Override public String toString() { return "Weighted{" + "val=" + val + ", weight=" + weight + '}'; } }
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/parser/AutoValue_ChannelTokenSource.java
package ai.grakn.graql.internal.parser; import javax.annotation.Generated; import org.antlr.v4.runtime.TokenSource; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_ChannelTokenSource extends ChannelTokenSource { private final TokenSource source; private final int channel; AutoValue_ChannelTokenSource( TokenSource source, int channel) { if (source == null) { throw new NullPointerException("Null source"); } this.source = source; this.channel = channel; } @Override TokenSource source() { return source; } @Override int channel() { return channel; } @Override public String toString() { return "ChannelTokenSource{" + "source=" + source + ", " + "channel=" + channel + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof ChannelTokenSource) { ChannelTokenSource that = (ChannelTokenSource) o; return (this.source.equals(that.source())) && (this.channel == that.channel()); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.source.hashCode(); h *= 1000003; h ^= this.channel; return h; } }
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/parser/AutoValue_SyntaxError.java
package ai.grakn.graql.internal.parser; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_SyntaxError extends SyntaxError { private final String queryLine; private final int line; private final int charPositionInLine; private final String msg; AutoValue_SyntaxError( @Nullable String queryLine, int line, int charPositionInLine, String msg) { this.queryLine = queryLine; this.line = line; this.charPositionInLine = charPositionInLine; if (msg == null) { throw new NullPointerException("Null msg"); } this.msg = msg; } @Nullable @Override String queryLine() { return queryLine; } @Override int line() { return line; } @Override int charPositionInLine() { return charPositionInLine; } @Override String msg() { return msg; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof SyntaxError) { SyntaxError that = (SyntaxError) o; return ((this.queryLine == null) ? (that.queryLine() == null) : this.queryLine.equals(that.queryLine())) && (this.line == that.line()) && (this.charPositionInLine == that.charPositionInLine()) && (this.msg.equals(that.msg())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= (queryLine == null) ? 0 : this.queryLine.hashCode(); h *= 1000003; h ^= this.line; h *= 1000003; h ^= this.charPositionInLine; h *= 1000003; h ^= this.msg.hashCode(); return h; } }
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/parser/ChannelTokenSource.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.parser; import com.google.auto.value.AutoValue; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.TokenFactory; import org.antlr.v4.runtime.TokenSource; import org.antlr.v4.runtime.UnbufferedTokenStream; /** * Implementation of {@link TokenSource} that wraps another {@link TokenSource}, only allowing tokens through if they * match the expected channel. * <p> * This class is necessary when using the {@link UnbufferedTokenStream} to parse extremely large files, because * that class does not filter out e.g. whitespace and comments. * </p> * * @author Felix Chapman */ @AutoValue public abstract class ChannelTokenSource implements TokenSource { abstract TokenSource source(); abstract int channel(); public static ChannelTokenSource of(TokenSource source) { return of(source, Token.DEFAULT_CHANNEL); } public static ChannelTokenSource of(TokenSource source, int channel) { return new AutoValue_ChannelTokenSource(source, channel); } @Override public Token nextToken() { Token token; do { token = source().nextToken(); } while (token.getChannel() != channel()); return token; } @Override public int getLine() { return source().getLine(); } @Override public int getCharPositionInLine() { return source().getCharPositionInLine(); } @Override public CharStream getInputStream() { return source().getInputStream(); } @Override public String getSourceName() { return source().getSourceName(); } @Override public void setTokenFactory(TokenFactory<?> factory) { source().setTokenFactory(factory); } @Override public TokenFactory<?> getTokenFactory() { return source().getTokenFactory(); } }
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/parser/GraqlConstructor.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.parser; import ai.grakn.concept.AttributeType; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Label; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Aggregate; 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.Graql; import ai.grakn.graql.InsertQuery; import ai.grakn.graql.Match; import ai.grakn.graql.Order; import ai.grakn.graql.Pattern; import ai.grakn.graql.Query; import ai.grakn.graql.QueryBuilder; import ai.grakn.graql.ValuePredicate; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.internal.antlr.GraqlBaseVisitor; import ai.grakn.graql.internal.antlr.GraqlParser; import ai.grakn.util.CommonUtil; import ai.grakn.util.GraqlSyntax; import ai.grakn.util.StringUtil; import com.google.common.collect.ImmutableMap; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.tree.TerminalNode; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.function.UnaryOperator; import java.util.stream.Stream; import static ai.grakn.graql.Graql.and; import static ai.grakn.graql.Graql.eq; import static ai.grakn.graql.Graql.label; import static ai.grakn.util.GraqlSyntax.Compute.Algorithm; import static ai.grakn.util.GraqlSyntax.Compute.Argument; import static ai.grakn.util.GraqlSyntax.Compute.Method; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; /** * ANTLR visitor class for parsing a query * * @author Grakn Warriors */ // This class performs a lot of unchecked casts, because ANTLR's visit methods only return 'object' @SuppressWarnings("unchecked") class GraqlConstructor extends GraqlBaseVisitor { private final QueryBuilder queryBuilder; private final ImmutableMap<String, Function<List<Object>, Aggregate>> aggregateMethods; private final boolean defineAllVars; GraqlConstructor( ImmutableMap<String, Function<List<Object>, Aggregate>> aggregateMethods, QueryBuilder queryBuilder, boolean defineAllVars ) { this.aggregateMethods = aggregateMethods; this.queryBuilder = queryBuilder; this.defineAllVars = defineAllVars; } @Override public Stream<? extends Query<?>> visitQueryList(GraqlParser.QueryListContext ctx) { return ctx.query().stream().map(this::visitQuery); } @Override public Query<?> visitQueryEOF(GraqlParser.QueryEOFContext ctx) { return visitQuery(ctx.query()); } @Override public Query<?> visitQuery(GraqlParser.QueryContext ctx) { return (Query<?>) super.visitQuery(ctx); } @Override public Match visitMatchBase(GraqlParser.MatchBaseContext ctx) { Collection<Pattern> patterns = visitPatterns(ctx.patterns()); return queryBuilder.match(patterns); } @Override public Match visitMatchOffset(GraqlParser.MatchOffsetContext ctx) { return visitMatchPart(ctx.matchPart()).offset(getInteger(ctx.INTEGER())); } @Override public Match visitMatchOrderBy(GraqlParser.MatchOrderByContext ctx) { Match match = visitMatchPart(ctx.matchPart()); // decide which ordering method to use Var var = getVariable(ctx.VARIABLE()); if (ctx.order() != null) { return match.orderBy(var, visitOrder(ctx.order())); } else { return match.orderBy(var); } } @Override public Match visitMatchLimit(GraqlParser.MatchLimitContext ctx) { return visitMatchPart(ctx.matchPart()).limit(getInteger(ctx.INTEGER())); } @Override public GetQuery visitGetQuery(GraqlParser.GetQueryContext ctx) { Match match = visitMatchPart(ctx.matchPart()); if (ctx.variables() != null) { Set<Var> vars = ctx.variables().VARIABLE().stream().map(this::getVariable).collect(toSet()); if (!vars.isEmpty()) return match.get(vars); } return match.get(); } @Override public InsertQuery visitInsertQuery(GraqlParser.InsertQueryContext ctx) { Collection<VarPattern> vars = visitVarPatterns(ctx.varPatterns()); if (ctx.matchPart() != null) { return visitMatchPart(ctx.matchPart()).insert(vars); } else { return queryBuilder.insert(vars); } } @Override public DefineQuery visitDefineQuery(GraqlParser.DefineQueryContext ctx) { Collection<VarPattern> vars = visitVarPatterns(ctx.varPatterns()); return queryBuilder.define(vars); } @Override public Object visitUndefineQuery(GraqlParser.UndefineQueryContext ctx) { Collection<VarPattern> vars = visitVarPatterns(ctx.varPatterns()); return queryBuilder.undefine(vars); } @Override public DeleteQuery visitDeleteQuery(GraqlParser.DeleteQueryContext ctx) { Match match = visitMatchPart(ctx.matchPart()); if (ctx.variables() != null) return match.delete(visitVariables(ctx.variables())); else return match.delete(); } @Override public Set<Var> visitVariables(GraqlParser.VariablesContext ctx) { return ctx.VARIABLE().stream().map(this::getVariable).collect(toSet()); } @Override public AggregateQuery<?> visitAggregateQuery(GraqlParser.AggregateQueryContext ctx) { Aggregate aggregate = visitAggregate(ctx.aggregate()); return visitMatchPart(ctx.matchPart()).aggregate(aggregate); } @Override public Aggregate<?> visitCustomAgg(GraqlParser.CustomAggContext ctx) { String name = visitIdentifier(ctx.identifier()); Function<List<Object>, Aggregate> aggregateMethod = aggregateMethods.get(name); if (aggregateMethod == null) { throw GraqlQueryException.unknownAggregate(name); } List<Object> arguments = ctx.argument().stream().map(this::visit).collect(toList()); return aggregateMethod.apply(arguments); } @Override public Var visitVariableArgument(GraqlParser.VariableArgumentContext ctx) { return getVariable(ctx.VARIABLE()); } @Override public Aggregate<?> visitAggregateArgument(GraqlParser.AggregateArgumentContext ctx) { return visitAggregate(ctx.aggregate()); } @Override public List<Pattern> visitPatterns(GraqlParser.PatternsContext ctx) { return ctx.pattern().stream() .map(this::visitPattern) .collect(toList()); } @Override public Pattern visitOrPattern(GraqlParser.OrPatternContext ctx) { return Graql.or(ctx.pattern().stream().map(this::visitPattern).collect(toList())); } @Override public List<VarPattern> visitVarPatterns(GraqlParser.VarPatternsContext ctx) { return ctx.varPattern().stream().map(this::visitVarPattern).collect(toList()); } @Override public Pattern visitAndPattern(GraqlParser.AndPatternContext ctx) { return and(visitPatterns(ctx.patterns())); } @Override public VarPattern visitVarPattern(GraqlParser.VarPatternContext ctx) { VarPattern var; if (ctx.VARIABLE() != null) { var = getVariable(ctx.VARIABLE()); } else { var = visitVariable(ctx.variable()); } return getVarProperties(ctx.property()).apply(var); } @Override public UnaryOperator<VarPattern> visitPropId(GraqlParser.PropIdContext ctx) { return var -> var.id(visitId(ctx.id())); } @Override public UnaryOperator<VarPattern> visitPropLabel(GraqlParser.PropLabelContext ctx) { return var -> var.label(visitLabel(ctx.label())); } @Override public UnaryOperator<VarPattern> visitPropValue(GraqlParser.PropValueContext ctx) { return var -> var.val(visitPredicate(ctx.predicate())); } @Override public UnaryOperator<VarPattern> visitPropWhen(GraqlParser.PropWhenContext ctx) { return var -> var.when(and(visitPatterns(ctx.patterns()))); } @Override public UnaryOperator<VarPattern> visitPropThen(GraqlParser.PropThenContext ctx) { return var -> var.then(and(visitVarPatterns(ctx.varPatterns()))); } @Override public UnaryOperator<VarPattern> visitPropHas(GraqlParser.PropHasContext ctx) { Label type = visitLabel(ctx.label()); VarPattern relation = Optional.ofNullable(ctx.relation).map(this::getVariable).orElseGet(Graql::var); VarPattern resource = Optional.ofNullable(ctx.resource).map(this::getVariable).orElseGet(Graql::var); if (ctx.predicate() != null) { resource = resource.val(visitPredicate(ctx.predicate())); } VarPattern finalResource = resource; return var -> var.has(type, finalResource, relation); } @Override public UnaryOperator<VarPattern> visitPropResource(GraqlParser.PropResourceContext ctx) { return var -> var.has(visitVariable(ctx.variable())); } @Override public UnaryOperator<VarPattern> visitPropKey(GraqlParser.PropKeyContext ctx) { return var -> var.key(visitVariable(ctx.variable())); } @Override public UnaryOperator<VarPattern> visitIsAbstract(GraqlParser.IsAbstractContext ctx) { return VarPattern::isAbstract; } @Override public UnaryOperator<VarPattern> visitPropDatatype(GraqlParser.PropDatatypeContext ctx) { return var -> var.datatype(visitDatatype(ctx.datatype())); } @Override public UnaryOperator<VarPattern> visitPropRegex(GraqlParser.PropRegexContext ctx) { return var -> var.regex(getRegex(ctx.REGEX())); } @Override public UnaryOperator<VarPattern> visitPropRel(GraqlParser.PropRelContext ctx) { return getVarProperties(ctx.casting()); } @Override public UnaryOperator<VarPattern> visitPropNeq(GraqlParser.PropNeqContext ctx) { return var -> var.neq(visitVariable(ctx.variable())); } @Override public UnaryOperator<VarPattern> visitCasting(GraqlParser.CastingContext ctx) { if (ctx.VARIABLE() == null) { return var -> var.rel(visitVariable(ctx.variable())); } else { return var -> var.rel(visitVariable(ctx.variable()), getVariable(ctx.VARIABLE())); } } @Override public UnaryOperator<VarPattern> visitIsa(GraqlParser.IsaContext ctx) { return var -> var.isa(visitVariable(ctx.variable())); } @Override public UnaryOperator<VarPattern> visitIsaExplicit(GraqlParser.IsaExplicitContext ctx) { return var -> var.isaExplicit(visitVariable(ctx.variable())); } @Override public UnaryOperator<VarPattern> visitSub(GraqlParser.SubContext ctx) { return var -> var.sub(visitVariable(ctx.variable())); } @Override public UnaryOperator<VarPattern> visitRelates(GraqlParser.RelatesContext ctx) { VarPattern superRole = ctx.superRole != null ? visitVariable(ctx.superRole) : null; return var -> var.relates(visitVariable(ctx.role), superRole); } @Override public UnaryOperator<VarPattern> visitPlays(GraqlParser.PlaysContext ctx) { return var -> var.plays(visitVariable(ctx.variable())); } @Override public Label visitLabel(GraqlParser.LabelContext ctx) { GraqlParser.IdentifierContext label = ctx.identifier(); if (label == null) { return Label.of(ctx.IMPLICIT_IDENTIFIER().getText()); } return Label.of(visitIdentifier(label)); } @Override public Set<Label> visitLabels(GraqlParser.LabelsContext labels) { List<GraqlParser.LabelContext> labelsList = new ArrayList<>(); if (labels.label() != null) { labelsList.add(labels.label()); } else if (labels.labelsArray() != null) { labelsList.addAll(labels.labelsArray().label()); } return labelsList.stream().map(this::visitLabel).collect(toSet()); } @Override public ConceptId visitId(GraqlParser.IdContext ctx) { return ConceptId.of(visitIdentifier(ctx.identifier())); } @Override public String visitIdentifier(GraqlParser.IdentifierContext ctx) { if (ctx.STRING() != null) { return getString(ctx.STRING()); } else { return ctx.getText(); } } @Override public VarPattern visitVariable(GraqlParser.VariableContext ctx) { if (ctx == null) { return var(); } else if (ctx.label() != null) { return label(visitLabel(ctx.label())); } else { return getVariable(ctx.VARIABLE()); } } @Override public ValuePredicate visitPredicateEq(GraqlParser.PredicateEqContext ctx) { return eq(visitValue(ctx.value())); } @Override public ValuePredicate visitPredicateVariable(GraqlParser.PredicateVariableContext ctx) { return eq(getVariable(ctx.VARIABLE())); } @Override public ValuePredicate visitPredicateNeq(GraqlParser.PredicateNeqContext ctx) { return applyPredicate(Graql::neq, Graql::neq, visitValueOrVar(ctx.valueOrVar())); } @Override public ValuePredicate visitPredicateGt(GraqlParser.PredicateGtContext ctx) { return applyPredicate((Function<Comparable<?>, ValuePredicate>) Graql::gt, Graql::gt, visitValueOrVar(ctx.valueOrVar())); } @Override public ValuePredicate visitPredicateGte(GraqlParser.PredicateGteContext ctx) { return applyPredicate((Function<Comparable<?>, ValuePredicate>) Graql::gte, Graql::gte, visitValueOrVar(ctx.valueOrVar())); } @Override public ValuePredicate visitPredicateLt(GraqlParser.PredicateLtContext ctx) { return applyPredicate((Function<Comparable<?>, ValuePredicate>) Graql::lt, Graql::lt, visitValueOrVar(ctx.valueOrVar())); } @Override public ValuePredicate visitPredicateLte(GraqlParser.PredicateLteContext ctx) { return applyPredicate((Function<Comparable<?>, ValuePredicate>) Graql::lte, Graql::lte, visitValueOrVar(ctx.valueOrVar())); } @Override public ValuePredicate visitPredicateContains(GraqlParser.PredicateContainsContext ctx) { Object stringOrVar = ctx.STRING() != null ? getString(ctx.STRING()) : getVariable(ctx.VARIABLE()); return applyPredicate((Function<String, ValuePredicate>) Graql::contains, Graql::contains, stringOrVar); } @Override public ValuePredicate visitPredicateRegex(GraqlParser.PredicateRegexContext ctx) { return Graql.regex(getRegex(ctx.REGEX())); } @Override public Order visitOrder(GraqlParser.OrderContext ctx) { if (ctx.ASC() != null) { return Order.asc; } else { assert ctx.DESC() != null; return Order.desc; } } @Override public VarPattern visitValueVariable(GraqlParser.ValueVariableContext ctx) { return getVariable(ctx.VARIABLE()); } @Override public String visitValueString(GraqlParser.ValueStringContext ctx) { return getString(ctx.STRING()); } @Override public Long visitValueInteger(GraqlParser.ValueIntegerContext ctx) { return getInteger(ctx.INTEGER()); } @Override public Double visitValueReal(GraqlParser.ValueRealContext ctx) { return Double.valueOf(ctx.REAL().getText()); } @Override public Boolean visitValueBoolean(GraqlParser.ValueBooleanContext ctx) { return visitBool(ctx.bool()); } @Override public LocalDateTime visitValueDate(GraqlParser.ValueDateContext ctx) { return LocalDate.parse(ctx.DATE().getText(), DateTimeFormatter.ISO_LOCAL_DATE).atStartOfDay(); } @Override public LocalDateTime visitValueDateTime(GraqlParser.ValueDateTimeContext ctx) { return LocalDateTime.parse(ctx.DATETIME().getText(), DateTimeFormatter.ISO_LOCAL_DATE_TIME); } @Override public Boolean visitBool(GraqlParser.BoolContext ctx) { return ctx.TRUE() != null; } @Override public AttributeType.DataType<?> visitDatatype(GraqlParser.DatatypeContext datatype) { if (datatype.BOOLEAN_TYPE() != null) { return AttributeType.DataType.BOOLEAN; } else if (datatype.DATE_TYPE() != null) { return AttributeType.DataType.DATE; } else if (datatype.DOUBLE_TYPE() != null) { return AttributeType.DataType.DOUBLE; } else if (datatype.LONG_TYPE() != null) { return AttributeType.DataType.LONG; } else if (datatype.STRING_TYPE() != null) { return AttributeType.DataType.STRING; } else { throw CommonUtil.unreachableStatement("Unrecognised " + datatype); } } private Match visitMatchPart(GraqlParser.MatchPartContext ctx) { return (Match) visit(ctx); } private Aggregate<?> visitAggregate(GraqlParser.AggregateContext ctx) { return (Aggregate) visit(ctx); } public Pattern visitPattern(GraqlParser.PatternContext ctx) { return (Pattern) visit(ctx); } private ValuePredicate visitPredicate(GraqlParser.PredicateContext ctx) { return (ValuePredicate) visit(ctx); } private Object visitValueOrVar(GraqlParser.ValueOrVarContext ctx) { return visit(ctx); } private Object visitValue(GraqlParser.ValueContext ctx) { return visit(ctx); } private Var getVariable(TerminalNode variable) { return getVariable(variable.getSymbol()); } private Var getVariable(Token variable) { // Remove '$' prefix return Graql.var(variable.getText().substring(1)); } private String getRegex(TerminalNode string) { // Remove surrounding /.../ String unquoted = unquoteString(string); return unquoted.replaceAll("\\\\/", "/"); } private String getString(TerminalNode string) { // Remove surrounding quotes String unquoted = unquoteString(string); return StringUtil.unescapeString(unquoted); } private String unquoteString(TerminalNode string) { return string.getText().substring(1, string.getText().length() - 1); } /** * Compose two functions together into a single function */ private <T> UnaryOperator<T> compose(UnaryOperator<T> before, UnaryOperator<T> after) { return x -> after.apply(before.apply(x)); } /** * Chain a stream of functions into a single function, which applies each one after the other */ private <T> UnaryOperator<T> chainOperators(Stream<UnaryOperator<T>> operators) { return operators.reduce(UnaryOperator.identity(), this::compose); } private UnaryOperator<VarPattern> getVarProperties(List<? extends ParserRuleContext> contexts) { return chainOperators(contexts.stream().map(ctx -> (UnaryOperator<VarPattern>) visit(ctx))); } protected long getInteger(TerminalNode integer) { return Long.parseLong(integer.getText()); } private <T> ValuePredicate applyPredicate( Function<T, ValuePredicate> valPred, Function<VarPattern, ValuePredicate> varPred, Object obj ) { if (obj instanceof VarPattern) { return varPred.apply((VarPattern) obj); } else { return valPred.apply((T) obj); } } private Var var() { Var var = Graql.var(); if (defineAllVars) { return var.asUserDefined(); } else { return var; } } //================================================================================================================// // Building Graql Compute (Analytics) Queries // //================================================================================================================// /** * Visits the compute query node in the parsed syntax tree and builds the appropriate compute query * * @param context for compute query parsed syntax * @return A ComputeQuery object */ public ComputeQuery visitComputeQuery(GraqlParser.ComputeQueryContext context) { GraqlParser.ComputeMethodContext method = context.computeMethod(); GraqlParser.ComputeConditionsContext conditions = context.computeConditions(); ComputeQuery query = queryBuilder.compute(Method.of(method.getText())); if (conditions == null) return query; for (GraqlParser.ComputeConditionContext condition : conditions.computeCondition()) { switch (((ParserRuleContext) condition.getChild(1)).getRuleIndex()) { case GraqlParser.RULE_computeFromID: query = query.from(visitId(condition.computeFromID().id())); break; case GraqlParser.RULE_computeToID: query = query.to(visitId(condition.computeToID().id())); break; case GraqlParser.RULE_computeOfLabels: query.of(visitLabels(condition.computeOfLabels().labels())); break; case GraqlParser.RULE_computeInLabels: query.in(visitLabels(condition.computeInLabels().labels())); break; case GraqlParser.RULE_computeAlgorithm: query.using(Algorithm.of(condition.computeAlgorithm().getText())); break; case GraqlParser.RULE_computeArgs: query.where(visitComputeArgs(condition.computeArgs())); break; default: throw GraqlQueryException.invalidComputeQuery_invalidCondition(query.method()); } } Optional<GraqlQueryException> exception = query.getException(); if (exception.isPresent()) throw exception.get(); return query; } /** * Visits the computeArgs tree in the compute query 'where <computeArgs>' condition and get the list of arguments * * @param computeArgs * @return */ @Override public List<Argument> visitComputeArgs(GraqlParser.ComputeArgsContext computeArgs) { List<GraqlParser.ComputeArgContext> argContextList = new ArrayList<>(); List<GraqlSyntax.Compute.Argument> argList = new ArrayList<>(); if (computeArgs.computeArg() != null) { argContextList.add(computeArgs.computeArg()); } else if (computeArgs.computeArgsArray() != null) { argContextList.addAll(computeArgs.computeArgsArray().computeArg()); } for (GraqlParser.ComputeArgContext argContext : argContextList) { if (argContext instanceof GraqlParser.ComputeArgMinKContext) { argList.add(Argument.min_k(getInteger(((GraqlParser.ComputeArgMinKContext) argContext).INTEGER()))); } else if (argContext instanceof GraqlParser.ComputeArgKContext) { argList.add(Argument.k(getInteger(((GraqlParser.ComputeArgKContext) argContext).INTEGER()))); } else if (argContext instanceof GraqlParser.ComputeArgSizeContext) { argList.add(Argument.size(getInteger(((GraqlParser.ComputeArgSizeContext) argContext).INTEGER()))); } else if (argContext instanceof GraqlParser.ComputeArgContainsContext) { argList.add(Argument.contains(visitId(((GraqlParser.ComputeArgContainsContext) argContext).id()))); } } return argList; } }
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/parser/GraqlErrorListener.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.parser; import com.google.common.collect.Lists; import org.antlr.v4.runtime.BaseErrorListener; import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.Recognizer; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * ANTLR error listener that listens for syntax errors. * * When a syntax error occurs, it is recorded. Call {@link GraqlErrorListener#hasErrors()} to see if there were errors. * View the errors with {@link GraqlErrorListener#toString()}. * * @author Felix Chapman */ public class GraqlErrorListener extends BaseErrorListener { private final @Nullable List<String> query; private final List<SyntaxError> errors = new ArrayList<>(); private GraqlErrorListener(@Nullable List<String> query) { this.query = query; } /** * Create a {@link GraqlErrorListener} without a reference to a query string. * <p> * This will have limited error-reporting abilities, but is necessary when dealing with very large queries * that should not be held in memory all at once. * </p> */ public static GraqlErrorListener withoutQueryString() { return new GraqlErrorListener(null); } public static GraqlErrorListener of(String query) { List<String> queryList = Lists.newArrayList(query.split("\n")); return new GraqlErrorListener(queryList); } @Override public void syntaxError( Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { if (query == null) { errors.add(SyntaxError.of(line, msg)); } else { errors.add(SyntaxError.of(line, msg, query.get(line-1), charPositionInLine)); } } public boolean hasErrors() { return !errors.isEmpty(); } @Override public String toString() { return errors.stream().map(SyntaxError::toString).collect(Collectors.joining("\n")); } }
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/parser/GremlinVisitor.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.parser; import ai.grakn.graql.internal.antlr.GremlinBaseVisitor; import ai.grakn.graql.internal.antlr.GremlinLexer; import ai.grakn.graql.internal.antlr.GremlinParser; import com.google.common.base.Strings; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import java.io.IOException; import java.util.List; import java.util.function.Consumer; import java.util.stream.Stream; /** * Parser to make Gremlin queries pretty * * @author Felix Chapman */ public class GremlinVisitor extends GremlinBaseVisitor<Consumer<GremlinVisitor.PrettyStringBuilder>> { private static final Consumer<PrettyStringBuilder> COMMA = s -> s.append(", "); private static final Consumer<PrettyStringBuilder> COMMA_AND_NEWLINE = COMMA.andThen(PrettyStringBuilder::newline); public static void main(String[] args) throws IOException { System.out.println(prettify(new ANTLRInputStream(System.in))); } /** * Change the traversal to a string in a readable format */ public static String prettify(GraphTraversal<?, ?> traversal) { return prettify(new ANTLRInputStream(traversal.toString())); } private static String prettify(CharStream input) { GremlinLexer lexer = new GremlinLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); GremlinParser parser = new GremlinParser(tokens); GremlinVisitor visitor = new GremlinVisitor(); PrettyStringBuilder pretty = PrettyStringBuilder.create(); visitor.visit(parser.traversal()).accept(pretty); return pretty.build(); } @Override public Consumer<PrettyStringBuilder> visitTraversal(GremlinParser.TraversalContext ctx) { return visit(ctx.expr()); } @Override public Consumer<PrettyStringBuilder> visitList(GremlinParser.ListContext ctx) { // To save space, we only indent if the list has more than one item boolean indent = ctx.expr().size() > 1; return str -> { // Lists are indented like: // [ // item1, // item2 // ] str.append("["); if (indent) str.indent(); visitWithSeparator(str, ctx.expr(), COMMA_AND_NEWLINE); if (indent) str.unindent(); str.append("]"); }; } @Override public Consumer<PrettyStringBuilder> visitStep(GremlinParser.StepContext ctx) { return str -> { visit(ctx.call()).accept(str); // Some steps have a list of bound names after like: // Step(arg1, arg2)@[x, y, z] if (ctx.ids() != null) { str.append("@"); visit(ctx.ids()).accept(str); } }; } @Override public Consumer<PrettyStringBuilder> visitCall(GremlinParser.CallContext ctx) { return str -> { str.append(ctx.ID().toString()).append("("); visitWithSeparator(str, ctx.expr(), COMMA); str.append(")"); }; } @Override public Consumer<PrettyStringBuilder> visitIdExpr(GremlinParser.IdExprContext ctx) { return str -> { str.append(ctx.ID().toString()); }; } @Override public Consumer<PrettyStringBuilder> visitMethodExpr(GremlinParser.MethodExprContext ctx) { return str -> { str.append(ctx.ID().toString()).append("."); visit(ctx.call()).accept(str); }; } @Override public Consumer<PrettyStringBuilder> visitListExpr(GremlinParser.ListExprContext ctx) { return visit(ctx.list()); } @Override public Consumer<PrettyStringBuilder> visitStepExpr(GremlinParser.StepExprContext ctx) { return visit(ctx.step()); } @Override public Consumer<PrettyStringBuilder> visitNegExpr(GremlinParser.NegExprContext ctx) { return str -> { str.append("!"); visit(ctx.expr()).accept(str); }; } @Override public Consumer<PrettyStringBuilder> visitSquigglyExpr(GremlinParser.SquigglyExprContext ctx) { return str -> { str.append("~"); visit(ctx.expr()).accept(str); }; } @Override public Consumer<PrettyStringBuilder> visitMapExpr(GremlinParser.MapExprContext ctx) { return str -> { // Maps are indented like: // { // key1=value1, // key2=value2 // } str.append("{").indent(); visitWithSeparator(str, ctx.mapEntry(), COMMA_AND_NEWLINE); str.unindent().append("}"); }; } @Override public Consumer<PrettyStringBuilder> visitMapEntry(GremlinParser.MapEntryContext ctx) { return str -> { str.append(ctx.ID().toString()).append("="); visit(ctx.expr()).accept(str); }; } @Override public Consumer<PrettyStringBuilder> visitIds(GremlinParser.IdsContext ctx) { return str -> { str.append("["); visitWithSeparator(str, ctx.ID(), COMMA); str.append("]"); }; } @Override public Consumer<PrettyStringBuilder> visitTerminal(TerminalNode node) { return str -> { str.append(node.getText()); }; } private void visitWithSeparator( PrettyStringBuilder str, List<? extends ParseTree> trees, Consumer<PrettyStringBuilder> elem) { Stream<Consumer<PrettyStringBuilder>> exprs = trees.stream().map(this::visit); intersperse(exprs, elem).forEach(consumer -> consumer.accept(str)); } /** * Helper method that intersperses elements of a stream with an additional element: * <pre> * intersperse(Stream.of(1, 2, 3), 42) == Stream.of(1, 42, 2, 42, 3); * * intersperse(Stream.of(), 42) == Stream.of() * intersperse(Stream.of(1), 42) == Stream.of(1) * intersperse(Stream.of(1, 2), 42) == Stream.of(1, 42, 2) * </pre> */ private <T> Stream<T> intersperse(Stream<T> stream, T elem) { return stream.flatMap(i -> Stream.of(elem, i)).skip(1); } /** * Helper class wrapping a {@link StringBuilder}. * * <p> * Supports indenting and un-indenting whole blocks. After calling {@link #indent}, all future * {@link #append(String)} calls will be indented. * </p> */ static class PrettyStringBuilder { private final StringBuilder builder = new StringBuilder(); private int indent = 0; private boolean newline = false; private static final String INDENT_STR = " "; static PrettyStringBuilder create() { return new PrettyStringBuilder(); } PrettyStringBuilder append(String string) { if (newline) { builder.append("\n"); builder.append(Strings.repeat(INDENT_STR, indent)); newline = false; } builder.append(string); return this; } PrettyStringBuilder indent() { newline(); indent += 1; return this; } PrettyStringBuilder unindent() { newline(); indent -= 1; return this; } PrettyStringBuilder newline() { newline = true; return this; } String build() { return builder.toString(); } } }
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/parser/QueryParserImpl.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.parser; import ai.grakn.concept.AttributeType; import ai.grakn.exception.GraqlQueryException; import ai.grakn.exception.GraqlSyntaxException; import ai.grakn.graql.Aggregate; import ai.grakn.graql.Graql; import ai.grakn.graql.Pattern; import ai.grakn.graql.Query; import ai.grakn.graql.QueryBuilder; import ai.grakn.graql.QueryParser; import ai.grakn.graql.Var; import ai.grakn.graql.internal.antlr.GraqlLexer; import ai.grakn.graql.internal.antlr.GraqlParser; import ai.grakn.graql.internal.antlr.GraqlParser.PatternContext; import ai.grakn.graql.internal.antlr.GraqlParser.PatternsContext; import ai.grakn.graql.internal.antlr.GraqlParser.QueryContext; import ai.grakn.graql.internal.antlr.GraqlParser.QueryEOFContext; import ai.grakn.graql.internal.antlr.GraqlParser.QueryListContext; import ai.grakn.graql.internal.query.aggregate.Aggregates; import ai.grakn.graql.internal.template.TemplateParser; import com.google.common.collect.AbstractIterator; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableMap; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.BailErrorStrategy; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenFactory; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.UnbufferedCharStream; import org.antlr.v4.runtime.UnbufferedTokenStream; import org.antlr.v4.runtime.misc.ParseCancellationException; import org.antlr.v4.runtime.tree.ParseTree; import javax.annotation.Nullable; import java.io.Reader; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Stream; import java.util.stream.StreamSupport; /** * Default implementation of {@link QueryParser} * * @author Felix Chapman */ public class QueryParserImpl implements QueryParser { private final QueryBuilder queryBuilder; private final TemplateParser templateParser = TemplateParser.create(); private final Map<String, Function<List<Object>, Aggregate>> aggregateMethods = new HashMap<>(); private boolean defineAllVars = false; public static final ImmutableBiMap<String, AttributeType.DataType<?>> DATA_TYPES = ImmutableBiMap.of( "long", AttributeType.DataType.LONG, "double", AttributeType.DataType.DOUBLE, "string", AttributeType.DataType.STRING, "boolean", AttributeType.DataType.BOOLEAN, "date", AttributeType.DataType.DATE ); /** * Create a query parser with the specified graph * @param queryBuilder the QueryBuilderImpl to operate the query on */ private QueryParserImpl(QueryBuilder queryBuilder) { this.queryBuilder = queryBuilder; } /** * Create a query parser with the specified graph * @param queryBuilder the QueryBuilderImpl to operate the query on * @return a query parser that operates with the specified graph */ public static QueryParser create(QueryBuilder queryBuilder) { QueryParserImpl parser = new QueryParserImpl(queryBuilder); parser.registerDefaultAggregates(); return parser; } private void registerAggregate(String name, int numArgs, Function<List<Object>, Aggregate> aggregateMethod) { registerAggregate(name, numArgs, numArgs, aggregateMethod); } private void registerAggregate(String name, int minArgs, int maxArgs, Function<List<Object>, Aggregate> aggregateMethod) { aggregateMethods.put(name, args -> { if (args.size() < minArgs || args.size() > maxArgs) { throw GraqlQueryException.incorrectAggregateArgumentNumber(name, minArgs, maxArgs, args); } return aggregateMethod.apply(args); }); } @Override public void registerAggregate(String name, Function<List<Object>, Aggregate> aggregateMethod) { aggregateMethods.put(name, aggregateMethod); } @Override public void defineAllVars(boolean defineAllVars) { this.defineAllVars = defineAllVars; } @Override /** * @param queryString a string representing a query * @return * a query, the type will depend on the type of QUERY. */ @SuppressWarnings("unchecked") public <T extends Query<?>> T parseQuery(String queryString) { // We can't be sure the returned query type is correct - even at runtime(!) because Java erases generics. // // e.g. // >> AggregateQuery<Boolean> q = qp.parseQuery("match $x isa movie; aggregate count;"); // The above will work at compile time AND runtime - it will only fail when the query is executed: // >> Boolean bool = q.execute(); // java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Boolean return (T) QUERY_EOF.parse(queryString); } /** * @param reader a reader representing several queries * @return a list of queries */ @Override public <T extends Query<?>> Stream<T> parseReader(Reader reader) { UnbufferedCharStream charStream = new UnbufferedCharStream(reader); GraqlErrorListener errorListener = GraqlErrorListener.withoutQueryString(); GraqlLexer lexer = createLexer(charStream, errorListener); /* We tell the lexer to copy the text into each generated token. Normally when calling `Token#getText`, it will look into the underlying `TokenStream` and call `TokenStream#size` to check it is in-bounds. However, `UnbufferedTokenStream#size` is not supported (because then it would have to read the entire input). To avoid this issue, we set this flag which will copy over the text into each `Token`, s.t. that `Token#getText` will just look up the copied text field. */ lexer.setTokenFactory(new CommonTokenFactory(true)); // Use an unbuffered token stream so we can handle extremely large input strings UnbufferedTokenStream tokenStream = new UnbufferedTokenStream(ChannelTokenSource.of(lexer)); GraqlParser parser = createParser(tokenStream, errorListener); /* The "bail" error strategy prevents us reading all the way to the end of the input, e.g. ``` match $x isa person; insert $x has name "Bob"; match $x isa movie; get; ^ ``` In this example, when ANTLR reaches the indicated `match`, it considers two possibilities: 1. this is the end of the query 2. the user has made a mistake. Maybe they accidentally pasted the `match` here. Because of case 2, ANTLR will parse beyond the `match` in order to produce a more helpful error message. This causes memory issues for very large queries, so we use the simpler "bail" strategy that will immediately stop when it hits `match`. */ parser.setErrorHandler(new BailErrorStrategy()); // This is a lazy iterator that will only consume a single query at a time, without parsing any further. // This means it can pass arbitrarily long streams of queries in constant memory! Iterable<T> queryIterator = () -> new AbstractIterator<T>() { @Nullable @Override protected T computeNext() { int latestToken = tokenStream.LA(1); if (latestToken == Token.EOF) { endOfData(); return null; } else { // This will parse and consume a single query, even if it doesn't reach an EOF // When we next run it, it will start where it left off in the stream return (T) QUERY.parse(parser, errorListener); } } }; return StreamSupport.stream(queryIterator.spliterator(), false); } @Override public <T extends Query<?>> Stream<T> parseList(String queryString) { return (Stream<T>) QUERY_LIST.parse(queryString); } @Override public List<Pattern> parsePatterns(String patternsString) { return PATTERNS.parse(patternsString); } @Override public Pattern parsePattern(String patternString){ return PATTERN.parse(patternString); } @Override public <T extends Query<?>> Stream<T> parseTemplate(String template, Map<String, Object> data) { return parseList(templateParser.parseTemplate(template, data)); } private static GraqlLexer createLexer(CharStream input, GraqlErrorListener errorListener) { GraqlLexer lexer = new GraqlLexer(input); lexer.removeErrorListeners(); lexer.addErrorListener(errorListener); return lexer; } private static GraqlParser createParser(TokenStream tokens, GraqlErrorListener errorListener) { GraqlParser parser = new GraqlParser(tokens); parser.removeErrorListeners(); parser.addErrorListener(errorListener); return parser; } private GraqlConstructor getQueryVisitor() { ImmutableMap<String, Function<List<Object>, Aggregate>> immutableAggregates = ImmutableMap.copyOf(aggregateMethods); return new GraqlConstructor(immutableAggregates, queryBuilder, defineAllVars); } // Aggregate methods that include other aggregates, such as group are not necessarily safe at runtime. // This is unavoidable in the parser. // TODO: remove this manual registration of aggregate queries and design it into the grammar @SuppressWarnings("unchecked") private void registerDefaultAggregates() { registerAggregate("count", 0, Integer.MAX_VALUE, args -> Graql.count()); registerAggregate("sum", 1, args -> Aggregates.sum((Var) args.get(0))); registerAggregate("max", 1, args -> Aggregates.max((Var) args.get(0))); registerAggregate("min", 1, args -> Aggregates.min((Var) args.get(0))); registerAggregate("mean", 1, args -> Aggregates.mean((Var) args.get(0))); registerAggregate("median", 1, args -> Aggregates.median((Var) args.get(0))); registerAggregate("std", 1, args -> Aggregates.std((Var) args.get(0))); registerAggregate("group", 1, 2, args -> { if (args.size() < 2) { return Aggregates.group((Var) args.get(0)); } else { return Aggregates.group((Var) args.get(0), (Aggregate) args.get(1)); } }); } private final QueryPart<QueryListContext, Stream<? extends Query<?>>> QUERY_LIST = createQueryPart(parser -> parser.queryList(), (constructor, context) -> constructor.visitQueryList(context)); private final QueryPart<QueryEOFContext, Query<?>> QUERY_EOF = createQueryPart(parser -> parser.queryEOF(), (constructor, context) -> constructor.visitQueryEOF(context)); private final QueryPart<QueryContext, Query<?>> QUERY = createQueryPart(parser -> parser.query(), (constructor, context) -> constructor.visitQuery(context)); private final QueryPart<PatternsContext, List<Pattern>> PATTERNS = createQueryPart(parser -> parser.patterns(), (constructor, context) -> constructor.visitPatterns(context)); private final QueryPart<PatternContext, Pattern> PATTERN = createQueryPart(parser -> parser.pattern(), (constructor, context) -> constructor.visitPattern(context)); private <S extends ParseTree, T> QueryPart<S, T> createQueryPart( Function<GraqlParser, S> parseTree, BiFunction<GraqlConstructor, S, T> visit) { return new QueryPart<S, T>() { @Override S parseTree(GraqlParser parser) { return parseTree.apply(parser); } @Override T visit(GraqlConstructor visitor, S context) { return visit.apply(visitor, context); } }; } /** * Represents a part of a Graql query to parse, such as "pattern". */ private abstract class QueryPart<S extends ParseTree, T> { /** * Get a {@link ParseTree} from a {@link GraqlParser}. */ abstract S parseTree(GraqlParser parser) throws ParseCancellationException; /** * Parse the {@link ParseTree} into a Java object using a {@link GraqlConstructor}. */ abstract T visit(GraqlConstructor visitor, S context); /** * Parse the string into a Java object */ final T parse(String queryString) { ANTLRInputStream charStream = new ANTLRInputStream(queryString); GraqlErrorListener errorListener = GraqlErrorListener.of(queryString); GraqlLexer lexer = createLexer(charStream, errorListener); CommonTokenStream tokens = new CommonTokenStream(lexer); GraqlParser parser = createParser(tokens, errorListener); return parse(parser, errorListener); } /** * Parse the {@link GraqlParser} into a Java object, where errors are reported to the given * {@link GraqlErrorListener}. */ final T parse(GraqlParser parser, GraqlErrorListener errorListener) { S tree; try { tree = parseTree(parser); } catch (ParseCancellationException e) { // If we're using the BailErrorStrategy, we will throw here // This strategy is designed for parsing very large files and cannot provide useful error information throw GraqlSyntaxException.create("syntax error"); } if (errorListener.hasErrors()) { throw GraqlSyntaxException.create(errorListener.toString()); } return visit(getQueryVisitor(), tree); } } }
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/parser/SyntaxError.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.parser; import ai.grakn.util.ErrorMessage; import com.google.auto.value.AutoValue; import org.apache.commons.lang.StringUtils; import javax.annotation.Nullable; @AutoValue abstract class SyntaxError { abstract @Nullable String queryLine(); abstract int line(); abstract int charPositionInLine(); abstract String msg(); static SyntaxError of(int line, String msg) { return of(line, msg, null, 0); } static SyntaxError of(int line, String msg, @Nullable String queryLine, int charPositionInLine) { return new AutoValue_SyntaxError(queryLine, line, charPositionInLine, msg); } @Override public String toString() { if (queryLine() == null) { return ErrorMessage.SYNTAX_ERROR_NO_POINTER.getMessage(line(), msg()); } else { // Error message appearance: // // syntax error at line 1: // match $ // ^ // blah blah antlr blah String pointer = StringUtils.repeat(" ", charPositionInLine()) + "^"; return ErrorMessage.SYNTAX_ERROR.getMessage(line(), queryLine(), pointer, msg()); } } }
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/pattern/$AutoValue_VarImpl.java
package ai.grakn.graql.internal.pattern; import ai.grakn.graql.Var; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") abstract class $AutoValue_VarImpl extends VarImpl { private final String getValue; private final Var.Kind kind; $AutoValue_VarImpl( String getValue, Var.Kind kind) { if (getValue == null) { throw new NullPointerException("Null getValue"); } this.getValue = getValue; if (kind == null) { throw new NullPointerException("Null kind"); } this.kind = kind; } @Override public String getValue() { return getValue; } @Override public Var.Kind kind() { return kind; } }
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/pattern/AbstractPattern.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.pattern; import ai.grakn.graql.Graql; import ai.grakn.graql.Pattern; import ai.grakn.graql.admin.PatternAdmin; /** * The abstract implementation of {@link PatternAdmin}. * * All implementations of {@link PatternAdmin} should extend this class to inherit certain default behaviours. * * @author Felix Chapman */ public abstract class AbstractPattern implements PatternAdmin { @Override public final Pattern and(Pattern pattern) { return Graql.and(this, pattern); } @Override public final Pattern or(Pattern pattern) { return Graql.or(this, pattern); } }
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/pattern/AbstractVarPattern.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.pattern; import ai.grakn.concept.AttributeType; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Label; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Graql; import ai.grakn.graql.Pattern; import ai.grakn.graql.ValuePredicate; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.Conjunction; import ai.grakn.graql.admin.Disjunction; import ai.grakn.graql.admin.RelationPlayer; import ai.grakn.graql.admin.UniqueVarProperty; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.admin.VarProperty; import ai.grakn.graql.internal.pattern.property.DataTypeProperty; import ai.grakn.graql.internal.pattern.property.IsaExplicitProperty; import ai.grakn.graql.internal.pattern.property.HasAttributeProperty; import ai.grakn.graql.internal.pattern.property.HasAttributeTypeProperty; import ai.grakn.graql.internal.pattern.property.IdProperty; import ai.grakn.graql.internal.pattern.property.IsAbstractProperty; import ai.grakn.graql.internal.pattern.property.IsaProperty; import ai.grakn.graql.internal.pattern.property.LabelProperty; import ai.grakn.graql.internal.pattern.property.NeqProperty; import ai.grakn.graql.internal.pattern.property.PlaysProperty; import ai.grakn.graql.internal.pattern.property.RegexProperty; import ai.grakn.graql.internal.pattern.property.RelatesProperty; import ai.grakn.graql.internal.pattern.property.RelationshipProperty; 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.graql.internal.util.StringConverter; import ai.grakn.util.CommonUtil; import com.google.common.collect.ImmutableMultiset; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.Stack; import java.util.stream.Stream; import static java.util.stream.Collectors.toSet; /** * Abstract implementation of {@link VarPatternAdmin}. * * @author Felix Chapman */ public abstract class AbstractVarPattern extends AbstractPattern implements VarPatternAdmin { @Override public abstract Var var(); protected abstract Set<VarProperty> properties(); @Override public final VarPatternAdmin admin() { return this; } @Override public final Optional<Label> getTypeLabel() { return getProperty(LabelProperty.class).map(LabelProperty::label); } @Override public final <T extends VarProperty> Stream<T> getProperties(Class<T> type) { return getProperties().filter(type::isInstance).map(type::cast); } @Override public final <T extends UniqueVarProperty> Optional<T> getProperty(Class<T> type) { return getProperties().filter(type::isInstance).map(type::cast).findAny(); } @Override public final <T extends VarProperty> boolean hasProperty(Class<T> type) { return getProperties(type).findAny().isPresent(); } @Override public final Collection<VarPatternAdmin> innerVarPatterns() { Stack<VarPatternAdmin> newVars = new Stack<>(); List<VarPatternAdmin> vars = new ArrayList<>(); newVars.add(this); while (!newVars.isEmpty()) { VarPatternAdmin var = newVars.pop(); vars.add(var); var.getProperties().flatMap(VarProperty::innerVarPatterns).forEach(newVars::add); } return vars; } @Override public final Collection<VarPatternAdmin> implicitInnerVarPatterns() { Stack<VarPatternAdmin> newVars = new Stack<>(); List<VarPatternAdmin> vars = new ArrayList<>(); newVars.add(this); while (!newVars.isEmpty()) { VarPatternAdmin var = newVars.pop(); vars.add(var); var.getProperties().flatMap(VarProperty::implicitInnerVarPatterns).forEach(newVars::add); } return vars; } @Override public final Set<Label> getTypeLabels() { return getProperties() .flatMap(VarProperty::getTypes) .map(VarPatternAdmin::getTypeLabel).flatMap(CommonUtil::optionalToStream) .collect(toSet()); } @Override public final Disjunction<Conjunction<VarPatternAdmin>> getDisjunctiveNormalForm() { // a disjunction containing only one option Conjunction<VarPatternAdmin> conjunction = Patterns.conjunction(Collections.singleton(this)); return Patterns.disjunction(Collections.singleton(conjunction)); } @Override public final Set<Var> commonVars() { return innerVarPatterns().stream() .filter(v -> v.var().isUserDefinedName()) .map(VarPatternAdmin::var) .collect(toSet()); } @Override public final VarPattern id(ConceptId id) { return addProperty(IdProperty.of(id)); } @Override public final VarPattern label(String label) { return label(Label.of(label)); } @Override public final VarPattern label(Label label) { return addProperty(LabelProperty.of(label)); } @Override public final VarPattern val(Object value) { return val(Graql.eq(value)); } @Override public final VarPattern val(ValuePredicate predicate) { return addProperty(ValueProperty.of(predicate)); } @Override public final VarPattern has(String type, Object value) { return has(type, Graql.eq(value)); } @Override public final VarPattern has(String type, ValuePredicate predicate) { return has(type, Graql.var().val(predicate)); } @Override public final VarPattern has(String type, VarPattern attribute) { return has(Label.of(type), attribute); } @Override public final VarPattern has(Label type, VarPattern attribute) { return has(type, attribute, Graql.var()); } @Override public final VarPattern has(Label type, VarPattern attribute, VarPattern relationship) { return addProperty(HasAttributeProperty.of(type, attribute.admin(), relationship.admin())); } @Override public final VarPattern isaExplicit(String type) { return isaExplicit(Graql.label(type)); } @Override public final VarPattern isaExplicit(VarPattern type) { return addProperty(IsaExplicitProperty.of(type.admin())); } @Override public final VarPattern isa(String type) { return isa(Graql.label(type)); } @Override public final VarPattern isa(VarPattern type) { return addProperty(IsaProperty.of(type.admin())); } @Override public final VarPattern sub(String type) { return sub(Graql.label(type)); } @Override public final VarPattern sub(VarPattern type) { return addProperty(SubProperty.of(type.admin())); } @Override public final VarPattern relates(String type) { return relates(type, null); } @Override public final VarPattern relates(VarPattern type) { return relates(type, null); } @Override public VarPattern relates(String roleType, String superRoleType) { return relates(Graql.label(roleType), superRoleType == null ? null : Graql.label(superRoleType)); } @Override public VarPattern relates(VarPattern roleType, VarPattern superRoleType) { return addProperty(RelatesProperty.of(roleType.admin(), superRoleType == null ? null : superRoleType.admin())); } @Override public final VarPattern plays(String type) { return plays(Graql.label(type)); } @Override public final VarPattern plays(VarPattern type) { return addProperty(PlaysProperty.of(type.admin(), false)); } @Override public final VarPattern has(String type) { return has(Graql.label(type)); } @Override public final VarPattern has(VarPattern type) { return addProperty(HasAttributeTypeProperty.of(type.admin(), false)); } @Override public final VarPattern key(String type) { return key(Graql.var().label(type)); } @Override public final VarPattern key(VarPattern type) { return addProperty(HasAttributeTypeProperty.of(type.admin(), true)); } @Override public final VarPattern rel(String roleplayer) { return rel(Graql.var(roleplayer)); } @Override public final VarPattern rel(VarPattern roleplayer) { return addCasting(RelationPlayer.of(roleplayer.admin())); } @Override public final VarPattern rel(String role, String roleplayer) { return rel(Graql.label(role), Graql.var(roleplayer)); } @Override public final VarPattern rel(VarPattern role, String roleplayer) { return rel(role, Graql.var(roleplayer)); } @Override public final VarPattern rel(String role, VarPattern roleplayer) { return rel(Graql.label(role), roleplayer); } @Override public final VarPattern rel(VarPattern role, VarPattern roleplayer) { return addCasting(RelationPlayer.of(role.admin(), roleplayer.admin())); } @Override public final VarPattern isAbstract() { return addProperty(IsAbstractProperty.get()); } @Override public final VarPattern datatype(AttributeType.DataType<?> datatype) { return addProperty(DataTypeProperty.of(datatype)); } @Override public final VarPattern regex(String regex) { return addProperty(RegexProperty.of(regex)); } @Override public final VarPattern when(Pattern when) { return addProperty(WhenProperty.of(when)); } @Override public final VarPattern then(Pattern then) { return addProperty(ThenProperty.of(then)); } @Override public final VarPattern neq(String var) { return neq(Graql.var(var)); } @Override public final VarPattern neq(VarPattern varPattern) { return addProperty(NeqProperty.of(varPattern.admin())); } @Override public final String getPrintableName() { if (properties().size() == 0) { // If there are no properties, we display the variable name return var().toString(); } else if (properties().size() == 1) { // If there is only a label, we display that Optional<Label> label = getTypeLabel(); if (label.isPresent()) { return StringConverter.typeLabelToString(label.get()); } } // Otherwise, we print the entire pattern return "`" + toString() + "`"; } @Override public final Stream<VarProperty> getProperties() { return properties().stream(); } private VarPattern addCasting(RelationPlayer relationPlayer) { Optional<RelationshipProperty> relationProperty = getProperty(RelationshipProperty.class); ImmutableMultiset<RelationPlayer> oldCastings = relationProperty .map(RelationshipProperty::relationPlayers) .orElse(ImmutableMultiset.of()); ImmutableMultiset<RelationPlayer> relationPlayers = Stream.concat(oldCastings.stream(), Stream.of(relationPlayer)).collect(CommonUtil.toImmutableMultiset()); RelationshipProperty newProperty = RelationshipProperty.of(relationPlayers); return relationProperty.map(this::removeProperty).orElse(this).addProperty(newProperty); } private VarPatternAdmin addProperty(VarProperty property) { if (property.isUnique()) { testUniqueProperty((UniqueVarProperty) property); } return Patterns.varPattern(var(), Sets.union(properties(), ImmutableSet.of(property))); } private AbstractVarPattern removeProperty(VarProperty property) { return (AbstractVarPattern) Patterns.varPattern(var(), Sets.difference(properties(), ImmutableSet.of(property))); } /** * Fail if there is already an equal property of this type */ private void testUniqueProperty(UniqueVarProperty property) { getProperty(property.getClass()).filter(other -> !other.equals(property)).ifPresent(other -> { throw GraqlQueryException.conflictingProperties(this, property, other); }); } }
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/pattern/AutoValue_ConjunctionImpl.java
package ai.grakn.graql.internal.pattern; import ai.grakn.graql.admin.PatternAdmin; import java.util.Set; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_ConjunctionImpl<T extends PatternAdmin> extends ConjunctionImpl<T> { private final Set<T> patterns; AutoValue_ConjunctionImpl( Set<T> patterns) { if (patterns == null) { throw new NullPointerException("Null patterns"); } this.patterns = patterns; } @Override public Set<T> getPatterns() { return patterns; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof ConjunctionImpl) { ConjunctionImpl<?> that = (ConjunctionImpl<?>) o; return (this.patterns.equals(that.getPatterns())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.patterns.hashCode(); return h; } }
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/pattern/AutoValue_DisjunctionImpl.java
package ai.grakn.graql.internal.pattern; import ai.grakn.graql.admin.PatternAdmin; import java.util.Set; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_DisjunctionImpl<T extends PatternAdmin> extends DisjunctionImpl<T> { private final Set<T> patterns; AutoValue_DisjunctionImpl( Set<T> patterns) { if (patterns == null) { throw new NullPointerException("Null patterns"); } this.patterns = patterns; } @Override public Set<T> getPatterns() { return patterns; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof DisjunctionImpl) { DisjunctionImpl<?> that = (DisjunctionImpl<?>) o; return (this.patterns.equals(that.getPatterns())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.patterns.hashCode(); return h; } }
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/pattern/AutoValue_VarImpl.java
package ai.grakn.graql.internal.pattern; import ai.grakn.graql.Var; import java.lang.Override; import java.lang.String; import javax.annotation.Generated; @Generated("com.google.auto.value.extension.memoized.MemoizeExtension") final class AutoValue_VarImpl extends $AutoValue_VarImpl { private volatile String name; AutoValue_VarImpl(String getValue$, Var.Kind kind$) { super(getValue$, kind$); } @Override public String name() { if (name == null) { synchronized (this) { if (name == null) { name = super.name(); if (name == null) { throw new NullPointerException("name() cannot return null"); } } } } return name; } }
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/pattern/AutoValue_VarPatternImpl.java
package ai.grakn.graql.internal.pattern; import ai.grakn.graql.Var; import ai.grakn.graql.admin.VarProperty; import java.util.Set; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_VarPatternImpl extends VarPatternImpl { private final Var var; private final Set<VarProperty> properties; AutoValue_VarPatternImpl( Var var, Set<VarProperty> properties) { if (var == null) { throw new NullPointerException("Null var"); } this.var = var; if (properties == null) { throw new NullPointerException("Null properties"); } this.properties = properties; } @Override public Var var() { return var; } @Override protected Set<VarProperty> properties() { return properties; } }
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/pattern/ConjunctionImpl.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.pattern; import ai.grakn.GraknTx; import ai.grakn.graql.Var; import ai.grakn.graql.admin.Conjunction; import ai.grakn.graql.admin.Disjunction; import ai.grakn.graql.admin.PatternAdmin; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.internal.reasoner.query.ReasonerQueries; import ai.grakn.kb.internal.EmbeddedGraknTx; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import java.util.List; import java.util.Set; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; @AutoValue abstract class ConjunctionImpl<T extends PatternAdmin> extends AbstractPattern implements Conjunction<T> { @Override public abstract Set<T> getPatterns(); @Override public Disjunction<Conjunction<VarPatternAdmin>> getDisjunctiveNormalForm() { // Get all disjunctions in query List<Set<Conjunction<VarPatternAdmin>>> disjunctionsOfConjunctions = getPatterns().stream() .map(p -> p.getDisjunctiveNormalForm().getPatterns()) .collect(toList()); // Get the cartesian product. // in other words, this puts the 'ands' on the inside and the 'ors' on the outside // e.g. (A or B) and (C or D) <=> (A and C) or (A and D) or (B and C) or (B and D) Set<Conjunction<VarPatternAdmin>> dnf = Sets.cartesianProduct(disjunctionsOfConjunctions).stream() .map(ConjunctionImpl::fromConjunctions) .collect(toSet()); return Patterns.disjunction(dnf); // Wasn't that a horrible function? Here it is in Haskell: // dnf = map fromConjunctions . sequence . map getDisjunctiveNormalForm . patterns } @Override public Set<Var> commonVars() { return getPatterns().stream().map(PatternAdmin::commonVars).reduce(ImmutableSet.of(), Sets::union); } @Override public boolean isConjunction() { return true; } @Override public Conjunction<?> asConjunction() { return this; } @Override public ReasonerQuery toReasonerQuery(GraknTx tx){ Conjunction<VarPatternAdmin> pattern = Iterables.getOnlyElement(getDisjunctiveNormalForm().getPatterns()); // TODO: This cast is unsafe - this method should accept an `EmbeddedGraknTx` return ReasonerQueries.create(pattern, (EmbeddedGraknTx<?>) tx); } private static <U extends PatternAdmin> Conjunction<U> fromConjunctions(List<Conjunction<U>> conjunctions) { Set<U> patterns = conjunctions.stream().flatMap(p -> p.getPatterns().stream()).collect(toSet()); return Patterns.conjunction(patterns); } @Override public String toString() { return "{" + getPatterns().stream().map(s -> s + ";").collect(joining(" ")) + "}"; } @Override public PatternAdmin admin() { return this; } }
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/pattern/DisjunctionImpl.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.pattern; import ai.grakn.graql.Var; import ai.grakn.graql.admin.Conjunction; import ai.grakn.graql.admin.Disjunction; import ai.grakn.graql.admin.PatternAdmin; import ai.grakn.graql.admin.VarPatternAdmin; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import java.util.Set; import java.util.stream.Collectors; import static java.util.stream.Collectors.toSet; @AutoValue abstract class DisjunctionImpl<T extends PatternAdmin> extends AbstractPattern implements Disjunction<T> { @Override public abstract Set<T> getPatterns(); @Override public Disjunction<Conjunction<VarPatternAdmin>> getDisjunctiveNormalForm() { // Concatenate all disjunctions into one big disjunction Set<Conjunction<VarPatternAdmin>> dnf = getPatterns().stream() .flatMap(p -> p.getDisjunctiveNormalForm().getPatterns().stream()) .collect(toSet()); return Patterns.disjunction(dnf); } @Override public Set<Var> commonVars() { return getPatterns().stream().map(PatternAdmin::commonVars).reduce(Sets::intersection).orElse(ImmutableSet.of()); } @Override public boolean isDisjunction() { return true; } @Override public Disjunction<?> asDisjunction() { return this; } @Override public String toString() { return getPatterns().stream().map(Object::toString).collect(Collectors.joining(" or ")); } @Override public PatternAdmin admin() { return this; } }
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/pattern/Patterns.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.pattern; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.Conjunction; import ai.grakn.graql.admin.Disjunction; import ai.grakn.graql.admin.PatternAdmin; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.admin.VarProperty; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; /** * Factory for instances of {@link ai.grakn.graql.Pattern}. * * Also includes helper methods to operate on a {@link ai.grakn.graql.Pattern} or {@link VarPattern}. * * @author Felix Chapman */ public class Patterns { private static final AtomicLong counter = new AtomicLong(System.currentTimeMillis() * 1000); public static final Var RELATION_EDGE = reservedVar("RELATION_EDGE"); public static final Var RELATION_DIRECTION = reservedVar("RELATION_DIRECTION"); private Patterns() {} public static <T extends PatternAdmin> Conjunction<T> conjunction(Set<T> patterns) { return new AutoValue_ConjunctionImpl<>(patterns); } public static <T extends PatternAdmin> Disjunction<T> disjunction(Set<T> patterns) { return new AutoValue_DisjunctionImpl<>(patterns); } public static Var var() { return VarImpl.of(Long.toString(counter.getAndIncrement()), Var.Kind.Generated); } public static Var var(String value) { return VarImpl.of(value, Var.Kind.UserDefined); } public static VarPatternAdmin varPattern(Var name, Set<VarProperty> properties) { if (properties.isEmpty()) { return name.admin(); } else { return new AutoValue_VarPatternImpl(name, properties); } } private static Var reservedVar(String value) { return VarImpl.of(value, Var.Kind.Reserved); } }
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/pattern/VarImpl.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.pattern; import ai.grakn.graql.Var; import ai.grakn.graql.admin.VarProperty; import com.google.auto.value.AutoValue; import com.google.auto.value.extension.memoized.Memoized; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import org.apache.commons.lang.StringUtils; import java.util.Set; import java.util.regex.Pattern; /** * Default implementation of {@link Var}. * * @author Felix Chapman */ @AutoValue abstract class VarImpl extends AbstractVarPattern implements Var { private static final Pattern VALID_VAR = Pattern.compile("[a-zA-Z0-9_-]+"); static VarImpl of(String value, Kind kind) { Preconditions.checkArgument( VALID_VAR.matcher(value).matches(), "Var value [%s] is invalid. Must match regex %s", value, VALID_VAR ); return new AutoValue_VarImpl(value, kind); } @Override public boolean isUserDefinedName() { return kind() == Kind.UserDefined; } @Override public Var asUserDefined() { if (isUserDefinedName()) { return this; } else { return VarImpl.of(getValue(), Kind.UserDefined); } } @Memoized @Override public String name() { return kind().prefix() + getValue(); } @Override public String shortName() { return kind().prefix() + StringUtils.right(getValue(), 3); } @Override public Var var() { return this; } @Override protected Set<VarProperty> properties() { return ImmutableSet.of(); } @Override public String toString() { return "$" + getValue(); } @Override public final boolean equals(Object o) { // This equals implementation is special: it ignores whether a variable is user-defined if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; VarImpl varName = (VarImpl) o; return getValue().equals(varName.getValue()); } @Override public final int hashCode() { // This hashCode implementation is special: it ignores whether a variable is user-defined return getValue().hashCode(); } }
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/pattern/VarPatternImpl.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.pattern; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.admin.VarProperty; import ai.grakn.graql.internal.pattern.property.HasAttributeProperty; import ai.grakn.graql.internal.pattern.property.LabelProperty; import com.google.auto.value.AutoValue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.Set; /** * Implementation of {@link VarPattern} interface */ @AutoValue abstract class VarPatternImpl extends AbstractVarPattern { protected final Logger LOG = LoggerFactory.getLogger(VarPatternImpl.class); private int hashCode = 0; @Override public abstract Var var(); @Override protected abstract Set<VarProperty> properties(); @Override public final boolean equals(Object o) { // This equals implementation is special: it considers all non-user-defined vars as equivalent if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AbstractVarPattern var = (AbstractVarPattern) o; if (var().isUserDefinedName() != var.var().isUserDefinedName()) return false; // "simplifying" this makes it harder to read //noinspection SimplifiableIfStatement if (!properties().equals(var.properties())) return false; return !var().isUserDefinedName() || var().equals(var.var()); } @Override public final int hashCode() { if (hashCode == 0) { // This hashCode implementation is special: it considers all non-user-defined vars as equivalent hashCode = properties().hashCode(); if (var().isUserDefinedName()) hashCode = 31 * hashCode + var().hashCode(); hashCode = 31 * hashCode + (var().isUserDefinedName() ? 1 : 0); } return hashCode; } @Override public final String toString() { Collection<VarPatternAdmin> innerVars = innerVarPatterns(); innerVars.remove(this); getProperties(HasAttributeProperty.class) .map(HasAttributeProperty::attribute) .flatMap(r -> r.innerVarPatterns().stream()) .forEach(innerVars::remove); if (innerVars.stream().anyMatch(VarPatternImpl::invalidInnerVariable)) { LOG.warn("printing a query with inner variables, which is not supported in native Graql"); } StringBuilder builder = new StringBuilder(); String name = var().isUserDefinedName() ? var().toString() : ""; builder.append(name); if (var().isUserDefinedName() && !properties().isEmpty()) { // Add a space after the var name builder.append(" "); } boolean first = true; for (VarProperty property : properties()) { if (!first) { builder.append(" "); } first = false; property.buildString(builder); } return builder.toString(); } private static boolean invalidInnerVariable(VarPatternAdmin var) { return var.getProperties().anyMatch(p -> !(p instanceof LabelProperty)); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/AbstractIsaProperty.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.pattern.property; import ai.grakn.GraknTx; import ai.grakn.concept.ConceptId; import ai.grakn.concept.SchemaConcept; import ai.grakn.concept.Type; 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.UniqueVarProperty; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.internal.reasoner.atom.binary.IsaAtom; import ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate; import com.google.common.collect.ImmutableSet; import javax.annotation.Nullable; import java.util.Collection; import java.util.Set; import java.util.stream.Stream; import static ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.getIdPredicate; /** * @author Jason Liu */ abstract class AbstractIsaProperty extends AbstractVarProperty implements UniqueVarProperty, NamedProperty { public abstract VarPatternAdmin type(); @Override public final String getProperty() { return type().getPrintableName(); } @Override public final Stream<VarPatternAdmin> getTypes() { return Stream.of(type()); } @Override public final Stream<VarPatternAdmin> innerVarPatterns() { return Stream.of(type()); } @Override public final Collection<PropertyExecutor> insert(Var var) throws GraqlQueryException { PropertyExecutor.Method method = executor -> { Type type = executor.get(this.type().var()).asType(); executor.builder(var).isa(type); }; return ImmutableSet.of(PropertyExecutor.builder(method).requires(type().var()).produces(var).build()); } @Override public final void checkValidProperty(GraknTx graph, VarPatternAdmin var) throws GraqlQueryException { type().getTypeLabel().ifPresent(typeLabel -> { SchemaConcept theSchemaConcept = graph.getSchemaConcept(typeLabel); if (theSchemaConcept != null && !theSchemaConcept.isType()) { throw GraqlQueryException.cannotGetInstancesOfNonType(typeLabel); } }); } @Nullable @Override public final Atomic mapToAtom(VarPatternAdmin var, Set<VarPatternAdmin> vars, ReasonerQuery parent) { //IsaProperty is unique within a var, so skip if this is a relation if (var.hasProperty(RelationshipProperty.class)) return null; Var varName = var.var().asUserDefined(); VarPatternAdmin typePattern = this.type(); Var typeVariable = typePattern.var(); IdPredicate predicate = getIdPredicate(typeVariable, typePattern, vars, parent); ConceptId predicateId = predicate != null ? predicate.getPredicate() : null; //isa part VarPatternAdmin isaVar = varPatternForAtom(varName, typeVariable).admin(); return IsaAtom.create(varName, typeVariable, isaVar, predicateId, parent); } protected abstract VarPattern varPatternForAtom(Var varName, Var typeVariable); }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/AbstractVarProperty.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.pattern.property; import ai.grakn.GraknTx; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Var; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.util.CommonUtil; import java.util.Collection; import java.util.stream.Stream; abstract class AbstractVarProperty implements VarPropertyInternal { @Override public final void checkValid(GraknTx graph, VarPatternAdmin var) throws GraqlQueryException { checkValidProperty(graph, var); innerVarPatterns().map(VarPatternAdmin::getTypeLabel).flatMap(CommonUtil::optionalToStream).forEach(label -> { if (graph.getSchemaConcept(label) == null) { throw GraqlQueryException.labelNotFound(label); } }); } void checkValidProperty(GraknTx graph, VarPatternAdmin var) { } abstract String getName(); @Override public Collection<PropertyExecutor> insert(Var var) throws GraqlQueryException { throw GraqlQueryException.insertUnsupportedProperty(getName()); } @Override public Collection<PropertyExecutor> define(Var var) throws GraqlQueryException { throw GraqlQueryException.defineUnsupportedProperty(getName()); } @Override public Collection<PropertyExecutor> undefine(Var var) throws GraqlQueryException { throw GraqlQueryException.defineUnsupportedProperty(getName()); } @Override public Stream<VarPatternAdmin> getTypes() { return Stream.empty(); } @Override public Stream<VarPatternAdmin> implicitInnerVarPatterns() { return innerVarPatterns(); } @Override public final String toString() { return graqlString(); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/AutoValue_DataTypeProperty.java
package ai.grakn.graql.internal.pattern.property; import ai.grakn.concept.AttributeType; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_DataTypeProperty extends DataTypeProperty { private final AttributeType.DataType<?> dataType; AutoValue_DataTypeProperty( AttributeType.DataType<?> dataType) { if (dataType == null) { throw new NullPointerException("Null dataType"); } this.dataType = dataType; } @Override public AttributeType.DataType<?> dataType() { return dataType; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof DataTypeProperty) { DataTypeProperty that = (DataTypeProperty) o; return (this.dataType.equals(that.dataType())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.dataType.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/AutoValue_HasAttributeProperty.java
package ai.grakn.graql.internal.pattern.property; import ai.grakn.concept.Label; import ai.grakn.graql.admin.VarPatternAdmin; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_HasAttributeProperty extends HasAttributeProperty { private final Label type; private final VarPatternAdmin attribute; private final VarPatternAdmin relationship; AutoValue_HasAttributeProperty( Label type, VarPatternAdmin attribute, VarPatternAdmin relationship) { if (type == null) { throw new NullPointerException("Null type"); } this.type = type; if (attribute == null) { throw new NullPointerException("Null attribute"); } this.attribute = attribute; if (relationship == null) { throw new NullPointerException("Null relationship"); } this.relationship = relationship; } @Override public Label type() { return type; } @Override public VarPatternAdmin attribute() { return attribute; } @Override public VarPatternAdmin relationship() { return relationship; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/AutoValue_HasAttributeTypeProperty.java
package ai.grakn.graql.internal.pattern.property; import ai.grakn.graql.admin.VarPatternAdmin; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_HasAttributeTypeProperty extends HasAttributeTypeProperty { private final VarPatternAdmin resourceType; private final VarPatternAdmin ownerRole; private final VarPatternAdmin valueRole; private final VarPatternAdmin relationOwner; private final VarPatternAdmin relationValue; private final boolean required; AutoValue_HasAttributeTypeProperty( VarPatternAdmin resourceType, VarPatternAdmin ownerRole, VarPatternAdmin valueRole, VarPatternAdmin relationOwner, VarPatternAdmin relationValue, boolean required) { if (resourceType == null) { throw new NullPointerException("Null resourceType"); } this.resourceType = resourceType; if (ownerRole == null) { throw new NullPointerException("Null ownerRole"); } this.ownerRole = ownerRole; if (valueRole == null) { throw new NullPointerException("Null valueRole"); } this.valueRole = valueRole; if (relationOwner == null) { throw new NullPointerException("Null relationOwner"); } this.relationOwner = relationOwner; if (relationValue == null) { throw new NullPointerException("Null relationValue"); } this.relationValue = relationValue; this.required = required; } @Override VarPatternAdmin resourceType() { return resourceType; } @Override VarPatternAdmin ownerRole() { return ownerRole; } @Override VarPatternAdmin valueRole() { return valueRole; } @Override VarPatternAdmin relationOwner() { return relationOwner; } @Override VarPatternAdmin relationValue() { return relationValue; } @Override boolean required() { return required; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof HasAttributeTypeProperty) { HasAttributeTypeProperty that = (HasAttributeTypeProperty) o; return (this.resourceType.equals(that.resourceType())) && (this.ownerRole.equals(that.ownerRole())) && (this.valueRole.equals(that.valueRole())) && (this.relationOwner.equals(that.relationOwner())) && (this.relationValue.equals(that.relationValue())) && (this.required == that.required()); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.resourceType.hashCode(); h *= 1000003; h ^= this.ownerRole.hashCode(); h *= 1000003; h ^= this.valueRole.hashCode(); h *= 1000003; h ^= this.relationOwner.hashCode(); h *= 1000003; h ^= this.relationValue.hashCode(); h *= 1000003; h ^= this.required ? 1231 : 1237; return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/AutoValue_IdProperty.java
package ai.grakn.graql.internal.pattern.property; import ai.grakn.concept.ConceptId; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_IdProperty extends IdProperty { private final ConceptId id; AutoValue_IdProperty( ConceptId id) { if (id == null) { throw new NullPointerException("Null id"); } this.id = id; } @Override public ConceptId id() { return id; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof IdProperty) { IdProperty that = (IdProperty) o; return (this.id.equals(that.id())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.id.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/AutoValue_IsaExplicitProperty.java
package ai.grakn.graql.internal.pattern.property; import ai.grakn.graql.admin.VarPatternAdmin; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_IsaExplicitProperty extends IsaExplicitProperty { private final VarPatternAdmin type; AutoValue_IsaExplicitProperty( VarPatternAdmin type) { if (type == null) { throw new NullPointerException("Null type"); } this.type = type; } @Override public VarPatternAdmin type() { return type; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof IsaExplicitProperty) { IsaExplicitProperty that = (IsaExplicitProperty) o; return (this.type.equals(that.type())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.type.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/AutoValue_IsaProperty.java
package ai.grakn.graql.internal.pattern.property; import ai.grakn.graql.Var; import ai.grakn.graql.admin.VarPatternAdmin; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_IsaProperty extends IsaProperty { private final VarPatternAdmin type; private final Var directTypeVar; AutoValue_IsaProperty( VarPatternAdmin type, Var directTypeVar) { if (type == null) { throw new NullPointerException("Null type"); } this.type = type; if (directTypeVar == null) { throw new NullPointerException("Null directTypeVar"); } this.directTypeVar = directTypeVar; } @Override public VarPatternAdmin type() { return type; } @Override public Var directTypeVar() { return directTypeVar; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/AutoValue_LabelProperty.java
package ai.grakn.graql.internal.pattern.property; import ai.grakn.concept.Label; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_LabelProperty extends LabelProperty { private final Label label; AutoValue_LabelProperty( Label label) { if (label == null) { throw new NullPointerException("Null label"); } this.label = label; } @Override public Label label() { return label; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof LabelProperty) { LabelProperty that = (LabelProperty) o; return (this.label.equals(that.label())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.label.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/AutoValue_NeqProperty.java
package ai.grakn.graql.internal.pattern.property; import ai.grakn.graql.admin.VarPatternAdmin; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_NeqProperty extends NeqProperty { private final VarPatternAdmin var; AutoValue_NeqProperty( VarPatternAdmin var) { if (var == null) { throw new NullPointerException("Null var"); } this.var = var; } @Override public VarPatternAdmin var() { return var; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof NeqProperty) { NeqProperty that = (NeqProperty) o; return (this.var.equals(that.var())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.var.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/AutoValue_PlaysProperty.java
package ai.grakn.graql.internal.pattern.property; import ai.grakn.graql.admin.VarPatternAdmin; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_PlaysProperty extends PlaysProperty { private final VarPatternAdmin role; private final boolean required; AutoValue_PlaysProperty( VarPatternAdmin role, boolean required) { if (role == null) { throw new NullPointerException("Null role"); } this.role = role; this.required = required; } @Override VarPatternAdmin role() { return role; } @Override boolean required() { return required; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof PlaysProperty) { PlaysProperty that = (PlaysProperty) o; return (this.role.equals(that.role())) && (this.required == that.required()); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.role.hashCode(); h *= 1000003; h ^= this.required ? 1231 : 1237; return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/AutoValue_PropertyExecutor.java
package ai.grakn.graql.internal.pattern.property; import ai.grakn.graql.Var; import com.google.common.collect.ImmutableSet; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_PropertyExecutor extends PropertyExecutor { private final ImmutableSet<Var> requiredVars; private final ImmutableSet<Var> producedVars; private final PropertyExecutor.Method executeMethod; private AutoValue_PropertyExecutor( ImmutableSet<Var> requiredVars, ImmutableSet<Var> producedVars, PropertyExecutor.Method executeMethod) { this.requiredVars = requiredVars; this.producedVars = producedVars; this.executeMethod = executeMethod; } @Override public ImmutableSet<Var> requiredVars() { return requiredVars; } @Override public ImmutableSet<Var> producedVars() { return producedVars; } @Override PropertyExecutor.Method executeMethod() { return executeMethod; } @Override public String toString() { return "PropertyExecutor{" + "requiredVars=" + requiredVars + ", " + "producedVars=" + producedVars + ", " + "executeMethod=" + executeMethod + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof PropertyExecutor) { PropertyExecutor that = (PropertyExecutor) o; return (this.requiredVars.equals(that.requiredVars())) && (this.producedVars.equals(that.producedVars())) && (this.executeMethod.equals(that.executeMethod())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.requiredVars.hashCode(); h *= 1000003; h ^= this.producedVars.hashCode(); h *= 1000003; h ^= this.executeMethod.hashCode(); return h; } static final class Builder extends PropertyExecutor.Builder { private ImmutableSet.Builder<Var> requiredVarsBuilder$; private ImmutableSet<Var> requiredVars; private ImmutableSet.Builder<Var> producedVarsBuilder$; private ImmutableSet<Var> producedVars; private PropertyExecutor.Method executeMethod; Builder() { } @Override ImmutableSet.Builder<Var> requiredVarsBuilder() { if (requiredVarsBuilder$ == null) { requiredVarsBuilder$ = ImmutableSet.builder(); } return requiredVarsBuilder$; } @Override ImmutableSet.Builder<Var> producedVarsBuilder() { if (producedVarsBuilder$ == null) { producedVarsBuilder$ = ImmutableSet.builder(); } return producedVarsBuilder$; } @Override PropertyExecutor.Builder executeMethod(PropertyExecutor.Method executeMethod) { if (executeMethod == null) { throw new NullPointerException("Null executeMethod"); } this.executeMethod = executeMethod; return this; } @Override PropertyExecutor build() { if (requiredVarsBuilder$ != null) { this.requiredVars = requiredVarsBuilder$.build(); } else if (this.requiredVars == null) { this.requiredVars = ImmutableSet.of(); } if (producedVarsBuilder$ != null) { this.producedVars = producedVarsBuilder$.build(); } else if (this.producedVars == null) { this.producedVars = ImmutableSet.of(); } String missing = ""; if (this.executeMethod == null) { missing += " executeMethod"; } if (!missing.isEmpty()) { throw new IllegalStateException("Missing required properties:" + missing); } return new AutoValue_PropertyExecutor( this.requiredVars, this.producedVars, this.executeMethod); } } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/AutoValue_RegexProperty.java
package ai.grakn.graql.internal.pattern.property; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_RegexProperty extends RegexProperty { private final String regex; AutoValue_RegexProperty( String regex) { if (regex == null) { throw new NullPointerException("Null regex"); } this.regex = regex; } @Override public String regex() { return regex; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof RegexProperty) { RegexProperty that = (RegexProperty) o; return (this.regex.equals(that.regex())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.regex.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/AutoValue_RelatesProperty.java
package ai.grakn.graql.internal.pattern.property; import ai.grakn.graql.admin.VarPatternAdmin; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_RelatesProperty extends RelatesProperty { private final VarPatternAdmin role; private final VarPatternAdmin superRole; AutoValue_RelatesProperty( VarPatternAdmin role, @Nullable VarPatternAdmin superRole) { if (role == null) { throw new NullPointerException("Null role"); } this.role = role; this.superRole = superRole; } @Override VarPatternAdmin role() { return role; } @Nullable @Override VarPatternAdmin superRole() { return superRole; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof RelatesProperty) { RelatesProperty that = (RelatesProperty) o; return (this.role.equals(that.role())) && ((this.superRole == null) ? (that.superRole() == null) : this.superRole.equals(that.superRole())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.role.hashCode(); h *= 1000003; h ^= (superRole == null) ? 0 : this.superRole.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/AutoValue_RelationshipProperty.java
package ai.grakn.graql.internal.pattern.property; import ai.grakn.graql.admin.RelationPlayer; import com.google.common.collect.ImmutableMultiset; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_RelationshipProperty extends RelationshipProperty { private final ImmutableMultiset<RelationPlayer> relationPlayers; AutoValue_RelationshipProperty( ImmutableMultiset<RelationPlayer> relationPlayers) { if (relationPlayers == null) { throw new NullPointerException("Null relationPlayers"); } this.relationPlayers = relationPlayers; } @Override public ImmutableMultiset<RelationPlayer> relationPlayers() { return relationPlayers; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof RelationshipProperty) { RelationshipProperty that = (RelationshipProperty) o; return (this.relationPlayers.equals(that.relationPlayers())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.relationPlayers.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/AutoValue_SubProperty.java
package ai.grakn.graql.internal.pattern.property; import ai.grakn.graql.admin.VarPatternAdmin; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_SubProperty extends SubProperty { private final VarPatternAdmin superType; AutoValue_SubProperty( VarPatternAdmin superType) { if (superType == null) { throw new NullPointerException("Null superType"); } this.superType = superType; } @Override public VarPatternAdmin superType() { return superType; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof SubProperty) { SubProperty that = (SubProperty) o; return (this.superType.equals(that.superType())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.superType.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/AutoValue_ThenProperty.java
package ai.grakn.graql.internal.pattern.property; import ai.grakn.graql.Pattern; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_ThenProperty extends ThenProperty { private final Pattern pattern; AutoValue_ThenProperty( Pattern pattern) { if (pattern == null) { throw new NullPointerException("Null pattern"); } this.pattern = pattern; } @Override public Pattern pattern() { return pattern; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof ThenProperty) { ThenProperty that = (ThenProperty) 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/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/AutoValue_ValueProperty.java
package ai.grakn.graql.internal.pattern.property; import ai.grakn.graql.ValuePredicate; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_ValueProperty extends ValueProperty { private final ValuePredicate predicate; AutoValue_ValueProperty( ValuePredicate predicate) { if (predicate == null) { throw new NullPointerException("Null predicate"); } this.predicate = predicate; } @Override public ValuePredicate predicate() { return predicate; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof ValueProperty) { ValueProperty that = (ValueProperty) o; return (this.predicate.equals(that.predicate())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.predicate.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/AutoValue_WhenProperty.java
package ai.grakn.graql.internal.pattern.property; import ai.grakn.graql.Pattern; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_WhenProperty extends WhenProperty { private final Pattern pattern; AutoValue_WhenProperty( Pattern pattern) { if (pattern == null) { throw new NullPointerException("Null pattern"); } this.pattern = pattern; } @Override public Pattern pattern() { return pattern; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof WhenProperty) { WhenProperty that = (WhenProperty) 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/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/DataTypeProperty.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.pattern.property; import ai.grakn.concept.AttributeType; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Var; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.UniqueVarProperty; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.internal.gremlin.EquivalentFragmentSet; import ai.grakn.graql.internal.gremlin.sets.EquivalentFragmentSets; import ai.grakn.graql.internal.parser.QueryParserImpl; import ai.grakn.graql.internal.reasoner.atom.property.DataTypeAtom; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import java.util.Collection; import java.util.Set; /** * Represents the {@code datatype} property on a {@link AttributeType}. * * This property can be queried or inserted. * * @author Felix Chapman */ @AutoValue public abstract class DataTypeProperty extends AbstractVarProperty implements NamedProperty, UniqueVarProperty { public static final String NAME = "datatype"; public static DataTypeProperty of(AttributeType.DataType<?> datatype) { return new AutoValue_DataTypeProperty(datatype); } public abstract AttributeType.DataType<?> dataType(); @Override public String getName() { return NAME; } @Override public String getProperty() { return QueryParserImpl.DATA_TYPES.inverse().get(dataType()); } @Override public Collection<EquivalentFragmentSet> match(Var start) { return ImmutableSet.of(EquivalentFragmentSets.dataType(this, start, dataType())); } @Override public Collection<PropertyExecutor> define(Var var) throws GraqlQueryException { PropertyExecutor.Method method = executor -> { executor.builder(var).dataType(dataType()); }; return ImmutableSet.of(PropertyExecutor.builder(method).produces(var).build()); } @Override public Collection<PropertyExecutor> undefine(Var var) throws GraqlQueryException { // TODO: resolve the below issue correctly // undefine for datatype must be supported, because it is supported in define. // However, making it do the right thing is difficult. Ideally we want the same as define: // // undefine name datatype string, sub attribute; <- Remove `name` // undefine first-name sub name; <- Remove `first-name` // undefine name datatype string; <- FAIL // undefine name sub attribute; <- FAIL // // Doing this is tough because it means the `datatype` property needs to be aware of the context somehow. // As a compromise, we make all the cases succeed (where some do nothing) return ImmutableSet.of(PropertyExecutor.builder(executor -> {}).build()); } @Override public Atomic mapToAtom(VarPatternAdmin var, Set<VarPatternAdmin> vars, ReasonerQuery parent) { return DataTypeAtom.create(var.var(), this, parent); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/HasAttributeProperty.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.pattern.property; import ai.grakn.GraknTx; import ai.grakn.concept.Attribute; import ai.grakn.concept.AttributeType; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Label; import ai.grakn.concept.Relationship; import ai.grakn.concept.SchemaConcept; import ai.grakn.concept.Thing; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Graql; import ai.grakn.graql.Var; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.internal.gremlin.EquivalentFragmentSet; import ai.grakn.graql.internal.reasoner.atom.binary.ResourceAtom; import ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate; import ai.grakn.graql.internal.reasoner.atom.predicate.ValuePredicate; import ai.grakn.util.Schema; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import java.util.Collection; import java.util.Set; import java.util.stream.Stream; import static ai.grakn.graql.Graql.label; import static ai.grakn.graql.internal.gremlin.sets.EquivalentFragmentSets.neq; import static ai.grakn.graql.internal.gremlin.sets.EquivalentFragmentSets.rolePlayer; import static ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.getIdPredicate; import static ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.getValuePredicates; import static ai.grakn.graql.internal.util.StringConverter.typeLabelToString; import static java.util.stream.Collectors.joining; /** * Represents the {@code has} property on an {@link Thing}. * * This property can be queried, inserted or deleted. * * The property is defined as a {@link Relationship} between an {@link Thing} and a {@link Attribute}, where the * {@link Attribute} is of a particular type. * * When matching, {@link ai.grakn.util.Schema.EdgeLabel#ROLE_PLAYER} edges are used to speed up the traversal. The type of the {@link Relationship} does not * matter. * * When inserting, an implicit {@link Relationship} is created between the instance and the {@link Attribute}, using * type labels derived from the label of the {@link AttributeType}. * * @author Felix Chapman */ @AutoValue public abstract class HasAttributeProperty extends AbstractVarProperty implements NamedProperty { public static final String NAME = "has"; public static HasAttributeProperty of(Label attributeType, VarPatternAdmin attribute, VarPatternAdmin relationship) { attribute = attribute.isa(label(attributeType)).admin(); return new AutoValue_HasAttributeProperty(attributeType, attribute, relationship); } public abstract Label type(); public abstract VarPatternAdmin attribute(); public abstract VarPatternAdmin relationship(); @Override public String getName() { return NAME; } @Override public String getProperty() { Stream.Builder<String> repr = Stream.builder(); repr.add(typeLabelToString(type())); if (attribute().var().isUserDefinedName()) { repr.add(attribute().var().toString()); } else { attribute().getProperties(ValueProperty.class).forEach(prop -> repr.add(prop.predicate().toString())); } if (hasReifiedRelationship()) { repr.add("via").add(relationship().getPrintableName()); } return repr.build().collect(joining(" ")); } @Override public Collection<EquivalentFragmentSet> match(Var start) { Label type = type(); Label has = Schema.ImplicitType.HAS.getLabel(type); Label key = Schema.ImplicitType.KEY.getLabel(type); Label hasOwnerRole = Schema.ImplicitType.HAS_OWNER.getLabel(type); Label keyOwnerRole = Schema.ImplicitType.KEY_OWNER.getLabel(type); Label hasValueRole= Schema.ImplicitType.HAS_VALUE.getLabel(type); Label keyValueRole = Schema.ImplicitType.KEY_VALUE.getLabel(type); Var edge1 = Graql.var(); Var edge2 = Graql.var(); return ImmutableSet.of( //owner rolePlayer edge rolePlayer(this, relationship().var(), edge1, start, null, ImmutableSet.of(hasOwnerRole, keyOwnerRole), ImmutableSet.of(has, key)), //value rolePlayer edge rolePlayer(this, relationship().var(), edge2, attribute().var(), null, ImmutableSet.of(hasValueRole, keyValueRole), ImmutableSet.of(has, key)), neq(this, edge1, edge2) ); } @Override public Stream<VarPatternAdmin> innerVarPatterns() { return Stream.of(attribute(), relationship()); } @Override void checkValidProperty(GraknTx graph, VarPatternAdmin var) { SchemaConcept schemaConcept = graph.getSchemaConcept(type()); if (schemaConcept == null) { throw GraqlQueryException.labelNotFound(type()); } if(!schemaConcept.isAttributeType()) { throw GraqlQueryException.mustBeAttributeType(type()); } } @Override public Collection<PropertyExecutor> insert(Var var) throws GraqlQueryException { PropertyExecutor.Method method = executor -> { Attribute attributeConcept = executor.get(attribute().var()).asAttribute(); Thing thing = executor.get(var).asThing(); ConceptId relationshipId = thing.relhas(attributeConcept).id(); executor.builder(relationship().var()).id(relationshipId); }; PropertyExecutor executor = PropertyExecutor.builder(method) .produces(relationship().var()) .requires(var, attribute().var()) .build(); return ImmutableSet.of(executor); } @Override public Stream<VarPatternAdmin> getTypes() { return Stream.of(label(type()).admin()); } private boolean hasReifiedRelationship() { return relationship().getProperties().findAny().isPresent() || relationship().var().isUserDefinedName(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; HasAttributeProperty that = (HasAttributeProperty) o; if (!type().equals(that.type())) return false; if (!attribute().equals(that.attribute())) return false; // TODO: Having to check this is pretty dodgy // This check is necessary for `equals` and `hashCode` because `VarPattern` equality is defined // s.t. `var() != var()`, but `var().label("movie") == var().label("movie")` // i.e., a `Var` is compared by name, but a `VarPattern` ignores the name if the var is not user-defined return !hasReifiedRelationship() || relationship().equals(that.relationship()); } @Override public int hashCode() { int result = type().hashCode(); result = 31 * result + attribute().hashCode(); // TODO: Having to check this is pretty dodgy, explanation in #equals if (hasReifiedRelationship()) { result = 31 * result + relationship().hashCode(); } return result; } @Override public Atomic mapToAtom(VarPatternAdmin var, Set<VarPatternAdmin> vars, ReasonerQuery parent) { //NB: HasAttributeProperty always has (type) label specified Var varName = var.var().asUserDefined(); Var relationVariable = relationship().var(); Var attributeVariable = attribute().var().asUserDefined(); Set<ValuePredicate> predicates = getValuePredicates(attributeVariable, attribute(), vars, parent); IsaProperty isaProp = attribute().getProperties(IsaProperty.class).findFirst().orElse(null); VarPatternAdmin typeVar = isaProp != null? isaProp.type() : null; IdPredicate predicate = typeVar != null? getIdPredicate(attributeVariable, typeVar, vars, parent) : null; ConceptId predicateId = predicate != null? predicate.getPredicate() : null; //add resource atom VarPatternAdmin resVar = relationVariable.isUserDefinedName()? varName.has(type(), attributeVariable, relationVariable).admin() : varName.has(type(), attributeVariable).admin(); return ResourceAtom.create(resVar, attributeVariable, relationVariable, predicateId, predicates, parent); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/HasAttributeTypeProperty.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.pattern.property; import ai.grakn.concept.AttributeType; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Label; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.concept.SchemaConcept; import ai.grakn.concept.Type; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Graql; import ai.grakn.graql.Match; 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.VarPatternAdmin; import ai.grakn.graql.internal.gremlin.EquivalentFragmentSet; import ai.grakn.graql.internal.reasoner.atom.binary.HasAtom; import ai.grakn.util.Schema; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.stream.Stream; import static ai.grakn.graql.Graql.var; import static ai.grakn.util.Schema.ImplicitType.KEY; import static ai.grakn.util.Schema.ImplicitType.KEY_OWNER; import static ai.grakn.util.Schema.ImplicitType.KEY_VALUE; /** * Represents the {@code has} and {@code key} properties on a {@link Type}. * * This property can be queried or inserted. Whether this is a key is indicated by the * {@link HasAttributeTypeProperty#required} field. * * This property is defined as an implicit ontological structure between a {@link Type} and a {@link AttributeType}, * including one implicit {@link RelationshipType} and two implicit {@link Role}s. The labels of these types are derived * from the label of the {@link AttributeType}. * * Like {@link HasAttributeProperty}, if this is not a key and is used in a {@link Match} it will not use the implicit * structure - instead, it will match if there is any kind of relation type connecting the two types. * * @author Felix Chapman */ @AutoValue public abstract class HasAttributeTypeProperty extends AbstractVarProperty implements NamedProperty { abstract VarPatternAdmin resourceType(); abstract VarPatternAdmin ownerRole(); abstract VarPatternAdmin valueRole(); abstract VarPatternAdmin relationOwner(); abstract VarPatternAdmin relationValue(); abstract boolean required(); /** * @throws GraqlQueryException if no label is specified on {@code resourceType} */ public static HasAttributeTypeProperty of(VarPatternAdmin resourceType, boolean required) { Label resourceLabel = resourceType.getTypeLabel().orElseThrow(() -> GraqlQueryException.noLabelSpecifiedForHas(resourceType) ); VarPattern role = Graql.label(Schema.MetaSchema.ROLE.getLabel()); VarPatternAdmin ownerRole = var().sub(role).admin(); VarPatternAdmin valueRole = var().sub(role).admin(); VarPattern relationType = var().sub(Graql.label(Schema.MetaSchema.RELATIONSHIP.getLabel())); // If a key, limit only to the implicit key type if(required){ ownerRole = ownerRole.label(KEY_OWNER.getLabel(resourceLabel)).admin(); valueRole = valueRole.label(KEY_VALUE.getLabel(resourceLabel)).admin(); relationType = relationType.label(KEY.getLabel(resourceLabel)); } VarPatternAdmin relationOwner = relationType.relates(ownerRole).admin(); VarPatternAdmin relationValue = relationType.admin().var().relates(valueRole).admin(); return new AutoValue_HasAttributeTypeProperty( resourceType, ownerRole, valueRole, relationOwner, relationValue, required); } @Override public String getName() { return required() ? "key" : "has"; } @Override public String getProperty() { return resourceType().getPrintableName(); } @Override public Collection<EquivalentFragmentSet> match(Var start) { Collection<EquivalentFragmentSet> traversals = new HashSet<>(); traversals.addAll(PlaysProperty.of(ownerRole(), required()).match(start)); //TODO: Get this to use real constraints no just the required flag traversals.addAll(PlaysProperty.of(valueRole(), false).match(resourceType().var())); traversals.addAll(NeqProperty.of(ownerRole()).match(valueRole().var())); return traversals; } @Override public Stream<VarPatternAdmin> getTypes() { return Stream.of(resourceType()); } @Override public Stream<VarPatternAdmin> innerVarPatterns() { return Stream.of(resourceType()); } @Override public Stream<VarPatternAdmin> implicitInnerVarPatterns() { return Stream.of(resourceType(), ownerRole(), valueRole(), relationOwner(), relationValue()); } @Override public Collection<PropertyExecutor> define(Var var) throws GraqlQueryException { PropertyExecutor.Method method = executor -> { Type entityTypeConcept = executor.get(var).asType(); AttributeType attributeTypeConcept = executor.get(resourceType().var()).asAttributeType(); if (required()) { entityTypeConcept.key(attributeTypeConcept); } else { entityTypeConcept.has(attributeTypeConcept); } }; return ImmutableSet.of(PropertyExecutor.builder(method).requires(var, resourceType().var()).build()); } @Override public Collection<PropertyExecutor> undefine(Var var) throws GraqlQueryException { PropertyExecutor.Method method = executor -> { Type type = executor.get(var).asType(); AttributeType<?> attributeType = executor.get(resourceType().var()).asAttributeType(); if (!type.isDeleted() && !attributeType.isDeleted()) { if (required()) { type.unkey(attributeType); } else { type.unhas(attributeType); } } }; return ImmutableSet.of(PropertyExecutor.builder(method).requires(var, resourceType().var()).build()); } @Override public Atomic mapToAtom(VarPatternAdmin var, Set<VarPatternAdmin> vars, ReasonerQuery parent) { //NB: HasResourceType is a special case and it doesn't allow variables as resource types Var varName = var.var().asUserDefined(); Label label = this.resourceType().getTypeLabel().orElse(null); Var predicateVar = var().asUserDefined(); SchemaConcept schemaConcept = parent.tx().getSchemaConcept(label); ConceptId predicateId = schemaConcept != null? schemaConcept.id() : null; //isa part VarPatternAdmin resVar = varName.has(Graql.label(label)).admin(); return HasAtom.create(resVar, predicateVar, predicateId, parent); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/IdProperty.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.pattern.property; import ai.grakn.concept.ConceptId; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Var; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.UniqueVarProperty; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.internal.gremlin.EquivalentFragmentSet; import ai.grakn.graql.internal.gremlin.sets.EquivalentFragmentSets; import ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate; import ai.grakn.graql.internal.util.StringConverter; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import java.util.Collection; import java.util.Set; /** * Represents the {@code id} property on a {@link ai.grakn.concept.Concept}. * * This property can be queried. While this property cannot be inserted, if used in an insert query any existing concept * with the given ID will be retrieved. * * @author Felix Chapman */ @AutoValue public abstract class IdProperty extends AbstractVarProperty implements NamedProperty, UniqueVarProperty { public static final String NAME = "id"; public static IdProperty of(ConceptId id) { return new AutoValue_IdProperty(id); } public abstract ConceptId id(); @Override public String getName() { return NAME; } @Override public String getProperty() { return StringConverter.idToString(id()); } @Override public Collection<EquivalentFragmentSet> match(Var start) { return ImmutableSet.of(EquivalentFragmentSets.id(this, start, id())); } @Override public Collection<PropertyExecutor> insert(Var var) throws GraqlQueryException { PropertyExecutor.Method method = executor -> { executor.builder(var).id(id()); }; return ImmutableSet.of(PropertyExecutor.builder(method).produces(var).build()); } @Override public Collection<PropertyExecutor> define(Var var) throws GraqlQueryException { // This property works in both insert and define queries, because it is only for look-ups return insert(var); } @Override public Collection<PropertyExecutor> undefine(Var var) throws GraqlQueryException { // This property works in undefine queries, because it is only for look-ups return insert(var); } @Override public boolean uniquelyIdentifiesConcept() { return true; } @Override public Atomic mapToAtom(VarPatternAdmin var, Set<VarPatternAdmin> vars, ReasonerQuery parent) { return IdPredicate.create(var.var(), id(), parent); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/IsAbstractProperty.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.pattern.property; import ai.grakn.concept.Concept; import ai.grakn.concept.Type; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Var; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.UniqueVarProperty; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.internal.gremlin.EquivalentFragmentSet; import ai.grakn.graql.internal.reasoner.atom.property.IsAbstractAtom; import com.google.common.collect.ImmutableSet; import java.util.Collection; import java.util.Set; import static ai.grakn.graql.internal.gremlin.sets.EquivalentFragmentSets.isAbstract; /** * Represents the {@code is-abstract} property on a {@link ai.grakn.concept.Type}. * * This property can be matched or inserted. * * This property states that a type cannot have direct instances. * * @author Felix Chapman */ public class IsAbstractProperty extends AbstractVarProperty implements UniqueVarProperty { private static final IsAbstractProperty INSTANCE = new IsAbstractProperty(); public static final String NAME = "is-abstract"; private IsAbstractProperty() { } public static IsAbstractProperty get() { return INSTANCE; } @Override public void buildString(StringBuilder builder) { builder.append(NAME); } @Override public Collection<EquivalentFragmentSet> match(Var start) { return ImmutableSet.of(isAbstract(this, start)); } @Override String getName() { return NAME; } @Override public Collection<PropertyExecutor> define(Var var) throws GraqlQueryException { PropertyExecutor.Method method = executor -> { Concept concept = executor.get(var); if (concept.isType()) { concept.asType().isAbstract(true); } else { throw GraqlQueryException.insertAbstractOnNonType(concept.asSchemaConcept()); } }; return ImmutableSet.of(PropertyExecutor.builder(method).requires(var).build()); } @Override public Collection<PropertyExecutor> undefine(Var var) throws GraqlQueryException { PropertyExecutor.Method method = executor -> { Type type = executor.get(var).asType(); if (!type.isDeleted()) { type.isAbstract(false); } }; return ImmutableSet.of(PropertyExecutor.builder(method).requires(var).build()); } @Override public Atomic mapToAtom(VarPatternAdmin var, Set<VarPatternAdmin> vars, ReasonerQuery parent) { return IsAbstractAtom.create(var.var(), parent); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/IsaExplicitProperty.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.pattern.property; import ai.grakn.concept.Thing; import ai.grakn.concept.Type; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.internal.gremlin.EquivalentFragmentSet; import ai.grakn.graql.internal.gremlin.sets.EquivalentFragmentSets; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import java.util.Collection; /** * Represents the {@code isa-explicit} property on a {@link Thing}. * <p> * This property can be queried and inserted. * </p> * <p> * THe property is defined as a relationship between an {@link Thing} and a {@link Type}. * </p> * <p> * When matching, any subtyping is ignored. For example, if we have {@code $bob isa man}, {@code man sub person}, * {@code person sub entity} then it only follows {@code $bob isa man}, not {@code bob isa entity}. * </p> * * @author Felix Chapman * @author Jason Liu */ @AutoValue public abstract class IsaExplicitProperty extends AbstractIsaProperty { public static final String NAME = "isa!"; public static IsaExplicitProperty of(VarPatternAdmin directType) { return new AutoValue_IsaExplicitProperty(directType); } @Override public String getName() { return NAME; } @Override public Collection<EquivalentFragmentSet> match(Var start) { return ImmutableSet.of( EquivalentFragmentSets.isa(this, start, type().var(), true) ); } @Override protected final VarPattern varPatternForAtom(Var varName, Var typeVariable) { return varName.isaExplicit(typeVariable); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/IsaProperty.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.pattern.property; import ai.grakn.concept.Thing; import ai.grakn.concept.Type; import ai.grakn.graql.Graql; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.internal.gremlin.EquivalentFragmentSet; import ai.grakn.graql.internal.gremlin.sets.EquivalentFragmentSets; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import java.util.Collection; /** * Represents the {@code isa} property on a {@link Thing}. * <p> * This property can be queried and inserted. * </p> * <p> * THe property is defined as a relationship between an {@link Thing} and a {@link Type}. * </p> * <p> * When matching, any subtyping is respected. For example, if we have {@code $bob isa man}, {@code man sub person}, * {@code person sub entity} then it follows that {@code $bob isa person} and {@code bob isa entity}. * </p> * * @author Felix Chapman */ @AutoValue public abstract class IsaProperty extends AbstractIsaProperty { public static final String NAME = "isa"; public static IsaProperty of(VarPatternAdmin type) { return new AutoValue_IsaProperty(type, Graql.var()); } public abstract Var directTypeVar(); @Override public String getName() { return NAME; } @Override public Collection<EquivalentFragmentSet> match(Var start) { return ImmutableSet.of( EquivalentFragmentSets.isa(this, start, directTypeVar(), true), EquivalentFragmentSets.sub(this, directTypeVar(), type().var()) ); } @Override protected final VarPattern varPatternForAtom(Var varName, Var typeVariable) { return varName.isa(typeVariable); } // TODO: These are overridden so we ignore `directType`, which ideally shouldn't be necessary @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof IsaProperty) { IsaProperty that = (IsaProperty) o; return this.type().equals(that.type()); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.type().hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/LabelProperty.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.pattern.property; import ai.grakn.concept.Label; import ai.grakn.concept.SchemaConcept; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Var; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.UniqueVarProperty; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.internal.gremlin.EquivalentFragmentSet; import ai.grakn.graql.internal.gremlin.sets.EquivalentFragmentSets; import ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate; import ai.grakn.graql.internal.util.StringConverter; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import java.util.Collection; import java.util.Set; /** * Represents the {@code label} property on a {@link ai.grakn.concept.Type}. * * This property can be queried and inserted. If used in an insert query and there is an existing type with the give * label, then that type will be retrieved. * * @author Felix Chapman */ @AutoValue public abstract class LabelProperty extends AbstractVarProperty implements NamedProperty, UniqueVarProperty { public static final String NAME = "label"; public static LabelProperty of(Label label) { return new AutoValue_LabelProperty(label); } public abstract Label label(); @Override public String getName() { return NAME; } @Override public String getProperty() { return StringConverter.typeLabelToString(label()); } @Override public Collection<EquivalentFragmentSet> match(Var start) { return ImmutableSet.of(EquivalentFragmentSets.label(this, start, ImmutableSet.of(label()))); } @Override public Collection<PropertyExecutor> insert(Var var) throws GraqlQueryException { // This is supported in insert queries in order to allow looking up schema concepts by label return define(var); } @Override public Collection<PropertyExecutor> define(Var var) throws GraqlQueryException { PropertyExecutor.Method method = executor -> { executor.builder(var).label(label()); }; return ImmutableSet.of(PropertyExecutor.builder(method).produces(var).build()); } @Override public Collection<PropertyExecutor> undefine(Var var) throws GraqlQueryException { // This is supported in undefine queries in order to allow looking up schema concepts by label return define(var); } @Override public boolean uniquelyIdentifiesConcept() { return true; } @Override public Atomic mapToAtom(VarPatternAdmin var, Set<VarPatternAdmin> vars, ReasonerQuery parent) { SchemaConcept schemaConcept = parent.tx().getSchemaConcept(label()); if (schemaConcept == null) throw GraqlQueryException.labelNotFound(label()); return IdPredicate.create(var.var().asUserDefined(), label(), parent); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/NamedProperty.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.pattern.property; interface NamedProperty extends VarPropertyInternal { String getName(); String getProperty(); default void buildString(StringBuilder builder) { builder.append(getName()).append(" ").append(getProperty()); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/NeqProperty.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.pattern.property; import ai.grakn.graql.Var; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.internal.gremlin.EquivalentFragmentSet; import ai.grakn.graql.internal.gremlin.sets.EquivalentFragmentSets; import ai.grakn.graql.internal.reasoner.atom.predicate.NeqPredicate; import com.google.auto.value.AutoValue; import com.google.common.collect.Sets; import java.util.Collection; import java.util.Set; import java.util.stream.Stream; /** * Represents the {@code !=} property on a {@link ai.grakn.concept.Concept}. * * This property can be queried. It asserts identity inequality between two concepts. Concepts may have shared * properties but still be distinct. For example, two instances of a type without any resources are still considered * unequal. Similarly, two resources with the same value but of different types are considered unequal. * * @author Felix Chapman */ @AutoValue public abstract class NeqProperty extends AbstractVarProperty implements NamedProperty { public static NeqProperty of(VarPatternAdmin var) { return new AutoValue_NeqProperty(var); } public abstract VarPatternAdmin var(); @Override public String getName() { return "!="; } @Override public String getProperty() { return var().getPrintableName(); } @Override public Collection<EquivalentFragmentSet> match(Var start) { return Sets.newHashSet( EquivalentFragmentSets.notInternalFragmentSet(this, start), EquivalentFragmentSets.notInternalFragmentSet(this, var().var()), EquivalentFragmentSets.neq(this, start, var().var()) ); } @Override public Stream<VarPatternAdmin> innerVarPatterns() { return Stream.of(var()); } @Override public Atomic mapToAtom(VarPatternAdmin var, Set<VarPatternAdmin> vars, ReasonerQuery parent) { return NeqPredicate.create(var.var(), this, parent); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/PlaysProperty.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.pattern.property; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Role; import ai.grakn.concept.Thing; import ai.grakn.concept.Type; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Var; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.internal.gremlin.EquivalentFragmentSet; import ai.grakn.graql.internal.gremlin.sets.EquivalentFragmentSets; import ai.grakn.graql.internal.reasoner.atom.binary.PlaysAtom; import ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import java.util.Collection; import java.util.Set; import java.util.stream.Stream; import static ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.getIdPredicate; /** * Reperesents the {@code plays} property on a {@link ai.grakn.concept.Type}. * * This property relates a {@link ai.grakn.concept.Type} and a {@link Role}. It indicates that an * {@link Thing} whose type is this {@link ai.grakn.concept.Type} is permitted to be a role-player * playing the role of the given {@link Role}. * * @author Felix Chapman */ @AutoValue public abstract class PlaysProperty extends AbstractVarProperty implements NamedProperty { public static final String NAME = "plays"; public static PlaysProperty of(VarPatternAdmin role, boolean required) { return new AutoValue_PlaysProperty(role, required); } abstract VarPatternAdmin role(); abstract boolean required(); @Override public String getName() { return NAME; } @Override public String getProperty() { return role().getPrintableName(); } @Override public Collection<EquivalentFragmentSet> match(Var start) { return ImmutableSet.of(EquivalentFragmentSets.plays(this, start, role().var(), required())); } @Override public Stream<VarPatternAdmin> getTypes() { return Stream.of(role()); } @Override public Stream<VarPatternAdmin> innerVarPatterns() { return Stream.of(role()); } @Override public Collection<PropertyExecutor> define(Var var) throws GraqlQueryException { PropertyExecutor.Method method = executor -> { Role role = executor.get(this.role().var()).asRole(); executor.get(var).asType().plays(role); }; return ImmutableSet.of(PropertyExecutor.builder(method).requires(var, role().var()).build()); } @Override public Collection<PropertyExecutor> undefine(Var var) throws GraqlQueryException { PropertyExecutor.Method method = executor -> { Type type = executor.get(var).asType(); Role role = executor.get(this.role().var()).asRole(); if (!type.isDeleted() && !role.isDeleted()) { type.unplay(role); } }; return ImmutableSet.of(PropertyExecutor.builder(method).requires(var, role().var()).build()); } @Override public Atomic mapToAtom(VarPatternAdmin var, Set<VarPatternAdmin> vars, ReasonerQuery parent) { Var varName = var.var().asUserDefined(); VarPatternAdmin typeVar = this.role(); Var typeVariable = typeVar.var().asUserDefined(); IdPredicate predicate = getIdPredicate(typeVariable, typeVar, vars, parent); ConceptId predicateId = predicate == null? null : predicate.getPredicate(); return PlaysAtom.create(varName, typeVariable, predicateId, parent); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/PropertyExecutor.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.pattern.property; import ai.grakn.concept.Concept; import ai.grakn.graql.Var; import ai.grakn.graql.admin.VarProperty; import ai.grakn.graql.internal.query.executor.QueryOperationExecutor; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; // TODO: Add an example of 'undefine' to this description /** * A class describing an operation to perform using a {@link VarProperty}. * * <p> * The behaviour is executed via a {@link QueryOperationExecutor} using {@link #execute}. The class also * report its {@link #requiredVars} before it can run and its {@link #producedVars()}, that will be available to * other {@link PropertyExecutor}s after it has run. * </p> * <p> * For example: * <pre> * SubProperty property = SubProperty.of(y); * PropertyExecutor executor = property.define(x); * executor.requiredVars(); // returns `{y}` * executor.producedVars(); // returns `{x}` * * // apply the `sub` property between `x` and `y` * // because it requires `y`, it will call `queryOperationExecutor.get(y)` * // because it produces `x`, it will call `queryOperationExecutor.builder(x)` * executor.execute(queryOperationExecutor); * </pre> * </p> * * @author Felix Chapman */ @AutoValue public abstract class PropertyExecutor { public static PropertyExecutor.Builder builder(Method executeMethod) { return builder().executeMethod(executeMethod); } private static PropertyExecutor.Builder builder() { return new AutoValue_PropertyExecutor.Builder(); } /** * Apply the given property, if possible. * * @param executor a class providing a map of concepts that are accessible and methods to build new concepts. * <p> * This method can expect any key to be here that is returned from * {@link #requiredVars()}. The method may also build a concept provided that key is returned * from {@link #producedVars()}. * </p> */ public final void execute(QueryOperationExecutor executor) { executeMethod().execute(executor); } /** * Get all {@link Var}s whose {@link Concept} must exist for the subject {@link Var} to be applied. * For example, for {@link IsaProperty} the type must already be present before an instance can be created. * * <p> * When calling {@link #execute}, the method can expect any {@link Var} returned here to be available by calling * {@link QueryOperationExecutor#get}. * </p> */ public abstract ImmutableSet<Var> requiredVars(); /** * Get all {@link Var}s whose {@link Concept} can only be created after this property is applied. * * <p> * When calling {@link #execute}, the method must help build a {@link Concept} for every {@link Var} returned * from this method, using {@link QueryOperationExecutor#builder}. * </p> */ public abstract ImmutableSet<Var> producedVars(); abstract Method executeMethod(); @AutoValue.Builder abstract static class Builder { abstract Builder executeMethod(Method value); abstract ImmutableSet.Builder<Var> requiredVarsBuilder(); public Builder requires(Var... values) { requiredVarsBuilder().add(values); return this; } public Builder requires(Iterable<Var> values) { requiredVarsBuilder().addAll(values); return this; } abstract ImmutableSet.Builder<Var> producedVarsBuilder(); public Builder produces(Var... values) { producedVarsBuilder().add(values); return this; } abstract PropertyExecutor build(); } @FunctionalInterface interface Method { void execute(QueryOperationExecutor queryOperationExecutor); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/RegexProperty.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.pattern.property; import ai.grakn.concept.AttributeType; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Var; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.UniqueVarProperty; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.internal.gremlin.EquivalentFragmentSet; import ai.grakn.graql.internal.gremlin.sets.EquivalentFragmentSets; import ai.grakn.graql.internal.reasoner.atom.property.RegexAtom; import ai.grakn.util.StringUtil; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import java.util.Collection; import java.util.Set; /** * Represents the {@code regex} property on a {@link AttributeType}. * * This property can be queried and inserted. * * This property introduces a validation constraint on instances of this {@link AttributeType}, stating that their * values must conform to the given regular expression. * * @author Felix Chapman */ @AutoValue public abstract class RegexProperty extends AbstractVarProperty implements UniqueVarProperty, NamedProperty { public static RegexProperty of(String regex) { return new AutoValue_RegexProperty(regex); } public abstract String regex(); @Override public String getName() { return "regex"; } @Override public String getProperty() { return "/" + StringUtil.escapeString(regex()) + "/"; } @Override public Collection<EquivalentFragmentSet> match(Var start) { return ImmutableSet.of(EquivalentFragmentSets.regex(this, start, regex())); } @Override public Collection<PropertyExecutor> define(Var var) throws GraqlQueryException { PropertyExecutor.Method method = executor -> { executor.get(var).asAttributeType().regex(regex()); }; return ImmutableSet.of(PropertyExecutor.builder(method).requires(var).build()); } @Override public Collection<PropertyExecutor> undefine(Var var) throws GraqlQueryException { PropertyExecutor.Method method = executor -> { AttributeType<Object> attributeType = executor.get(var).asAttributeType(); if (!attributeType.isDeleted() && regex().equals(attributeType.regex())) { attributeType.regex(null); } }; return ImmutableSet.of(PropertyExecutor.builder(method).requires(var).build()); } @Override public Atomic mapToAtom(VarPatternAdmin var, Set<VarPatternAdmin> vars, ReasonerQuery parent) { return RegexAtom.create(var.var(), this, parent); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/RelatesProperty.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.pattern.property; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Relationship; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Var; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.internal.gremlin.EquivalentFragmentSet; import ai.grakn.graql.internal.reasoner.atom.binary.RelatesAtom; import ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import javax.annotation.Nullable; import java.util.Collection; import java.util.Set; import java.util.stream.Stream; import static ai.grakn.graql.internal.gremlin.sets.EquivalentFragmentSets.relates; import static ai.grakn.graql.internal.gremlin.sets.EquivalentFragmentSets.sub; import static ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.getIdPredicate; /** * Represents the {@code relates} property on a {@link RelationshipType}. * <p> * This property can be queried, inserted or deleted. * <p> * This property relates a {@link RelationshipType} and a {@link Role}. It indicates that a {@link Relationship} whose * type is this {@link RelationshipType} may have a role-player playing the given {@link Role}. * * @author Felix Chapman */ @AutoValue public abstract class RelatesProperty extends AbstractVarProperty { public static RelatesProperty of(VarPatternAdmin role, @Nullable VarPatternAdmin superRole) { return new AutoValue_RelatesProperty(role, superRole); } public static RelatesProperty of(VarPatternAdmin role) { return RelatesProperty.of(role, null); } abstract VarPatternAdmin role(); @Nullable abstract VarPatternAdmin superRole(); @Override public String getName() { return "relates"; } @Override public void buildString(StringBuilder builder) { VarPatternAdmin superRole = superRole(); builder.append("relates").append(" ").append(role().getPrintableName()); if (superRole != null) { builder.append(" as ").append(superRole.getPrintableName()); } } @Override public Collection<EquivalentFragmentSet> match(Var start) { VarPatternAdmin superRole = superRole(); EquivalentFragmentSet relates = relates(this, start, role().var()); if (superRole == null) { return ImmutableSet.of(relates); } else { return ImmutableSet.of(relates, sub(this, role().var(), superRole.var())); } } @Override public Stream<VarPatternAdmin> getTypes() { return Stream.of(role()); } @Override public Stream<VarPatternAdmin> innerVarPatterns() { return superRole() == null ? Stream.of(role()) : Stream.of(superRole(), role()); } @Override public Collection<PropertyExecutor> define(Var var) throws GraqlQueryException { Var roleVar = role().var(); PropertyExecutor.Method relatesMethod = executor -> { Role role = executor.get(roleVar).asRole(); executor.get(var).asRelationshipType().relates(role); }; PropertyExecutor relatesExecutor = PropertyExecutor.builder(relatesMethod).requires(var, roleVar).build(); // This allows users to skip stating `$roleVar sub role` when they say `$var relates $roleVar` PropertyExecutor.Method isRoleMethod = executor -> executor.builder(roleVar).isRole(); PropertyExecutor isRoleExecutor = PropertyExecutor.builder(isRoleMethod).produces(roleVar).build(); VarPatternAdmin superRoleVarPattern = superRole(); if (superRoleVarPattern != null) { Var superRoleVar = superRoleVarPattern.var(); PropertyExecutor.Method subMethod = executor -> { Role superRole = executor.get(superRoleVar).asRole(); executor.builder(roleVar).sub(superRole); }; PropertyExecutor subExecutor = PropertyExecutor.builder(subMethod) .requires(superRoleVar).produces(roleVar).build(); return ImmutableSet.of(relatesExecutor, isRoleExecutor, subExecutor); } else { return ImmutableSet.of(relatesExecutor, isRoleExecutor); } } @Override public Collection<PropertyExecutor> undefine(Var var) throws GraqlQueryException { PropertyExecutor.Method method = executor -> { RelationshipType relationshipType = executor.get(var).asRelationshipType(); Role role = executor.get(this.role().var()).asRole(); if (!relationshipType.isDeleted() && !role.isDeleted()) { relationshipType.unrelate(role); } }; return ImmutableSet.of(PropertyExecutor.builder(method).requires(var, role().var()).build()); } @Override public Atomic mapToAtom(VarPatternAdmin var, Set<VarPatternAdmin> vars, ReasonerQuery parent) { Var varName = var.var().asUserDefined(); VarPatternAdmin roleVar = this.role(); Var roleVariable = roleVar.var().asUserDefined(); IdPredicate predicate = getIdPredicate(roleVariable, roleVar, vars, parent); ConceptId predicateId = predicate != null ? predicate.getPredicate() : null; return RelatesAtom.create(varName, roleVariable, predicateId, parent); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/RelationshipProperty.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.pattern.property; import ai.grakn.GraknTx; import ai.grakn.concept.Concept; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Label; import ai.grakn.concept.Relationship; import ai.grakn.concept.SchemaConcept; import ai.grakn.concept.Role; import ai.grakn.concept.Thing; import ai.grakn.exception.GraqlQueryException; 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.RelationPlayer; import ai.grakn.graql.admin.UniqueVarProperty; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.internal.gremlin.EquivalentFragmentSet; import ai.grakn.graql.internal.gremlin.sets.EquivalentFragmentSets; import ai.grakn.graql.internal.query.executor.QueryOperationExecutor; import ai.grakn.graql.internal.reasoner.atom.binary.RelationshipAtom; import ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate; import ai.grakn.util.CommonUtil; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableMultiset; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import java.util.Collection; import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.stream.Stream; import static ai.grakn.graql.internal.gremlin.sets.EquivalentFragmentSets.rolePlayer; import static ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.getUserDefinedIdPredicate; import static ai.grakn.util.CommonUtil.toImmutableSet; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toSet; /** * Represents the relation property (e.g. {@code ($x, $y)} or {@code (wife: $x, husband: $y)}) on a {@link Relationship}. * * This property can be queried and inserted. * * This propert is comprised of instances of {@link RelationPlayer}, which represents associations between a * role-player {@link Thing} and an optional {@link Role}. * * @author Felix Chapman */ @AutoValue public abstract class RelationshipProperty extends AbstractVarProperty implements UniqueVarProperty { public static RelationshipProperty of(ImmutableMultiset<RelationPlayer> relationPlayers) { return new AutoValue_RelationshipProperty(relationPlayers); } public abstract ImmutableMultiset<RelationPlayer> relationPlayers(); @Override String getName() { return "relationship"; } @Override public void buildString(StringBuilder builder) { builder.append("(").append(relationPlayers().stream().map(Object::toString).collect(joining(", "))).append(")"); } @Override public Collection<EquivalentFragmentSet> match(Var start) { Collection<Var> castingNames = new HashSet<>(); ImmutableSet<EquivalentFragmentSet> traversals = relationPlayers().stream().flatMap(relationPlayer -> { Var castingName = Graql.var(); castingNames.add(castingName); return equivalentFragmentSetFromCasting(start, castingName, relationPlayer); }).collect(toImmutableSet()); ImmutableSet<EquivalentFragmentSet> distinctCastingTraversals = castingNames.stream().flatMap( castingName -> castingNames.stream() .filter(otherName -> !otherName.equals(castingName)) .map(otherName -> EquivalentFragmentSets.neq(this, castingName, otherName)) ).collect(toImmutableSet()); return Sets.union(traversals, distinctCastingTraversals); } @Override public Stream<VarPatternAdmin> getTypes() { return relationPlayers().stream().map(RelationPlayer::getRole).flatMap(CommonUtil::optionalToStream); } @Override public Stream<VarPatternAdmin> innerVarPatterns() { return relationPlayers().stream().flatMap(relationPlayer -> { Stream.Builder<VarPatternAdmin> builder = Stream.builder(); builder.add(relationPlayer.getRolePlayer()); relationPlayer.getRole().ifPresent(builder::add); return builder.build(); }); } private Stream<EquivalentFragmentSet> equivalentFragmentSetFromCasting(Var start, Var castingName, RelationPlayer relationPlayer) { Optional<VarPatternAdmin> roleType = relationPlayer.getRole(); if (roleType.isPresent()) { return addRelatesPattern(start, castingName, roleType.get(), relationPlayer.getRolePlayer()); } else { return addRelatesPattern(start, castingName, relationPlayer.getRolePlayer()); } } /** * Add some patterns where this variable is a relation and the given variable is a roleplayer of that relationship * @param rolePlayer a variable that is a roleplayer of this relation */ private Stream<EquivalentFragmentSet> addRelatesPattern(Var start, Var casting, VarPatternAdmin rolePlayer) { return Stream.of(rolePlayer(this, start, casting, rolePlayer.var(), null)); } /** * Add some patterns where this variable is a relation relating the given roleplayer as the given roletype * @param roleType a variable that is the roletype of the given roleplayer * @param rolePlayer a variable that is a roleplayer of this relation */ private Stream<EquivalentFragmentSet> addRelatesPattern(Var start, Var casting, VarPatternAdmin roleType, VarPatternAdmin rolePlayer) { return Stream.of(rolePlayer(this, start, casting, rolePlayer.var(), roleType.var())); } @Override public void checkValidProperty(GraknTx graph, VarPatternAdmin var) throws GraqlQueryException { Set<Label> roleTypes = relationPlayers().stream() .map(RelationPlayer::getRole).flatMap(CommonUtil::optionalToStream) .map(VarPatternAdmin::getTypeLabel).flatMap(CommonUtil::optionalToStream) .collect(toSet()); Optional<Label> maybeLabel = var.getProperty(IsaProperty.class).map(IsaProperty::type).flatMap(VarPatternAdmin::getTypeLabel); maybeLabel.ifPresent(label -> { SchemaConcept schemaConcept = graph.getSchemaConcept(label); if (schemaConcept == null || !schemaConcept.isRelationshipType()) { throw GraqlQueryException.notARelationType(label); } }); // Check all role types exist roleTypes.forEach(roleId -> { SchemaConcept schemaConcept = graph.getSchemaConcept(roleId); if (schemaConcept == null || !schemaConcept.isRole()) { throw GraqlQueryException.notARoleType(roleId); } }); } @Override public Collection<PropertyExecutor> insert(Var var) throws GraqlQueryException { PropertyExecutor.Method method = executor -> { Relationship relationship = executor.get(var).asRelationship(); relationPlayers().forEach(relationPlayer -> addRoleplayer(executor, relationship, relationPlayer)); }; return ImmutableSet.of(PropertyExecutor.builder(method).requires(requiredVars(var)).build()); } /** * Add a roleplayer to the given {@link Relationship} * @param relationship the concept representing the {@link Relationship} * @param relationPlayer a casting between a role type and role player */ private void addRoleplayer(QueryOperationExecutor executor, Relationship relationship, RelationPlayer relationPlayer) { VarPatternAdmin roleVar = getRole(relationPlayer); Role role = executor.get(roleVar.var()).asRole(); Thing roleplayer = executor.get(relationPlayer.getRolePlayer().var()).asThing(); relationship.assign(role, roleplayer); } private Set<Var> requiredVars(Var var) { Stream<Var> relationPlayers = this.relationPlayers().stream() .flatMap(relationPlayer -> Stream.of(relationPlayer.getRolePlayer(), getRole(relationPlayer))) .map(VarPatternAdmin::var); return Stream.concat(relationPlayers, Stream.of(var)).collect(toImmutableSet()); } private VarPatternAdmin getRole(RelationPlayer relationPlayer) { return relationPlayer.getRole().orElseThrow(GraqlQueryException::insertRolePlayerWithoutRoleType); } @Override public Atomic mapToAtom(VarPatternAdmin var, Set<VarPatternAdmin> vars, ReasonerQuery parent) { //set varName as user defined if reified //reified if contains more properties than the RelationshipProperty itself and potential IsaProperty boolean isReified = var.getProperties() .filter(prop -> !RelationshipProperty.class.isInstance(prop)) .anyMatch(prop -> !AbstractIsaProperty.class.isInstance(prop)); VarPattern relVar = isReified? var.var().asUserDefined() : var.var(); for (RelationPlayer rp : relationPlayers()) { VarPattern rolePattern = rp.getRole().orElse(null); VarPattern rolePlayer = rp.getRolePlayer(); if (rolePattern != null){ Var roleVar = rolePattern.admin().var(); //look for indirect role definitions IdPredicate roleId = getUserDefinedIdPredicate(roleVar, vars, parent); if (roleId != null){ Concept concept = parent.tx().getConcept(roleId.getPredicate()); if(concept != null) { if (concept.isRole()) { Label roleLabel = concept.asSchemaConcept().label(); rolePattern = roleVar.label(roleLabel); } else { throw GraqlQueryException.nonRoleIdAssignedToRoleVariable(var); } } } relVar = relVar.rel(rolePattern, rolePlayer); } else relVar = relVar.rel(rolePlayer); } //isa part AbstractIsaProperty isaProp = var.getProperty(AbstractIsaProperty.class).orElse(null); IdPredicate predicate = null; //if no isa property present generate type variable Var typeVariable = isaProp != null? isaProp.type().var() : Graql.var(); //Isa present if (isaProp != null) { VarPatternAdmin isaVar = isaProp.type(); Label label = isaVar.getTypeLabel().orElse(null); if (label != null) { predicate = IdPredicate.create(typeVariable, label, parent); } else { typeVariable = isaVar.var(); predicate = getUserDefinedIdPredicate(typeVariable, vars, parent); } } ConceptId predicateId = predicate != null? predicate.getPredicate() : null; relVar = isaProp instanceof IsaExplicitProperty ? relVar.isaExplicit(typeVariable.asUserDefined()) : relVar.isa(typeVariable.asUserDefined()); return RelationshipAtom.create(relVar.admin(), typeVariable, predicateId, parent); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/RuleProperty.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.pattern.property; import ai.grakn.graql.Pattern; import ai.grakn.graql.Var; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.UniqueVarProperty; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.internal.gremlin.EquivalentFragmentSet; import ai.grakn.util.ErrorMessage; import javax.annotation.Nullable; import java.util.Collection; import java.util.Set; /** * Abstract property for the patterns within rules. * * @author Felix Chapman */ public abstract class RuleProperty extends AbstractVarProperty implements UniqueVarProperty, NamedProperty { public abstract Pattern pattern(); @Override public String getProperty() { return pattern().toString(); } @Override public Collection<EquivalentFragmentSet> match(Var start) { throw new UnsupportedOperationException(ErrorMessage.MATCH_INVALID.getMessage(this.getName())); } @Nullable @Override public Atomic mapToAtom(VarPatternAdmin var, Set<VarPatternAdmin> vars, ReasonerQuery parent) { return null; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/SubProperty.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.pattern.property; import ai.grakn.concept.ConceptId; import ai.grakn.concept.SchemaConcept; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Var; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.UniqueVarProperty; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.internal.gremlin.EquivalentFragmentSet; import ai.grakn.graql.internal.gremlin.sets.EquivalentFragmentSets; import ai.grakn.graql.internal.query.executor.ConceptBuilder; import ai.grakn.graql.internal.reasoner.atom.binary.SubAtom; import ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import java.util.Collection; import java.util.Optional; import java.util.Set; import java.util.stream.Stream; import static ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.getIdPredicate; /** * Represents the {@code sub} property on a {@link ai.grakn.concept.Type}. * * This property can be queried or inserted. * * This property relates a {@link ai.grakn.concept.Type} and another {@link ai.grakn.concept.Type}. It indicates * that every instance of the left type is also an instance of the right type. * * @author Felix Chapman */ @AutoValue public abstract class SubProperty extends AbstractVarProperty implements NamedProperty, UniqueVarProperty { public static final String NAME = "sub"; public static SubProperty of(VarPatternAdmin superType) { return new AutoValue_SubProperty(superType); } public abstract VarPatternAdmin superType(); @Override public String getName() { return NAME; } @Override public String getProperty() { return superType().getPrintableName(); } @Override public Collection<EquivalentFragmentSet> match(Var start) { return ImmutableSet.of(EquivalentFragmentSets.sub(this, start, superType().var())); } @Override public Stream<VarPatternAdmin> getTypes() { return Stream.of(superType()); } @Override public Stream<VarPatternAdmin> innerVarPatterns() { return Stream.of(superType()); } @Override public Collection<PropertyExecutor> define(Var var) throws GraqlQueryException { PropertyExecutor.Method method = executor -> { SchemaConcept superConcept = executor.get(superType().var()).asSchemaConcept(); Optional<ConceptBuilder> builder = executor.tryBuilder(var); if (builder.isPresent()) { builder.get().sub(superConcept); } else { ConceptBuilder.setSuper(executor.get(var).asSchemaConcept(), superConcept); } }; return ImmutableSet.of(PropertyExecutor.builder(method).requires(superType().var()).produces(var).build()); } @Override public Collection<PropertyExecutor> undefine(Var var) throws GraqlQueryException { PropertyExecutor.Method method = executor -> { SchemaConcept concept = executor.get(var).asSchemaConcept(); SchemaConcept expectedSuperConcept = executor.get(superType().var()).asSchemaConcept(); SchemaConcept actualSuperConcept = concept.sup(); if (!concept.isDeleted() && expectedSuperConcept.equals(actualSuperConcept)) { concept.delete(); } }; return ImmutableSet.of(PropertyExecutor.builder(method).requires(var, superType().var()).build()); } @Override public Atomic mapToAtom(VarPatternAdmin var, Set<VarPatternAdmin> vars, ReasonerQuery parent) { Var varName = var.var().asUserDefined(); VarPatternAdmin typeVar = this.superType(); Var typeVariable = typeVar.var().asUserDefined(); IdPredicate predicate = getIdPredicate(typeVariable, typeVar, vars, parent); ConceptId predicateId = predicate != null? predicate.getPredicate() : null; return SubAtom.create(varName, typeVariable, predicateId, parent); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/ThenProperty.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.pattern.property; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Pattern; import ai.grakn.graql.Var; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import java.util.Collection; /** * Represents the {@code then} (right-hand side) property on a {@link ai.grakn.concept.Rule}. * * This property can be inserted and not queried. * * The then side describes the right-hand of an implication, stating that when the when side of a rule is * true the then side must hold. * * @author Felix Chapman */ @AutoValue public abstract class ThenProperty extends RuleProperty { public static final String NAME = "then"; public static ThenProperty of(Pattern then) { return new AutoValue_ThenProperty(then); } @Override public String getName() { return NAME; } @Override public Collection<PropertyExecutor> define(Var var) throws GraqlQueryException { PropertyExecutor.Method method = executor -> { // This allows users to skip stating `$ruleVar sub rule` when they say `$ruleVar then { ... }` executor.builder(var).isRule().then(pattern()); }; return ImmutableSet.of(PropertyExecutor.builder(method).produces(var).build()); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/ValueProperty.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.pattern.property; import ai.grakn.concept.Attribute; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.ValuePredicate; import ai.grakn.graql.Var; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.internal.gremlin.EquivalentFragmentSet; import ai.grakn.graql.internal.gremlin.sets.EquivalentFragmentSets; import ai.grakn.util.CommonUtil; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import java.util.Collection; import java.util.Set; import java.util.stream.Stream; /** * Represents the {@code value} property on a {@link Attribute}. * * This property can be queried or inserted. * * This property matches only resources whose value matches the given {@link ValuePredicate}. * * @author Felix Chapman */ @AutoValue public abstract class ValueProperty extends AbstractVarProperty implements NamedProperty { public static final String NAME = ""; public static ValueProperty of(ValuePredicate predicate) { return new AutoValue_ValueProperty(predicate); } public abstract ValuePredicate predicate(); @Override public String getName() { return NAME; } @Override public String getProperty() { return predicate().toString(); } @Override public void buildString(StringBuilder builder) { builder.append(getProperty()); } @Override public Collection<EquivalentFragmentSet> match(Var start) { return ImmutableSet.of(EquivalentFragmentSets.value(this, start, predicate())); } @Override public Collection<PropertyExecutor> insert(Var var) throws GraqlQueryException { PropertyExecutor.Method method = executor -> { Object value = predicate().equalsValue().orElseThrow(GraqlQueryException::insertPredicate); executor.builder(var).value(value); }; return ImmutableSet.of(PropertyExecutor.builder(method).produces(var).build()); } @Override public Stream<VarPatternAdmin> innerVarPatterns() { return CommonUtil.optionalToStream(predicate().getInnerVar()); } @Override public Atomic mapToAtom(VarPatternAdmin var, Set<VarPatternAdmin> vars, ReasonerQuery parent) { return ai.grakn.graql.internal.reasoner.atom.predicate.ValuePredicate.create(var.var(), this.predicate(), parent); } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/VarPropertyInternal.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.pattern.property; import ai.grakn.GraknTx; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Match; import ai.grakn.graql.Var; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.admin.VarProperty; import ai.grakn.graql.internal.gremlin.EquivalentFragmentSet; import java.util.Collection; import java.util.stream.Stream; /** * Internal interface for {@link VarProperty}, providing additional methods to match, insert or define the property. * * @author Felix Chapman */ public interface VarPropertyInternal extends VarProperty { /** * Check if the given property can be used in a {@link Match} */ void checkValid(GraknTx graph, VarPatternAdmin var) throws GraqlQueryException; /** * Return a collection of {@link EquivalentFragmentSet} to match the given property in the graph */ Collection<EquivalentFragmentSet> match(Var start); /** * Returns a {@link PropertyExecutor} that describes how to insert the given {@link VarProperty} into. * * @throws GraqlQueryException if this {@link VarProperty} cannot be inserted */ Collection<PropertyExecutor> insert(Var var) throws GraqlQueryException; Collection<PropertyExecutor> define(Var var) throws GraqlQueryException; Collection<PropertyExecutor> undefine(Var var) throws GraqlQueryException; /** * Whether this property will uniquely identify a concept in the graph, if one exists. * This is used for recognising equivalent variables in insert queries. */ default boolean uniquelyIdentifiesConcept() { return false; } @Override default Stream<VarPatternAdmin> innerVarPatterns() { return Stream.empty(); } /** * Helper method to perform the safe cast into this internal type */ static VarPropertyInternal from(VarProperty varProperty) { return (VarPropertyInternal) varProperty; } }
0
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/pattern/property/WhenProperty.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.pattern.property; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Pattern; import ai.grakn.graql.Var; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import java.util.Collection; /** * Represents the {@code when} property on a {@link ai.grakn.concept.Rule}. * * This property can be inserted and not queried. * * The when side describes the left-hand of an implication, stating that when the when side of a rule is true * the then side must hold. * * @author Felix Chapman */ @AutoValue public abstract class WhenProperty extends RuleProperty { public static final String NAME = "when"; public static WhenProperty of(Pattern pattern) { return new AutoValue_WhenProperty(pattern); } @Override public String getName(){ return NAME; } @Override public Collection<PropertyExecutor> define(Var var) throws GraqlQueryException { PropertyExecutor.Method method = executor -> { // This allows users to skip stating `$ruleVar sub rule` when they say `$ruleVar when { ... }` executor.builder(var).isRule().when(pattern()); }; return ImmutableSet.of(PropertyExecutor.builder(method).produces(var).build()); } }
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/printer/JsonPrinter.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.printer; import ai.grakn.concept.Concept; import ai.grakn.concept.SchemaConcept; import ai.grakn.graql.Pattern; import ai.grakn.graql.Var; import ai.grakn.graql.answer.AnswerGroup; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.answer.ConceptSetMeasure; import ai.grakn.util.CommonUtil; import mjson.Json; import java.util.Collection; import java.util.Map; import static java.util.stream.Collectors.toList; /** * Class to print Graql Responses in to JSON Formatted Strings * * @author Grakn Warriors */ class JsonPrinter extends Printer<Json> { @Override protected final String complete(Json builder) { return builder.toString(); } @Override protected Json concept(Concept concept) { Json json = Json.object("id", concept.id().getValue()); if (concept.isSchemaConcept()) { json.set("name", concept.asSchemaConcept().label().getValue()); SchemaConcept superConcept = concept.asSchemaConcept().sup(); if (superConcept != null) json.set("sub", superConcept.label().getValue()); } else if (concept.isThing()) { json.set("isa", concept.asThing().type().label().getValue()); } else { throw CommonUtil.unreachableStatement("Unrecognised concept " + concept); } if (concept.isAttribute()) { json.set("value", concept.asAttribute().value()); } if (concept.isRule()) { Pattern when = concept.asRule().when(); if (when != null) { json.set("when", when.toString()); } Pattern then = concept.asRule().then(); if (then != null) { json.set("then", then.toString()); } } return json; } @Override protected final Json bool(boolean bool) { return Json.make(bool); } @Override public final Json collection(Collection<?> collection) { return Json.make(collection.stream().map(item -> build(item)).collect(toList())); } @Override protected final Json map(Map<?, ?> map) { Json json = Json.object(); map.forEach((Object key, Object value) -> { if (key instanceof Var) key = ((Var) key).getValue(); String keyString = key == null ? "" : key.toString(); json.set(keyString, build(value)); }); return json; } @Override protected Json answerGroup(AnswerGroup<?> answer) { Json json = Json.object(); json.set(answer.toString(), build(answer.answers())); return json; } @Override protected Json conceptMap(ConceptMap answer) { return map(answer.map()); } @Override protected Json conceptSetMeasure(ConceptSetMeasure answer) { Json json = Json.object(); json.set(answer.measurement().toString(), collection(answer.set())); return json; } @Override protected final Json object(Object object) { return Json.make(object); } }
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/printer/Printer.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.printer; import ai.grakn.concept.AttributeType; import ai.grakn.concept.Concept; import ai.grakn.graql.answer.AnswerGroup; import ai.grakn.graql.answer.ConceptList; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.answer.ConceptSet; import ai.grakn.graql.answer.ConceptSetMeasure; import ai.grakn.graql.answer.Value; import mjson.Json; import javax.annotation.CheckReturnValue; import java.util.Collection; import java.util.Map; import java.util.stream.Stream; /** * An interface for print objects in Graql responses (e.g. {@link Integer}s and {@link ConceptMap}s into a String). * The intermediate {@link Builder} type is used when the final type is different to the "in-progress" type when * creating it. For example, you may want to use a {@link StringBuilder} for {@link Builder} (for efficiency). * * If you don't need a {@link Builder} type, then set it to the same type as String and implement * {@link #complete(Builder)} to just return its argument. * * @param <Builder> An intermediate builder type that can be changed into a String * @author Grakn Warriors */ public abstract class Printer<Builder> { /** * Constructs a special type of Printer: StringPrinter * * @param colorize boolean parameter to determine if the String output should be colorized * @param attributeTypes list of attribute types that should be included in the String output * @return a new StringPrinter object */ public static Printer<StringBuilder> stringPrinter(boolean colorize, AttributeType... attributeTypes) { return new StringPrinter(colorize, attributeTypes); } /** * Constructs a special type of Printer: JsonPrinter * * @return a new JsonPrinter object */ public static Printer<Json> jsonPrinter() { return new JsonPrinter(); } /** * Convert a stream of objects into a stream of Strings to be printed * * @param objects the objects to be printed * @return the stream of String print output for the object */ public Stream<String> toStream(Stream<?> objects) { if (objects == null) return Stream.empty(); return objects.map(this::toString); } /** * Convert any object into a String to be printed * * @param object the object to be printed * @return the String print output for the object */ @CheckReturnValue public String toString(Object object) { Builder builder = build(object); return complete(builder); } /** * Convert any object into its print builder * * @param object the object to convert into its print builder * @return the object as a builder */ @CheckReturnValue protected Builder build(Object object) { if (object instanceof Concept) { return concept((Concept) object); } else if (object instanceof Boolean) { return bool((boolean) object); } else if (object instanceof Collection) { return collection((Collection<?>) object); } else if (object instanceof AnswerGroup<?>) { return answerGroup((AnswerGroup<?>) object); } else if (object instanceof ConceptList) { return conceptList((ConceptList) object); } else if (object instanceof ConceptMap) { return conceptMap((ConceptMap) object); } else if (object instanceof ConceptSet) { if (object instanceof ConceptSetMeasure) { return conceptSetMeasure((ConceptSetMeasure) object); } else { return conceptSet((ConceptSet) object); } } else if (object instanceof Value) { return value((Value) object); } else if (object instanceof Map) { return map((Map<?, ?>) object); } else { return object(object); } } /** * Convert a builder into the final type * * @param builder the builder to convert into the final type * @return the converted builder */ @CheckReturnValue protected abstract String complete(Builder builder); /** * Convert any concept into its print builder * * @param concept the concept to convert into its print builder * @return the concept as a builder */ @CheckReturnValue protected abstract Builder concept(Concept concept); /** * Convert any boolean into its print builder * * @param bool the boolean to convert into its print builder * @return the boolean as a builder */ @CheckReturnValue protected abstract Builder bool(boolean bool); /** * Convert any collection into its print builder * * @param collection the collection to convert into its print builder * @return the collection as a builder */ @CheckReturnValue protected abstract Builder collection(Collection<?> collection); /** * Convert any map into its print builder * * @param map the map to convert into its print builder * @return the map as a builder */ @CheckReturnValue protected abstract Builder map(Map<?, ?> map); /** * Convert any {@link AnswerGroup} into its print builder * * @param answer is the answer result of a Graql Compute queries * @return the grouped answers as an output builder */ @CheckReturnValue protected abstract Builder answerGroup(AnswerGroup<?> answer); /** * Convert any {@link ConceptList} into its print builder * * @param answer is the answer result of a Graql Compute queries * @return the concept list as an output builder */ @CheckReturnValue protected Builder conceptList(ConceptList answer) { return collection(answer.list()); } /** * Convert any {@link ConceptMap} into its print builder * * @param answer is the answer result of a Graql Compute queries * @return the concept map as an output builder */ @CheckReturnValue protected abstract Builder conceptMap(ConceptMap answer); /** * Convert any {@link ConceptSet} into its print builder * * @param answer is the answer result of a Graql Compute queries * @return the concept set as an output builder */ @CheckReturnValue protected Builder conceptSet(ConceptSet answer) { return collection(answer.set()); } /** * Convert any {@link ConceptSetMeasure} into its print builder * * @param answer is the answer result of a Graql Compute queries * @return the concept set measure as an output builder */ @CheckReturnValue protected abstract Builder conceptSetMeasure(ConceptSetMeasure answer); /** * Convert any {@link Value} into its print builder * * @param answer is the answer result of a Graql Compute queries * @return the number as an output builder */ @CheckReturnValue protected Builder value(Value answer) { return object(answer.number()); } /** * Default conversion behaviour if none of the more specific methods can be used * * @param object the object to convert into its print builder * @return the object as a builder */ @CheckReturnValue protected abstract Builder object(Object object); }
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/printer/StringPrinter.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.printer; import ai.grakn.concept.AttributeType; import ai.grakn.concept.Concept; import ai.grakn.concept.Role; import ai.grakn.concept.SchemaConcept; import ai.grakn.concept.Thing; import ai.grakn.concept.Type; import ai.grakn.graql.answer.AnswerGroup; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.answer.ConceptSetMeasure; import ai.grakn.graql.internal.util.ANSI; import ai.grakn.util.StringUtil; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import static ai.grakn.graql.internal.util.StringConverter.idToString; import static ai.grakn.graql.internal.util.StringConverter.typeLabelToString; /** * Default printer that prints results in Graql syntax * * @author Grakn Warriors */ class StringPrinter extends Printer<StringBuilder> { private final AttributeType[] attributeTypes; private final boolean colorize; StringPrinter(boolean colorize, AttributeType... attributeTypes) { this.colorize = colorize; this.attributeTypes = attributeTypes; } @Override protected String complete(StringBuilder output) { return output.toString(); } @Override protected StringBuilder concept(Concept concept) { StringBuilder output = new StringBuilder(); // Display values for resources and ids for everything else if (concept.isAttribute()) { output.append(colorKeyword("val ")).append(StringUtil.valueToString(concept.asAttribute().value())); } else if (concept.isSchemaConcept()) { SchemaConcept ontoConcept = concept.asSchemaConcept(); output.append(colorKeyword("label ")).append(colorType(ontoConcept)); SchemaConcept superConcept = ontoConcept.sup(); if (superConcept != null) { output.append(colorKeyword(" sub ")).append(colorType(superConcept)); } } else { output.append(colorKeyword("id ")).append(idToString(concept.id())); } if (concept.isRelationship()) { List<String> rolePlayerList = new LinkedList<>(); for (Map.Entry<Role, Set<Thing>> rolePlayers : concept.asRelationship().rolePlayersMap().entrySet()) { Role role = rolePlayers.getKey(); Set<Thing> things = rolePlayers.getValue(); for (Thing thing : things) { rolePlayerList.add(colorType(role) + ": id " + idToString(thing.id())); } } String relationString = rolePlayerList.stream().collect(Collectors.joining(", ")); output.append(" (").append(relationString).append(")"); } // Display type of each instance if (concept.isThing()) { Type type = concept.asThing().type(); output.append(colorKeyword(" isa ")).append(colorType(type)); } // Display when and then for rules if (concept.isRule()) { output.append(colorKeyword(" when ")).append("{ ").append(concept.asRule().when()).append(" }"); output.append(colorKeyword(" then ")).append("{ ").append(concept.asRule().then()).append(" }"); } // Display any requested resources if (concept.isThing() && attributeTypes.length > 0) { concept.asThing().attributes(attributeTypes).forEach(resource -> { String resourceType = colorType(resource.type()); String value = StringUtil.valueToString(resource.value()); output.append(colorKeyword(" has ")).append(resourceType).append(" ").append(value); }); } return output; } @Override protected StringBuilder bool(boolean bool) { StringBuilder builder = new StringBuilder(); if (bool) { return builder.append(ANSI.color("true", ANSI.GREEN)); } else { return builder.append(ANSI.color("false", ANSI.RED)); } } @Override protected StringBuilder collection(Collection<?> collection) { StringBuilder builder = new StringBuilder(); builder.append("{"); collection.stream().findFirst().ifPresent(item -> builder.append(build(item))); collection.stream().skip(1).forEach(item -> builder.append(", ").append(build(item))); builder.append("}"); return builder; } @Override protected StringBuilder map(Map<?, ?> map) { return collection(map.entrySet()); } @Override protected StringBuilder answerGroup(AnswerGroup<?> answer) { StringBuilder builder = new StringBuilder(); return builder.append('{') .append(concept(answer.owner())) .append(": ") .append(build(answer.answers())) .append('}'); } @Override protected StringBuilder conceptMap(ConceptMap answer) { StringBuilder builder = new StringBuilder(); answer.forEach((name, concept) -> builder.append(name).append(" ").append(concept(concept)).append("; ")); return new StringBuilder("{" + builder.toString().trim() + "}"); } @Override protected StringBuilder conceptSetMeasure(ConceptSetMeasure answer) { StringBuilder builder = new StringBuilder(); return builder.append(answer.measurement()).append(": ").append(collection(answer.set())); } @Override protected StringBuilder object(Object object) { StringBuilder builder = new StringBuilder(); if (object instanceof Map.Entry<?, ?>) { Map.Entry<?, ?> entry = (Map.Entry<?, ?>) object; builder.append(build(entry.getKey())); builder.append(": "); builder.append(build(entry.getValue())); } else if (object != null) { builder.append(Objects.toString(object)); } return builder; } /** * Color-codes the keyword if colorization enabled * @param keyword a keyword to color-code using ANSI colors * @return the keyword, color-coded */ private String colorKeyword(String keyword) { if(colorize) { return ANSI.color(keyword, ANSI.BLUE); } else { return keyword; } } /** * Color-codes the given type if colorization enabled * @param schemaConcept a type to color-code using ANSI colors * @return the type, color-coded */ private String colorType(SchemaConcept schemaConcept) { if(colorize) { return ANSI.color(typeLabelToString(schemaConcept.label()), ANSI.PURPLE); } else { return typeLabelToString(schemaConcept.label()); } } }
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/query/AggregateQueryImpl.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; import ai.grakn.GraknTx; import ai.grakn.graql.Aggregate; import ai.grakn.graql.AggregateQuery; import ai.grakn.graql.Match; import ai.grakn.graql.answer.Answer; import com.google.auto.value.AutoValue; import java.util.stream.Stream; /** * Implementation of AggregateQuery * @param <T> the type of the aggregate result */ @AutoValue abstract class AggregateQueryImpl<T extends Answer> implements AggregateQuery<T> { public static <T extends Answer> AggregateQueryImpl<T> of(Match match, Aggregate<T> aggregate) { return new AutoValue_AggregateQueryImpl<>(match, aggregate); } @Override public final AggregateQuery<T> withTx(GraknTx tx) { return Queries.aggregate(match().withTx(tx).admin(), aggregate()); } @Override public final Stream<T> stream() { return executor().run(this); } @Override public boolean isReadOnly() { //TODO An aggregate query may modify the graph if using a user-defined aggregate method. See TP # 13731. return true; } @Override public final GraknTx tx() { return match().admin().tx(); } @Override public final String toString() { return match().toString() + " aggregate " + aggregate().toString() + ";"; } @Override public final Boolean inferring() { return match().admin().inferring(); } }
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/query/AutoValue_AggregateQueryImpl.java
package ai.grakn.graql.internal.query; import ai.grakn.graql.Aggregate; import ai.grakn.graql.Match; import ai.grakn.graql.answer.Answer; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_AggregateQueryImpl<T extends Answer> extends AggregateQueryImpl<T> { private final Match match; private final Aggregate<T> aggregate; AutoValue_AggregateQueryImpl( @Nullable Match match, Aggregate<T> aggregate) { this.match = match; if (aggregate == null) { throw new NullPointerException("Null aggregate"); } this.aggregate = aggregate; } @Nullable @Override public Match match() { return match; } @Override public Aggregate<T> aggregate() { return aggregate; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof AggregateQueryImpl) { AggregateQueryImpl<?> that = (AggregateQueryImpl<?>) o; return ((this.match == null) ? (that.match() == null) : this.match.equals(that.match())) && (this.aggregate.equals(that.aggregate())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= (match == null) ? 0 : this.match.hashCode(); h *= 1000003; h ^= this.aggregate.hashCode(); return h; } }
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/query/AutoValue_DefineQueryImpl.java
package ai.grakn.graql.internal.query; import ai.grakn.GraknTx; import ai.grakn.graql.VarPattern; import java.util.Collection; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_DefineQueryImpl extends DefineQueryImpl { private final GraknTx tx; private final Collection<? extends VarPattern> varPatterns; AutoValue_DefineQueryImpl( @Nullable GraknTx tx, Collection<? extends VarPattern> varPatterns) { this.tx = tx; if (varPatterns == null) { throw new NullPointerException("Null varPatterns"); } this.varPatterns = varPatterns; } @Nullable @Override public GraknTx tx() { return tx; } @Override public Collection<? extends VarPattern> varPatterns() { return varPatterns; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof DefineQueryImpl) { DefineQueryImpl that = (DefineQueryImpl) o; return ((this.tx == null) ? (that.tx() == null) : this.tx.equals(that.tx())) && (this.varPatterns.equals(that.varPatterns())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= (tx == null) ? 0 : this.tx.hashCode(); h *= 1000003; h ^= this.varPatterns.hashCode(); return h; } }
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/query/AutoValue_DeleteQueryImpl.java
package ai.grakn.graql.internal.query; import ai.grakn.graql.Match; import ai.grakn.graql.Var; import java.util.Set; import javax.annotation.CheckReturnValue; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_DeleteQueryImpl extends DeleteQueryImpl { private final Match match; private final Set<Var> vars; AutoValue_DeleteQueryImpl( Match match, Set<Var> vars) { if (match == null) { throw new NullPointerException("Null match"); } this.match = match; if (vars == null) { throw new NullPointerException("Null vars"); } this.vars = vars; } @CheckReturnValue @Override public Match match() { return match; } @CheckReturnValue @Override public Set<Var> vars() { return vars; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof DeleteQueryImpl) { DeleteQueryImpl that = (DeleteQueryImpl) o; return (this.match.equals(that.match())) && (this.vars.equals(that.vars())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.match.hashCode(); h *= 1000003; h ^= this.vars.hashCode(); return h; } }
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/query/AutoValue_GetQueryImpl.java
package ai.grakn.graql.internal.query; import ai.grakn.graql.Match; import ai.grakn.graql.Var; import com.google.common.collect.ImmutableSet; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_GetQueryImpl extends GetQueryImpl { private final ImmutableSet<Var> vars; private final Match match; AutoValue_GetQueryImpl( ImmutableSet<Var> vars, Match match) { if (vars == null) { throw new NullPointerException("Null vars"); } this.vars = vars; if (match == null) { throw new NullPointerException("Null match"); } this.match = match; } @Override public ImmutableSet<Var> vars() { return vars; } @Override public Match match() { return match; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof GetQueryImpl) { GetQueryImpl that = (GetQueryImpl) o; return (this.vars.equals(that.vars())) && (this.match.equals(that.match())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.vars.hashCode(); h *= 1000003; h ^= this.match.hashCode(); return h; } }
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/query/AutoValue_InsertQueryImpl.java
package ai.grakn.graql.internal.query; import ai.grakn.GraknTx; import ai.grakn.graql.Match; import ai.grakn.graql.admin.VarPatternAdmin; import java.util.Collection; import javax.annotation.CheckReturnValue; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_InsertQueryImpl extends InsertQueryImpl { private final GraknTx tx; private final Match match; private final Collection<VarPatternAdmin> varPatterns; AutoValue_InsertQueryImpl( @Nullable GraknTx tx, @Nullable Match match, Collection<VarPatternAdmin> varPatterns) { this.tx = tx; this.match = match; if (varPatterns == null) { throw new NullPointerException("Null varPatterns"); } this.varPatterns = varPatterns; } @Nullable @Override public GraknTx tx() { return tx; } @Nullable @CheckReturnValue @Override public Match match() { return match; } @CheckReturnValue @Override public Collection<VarPatternAdmin> varPatterns() { return varPatterns; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof InsertQueryImpl) { InsertQueryImpl that = (InsertQueryImpl) o; return ((this.tx == null) ? (that.tx() == null) : this.tx.equals(that.tx())) && ((this.match == null) ? (that.match() == null) : this.match.equals(that.match())) && (this.varPatterns.equals(that.varPatterns())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= (tx == null) ? 0 : this.tx.hashCode(); h *= 1000003; h ^= (match == null) ? 0 : this.match.hashCode(); h *= 1000003; h ^= this.varPatterns.hashCode(); return h; } }
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/query/AutoValue_UndefineQueryImpl.java
package ai.grakn.graql.internal.query; import ai.grakn.GraknTx; import ai.grakn.graql.VarPattern; import java.util.Collection; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_UndefineQueryImpl extends UndefineQueryImpl { private final GraknTx tx; private final Collection<? extends VarPattern> varPatterns; AutoValue_UndefineQueryImpl( @Nullable GraknTx tx, Collection<? extends VarPattern> varPatterns) { this.tx = tx; if (varPatterns == null) { throw new NullPointerException("Null varPatterns"); } this.varPatterns = varPatterns; } @Nullable @Override public GraknTx tx() { return tx; } @Override public Collection<? extends VarPattern> varPatterns() { return varPatterns; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof UndefineQueryImpl) { UndefineQueryImpl that = (UndefineQueryImpl) o; return ((this.tx == null) ? (that.tx() == null) : this.tx.equals(that.tx())) && (this.varPatterns.equals(that.varPatterns())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= (tx == null) ? 0 : this.tx.hashCode(); h *= 1000003; h ^= this.varPatterns.hashCode(); return h; } }
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/query/ComputeQueryImpl.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; import ai.grakn.ComputeExecutor; import ai.grakn.GraknTx; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Label; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.ComputeQuery; import ai.grakn.graql.answer.Answer; import ai.grakn.graql.internal.util.StringConverter; import com.google.common.collect.ImmutableSet; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import static ai.grakn.util.CommonUtil.toImmutableSet; import static ai.grakn.util.GraqlSyntax.Char.COMMA_SPACE; import static ai.grakn.util.GraqlSyntax.Char.EQUAL; import static ai.grakn.util.GraqlSyntax.Char.QUOTE; import static ai.grakn.util.GraqlSyntax.Char.SEMICOLON; import static ai.grakn.util.GraqlSyntax.Char.SPACE; import static ai.grakn.util.GraqlSyntax.Char.SQUARE_CLOSE; import static ai.grakn.util.GraqlSyntax.Char.SQUARE_OPEN; import static ai.grakn.util.GraqlSyntax.Command.COMPUTE; import static ai.grakn.util.GraqlSyntax.Compute.ALGORITHMS_ACCEPTED; import static ai.grakn.util.GraqlSyntax.Compute.ALGORITHMS_DEFAULT; import static ai.grakn.util.GraqlSyntax.Compute.ARGUMENTS_ACCEPTED; import static ai.grakn.util.GraqlSyntax.Compute.ARGUMENTS_DEFAULT; import static ai.grakn.util.GraqlSyntax.Compute.Algorithm; import static ai.grakn.util.GraqlSyntax.Compute.Argument; import static ai.grakn.util.GraqlSyntax.Compute.CONDITIONS_ACCEPTED; import static ai.grakn.util.GraqlSyntax.Compute.CONDITIONS_REQUIRED; import static ai.grakn.util.GraqlSyntax.Compute.Condition; import static ai.grakn.util.GraqlSyntax.Compute.Condition.FROM; import static ai.grakn.util.GraqlSyntax.Compute.Condition.IN; import static ai.grakn.util.GraqlSyntax.Compute.Condition.OF; import static ai.grakn.util.GraqlSyntax.Compute.Condition.TO; import static ai.grakn.util.GraqlSyntax.Compute.Condition.USING; import static ai.grakn.util.GraqlSyntax.Compute.Condition.WHERE; import static ai.grakn.util.GraqlSyntax.Compute.INCLUDE_ATTRIBUTES_DEFAULT; import static ai.grakn.util.GraqlSyntax.Compute.Method; import static ai.grakn.util.GraqlSyntax.Compute.Parameter; import static ai.grakn.util.GraqlSyntax.Compute.Parameter.CONTAINS; import static ai.grakn.util.GraqlSyntax.Compute.Parameter.K; import static ai.grakn.util.GraqlSyntax.Compute.Parameter.MIN_K; import static ai.grakn.util.GraqlSyntax.Compute.Parameter.SIZE; import static java.util.stream.Collectors.joining; /** * Graql Compute Query: to perform distributed analytics OLAP computation on Grakn * @param <T> return type of ComputeQuery */ public class ComputeQueryImpl<T extends Answer> implements ComputeQuery<T> { private GraknTx tx; private Set<ComputeExecutor> runningJobs = ConcurrentHashMap.newKeySet(); private Method method; private boolean includeAttributes; // All these condition properties need to start off as NULL, they will be initialised when the user provides input private ConceptId fromID = null; private ConceptId toID = null; private Set<Label> ofTypes = null; private Set<Label> inTypes = null; private Algorithm algorithm = null; private ArgumentsImpl arguments = null; // But arguments will also be set when where() is called for cluster/centrality private final Map<Condition, Supplier<Optional<?>>> conditionsMap = setConditionsMap(); public ComputeQueryImpl(GraknTx tx, Method<T> method) { this(tx, method, INCLUDE_ATTRIBUTES_DEFAULT.get(method)); } public ComputeQueryImpl(GraknTx tx, Method method, boolean includeAttributes) { this.method = method; this.tx = tx; this.includeAttributes = includeAttributes; } private Map<Condition, Supplier<Optional<?>>> setConditionsMap() { Map<Condition, Supplier<Optional<?>>> conditions = new HashMap<>(); conditions.put(FROM, this::from); conditions.put(TO, this::to); conditions.put(OF, this::of); conditions.put(IN, this::in); conditions.put(USING, this::using); conditions.put(WHERE, this::where); return conditions; } @Override public final Stream<T> stream() { Optional<GraqlQueryException> exception = getException(); if (exception.isPresent()) throw exception.get(); ComputeExecutor<T> job = executor().run(this); runningJobs.add(job); try { return job.stream(); } finally { runningJobs.remove(job); } } @Override public final void kill() { runningJobs.forEach(ComputeExecutor::kill); } @Override public final ComputeQuery<T> withTx(GraknTx tx) { this.tx = tx; return this; } @Override public final GraknTx tx() { return tx; } @Override public final Method method() { return method; } @Override public final ComputeQuery<T> from(ConceptId fromID) { this.fromID = fromID; return this; } @Override public final Optional<ConceptId> from() { return Optional.ofNullable(fromID); } @Override public final ComputeQuery<T> to(ConceptId toID) { this.toID = toID; return this; } @Override public final Optional<ConceptId> to() { return Optional.ofNullable(toID); } @Override public final ComputeQuery<T> of(String type, String... types) { ArrayList<String> typeList = new ArrayList<>(types.length + 1); typeList.add(type); typeList.addAll(Arrays.asList(types)); return of(typeList.stream().map(Label::of).collect(toImmutableSet())); } @Override public final ComputeQuery<T> of(Collection<Label> types) { this.ofTypes = ImmutableSet.copyOf(types); return this; } @Override public final Optional<Set<Label>> of() { return Optional.ofNullable(ofTypes); } @Override public final ComputeQuery<T> in(String type, String... types) { ArrayList<String> typeList = new ArrayList<>(types.length + 1); typeList.add(type); typeList.addAll(Arrays.asList(types)); return in(typeList.stream().map(Label::of).collect(toImmutableSet())); } @Override public final ComputeQuery<T> in(Collection<Label> types) { this.inTypes = ImmutableSet.copyOf(types); return this; } @Override public final Optional<Set<Label>> in() { if (this.inTypes == null) return Optional.of(ImmutableSet.of()); return Optional.of(this.inTypes); } @Override public final ComputeQuery<T> using(Algorithm algorithm) { this.algorithm = algorithm; return this; } @Override public final Optional<Algorithm> using() { if (ALGORITHMS_DEFAULT.containsKey(method) && algorithm == null) return Optional.of(ALGORITHMS_DEFAULT.get(method)); return Optional.ofNullable(algorithm); } @Override public final ComputeQuery<T> where(Argument arg, Argument... args) { ArrayList<Argument> argList = new ArrayList(args.length + 1); argList.add(arg); argList.addAll(Arrays.asList(args)); return this.where(argList); } @Override public final ComputeQuery<T> where(Collection<Argument> args) { if (this.arguments == null) this.arguments = new ArgumentsImpl(); for (Argument arg : args) this.arguments.setArgument(arg); return this; } @Override public final Optional<Arguments> where() { if (ARGUMENTS_DEFAULT.containsKey(method) && arguments == null) arguments = new ArgumentsImpl(); return Optional.ofNullable(this.arguments); } @Override public final ComputeQueryImpl includeAttributes(boolean include) { this.includeAttributes = include; return this; } @Override public final boolean includesAttributes() { return includeAttributes; } @Override public final Boolean inferring() { return false; } @Override public final boolean isValid() { return !getException().isPresent(); } @Override public Optional<GraqlQueryException> getException() { // Check that all required conditions for the current query method are provided for (Condition condition : collect(CONDITIONS_REQUIRED.get(this.method()))) { if (!this.conditionsMap.get(condition).get().isPresent()) { return Optional.of(GraqlQueryException.invalidComputeQuery_missingCondition(this.method())); } } // Check that all the provided conditions are accepted for the current query method for (Condition condition : this.conditionsMap.keySet().stream() .filter(con -> this.conditionsMap.get(con).get().isPresent()) .collect(Collectors.toSet())) { if (!CONDITIONS_ACCEPTED.get(this.method()).contains(condition)) { return Optional.of(GraqlQueryException.invalidComputeQuery_invalidCondition(this.method())); } } // Check that the provided algorithm is accepted for the current query method if (ALGORITHMS_ACCEPTED.containsKey(this.method()) && !ALGORITHMS_ACCEPTED.get(this.method()).contains(this.using().get())) { return Optional.of(GraqlQueryException.invalidComputeQuery_invalidMethodAlgorithm(this.method())); } // Check that the provided arguments are accepted for the current query method and algorithm if (this.where().isPresent()) { for (Parameter param : this.where().get().getParameters()) { if (!ARGUMENTS_ACCEPTED.get(this.method()).get(this.using().get()).contains(param)) { return Optional.of(GraqlQueryException.invalidComputeQuery_invalidArgument(this.method(), this.using().get())); } } } return Optional.empty(); } private <T> Collection<T> collect(Collection<T> collection) { return collection != null ? collection : Collections.emptyList(); } @Override public final String toString() { StringBuilder query = new StringBuilder(); query.append(str(COMPUTE, SPACE, method)); if (!conditionsSyntax().isEmpty()) query.append(str(SPACE, conditionsSyntax())); query.append(SEMICOLON); return query.toString(); } private String conditionsSyntax() { List<String> conditionsList = new ArrayList<>(); // It is important that check for whether each condition is NULL, rather than using the getters. // Because, we want to know the user provided conditions, rather than the default conditions from the getters. // The exception is for arguments. It needs to be set internally for the query object to have default argument // values. However, we can query for .getParameters() to get user provided argument parameters. if (fromID != null) conditionsList.add(str(FROM, SPACE, QUOTE, fromID, QUOTE)); if (toID != null) conditionsList.add(str(TO, SPACE, QUOTE, toID, QUOTE)); if (ofTypes != null) conditionsList.add(ofSyntax()); if (inTypes != null) conditionsList.add(inSyntax()); if (algorithm != null) conditionsList.add(algorithmSyntax()); if (arguments != null && !arguments.getParameters().isEmpty()) conditionsList.add(argumentsSyntax()); return conditionsList.stream().collect(joining(COMMA_SPACE.toString())); } private String ofSyntax() { if (ofTypes != null) return str(OF, SPACE, typesSyntax(ofTypes)); return ""; } private String inSyntax() { if (inTypes != null) return str(IN, SPACE, typesSyntax(inTypes)); return ""; } private String typesSyntax(Set<Label> types) { StringBuilder inTypesString = new StringBuilder(); if (!types.isEmpty()) { if (types.size() == 1) inTypesString.append(StringConverter.typeLabelToString(types.iterator().next())); else { inTypesString.append(SQUARE_OPEN); inTypesString.append(inTypes.stream().map(StringConverter::typeLabelToString).collect(joining(COMMA_SPACE.toString()))); inTypesString.append(SQUARE_CLOSE); } } return inTypesString.toString(); } private String algorithmSyntax() { if (algorithm != null) return str(USING, SPACE, algorithm); return ""; } private String argumentsSyntax() { if (arguments == null) return ""; List<String> argumentsList = new ArrayList<>(); StringBuilder argumentsString = new StringBuilder(); for (Parameter param : arguments.getParameters()) { argumentsList.add(str(param, EQUAL, arguments.getArgument(param).get())); } if (!argumentsList.isEmpty()) { argumentsString.append(str(WHERE, SPACE)); if (argumentsList.size() == 1) argumentsString.append(argumentsList.get(0)); else { argumentsString.append(SQUARE_OPEN); argumentsString.append(argumentsList.stream().collect(joining(COMMA_SPACE.toString()))); argumentsString.append(SQUARE_CLOSE); } } return argumentsString.toString(); } private String str(Object... objects) { StringBuilder builder = new StringBuilder(); for (Object obj : objects) builder.append(obj.toString()); return builder.toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ComputeQuery<?> that = (ComputeQuery<?>) o; return (Objects.equals(this.tx(), that.tx()) && this.method().equals(that.method()) && this.from().equals(that.from()) && this.to().equals(that.to()) && this.of().equals(that.of()) && this.in().equals(that.in()) && this.using().equals(that.using()) && this.where().equals(that.where()) && this.includesAttributes() == that.includesAttributes()); } @Override public int hashCode() { int result = tx.hashCode(); result = 31 * result + Objects.hashCode(method); result = 31 * result + Objects.hashCode(fromID); result = 31 * result + Objects.hashCode(toID); result = 31 * result + Objects.hashCode(ofTypes); result = 31 * result + Objects.hashCode(inTypes); result = 31 * result + Objects.hashCode(algorithm); result = 31 * result + Objects.hashCode(arguments); result = 31 * result + Objects.hashCode(includeAttributes); return result; } /** * Argument inner class to provide access Compute Query arguments * * @author Grakn Warriors */ public class ArgumentsImpl implements Arguments { private LinkedHashMap<Parameter, Argument> argumentsOrdered = new LinkedHashMap<>(); private final Map<Parameter, Supplier<Optional<?>>> argumentsMap = setArgumentsMap(); private Map<Parameter, Supplier<Optional<?>>> setArgumentsMap() { Map<Parameter, Supplier<Optional<?>>> arguments = new HashMap<>(); arguments.put(MIN_K, this::minK); arguments.put(K, this::k); arguments.put(SIZE, this::size); arguments.put(CONTAINS, this::contains); return arguments; } private void setArgument(Argument arg) { argumentsOrdered.remove(arg.type()); argumentsOrdered.put(arg.type(), arg); } @Override public Optional<?> getArgument(Parameter param) { return argumentsMap.get(param).get(); } @Override public Collection<Parameter> getParameters() { return argumentsOrdered.keySet(); } @Override public Optional<Long> minK() { Object defaultArg = getDefaultArgument(MIN_K); if (defaultArg != null) return Optional.of((Long) defaultArg); return Optional.ofNullable((Long) getArgumentValue(MIN_K)); } @Override public Optional<Long> k() { Object defaultArg = getDefaultArgument(K); if (defaultArg != null) return Optional.of((Long) defaultArg); return Optional.ofNullable((Long) getArgumentValue(K)); } @Override public Optional<Long> size() { return Optional.ofNullable((Long) getArgumentValue(SIZE)); } @Override public Optional<ConceptId> contains() { return Optional.ofNullable((ConceptId) getArgumentValue(CONTAINS)); } private Object getArgumentValue(Parameter param) { return argumentsOrdered.get(param) != null ? argumentsOrdered.get(param).get() : null; } private Object getDefaultArgument(Parameter param) { if (ARGUMENTS_DEFAULT.containsKey(method) && ARGUMENTS_DEFAULT.get(method).containsKey(algorithm) && ARGUMENTS_DEFAULT.get(method).get(algorithm).containsKey(param) && !argumentsOrdered.containsKey(param)) { return ARGUMENTS_DEFAULT.get(method).get(algorithm).get(param); } return null; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ArgumentsImpl that = (ArgumentsImpl) o; return (this.minK().equals(that.minK()) && this.k().equals(that.k()) && this.size().equals(that.size()) && this.contains().equals(that.contains())); } @Override public int hashCode() { int result = tx.hashCode(); result = 31 * result + argumentsOrdered.hashCode(); return result; } } }
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/query/DefineQueryImpl.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; import ai.grakn.GraknTx; import ai.grakn.graql.DefineQuery; import ai.grakn.graql.Query; import ai.grakn.graql.VarPattern; import ai.grakn.graql.answer.ConceptMap; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import javax.annotation.Nullable; import java.util.Collection; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Implementation for {@link DefineQuery} */ @AutoValue abstract class DefineQueryImpl implements DefineQuery { static DefineQueryImpl of(Collection<? extends VarPattern> varPatterns, @Nullable GraknTx tx) { return new AutoValue_DefineQueryImpl(tx, ImmutableList.copyOf(varPatterns)); } @Override public Query<ConceptMap> withTx(GraknTx tx) { return DefineQueryImpl.of(varPatterns(), tx); } @Override public final Stream<ConceptMap> stream() { return executor().run(this); } @Override public boolean isReadOnly() { return false; } @Override public String toString() { return "define " + varPatterns().stream().map(v -> v + ";").collect(Collectors.joining("\n")).trim(); } @Override public Boolean inferring() { 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/query/DeleteQueryImpl.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; import ai.grakn.GraknTx; import ai.grakn.graql.DeleteQuery; import ai.grakn.graql.Match; import ai.grakn.graql.Var; import ai.grakn.graql.admin.DeleteQueryAdmin; import ai.grakn.graql.answer.ConceptSet; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import java.util.Collection; import java.util.stream.Stream; import static java.util.stream.Collectors.joining; /** * A {@link DeleteQuery} that will execute deletions for every result of a {@link Match} * * @author Grakn Warriors */ @AutoValue abstract class DeleteQueryImpl implements DeleteQueryAdmin { /** * @param vars a collection of variables to delete * @param match a pattern to match and delete for each result */ static DeleteQueryImpl of(Collection<? extends Var> vars, Match match) { return new AutoValue_DeleteQueryImpl(match, ImmutableSet.copyOf(vars)); } @Override public Stream<ConceptSet> stream() { return executor().run(this); } @Override public final boolean isReadOnly() { return false; } @Override public final GraknTx tx() { return match().admin().tx(); } @Override public DeleteQuery withTx(GraknTx tx) { return Queries.delete(match().withTx(tx).admin(), vars()); } @Override public DeleteQueryAdmin admin() { return this; } @Override public String toString() { StringBuilder query = new StringBuilder(); query.append(match()).append(" ").append("delete"); if(!vars().isEmpty()) query.append(" ").append(vars().stream().map(Var::toString).collect(joining(", ")).trim()); query.append(";"); return query.toString(); } @Override public final Boolean inferring() { return match().admin().inferring(); } }
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/query/GetQueryImpl.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; import ai.grakn.GraknTx; import ai.grakn.graql.GetQuery; import ai.grakn.graql.Match; import ai.grakn.graql.Var; import ai.grakn.graql.answer.ConceptMap; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import java.util.stream.Stream; import static java.util.stream.Collectors.joining; /** * Default implementation of {@link GetQuery} * * @author Grakn Warriors */ @AutoValue public abstract class GetQueryImpl implements GetQuery { public abstract ImmutableSet<Var> vars(); public abstract Match match(); public static GetQueryImpl of(Match match, ImmutableSet<Var> vars) { return new AutoValue_GetQueryImpl(vars, match); } @Override public GetQuery withTx(GraknTx tx) { return Queries.get(match().withTx(tx).admin(), vars()); } @Override public final GraknTx tx() { return match().admin().tx(); } @Override public boolean isReadOnly() { return true; } @Override public final Stream<ConceptMap> stream() { return executor().run(this); } @Override public String toString() { return match().toString() + " get " + vars().stream().map(Object::toString).collect(joining(", ")) + ";"; } @Override public final Boolean inferring() { return match().admin().inferring(); } }
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/query/InsertQueryImpl.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; import ai.grakn.GraknTx; import ai.grakn.concept.SchemaConcept; import ai.grakn.concept.Type; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.InsertQuery; import ai.grakn.graql.Match; import ai.grakn.graql.admin.InsertQueryAdmin; import ai.grakn.graql.admin.MatchAdmin; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.util.CommonUtil; import com.google.auto.value.AutoValue; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import java.util.Collection; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; /** * A query that will insert a collection of variables into a graph * * @author Grakn Warriors */ @AutoValue abstract class InsertQueryImpl implements InsertQueryAdmin { /** * At least one of {@code tx} and {@code match} must be absent. * @param tx the graph to execute on * @param match the {@link Match} to insert for each result * @param vars a collection of Vars to insert */ static InsertQueryImpl create(GraknTx tx, MatchAdmin match, Collection<VarPatternAdmin> vars) { if (match != null && match.tx() != null) Preconditions.checkArgument(match.tx().equals(tx)); if (vars.isEmpty()) { throw GraqlQueryException.noPatterns(); } return new AutoValue_InsertQueryImpl(tx, match, ImmutableList.copyOf(vars)); } @Override public final InsertQuery withTx(GraknTx tx) { if (match() != null) { return Queries.insert(match().withTx(tx).admin(), varPatterns()); } else { return Queries.insert(tx, varPatterns()); } } @Override public boolean isReadOnly() { return false; } @Override public final Stream<ConceptMap> stream() { return executor().run(this); } @Override public InsertQueryAdmin admin() { return this; } @Override public Set<SchemaConcept> getSchemaConcepts() { if (getTx() == null) throw GraqlQueryException.noTx(); GraknTx theGraph = getTx(); Set<SchemaConcept> types = allVarPatterns() .map(VarPatternAdmin::getTypeLabel) .flatMap(CommonUtil::optionalToStream) .map(theGraph::<Type>getSchemaConcept) .collect(Collectors.toSet()); if (match() != null) types.addAll(match().admin().getSchemaConcepts()); return types; } private Stream<VarPatternAdmin> allVarPatterns() { return varPatterns().stream().flatMap(v -> v.innerVarPatterns().stream()); } private GraknTx getTx() { if (match() != null && match().admin().tx() != null) return match().admin().tx(); else return tx(); } @Override public final String toString() { StringBuilder builder = new StringBuilder(); if (match() != null) builder.append(match()).append("\n"); builder.append("insert "); builder.append(varPatterns().stream().map(v -> v + ";").collect(Collectors.joining("\n")).trim()); return builder.toString(); } @Override public final Boolean inferring() { if (match() != null) return match().admin().inferring(); else 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/query/Queries.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; import ai.grakn.GraknTx; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Aggregate; import ai.grakn.graql.AggregateQuery; import ai.grakn.graql.GetQuery; import ai.grakn.graql.Match; import ai.grakn.graql.Var; import ai.grakn.graql.admin.DeleteQueryAdmin; import ai.grakn.graql.admin.InsertQueryAdmin; import ai.grakn.graql.admin.MatchAdmin; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.answer.Answer; import com.google.common.collect.ImmutableSet; import java.util.Collection; import java.util.Set; /** * Internal query factory * * @author Grakn Warriors */ public class Queries { private Queries() { } public static GetQuery get(MatchAdmin match, ImmutableSet<Var> vars) { validateMatchVars(match, vars); return GetQueryImpl.of(match, vars); } public static InsertQueryAdmin insert(GraknTx tx, Collection<VarPatternAdmin> vars) { return InsertQueryImpl.create(tx, null, vars); } /** * @param match the {@link Match} to insert for each result * @param varPattern a collection of Vars to insert */ public static InsertQueryAdmin insert(MatchAdmin match, Collection<VarPatternAdmin> varPattern) { return InsertQueryImpl.create(match.tx(), match, varPattern); } public static DeleteQueryAdmin delete(MatchAdmin match, Set<Var> vars) { validateMatchVars(match, vars); return DeleteQueryImpl.of(vars, match); } public static <T extends Answer> AggregateQuery<T> aggregate(MatchAdmin match, Aggregate<T> aggregate) { //TODO: validate vars in aggregate query return AggregateQueryImpl.of(match, aggregate); } private static void validateMatchVars(MatchAdmin match, Set<Var> vars) { Set<Var> selectedVars = match.getSelectedNames(); for (Var var : vars) { if (!selectedVars.contains(var)) { throw GraqlQueryException.varNotInQuery(var); } } } }
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/query/QueryBuilderImpl.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; import ai.grakn.GraknTx; import ai.grakn.graql.ComputeQuery; import ai.grakn.graql.DefineQuery; import ai.grakn.graql.InsertQuery; import ai.grakn.graql.Match; import ai.grakn.graql.Pattern; import ai.grakn.graql.Query; import ai.grakn.graql.QueryBuilder; import ai.grakn.graql.QueryParser; import ai.grakn.graql.UndefineQuery; import ai.grakn.graql.VarPattern; import ai.grakn.graql.admin.Conjunction; import ai.grakn.graql.admin.PatternAdmin; import ai.grakn.graql.admin.VarPatternAdmin; import ai.grakn.graql.answer.Answer; import ai.grakn.graql.internal.parser.QueryParserImpl; import ai.grakn.graql.internal.pattern.Patterns; import ai.grakn.graql.internal.query.match.MatchBase; 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 javax.annotation.Nullable; import java.util.Arrays; import java.util.Collection; import static ai.grakn.util.GraqlSyntax.Compute.Method; /** * A starting point for creating queries. * <p> * A {@code QueryBuiler} is constructed with a {@code GraknTx}. All operations are performed using this * transaction. The user must explicitly commit or rollback changes after executing queries. * <p> * {@code QueryBuilderImpl} also provides static methods for creating {@code Vars}. * * @author Grakn Warriors */ public class QueryBuilderImpl implements QueryBuilder { @Nullable private final GraknTx tx; private final QueryParser queryParser = QueryParserImpl.create(this); private boolean infer = true; public QueryBuilderImpl() { this.tx = null; } @SuppressWarnings("unused") /** used by {@link EmbeddedGraknTx#graql()}*/ public QueryBuilderImpl(GraknTx tx) { this.tx = tx; } @Override public QueryBuilder infer(boolean infer) { this.infer = infer; return this; } /** * @param patterns an array of patterns to match in the knowledge base * @return a {@link Match} that will find matches of the given patterns */ @Override public Match match(Pattern... patterns) { return match(Arrays.asList(patterns)); } /** * @param patterns a collection of patterns to match in the knowledge base * @return a {@link Match} that will find matches of the given patterns */ @Override public Match match(Collection<? extends Pattern> patterns) { Conjunction<PatternAdmin> conjunction = Patterns.conjunction(Sets.newHashSet(AdminConverter.getPatternAdmins(patterns))); MatchBase base = new MatchBase(conjunction); Match match = infer ? base.infer().admin() : base; return (tx != null) ? match.withTx(tx) : match; } /** * @param vars an array of variables to insert into the knowledge base * @return an insert query that will insert the given variables into the knowledge base */ @Override public InsertQuery insert(VarPattern... vars) { return insert(Arrays.asList(vars)); } /** * @param vars a collection of variables to insert into the knowledge base * @return an insert query that will insert the given variables into the knowledge base */ @Override public InsertQuery insert(Collection<? extends VarPattern> vars) { ImmutableList<VarPatternAdmin> varAdmins = ImmutableList.copyOf(AdminConverter.getVarAdmins(vars)); return Queries.insert(tx, varAdmins); } @Override public DefineQuery define(VarPattern... varPatterns) { return define(Arrays.asList(varPatterns)); } @Override public DefineQuery define(Collection<? extends VarPattern> varPatterns) { ImmutableList<VarPatternAdmin> admins = ImmutableList.copyOf(AdminConverter.getVarAdmins(varPatterns)); return DefineQueryImpl.of(admins, tx); } @Override public UndefineQuery undefine(VarPattern... varPatterns) { return undefine(Arrays.asList(varPatterns)); } @Override public UndefineQuery undefine(Collection<? extends VarPattern> varPatterns) { ImmutableList<VarPatternAdmin> admins = ImmutableList.copyOf(AdminConverter.getVarAdmins(varPatterns)); return UndefineQueryImpl.of(admins, tx); } public <T extends Answer> ComputeQuery<T> compute(Method<T> method) { return new ComputeQueryImpl<>(tx, method); } @Override public QueryParser parser() { return queryParser; } /** * @param queryString a string representing a query * @return a query, the type will depend on the type of query. */ @Override public <T extends Query<?>> T parse(String queryString) { return queryParser.parseQuery(queryString); } }
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/query/UndefineQueryImpl.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; import ai.grakn.GraknTx; import ai.grakn.graql.UndefineQuery; import ai.grakn.graql.VarPattern; import ai.grakn.graql.answer.ConceptMap; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import javax.annotation.Nullable; import java.util.Collection; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Implementation for {@link UndefineQuery} * * @author Grakn Warriors */ @AutoValue abstract class UndefineQueryImpl implements UndefineQuery { static UndefineQueryImpl of(Collection<? extends VarPattern> varPatterns, @Nullable GraknTx tx) { return new AutoValue_UndefineQueryImpl(tx, ImmutableList.copyOf(varPatterns)); } @Override public UndefineQuery withTx(GraknTx tx) { return of(varPatterns(), tx); } @Override public Stream<ConceptMap> stream() { return executor().run(this); } @Override public boolean isReadOnly() { return false; } @Override public String toString() { return "undefine " + varPatterns().stream().map(v -> v + ";").collect(Collectors.joining("\n")).trim(); } @Override public Boolean inferring() { return false; } }
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/Aggregates.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.Answer; import ai.grakn.graql.answer.AnswerGroup; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.answer.Value; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * Factory for making {@link Aggregate} implementations. */ public class Aggregates { private Aggregates() {} /** * Aggregate that counts results of a {@link Match}. */ public static Aggregate<Value> count(Var... vars) { return new CountAggregate(new HashSet<>(Arrays.asList(vars))); } public static Aggregate<Value> count(Set<Var> vars) { return new CountAggregate(vars); } /** * Aggregate that sums results of a {@link Match}. */ public static Aggregate<Value> sum(Var varName) { return new SumAggregate(varName); } /** * Aggregate that finds minimum of a {@link Match}. */ public static Aggregate<Value> min(Var varName) { return new MinAggregate(varName); } /** * Aggregate that finds maximum of a {@link Match}. */ public static Aggregate<Value> max(Var varName) { return new MaxAggregate(varName); } /** * Aggregate that finds mean of a {@link Match}. */ public static Aggregate<Value> mean(Var varName) { return new MeanAggregate(varName); } /** * Aggregate that finds median of a {@link Match}. */ public static Aggregate<Value> median(Var varName) { return new MedianAggregate(varName); } /** * Aggregate that finds the unbiased sample standard deviation of a {@link Match} */ public static Aggregate<Value> std(Var varName) { return new StdAggregate(varName); } /** * An aggregate that changes {@link Match} results into a list. */ public static Aggregate<ConceptMap> list() { return new ListAggregate(); } /** * Aggregate that groups results of a {@link Match} by variable name * @param varName the variable name to group results by */ public static Aggregate<AnswerGroup<ConceptMap>> group(Var varName) { return group(varName, new ListAggregate()); } /** * Aggregate that groups results of a {@link Match} by variable name, applying an aggregate to each group. * @param <T> the type of each group */ public static <T extends Answer> Aggregate<AnswerGroup<T>> group(Var varName, Aggregate<T> innerAggregate) { return new GroupAggregate<>(varName, innerAggregate); } }
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/CountAggregate.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.Set; import java.util.stream.Stream; /** * Aggregate that counts results of a {@link Match}. */ class CountAggregate implements Aggregate<Value> { private final Set<Var> vars; public CountAggregate(Set<Var> vars) { this.vars = vars; } @Override public List<Value> apply(Stream<? extends ConceptMap> stream) { long count; if (vars.isEmpty()) count = stream.distinct().count(); else count = stream.map(res -> res.project(vars)).distinct().count(); return Collections.singletonList(new Value(count)); } @Override public String toString() { return "count"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return true; } @Override public int hashCode() { return 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/aggregate/GroupAggregate.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.concept.Concept; import ai.grakn.exception.GraqlQueryException; import ai.grakn.graql.Aggregate; import ai.grakn.graql.Match; import ai.grakn.graql.Var; import ai.grakn.graql.answer.Answer; import ai.grakn.graql.answer.AnswerGroup; import ai.grakn.graql.answer.ConceptMap; import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; import java.util.stream.Collector; import java.util.stream.Stream; import static java.util.stream.Collectors.collectingAndThen; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.toList; /** * Aggregate that groups results of a {@link Match} by variable name, applying an aggregate to each group. * @param <T> the type of each group */ class GroupAggregate<T extends Answer> implements Aggregate<AnswerGroup<T>> { private final Var varName; private final Aggregate<T> innerAggregate; GroupAggregate(Var varName, Aggregate<T> innerAggregate) { this.varName = varName; this.innerAggregate = innerAggregate; } @Override public List<AnswerGroup<T>> apply(Stream<? extends ConceptMap> conceptMaps) { Collector<ConceptMap, ?, List<T>> applyAggregate = collectingAndThen(toList(), list -> innerAggregate.apply(list.stream())); List<AnswerGroup<T>> answerGroups = new ArrayList<>(); conceptMaps.collect(groupingBy(this::getConcept, applyAggregate)) .forEach( (key, values) -> answerGroups.add(new AnswerGroup<>(key, values))); return answerGroups; } private @Nonnull Concept getConcept(ConceptMap result) { Concept concept = result.get(varName); if (concept == null) { throw GraqlQueryException.varNotInQuery(varName); } return concept; } @Override public String toString() { if (innerAggregate instanceof ListAggregate) { return "group " + varName; } else { return "group " + varName + " " + innerAggregate.toString(); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GroupAggregate<?> that = (GroupAggregate<?>) o; if (!varName.equals(that.varName)) return false; return innerAggregate.equals(that.innerAggregate); } @Override public int hashCode() { int result = varName.hashCode(); result = 31 * result + innerAggregate.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/aggregate/ListAggregate.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.answer.ConceptMap; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; /** * An aggregate that changes {@link Match} results into a list. */ public class ListAggregate implements Aggregate<ConceptMap> { @Override public List<ConceptMap> apply(Stream<? extends ConceptMap> stream) { return stream.collect(Collectors.toList()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return true; } @Override public int hashCode() { return 31; } }
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/MaxAggregate.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 maximum of a {@link Match}. */ class MaxAggregate implements Aggregate<Value> { private final Var varName; MaxAggregate(Var varName) { this.varName = varName; } @Override public List<Value> apply(Stream<? extends ConceptMap> stream) { PrimitiveNumberComparator comparator = new PrimitiveNumberComparator(); Number number = stream.map(this::getValue).max(comparator).orElse(null); if (number == null) return Collections.emptyList(); else return Collections.singletonList( new Value(number)); } @Override public String toString() { return "max " + 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 Max Aggregate function"); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MaxAggregate that = (MaxAggregate) 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/MeanAggregate.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 mean of a {@link Match}. */ class MeanAggregate implements Aggregate<Value> { private final Var varName; private final CountAggregate countAggregate; private final Aggregate<Value> sumAggregate; MeanAggregate(Var var) { this.varName = var; countAggregate = new CountAggregate(Collections.singleton(var)); sumAggregate = Aggregates.sum(var); } @Override public List<Value> apply(Stream<? extends ConceptMap> stream) { List<? extends ConceptMap> list = stream.collect(toList()); Number count = countAggregate.apply(list.stream()).get(0).number(); if (count.intValue() == 0) { return Collections.emptyList(); } else { Number sum = sumAggregate.apply(list.stream()).get(0).number(); return Collections.singletonList(new Value(sum.doubleValue() / count.longValue())); } } @Override public String toString() { return "mean " + varName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MeanAggregate that = (MeanAggregate) o; return varName.equals(that.varName); } @Override public int hashCode() { return varName.hashCode(); } }