Coverage Report

Created: 2026-09-17 08:03

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exprs/aggregate/aggregate_function_ema.h
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
// This file is adapted from
19
// https://github.com/ClickHouse/ClickHouse/blob/master/src/AggregateFunctions/AggregateFunctionExponentialMovingAverage.cpp
20
21
#pragma once
22
23
#include <cmath>
24
#include <limits>
25
#include <memory>
26
27
#include "common/exception.h"
28
#include "core/assert_cast.h"
29
#include "core/column/column_vector.h"
30
#include "core/data_type/data_type_number.h"
31
#include "core/types.h"
32
#include "exprs/aggregate/aggregate_function.h"
33
34
namespace doris {
35
class Arena;
36
class BufferReadable;
37
class BufferWritable;
38
class IColumn;
39
40
/**
41
 * Exponentially smoothed moving average over time.
42
 *
43
 * Each value corresponds to a timeunit index. The half_decay parameter is the
44
 * time lag at which exponential weights decay by one-half.
45
 *
46
 * State is a (value, time) pair representing the exponentially accumulated sum
47
 * at a reference time. To get the average, divide by sumWeights(half_decay).
48
 *
49
 * Formula:
50
 *   scale(dt, x) = 2^(-dt/x)
51
 *   sumWeights(x) = 1 / (1 - 2^(-1/x))
52
 *   add(v, t): merge current state with point (v, t)
53
 *   merge(a, b): move both to the later time, then sum values
54
 *   get():  value / sumWeights(half_decay)
55
 *
56
 * Usage: exponential_moving_average(half_decay, value, timeunit)
57
 *   - half_decay: constant double, the half-life period in timeunit units
58
 *   - value:      numeric column to average
59
 *   - timeunit:   numeric time index (not raw timestamp; use intDiv if needed)
60
 * Returns DOUBLE.
61
 *
62
 * A zero half_decay returns 0 but remains an initialized configuration. Only
63
 * fresh/reset states are identities; all initialized states must have matching
64
 * half decays when merged.
65
 */
66
struct ExponentialMovingAverageData {
67
    double value = 0.0;
68
    double time = 0.0;
69
    double half_decay = 0.0;
70
    bool initialized = false;
71
72
128
    static double scale(double time_passed, double hd) { return std::exp2(-time_passed / hd); }
73
74
58
    static double sum_weights(double hd) { return 1.0 / (1.0 - std::exp2(-1.0 / hd)); }
75
76
175
    void add(double new_value, double current_time, double hd) {
77
175
        half_decay = hd;
78
175
        initialized = true;
79
175
        ExponentialMovingAverageData other;
80
175
        other.value = new_value;
81
175
        other.time = current_time;
82
175
        merge_point(other, hd);
83
175
    }
84
85
191
    void merge_point(const ExponentialMovingAverageData& other, double hd) {
86
191
        if (time > other.time) {
87
4
            value = value + other.value * scale(time - other.time, hd);
88
187
        } else if (time < other.time) {
89
124
            value = other.value + value * scale(other.time - time, hd);
90
124
            time = other.time;
91
124
        } else {
92
63
            value = value + other.value;
93
63
        }
94
191
    }
95
96
112
    void merge(const ExponentialMovingAverageData& rhs) {
97
112
        if (!rhs.initialized) {
98
30
            return;
99
30
        }
100
82
        if (!initialized) {
101
42
            *this = rhs;
102
42
            return;
103
42
        }
104
40
        if (UNLIKELY(half_decay != rhs.half_decay)) {
105
24
            throw Exception(
106
24
                    ErrorCode::INVALID_ARGUMENT,
107
24
                    "exponential_moving_average aggregate states have incompatible half decay");
108
24
        }
109
16
        merge_point(rhs, half_decay);
110
16
    }
111
112
125
    double get() const {
113
125
        check_half_decay();
114
125
        if (half_decay == 0.0) {
115
66
            return 0.0;
116
66
        }
117
59
        return value / sum_weights(half_decay);
118
125
    }
119
120
54
    void write(BufferWritable& buf) const {
121
54
        check_half_decay();
122
54
        buf.write_binary(value);
123
54
        buf.write_binary(time);
124
        // NaN is rejected for configured states, so it can encode initialization without
125
        // adding a field or colliding with the valid zero half-decay configuration.
126
54
        buf.write_binary(initialized ? half_decay : std::numeric_limits<double>::quiet_NaN());
127
54
    }
128
129
67
    void read(BufferReadable& buf) {
130
67
        buf.read_binary(value);
131
67
        buf.read_binary(time);
132
67
        buf.read_binary(half_decay);
133
67
        initialized = !std::isnan(half_decay);
134
67
        if (!initialized) {
135
15
            half_decay = 0.0;
136
15
        }
137
67
    }
138
139
179
    void check_half_decay() const {
140
179
        if (UNLIKELY(std::isnan(half_decay))) {
141
2
            throw Exception(ErrorCode::INVALID_ARGUMENT,
142
2
                            "exponential_moving_average half decay must not be NaN");
143
2
        }
144
179
    }
145
146
6
    void reset() {
147
6
        value = 0.0;
148
6
        time = 0.0;
149
6
        half_decay = 0.0;
150
6
        initialized = false;
151
6
    }
152
};
153
154
class AggregateFunctionExponentialMovingAverage final
155
        : public IAggregateFunctionDataHelper<ExponentialMovingAverageData,
156
                                              AggregateFunctionExponentialMovingAverage>,
157
          MultiExpression,
158
          NullableAggregateFunction {
159
public:
160
    AggregateFunctionExponentialMovingAverage(const DataTypes& argument_types_)
161
5
            : IAggregateFunctionDataHelper<ExponentialMovingAverageData,
162
5
                                           AggregateFunctionExponentialMovingAverage>(
163
5
                      argument_types_) {}
164
165
0
    String get_name() const override { return "exponential_moving_average"; }
166
167
125
    DataTypePtr get_return_type() const override { return std::make_shared<DataTypeFloat64>(); }
168
169
6
    void reset(AggregateDataPtr __restrict place) const override { this->data(place).reset(); }
170
171
    void add(AggregateDataPtr __restrict place, const IColumn** columns, ssize_t row_num,
172
175
             Arena&) const override {
173
175
        const double half_decay =
174
175
                assert_cast<const ColumnFloat64&, TypeCheckOnRelease::DISABLE>(*columns[0])
175
175
                        .get_data()[row_num];
176
175
        const double new_value =
177
175
                assert_cast<const ColumnFloat64&, TypeCheckOnRelease::DISABLE>(*columns[1])
178
175
                        .get_data()[row_num];
179
175
        const double current_time =
180
175
                assert_cast<const ColumnFloat64&, TypeCheckOnRelease::DISABLE>(*columns[2])
181
175
                        .get_data()[row_num];
182
175
        this->data(place).add(new_value, current_time, half_decay);
183
175
    }
184
185
0
    void check_input_columns_type(const IColumn** columns) const override {
186
0
        this->template check_argument_column_type<ColumnFloat64>(columns[0]);
187
0
        this->template check_argument_column_type<ColumnFloat64>(columns[1]);
188
0
        this->template check_argument_column_type<ColumnFloat64>(columns[2]);
189
0
    }
190
191
    void merge(AggregateDataPtr __restrict place, ConstAggregateDataPtr rhs,
192
112
               Arena&) const override {
193
112
        this->data(place).merge(this->data(rhs));
194
112
    }
195
196
54
    void serialize(ConstAggregateDataPtr __restrict place, BufferWritable& buf) const override {
197
54
        this->data(place).write(buf);
198
54
    }
199
200
    void deserialize(AggregateDataPtr __restrict place, BufferReadable& buf,
201
67
                     Arena&) const override {
202
67
        this->data(place).read(buf);
203
67
    }
204
205
125
    void insert_result_into(ConstAggregateDataPtr __restrict place, IColumn& to) const override {
206
125
        assert_cast<ColumnFloat64&, TypeCheckOnRelease::DISABLE>(to).get_data().push_back(
207
125
                this->data(place).get());
208
125
    }
209
};
210
211
} // namespace doris