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

Spatial join area #1713

Open
wants to merge 50 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
50 commits
Select commit Hold shift + click to select a range
c7a1ea8
untested changes
Jonathan24680 Dec 17, 2024
a266201
continued development
Jonathan24680 Dec 18, 2024
2cc8504
added all areas to the dataset and some tests
Jonathan24680 Dec 23, 2024
d784513
make file_buffer_size in the test index be a parameter
Jonathan24680 Dec 28, 2024
f6e1647
bugfix area dataset
Jonathan24680 Dec 28, 2024
1a4ff8f
backup commit
Jonathan24680 Dec 30, 2024
e3a2644
area test with points and areas working
Jonathan24680 Dec 31, 2024
f38cb1d
moved some stuff from dev space into the project
Jonathan24680 Jan 2, 2025
4d71c4e
new tests
Jonathan24680 Jan 4, 2025
38c9585
first test works now for the areas as well
Jonathan24680 Jan 11, 2025
ddea6d3
all tests are now executed and passed
Jonathan24680 Jan 12, 2025
1902d44
clang format
Jonathan24680 Jan 12, 2025
31e7054
merge master
Jonathan24680 Jan 12, 2025
cba4324
backup with removed filebuffersize compiling but not testing
Jonathan24680 Jan 17, 2025
d5c934c
make buffer size of test index variable
Jonathan24680 Jan 17, 2025
c1dc963
clean up code
Jonathan24680 Jan 17, 2025
c5284ef
sonarqube
Jonathan24680 Jan 20, 2025
fc1a1fe
correct bug for function without inline in header file
Jonathan24680 Jan 21, 2025
ec75e89
arbitrary geometry types and areas dont need to be approximated as po…
Jonathan24680 Jan 25, 2025
4fd698c
PR feedback
Jonathan24680 Jan 31, 2025
173e646
PR feedback
Jonathan24680 Jan 31, 2025
7dd8156
backup
Jonathan24680 Feb 1, 2025
1c60bf9
PR feedback
Jonathan24680 Feb 1, 2025
3b8ea1a
spelling mistake
Jonathan24680 Feb 1, 2025
a121ef2
Sonarqube issues
Jonathan24680 Feb 4, 2025
1168f32
PR changes
Jonathan24680 Feb 4, 2025
ca7f08e
PR changes
Jonathan24680 Feb 4, 2025
9d2956e
PR changes
Jonathan24680 Feb 4, 2025
14032bd
PR changes
Jonathan24680 Feb 4, 2025
29171b5
Sonarqube issues
Jonathan24680 Feb 4, 2025
457f8d4
format check
Jonathan24680 Feb 4, 2025
bf886c4
backup
Jonathan24680 Feb 7, 2025
10bdf7b
strange bug
Jonathan24680 Feb 7, 2025
5f12f22
solved strange bug
Jonathan24680 Feb 7, 2025
978b512
PR feedback
Jonathan24680 Feb 7, 2025
4132701
Sonarqube issue
Jonathan24680 Feb 7, 2025
d711586
Merge branch 'master' into SpatialJoinArea
Jonathan24680 Feb 7, 2025
f3c5b01
consistent naming of QueryBox and BoundingBox
Jonathan24680 Feb 8, 2025
a46fccd
add test for distance between GeoPoints and Areas
Jonathan24680 Feb 8, 2025
2cc0fef
improve true area distance calculation
Jonathan24680 Feb 8, 2025
96a903a
backup
Jonathan24680 Feb 10, 2025
47ba454
backup
Jonathan24680 Feb 10, 2025
61c6b98
PR changes
Jonathan24680 Feb 10, 2025
c0bf282
clang format
Jonathan24680 Feb 10, 2025
988ba8d
Sonarqube issus and bugfix
Jonathan24680 Feb 12, 2025
e42d9d0
format check
Jonathan24680 Feb 12, 2025
5b88f47
Merge branch 'master' into SpatialJoinArea
Jonathan24680 Feb 14, 2025
5a99080
Sonarqube issue remove unused operator
Jonathan24680 Feb 14, 2025
a7f4695
PR feedback
Jonathan24680 Feb 15, 2025
e5121f6
suggested parentheses around and condition
Jonathan24680 Feb 15, 2025
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
4 changes: 4 additions & 0 deletions src/engine/SpatialJoin.h
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,10 @@ class SpatialJoin : public Operation {
return childRight_;
}

