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

[SEDONA-625] Add ST_GeneratePoints #1520

Merged
merged 14 commits into from
Jul 17, 2024
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
18 changes: 18 additions & 0 deletions common/src/main/java/org/apache/sedona/common/Functions.java
Original file line number Diff line number Diff line change
Expand Up @@ -1812,6 +1812,24 @@ private static Geometry[] convertGeometryToArray(Geometry geom) {
return array;
}

public static Geometry generatePoints(Geometry geom, int numPoints, long seed) {
RandomPointsBuilderSeed pointsBuilder = new RandomPointsBuilderSeed(geom.getFactory(), seed);
pointsBuilder.setExtent(geom);
pointsBuilder.setNumPoints(numPoints);
return pointsBuilder.getGeometry();
}

public static Geometry generatePoints(Geometry geom, int numPoints) {
return generatePoints(geom, numPoints, 0);
}

public static Geometry generatePoints(Geometry geom, int numPoints, Random random) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is there another overloaded function that takes Random as input?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is for using the random member of ST_GeneratePoints to generate consistent random streams

RandomPointsBuilderSeed pointsBuilder = new RandomPointsBuilderSeed(geom.getFactory(), random);
pointsBuilder.setExtent(geom);
pointsBuilder.setNumPoints(numPoints);
return pointsBuilder.getGeometry();
}

