20 #ifndef GRADIENTDESCENT_H_
21 #define GRADIENTDESCENT_H_
30 #include <fast_methods/ndgridmap/ndgridmap.hpp>
31 #include <fast_methods/ndgridmap/fmcell.h>
38 return (T(0) < val) - (val < T(0));
44 static constexpr
size_t ndims_ = grid_t::getNDims();
47 typedef typename std::array<unsigned int, ndims_>
Coord;
50 typedef typename std::array<double, ndims_>
Point;
53 typedef typename std::vector <Point>
Path;
67 (grid_t & grid,
unsigned int & idx,
Path & path, std::vector <double> & path_velocity,
double step = 1) {
71 Coord dimsize = grid.getDimSizes();
73 std::array<
unsigned int,
ndims_-1> d_;
75 for (
size_t i = 1; i <
ndims_; ++i)
76 d_[i] = dimsize[i]*d_[i-1];
78 grid.idx2coord(idx, current_coord);
79 std::copy_n( current_coord.begin(),
ndims_, current_point.begin() );
80 path.push_back(current_point);
81 path_velocity.push_back(grid[idx].getVelocity());
83 std::array<double, ndims_> grads;
85 while(grid[idx].getArrivalTime() != 0) {
91 grads[0] = - grid[idx-1].getValue()/2 + grid[idx+1].getValue()/2;
93 grads[0] = sgn<double>(grads[0]);
94 double max_grad = std::abs(grads[0]);
96 for (
size_t i = 1; i <
ndims_; ++i) {
97 grads[i] = - grid[idx-d_[i-1]].getValue()/2 + grid[idx+d_[i-1]].getValue()/2;
99 grads[i] = sgn<double>(grads[i]);
100 if (std::abs(max_grad) < std::abs(grads[i]))
105 for (
size_t i = 0; i <
ndims_; ++i) {
107 current_point[i] = current_point[i] - step*grads[i]/std::abs(max_grad);
108 current_coord[i] = int(current_point[i]+0.5);
110 path.push_back(current_point);
111 path_velocity.push_back(grid[idx].getVelocity());
112 grid.coord2idx(current_coord,idx);
115 grid.idx2coord(idx, current_coord);
116 std::copy_n( current_coord.begin(),
ndims_, current_point.begin() );
117 path.push_back(current_point);
118 path_velocity.push_back(grid[idx].getVelocity());
std::vector< Point > Path
Shorthand for path type of real points.
Implements gradient descent to be used together with nDGridMap and FMCell or derived types...
std::array< double, ndims_ > Point
Shorhand for real points.
std::array< unsigned int, ndims_ > Coord
Shorthand for coordinates.
static void apply(grid_t &grid, unsigned int &idx, Path &path, std::vector< double > &path_velocity, double step=1)
Computes the path over grid from idx to a minimum and extracts the velocity in every point...
static constexpr size_t ndims_
Shorthand for number of dimensions.