You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@doris.apache.org by "wrlcke (via GitHub)" <gi...@apache.org> on 2026/02/25 12:01:21 UTC

[PR] [Feature](agg) add agg function entropy [doris]

wrlcke opened a new pull request, #60833:
URL: https://github.com/apache/doris/pull/60833

   ### What problem does this PR solve?
   
   add new aggregate function entropy
   
   Issue Number: #48203 
   
   Related PR: #xxx
   
   Problem Summary:
   
   ### Release note
   
   None
   
   ### Check List (For Author)
   
   - Test <!-- At least one of them must be included. -->
       - [x] Regression test
       - [x] Unit Test
       - [ ] Manual test (add detailed scripts or steps below)
       - [ ] No need to test or manual test. Explain why:
           - [ ] This is a refactor/code format and no logic has been changed.
           - [ ] Previous test can cover this change.
           - [ ] No code files have been changed.
           - [ ] Other reason <!-- Add your reason?  -->
   
   - Behavior changed:
       - [x] No.
       - [ ] Yes. <!-- Explain the behavior change -->
   
   - Does this need documentation?
       - [ ] No.
       - [x] Yes. [https://github.com/apache/doris-website/pull/3412](https://github.com/apache/doris-website/pull/3412)
   
   ### Check List (For Reviewer who merge this PR)
   
   - [ ] Confirm the release note
   - [ ] Confirm test cases
   - [ ] Confirm document
   - [ ] Add branch pick label <!-- Add branch pick label that this PR should merge into -->
   
   


-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [Feature](agg) add agg function entropy [doris]

Posted by "wrlcke (via GitHub)" <gi...@apache.org>.
wrlcke commented on code in PR #60833:
URL: https://github.com/apache/doris/pull/60833#discussion_r2931766906


##########
be/test/exprs/aggregate/agg_function_test.h:
##########
@@ -179,8 +179,11 @@ struct AggregateFunctiontest : public testing::Test {
 
                 agg_fn->create(place);
                 Defer defer([&]() { agg_fn->destroy(place); });
-                agg_fn->function()->deserialize_and_merge_from_column_range(
-                        place, *serialize_column, 0, block.rows() - 1, arena);
+
+                if (block.rows() != 0) {

Review Comment:
   Do you mean there might be a case where an empty block is supposed to trigger an error?
   In this test framework, the block is provided by the test author, so if it contains zero rows it usually means the test intentionally wants to verify the behavior on empty input. In such cases there’s nothing to merge here so it should be skipped (in other merge path it's naturally skipped but here streaming_agg_serialize_to_column will produce an empty column)



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [Feature](agg) add agg function entropy [doris]

Posted by "wrlcke (via GitHub)" <gi...@apache.org>.
wrlcke commented on code in PR #60833:
URL: https://github.com/apache/doris/pull/60833#discussion_r2931763807


##########
regression-test/suites/query_p0/aggregate/aggregate_function_entropy.groovy:
##########
@@ -0,0 +1,185 @@
+// 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.
+
+suite("test_entropy") {
+
+    sql """set enable_nereids_planner=true"""
+    sql """set enable_fallback_to_original_planner=false"""
+    sql """set enable_decimal256=true"""
+
+    qt_entropy_null """select entropy(NULL)"""

Review Comment:
   zero column is tested here https://github.com/apache/doris/pull/60833/changes#diff-5f776e3021bda437388266abe7075c79f487ce0ad6ba66cd2e0873c1e191a37bR183
   ```
   qt_entropy_empty """select entropy(col_int) from test_entropy where 1=0"""
   ```



##########
regression-test/suites/query_p0/aggregate/aggregate_function_entropy.groovy:
##########
@@ -0,0 +1,185 @@
+// 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.
+
+suite("test_entropy") {
+
+    sql """set enable_nereids_planner=true"""

Review Comment:
   ok



##########
be/src/exprs/aggregate/aggregate_function_entropy.h:
##########
@@ -0,0 +1,191 @@
+// 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.
+// This file is copied from
+// https://github.com/ClickHouse/ClickHouse/blob/master/src/AggregateFunctions/AggregateFunctionEntropy.cpp
+// and modified by Doris
+
+#pragma once
+
+#include "core/assert_cast.h"
+#include "core/column/column.h"
+#include "core/column/column_decimal.h"
+#include "core/data_type/data_type.h"
+#include "core/data_type/data_type_number.h"
+#include "core/string_ref.h"
+#include "core/types.h"
+#include "core/uint128.h"
+#include "exec/common/hash_table/hash.h"
+#include "exec/common/hash_table/phmap_fwd_decl.h"
+#include "exprs/aggregate/aggregate_function.h"
+
+namespace doris {
+#include "common/compile_check_begin.h"
+
+class Arena;
+class BufferReadable;
+class BufferWritable;
+template <PrimitiveType>
+class ColumnVector;
+
+/** Calculates Shannon Entropy, using HashMap and computing empirical distribution function.
+  * Entropy is measured in bits (base-2 logarithm is used).
+  */
+template <typename Value, typename Hash = HashCRC32<Value>>
+struct AggregateFunctionEntropyData {
+    using Container = flat_hash_map<Value, uint64_t, Hash>;
+    using Self = AggregateFunctionEntropyData<Value, Hash>;
+    Container frequency_map;
+
+    void clear() { frequency_map.clear(); }
+
+    void add(const Value& elem) { ++frequency_map[elem]; }
+
+    void merge(const Self& rhs) {
+        frequency_map.reserve(frequency_map.size() + rhs.frequency_map.size());
+        for (const auto& [elem, count] : rhs.frequency_map) {
+            frequency_map[elem] += count;
+        }
+    }
+
+    void write(BufferWritable& buf) const {
+        buf.write_var_uint(frequency_map.size());
+        for (const auto& [elem, count] : frequency_map) {
+            buf.write_binary(elem);
+            buf.write_binary(count);
+        }
+    }
+
+    void read(BufferReadable& buf) {
+        uint64_t new_size = 0;
+        buf.read_var_uint(new_size);
+        frequency_map.reserve(frequency_map.size() + new_size);
+
+        Value elem;
+        uint64_t count;
+        for (size_t i = 0; i < new_size; ++i) {
+            buf.read_binary(elem);
+            buf.read_binary(count);
+            frequency_map[elem] += count;
+        }
+    }
+
+    Float64 get_result() const {
+        Float64 entropy = 0;
+        uint64_t total_count = 0;
+        for (const auto& [_, count] : frequency_map) {
+            total_count += count;
+        }
+        for (const auto& [_, count] : frequency_map) {
+            Float64 p = static_cast<Float64>(count) / static_cast<Float64>(total_count);
+            entropy -= p * std::log2(p);
+        }
+        return entropy;
+    }
+
+    static String get_name() { return "entropy"; }
+};
+
+template <PrimitiveType T>
+struct AggregateFunctionEntropySingleNumericData
+        : public AggregateFunctionEntropyData<typename PrimitiveTypeTraits<T>::CppType> {
+    using Base = AggregateFunctionEntropyData<typename PrimitiveTypeTraits<T>::CppType>;
+
+    void add(const IColumn** columns, size_t /* columns_num */, size_t row_num, Arena&) {
+        const auto& vec = assert_cast<const typename PrimitiveTypeTraits<T>::ColumnType&,
+                                      TypeCheckOnRelease::DISABLE>(*columns[0])
+                                  .get_data();
+        Base::add(vec[row_num]);
+    }
+};
+
+struct AggregateFunctionEntropySingleStringData
+        : public AggregateFunctionEntropyData<UInt128, UInt128TrivialHash> {
+    using Base = AggregateFunctionEntropyData<UInt128, UInt128TrivialHash>;
+
+    void add(const IColumn** columns, size_t /* columns_num */, size_t row_num, Arena&) {
+        auto key = columns[0]->get_data_at(row_num);

Review Comment:
   ok



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [Feature](agg) add agg function entropy [doris]

Posted by "doris-robot (via GitHub)" <gi...@apache.org>.
doris-robot commented on PR #60833:
URL: https://github.com/apache/doris/pull/60833#issuecomment-4061651303

   
   <details>
   <summary>TPC-DS: <b>Total hot run time: 169384 ms</b></summary>
   
   ```
   machine: 'aliyun_ecs.c7a.8xlarge_32C64G'
   scripts: https://github.com/apache/doris/tree/master/tools/tpcds-tools
   TPC-DS sf100 test result on commit 4ef69af34e68c432ec507db3d432690b9cce55ed, data reload: false
   
   query5	4344	653	536	536
   query6	325	241	221	221
   query7	4238	477	272	272
   query8	354	282	244	244
   query9	8726	2775	2741	2741
   query10	522	400	345	345
   query11	6976	5118	4902	4902
   query12	182	133	124	124
   query13	1268	468	351	351
   query14	5685	3700	3500	3500
   query14_1	2869	2863	2907	2863
   query15	203	196	177	177
   query16	975	449	442	442
   query17	913	747	639	639
   query18	2449	460	356	356
   query19	210	212	192	192
   query20	136	134	131	131
   query21	214	136	119	119
   query22	13311	14186	14501	14186
   query23	16311	15910	15774	15774
   query23_1	16141	15790	16306	15790
   query24	7267	1645	1257	1257
   query24_1	1271	1267	1269	1267
   query25	570	498	528	498
   query26	1244	277	158	158
   query27	2754	493	292	292
   query28	4483	1866	1852	1852
   query29	822	575	483	483
   query30	296	224	190	190
   query31	1040	945	900	900
   query32	80	72	70	70
   query33	514	331	281	281
   query34	921	872	529	529
   query35	642	679	609	609
   query36	1074	1143	951	951
   query37	140	102	89	89
   query38	2963	2985	2877	2877
   query39	864	823	817	817
   query39_1	832	821	792	792
   query40	226	153	135	135
   query41	63	61	58	58
   query42	265	256	260	256
   query43	250	259	220	220
   query44	
   query45	202	191	182	182
   query46	889	988	598	598
   query47	2124	3023	2054	2054
   query48	322	322	233	233
   query49	634	462	378	378
   query50	677	295	218	218
   query51	4109	4120	3982	3982
   query52	265	271	258	258
   query53	295	330	294	294
   query54	296	276	274	274
   query55	95	83	86	83
   query56	317	310	322	310
   query57	1950	1743	1705	1705
   query58	290	274	269	269
   query59	2805	2951	2722	2722
   query60	348	342	327	327
   query61	152	148	152	148
   query62	633	579	537	537
   query63	313	287	283	283
   query64	4938	1244	956	956
   query65	
   query66	1464	459	358	358
   query67	24375	24586	24273	24273
   query68	
   query69	398	326	287	287
   query70	992	990	943	943
   query71	332	316	313	313
   query72	2943	2684	2417	2417
   query73	552	555	315	315
   query74	9611	9542	9433	9433
   query75	2863	2758	2477	2477
   query76	2277	1037	691	691
   query77	362	391	316	316
   query78	10879	11186	10474	10474
   query79	2357	779	577	577
   query80	1747	629	559	559
   query81	553	268	221	221
   query82	1013	149	132	132
   query83	334	260	249	249
   query84	299	116	93	93
   query85	903	500	446	446
   query86	418	306	308	306
   query87	3156	3166	3020	3020
   query88	3595	2661	2645	2645
   query89	432	375	345	345
   query90	2012	186	186	186
   query91	169	161	137	137
   query92	82	75	71	71
   query93	1029	877	503	503
   query94	626	322	291	291
   query95	584	341	389	341
   query96	637	519	233	233
   query97	2437	2471	2431	2431
   query98	241	221	217	217
   query99	1038	1009	902	902
   Total cold run time: 251330 ms
   Total hot run time: 169384 ms
   ```
   </details>
   


-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [Feature](agg) add agg function entropy [doris]

Posted by "doris-robot (via GitHub)" <gi...@apache.org>.
doris-robot commented on PR #60833:
URL: https://github.com/apache/doris/pull/60833#issuecomment-4065004551

   
   <details>
   <summary>TPC-DS: <b>Total hot run time: 167661 ms</b></summary>
   
   ```
   machine: 'aliyun_ecs.c7a.8xlarge_32C64G'
   scripts: https://github.com/apache/doris/tree/master/tools/tpcds-tools
   TPC-DS sf100 test result on commit 9b7d7b3a7fd662d34a1d23ade4ee79aeac35f263, data reload: false
   
   query5	4329	637	498	498
   query6	342	222	235	222
   query7	4217	459	273	273
   query8	336	230	229	229
   query9	8716	2744	2751	2744
   query10	523	405	344	344
   query11	6982	5070	4874	4874
   query12	183	133	130	130
   query13	1275	481	351	351
   query14	5702	3691	3437	3437
   query14_1	2822	2802	2821	2802
   query15	215	196	176	176
   query16	975	460	447	447
   query17	913	724	647	647
   query18	2448	455	355	355
   query19	214	212	188	188
   query20	139	132	125	125
   query21	214	135	108	108
   query22	13220	13947	14690	13947
   query23	16179	16003	15738	15738
   query23_1	15622	15716	15302	15302
   query24	7228	1613	1215	1215
   query24_1	1218	1224	1253	1224
   query25	537	459	397	397
   query26	1236	265	153	153
   query27	2781	473	306	306
   query28	4489	1824	1837	1824
   query29	880	564	474	474
   query30	301	221	188	188
   query31	998	942	871	871
   query32	86	72	69	69
   query33	506	323	288	288
   query34	904	873	532	532
   query35	650	685	595	595
   query36	1078	1117	969	969
   query37	126	95	88	88
   query38	2943	2927	2867	2867
   query39	857	841	799	799
   query39_1	788	805	812	805
   query40	231	160	132	132
   query41	62	58	58	58
   query42	267	260	250	250
   query43	236	246	214	214
   query44	
   query45	198	191	181	181
   query46	879	974	612	612
   query47	2122	2151	2070	2070
   query48	315	318	229	229
   query49	660	461	382	382
   query50	693	278	205	205
   query51	4075	4064	3980	3980
   query52	264	267	254	254
   query53	282	332	286	286
   query54	293	274	267	267
   query55	102	85	85	85
   query56	319	316	306	306
   query57	1910	1793	1698	1698
   query58	284	280	271	271
   query59	2796	2943	2764	2764
   query60	335	342	318	318
   query61	155	149	148	148
   query62	636	590	534	534
   query63	304	274	270	270
   query64	5142	1261	1006	1006
   query65	
   query66	1500	457	357	357
   query67	24209	24325	24161	24161
   query68	
   query69	408	305	284	284
   query70	951	962	946	946
   query71	328	301	302	301
   query72	2807	2665	2166	2166
   query73	548	544	319	319
   query74	9650	9582	9473	9473
   query75	2861	2731	2457	2457
   query76	2279	1028	700	700
   query77	363	376	303	303
   query78	11003	11297	10501	10501
   query79	1085	836	580	580
   query80	688	632	528	528
   query81	486	269	232	232
   query82	1365	151	118	118
   query83	369	268	250	250
   query84	297	114	95	95
   query85	846	475	427	427
   query86	370	308	332	308
   query87	3151	3165	2968	2968
   query88	3596	2663	2664	2663
   query89	418	371	340	340
   query90	2021	177	165	165
   query91	173	157	136	136
   query92	80	73	70	70
   query93	904	878	483	483
   query94	458	325	283	283
   query95	598	410	320	320
   query96	654	529	230	230
   query97	2527	2492	2408	2408
   query98	233	241	220	220
   query99	1001	972	925	925
   Total cold run time: 248275 ms
   Total hot run time: 167661 ms
   ```
   </details>
   


-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [Feature](agg) add agg function entropy [doris]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #60833:
URL: https://github.com/apache/doris/pull/60833#discussion_r2853375419


##########
be/src/vec/aggregate_functions/aggregate_function_entropy.h:
##########
@@ -0,0 +1,191 @@
+// 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.
+// This file is copied from
+// https://github.com/ClickHouse/ClickHouse/blob/master/src/AggregateFunctions/AggregateFunctionEntropy.cpp
+// and modified by Doris
+
+#pragma once
+
+#include "vec/aggregate_functions/aggregate_function.h"
+#include "vec/columns/column.h"
+#include "vec/columns/column_decimal.h"
+#include "vec/common/assert_cast.h"
+#include "vec/common/hash_table/hash.h"
+#include "vec/common/hash_table/phmap_fwd_decl.h"
+#include "vec/common/string_ref.h"
+#include "vec/common/uint128.h"
+#include "vec/core/types.h"
+#include "vec/data_types/data_type.h"
+#include "vec/data_types/data_type_number.h"
+
+namespace doris::vectorized {
+#include "common/compile_check_begin.h"
+
+class Arena;
+class BufferReadable;
+class BufferWritable;
+template <PrimitiveType>
+class ColumnVector;
+
+/** Calculates Shannon Entropy, using HashMap and computing empirical distribution function.
+  * Entropy is measured in bits (base-2 logarithm is used).
+  */
+template <typename Value, typename Hash = HashCRC32<Value>>
+struct AggregateFunctionEntropyData {
+    using Container = flat_hash_map<Value, uint64_t, Hash>;
+    using Self = AggregateFunctionEntropyData<Value, Hash>;
+    Container frequency_map;
+
+    void clear() { frequency_map.clear(); }
+
+    void add(const Value& elem) { ++frequency_map[elem]; }
+
+    void merge(const Self& rhs) {
+        frequency_map.reserve(frequency_map.size() + rhs.frequency_map.size());
+        for (const auto& [elem, count] : rhs.frequency_map) {
+            frequency_map[elem] += count;
+        }
+    }
+
+    void write(BufferWritable& buf) const {
+        buf.write_var_uint(frequency_map.size());
+        for (const auto& [elem, count] : frequency_map) {
+            buf.write_binary(elem);
+            buf.write_binary(count);
+        }
+    }
+
+    void read(BufferReadable& buf) {
+        uint64_t new_size = 0;
+        buf.read_var_uint(new_size);
+        frequency_map.reserve(frequency_map.size() + new_size);
+
+        Value elem;
+        uint64_t count;
+        for (size_t i = 0; i < new_size; ++i) {
+            buf.read_binary(elem);
+            buf.read_binary(count);
+            frequency_map[elem] += count;
+        }
+    }
+
+    Float64 get_result() const {
+        Float64 entropy = 0;
+        uint64_t total_count = 0;
+        for (const auto& [_, count] : frequency_map) {
+            total_count += count;
+        }
+        for (const auto& [_, count] : frequency_map) {
+            Float64 p = static_cast<Float64>(count) / static_cast<Float64>(total_count);
+            entropy -= p * std::log2(p);
+        }
+        return entropy;
+    }

Review Comment:
   The get_result() method has a division by zero bug when the frequency_map is empty (no data has been added). When total_count is 0, line 93 performs a division by zero. This needs to be handled by checking if total_count is 0 and returning 0.0 in that case before attempting the division.



##########
be/test/vec/aggregate_functions/agg_entropy_test.cpp:
##########
@@ -0,0 +1,115 @@
+// 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 <gtest/gtest.h>
+
+#include "agg_function_test.h"
+
+namespace doris::vectorized {
+
+struct AggregateFunctionEntropyTest : public AggregateFunctiontest {};
+
+// ------------------------------------------------------------
+// 1. Numeric entropy test
+// ------------------------------------------------------------
+TEST_F(AggregateFunctionEntropyTest, test_numeric_entropy) {
+    create_agg("entropy", false, {std::make_shared<DataTypeInt32>()},
+               std::make_shared<DataTypeFloat64>());
+
+    // values: 1,1,2,2,3
+    Block block = ColumnHelper::create_block<DataTypeInt32>({1, 1, 2, 2, 3});
+
+    double p1 = 2.0 / 5;
+    double p2 = 2.0 / 5;
+    double p3 = 1.0 / 5;
+    double expected = -(p1 * log2(p1) + p2 * log2(p2) + p3 * log2(p3));
+
+    execute(block, ColumnHelper::create_column_with_name<DataTypeFloat64>({expected}));
+}
+
+// ------------------------------------------------------------
+// 2. String entropy test
+// ------------------------------------------------------------
+TEST_F(AggregateFunctionEntropyTest, test_string_entropy) {
+    create_agg("entropy", false, {std::make_shared<DataTypeString>()},
+               std::make_shared<DataTypeFloat64>());
+
+    Block block = ColumnHelper::create_block<DataTypeString>({"a", "a", "b"});
+
+    double p1 = 2.0 / 3;
+    double p2 = 1.0 / 3;
+    double expected = -(p1 * log2(p1) + p2 * log2(p2));
+
+    execute(block, ColumnHelper::create_column_with_name<DataTypeFloat64>({expected}));
+}
+
+// ------------------------------------------------------------
+// 3. Generic entropy test
+// ------------------------------------------------------------
+TEST_F(AggregateFunctionEntropyTest, test_generic_entropy) {
+    create_agg("entropy", false,
+               {std::make_shared<DataTypeInt32>(), std::make_shared<DataTypeString>()},
+               std::make_shared<DataTypeFloat64>());
+
+    // rows:
+    // (1, "a")
+    // (1, "a")
+    // (2, "b")
+    Block block =
+            ColumnHelper::create_block<DataTypeInt32, DataTypeString>({1, 1, 2}, {"a", "a", "b"});
+
+    double p1 = 2.0 / 3;
+    double p2 = 1.0 / 3;
+    double expected = -(p1 * log2(p1) + p2 * log2(p2));
+
+    execute(block, ColumnHelper::create_column_with_name<DataTypeFloat64>({expected}));
+}
+
+// ------------------------------------------------------------
+// 4. NULL entropy test
+// ------------------------------------------------------------
+TEST_F(AggregateFunctionEntropyTest, test_nullable_entropy) {
+    create_agg("entropy", false,
+               {std::make_shared<DataTypeNullable>(std::make_shared<DataTypeInt32>())},
+               std::make_shared<DataTypeFloat64>());
+
+    // values: 1,1,NULL,2,NULL
+    Block block =
+            ColumnHelper::create_nullable_block<DataTypeInt32>({1, 1, 0, 2, 0}, {0, 0, 1, 0, 1});
+
+    // only non-null values: 1,1,2
+    double p1 = 2.0 / 3;
+    double p2 = 1.0 / 3;
+    double expected = -(p1 * log2(p1) + p2 * log2(p2));
+
+    execute(block, ColumnHelper::create_column_with_name<DataTypeFloat64>({expected}));
+}
+
+// ------------------------------------------------------------
+// 5. Empty input test
+// ------------------------------------------------------------
+TEST_F(AggregateFunctionEntropyTest, test_empty) {
+    create_agg("entropy", false, {std::make_shared<DataTypeInt32>()},
+               std::make_shared<DataTypeFloat64>());
+
+    Block block = ColumnHelper::create_block<DataTypeInt32>({});
+
+    // entropy of empty set = 0
+    execute(block, ColumnHelper::create_column_with_name<DataTypeFloat64>({0.0}));

Review Comment:
   There is a discrepancy in the expected behavior for empty input. The unit test expects entropy of an empty set to be 0.0 (line 112), but the regression test expects NULL (line 114 of the .out file). This inconsistency needs to be resolved. Based on the regression test and the fact that the function inherits from NullableAggregateFunction, the correct behavior should likely be NULL for empty input, which means the unit test expectation at line 112 is incorrect.
   ```suggestion
       // entropy of empty set = NULL
       execute(block, ColumnHelper::create_nullable_column_with_name<DataTypeFloat64>({0.0}, {1}));
   ```



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [Feature](agg) add agg function entropy [doris]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #60833:
URL: https://github.com/apache/doris/pull/60833#issuecomment-5649649303

   We're closing this PR because it hasn't been updated in a while.
   This isn't a judgement on the merit of the PR in any way. It's just a way of keeping the PR queue manageable.
   If you'd like to revive this PR, please reopen it and feel free a maintainer to remove the Stale tag!


-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [Feature](agg) add agg function entropy [doris]

Posted by "doris-robot (via GitHub)" <gi...@apache.org>.
doris-robot commented on PR #60833:
URL: https://github.com/apache/doris/pull/60833#issuecomment-4064977498

   
   <details>
   <summary>TPC-H: <b>Total hot run time: 26916 ms</b></summary>
   
   ```
   machine: 'aliyun_ecs.c7a.8xlarge_32C64G'
   scripts: https://github.com/apache/doris/tree/master/tools/tpch-tools
   Tpch sf100 test result on commit 9b7d7b3a7fd662d34a1d23ade4ee79aeac35f263, data reload: false
   
   ------ Round 1 ----------------------------------
   orders	Doris	NULL	NULL	0	0	0	NULL	0	NULL	NULL	2023-12-26 18:27:23	2023-12-26 18:42:55	NULL	utf-8	NULL	NULL	
   ============================================
   q1	17594	4486	4299	4299
   q2	q3	10640	786	528	528
   q4	4680	352	249	249
   q5	7560	1197	1021	1021
   q6	188	183	146	146
   q7	781	892	670	670
   q8	9301	1480	1345	1345
   q9	4827	4793	4729	4729
   q10	6308	1911	1652	1652
   q11	471	265	244	244
   q12	729	593	474	474
   q13	18033	2950	2181	2181
   q14	226	236	210	210
   q15	q16	768	749	683	683
   q17	740	842	451	451
   q18	6102	5414	5273	5273
   q19	1121	986	628	628
   q20	539	503	390	390
   q21	4444	1842	1450	1450
   q22	532	385	293	293
   Total cold run time: 95584 ms
   Total hot run time: 26916 ms
   
   ----- Round 2, with runtime_filter_mode=off -----
   orders	Doris	NULL	NULL	150000000	42	6422171781	NULL	22778155	NULL	NULL	2023-12-26 18:27:23	2023-12-26 18:42:55	NULL	utf-8	NULL	NULL	
   ============================================
   q1	4672	4702	4561	4561
   q2	q3	3903	4370	3866	3866
   q4	890	1223	796	796
   q5	4100	4383	4334	4334
   q6	185	180	143	143
   q7	1729	1669	1534	1534
   q8	2505	2737	2566	2566
   q9	7670	7446	7495	7446
   q10	3774	4034	3588	3588
   q11	533	433	410	410
   q12	480	596	459	459
   q13	2762	3161	2346	2346
   q14	295	315	296	296
   q15	q16	745	761	711	711
   q17	1169	1367	1391	1367
   q18	7113	6942	6727	6727
   q19	926	906	908	906
   q20	2077	2153	2007	2007
   q21	4068	3462	3397	3397
   q22	467	462	399	399
   Total cold run time: 50063 ms
   Total hot run time: 47859 ms
   ```
   </details>
   


-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [Feature](agg) add agg function entropy [doris]

Posted by "hello-stephen (via GitHub)" <gi...@apache.org>.
hello-stephen commented on PR #60833:
URL: https://github.com/apache/doris/pull/60833#issuecomment-4065426168

   # BE Regression && UT Coverage Report
   Increment line coverage `100% (0/0)` :tada:
   
   [Increment coverage report](http://coverage.selectdb-in.cc/coverage/60833_9b7d7b3a7fd662d34a1d23ade4ee79aeac35f263_merge/increment_report/index.html)
   [Complete coverage report](http://coverage.selectdb-in.cc/coverage/60833_9b7d7b3a7fd662d34a1d23ade4ee79aeac35f263_merge/report/index.html)
   | Category          | Coverage           |
   |-------------------|--------------------|
   | Function Coverage | 73.22% (26859/36681) |
   | Line Coverage     | 56.61% (286912/506845) |
   | Region Coverage   | 53.86% (238812/443362) |
   | Branch Coverage   | 55.56% (103186/185727) |


-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [Feature](agg) add agg function entropy [doris]

Posted by "zclllyybb (via GitHub)" <gi...@apache.org>.
zclllyybb commented on PR #60833:
URL: https://github.com/apache/doris/pull/60833#issuecomment-4064702770

   run buildall


-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [Feature](agg) add agg function entropy [doris]

Posted by "hello-stephen (via GitHub)" <gi...@apache.org>.
hello-stephen commented on PR #60833:
URL: https://github.com/apache/doris/pull/60833#issuecomment-4064917182

   # FE UT Coverage Report
   Increment line coverage `  5.56% (1/18)` :tada:
   [Increment coverage report](http://coverage.selectdb-in.cc/coverage/60833_9b7d7b3a7fd662d34a1d23ade4ee79aeac35f263/fe_increment_report/index.html)
   [Complete coverage report](http://coverage.selectdb-in.cc/coverage/60833_9b7d7b3a7fd662d34a1d23ade4ee79aeac35f263/fe_report/index.html)
   


-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [Feature](agg) add agg function entropy [doris]

Posted by "doris-robot (via GitHub)" <gi...@apache.org>.
doris-robot commented on PR #60833:
URL: https://github.com/apache/doris/pull/60833#issuecomment-4065396400

   # BE UT Coverage Report
   Increment line coverage ` ` :tada:
   
   [Increment coverage report](http://coverage.selectdb-in.cc/coverage/9b7d7b3a7fd662d34a1d23ade4ee79aeac35f263_9b7d7b3a7fd662d34a1d23ade4ee79aeac35f263/increment_report/index.html)
   [Complete coverage report](http://coverage.selectdb-in.cc/coverage/9b7d7b3a7fd662d34a1d23ade4ee79aeac35f263_9b7d7b3a7fd662d34a1d23ade4ee79aeac35f263/report/index.html)
   | Category          | Coverage           |
   |-------------------|--------------------|
   | Function Coverage | 52.68% (19742/37475) |
   | Line Coverage     | 36.27% (184435/508558) |
   | Region Coverage   | 32.36% (142178/439313) |
   | Branch Coverage   | 33.56% (62175/185245) |


-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [Feature](agg) add agg function entropy [doris]

Posted by "zclllyybb (via GitHub)" <gi...@apache.org>.
zclllyybb commented on code in PR #60833:
URL: https://github.com/apache/doris/pull/60833#discussion_r2935410284


##########
regression-test/suites/query_p0/aggregate/aggregate_function_entropy.groovy:
##########
@@ -0,0 +1,185 @@
+// 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.
+
+suite("test_entropy") {
+
+    sql """set enable_nereids_planner=true"""
+    sql """set enable_fallback_to_original_planner=false"""
+    sql """set enable_decimal256=true"""
+
+    qt_entropy_null """select entropy(NULL)"""

Review Comment:
   I mean zero column. not zero row.



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [Feature](agg) add agg function entropy [doris]

Posted by "zclllyybb (via GitHub)" <gi...@apache.org>.
zclllyybb commented on code in PR #60833:
URL: https://github.com/apache/doris/pull/60833#discussion_r2931144132


##########
be/src/exprs/aggregate/aggregate_function_entropy.h:
##########
@@ -0,0 +1,191 @@
+// 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.
+// This file is copied from
+// https://github.com/ClickHouse/ClickHouse/blob/master/src/AggregateFunctions/AggregateFunctionEntropy.cpp
+// and modified by Doris
+
+#pragma once
+
+#include "core/assert_cast.h"
+#include "core/column/column.h"
+#include "core/column/column_decimal.h"
+#include "core/data_type/data_type.h"
+#include "core/data_type/data_type_number.h"
+#include "core/string_ref.h"
+#include "core/types.h"
+#include "core/uint128.h"
+#include "exec/common/hash_table/hash.h"
+#include "exec/common/hash_table/phmap_fwd_decl.h"
+#include "exprs/aggregate/aggregate_function.h"
+
+namespace doris {
+#include "common/compile_check_begin.h"
+
+class Arena;
+class BufferReadable;
+class BufferWritable;
+template <PrimitiveType>
+class ColumnVector;
+
+/** Calculates Shannon Entropy, using HashMap and computing empirical distribution function.
+  * Entropy is measured in bits (base-2 logarithm is used).
+  */
+template <typename Value, typename Hash = HashCRC32<Value>>
+struct AggregateFunctionEntropyData {
+    using Container = flat_hash_map<Value, uint64_t, Hash>;
+    using Self = AggregateFunctionEntropyData<Value, Hash>;
+    Container frequency_map;
+
+    void clear() { frequency_map.clear(); }
+
+    void add(const Value& elem) { ++frequency_map[elem]; }
+
+    void merge(const Self& rhs) {
+        frequency_map.reserve(frequency_map.size() + rhs.frequency_map.size());
+        for (const auto& [elem, count] : rhs.frequency_map) {
+            frequency_map[elem] += count;
+        }
+    }
+
+    void write(BufferWritable& buf) const {
+        buf.write_var_uint(frequency_map.size());
+        for (const auto& [elem, count] : frequency_map) {
+            buf.write_binary(elem);
+            buf.write_binary(count);
+        }
+    }
+
+    void read(BufferReadable& buf) {
+        uint64_t new_size = 0;
+        buf.read_var_uint(new_size);
+        frequency_map.reserve(frequency_map.size() + new_size);
+
+        Value elem;
+        uint64_t count;
+        for (size_t i = 0; i < new_size; ++i) {
+            buf.read_binary(elem);
+            buf.read_binary(count);
+            frequency_map[elem] += count;
+        }
+    }
+
+    Float64 get_result() const {
+        Float64 entropy = 0;
+        uint64_t total_count = 0;
+        for (const auto& [_, count] : frequency_map) {
+            total_count += count;
+        }
+        for (const auto& [_, count] : frequency_map) {
+            Float64 p = static_cast<Float64>(count) / static_cast<Float64>(total_count);
+            entropy -= p * std::log2(p);
+        }
+        return entropy;
+    }
+
+    static String get_name() { return "entropy"; }
+};
+
+template <PrimitiveType T>
+struct AggregateFunctionEntropySingleNumericData
+        : public AggregateFunctionEntropyData<typename PrimitiveTypeTraits<T>::CppType> {
+    using Base = AggregateFunctionEntropyData<typename PrimitiveTypeTraits<T>::CppType>;
+
+    void add(const IColumn** columns, size_t /* columns_num */, size_t row_num, Arena&) {
+        const auto& vec = assert_cast<const typename PrimitiveTypeTraits<T>::ColumnType&,
+                                      TypeCheckOnRelease::DISABLE>(*columns[0])
+                                  .get_data();
+        Base::add(vec[row_num]);
+    }
+};
+
+struct AggregateFunctionEntropySingleStringData
+        : public AggregateFunctionEntropyData<UInt128, UInt128TrivialHash> {
+    using Base = AggregateFunctionEntropyData<UInt128, UInt128TrivialHash>;
+
+    void add(const IColumn** columns, size_t /* columns_num */, size_t row_num, Arena&) {
+        auto key = columns[0]->get_data_at(row_num);
+        auto hash_value = XXH_INLINE_XXH128(key.data, key.size, 0);

Review Comment:
   should always prefer crc32c to do hash. could you replace all?



##########
be/test/exprs/aggregate/agg_function_test.h:
##########
@@ -179,8 +179,11 @@ struct AggregateFunctiontest : public testing::Test {
 
                 agg_fn->create(place);
                 Defer defer([&]() { agg_fn->destroy(place); });
-                agg_fn->function()->deserialize_and_merge_from_column_range(
-                        place, *serialize_column, 0, block.rows() - 1, arena);
+
+                if (block.rows() != 0) {

Review Comment:
   what if block has zero row before?



##########
be/src/exprs/aggregate/aggregate_function_entropy.h:
##########
@@ -0,0 +1,191 @@
+// 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.
+// This file is copied from
+// https://github.com/ClickHouse/ClickHouse/blob/master/src/AggregateFunctions/AggregateFunctionEntropy.cpp
+// and modified by Doris
+
+#pragma once
+
+#include "core/assert_cast.h"
+#include "core/column/column.h"
+#include "core/column/column_decimal.h"
+#include "core/data_type/data_type.h"
+#include "core/data_type/data_type_number.h"
+#include "core/string_ref.h"
+#include "core/types.h"
+#include "core/uint128.h"
+#include "exec/common/hash_table/hash.h"
+#include "exec/common/hash_table/phmap_fwd_decl.h"
+#include "exprs/aggregate/aggregate_function.h"
+
+namespace doris {
+#include "common/compile_check_begin.h"
+
+class Arena;
+class BufferReadable;
+class BufferWritable;
+template <PrimitiveType>
+class ColumnVector;
+
+/** Calculates Shannon Entropy, using HashMap and computing empirical distribution function.
+  * Entropy is measured in bits (base-2 logarithm is used).
+  */
+template <typename Value, typename Hash = HashCRC32<Value>>
+struct AggregateFunctionEntropyData {
+    using Container = flat_hash_map<Value, uint64_t, Hash>;
+    using Self = AggregateFunctionEntropyData<Value, Hash>;
+    Container frequency_map;
+
+    void clear() { frequency_map.clear(); }
+
+    void add(const Value& elem) { ++frequency_map[elem]; }
+
+    void merge(const Self& rhs) {
+        frequency_map.reserve(frequency_map.size() + rhs.frequency_map.size());
+        for (const auto& [elem, count] : rhs.frequency_map) {
+            frequency_map[elem] += count;
+        }
+    }
+
+    void write(BufferWritable& buf) const {
+        buf.write_var_uint(frequency_map.size());
+        for (const auto& [elem, count] : frequency_map) {
+            buf.write_binary(elem);
+            buf.write_binary(count);
+        }
+    }
+
+    void read(BufferReadable& buf) {
+        uint64_t new_size = 0;
+        buf.read_var_uint(new_size);
+        frequency_map.reserve(frequency_map.size() + new_size);
+
+        Value elem;
+        uint64_t count;
+        for (size_t i = 0; i < new_size; ++i) {
+            buf.read_binary(elem);
+            buf.read_binary(count);
+            frequency_map[elem] += count;
+        }
+    }
+
+    Float64 get_result() const {
+        Float64 entropy = 0;
+        uint64_t total_count = 0;
+        for (const auto& [_, count] : frequency_map) {
+            total_count += count;
+        }
+        for (const auto& [_, count] : frequency_map) {
+            Float64 p = static_cast<Float64>(count) / static_cast<Float64>(total_count);
+            entropy -= p * std::log2(p);
+        }
+        return entropy;
+    }
+
+    static String get_name() { return "entropy"; }
+};
+
+template <PrimitiveType T>
+struct AggregateFunctionEntropySingleNumericData
+        : public AggregateFunctionEntropyData<typename PrimitiveTypeTraits<T>::CppType> {
+    using Base = AggregateFunctionEntropyData<typename PrimitiveTypeTraits<T>::CppType>;
+
+    void add(const IColumn** columns, size_t /* columns_num */, size_t row_num, Arena&) {
+        const auto& vec = assert_cast<const typename PrimitiveTypeTraits<T>::ColumnType&,
+                                      TypeCheckOnRelease::DISABLE>(*columns[0])
+                                  .get_data();
+        Base::add(vec[row_num]);
+    }
+};
+
+struct AggregateFunctionEntropySingleStringData
+        : public AggregateFunctionEntropyData<UInt128, UInt128TrivialHash> {
+    using Base = AggregateFunctionEntropyData<UInt128, UInt128TrivialHash>;
+
+    void add(const IColumn** columns, size_t /* columns_num */, size_t row_num, Arena&) {
+        auto key = columns[0]->get_data_at(row_num);

Review Comment:
   maybe tamplating `AggregateFunctionEntropySingleStringData` and `assert_cast` here to aovid virtual function call



##########
regression-test/suites/query_p0/aggregate/aggregate_function_entropy.groovy:
##########
@@ -0,0 +1,185 @@
+// 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.
+
+suite("test_entropy") {
+
+    sql """set enable_nereids_planner=true"""

Review Comment:
   dont need these set about planner now.



##########
regression-test/suites/query_p0/aggregate/aggregate_function_entropy.groovy:
##########
@@ -0,0 +1,185 @@
+// 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.
+
+suite("test_entropy") {
+
+    sql """set enable_nereids_planner=true"""
+    sql """set enable_fallback_to_original_planner=false"""
+    sql """set enable_decimal256=true"""
+
+    qt_entropy_null """select entropy(NULL)"""

Review Comment:
   what if zero column?



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [Feature](agg) add agg function entropy [doris]

Posted by "wrlcke (via GitHub)" <gi...@apache.org>.
wrlcke commented on code in PR #60833:
URL: https://github.com/apache/doris/pull/60833#discussion_r2931761334


##########
be/src/exprs/aggregate/aggregate_function_entropy.h:
##########
@@ -0,0 +1,191 @@
+// 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.
+// This file is copied from
+// https://github.com/ClickHouse/ClickHouse/blob/master/src/AggregateFunctions/AggregateFunctionEntropy.cpp
+// and modified by Doris
+
+#pragma once
+
+#include "core/assert_cast.h"
+#include "core/column/column.h"
+#include "core/column/column_decimal.h"
+#include "core/data_type/data_type.h"
+#include "core/data_type/data_type_number.h"
+#include "core/string_ref.h"
+#include "core/types.h"
+#include "core/uint128.h"
+#include "exec/common/hash_table/hash.h"
+#include "exec/common/hash_table/phmap_fwd_decl.h"
+#include "exprs/aggregate/aggregate_function.h"
+
+namespace doris {
+#include "common/compile_check_begin.h"
+
+class Arena;
+class BufferReadable;
+class BufferWritable;
+template <PrimitiveType>
+class ColumnVector;
+
+/** Calculates Shannon Entropy, using HashMap and computing empirical distribution function.
+  * Entropy is measured in bits (base-2 logarithm is used).
+  */
+template <typename Value, typename Hash = HashCRC32<Value>>
+struct AggregateFunctionEntropyData {
+    using Container = flat_hash_map<Value, uint64_t, Hash>;
+    using Self = AggregateFunctionEntropyData<Value, Hash>;
+    Container frequency_map;
+
+    void clear() { frequency_map.clear(); }
+
+    void add(const Value& elem) { ++frequency_map[elem]; }
+
+    void merge(const Self& rhs) {
+        frequency_map.reserve(frequency_map.size() + rhs.frequency_map.size());
+        for (const auto& [elem, count] : rhs.frequency_map) {
+            frequency_map[elem] += count;
+        }
+    }
+
+    void write(BufferWritable& buf) const {
+        buf.write_var_uint(frequency_map.size());
+        for (const auto& [elem, count] : frequency_map) {
+            buf.write_binary(elem);
+            buf.write_binary(count);
+        }
+    }
+
+    void read(BufferReadable& buf) {
+        uint64_t new_size = 0;
+        buf.read_var_uint(new_size);
+        frequency_map.reserve(frequency_map.size() + new_size);
+
+        Value elem;
+        uint64_t count;
+        for (size_t i = 0; i < new_size; ++i) {
+            buf.read_binary(elem);
+            buf.read_binary(count);
+            frequency_map[elem] += count;
+        }
+    }
+
+    Float64 get_result() const {
+        Float64 entropy = 0;
+        uint64_t total_count = 0;
+        for (const auto& [_, count] : frequency_map) {
+            total_count += count;
+        }
+        for (const auto& [_, count] : frequency_map) {
+            Float64 p = static_cast<Float64>(count) / static_cast<Float64>(total_count);
+            entropy -= p * std::log2(p);
+        }
+        return entropy;
+    }
+
+    static String get_name() { return "entropy"; }
+};
+
+template <PrimitiveType T>
+struct AggregateFunctionEntropySingleNumericData
+        : public AggregateFunctionEntropyData<typename PrimitiveTypeTraits<T>::CppType> {
+    using Base = AggregateFunctionEntropyData<typename PrimitiveTypeTraits<T>::CppType>;
+
+    void add(const IColumn** columns, size_t /* columns_num */, size_t row_num, Arena&) {
+        const auto& vec = assert_cast<const typename PrimitiveTypeTraits<T>::ColumnType&,
+                                      TypeCheckOnRelease::DISABLE>(*columns[0])
+                                  .get_data();
+        Base::add(vec[row_num]);
+    }
+};
+
+struct AggregateFunctionEntropySingleStringData
+        : public AggregateFunctionEntropyData<UInt128, UInt128TrivialHash> {
+    using Base = AggregateFunctionEntropyData<UInt128, UInt128TrivialHash>;
+
+    void add(const IColumn** columns, size_t /* columns_num */, size_t row_num, Arena&) {
+        auto key = columns[0]->get_data_at(row_num);
+        auto hash_value = XXH_INLINE_XXH128(key.data, key.size, 0);
+        Base::add(UInt128 {hash_value.high64, hash_value.low64});
+    }
+};
+
+struct AggregateFunctionEntropyGenericData
+        : public AggregateFunctionEntropyData<UInt128, UInt128TrivialHash> {
+    using Base = AggregateFunctionEntropyData<UInt128, UInt128TrivialHash>;
+
+    void add(const IColumn** columns, size_t columns_num, size_t row_num, Arena& arena) {
+        const char* begin = nullptr;
+        StringRef key(begin, 0);
+        for (size_t i = 0; i < columns_num; ++i) {
+            auto cur_ref = columns[i]->serialize_value_into_arena(row_num, arena, begin);
+            key.data = cur_ref.data - key.size;
+            key.size += cur_ref.size;
+        }
+        auto hash_value = XXH_INLINE_XXH128(key.data, key.size, 0);
+        Base::add(UInt128 {hash_value.high64, hash_value.low64});
+    }
+};
+
+template <typename Data>
+class AggregateFunctionEntropy
+        : public IAggregateFunctionDataHelper<Data, AggregateFunctionEntropy<Data>>,

Review Comment:
   ok



##########
be/src/exprs/aggregate/aggregate_function_entropy.h:
##########
@@ -0,0 +1,191 @@
+// 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.
+// This file is copied from
+// https://github.com/ClickHouse/ClickHouse/blob/master/src/AggregateFunctions/AggregateFunctionEntropy.cpp
+// and modified by Doris
+
+#pragma once
+
+#include "core/assert_cast.h"
+#include "core/column/column.h"
+#include "core/column/column_decimal.h"
+#include "core/data_type/data_type.h"
+#include "core/data_type/data_type_number.h"
+#include "core/string_ref.h"
+#include "core/types.h"
+#include "core/uint128.h"
+#include "exec/common/hash_table/hash.h"
+#include "exec/common/hash_table/phmap_fwd_decl.h"
+#include "exprs/aggregate/aggregate_function.h"
+
+namespace doris {
+#include "common/compile_check_begin.h"
+
+class Arena;
+class BufferReadable;
+class BufferWritable;
+template <PrimitiveType>
+class ColumnVector;
+
+/** Calculates Shannon Entropy, using HashMap and computing empirical distribution function.
+  * Entropy is measured in bits (base-2 logarithm is used).
+  */
+template <typename Value, typename Hash = HashCRC32<Value>>
+struct AggregateFunctionEntropyData {
+    using Container = flat_hash_map<Value, uint64_t, Hash>;
+    using Self = AggregateFunctionEntropyData<Value, Hash>;
+    Container frequency_map;
+
+    void clear() { frequency_map.clear(); }
+
+    void add(const Value& elem) { ++frequency_map[elem]; }
+
+    void merge(const Self& rhs) {
+        frequency_map.reserve(frequency_map.size() + rhs.frequency_map.size());
+        for (const auto& [elem, count] : rhs.frequency_map) {
+            frequency_map[elem] += count;
+        }
+    }
+
+    void write(BufferWritable& buf) const {
+        buf.write_var_uint(frequency_map.size());
+        for (const auto& [elem, count] : frequency_map) {
+            buf.write_binary(elem);
+            buf.write_binary(count);
+        }
+    }
+
+    void read(BufferReadable& buf) {
+        uint64_t new_size = 0;
+        buf.read_var_uint(new_size);
+        frequency_map.reserve(frequency_map.size() + new_size);
+
+        Value elem;
+        uint64_t count;
+        for (size_t i = 0; i < new_size; ++i) {
+            buf.read_binary(elem);
+            buf.read_binary(count);
+            frequency_map[elem] += count;
+        }
+    }
+
+    Float64 get_result() const {
+        Float64 entropy = 0;

Review Comment:
   The performance impact is negligible, so it’s not necessary to switch to a less intuitive formula.



##########
be/src/exprs/aggregate/aggregate_function_entropy.h:
##########
@@ -0,0 +1,191 @@
+// 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.
+// This file is copied from
+// https://github.com/ClickHouse/ClickHouse/blob/master/src/AggregateFunctions/AggregateFunctionEntropy.cpp
+// and modified by Doris
+
+#pragma once
+
+#include "core/assert_cast.h"
+#include "core/column/column.h"
+#include "core/column/column_decimal.h"
+#include "core/data_type/data_type.h"
+#include "core/data_type/data_type_number.h"
+#include "core/string_ref.h"
+#include "core/types.h"
+#include "core/uint128.h"
+#include "exec/common/hash_table/hash.h"
+#include "exec/common/hash_table/phmap_fwd_decl.h"
+#include "exprs/aggregate/aggregate_function.h"
+
+namespace doris {
+#include "common/compile_check_begin.h"
+
+class Arena;
+class BufferReadable;
+class BufferWritable;
+template <PrimitiveType>
+class ColumnVector;
+
+/** Calculates Shannon Entropy, using HashMap and computing empirical distribution function.
+  * Entropy is measured in bits (base-2 logarithm is used).
+  */
+template <typename Value, typename Hash = HashCRC32<Value>>
+struct AggregateFunctionEntropyData {
+    using Container = flat_hash_map<Value, uint64_t, Hash>;
+    using Self = AggregateFunctionEntropyData<Value, Hash>;
+    Container frequency_map;
+
+    void clear() { frequency_map.clear(); }
+
+    void add(const Value& elem) { ++frequency_map[elem]; }
+
+    void merge(const Self& rhs) {
+        frequency_map.reserve(frequency_map.size() + rhs.frequency_map.size());
+        for (const auto& [elem, count] : rhs.frequency_map) {
+            frequency_map[elem] += count;
+        }
+    }
+
+    void write(BufferWritable& buf) const {
+        buf.write_var_uint(frequency_map.size());
+        for (const auto& [elem, count] : frequency_map) {
+            buf.write_binary(elem);
+            buf.write_binary(count);
+        }
+    }
+
+    void read(BufferReadable& buf) {
+        uint64_t new_size = 0;
+        buf.read_var_uint(new_size);
+        frequency_map.reserve(frequency_map.size() + new_size);
+
+        Value elem;
+        uint64_t count;
+        for (size_t i = 0; i < new_size; ++i) {
+            buf.read_binary(elem);
+            buf.read_binary(count);
+            frequency_map[elem] += count;
+        }
+    }
+
+    Float64 get_result() const {
+        Float64 entropy = 0;
+        uint64_t total_count = 0;
+        for (const auto& [_, count] : frequency_map) {
+            total_count += count;
+        }
+        for (const auto& [_, count] : frequency_map) {
+            Float64 p = static_cast<Float64>(count) / static_cast<Float64>(total_count);
+            entropy -= p * std::log2(p);
+        }
+        return entropy;
+    }
+
+    static String get_name() { return "entropy"; }
+};
+
+template <PrimitiveType T>
+struct AggregateFunctionEntropySingleNumericData
+        : public AggregateFunctionEntropyData<typename PrimitiveTypeTraits<T>::CppType> {
+    using Base = AggregateFunctionEntropyData<typename PrimitiveTypeTraits<T>::CppType>;
+
+    void add(const IColumn** columns, size_t /* columns_num */, size_t row_num, Arena&) {
+        const auto& vec = assert_cast<const typename PrimitiveTypeTraits<T>::ColumnType&,
+                                      TypeCheckOnRelease::DISABLE>(*columns[0])
+                                  .get_data();
+        Base::add(vec[row_num]);
+    }
+};
+
+struct AggregateFunctionEntropySingleStringData
+        : public AggregateFunctionEntropyData<UInt128, UInt128TrivialHash> {
+    using Base = AggregateFunctionEntropyData<UInt128, UInt128TrivialHash>;
+
+    void add(const IColumn** columns, size_t /* columns_num */, size_t row_num, Arena&) {
+        auto key = columns[0]->get_data_at(row_num);
+        auto hash_value = XXH_INLINE_XXH128(key.data, key.size, 0);

Review Comment:
   For numeric keys the key itself is used as the hash table key, and CRC32 is used as the hash inside the hash table.
   For string and multi‑column keys this code path use XXH128 to produce a 128‑bit key representation that becomes the actual hash‑table key. This 128‑bit value should be effectively collision‑free in practice, so replacing it with CRC32C would be less safe.



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [Feature](agg) add agg function entropy [doris]

Posted by "zclllyybb (via GitHub)" <gi...@apache.org>.
zclllyybb commented on PR #60833:
URL: https://github.com/apache/doris/pull/60833#issuecomment-4035850779

   /review


-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [Feature](agg) add agg function entropy [doris]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on code in PR #60833:
URL: https://github.com/apache/doris/pull/60833#discussion_r2898912776


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/agg/Entropy.java:
##########
@@ -0,0 +1,77 @@
+// 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.
+
+package org.apache.doris.nereids.trees.expressions.functions.agg;
+
+import org.apache.doris.catalog.FunctionSignature;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.functions.ExplicitlyCastableSignature;
+import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
+import org.apache.doris.nereids.types.DoubleType;
+import org.apache.doris.nereids.types.coercion.AnyDataType;
+import org.apache.doris.nereids.util.ExpressionUtils;
+
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+
+/** Entropy */
+public class Entropy extends NullableAggregateFunction implements ExplicitlyCastableSignature {
+    public static final List<FunctionSignature> SIGNATURES = ImmutableList.of(
+            FunctionSignature.ret(DoubleType.INSTANCE).varArgs(AnyDataType.INSTANCE_WITHOUT_INDEX)
+    );
+
+    public Entropy(Expression arg0, Expression... varArgs) {
+        this(false, false, arg0, varArgs);
+    }
+
+    public Entropy(boolean distinct, Expression arg0, Expression... varArgs) {
+        this(distinct, false, arg0, varArgs);
+    }
+
+    public Entropy(boolean distinct, boolean alwaysNullable, Expression arg0, Expression... varArgs) {
+        this(distinct, alwaysNullable, false, ExpressionUtils.mergeArguments(arg0, varArgs));
+    }
+
+    private Entropy(boolean distinct, boolean alwaysNullable, boolean isSkew, List<Expression> expressions) {
+        super("entropy", distinct, alwaysNullable, isSkew, expressions);

Review Comment:
   **[Low]** The `isSkew` parameter is accepted here and passed to the superclass, but `Entropy` does not override `withIsSkew()`. The base class `AggregateFunction.withIsSkew()` throws `RuntimeException("current expression has not impl the withIsSkew method")`. If the optimizer ever attempts to set skew on an entropy aggregation, this would cause a runtime crash.
   
   Since there's no semantic reason for entropy to support skew optimization, consider removing the `isSkew` parameter and using the simpler super constructor (matching the pattern used by `Avg`, `Variance`, `Sem`):
   ```java
   private Entropy(boolean distinct, boolean alwaysNullable, List<Expression> expressions) {
       super("entropy", distinct, alwaysNullable, expressions);
   }
   ```
   Or alternatively, override `withIsSkew()` to handle it properly.



##########
be/src/vec/aggregate_functions/aggregate_function_entropy.cpp:
##########
@@ -0,0 +1,65 @@
+// 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.
+// This file is copied from
+// https://github.com/ClickHouse/ClickHouse/blob/master/src/AggregateFunctions/AggregateFunctionEntropy.cpp
+// and modified by Doris
+
+#include "vec/aggregate_functions/aggregate_function_entropy.h"
+
+#include "runtime/define_primitive_type.h"
+#include "vec/aggregate_functions/aggregate_function_simple_factory.h"
+#include "vec/aggregate_functions/helpers.h"
+
+namespace doris::vectorized {
+#include "common/compile_check_begin.h"
+
+AggregateFunctionPtr create_aggregate_function_entropy(const std::string& name,
+                                                       const DataTypes& argument_types,
+                                                       const DataTypePtr& result_type,
+                                                       const bool result_is_nullable,
+                                                       const AggregateFunctionAttr& attr) {
+    if (argument_types.size() == 1) {
+        auto res = creator_with_type_list<
+                TYPE_BOOLEAN, TYPE_TINYINT, TYPE_SMALLINT, TYPE_INT, TYPE_BIGINT, TYPE_LARGEINT,
+                TYPE_DECIMAL32, TYPE_DECIMAL64, TYPE_DECIMAL128I, TYPE_DECIMAL256, TYPE_DECIMALV2,
+                TYPE_FLOAT, TYPE_DOUBLE, TYPE_DATE, TYPE_DATETIME, TYPE_DATEV2, TYPE_DATETIMEV2,
+                TYPE_TIME, TYPE_TIMEV2, TYPE_TIMESTAMPTZ>::
+                create<AggregateFunctionEntropy, AggregateFunctionEntropySingleNumericData>(

Review Comment:
   **[Medium]** `TYPE_IPV4` and `TYPE_IPV6` are missing from this numeric type list. Currently they fall through to the generic path (`AggregateFunctionEntropyGenericData`), which works but is suboptimal — it serializes values into the Arena and hashes them, while the numeric path uses values directly as hash map keys.
   
   Both types have proper `PrimitiveTypeTraits` defined (`IPv4` is uint32-like, `IPv6` is uint128-like), and other comparable aggregate functions (`topn`, `approx_count_distinct`) include them in their numeric type lists.
   
   Suggested fix:
   ```cpp
   creator_with_type_list<
           TYPE_BOOLEAN, TYPE_TINYINT, TYPE_SMALLINT, TYPE_INT, TYPE_BIGINT, TYPE_LARGEINT,
           TYPE_DECIMAL32, TYPE_DECIMAL64, TYPE_DECIMAL128I, TYPE_DECIMAL256, TYPE_DECIMALV2,
           TYPE_FLOAT, TYPE_DOUBLE, TYPE_DATE, TYPE_DATETIME, TYPE_DATEV2, TYPE_DATETIMEV2,
           TYPE_TIME, TYPE_TIMEV2, TYPE_TIMESTAMPTZ, TYPE_IPV4, TYPE_IPV6>
   ```



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [Feature](agg) add agg function entropy [doris]

Posted by "Thearas (via GitHub)" <gi...@apache.org>.
Thearas commented on PR #60833:
URL: https://github.com/apache/doris/pull/60833#issuecomment-3958794066

   
   Thank you for your contribution to Apache Doris.
   Don't know what should be done next? See [How to process your PR](https://cwiki.apache.org/confluence/display/DORIS/How+to+process+your+PR).
   
   Please clearly describe your PR:
   1. What problem was fixed (it's best to include specific error reporting information). How it was fixed.
   2. Which behaviors were modified. What was the previous behavior, what is it now, why was it modified, and what possible impacts might there be.
   3. What features were added. Why was this function added?
   4. Which code was refactored and why was this part of the code refactored?
   5. Which functions were optimized and what is the difference before and after the optimization?
       


-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [Feature](agg) add agg function entropy [doris]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on code in PR #60833:
URL: https://github.com/apache/doris/pull/60833#discussion_r2915578002


##########
be/src/exprs/aggregate/aggregate_function_entropy.h:
##########
@@ -0,0 +1,191 @@
+// 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.
+// This file is copied from
+// https://github.com/ClickHouse/ClickHouse/blob/master/src/AggregateFunctions/AggregateFunctionEntropy.cpp
+// and modified by Doris
+
+#pragma once
+
+#include "core/assert_cast.h"
+#include "core/column/column.h"
+#include "core/column/column_decimal.h"
+#include "core/data_type/data_type.h"
+#include "core/data_type/data_type_number.h"
+#include "core/string_ref.h"
+#include "core/types.h"
+#include "core/uint128.h"
+#include "exec/common/hash_table/hash.h"
+#include "exec/common/hash_table/phmap_fwd_decl.h"
+#include "exprs/aggregate/aggregate_function.h"
+
+namespace doris {
+#include "common/compile_check_begin.h"
+
+class Arena;
+class BufferReadable;
+class BufferWritable;
+template <PrimitiveType>
+class ColumnVector;
+
+/** Calculates Shannon Entropy, using HashMap and computing empirical distribution function.
+  * Entropy is measured in bits (base-2 logarithm is used).
+  */
+template <typename Value, typename Hash = HashCRC32<Value>>
+struct AggregateFunctionEntropyData {
+    using Container = flat_hash_map<Value, uint64_t, Hash>;
+    using Self = AggregateFunctionEntropyData<Value, Hash>;
+    Container frequency_map;
+
+    void clear() { frequency_map.clear(); }
+
+    void add(const Value& elem) { ++frequency_map[elem]; }
+
+    void merge(const Self& rhs) {
+        frequency_map.reserve(frequency_map.size() + rhs.frequency_map.size());
+        for (const auto& [elem, count] : rhs.frequency_map) {
+            frequency_map[elem] += count;
+        }
+    }
+
+    void write(BufferWritable& buf) const {
+        buf.write_var_uint(frequency_map.size());
+        for (const auto& [elem, count] : frequency_map) {
+            buf.write_binary(elem);
+            buf.write_binary(count);
+        }
+    }
+
+    void read(BufferReadable& buf) {
+        uint64_t new_size = 0;
+        buf.read_var_uint(new_size);
+        frequency_map.reserve(frequency_map.size() + new_size);
+
+        Value elem;
+        uint64_t count;
+        for (size_t i = 0; i < new_size; ++i) {
+            buf.read_binary(elem);
+            buf.read_binary(count);
+            frequency_map[elem] += count;
+        }
+    }
+
+    Float64 get_result() const {
+        Float64 entropy = 0;

Review Comment:
   Suggestion: `get_result()` iterates over `frequency_map` twice — once to compute `total_count` and once to compute entropy. For large maps this means traversing the hash map's memory twice. Consider merging into a single pass:
   ```cpp
   Float64 get_result() const {
       Float64 entropy = 0;
       uint64_t total_count = 0;
       for (const auto& [_, count] : frequency_map) {
           total_count += count;
       }
       if (total_count == 0) return 0;
       Float64 log_total = std::log2(static_cast<Float64>(total_count));
       for (const auto& [_, count] : frequency_map) {
           // H = log2(N) - (1/N) * Σ count_i * log2(count_i)
           entropy += static_cast<Float64>(count) * std::log2(static_cast<Float64>(count));
       }
       entropy = log_total - entropy / static_cast<Float64>(total_count);
       return entropy;
   }
   ```
   Alternatively, the current two-pass approach is fine for moderate-sized maps. Just a suggestion for optimization.



##########
be/src/exprs/aggregate/aggregate_function_entropy.h:
##########
@@ -0,0 +1,191 @@
+// 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.
+// This file is copied from
+// https://github.com/ClickHouse/ClickHouse/blob/master/src/AggregateFunctions/AggregateFunctionEntropy.cpp
+// and modified by Doris
+
+#pragma once
+
+#include "core/assert_cast.h"
+#include "core/column/column.h"
+#include "core/column/column_decimal.h"
+#include "core/data_type/data_type.h"
+#include "core/data_type/data_type_number.h"
+#include "core/string_ref.h"
+#include "core/types.h"
+#include "core/uint128.h"
+#include "exec/common/hash_table/hash.h"
+#include "exec/common/hash_table/phmap_fwd_decl.h"
+#include "exprs/aggregate/aggregate_function.h"
+
+namespace doris {
+#include "common/compile_check_begin.h"
+
+class Arena;
+class BufferReadable;
+class BufferWritable;
+template <PrimitiveType>
+class ColumnVector;
+
+/** Calculates Shannon Entropy, using HashMap and computing empirical distribution function.
+  * Entropy is measured in bits (base-2 logarithm is used).
+  */
+template <typename Value, typename Hash = HashCRC32<Value>>
+struct AggregateFunctionEntropyData {
+    using Container = flat_hash_map<Value, uint64_t, Hash>;
+    using Self = AggregateFunctionEntropyData<Value, Hash>;
+    Container frequency_map;
+
+    void clear() { frequency_map.clear(); }
+
+    void add(const Value& elem) { ++frequency_map[elem]; }
+
+    void merge(const Self& rhs) {
+        frequency_map.reserve(frequency_map.size() + rhs.frequency_map.size());
+        for (const auto& [elem, count] : rhs.frequency_map) {
+            frequency_map[elem] += count;
+        }
+    }
+
+    void write(BufferWritable& buf) const {
+        buf.write_var_uint(frequency_map.size());
+        for (const auto& [elem, count] : frequency_map) {
+            buf.write_binary(elem);
+            buf.write_binary(count);
+        }
+    }
+
+    void read(BufferReadable& buf) {
+        uint64_t new_size = 0;
+        buf.read_var_uint(new_size);
+        frequency_map.reserve(frequency_map.size() + new_size);
+
+        Value elem;
+        uint64_t count;
+        for (size_t i = 0; i < new_size; ++i) {
+            buf.read_binary(elem);
+            buf.read_binary(count);
+            frequency_map[elem] += count;
+        }
+    }
+
+    Float64 get_result() const {
+        Float64 entropy = 0;
+        uint64_t total_count = 0;
+        for (const auto& [_, count] : frequency_map) {
+            total_count += count;
+        }
+        for (const auto& [_, count] : frequency_map) {
+            Float64 p = static_cast<Float64>(count) / static_cast<Float64>(total_count);
+            entropy -= p * std::log2(p);
+        }
+        return entropy;
+    }
+
+    static String get_name() { return "entropy"; }
+};
+
+template <PrimitiveType T>
+struct AggregateFunctionEntropySingleNumericData
+        : public AggregateFunctionEntropyData<typename PrimitiveTypeTraits<T>::CppType> {
+    using Base = AggregateFunctionEntropyData<typename PrimitiveTypeTraits<T>::CppType>;
+
+    void add(const IColumn** columns, size_t /* columns_num */, size_t row_num, Arena&) {
+        const auto& vec = assert_cast<const typename PrimitiveTypeTraits<T>::ColumnType&,
+                                      TypeCheckOnRelease::DISABLE>(*columns[0])
+                                  .get_data();
+        Base::add(vec[row_num]);
+    }
+};
+
+struct AggregateFunctionEntropySingleStringData
+        : public AggregateFunctionEntropyData<UInt128, UInt128TrivialHash> {
+    using Base = AggregateFunctionEntropyData<UInt128, UInt128TrivialHash>;
+
+    void add(const IColumn** columns, size_t /* columns_num */, size_t row_num, Arena&) {
+        auto key = columns[0]->get_data_at(row_num);
+        auto hash_value = XXH_INLINE_XXH128(key.data, key.size, 0);
+        Base::add(UInt128 {hash_value.high64, hash_value.low64});
+    }
+};
+
+struct AggregateFunctionEntropyGenericData
+        : public AggregateFunctionEntropyData<UInt128, UInt128TrivialHash> {
+    using Base = AggregateFunctionEntropyData<UInt128, UInt128TrivialHash>;
+
+    void add(const IColumn** columns, size_t columns_num, size_t row_num, Arena& arena) {
+        const char* begin = nullptr;
+        StringRef key(begin, 0);
+        for (size_t i = 0; i < columns_num; ++i) {
+            auto cur_ref = columns[i]->serialize_value_into_arena(row_num, arena, begin);
+            key.data = cur_ref.data - key.size;
+            key.size += cur_ref.size;
+        }
+        auto hash_value = XXH_INLINE_XXH128(key.data, key.size, 0);
+        Base::add(UInt128 {hash_value.high64, hash_value.low64});
+    }
+};
+
+template <typename Data>
+class AggregateFunctionEntropy
+        : public IAggregateFunctionDataHelper<Data, AggregateFunctionEntropy<Data>>,

Review Comment:
   Nit: Missing `final` keyword. Nearly all other aggregate function classes in the codebase (46+) are declared `final` (e.g., `AggregateFunctionUniq`, `AggregateFunctionCountByEnum`, `AggregateFunctionUniqDistributeKey`, etc.). Since this class is not intended to be subclassed, it should be:
   ```cpp
   class AggregateFunctionEntropy final
   ```
   This also enables potential devirtualization optimizations by the compiler.



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [Feature](agg) add agg function entropy [doris]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] closed pull request #60833: [Feature](agg) add agg function entropy
URL: https://github.com/apache/doris/pull/60833


-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [Feature](agg) add agg function entropy [doris]

Posted by "zclllyybb (via GitHub)" <gi...@apache.org>.
zclllyybb commented on PR #60833:
URL: https://github.com/apache/doris/pull/60833#issuecomment-4015479758

   /review


-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [Feature](agg) add agg function entropy [doris]

Posted by "doris-robot (via GitHub)" <gi...@apache.org>.
doris-robot commented on PR #60833:
URL: https://github.com/apache/doris/pull/60833#issuecomment-4061629219

   
   <details>
   <summary>TPC-H: <b>Total hot run time: 26981 ms</b></summary>
   
   ```
   machine: 'aliyun_ecs.c7a.8xlarge_32C64G'
   scripts: https://github.com/apache/doris/tree/master/tools/tpch-tools
   Tpch sf100 test result on commit 4ef69af34e68c432ec507db3d432690b9cce55ed, data reload: false
   
   ------ Round 1 ----------------------------------
   orders	Doris	NULL	NULL	0	0	0	NULL	0	NULL	NULL	2023-12-26 18:27:23	2023-12-26 18:42:55	NULL	utf-8	NULL	NULL	
   ============================================
   q1	17654	4517	4300	4300
   q2	q3	10646	762	508	508
   q4	4676	369	253	253
   q5	7551	1213	1018	1018
   q6	176	178	150	150
   q7	809	845	667	667
   q8	9756	1471	1337	1337
   q9	5107	4780	4663	4663
   q10	6321	1885	1652	1652
   q11	463	263	258	258
   q12	740	573	482	482
   q13	18043	2970	2182	2182
   q14	232	230	223	223
   q15	q16	746	731	670	670
   q17	731	851	448	448
   q18	5979	5411	5313	5313
   q19	1249	991	598	598
   q20	553	481	384	384
   q21	4480	1848	1601	1601
   q22	431	325	274	274
   Total cold run time: 96343 ms
   Total hot run time: 26981 ms
   
   ----- Round 2, with runtime_filter_mode=off -----
   orders	Doris	NULL	NULL	150000000	42	6422171781	NULL	22778155	NULL	NULL	2023-12-26 18:27:23	2023-12-26 18:42:55	NULL	utf-8	NULL	NULL	
   ============================================
   q1	4759	4725	4676	4676
   q2	q3	3904	4346	3856	3856
   q4	884	1230	814	814
   q5	4167	4437	4430	4430
   q6	178	172	144	144
   q7	1772	1632	1486	1486
   q8	2512	2721	2636	2636
   q9	7651	7055	7432	7055
   q10	3834	4081	3635	3635
   q11	494	451	417	417
   q12	484	598	462	462
   q13	2683	3298	2323	2323
   q14	400	419	313	313
   q15	q16	708	783	706	706
   q17	1162	1410	1443	1410
   q18	6985	6727	6573	6573
   q19	922	872	924	872
   q20	2057	2145	2012	2012
   q21	4027	3620	3337	3337
   q22	452	433	388	388
   Total cold run time: 50035 ms
   Total hot run time: 47545 ms
   ```
   </details>
   


-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [Feature](agg) add agg function entropy [doris]

Posted by "wrlcke (via GitHub)" <gi...@apache.org>.
wrlcke commented on code in PR #60833:
URL: https://github.com/apache/doris/pull/60833#discussion_r2935951010


##########
regression-test/suites/query_p0/aggregate/aggregate_function_entropy.groovy:
##########
@@ -0,0 +1,185 @@
+// 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.
+
+suite("test_entropy") {
+
+    sql """set enable_nereids_planner=true"""
+    sql """set enable_fallback_to_original_planner=false"""
+    sql """set enable_decimal256=true"""
+
+    qt_entropy_null """select entropy(NULL)"""

Review Comment:
   added



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [Feature](agg) add agg function entropy [doris]

Posted by "doris-robot (via GitHub)" <gi...@apache.org>.
doris-robot commented on PR #60833:
URL: https://github.com/apache/doris/pull/60833#issuecomment-4061764812

   # BE UT Coverage Report
   Increment line coverage ` ` :tada:
   
   [Increment coverage report](http://coverage.selectdb-in.cc/coverage/4ef69af34e68c432ec507db3d432690b9cce55ed_4ef69af34e68c432ec507db3d432690b9cce55ed/increment_report/index.html)
   [Complete coverage report](http://coverage.selectdb-in.cc/coverage/4ef69af34e68c432ec507db3d432690b9cce55ed_4ef69af34e68c432ec507db3d432690b9cce55ed/report/index.html)
   | Category          | Coverage           |
   |-------------------|--------------------|
   | Function Coverage | 52.70% (19753/37479) |
   | Line Coverage     | 36.26% (184396/508538) |
   | Region Coverage   | 32.36% (142254/439594) |
   | Branch Coverage   | 33.57% (62205/185281) |


-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [Feature](agg) add agg function entropy [doris]

Posted by "linrrzqqq (via GitHub)" <gi...@apache.org>.
linrrzqqq commented on PR #60833:
URL: https://github.com/apache/doris/pull/60833#issuecomment-4061565934

   run buildall


-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org