2 * Copyright (C) 2012-2021 Euclid Science Ground Segment
4 * This library is free software; you can redistribute it and/or modify it under
5 * the terms of the GNU Lesser General Public License as published by the Free
6 * Software Foundation; either version 3.0 of the License, or (at your option)
9 * This library is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
14 * You should have received a copy of the GNU Lesser General Public License
15 * along with this library; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 #include "SOM/ImplTools.h"
32 namespace UMatrix_impl {
34 std::map<UMatrixType, std::function<double(const std::vector<double>&)>> type_func_map{
35 {UMatrixType::MIN, [](const std::vector<double>& dist_list) { return *std::min_element(dist_list.begin(), dist_list.end()); }},
36 {UMatrixType::MAX, [](const std::vector<double>& dist_list) { return *std::max_element(dist_list.begin(), dist_list.end()); }},
37 {UMatrixType::MEAN, [](const std::vector<double>& dist_list) {
38 return std::accumulate(dist_list.begin(), dist_list.end(), 0.) / dist_list.size();
43 template <std::size_t ND, typename DistFunc>
44 UMatrix computeUMatrix(const SOM<ND, DistFunc>& som, UMatrixType type) {
48 auto size = som.getSize();
49 UMatrix result = UMatrix(ImplTools::indexAxis("X", size.first), ImplTools::indexAxis("Y", size.second));
51 // Chose the method used for computing the u-matrix values
52 auto type_func = UMatrix_impl::type_func_map.at(type);
54 // Go through the SOM cells and compute the u-matrix cells
55 for (std::size_t x = 0; x < size.first; ++x) {
56 for (std::size_t y = 0; y < size.second; ++y) {
58 // Go through the neighbor cells and create the vector with the distances
59 std::vector<double> dist_list{};
60 for (int i = int(x) - 1; i <= (int)x + 1; ++i) {
61 for (int j = int(y) - 1; j <= (int)y + 1; ++j) {
63 // Check that we are not at the cell itself
64 if (i == (int)x && j == (int)y) {
67 // Double check that we are not outside of the SOM borders
68 if (i < 0 || i == (int)size.first || j < 0 || j == (int)size.second) {
72 dist_list.push_back(dist_func.distance(som(x, y), som(i, j)));
76 // Populate the u-matrix cell
77 result(x, y) = type_func(dist_list);