PreparedSpatialJoinParams onlyForTestingGetPrepareJoin() const {
return prepareJoin();
}

private:
// helper function to generate a variable to column map from `childRight_`
// that only contains the columns selected by `config_.payloadVariables_`
Expand Down
201 changes: 177 additions & 24 deletions src/engine/SpatialJoinAlgorithms.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

#include <cmath>

#include "engine/ExportQueryExecutionTrees.h"
#include "engine/SpatialJoin.h"
#include "util/GeoSparqlHelpers.h"

Expand All @@ -37,19 +38,103 @@
: std::nullopt;
};

// ____________________________________________________________________________
std::string SpatialJoinAlgorithms::betweenQuotes(
std::string extractFrom) const {
size_t pos1 = extractFrom.find("\"", 0);
size_t pos2 = extractFrom.find("\"", pos1 + 1);
if (pos1 != std::string::npos && pos2 != std::string::npos) {
return extractFrom.substr(pos1 + 1, pos2 - pos1 - 1);
} else {
return extractFrom;
}

Check warning on line 50 in src/engine/SpatialJoinAlgorithms.cpp

View check run for this annotation

Codecov / codecov/patch

src/engine/SpatialJoinAlgorithms.cpp#L49-L50

Added lines #L49 - L50 were not covered by tests
}

struct DistanceVisitor : public boost::static_visitor<double> {
template <typename Geometry1, typename Geometry2>
double operator()(const Geometry1& geom1, const Geometry2& geom2) const {
return bg::distance(geom1, geom2);
}
};

