Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Percentile functions #44

Merged
merged 1 commit into from
Apr 13, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
/*
* Copyright (c) 2018 "Neo4j, Inc." [https://neo4j.com]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opencypher.gremlin.queries;

import static java.util.Collections.emptyMap;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.assertj.core.api.Assertions.tuple;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.opencypher.gremlin.rules.GremlinServerExternalResource;

public class PercentileTest {

@ClassRule
public static final GremlinServerExternalResource gremlinServer = new GremlinServerExternalResource();

@Before
public void setUp() {
gremlinServer.gremlinClient().submit("g.V().drop()").all().join();
}

private List<Map<String, Object>> submitAndGet(String cypher) {
return submitAndGet(cypher, emptyMap());
}

private List<Map<String, Object>> submitAndGet(String cypher, Map<String, ?> parameters) {
return gremlinServer.cypherGremlinClient().submit(cypher, parameters).all();
}

@Test
public void percentileCont() throws Exception {
List<Map<String, Object>> results = submitAndGet(
"UNWIND [10, 20, 30] AS i " +
"RETURN " +
"percentileCont(i, 0.0) AS p0, " +
"percentileCont(i, 0.33) AS p33, " +
"percentileCont(i, 0.5) AS p50, " +
"percentileCont(i, 0.66) AS p66, " +
"percentileCont(i, 1.0) AS p100"
);

assertThat(results)
.extracting("p0", "p33", "p50", "p66", "p100")
.containsExactly(tuple(10L, 16.6, 20L, 23.2, 30L));
}

@Test
public void percentileContSingle() throws Exception {
List<Map<String, Object>> results = submitAndGet(
"UNWIND [10] AS i " +
"RETURN percentileCont(i, 0.5) AS p50"
);

assertThat(results)
.extracting("p50")
.containsExactly(10L);
}

@Test
public void percentileContEmpty() throws Exception {
List<Map<String, Object>> results = submitAndGet(
"UNWIND [] AS i " +
"RETURN percentileCont(i, 0.5) AS p50"
);

assertThat(results)
.extracting("p50")
.containsExactly((Object) null);
}

@Test
public void percentileContInvalidArgument() throws Exception {
submitAndGet("CREATE ({prop: 10.0})");
List<Throwable> throwables = Stream.of(1000, -1, 1.1)
.map(param -> catchThrowable(() -> submitAndGet(
"MATCH (n) RETURN percentileCont(n.prop, $param)",
Collections.singletonMap("param", param)
)))
.collect(toList());

assertThat(throwables)
.allSatisfy(throwable ->
assertThat(throwable)
.hasMessageContaining("Number out of range"));
}

@Test
public void percentileDisc() throws Exception {
List<Map<String, Object>> results = submitAndGet(
"UNWIND [10, 20, 30] AS i " +
"RETURN " +
"percentileDisc(i, 0.0) AS p0, " +
"percentileDisc(i, 0.33) AS p33, " +
"percentileDisc(i, 0.34) AS p34, " +
"percentileDisc(i, 0.5) AS p50, " +
"percentileDisc(i, 0.66) AS p66, " +
"percentileDisc(i, 0.67) AS p67, " +
"percentileDisc(i, 1.0) AS p100"
);

assertThat(results)
.extracting("p0", "p33", "p34", "p50", "p66", "p67", "p100")
.containsExactly(tuple(10L, 10L, 20L, 20L, 20L, 30L, 30L));
}

@Test
public void percentileDiscSingle() throws Exception {
List<Map<String, Object>> results = submitAndGet(
"UNWIND [10] AS i " +
"RETURN percentileDisc(i, 0.5) AS p50"
);

assertThat(results)
.extracting("p50")
.containsExactly(10L);
}

@Test
public void percentileDiscEmpty() throws Exception {
List<Map<String, Object>> results = submitAndGet(
"UNWIND [] AS i " +
"RETURN percentileDisc(i, 0.5) AS p50"
);

assertThat(results)
.extracting("p50")
.containsExactly((Object) null);
}

@Test
public void percentileDiscInvalidArgument() throws Exception {
submitAndGet("CREATE ({prop: 10.0})");
List<Throwable> throwables = Stream.of(1000, -1, 1.1)
.map(param -> catchThrowable(() -> submitAndGet(
"MATCH (n) RETURN percentileDisc(n.prop, $param)",
Collections.singletonMap("param", param)
)))
.collect(toList());

assertThat(throwables)
.allSatisfy(throwable ->
assertThat(throwable)
.hasMessageContaining("Number out of range"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ package org.opencypher.gremlin.tck

import org.opencypher.tools.tck.api.ExecutionFailed
import org.opencypher.tools.tck.constants.TCKErrorDetails._
import org.opencypher.tools.tck.constants.TCKErrorPhases.{COMPILE_TIME, RUNTIME}
import org.opencypher.tools.tck.constants.TCKErrorTypes.{SYNTAX_ERROR, TYPE_ERROR}
import org.opencypher.tools.tck.constants.TCKErrorPhases._
import org.opencypher.tools.tck.constants.TCKErrorTypes._

object GremlinErrors {
val mappings = Map(
Expand Down Expand Up @@ -97,6 +97,8 @@ object GremlinErrors {
"Unsupported graph element type: (.+)" ->
ExecutionFailed(SYNTAX_ERROR, RUNTIME, PROPERTY_ACCESS_ON_NON_MAP),
"Cannot convert .+ to .+" ->
ExecutionFailed(TYPE_ERROR, RUNTIME, INVALID_ARGUMENT_VALUE)
ExecutionFailed(TYPE_ERROR, RUNTIME, INVALID_ARGUMENT_VALUE),
"Number out of range: (.+)" ->
ExecutionFailed(ARGUMENT_ERROR, RUNTIME, NUMBER_OUT_OF_RANGE)
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.tinkerpop.gremlin.process.traversal.Path;
import org.apache.tinkerpop.gremlin.process.traversal.Traverser;
Expand Down Expand Up @@ -199,7 +200,7 @@ public static CustomFunction listComprehension(final Object functionTraversal) {
GraphTraversal.Admin admin = GraphTraversal.class.cast(functionTraversal).asAdmin();
return TraversalUtil.apply(item, admin);
})
.collect(Collectors.toList());
.collect(toList());
},
functionTraversal);
}
Expand All @@ -225,7 +226,7 @@ public static CustomFunction pathComprehension() {
.map(CustomFunction::finalizeElements)
.collect(toList());
})
.collect(Collectors.toList()));
.collect(toList()));
}

public static CustomFunction containerIndex(Object index) {
Expand All @@ -247,6 +248,79 @@ public static CustomFunction containerIndex(Object index) {
index);
}

public static CustomFunction percentileCont(double percentile) {
return new CustomFunction(
"percentileCont",
percentileFunction(
percentile,
data -> {
int last = data.size() - 1;
double lowPercentile = Math.floor(percentile * last) / last;
double highPercentile = Math.ceil(percentile * last) / last;
if (lowPercentile == highPercentile) {
return percentileNearest(data, percentile);
}

double scale = (percentile - lowPercentile) / (highPercentile - lowPercentile);
double low = percentileNearest(data, lowPercentile).doubleValue();
double high = percentileNearest(data, highPercentile).doubleValue();
return (high - low) * scale + low;
}
),
percentile
);
}

public static CustomFunction percentileDisc(double percentile) {
return new CustomFunction(
"percentileDisc",
percentileFunction(
percentile,
data -> percentileNearest(data, percentile)
),
percentile
);
}

private static Function<Traverser, Object> percentileFunction(double percentile,
Function<List<Number>, Number> percentileStrategy) {
return traverser -> {
if (percentile < 0 || percentile > 1) {
throw new IllegalArgumentException("Number out of range: " + percentile);
}

Collection<?> coll = (Collection<?>) traverser.get();
boolean invalid = coll.stream()
.anyMatch(o -> !(o == null || o instanceof Number));
if (invalid) {
throw new IllegalArgumentException("Percentile function can only handle numerical values");
}
List<Number> data = coll.stream()
.filter(Objects::nonNull)
.map(o -> (Number) o)
.sorted()
.collect(toList());

int size = data.size();
if (size == 0) {
return Tokens.NULL;
} else if (size == 1) {
return data.get(0);
}

return percentileStrategy.apply(data);
};
}

private static <T> T percentileNearest(List<T> sorted, double percentile) {
int size = sorted.size();
int index = (int) Math.ceil(percentile * size) - 1;
if (index == -1) {
index = 0;
}
return sorted.get(index);
}

public static CustomFunction size() {
return new CustomFunction(
"size", traverser -> traverser.get() instanceof String ?
Expand Down Expand Up @@ -288,7 +362,7 @@ private static Object nullToToken(Object maybeNull) {
return maybeNull == null ? Tokens.NULL : maybeNull;
}

public static Object pathToList(Object value) {
private static Object pathToList(Object value) {
return value instanceof Path ? new ArrayList<>(((Path) value).objects()) : value;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -487,14 +487,24 @@ private class ProjectionWalker[T, P](context: StatementContext[T, P], g: Gremlin
traversal.is(p.neq(NULL))

fnName.toLowerCase match {
case "avg" => (Aggregation, traversal.mean())
case "collect" => (Aggregation, traversal.fold())
case "count" => (Aggregation, traversal.count())
case "avg" =>
(Aggregation, traversal.mean())
case "collect" =>
(Aggregation, traversal.fold())
case "count" =>
(Aggregation, traversal.count())
case "max" =>
(Aggregation, traversal.max().choose(p.isEq(Integer.MIN_VALUE), __.constant(NULL)))
case "min" =>
(Aggregation, traversal.min().choose(p.isEq(Integer.MAX_VALUE), __.constant(NULL)))
case "sum" => (Aggregation, traversal.sum())
case "percentilecont" =>
val percentile = inlineExpressionValue(args(1), context, classOf[java.lang.Number]).doubleValue()
(Aggregation, traversal.fold().map(CustomFunction.percentileCont(percentile)))
case "percentiledisc" =>
val percentile = inlineExpressionValue(args(1), context, classOf[java.lang.Number]).doubleValue()
(Aggregation, traversal.fold().map(CustomFunction.percentileDisc(percentile)))
case "sum" =>
(Aggregation, traversal.sum())
case _ =>
throw new SyntaxException(s"Unknown function '$fnName'")
}
Expand Down