solver  1.0
Algorithms.h
Go to the documentation of this file.
1 /*
2  This file is part of the EnergyOptimizatorOfRoboticCells program.
3 
4  EnergyOptimizatorOfRoboticCells is free software: you can redistribute it and/or modify
5  it under the terms of the GNU General Public License as published by
6  the Free Software Foundation, either version 3 of the License, or
7  (at your option) any later version.
8 
9  EnergyOptimizatorOfRoboticCells is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  GNU General Public License for more details.
13 
14  You should have received a copy of the GNU General Public License
15  along with EnergyOptimizatorOfRoboticCells. If not, see <http://www.gnu.org/licenses/>.
16 */
17 
18 #ifndef HLIDAC_PES_ALGORITHMS_H
19 #define HLIDAC_PES_ALGORITHMS_H
20 
27 #include <algorithm>
28 #include <cmath>
29 #include <cassert>
30 #include <functional>
31 #include <vector>
32 #include <utility>
33 
38 template <class T>
39 using DistanceMatrix = std::vector<std::vector<T>>;
40 
49 template <class T, class C = std::greater<T>>
50 DistanceMatrix<T> floyd(DistanceMatrix<T> m, const C& cmp = std::greater<T>()) {
51  size_t matrixSize = m.size();
52  for (size_t k = 0; k < matrixSize; ++k) {
53  for (size_t i = 0; i < matrixSize; ++i) {
54  for (size_t j = 0; j < matrixSize; ++j) {
55  assert(i < m.size() && j < m[i].size() && k < m[i].size() && k < m.size() && j < m[k].size() && "Floyd needs square matrix!");
56  if (cmp(m[i][j], m[i][k]+m[k][j]))
57  m[i][j] = m[i][k]+m[k][j];
58  }
59  }
60  }
61 
62  return m;
63 }
64 
71 template <class T>
72 std::pair<double, double> goldenSearch(const T& unimodalFce) {
73  const double tol = unimodalFce.tolerance();
74  const static double phi = (std::sqrt(5.0)-1.0)/2.0;
75 
76  double a = 0.0, b = 1.0, c = 1.0-phi, d;
77  double fxC = unimodalFce.functionValue(c), fxD;
78  while (b-a > tol) {
79  if (c-a < b-c) {
80  d = phi*(b-a)+a;
81  fxD = unimodalFce.functionValue(d);
82  if (fxC <= fxD) {
83  b = d;
84  } else {
85  a = c; c = d;
86  fxC = fxD;
87  }
88  } else {
89  d = (1-phi)*(b-a)+a;
90  fxD = unimodalFce.functionValue(d);
91  if (fxD <= fxC) {
92  b = c; c = d;
93  fxC = fxD;
94  } else {
95  a = d;
96  }
97  }
98  }
99 
100  return { c, fxC };
101 }
102 
103 #endif
std::pair< double, double > goldenSearch(const T &unimodalFce)
It finds the minimal function value of a unimodal convex function.
Definition: Algorithms.h:72
DistanceMatrix< T > floyd(DistanceMatrix< T > m, const C &cmp=std::greater< T >())
It calculates all-to-all shortest paths and returns the matrix with their lengths.
Definition: Algorithms.h:50
std::vector< std::vector< T >> DistanceMatrix
Definition of the matrix data type.
Definition: Algorithms.h:39