1#include "config_functions.h"
2#if USE_H3
3# include <Columns/ColumnsNumber.h>
4# include <DataTypes/DataTypesNumber.h>
5# include <Functions/FunctionFactory.h>
6# include <Functions/IFunction.h>
7# include <Common/typeid_cast.h>
8# include <ext/range.h>
9
10# include <h3api.h>
11
12
13namespace DB
14{
15// Average metric edge length of H3 hexagon. The edge length `e` for given resolution `res` can
16// be used for converting metric search radius `radius` to hexagon search ring size `k` that is
17// used by `H3kRing` function. For small enough search area simple flat approximation can be used,
18// i.e. the smallest `k` that satisfies relation `3 k^2 - 3 k + 1 >= (radius / e)^2` should be
19// chosen
20class FunctionH3EdgeLengthM : public IFunction
21{
22public:
23 static constexpr auto name = "h3EdgeLengthM";
24
25 static FunctionPtr create(const Context &) { return std::make_shared<FunctionH3EdgeLengthM>(); }
26
27 std::string getName() const override { return name; }
28
29 size_t getNumberOfArguments() const override { return 1; }
30 bool useDefaultImplementationForConstants() const override { return true; }
31
32 DataTypePtr getReturnTypeImpl(const DataTypes & arguments) const override
33 {
34 auto arg = arguments[0].get();
35 if (!WhichDataType(arg).isUInt8())
36 throw Exception(
37 "Illegal type " + arg->getName() + " of argument " + std::to_string(1) + " of function " + getName() + ". Must be UInt8",
38 ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);
39
40 return std::make_shared<DataTypeFloat64>();
41 }
42
43 void executeImpl(Block & block, const ColumnNumbers & arguments, size_t result, size_t input_rows_count) override
44 {
45 const auto col_hindex = block.getByPosition(arguments[0]).column.get();
46
47 auto dst = ColumnVector<Float64>::create();
48 auto & dst_data = dst->getData();
49 dst_data.resize(input_rows_count);
50
51 for (const auto row : ext::range(0, input_rows_count))
52 {
53 const int resolution = col_hindex->getUInt(row);
54
55 Float64 res = edgeLengthM(resolution);
56
57 dst_data[row] = res;
58 }
59
60 block.getByPosition(result).column = std::move(dst);
61 }
62};
63
64
65void registerFunctionH3EdgeLengthM(FunctionFactory & factory)
66{
67 factory.registerFunction<FunctionH3EdgeLengthM>();
68}
69
70}
71#endif
72