Mryange commented on code in PR #69032:
URL: https://github.com/apache/doris/pull/69032#discussion_r4748870433


##########
be/src/exprs/function/geo/geography_calculation.cpp:
##########
@@ -0,0 +1,2469 @@
+// 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.
+
+#include "exprs/function/geo/geography_calculation.h"
+
+#include <glog/logging.h>
+#include <s2/mutable_s2shape_index.h>
+#include <s2/s2boolean_operation.h>
+#include <s2/s2closest_edge_query.h>
+#include <s2/s2closest_point_query.h>
+#include <s2/s2contains_point_query.h>
+#include <s2/s2crossing_edge_query.h>
+#include <s2/s2earth.h>
+#include <s2/s2edge_crossings.h>
+#include <s2/s2edge_distances.h>
+#include <s2/s2edge_vector_shape.h>
+#include <s2/s2latlng_rect_bounder.h>
+#include <s2/s2lax_polygon_shape.h>
+#include <s2/s2loop.h>
+#include <s2/s2loop_measures.h>
+#include <s2/s2point.h>
+#include <s2/s2point_index.h>
+#include <s2/s2point_vector_shape.h>
+#include <s2/s2pointutil.h>
+#include <s2/s2polygon.h>
+#include <s2/s2polyline.h>
+#include <s2/s2predicates.h>
+#include <s2/s2shape_measures.h>
+
+#include <algorithm>
+#include <array>
+#include <bit>
+#include <boost/iterator/iterator_facade.hpp>
+// Integer proofs and software-wide arithmetic need no quadmath wrappers. 
Boost's float128
+// numeric_limits specialization conflicts with libstdc++ 15 in the GCC 
performance build.
+#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 15
+#define BOOST_CSTDFLOAT_NO_LIBQUADMATH_SUPPORT
+#endif
+#include <boost/multiprecision/cpp_bin_float.hpp>
+#include <boost/multiprecision/cpp_int.hpp>
+#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 15
+#undef BOOST_CSTDFLOAT_NO_LIBQUADMATH_SUPPORT
+#endif
+#include <cmath>
+#include <cstdint>
+#include <limits>
+#include <map>
+#include <numbers>
+#include <optional>
+#include <set>
+#include <type_traits>
+#include <utility>
+
+#include "core/assert_cast.h"
+#include "core/custom_allocator.h"
+#include "exprs/function/geo/geo_types.h"
+#include "exprs/function/geo/wkb_parse.h"
+
+namespace doris {
+
+// Apple ARM64 long double has binary64 precision/range. Keep native wide 
arithmetic
+// where available; software quad preserves the tiny residual products on 
narrower ABIs.
+using GeographyFloat =
+        std::conditional_t<std::numeric_limits<long double>::digits >= 64 &&
+                                   std::numeric_limits<long 
double>::min_exponent <= -4096,
+                           long double, 
boost::multiprecision::cpp_bin_float_quad>;
+static_assert(std::numeric_limits<GeographyFloat>::digits >= 64 &&
+              std::numeric_limits<GeographyFloat>::min_exponent <= -4096);
+
+template <typename Float>
+static Float geography_pi() {
+    if constexpr (std::is_same_v<Float, long double>) {
+        return std::numbers::pi_v<long double>;
+    } else {
+        // Public software acos avoids float128 constant 
conversions/libquadmath on GCC.
+        static const Float pi = boost::multiprecision::acos(Float(-1));
+        return pi;
+    }
+}
+
+// Error-free TwoSum preserves tiny differences from a half-turn (e.g. -1e-15 
+ 180).
+static std::pair<double, double> geography_degree_sum(double a, double b) {
+    const double high = a + b;
+    const double offset = high - a;
+    return {high, (a - (high - offset)) + (b - offset)};
+}
+
+// Reduce the exact degree sum before converting to radians. In particular,
+// 180 + (-1e-300) must retain its small sine instead of becoming sin(pi).
+template <typename Float = GeographyFloat>
+static std::pair<Float, Float> geography_degree_sincos(double a, double b = 0, 
bool half = false) {
+    // Explicit scalar locals keep lambda captures visible to the static 
analyzer.
+    const auto sum = geography_degree_sum(a, b);
+    const double high = sum.first;
+    const double low = sum.second;
+    int quadrant;
+    const Float reduced = [&] {
+        if constexpr (std::is_same_v<Float, long double>) {
+            return std::remquo(static_cast<Float>(high), half ? 180.0L : 
90.0L, &quadrant) +
+                   static_cast<Float>(low);
+        } else {
+            // high is binary64 and the periods are exact integers: its 
reduced remainder
+            // is representable in binary64. Add TwoSum's low residual only 
after widening.
+            return Float(std::remquo(high, half ? 180.0 : 90.0, &quadrant)) + 
Float(low);
+        }
+    }();
+    const Float radians = reduced * (geography_pi<Float>() / 180) / (half ? 2 
: 1);
+    using std::cos;
+    using std::sin;
+    const Float sine = sin(radians);
+    const Float cosine = cos(radians);
+    switch ((quadrant % 4 + 4) % 4) {
+    case 0:
+        return {sine, cosine};
+    case 1:
+        return {cosine, -sine};
+    case 2:
+        return {-sine, -cosine};
+    default:
+        return {-cosine, sine};
+    }
+}
+
+// In longitude-midpoint coordinates, the raw normal retains the low bits of 
both
+// endpoint differences. A Cartesian cross product would subtract rounded 
products.
+template <typename Float>
+static std::array<Float, 3> geography_raw_normal(const GeoCoordinate& a, const 
GeoCoordinate& b,
+                                                 const Float& sin_half, const 
Float& cos_half) {
+    return {-sin_half * geography_degree_sincos<Float>(a.y, b.y).first,
+            cos_half * geography_degree_sincos<Float>(a.y, -b.y).first,
+            geography_degree_sincos<Float>(a.y).second *
+                    geography_degree_sincos<Float>(b.y).second *
+                    geography_degree_sincos<Float>(b.x, -a.x).first};
+}
+
+template <typename Float = GeographyFloat>
+struct GeographyRawArc {
+    S2Point normal;
+    S2Point midpoint;
+
+    GeographyRawArc(const GeoCoordinate& a, const GeoCoordinate& b) {
+        const auto [sd, cd] = geography_degree_sincos<Float>(b.x, -a.x, true);
+        const auto middle = geography_degree_sincos<Float>(a.x, b.x, true);
+        const Float sm = middle.first;
+        const Float cm = middle.second;
+        const auto rotate_unit = [&](Float x, Float y, Float z) {
+            using std::sqrt;
+            const Float norm = sqrt(x * x + y * y + z * z);
+            DCHECK_GT(norm, 0);
+            return S2Point(static_cast<double>((cm * x - sm * y) / norm),
+                           static_cast<double>((sm * x + cm * y) / norm),
+                           static_cast<double>(z / norm));
+        };
+        const auto [nx, ny, nz] = geography_raw_normal(a, b, sd, cd);
+        normal = rotate_unit(nx, ny, nz);
+        const auto [sl, cl] = geography_degree_sincos<Float>(a.y, b.y, true);
+        const auto [st, ct] = geography_degree_sincos<Float>(b.y, -a.y, true);
+        midpoint = rotate_unit(cd * cl * ct, -sd * sl * st, sl * ct);
+    }
+};
+
+// Raw identity must survive ToPoint rounding: 58 and 58.00000000000001 degrees
+// produce the same S2Point, but only one is an endpoint of the original edge.
+struct GeographyVertex {
+    GeoCoordinate coordinate;
+    S2Point point;
+
+    GeographyVertex() : GeographyVertex({.x = 0, .y = 0}) {}
+    explicit GeographyVertex(GeoCoordinate value) : coordinate(value) {
+        if (std::abs(coordinate.y) == 90) {
+            coordinate.x = 0;
+            point = {0, 0, coordinate.y > 0 ? 1.0 : -1.0};
+        } else {
+            if (coordinate.x == 180) {
+                coordinate.x = -180;
+            }
+            point = S2LatLng::FromDegrees(coordinate.y, 
coordinate.x).ToPoint();
+        }
+    }
+    bool operator==(const GeographyVertex& other) const {
+        return coordinate.x == other.coordinate.x && coordinate.y == 
other.coordinate.y;
+    }
+    bool operator<(const GeographyVertex& other) const {
+        return std::pair {coordinate.x, coordinate.y} <
+               std::pair {other.coordinate.x, other.coordinate.y};
+    }
+};
+
+static bool geography_antipodal(const GeographyVertex& a, const 
GeographyVertex& b) {
+    return a.coordinate.y == -b.coordinate.y &&
+           (std::abs(a.coordinate.y) == 90 ||
+            geography_degree_sum(std::max(a.coordinate.x, b.coordinate.x),
+                                 -std::min(a.coordinate.x, b.coordinate.x)) ==
+                    std::pair {180.0, 0.0});
+}
+
+struct GeographyCoordinates {
+    GeoShapeType type = GeoShapeType::GEO_SHAPE_ANY;
+    DorisVector<DorisVector<GeographyVertex>> sequences;
+    GeoParseStatus status;
+
+    explicit GeographyCoordinates(StringRef wkb) {
+        GeoCoordinateListList raw;
+        status = WkbParse::calculation_coordinates(wkb.data, wkb.size, &raw, 
&type);
+        if (status != GeoParseStatus::GEO_PARSE_OK) {
+            return;
+        }
+        for (const auto& sequence : raw.list) {
+            auto& vertices = sequences.emplace_back();
+            for (const auto& coordinate : sequence->list) {
+                vertices.emplace_back(coordinate);
+            }
+        }
+    }
+};
+
+static bool geography_stable_points(const DorisVector<GeographyVertex>& 
sequence,
+                                    std::vector<S2Point>* points) {
+    for (size_t i = 0; i + 1 < sequence.size(); ++i) {
+        const auto& a = sequence[i];
+        const auto& b = sequence[i + 1];
+        // (0,0)->(180,0) has no unique arc and would normalize a zero raw 
normal.
+        if (geography_antipodal(a, b)) {
+            return false;
+        }
+        points->push_back(a.point);
+        // Stabilize before S2 admission: rounded (30,58)->(-150,-58-e) can be
+        // exactly antipodal despite its unique raw arc passing through the 
south pole.
+        if (a.point.DotProd(b.point) < 0) {
+            points->push_back(GeographyRawArc(a.coordinate, 
b.coordinate).midpoint);
+        }
+    }
+    // A line's final vertex is real, including its closing edge; only rings 
remove it.
+    points->push_back(sequence.back().point);
+    points->erase(std::ranges::unique(*points).begin(), points->end());
+    return true;
+}
+
+static std::unique_ptr<GeoShape> decode_geography_line(const 
GeographyCoordinates& raw,
+                                                       StringRef value) {
+    std::vector<S2Point> points;
+    if (!geography_stable_points(raw.sequences.front(), &points)) {
+        return nullptr;
+    }
+    if (points.size() < 2) {
+        // Canonical pole aliases such as (0,90),(90,90) collapse to one 
calculation
+        // point. Preserve their prior admission; the old parser still rejects 
a
+        // truly duplicate-only line such as (1,1),(1,1).
+        GeoParseStatus status;
+        return GeoShape::from_wkb_bytes(value.data, value.size, status);
+    }
+    auto polyline = std::make_unique<S2Polyline>(points, S2Debug::DISABLE);
+    if (!polyline->IsValid()) {
+        return nullptr;
+    }
+    return GeoLine::create_unique(std::move(polyline));
+}
+
+#ifdef BE_TEST
+static thread_local size_t geography_line_decodes = 0;
+#endif
+
+std::unique_ptr<GeoShape> decode_geography_calculation_shape(StringRef value) {
+    GeographyCoordinates raw(value);
+    if (raw.status != GeoParseStatus::GEO_PARSE_OK) {
+        return nullptr;
+    }
+    if (raw.type == GeoShapeType::GEO_SHAPE_POINT) {
+        GeoParseStatus status;
+        return GeoShape::from_wkb_bytes(value.data, value.size, status);
+    }
+    if (raw.type == GeoShapeType::GEO_SHAPE_LINE_STRING) {
+#ifdef BE_TEST
+        ++geography_line_decodes;
+#endif
+        return decode_geography_line(raw, value);
+    }
+    std::vector<std::unique_ptr<S2Loop>> loops;
+    std::vector<const S2Loop*> input_loops;
+    for (const auto& ring : raw.sequences) {
+        std::vector<S2Point> points;
+        // Validate holes against stable raw arcs, as with typed line 
admission.
+        if (!geography_stable_points(ring, &points)) {
+            return nullptr;
+        }
+        // Validated WKB rings are closed; only polygon admission removes that 
endpoint.
+        DCHECK(points.front() == points.back());
+        points.pop_back();
+        if (points.size() < 3) {
+            return nullptr;
+        }
+        auto loop = std::make_unique<S2Loop>(points, S2Debug::DISABLE);
+        if (!loop->IsValid()) {
+            return nullptr;
+        }
+        loop->Normalize();
+        if (!loops.empty() && !loops.front()->Contains(*loop)) {
+            return nullptr;
+        }
+        input_loops.push_back(loop.get());
+        loops.push_back(std::move(loop));
+    }
+    auto polygon = std::make_unique<S2Polygon>(std::move(loops), 
S2Debug::DISABLE);
+    if (!polygon->IsValid()) {
+        return nullptr;
+    }
+    std::vector<int> depths;
+    for (const auto* loop : input_loops) {
+        depths.push_back(loop->depth());
+    }
+    return GeoPolygon::create_unique(std::move(polygon), std::move(depths));
+}
+
+#ifdef BE_TEST
+static thread_local size_t geography_exact_proofs = 0;
+static thread_local size_t geography_candidate_visits = 0;
+static thread_local size_t geography_polygon_crossing_checks = 0;
+static thread_local size_t geography_polygon_admission_checks = 0;
+static thread_local size_t geography_point_polygon_preparations = 0;
+static thread_local size_t geography_point_line_preparations = 0;
+static thread_local size_t geography_point_line_candidates = 0;
+static thread_local size_t geography_point_line_queries = 0;
+static thread_local size_t geography_distance_evaluations = 0;
+static thread_local size_t geography_distance_pair_nodings = 0;
+#endif
+
+// Test coplanarity of the original degree ordinates, not independently 
rounded S2 vectors.
+// For example (45,-45), (90,0), (135,45) share an arc although ToPoint's 
determinant is nonzero.
+// Keep the dyadic conversion and polynomial reduction together for the 
exact-zero proof.
+// NOLINTNEXTLINE(readability-function-size)
+static bool geography_common_great_circle(const GeoCoordinate& a, const 
GeoCoordinate& b,

Review Comment:
   这个判定太严格了,正确性应该没问题,性能这块可以等合入之后测一下。



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to