OmniSciDB  72c90bc290
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
AggMode.h
Go to the documentation of this file.
1 /*
2  * Copyright 2022 HEAVY.AI, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
23 #pragma once
24 
25 #include <algorithm>
26 #include <mutex>
27 #include <optional>
28 #include "ThirdParty/robin_hood/robin_hood.h"
29 
30 class AggMode {
31  public:
32  using Value = int64_t;
33  using Count = uint64_t;
34  using Map = robin_hood::unordered_map<Value, Count>;
35  struct ByCount {
36  bool operator()(Map::value_type const& a, Map::value_type const& b) const {
37  return a.second < b.second;
38  }
39  };
40  void add(Value const value) {
41  std::lock_guard<std::mutex> lock(mutex_);
42  auto const [itr, emplaced] = map_.emplace(value, 1u);
43  if (!emplaced) {
44  ++itr->second;
45  }
46  }
47  void reduce(AggMode&& rhs) {
48  std::lock_guard<std::mutex> lock(mutex_);
49  if (map_.size() < rhs.map_.size()) { // Loop over the smaller map
50  rhs.reduceMap(map_);
51  map_ = std::move(rhs.map_);
52  } else {
53  reduceMap(rhs.map_);
54  }
55  }
56  std::optional<Value> mode() const {
57  // In case of ties, any max element may be chosen.
58  auto const itr = std::max_element(map_.begin(), map_.end(), ByCount{});
59  return itr == map_.end() ? std::nullopt : std::make_optional(itr->first);
60  }
61 
62  private:
63  void reduceMap(Map const& map) {
64  for (Map::value_type const& pair : map) {
65  auto const [itr, emplaced] = map_.emplace(pair);
66  if (!emplaced) {
67  itr->second += pair.second;
68  }
69  }
70  }
72  std::mutex mutex_;
73 };
void reduce(AggMode &&rhs)
Definition: AggMode.h:47
robin_hood::unordered_map< Value, Count > Map
Definition: AggMode.h:34
void reduceMap(Map const &map)
Definition: AggMode.h:63
bool operator()(Map::value_type const &a, Map::value_type const &b) const
Definition: AggMode.h:36
uint64_t Count
Definition: AggMode.h:33
Map map_
Definition: AggMode.h:71
constexpr double a
Definition: Utm.h:32
std::optional< Value > mode() const
Definition: AggMode.h:56
void add(Value const value)
Definition: AggMode.h:40
std::mutex mutex_
Definition: AggMode.h:72