jubatus_core  0.1.2
Jubatus: Online machine learning framework for distributed environment
portable_mixer.hpp
Go to the documentation of this file.
1 // Jubatus: Online machine learning framework for distributed environment
2 // Copyright (C) 2011,2012 Preferred Networks and Nippon Telegraph and Telephone Corporation.
3 //
4 // This library is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU Lesser General Public
6 // License version 2.1 as published by the Free Software Foundation.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16 
17 #ifndef JUBATUS_CORE_COMMON_PORTABLE_MIXER_HPP_
18 #define JUBATUS_CORE_COMMON_PORTABLE_MIXER_HPP_
19 
20 #include <string>
21 #include <vector>
22 #include "jubatus/util/math/random.h"
23 #include "../common/hash.hpp"
24 
25 namespace jubatus {
26 namespace core {
27 namespace common {
28 
29 template <typename Storage, typename Diff = std::string>
31  public:
33  }
34 
35  explicit portable_mixer(uint32_t seed)
36  : rand_(seed) {
37  }
38 
39  void clear() {
40  storages_.clear();
41  }
42 
43  void add(Storage* storage) {
44  storages_.push_back(storage);
45  }
46 
47  Storage* get_random() {
48  return storages_[rand_(storages_.size())];
49  }
50 
51  Storage* get_hash(const std::string& id) const {
52  return storages_[hash_util::calc_string_hash(id) % storages_.size()];
53  }
54 
55  void mix() {
56  if (storages_.empty()) {
57  return;
58  }
59 
60  Diff mixed;
61  storages_[0]->get_diff(mixed);
62 
63  for (size_t i = 1; i < storages_.size(); ++i) {
64  Diff diff;
65  storages_[i]->get_diff(diff);
66  storages_[0]->mix(diff, mixed);
67  }
68 
69  for (size_t i = 0; i < storages_.size(); ++i) {
70  storages_[i]->put_diff(mixed);
71  }
72  }
73 
74  private:
75  std::vector<Storage*> storages_;
76  jubatus::util::math::random::mtrand rand_;
77 };
78 
79 } // namespace common
80 } // namespace core
81 } // namespace jubatus
82 
83 #endif // JUBATUS_CORE_COMMON_PORTABLE_MIXER_HPP_
std::vector< Storage * > storages_
Storage * get_hash(const std::string &id) const
jubatus::util::math::random::mtrand rand_
static uint64_t calc_string_hash(const std::string &s)
Definition: hash.hpp:29