Coverage Report

Created: 2026-04-10 12:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exprs/aggregate/aggregate_function_sem.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
#pragma once
19
20
#include <math.h>
21
22
#include "core/assert_cast.h"
23
#include "core/column/column.h"
24
#include "core/data_type/data_type.h"
25
#include "core/data_type/data_type_decimal.h"
26
#include "core/data_type/define_primitive_type.h"
27
#include "core/data_type/primitive_type.h"
28
#include "core/types.h"
29
#include "core/value/decimalv2_value.h"
30
#include "exprs/aggregate/aggregate_function.h"
31
32
namespace doris {
33
34
class Arena;
35
class BufferReadable;
36
class BufferWritable;
37
38
/**
39
 * SEM = sqrt(variance / count) = sqrt(m2 / (count * (count - 1)))
40
 * It uses Welford’s method for numerically stable one-pass computation of the mean and variance.
41
 */
42
struct AggregateFunctionSemData {
43
    double mean {};
44
    double m2 {}; // Cumulative sum of squares
45
    UInt64 count = 0;
46
47
    //  Let the old mean be mean_{n-1} and we receive a new value x_n.
48
    //  The new mean should be: mean_n = mean_{n-1} + (x_n - mean_{n-1}) / n
49
    //  The new M2 should capture total squared deviations from the new mean:
50
    //      M2_n = M2_{n-1} + (x_n - mean_{n-1}) * (x_n - mean_n)
51
166
    void add(const double& value) {
52
166
        count++;
53
166
        double delta = value - mean;
54
166
        mean += delta / static_cast<double>(count);
55
166
        double delta2 = value - mean;
56
166
        m2 += delta * delta2;
57
166
    }
58
59
    // Suppose we have dataset A (count_a, mean_a, M2_a) and B (count_b, mean_b, M2_b).
60
    // When merging:
61
    //   - The total count is count_a + count_b
62
    //   - The new mean is the weighted average of the two means
63
    //   - The new M2 accumulates both variances and an adjustment term to account for
64
    //     the difference in means between A and B:
65
    //        M2 = M2_a + M2_b + delta^2 * count_a * count_b / total_count
66
    // where delta = mean_b - mean_a
67
22
    void merge(const AggregateFunctionSemData& rhs) {
68
22
        UInt64 total_count = count + rhs.count;
69
22
        double delta = rhs.mean - mean;
70
22
        mean = (mean * static_cast<double>(count) + rhs.mean * static_cast<double>(rhs.count)) /
71
22
               static_cast<double>(total_count);
72
22
        m2 += rhs.m2 + delta * delta * static_cast<double>(count) * static_cast<double>(rhs.count) /
73
22
                               static_cast<double>(total_count);
74
22
        count = total_count;
75
22
    }
76
77
22
    void write(BufferWritable& buf) const {
78
22
        buf.write_binary(mean);
79
22
        buf.write_binary(m2);
80
22
        buf.write_binary(count);
81
22
    }
82
83
22
    void read(BufferReadable& buf) {
84
22
        buf.read_binary(mean);
85
22
        buf.read_binary(m2);
86
22
        buf.read_binary(count);
87
22
    }
88
89
3
    void reset() {
90
3
        mean = {};
91
3
        m2 = {};
92
3
        count = 0;
93
3
    }
94
95
27
    double result() const {
96
27
        if (count < 2) {
97
1
            return 0;
98
1
        }
99
26
        double dCount = static_cast<double>(count);
100
26
        double result = std::sqrt(m2 / (dCount * (dCount - 1.0)));
101
26
        return result;
102
27
    }
103
};
104
105
template <typename Data>
106
class AggregateFunctionSem final
107
        : public IAggregateFunctionDataHelper<Data, AggregateFunctionSem<Data>>,
108
          UnaryExpression,
109
          NullableAggregateFunction {
110
public:
111
    AggregateFunctionSem(const DataTypes& argument_types_)
112
24
            : IAggregateFunctionDataHelper<Data, AggregateFunctionSem<Data>>(argument_types_) {}
113
114
3
    String get_name() const override { return "sem"; }
115
116
51
    DataTypePtr get_return_type() const override { return std::make_shared<DataTypeFloat64>(); }
117
118
    void add(AggregateDataPtr __restrict place, const IColumn** columns, ssize_t row_num,
119
166
             Arena&) const override {
120
166
        const auto& column =
121
166
                assert_cast<const ColumnFloat64&, TypeCheckOnRelease::DISABLE>(*columns[0]);
122
166
        this->data(place).add((double)column.get_data()[row_num]);
123
166
    }
124
125
3
    void reset(AggregateDataPtr place) const override { this->data(place).reset(); }
126
127
    void merge(AggregateDataPtr __restrict place, ConstAggregateDataPtr rhs,
128
22
               Arena&) const override {
129
22
        this->data(place).merge(this->data(rhs));
130
22
    }
131
132
22
    void serialize(ConstAggregateDataPtr __restrict place, BufferWritable& buf) const override {
133
22
        this->data(place).write(buf);
134
22
    }
135
136
    void deserialize(AggregateDataPtr __restrict place, BufferReadable& buf,
137
22
                     Arena&) const override {
138
22
        this->data(place).read(buf);
139
22
    }
140
141
27
    void insert_result_into(ConstAggregateDataPtr __restrict place, IColumn& to) const override {
142
27
        auto& column = assert_cast<ColumnFloat64&>(to);
143
27
        column.get_data().push_back(this->data(place).result());
144
27
    }
145
};
146
147
} // namespace doris