aboutsummaryrefslogtreecommitdiff
path: root/forcescheme.cpp
blob: 44c3acc64bda59e5d0fc59ce8e95e1062066dfbd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include "mp.h"

#include <algorithm>
#include <limits>

static const double EPSILON = 1e-3;

arma::mat mp::forceScheme(const arma::mat &D,
        arma::mat &Y,
        size_t maxIter,
        double tol,
        double fraction)
{
    arma::uword n = Y.n_rows;
    arma::uvec indices1(n), indices2(n);
    for (arma::uword k = 0; k < n; k++) {
        indices1[k] = indices2[k] = k;
    }

    double prevDeltaSum = std::numeric_limits<double>::infinity();
    for (size_t iter = 0; iter < maxIter; iter++) {
        double deltaSum = 0;

        arma::shuffle(indices1);
        for (auto i: indices1) {
            arma::shuffle(indices2);
            for (auto j: indices2) {
                if (i == j) {
                    continue;
                }

                arma::rowvec direction(Y.row(j) - Y.row(i));
                double d2 = std::max(arma::norm(direction, 2), EPSILON);
                double delta = (D(i, j) - d2) / fraction;
                deltaSum += fabs(delta);
                Y.row(j) += delta * (direction / d2);
            }
        }

        if (fabs(prevDeltaSum - deltaSum) < tol) {
            break;
        }
        prevDeltaSum = deltaSum;
    }

    return Y;
}