Program Listing for File effective_sample_size.hpp
↰ Return to documentation for file (include/beluga/algorithm/effective_sample_size.hpp
)
// Copyright 2024 Ekumen, Inc.
//
// Licensed 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.
#ifndef BELUGA_ALGORITHM_EFFECTIVE_SAMPLE_SIZE_HPP
#define BELUGA_ALGORITHM_EFFECTIVE_SAMPLE_SIZE_HPP
#include <beluga/type_traits/particle_traits.hpp>
#include <beluga/views/particles.hpp>
#include <range/v3/numeric/accumulate.hpp>
namespace beluga {
template <class Range, std::enable_if_t<!is_particle_range_v<Range>, int> = 0>
auto effective_sample_size(Range&& range) {
const auto total_weight = ranges::accumulate(range, 0.0);
if (total_weight == 0.0) {
return 0.0;
}
auto normalize_and_square = [total_weight](auto weight) {
const auto normalized_weight = weight / total_weight;
return normalized_weight * normalized_weight;
};
return 1.0 / ranges::accumulate(range, 0.0, std::plus<>{}, std::move(normalize_and_square));
}
template <class Range, std::enable_if_t<is_particle_range_v<Range>, int> = 0>
auto effective_sample_size(Range&& range) {
return effective_sample_size(range | beluga::views::weights);
}
} // namespace beluga
#endif