ClickHouse

Форк
0
/
pointInEllipses.cpp 
200 строк · 7.2 Кб
1
#include <DataTypes/DataTypesNumber.h>
2
#include <Columns/ColumnsNumber.h>
3
#include <Columns/ColumnConst.h>
4
#include <Common/typeid_cast.h>
5
#include <Common/assert_cast.h>
6
#include <Functions/IFunction.h>
7
#include <Functions/FunctionHelpers.h>
8
#include <Functions/FunctionFactory.h>
9
#include <base/range.h>
10

11

12
namespace DB
13
{
14
namespace ErrorCodes
15
{
16
    extern const int ILLEGAL_TYPE_OF_ARGUMENT;
17
    extern const int TOO_MANY_ARGUMENTS_FOR_FUNCTION;
18
    extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH;
19
    extern const int ILLEGAL_COLUMN;
20
}
21

22
namespace
23
{
24

25
/**
26
 * The function checks if a point is in one of ellipses in set.
27
 * The number of arguments must be 2 + 4*N where N is the number of ellipses.
28
 * The arguments must be arranged as follows: (x, y, x_0, y_0, a_0, b_0, ..., x_i, y_i, a_i, b_i)
29
 * All ellipses parameters must be const values;
30
 *
31
 * The function first checks bounding box condition.
32
 * If a point is inside an ellipse's bounding box, the quadratic condition is evaluated.
33
 *
34
 * Here we assume that points in one columns are close and are likely to fit in one ellipse,
35
 * so the last success ellipse index is remembered to check this ellipse first for next point.
36
 *
37
 */
38
class FunctionPointInEllipses : public IFunction
39
{
40
public:
41
    static constexpr auto name = "pointInEllipses";
42
    static FunctionPtr create(ContextPtr) { return std::make_shared<FunctionPointInEllipses>(); }
43

44
private:
45

46
    struct Ellipse
47
    {
48
        Float64 x;
49
        Float64 y;
50
        Float64 a;
51
        Float64 b;
52
    };
53

54
    String getName() const override { return name; }
55

56
    bool isVariadic() const override { return true; }
57

58
    bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return true; }
59

60
    size_t getNumberOfArguments() const override { return 0; }
61

62
    DataTypePtr getReturnTypeImpl(const DataTypes & arguments) const override
63
    {
64
        if (arguments.size() < 6 || arguments.size() % 4 != 2)
65
        {
66
            throw Exception(ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH,
67
                "Incorrect number of arguments of function {}. "
68
                "Must be 2 for your point plus 4 * N for ellipses (x_i, y_i, a_i, b_i).", getName());
69
        }
70

71
        /// For array on stack, see below.
72
        if (arguments.size() > 10000)
73
        {
74
            throw Exception(ErrorCodes::TOO_MANY_ARGUMENTS_FOR_FUNCTION,
75
                            "Number of arguments of function {} is too large (maximum: 10000).",
76
                            getName());
77
        }
78

79
        for (const auto arg_idx : collections::range(0, arguments.size()))
80
        {
81
            const auto * arg = arguments[arg_idx].get();
82
            if (!WhichDataType(arg).isFloat64())
83
            {
84
                throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Illegal type {} of argument {} of function {}. "
85
                    "Must be Float64", arg->getName(), std::to_string(arg_idx + 1), getName());
86
            }
87
        }
88

89
        return std::make_shared<DataTypeUInt8>();
90
    }
91

92
    ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t input_rows_count) const override
93
    {
94
        const auto size = input_rows_count;
95

96
        /// Prepare array of ellipses.
97
        size_t ellipses_count = (arguments.size() - 2) / 4;
98
        std::vector<Ellipse> ellipses(ellipses_count);
99

100
        for (const auto ellipse_idx : collections::range(0, ellipses_count))
101
        {
102
            Float64 ellipse_data[4];
103
            for (const auto idx : collections::range(0, 4))
104
            {
105
                size_t arg_idx = 2 + 4 * ellipse_idx + idx;
106
                const auto * column = arguments[arg_idx].column.get();
107
                if (const auto * col = checkAndGetColumnConst<ColumnVector<Float64>>(column))
108
                {
109
                    ellipse_data[idx] = col->getValue<Float64>();
110
                }
111
                else
112
                {
113
                    throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Illegal type {} of argument {} of function {}. "
114
                        "Must be const Float64", column->getName(), std::to_string(arg_idx + 1), getName());
115
                }
116
            }
117
            ellipses[ellipse_idx] = Ellipse{ellipse_data[0], ellipse_data[1], ellipse_data[2], ellipse_data[3]};
118
        }
119

120
        int const_cnt = 0;
121
        for (const auto idx : collections::range(0, 2))
122
        {
123
            const auto * column = arguments[idx].column.get();
124
            if (typeid_cast<const ColumnConst *> (column))
125
            {
126
                ++const_cnt;
127
            }
128
            else if (!typeid_cast<const ColumnVector<Float64> *> (column))
129
            {
130
                throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}",
131
                    column->getName(), getName());
132
            }
133
        }
134

135
        const auto * col_x = arguments[0].column.get();
136
        const auto * col_y = arguments[1].column.get();
137
        if (const_cnt == 0)
138
        {
139
                const auto * col_vec_x = assert_cast<const ColumnVector<Float64> *> (col_x);
140
                const auto * col_vec_y = assert_cast<const ColumnVector<Float64> *> (col_y);
141

142
                auto dst = ColumnVector<UInt8>::create();
143
                auto & dst_data = dst->getData();
144
                dst_data.resize(size);
145

146
                size_t start_index = 0;
147
                for (const auto row : collections::range(0, size))
148
                {
149
                    dst_data[row] = isPointInEllipses(col_vec_x->getData()[row], col_vec_y->getData()[row], ellipses.data(), ellipses_count, start_index);
150
                }
151

152
                return dst;
153
        }
154
        else if (const_cnt == 2)
155
        {
156
            const auto * col_const_x = assert_cast<const ColumnConst *> (col_x);
157
            const auto * col_const_y = assert_cast<const ColumnConst *> (col_y);
158
            size_t start_index = 0;
159
            UInt8 res = isPointInEllipses(col_const_x->getValue<Float64>(), col_const_y->getValue<Float64>(), ellipses.data(), ellipses_count, start_index);
160
            return DataTypeUInt8().createColumnConst(size, res);
161
        }
162
        else
163
        {
164
            throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Illegal types {}, {} of arguments 1, 2 of function {}. "
165
                "Both must be either const or vector", col_x->getName(), col_y->getName(), getName());
166
        }
167
    }
168

169
    static bool isPointInEllipses(Float64 x, Float64 y, const Ellipse * ellipses, size_t ellipses_count, size_t & start_index)
170
    {
171
        size_t index = 0 + start_index;
172
        for (size_t i = 0; i < ellipses_count; ++i)
173
        {
174
            Ellipse el = ellipses[index];
175
            double p1 = ((x - el.x) / el.a);
176
            double p2 = ((y - el.y) / el.b);
177
            if (x <= el.x + el.a && x >= el.x - el.a && y <= el.y + el.b && y >= el.y - el.b /// Bounding box check
178
                && p1 * p1 + p2 * p2 <= 1.0)    /// Precise check
179
            {
180
                start_index = index;
181
                return true;
182
            }
183
            ++index;
184
            if (index == ellipses_count)
185
            {
186
                index = 0;
187
            }
188
        }
189
        return false;
190
    }
191
};
192

193
}
194

195
REGISTER_FUNCTION(PointInEllipses)
196
{
197
    factory.registerFunction<FunctionPointInEllipses>();
198
}
199

200
}
201

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.