9#ifndef LIBENA_POSITIONS_HPP
10#define LIBENA_POSITIONS_HPP
18#include <libqe/adjacency.hpp>
19#include <libqe/linalg_fallback.hpp>
20#include <libqe/stats.hpp>
78 double conf_level = 0.95) {
79 int n = points.n_rows;
80 int n_pairs = (n * (n - 1)) / 2;
82 arma::umat idx1(1, n_pairs), idx2(1, n_pairs);
84 for (
int i = 0; i < n; i++)
85 for (
int j = i + 1; j < n; j++) { idx1[col] = i; idx2[col] = j; col++; }
87 arma::mat pts_diff = points.rows(idx1.row(0)) - points.rows(idx2.row(0));
88 arma::mat cts_diff = centroids.rows(idx1.row(0)) - centroids.rows(idx2.row(0));
89 arma::mat cr = arma::cor(pts_diff, cts_diff);
91 double qq = normal_quantile((1.0 + conf_level) / 2.0);
92 arma::mat out(points.n_cols, 3);
93 for (arma::uword i = 0; i < points.n_cols; i++) {
95 double z = std::atanh(r);
96 double sigma = 1.0 / std::sqrt(
static_cast<double>(n_pairs) - 3.0);
98 out(i, 1) = std::tanh(z - sigma * qq);
99 out(i, 2) = std::tanh(z + sigma * qq);
125 int tri_size = line_weights.n_cols;
126 int num_nodes =
static_cast<int>(
127 std::pow(std::ceil(std::sqrt(
static_cast<double>(2 * tri_size))), 2.0)
129 int row_count = line_weights.n_rows;
131 arma::mat weights(row_count, num_nodes, arma::fill::zeros);
132 for (
int k = 0; k < row_count; k++) {
133 arma::rowvec curr = line_weights.row(k);
135 for (
int x = 0; x < num_nodes - 1; x++) {
136 for (
int y = 0; y <= x; y++) {
137 weights(k, x + 1) += 0.5 * curr[z];
138 weights(k, y) += 0.5 * curr[z];
143 for (
int k = 0; k < row_count; k++) {
144 double len = arma::accu(arma::abs(weights.row(k)));
145 if (len < 0.0001) len = 0.0001;
146 weights.row(k) /= len;
176 if (!std::isfinite(self_weight) || self_weight < 0)
177 throw std::invalid_argument(
"directed_node_weights: self_weight must be finite and >= 0");
178 int num_nodes =
static_cast<int>(
179 std::ceil(std::sqrt(
static_cast<double>(line_weights.n_cols)))
181 int row_count = line_weights.n_rows;
183 arma::mat nw(row_count, num_nodes, arma::fill::zeros);
184 for (
int k = 0; k < row_count; k++) {
185 arma::mat curr = line_weights.row(k);
187 for (
int x = 0; x < num_nodes; x++)
188 for (
int y = 0; y < num_nodes; y++) {
193 nw(k, x) += self_weight * curr[z];
198 for (
int k = 0; k < row_count; k++) {
199 double len = arma::accu(arma::abs(nw.row(k)));
200 if (len < 0.0001) len = 0.0001;
227 arma::umat idx = connection_indices(n_codes, -1, diagonal);
228 return ConnectionKey{ arma::uvec(idx.row(0).t()), arma::uvec(idx.row(1).t()) };
236 const arma::uword n =
static_cast<arma::uword
>(n_codes);
238 for (arma::uword j = 0; j < n; ++j)
239 for (arma::uword i = 0; i < n; ++i) {
240 key.
from[j * n + i] = i;
241 key.to[j * n + i] = j;
270 if (key.
from.n_elem != line_weights.n_cols || key.
to.n_elem != line_weights.n_cols)
271 throw std::invalid_argument(
272 "node_weights_by_key: the key has " + std::to_string(key.
from.n_elem) +
273 " columns; line_weights has " + std::to_string(line_weights.n_cols));
274 if (n_codes < 1 || (key.
from.n_elem && (key.
from.max() >=
static_cast<arma::uword
>(n_codes) ||
275 key.
to.max() >=
static_cast<arma::uword
>(n_codes))))
276 throw std::invalid_argument(
"node_weights_by_key: key index out of range for n_codes");
277 if (!std::isfinite(self_weight) || self_weight < 0)
278 throw std::invalid_argument(
"node_weights_by_key: self_weight must be finite and >= 0");
280 arma::mat w(line_weights.n_rows, n_codes, arma::fill::zeros);
281 for (arma::uword k = 0; k < line_weights.n_cols; ++k) {
282 const arma::uword a = key.
from[k], b = key.
to[k];
284 w.col(a) += line_weights.col(k);
285 w.col(b) += line_weights.col(k);
287 w.col(a) += self_weight * line_weights.col(k);
290 for (arma::uword u = 0; u < w.n_rows; ++u) {
291 double len = arma::accu(arma::abs(w.row(u)));
292 if (len < 0.0001) len = 0.0001;
329 if (!adj_mats.is_finite() || !t.is_finite())
330 throw std::invalid_argument(
"node_positions: input matrices must not contain NaN or Inf");
332 int num_nodes = weights.n_cols;
334 arma::mat ssX(num_dims, num_nodes, arma::fill::zeros);
335 arma::mat ssA = weights.t() * weights;
336 for (
int i = 0; i < num_dims; i++) {
337 arma::mat ssb = weights.t() * t.col(i);
338 ssX.row(i) = qe::linalg::solve_spd(ssA, ssb).t();
393 arma::mat points,
int num_dims,
394 bool combine_pairs =
false,
396 if (!line_weights.is_finite() || !points.is_finite())
397 throw std::invalid_argument(
"directed_node_positions: input matrices must not contain NaN or Inf");
399 int num_nodes = nw.n_cols;
400 int row_count = line_weights.n_rows;
404 arma::mat nw_added(row_count / 2, num_nodes, arma::fill::zeros);
405 arma::mat pts_added(row_count / 2, num_dims, arma::fill::zeros);
406 for (
int k = 0; k < row_count; k += 2) {
407 nw_added.row(k / 2) = nw.row(k) + nw.row(k + 1);
408 pts_added.row(k / 2) = points.row(k) + points.row(k + 1);
411 arma::mat ssX(num_dims, num_nodes, arma::fill::zeros);
412 arma::mat ssA = nw_added.t() * nw_added;
413 for (
int i = 0; i < num_dims; i++) {
414 arma::mat ssb = nw_added.t() * pts_added.col(i);
415 ssX.row(i) = qe::linalg::solve_spd(ssA, ssb).t();
426 arma::mat ssX(num_dims, num_nodes, arma::fill::zeros);
427 arma::mat ssA = nw.t() * nw;
428 for (
int i = 0; i < num_dims; i++) {
429 arma::mat ssb = nw.t() * points.col(i);
430 ssX.row(i) = qe::linalg::solve_spd(ssA, ssb).t();
455 const arma::mat& points,
int num_dims,
458 if (!line_weights.is_finite() || !points.is_finite())
459 throw std::invalid_argument(
"node_positions_by_key: input matrices must not contain NaN or Inf");
462 arma::mat ssX(num_dims, n_codes, arma::fill::zeros);
463 arma::mat ssA = w.t() * w;
464 for (
int i = 0; i < num_dims; i++) {
465 arma::mat ssb = w.t() * points.col(i);
466 ssX.row(i) = qe::linalg::solve_spd(ssA, ssb).t();
500 throw std::invalid_argument(
501 "unit_circle_mode: mode must be \"equal\" or \"radial\", got \"" + name +
"\"");
538 if (dim_x >= nodes.n_cols || dim_y >= nodes.n_cols)
539 throw std::invalid_argument(
540 "unit_circle_nodes: dimension index out of range (nodes have " +
541 std::to_string(nodes.n_cols) +
" columns)");
543 throw std::invalid_argument(
"unit_circle_nodes: the two dimensions must differ");
544 if (!nodes.is_finite())
545 throw std::invalid_argument(
"unit_circle_nodes: nodes must not contain NaN or Inf");
547 arma::mat out = nodes;
548 const arma::uword n = nodes.n_rows;
549 arma::vec x = nodes.col(dim_x);
550 arma::vec y = nodes.col(dim_y);
552 std::vector<double> len(n);
553 std::vector<arma::uword> non_zero;
554 double max_len = 0.0;
555 for (arma::uword k = 0; k < n; ++k) {
556 len[k] = std::sqrt(x[k] * x[k] + y[k] * y[k]);
557 if (len[k] > max_len) max_len = len[k];
558 if (len[k] != 0.0) non_zero.push_back(k);
560 if (non_zero.empty())
return out;
563 for (arma::uword k : non_zero) {
564 double scale = max_len / len[k];
565 out(k, dim_x) = x[k] * scale;
566 out(k, dim_y) = y[k] * scale;
576 std::vector<arma::uword> upper, lower;
577 for (arma::uword k : non_zero) (y[k] >= 0.0 ? upper : lower).push_back(k);
578 std::stable_sort(upper.begin(), upper.end(),
579 [&](arma::uword a, arma::uword b) { return x[a] > x[b]; });
580 std::stable_sort(lower.begin(), lower.end(),
581 [&](arma::uword a, arma::uword b) { return x[a] < x[b]; });
582 std::vector<arma::uword> sorted(upper);
583 sorted.insert(sorted.end(), lower.begin(), lower.end());
587 arma::uword fixed = non_zero.front();
588 for (arma::uword k : non_zero)
589 if (len[k] == max_len) { fixed = k;
break; }
590 const std::size_t m = sorted.size();
591 const std::size_t first =
592 std::find(sorted.begin(), sorted.end(), fixed) - sorted.begin();
594 const double x1 = x[fixed], y1 = y[fixed];
595 const double step = 2.0 * arma::datum::pi /
static_cast<double>(m);
596 for (std::size_t i = 0; i < m; ++i) {
597 const arma::uword k = sorted[(first + i) % m];
598 const double angle =
static_cast<double>(i) * step;
599 out(k, dim_x) = x1 * std::cos(angle) - y1 * std::sin(angle);
600 out(k, dim_y) = x1 * std::sin(angle) + y1 * std::cos(angle);
632 const arma::mat& nodes,
bool directed =
false,
634 const arma::uword n = nodes.n_rows;
635 if (!directed && n < 2)
636 throw std::invalid_argument(
"node_centroids: undirected networks need at least 2 codes");
637 const arma::uword expected = directed ? n * n : n * (n - 1) / 2;
638 if (line_weights.n_cols != expected)
639 throw std::invalid_argument(
640 "node_centroids: line_weights has " + std::to_string(line_weights.n_cols) +
641 " columns; " + std::to_string(n) +
" nodes need " + std::to_string(expected) +
642 (directed ?
" (n_codes², directed)" :
" (choose(n_codes, 2), undirected)"));
643 if (!line_weights.is_finite() || !nodes.is_finite())
644 throw std::invalid_argument(
"node_centroids: input matrices must not contain NaN or Inf");
648 return weights * nodes;
672 const arma::mat& nodes,
673 arma::uword dim_x, arma::uword dim_y,
675 bool directed =
false,
690 if (!line_weights.is_finite() || !nodes.is_finite())
691 throw std::invalid_argument(
"node_centroids_by_key: input matrices must not contain NaN or Inf");
692 return node_weights_by_key(line_weights, key,
static_cast<int>(nodes.n_rows), self_weight) * nodes;
701 const arma::mat& nodes,
702 arma::uword dim_x, arma::uword dim_y,
Definition cxxwrap.hpp:36
arma::mat ena_correlation(arma::mat points, arma::mat centroids, double conf_level=0.95)
Pearson correlation with Fisher-z confidence interval between ENA unit points and their centroids.
Definition positions.hpp:77
arma::mat unit_circle_nodes(const arma::mat &nodes, arma::uword dim_x, arma::uword dim_y, UnitCircleMode mode=UnitCircleMode::Equal)
Move nodes onto a circle in the plane of two dimensions.
Definition positions.hpp:535
MovedNodes move_nodes_to_unit_circle_by_key(const arma::mat &line_weights, const arma::mat &nodes, arma::uword dim_x, arma::uword dim_y, UnitCircleMode mode, const ConnectionKey &key, double self_weight=DIRECTED_SELF_WEIGHT)
Layout-agnostic post-fit unit-circle move (as move_nodes_to_unit_circle), centroids from node_centroi...
Definition positions.hpp:700
constexpr double DIRECTED_SELF_WEIGHT
Definition positions.hpp:155
arma::mat node_centroids_by_key(const arma::mat &line_weights, const arma::mat &nodes, const ConnectionKey &key, double self_weight=DIRECTED_SELF_WEIGHT)
Layout-agnostic unit centroids: node_weights_by_key times nodes (as node_centroids).
Definition positions.hpp:687
arma::mat node_weights(const arma::mat &line_weights)
Per-unit node weights for undirected ENA.
Definition positions.hpp:124
arma::mat node_weights_by_key(const arma::mat &line_weights, const ConnectionKey &key, int n_codes, double self_weight=DIRECTED_SELF_WEIGHT)
Layout-agnostic node weights: every column counts toward each code it connects; a self-connection (fr...
Definition positions.hpp:267
UnitCircleMode unit_circle_mode(const std::string &name)
Parse a mode name for the bindings: "equal" or "radial".
Definition positions.hpp:497
UnitCircleMode
How unit_circle_nodes places the nodes on the circle.
Definition positions.hpp:487
@ Equal
Equally spaced, 2π/n apart, the longest node fixed.
@ Radial
Each node pushed out along its own ray.
MovedNodes move_nodes_to_unit_circle(const arma::mat &line_weights, const arma::mat &nodes, arma::uword dim_x, arma::uword dim_y, UnitCircleMode mode=UnitCircleMode::Equal, bool directed=false, double self_weight=DIRECTED_SELF_WEIGHT)
The post-fit unit-circle move of a model: moved nodes and their centroids.
Definition positions.hpp:671
NodePositions node_positions_by_key(const arma::mat &line_weights, const arma::mat &points, int num_dims, const ConnectionKey &key, int n_codes, double self_weight=DIRECTED_SELF_WEIGHT)
Layout-agnostic least-squares node positions: the solve of node_positions / directed_node_positions w...
Definition positions.hpp:454
arma::mat directed_node_weights(const arma::mat &line_weights, double self_weight=DIRECTED_SELF_WEIGHT)
Per-unit node weights for directed (ordered) ENA.
Definition positions.hpp:174
NodePositions directed_node_positions(arma::mat line_weights, arma::mat points, int num_dims, bool combine_pairs=false, double self_weight=DIRECTED_SELF_WEIGHT)
Least-squares node positions for directed (ordered) ENA.
Definition positions.hpp:392
ConnectionKey undirected_connection_key(int n_codes, bool diagonal=false)
Key of the undirected layout: the column-major upper triangle (libqe connection_indices),...
Definition positions.hpp:226
NodePositions node_positions(arma::mat adj_mats, arma::mat t, int num_dims)
Multiobjective least-squares node positions for undirected ENA.
Definition positions.hpp:327
ConnectionKey directed_connection_key(int n_codes)
Key of the ordered (directed) layout: column j*n+i is ground i -> response j, so from = i and to = j.
Definition positions.hpp:235
arma::mat node_centroids(const arma::mat &line_weights, const arma::mat &nodes, bool directed=false, double self_weight=DIRECTED_SELF_WEIGHT)
Unit centroids for a set of node positions.
Definition positions.hpp:631
Which two codes each connection column connects: the column map the layout-agnostic (_by_key) node we...
Definition positions.hpp:216
arma::uvec to
Second code of each column (0-based).
Definition positions.hpp:218
arma::uvec from
First code of each column (0-based).
Definition positions.hpp:217
Result of move_nodes_to_unit_circle.
Definition positions.hpp:47
arma::mat nodes
Moved node locations, n_codes × n_dims.
Definition positions.hpp:48
arma::mat centroids
Centroids recomputed from the moved nodes, n_units × n_dims.
Definition positions.hpp:49
Aggregated result returned by every node-position solver.
Definition positions.hpp:35
arma::mat points
Input rotated points echoed back unchanged, n_units × n_dims.
Definition positions.hpp:39
arma::mat nodes
Solved node locations, n_codes × n_dims.
Definition positions.hpp:36
arma::mat centroids
Per-unit centroids projected onto the node space, n_units × n_dims.
Definition positions.hpp:37
arma::mat weights
Normalised half-edge weight per unit per node, n_units × n_codes.
Definition positions.hpp:38