// ____________________________________________________________________________
Id SpatialJoinAlgorithms::computeDist(const IdTable* idTableLeft,
const IdTable* idTableRight,
size_t rowLeft, size_t rowRight,
ColumnIndex leftPointCol,
ColumnIndex rightPointCol) const {
auto getAreaString = [&](const IdTable* idtable, size_t row, size_t col) {
return betweenQuotes(ExportQueryExecutionTrees::idToStringAndType(
qec_->getIndex(), idtable->at(row, col), {})
.value()
.first);
};

auto getAreaOrPointGeometry =
[&](const IdTable* idtable, size_t row, size_t col,
std::optional<GeoPoint> point) -> std::optional<AnyGeometry> {
AnyGeometry geometry;
try {
if (!point) {
boost::geometry::read_wkt(getAreaString(idtable, row, col), geometry);
} else {
geometry = Point(point.value().getLng(), point.value().getLat());
}

Check warning on line 82 in src/engine/SpatialJoinAlgorithms.cpp

View check run for this annotation

Codecov / codecov/patch

src/engine/SpatialJoinAlgorithms.cpp#L81-L82

Added lines #L81 - L82 were not covered by tests
} catch (...) {
return std::nullopt;
}

Check warning on line 85 in src/engine/SpatialJoinAlgorithms.cpp

View check run for this annotation

Codecov / codecov/patch

src/engine/SpatialJoinAlgorithms.cpp#L84-L85

Added lines #L84 - L85 were not covered by tests
Copy link
Member

Choose a reason for hiding this comment

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

does boost geometry have a mode or overload of readWkt that doesn't use exceptions? then use that.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

No. At least I'm not aware of such a function or overload and could not find one.

return geometry;
};

// for now we need to get the data from the disk, but in the future, this
// information will be stored in an ID, just like GeoPoint
auto getAreaPoint = [&](const IdTable* idtable, size_t row,
size_t col) -> std::optional<GeoPoint> {
std::string areastring = getAreaString(idtable, row, col);

Box areaBox;
try {
areaBox = calculateBoundingBoxOfArea(areastring);
} catch (...) {
// nothing to do. When parsing a point or an area fails, a warning message
// gets printed at another place and the point/area just gets skipped
return std::nullopt;
}
Point p = calculateMidpointOfBox(areaBox);
return GeoPoint(p.get<1>(), p.get<0>());
};

auto point1 = getPoint(idTableLeft, rowLeft, leftPointCol);
auto point2 = getPoint(idTableRight, rowRight, rightPointCol);
if (!point1.has_value() || !point2.has_value()) {
return Id::makeUndefined();
if (useMidpointForAreas_) {
if (!point1) {
point1 = getAreaPoint(idTableLeft, rowLeft, leftPointCol);
}

if (!point2) {
point2 = getAreaPoint(idTableRight, rowRight, rightPointCol);
}

if (!point1.has_value() || !point2.has_value()) {
return Id::makeUndefined();
}
return Id::makeFromDouble(
ad_utility::detail::wktDistImpl(point1.value(), point2.value()));
} else {
auto geometry1 =
getAreaOrPointGeometry(idTableLeft, rowLeft, leftPointCol, point1);
auto geometry2 =
getAreaOrPointGeometry(idTableRight, rowRight, rightPointCol, point2);
if (!geometry1.has_value() || !geometry2.has_value()) {
return Id::makeUndefined();
}

Check warning on line 130 in src/engine/SpatialJoinAlgorithms.cpp

View check run for this annotation

Codecov / codecov/patch

src/engine/SpatialJoinAlgorithms.cpp#L129-L130

Added lines #L129 - L130 were not covered by tests
// convert to m and return. Note that the 78630 is an approximation, which
// does not provide accurate results for the poles.
return Id::makeFromDouble(boost::apply_visitor(DistanceVisitor(),
geometry1.value(),
geometry2.value()) *
78630);
}
return Id::makeFromDouble(
ad_utility::detail::wktDistImpl(point1.value(), point2.value()));
}

// ____________________________________________________________________________
Expand Down Expand Up @@ -241,7 +326,7 @@

// ____________________________________________________________________________
std::vector<Box> SpatialJoinAlgorithms::computeBoundingBox(
const Point& startPoint) const {
const Point& startPoint, double additionalDist) const {
const auto [idTableLeft, resultLeft, idTableRight, resultRight, leftJoinCol,
rightJoinCol, rightSelectedCols, numColumns, maxDist,
maxResults] = params_;
Expand All @@ -254,8 +339,9 @@
auto archaversine = [](double theta) { return std::acos(1 - 2 * theta); };

// safety buffer for numerical inaccuracies
double maxDistInMetersBuffer;
if (maxDist.value() < 10) {
double maxDistInMetersBuffer =
static_cast<double>(maxDist.value()) + additionalDist;
if (maxDistInMetersBuffer < 10) {
maxDistInMetersBuffer = 10;
} else if (static_cast<double>(maxDist.value()) <
static_cast<double>(std::numeric_limits<long long>::max()) /
Expand Down Expand Up @@ -442,16 +528,54 @@
return std::array{northPoleReached, southPoleReached};
}

struct BoundingBoxVisitor : public boost::static_visitor<Box> {
template <typename Geometry>
Box operator()(const Geometry& geometry) const {
Box box;
bg::envelope(geometry, box);
return box;
}
};

// ____________________________________________________________________________
Box SpatialJoinAlgorithms::calculateBoundingBoxOfArea(
const std::string& wktString) const {
AnyGeometry geometry;
boost::geometry::read_wkt(wktString, geometry);
return boost::apply_visitor(BoundingBoxVisitor(), geometry);
}

// ____________________________________________________________________________
Point SpatialJoinAlgorithms::calculateMidpointOfBox(const Box& box) const {
double lng = (box.min_corner().get<0>() + box.max_corner().get<0>()) / 2.0;
double lat = (box.min_corner().get<1>() + box.max_corner().get<1>()) / 2.0;
return Point(lng, lat);
}

// ____________________________________________________________________________
double SpatialJoinAlgorithms::getMaxDistFromMidpointToAnyPointInsideTheBox(
const Box& box, std::optional<Point> midpoint) const {
if (!midpoint) {
midpoint = calculateMidpointOfBox(box);
}
double distLng =
std::abs(box.min_corner().get<0>() - midpoint.value().get<0>());
double distLat =
std::abs(box.min_corner().get<1>() - midpoint.value().get<1>());
// convert to meters and return
return (distLng + distLat) * 40075000 / 360;
}

// ____________________________________________________________________________
Result SpatialJoinAlgorithms::BoundingBoxAlgorithm() {
auto printWarning = [alreadyWarned = false,
&spatialJoin = spatialJoin_]() mutable {
if (!alreadyWarned) {
std::string warning =
"The input to a spatial join contained at least one element, "
"that is not a point geometry and is thus skipped. Note that "
"QLever currently only accepts point geometries for the "
"spatial joins";
"that is not a point or polygon geometry and is thus skipped. Note "
"that QLever currently only accepts point or polygon geometries for "
"the spatial joins";
AD_LOG_WARN << warning << std::endl;
alreadyWarned = true;
if (spatialJoin.has_value()) {
Expand All @@ -478,38 +602,67 @@
std::swap(smallerResJoinCol, otherResJoinCol);
}

// build rtree with one child
bgi::rtree<Value, bgi::quadratic<16>, bgi::indexable<Value>,
bgi::equal_to<Value>, ad_utility::AllocatorWithLimit<Value>>
rtree(bgi::quadratic<16>{}, bgi::indexable<Value>{},
bgi::equal_to<Value>{}, qec_->getAllocator());
for (size_t i = 0; i < smallerResult->numRows(); i++) {
// get point of row i
auto geopoint = getPoint(smallerResult, i, smallerResJoinCol);
Box bbox;

if (!geopoint) {
printWarning();
continue;
try {
std::string areastring = betweenQuotes(
ExportQueryExecutionTrees::idToStringAndType(
qec_->getIndex(), smallerResult->at(i, smallerResJoinCol), {})
.value()
.first);
bbox = calculateBoundingBoxOfArea(areastring);
} catch (...) {
printWarning();
continue;
}
} else {
// create a box with a side length of at most 1mm to approximate the point
bbox = Box(Point(geopoint.value().getLng(), geopoint.value().getLat()),
Point(geopoint.value().getLng() + 0.00000001,
geopoint.value().getLat() + 0.00000001));
}

Point p(geopoint.value().getLng(), geopoint.value().getLat());

// add every point together with the row number into the rtree
rtree.insert(std::make_pair(std::move(p), i));
// add every box together with the row number into the rtree
rtree.insert(std::make_pair(std::move(bbox), i));
}

// query rtree with the other child
std::vector<Value, ad_utility::AllocatorWithLimit<Value>> results{
qec_->getAllocator()};
for (size_t i = 0; i < otherResult->numRows(); i++) {
auto geopoint1 = getPoint(otherResult, i, otherResJoinCol);
auto geopoint = getPoint(otherResult, i, otherResJoinCol);
std::vector<Box> bbox;

if (!geopoint1) {
printWarning();
continue;
if (!geopoint) {
try {
std::string areastring = betweenQuotes(
ExportQueryExecutionTrees::idToStringAndType(
qec_->getIndex(), otherResult->at(i, otherResJoinCol), {})
.value()
.first);
auto areaBox = calculateBoundingBoxOfArea(areastring);
auto midpoint = calculateMidpointOfBox(areaBox);
bbox = computeBoundingBox(
midpoint,
getMaxDistFromMidpointToAnyPointInsideTheBox(areaBox, midpoint));
} catch (...) {
printWarning();
continue;
}
} else {
bbox = computeBoundingBox(
Point(geopoint.value().getLng(), geopoint.value().getLat()));
}

Point p(geopoint1.value().getLng(), geopoint1.value().getLat());

// query the other rtree for every point using the following bounding box
std::vector<Box> bbox = computeBoundingBox(p);
results.clear();

ql::ranges::for_each(bbox, [&](const Box& bbox) {
Expand Down
Loading
Loading