public static Integer nRings(Geometry geometry) throws Exception {
String geometryType = geometry.getGeometryType();
if (!(geometry instanceof Polygon || geometry instanceof MultiPolygon)) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.sedona.common.utils;

import java.util.Random;
import org.locationtech.jts.geom.*;
import org.locationtech.jts.shape.random.RandomPointsBuilder;

public class RandomPointsBuilderSeed extends RandomPointsBuilder {
Random rand;

public RandomPointsBuilderSeed(GeometryFactory geometryFactory, long seed) {
super(geometryFactory);
if (seed > 0) {
this.rand = new Random(seed);
} else {
this.rand = new Random();
}
}

public RandomPointsBuilderSeed(GeometryFactory geometryFactory, Random random) {
super(geometryFactory);
this.rand = random;
}

@Override
protected Coordinate createRandomCoord(Envelope env) {
double x = env.getMinX() + env.getWidth() * rand.nextDouble();
double y = env.getMinY() + env.getHeight() * rand.nextDouble();
return createCoord(x, y);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2112,6 +2112,48 @@ public void minimumClearanceLine() throws ParseException {
assertEquals(expected, actual);
}

@Test
public void generatePoints() throws ParseException {
Geometry geom = Constructors.geomFromWKT("LINESTRING(50 50,10 10,10 50)", 4326);

Geometry actual =
Functions.generatePoints(Functions.buffer(geom, 10, false, "endcap=round join=round"), 12);
assertEquals(actual.getNumGeometries(), 12);

actual =
Functions.reducePrecision(
Functions.generatePoints(
Functions.buffer(geom, 10, false, "endcap=round join=round"), 5, 100),
5);
String expected =
"MULTIPOINT ((40.02957 46.70645), (37.11646 37.38582), (14.2051 29.23363), (40.82533 31.47273), (28.16839 34.16338))";
assertEquals(expected, actual.toString());
assertEquals(4326, actual.getSRID());

geom =
Constructors.geomFromEWKT(
"MULTIPOLYGON (((10 0, 10 10, 20 10, 20 0, 10 0)), ((50 0, 50 10, 70 10, 70 0, 50 0)))");
actual = Functions.generatePoints(geom, 30);
assertEquals(actual.getNumGeometries(), 30);

// Deterministic when using the same seed
Geometry first = Functions.generatePoints(geom, 10, 100);
Geometry second = Functions.generatePoints(geom, 10, 100);
assertEquals(first, second);

// Deterministic when using the same random number generator
geom = geom.buffer(10, 48);
Random rand = new Random(100);
Random rand2 = new Random(100);
first = Functions.generatePoints(geom, 100, rand);
second = Functions.generatePoints(geom, 100, rand);
Geometry first2 = Functions.generatePoints(geom, 100, rand2);
Geometry second2 = Functions.generatePoints(geom, 100, rand2);
assertNotEquals(first, second);
assertEquals(first, first2);
assertEquals(second, second2);
}

@Test
public void nRingsPolygonOnlyExternal() throws Exception {
Polygon polygon = GEOMETRY_FACTORY.createPolygon(coordArray(1, 0, 1, 1, 2, 1, 2, 0, 1, 0));
Expand Down
29 changes: 29 additions & 0 deletions docs/api/flink/Function.md
Original file line number Diff line number Diff line change
Expand Up @@ -1552,6 +1552,35 @@ Output:
5.0990195135927845
```

## ST_GeneratePoints

Introduction: Generates a specified quantity of pseudo-random points within the boundaries of the provided polygonal geometry. When `seed` is either zero or not defined then output will be random.

Format:

`ST_GeneratePoints(geom: Geometry, numPoints: Integer, seed: Long = 0)`

`ST_GeneratePoints(geom: Geometry, numPoints: Integer)`

Since: `v1.6.1`

SQL Example:

```sql
SELECT ST_GeneratePoints(
ST_GeomFromWKT('POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))'), 4
)
```

Output:

!!!Note
Due to the pseudo-random nature of point generation, the output of this function will vary between executions and may not match any provided examples.

```
MULTIPOINT ((0.2393028905520183 0.9721563442837837), (0.3805848547053376 0.7546556656982678), (0.0950295778200995 0.2494334895495989), (0.4133520939987385 0.3447046312451945))
```

## ST_GeoHash

Introduction: Returns GeoHash of the geometry with given precision
Expand Down
27 changes: 27 additions & 0 deletions docs/api/snowflake/vector-data/Function.md
Original file line number Diff line number Diff line change
Expand Up @@ -1163,6 +1163,33 @@ Output:
5.0990195135927845
```

## ST_GeneratePoints

Introduction: Generates a specified quantity of pseudo-random points within the boundaries of the provided polygonal geometry. When `seed` is either zero or not defined then output will be random.

Format:

`ST_GeneratePoints(geom: Geometry, numPoints: Integer, seed: Long = 0)`

`ST_GeneratePoints(geom: Geometry, numPoints: Integer)`

SQL Example:

```sql
SELECT ST_GeneratePoints(
ST_GeomFromWKT('POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))'), 4
)
```

Output:

!!!Note
Due to the pseudo-random nature of point generation, the output of this function will vary between executions and may not match any provided examples.

```
MULTIPOINT ((0.2393028905520183 0.9721563442837837), (0.3805848547053376 0.7546556656982678), (0.0950295778200995 0.2494334895495989), (0.4133520939987385 0.3447046312451945))
```

## ST_GeoHash

Introduction: Returns GeoHash of the geometry with given precision
Expand Down
29 changes: 29 additions & 0 deletions docs/api/sql/Function.md
Original file line number Diff line number Diff line change
Expand Up @@ -1557,6 +1557,35 @@ Output:
5.0990195135927845
```

## ST_GeneratePoints

Introduction: Generates a specified quantity of pseudo-random points within the boundaries of the provided polygonal geometry. When `seed` is either zero or not defined then output will be random.

Format:

`ST_GeneratePoints(geom: Geometry, numPoints: Integer, seed: Long = 0)`

`ST_GeneratePoints(geom: Geometry, numPoints: Integer)`

Since: `v1.6.1`

SQL Example:

```sql
SELECT ST_GeneratePoints(
ST_GeomFromWKT('POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))'), 4
)
```

Output:

!!!Note
Due to the pseudo-random nature of point generation, the output of this function will vary between executions and may not match any provided examples.

```
MULTIPOINT ((0.2393028905520183 0.9721563442837837), (0.3805848547053376 0.7546556656982678), (0.0950295778200995 0.2494334895495989), (0.4133520939987385 0.3447046312451945))
```

## ST_GeoHash

Introduction: Returns GeoHash of the geometry with given precision
Expand Down
1 change: 1 addition & 0 deletions flink/src/main/java/org/apache/sedona/flink/Catalog.java
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ public static UserDefinedFunction[] getFuncs() {
new Functions.ST_ForceCollection(),
new Functions.ST_ForcePolygonCW(),
new Functions.ST_ForceRHR(),
new Functions.ST_GeneratePoints(),
new Functions.ST_NRings(),
new Functions.ST_IsPolygonCCW(),
new Functions.ST_ForcePolygonCCW(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1549,6 +1549,25 @@ public Geometry eval(
}
}

public static class ST_GeneratePoints extends ScalarFunction {
@DataTypeHint(value = "RAW", bridgedTo = org.locationtech.jts.geom.Geometry.class)
public Geometry eval(
@DataTypeHint(value = "RAW", bridgedTo = org.locationtech.jts.geom.Geometry.class) Object o,
@DataTypeHint(value = "Integer") Integer numPoints) {
Geometry geom = (Geometry) o;
return org.apache.sedona.common.Functions.generatePoints(geom, numPoints);
}

@DataTypeHint(value = "RAW", bridgedTo = org.locationtech.jts.geom.Geometry.class)
public Geometry eval(
@DataTypeHint(value = "RAW", bridgedTo = org.locationtech.jts.geom.Geometry.class) Object o,
@DataTypeHint(value = "Integer") Integer numPoints,
@DataTypeHint(value = "BIGINT") Long seed) {
Geometry geom = (Geometry) o;
return org.apache.sedona.common.Functions.generatePoints(geom, numPoints, seed);
}
}

public static class ST_NRings extends ScalarFunction {
@DataTypeHint(value = "Integer")
public int eval(
Expand Down
43 changes: 43 additions & 0 deletions flink/src/test/java/org/apache/sedona/flink/FunctionTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -2142,6 +2142,49 @@ public void testIsPolygonCW() {
assertTrue(actual);
}

@Test
public void testGeneratePoints() {
Table polyTable =
tableEnv.sqlQuery(
"SELECT ST_Buffer(ST_GeomFromWKT('LINESTRING(50 50,10 10,10 50)'), 10, false, 'endcap=round join=round') AS geom");
Geometry actual =
(Geometry)
first(
polyTable.select(
call(Functions.ST_GeneratePoints.class.getSimpleName(), $("geom"), 15)))
.getField(0);
assertEquals(actual.getNumGeometries(), 15);

actual =
(Geometry)
first(
polyTable
.select(
call(
Functions.ST_GeneratePoints.class.getSimpleName(),
$("geom"),
5,
100L))
.as("geom")
.select(
call(Functions.ST_ReducePrecision.class.getSimpleName(), $("geom"), 5)))
.getField(0);
String expected =
"MULTIPOINT ((40.02957 46.70645), (37.11646 37.38582), (14.2051 29.23363), (40.82533 31.47273), (28.16839 34.16338))";
assertEquals(expected, actual.toString());

polyTable =
tableEnv.sqlQuery(
"SELECT ST_GeomFromWKT('MULTIPOLYGON (((10 0, 10 10, 20 10, 20 0, 10 0)), ((50 0, 50 10, 70 10, 70 0, 50 0)))') AS geom");
actual =
(Geometry)
first(
polyTable.select(
call(Functions.ST_GeneratePoints.class.getSimpleName(), $("geom"), 30)))
.getField(0);
assertEquals(actual.getNumGeometries(), 30);
}

@Test
public void testNRings() {
Integer expected = 1;
Expand Down
18 changes: 18 additions & 0 deletions python/sedona/sql/st_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -548,6 +548,24 @@ def ST_Force_2D(geometry: ColumnOrName) -> Column:
return _call_st_function("ST_Force_2D", geometry)


@validate_argument_types
def ST_GeneratePoints(geometry: ColumnOrName, numPoints: Union[ColumnOrName, int], seed:Optional[Union[ColumnOrName, int]] = None) -> Column:
"""Generate random points in given geometry.

:param geometry: Geometry column to hash.
:type geometry: ColumnOrName
:param numPoints: Precision level to hash geometry at, given as an integer or an integer column.
:type numPoints: Union[ColumnOrName, int]
:return: Generate random points in given geometry
:rtype: Column
"""
if seed is None:
args = (geometry, numPoints)
else:
args = (geometry, numPoints, seed)

return _call_st_function("ST_GeneratePoints", args)

@validate_argument_types
def ST_GeoHash(geometry: ColumnOrName, precision: Union[ColumnOrName, int]) -> Column:
"""Return the geohash of a geometry column at a given precision level.
Expand Down
4 changes: 4 additions & 0 deletions python/tests/sql/test_dataframe_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,8 @@
(stf.ST_ForceRHR, ("geom",), "geom_with_hole", "", "POLYGON ((0 0, 3 3, 3 0, 0 0), (1 1, 2 1, 2 2, 1 1))"),
(stf.ST_FrechetDistance, ("point", "line",), "point_and_line", "", 5.0990195135927845),
(stf.ST_GeometricMedian, ("multipoint",), "multipoint_geom", "", "POINT (22.500002656424286 21.250001168173426)"),
(stf.ST_GeneratePoints, ("geom", 15), "square_geom", "ST_NumGeometries(geom)", 15),
(stf.ST_GeneratePoints, ("geom", 15, 100), "square_geom", "ST_NumGeometries(geom)", 15),
(stf.ST_GeometryN, ("geom", 0), "multipoint", "", "POINT (0 0)"),
(stf.ST_GeometryType, ("point",), "point_geom", "", "ST_Point"),
(stf.ST_HausdorffDistance, ("point", "line",), "point_and_line", "", 5.0990195135927845),
Expand Down Expand Up @@ -351,6 +353,8 @@
(stf.ST_GeometryN, ("", None)),
(stf.ST_GeometryN, ("", 0.0)),
(stf.ST_GeometryType, (None,)),
(stf.ST_GeneratePoints, (None, 0.0)),
(stf.ST_GeneratePoints, ("", None)),
(stf.ST_InteriorRingN, (None, 0)),
(stf.ST_InteriorRingN, ("", None)),
(stf.ST_InteriorRingN, ("", 0.0)),
Expand Down
20 changes: 20 additions & 0 deletions python/tests/sql/test_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -1606,6 +1606,26 @@ def test_forceRHR(self):
expected = "POLYGON ((20 35, 45 20, 30 5, 10 10, 10 30, 20 35), (30 20, 20 25, 20 15, 30 20))"
assert expected == actual

def test_generate_points(self):
actual = self.spark.sql("SELECT ST_NumGeometries(ST_GeneratePoints(ST_Buffer(ST_GeomFromWKT('LINESTRING(50 50,150 150,150 50)'), 10, false, 'endcap=round join=round'), 15))")\
.first()[0]
assert actual == 15

actual = self.spark.sql(
"SELECT ST_AsText(ST_ReducePrecision(ST_GeneratePoints(ST_GeomFromWKT('MULTIPOLYGON (((10 0, 10 10, 20 10, 20 0, 10 0)), ((50 0, 50 10, 70 10, 70 0, 50 0)))'), 5, 10), 5))") \
.first()[0]
expected = "MULTIPOINT ((53.82582 2.57803), (13.55212 2.44117), (59.12854 3.70611), (61.37698 7.14985), (10.49657 4.40622))"
assert expected == actual

actual = self.spark.sql(
"SELECT ST_NumGeometries(ST_GeneratePoints(ST_Buffer(ST_GeomFromWKT('LINESTRING(50 50,150 150,150 50)'), 10, false, 'endcap=round join=round'), 15, 100))") \
.first()[0]
assert actual == 15

actual = self.spark.sql("SELECT ST_NumGeometries(ST_GeneratePoints(ST_GeomFromWKT('MULTIPOLYGON (((10 0, 10 10, 20 10, 20 0, 10 0)), ((50 0, 50 10, 70 10, 70 0, 50 0)))'), 30))")\
.first()[0]
assert actual == 30

def test_nRings(self):
expected = 1
actualDf = self.spark.sql("SELECT ST_GeomFromText('POLYGON ((1 0, 1 1, 2 1, 2 0, 1 0))') AS geom")
Expand Down
Loading
Loading