libena 0.4.18-dev.9021
QE C++ library
Loading...
Searching...
No Matches
positions.hpp
Go to the documentation of this file.
1
9#ifndef LIBENA_POSITIONS_HPP
10#define LIBENA_POSITIONS_HPP
11
12#include <armadillo>
13#include <algorithm>
14#include <cmath>
15#include <stdexcept>
16#include <string>
17#include <vector>
18#include <libqe/adjacency.hpp> // qe::connection_indices (keys)
19#include <libqe/linalg_fallback.hpp> // qe::linalg::solve_spd
20#include <libqe/stats.hpp> // normal_quantile
21
22namespace qe {
23
24// ---------------------------------------------------------------------------
27// ---------------------------------------------------------------------------
28
36 arma::mat nodes;
37 arma::mat centroids;
38 arma::mat weights;
39 arma::mat points;
40};
41
47struct MovedNodes {
48 arma::mat nodes;
49 arma::mat centroids;
50};
51
53
54// ---------------------------------------------------------------------------
57// ---------------------------------------------------------------------------
58
77inline arma::mat ena_correlation(arma::mat points, arma::mat centroids,
78 double conf_level = 0.95) {
79 int n = points.n_rows;
80 int n_pairs = (n * (n - 1)) / 2;
81
82 arma::umat idx1(1, n_pairs), idx2(1, n_pairs);
83 int col = 0;
84 for (int i = 0; i < n; i++)
85 for (int j = i + 1; j < n; j++) { idx1[col] = i; idx2[col] = j; col++; }
86
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);
90
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++) {
94 double r = cr(i, i);
95 double z = std::atanh(r);
96 double sigma = 1.0 / std::sqrt(static_cast<double>(n_pairs) - 3.0);
97 out(i, 0) = r;
98 out(i, 1) = std::tanh(z - sigma * qq);
99 out(i, 2) = std::tanh(z + sigma * qq);
100 }
101 return out;
102}
103
105
106// ---------------------------------------------------------------------------
109// ---------------------------------------------------------------------------
110
124inline arma::mat node_weights(const arma::mat& line_weights) {
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)
128 ) - (2 * tri_size);
129 int row_count = line_weights.n_rows;
130
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);
134 int z = 0;
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];
139 z++;
140 }
141 }
142 }
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;
147 }
148 return weights;
149}
150
155constexpr double DIRECTED_SELF_WEIGHT = 2.0;
156
174inline arma::mat directed_node_weights(const arma::mat& line_weights,
175 double self_weight = DIRECTED_SELF_WEIGHT) {
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)))
180 );
181 int row_count = line_weights.n_rows;
182
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);
186 int z = 0;
187 for (int x = 0; x < num_nodes; x++)
188 for (int y = 0; y < num_nodes; y++) {
189 if (x != y) {
190 nw(k, x) += curr[z];
191 nw(k, y) += curr[z];
192 } else {
193 nw(k, x) += self_weight * curr[z];
194 }
195 z++;
196 }
197 }
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;
201 nw.row(k) /= len;
202 }
203 return nw;
204}
205
217 arma::uvec from;
218 arma::uvec to;
219};
220
226inline ConnectionKey undirected_connection_key(int n_codes, bool diagonal = false) {
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()) };
229}
230
236 const arma::uword n = static_cast<arma::uword>(n_codes);
237 ConnectionKey key{ arma::uvec(n * n), arma::uvec(n * n) };
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;
242 }
243 return key;
244}
245
267inline arma::mat node_weights_by_key(const arma::mat& line_weights,
268 const ConnectionKey& key, int n_codes,
269 double self_weight = DIRECTED_SELF_WEIGHT) {
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");
279
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];
283 if (a != b) {
284 w.col(a) += line_weights.col(k);
285 w.col(b) += line_weights.col(k);
286 } else {
287 w.col(a) += self_weight * line_weights.col(k);
288 }
289 }
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;
293 w.row(u) /= len;
294 }
295 return w;
296}
297
299
300// ---------------------------------------------------------------------------
303// ---------------------------------------------------------------------------
304
327inline NodePositions node_positions(arma::mat adj_mats, arma::mat t,
328 int num_dims) {
329 if (!adj_mats.is_finite() || !t.is_finite())
330 throw std::invalid_argument("node_positions: input matrices must not contain NaN or Inf");
331 arma::mat weights = node_weights(adj_mats);
332 int num_nodes = weights.n_cols;
333
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();
339 }
340
342 r.nodes = ssX.t();
343 r.centroids = (ssX * weights.t()).t();
344 r.weights = weights;
345 r.points = t;
346 return r;
347}
348
392inline NodePositions directed_node_positions(arma::mat line_weights,
393 arma::mat points, int num_dims,
394 bool combine_pairs = false,
395 double self_weight = DIRECTED_SELF_WEIGHT) {
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");
398 arma::mat nw = directed_node_weights(line_weights, self_weight);
399 int num_nodes = nw.n_cols;
400 int row_count = line_weights.n_rows;
401
402 if (combine_pairs) {
403 // Combine paired rows (ground at k, response at k+1)
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);
409 }
410
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();
416 }
417
419 r.nodes = ssX.t();
420 r.centroids = (ssX * nw.t()).t();
421 r.weights = nw;
422 r.points = points;
423 return r;
424 }
425
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();
431 }
432
434 r.nodes = ssX.t();
435 r.centroids = (ssX * nw.t()).t();
436 r.weights = nw;
437 r.points = points;
438 return r;
439}
440
454inline NodePositions node_positions_by_key(const arma::mat& line_weights,
455 const arma::mat& points, int num_dims,
456 const ConnectionKey& key, int n_codes,
457 double self_weight = DIRECTED_SELF_WEIGHT) {
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");
460 arma::mat w = node_weights_by_key(line_weights, key, n_codes, self_weight);
461
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();
467 }
468
470 r.nodes = ssX.t();
471 r.centroids = (ssX * w.t()).t();
472 r.weights = w;
473 r.points = points;
474 return r;
475}
476
478
479// ---------------------------------------------------------------------------
482// ---------------------------------------------------------------------------
483
487enum class UnitCircleMode {
488 Equal,
489 Radial
490};
491
497inline UnitCircleMode unit_circle_mode(const std::string& name) {
498 if (name == "equal") return UnitCircleMode::Equal;
499 if (name == "radial") return UnitCircleMode::Radial;
500 throw std::invalid_argument(
501 "unit_circle_mode: mode must be \"equal\" or \"radial\", got \"" + name + "\"");
502}
503
535inline arma::mat unit_circle_nodes(const arma::mat& nodes, arma::uword dim_x,
536 arma::uword dim_y,
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)");
542 if (dim_x == dim_y)
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");
546
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);
551
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);
559 }
560 if (non_zero.empty()) return out;
561
562 if (mode == UnitCircleMode::Radial) {
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;
567 }
568 return out;
569 }
570
571 // Order around the origin: upper half-plane (y >= 0) by decreasing x,
572 // then lower half-plane by increasing x; stable, as R's order().
573 // Deliberate: this is the old R code's order, kept for parity (the
574 // user's decision, 2026-10-16), not true angular order. The two differ
575 // only when nodes of different lengths cross between x order and angle.
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());
584
585 // The longest node (first in node order on a tie) stays put; the others
586 // follow it around the circle.
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();
593
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);
601 }
602 return out;
603}
604
631inline arma::mat node_centroids(const arma::mat& line_weights,
632 const arma::mat& nodes, bool directed = false,
633 double self_weight = DIRECTED_SELF_WEIGHT) {
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");
645
646 const arma::mat weights = directed ? directed_node_weights(line_weights, self_weight)
647 : node_weights(line_weights);
648 return weights * nodes;
649}
650
671inline MovedNodes move_nodes_to_unit_circle(const arma::mat& line_weights,
672 const arma::mat& nodes,
673 arma::uword dim_x, arma::uword dim_y,
675 bool directed = false,
676 double self_weight = DIRECTED_SELF_WEIGHT) {
677 MovedNodes r;
678 r.nodes = unit_circle_nodes(nodes, dim_x, dim_y, mode);
679 r.centroids = node_centroids(line_weights, r.nodes, directed, self_weight);
680 return r;
681}
682
687inline arma::mat node_centroids_by_key(const arma::mat& line_weights, const arma::mat& nodes,
688 const ConnectionKey& key,
689 double self_weight = DIRECTED_SELF_WEIGHT) {
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;
693}
694
700inline MovedNodes move_nodes_to_unit_circle_by_key(const arma::mat& line_weights,
701 const arma::mat& nodes,
702 arma::uword dim_x, arma::uword dim_y,
703 UnitCircleMode mode,
704 const ConnectionKey& key,
705 double self_weight = DIRECTED_SELF_WEIGHT) {
706 MovedNodes r;
707 r.nodes = unit_circle_nodes(nodes, dim_x, dim_y, mode);
708 r.centroids = node_centroids_by_key(line_weights, r.nodes, key, self_weight);
709 return r;
710}
711
713
714} // namespace qe
715
716#endif // LIBENA_POSITIONS_HPP
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