8#ifndef LIBQE_ACCUMULATION_HPP
9#define LIBQE_ACCUMULATION_HPP
19#include <libqe/adjacency.hpp>
44 arma::rowvec ground, arma::rowvec response,
45 double response_weight = 1.0,
bool ordered =
true
47 arma::mat resp_self = response.t() * response;
48 arma::mat g_by_r = ground.t() * response;
51 resp_self.diag().zeros();
52 return g_by_r + (0.5 * response_weight * resp_self);
54 return (response_weight * resp_self) + g_by_r + (response.t() * ground);
98 int window_forward = 0,
102 int n_rows = codes.n_rows;
103 int n_codes = codes.n_cols;
104 const int INT_MAX_VAL = std::numeric_limits<int>::max();
107 auto get_earliest = [&](
int row) ->
int {
108 if (window_back == INT_MAX_VAL || window_back == 0)
109 return (window_back == 0) ? row : 0;
110 return std::max(0, row - (window_back - 1));
114 arma::mat out(n_rows, n_codes * n_codes, arma::fill::zeros);
115 for (
int row = 0; row < n_rows; row++) {
116 int earliest = get_earliest(row);
117 arma::rowvec response = codes.row(row);
118 arma::rowvec ground(n_codes, arma::fill::zeros);
120 ground = arma::sum(codes.rows(earliest, row - 1));
121 out.row(row) = arma::vectorise(
124 if (binary) out.elem(arma::find(out > 0)).ones();
129 int n_tri = choose_two(n_codes);
130 arma::mat out(n_rows, n_tri, arma::fill::zeros);
132 for (
int row = 0; row < n_rows; row++) {
133 int earliest = get_earliest(row);
136 if (window_forward == INT_MAX_VAL || row + window_forward >= n_rows) {
138 }
else if (window_forward > 0) {
139 latest = std::min(n_rows - 1, row + window_forward);
142 arma::mat window_rows = codes.rows(earliest, latest);
143 arma::mat summed = arma::sum(window_rows);
144 arma::rowvec to_ut = code_connections(summed);
147 int win_rows = latest - earliest + 1;
148 if (win_rows > 0 && window_back > 1 && row - 1 >= 0) {
149 int head_rows = win_rows - 1 - window_forward;
151 arma::mat refs = window_rows.head_rows(head_rows);
152 arma::mat ref_sum = arma::sum(refs);
153 to_ut -= code_connections(ref_sum);
158 if (window_forward > 0 && latest <= n_rows - 1) {
159 int tail_rows = latest - row;
161 arma::mat refs = window_rows.tail_rows(tail_rows);
162 arma::mat ref_sum = arma::sum(refs);
163 to_ut -= code_connections(ref_sum);
167 out.row(row) = to_ut;
170 if (binary) out.elem(arma::find(out > 0)).ones();
211 const arma::mat& codes,
212 const std::vector<int>& unit_rows,
213 std::function<arma::vec(arma::vec)> decay_fn,
216 int code_cnt = codes.n_cols;
217 arma::mat g_w_vec(code_cnt, code_cnt, arma::fill::zeros);
219 for (
int unit_row : unit_rows) {
220 if (unit_row == 0)
continue;
222 arma::rowvec response = codes.row(unit_row);
225 arma::uvec ground_indices = arma::regspace<arma::uvec>(0, 1, unit_row);
226 arma::vec distances(ground_indices.n_elem);
227 for (arma::uword k = 0; k < ground_indices.n_elem; k++)
228 distances[k] =
static_cast<double>(unit_row - ground_indices[k]);
230 arma::vec decay_weights = decay_fn(distances);
232 arma::mat ground_codes = codes.rows(ground_indices);
233 arma::mat weighted = ground_codes.each_col() % decay_weights;
234 arma::rowvec g_summed = arma::sum(weighted);
237 arma::rowvec g_no_resp = g_summed - weighted.tail_rows(1).row(0);
243 if (!ordered)
return fold_directed_network(arma::vectorise(g_w_vec));
244 return arma::vectorise(g_w_vec).t();
285 const arma::mat& codes,
286 const std::vector<int>& unit_rows,
287 std::function<arma::vec(
int, arma::uvec)> decay_fn,
290 int code_cnt = codes.n_cols;
291 int n_unit_rows = unit_rows.size();
293 arma::mat g_w_mat(code_cnt, code_cnt, arma::fill::zeros);
294 arma::mat row_networks(n_unit_rows, code_cnt * code_cnt, arma::fill::zeros);
296 for (
int i = 0; i < n_unit_rows; ++i) {
297 int unit_row = unit_rows[i];
299 arma::uvec ground_indices = arma::regspace<arma::uvec>(0, 1, unit_row);
300 arma::vec decay_weights = decay_fn(unit_row, ground_indices);
302 arma::mat ground_codes = codes.rows(ground_indices);
303 arma::mat weighted = ground_codes.each_col() % decay_weights;
304 arma::rowvec g_summed = arma::sum(weighted);
305 arma::rowvec g_no_resp = g_summed - weighted.tail_rows(1).row(0);
307 arma::rowvec response = codes.row(unit_row);
311 row_networks.row(i) = arma::vectorise(conn).t();
316 result.
networks = fold_directed_network(arma::vectorise(g_w_mat));
318 result.
networks = arma::vectorise(g_w_mat).t();
338 const std::vector<int>& dims) {
339 if (indices.size() != dims.size())
340 throw std::invalid_argument(
"Number of indices must match number of dimensions.");
341 size_t linear = 0, stride = 1;
342 for (
size_t v = 0; v < indices.size(); ++v) {
343 if (dims[v] <= 0 || indices[v] < 0 || indices[v] >= dims[v])
344 throw std::out_of_range(
"Tensor index out of range for its dimension.");
345 linear +=
static_cast<size_t>(indices[v]) * stride;
346 stride *=
static_cast<size_t>(dims[v]);
348 return static_cast<int>(linear);
390inline arma::mat
miss_matrix(
const arma::rowvec& ground,
const arma::rowvec& response) {
391 arma::rowvec absent = arma::conv_to<arma::rowvec>::from(response == 0);
392 return ground.t() * absent;
434 const arma::vec& tensor,
435 const std::vector<int>& dims,
436 const std::vector<int>& dims_sender,
437 const std::vector<int>& dims_receiver,
438 const std::vector<int>& dims_mode,
439 const arma::imat& context_lookup,
440 const std::vector<int>& unit_rows,
441 const arma::mat& codes,
442 const arma::vec& times,
444 bool return_members =
false,
445 bool return_misses =
false
447 const int WINDOW_DIM = 1;
448 const int WEIGHT_DIM = 0;
449 const bool IS_DEFAULT = (dims.size() == 1 && dims[0] == 2);
451 int code_cnt = codes.n_cols;
452 int n_unit_rows =
static_cast<int>(unit_rows.size());
453 int ctx_cols =
static_cast<int>(context_lookup.n_cols);
458 size_t tensor_len = 1;
460 if (d <= 0)
throw std::invalid_argument(
"tensor dims must be positive");
461 tensor_len *=
static_cast<size_t>(d);
463 if (tensor_len != tensor.n_elem)
464 throw std::invalid_argument(
"tensor length does not match the product of dims");
465 if (!IS_DEFAULT && dims.size() !=
static_cast<size_t>(ctx_cols) + 1)
466 throw std::invalid_argument(
"dims must have one entry per context column plus one");
467 const arma::uword n_rows = codes.n_rows;
468 if (times.n_elem < n_rows || (ctx_cols > 0 && context_lookup.n_rows < n_rows))
469 throw std::invalid_argument(
"times and context_lookup must cover every code row");
470 for (
int ri : unit_rows)
471 if (ri < 0 ||
static_cast<arma::uword
>(ri) >= n_rows)
472 throw std::out_of_range(
"unit row index out of range");
473 for (
int dim : dims_receiver)
474 if (dim < 0 || dim > ctx_cols)
475 throw std::out_of_range(
"receiver dimension out of range");
478 arma::mat g_w_mat(code_cnt, code_cnt, arma::fill::zeros);
479 arma::mat row_conn(n_unit_rows, code_cnt * code_cnt, arma::fill::zeros);
481 if (return_misses) row_miss.zeros(n_unit_rows, code_cnt * code_cnt);
483 std::vector<std::vector<int>> members_all;
484 std::vector<std::vector<double>> wins_all;
485 if (return_members) { members_all.reserve(n_unit_rows); wins_all.reserve(n_unit_rows); }
487 int response_win = 0;
488 int response_weight = 0;
490 response_win =
static_cast<int>(tensor[1]);
491 response_weight =
static_cast<int>(tensor[0]);
494 for (
int i = 0; i < n_unit_rows; ++i) {
495 int ri = unit_rows[i];
496 double response_time = times[ri];
498 std::vector<int> resp_ctx(ctx_cols + 1);
499 for (
int j = 0; j < ctx_cols; ++j) resp_ctx[j] = context_lookup(ri, j);
500 resp_ctx[ctx_cols] = WINDOW_DIM;
503 response_win =
static_cast<int>(tensor[
flat_index(resp_ctx, dims)]);
505 std::vector<int> gri_v;
506 std::vector<double> grw_v;
507 std::vector<double> grwin_v;
508 arma::rowvec g_ws(code_cnt, arma::fill::zeros);
511 for (
int gr = ri - 1; gr >= 0; --gr) {
512 std::vector<int> row_v(ctx_cols + 1);
513 for (
int j = 0; j < ctx_cols; ++j) row_v[j] = context_lookup(gr, j);
514 row_v[ctx_cols] = WINDOW_DIM;
515 for (
int dim : dims_receiver) row_v[dim] = resp_ctx[dim];
517 double row_win =
static_cast<double>(response_win);
521 if (times[gr] + row_win > response_time) {
523 if (return_members) grwin_v.push_back(row_win);
524 row_v[ctx_cols] = WEIGHT_DIM;
525 double row_wgt =
static_cast<double>(response_weight);
528 grw_v.push_back(row_wgt);
532 if (!gri_v.empty()) {
533 arma::uvec gri_u(gri_v.size());
534 for (
size_t k = 0; k < gri_v.size(); ++k) gri_u[k] = gri_v[k];
535 arma::mat gc = codes.rows(gri_u);
536 arma::colvec wts = arma::conv_to<arma::colvec>::from(grw_v);
537 g_ws = arma::sum(gc.each_col() % wts, 0);
542 resp_ctx[ctx_cols] = WEIGHT_DIM;
543 response_weight =
static_cast<int>(tensor[
flat_index(resp_ctx, dims)]);
546 arma::rowvec row_vec = codes.row(ri);
548 g_ws, row_vec,
static_cast<double>(response_weight), ordered);
550 row_conn.row(i) = arma::vectorise(resp).t();
552 row_miss.row(i) = arma::vectorise(
miss_matrix(g_ws, row_vec)).t();
554 if (return_members) {
555 members_all.push_back(std::move(gri_v));
556 wins_all.push_back(std::move(grwin_v));
563 if (return_members) {
604 s.reserve(name.size());
605 for (
char c : name) s +=
static_cast<char>(std::tolower(
static_cast<unsigned char>(c)));
611 throw std::invalid_argument(
612 "Unknown weight model '" + name +
"'; expected one of "
613 "'binary', 'product', 'sqrt', 'log1p'.");
626 if (!ordered) v.elem(arma::find(v > 0)).ones();
631 v.transform([](
double x) {
return std::sqrt(x); });
634 v.transform([](
double x) {
return std::log1p(x); });
669 const arma::mat& row_conn,
673 bool diagonal =
false
675 const int n_rows =
static_cast<int>(row_conn.n_rows);
676 const int n_out = ordered ? n_codes * n_codes : n_connections(n_codes, diagonal);
677 arma::mat out(n_rows, n_out, arma::fill::zeros);
679 for (
int r = 0; r < n_rows; ++r) {
680 arma::rowvec v = ordered
681 ? arma::rowvec(row_conn.row(r))
682 : fold_directed_network(arma::vectorise(row_conn.row(r)), diagonal);
715 const arma::mat& row_conn,
719 bool diagonal =
false
721 const int n_out = ordered ? n_codes * n_codes : n_connections(n_codes, diagonal);
722 if (row_conn.n_rows == 0)
return arma::rowvec(n_out, arma::fill::zeros);
733 const arma::mat& row_conn,
735 bool ordered =
false,
761 const arma::mat& row_conn,
766 if (row_conn.n_cols !=
static_cast<arma::uword
>(n_codes * n_codes))
767 throw std::invalid_argument(
"row_conn must have n_codes^2 columns");
768 const int n_rows =
static_cast<int>(row_conn.n_rows);
769 arma::mat out(n_rows, n_codes, arma::fill::zeros);
770 for (
int r = 0; r < n_rows; ++r) {
771 arma::rowvec v(n_codes);
772 for (
int i = 0; i < n_codes; ++i) v[i] = row_conn(r, i * n_codes + i);
785 const arma::mat& row_conn,
790 if (row_conn.n_rows == 0)
return arma::rowvec(n_codes, arma::fill::zeros);
807 arma::mat out = rows;
808 for (arma::uword r = 0; r < out.n_rows; ++r) {
809 arma::rowvec v = out.row(r);
861 const arma::vec& tensor,
862 const std::vector<int>& dims,
863 const std::vector<int>& dims_sender,
864 const std::vector<int>& dims_receiver,
865 const std::vector<int>& dims_mode,
866 const arma::imat& context_lookup,
867 const std::vector<int>& unit_rows,
868 const arma::mat& codes,
869 const arma::vec& times,
870 bool ordered =
false,
873 bool diagonal =
false
875 const int p =
static_cast<int>(codes.n_cols);
878 tensor, dims, dims_sender, dims_receiver, dims_mode,
879 context_lookup, unit_rows, codes, times,
880 true,
false, misses);
913 const arma::mat& codes,
916 int n_rows = codes.n_rows;
917 int n_tri = choose_two(codes.n_cols);
918 arma::mat out(n_rows, n_tri, arma::fill::zeros);
919 for (
int row = 0; row < n_rows; ++row)
920 out.row(row) = code_connections(codes.row(row));
921 if (binary) out.elem(arma::find(out > 0)).ones();
941 const arma::mat& codes,
944 int n_rows = codes.n_rows;
945 arma::mat out(n_rows, codes.n_cols, arma::fill::zeros);
946 for (
int row = 0; row < n_rows; ++row) {
947 int earliest = (window_size > 0)
948 ? std::max(0, row - (window_size - 1))
950 out.row(row) = arma::sum(codes.rows(earliest, row));
Definition accumulation.hpp:21
arma::rowvec aggregate_self_connections(const arma::mat &row_conn, int n_codes, bool ordered, WeightModel weight)
Unit self-connection vector: finalize_self_connections() summed over the lines.
Definition accumulation.hpp:784
arma::mat finalize_self_connections(const arma::mat &row_conn, int n_codes, bool ordered, WeightModel weight)
Per-line self-connections: the diagonal of each directed row.
Definition accumulation.hpp:760
arma::mat accumulate_stanza(arma::mat codes, int window_back=1, int window_forward=0, bool binary=true, bool ordered=false)
Accumulate connection vectors for every row in one conversation using a stanza window.
Definition accumulation.hpp:95
arma::rowvec accumulate_unit(const arma::mat &codes, const std::vector< int > &unit_rows, std::function< arma::vec(arma::vec)> decay_fn, bool ordered=false)
Accumulate connections for a single unit from its context rows.
Definition accumulation.hpp:210
void apply_weight_model(arma::rowvec &v, WeightModel weight, bool ordered)
Apply a weight model in place to one line's connection vector.
Definition accumulation.hpp:623
int flat_index(const std::vector< int > &indices, const std::vector< int > &dims)
Compute the linear index into a column-major multi-dimensional array.
Definition accumulation.hpp:337
TensorNetworks apply_tensor_unit(const arma::vec &tensor, const std::vector< int > &dims, const std::vector< int > &dims_sender, const std::vector< int > &dims_receiver, const std::vector< int > &dims_mode, const arma::imat &context_lookup, const std::vector< int > &unit_rows, const arma::mat &codes, const arma::vec ×, bool ordered=true, bool return_members=false, bool return_misses=false)
Pure-C++ port of the tma apply_tensor() inner logic.
Definition accumulation.hpp:433
arma::mat row_connections(const arma::mat &codes, bool binary=true)
Compute the upper-triangle co-occurrence vector for each row.
Definition accumulation.hpp:912
WeightModel weight_model_from_string(const std::string &name)
Parse a weight-model name (case-insensitive).
Definition accumulation.hpp:602
UnitAccumulation accumulate_unit_networks(const arma::vec &tensor, const std::vector< int > &dims, const std::vector< int > &dims_sender, const std::vector< int > &dims_receiver, const std::vector< int > &dims_mode, const arma::imat &context_lookup, const std::vector< int > &unit_rows, const arma::mat &codes, const arma::vec ×, bool ordered=false, WeightModel weight=WeightModel::Binary, bool misses=true, bool diagonal=false)
Accumulate one unit's networks end to end.
Definition accumulation.hpp:860
WeightModel
Transform applied to each line's connection counts before the per-unit sum.
Definition accumulation.hpp:594
arma::mat weight_rows(const arma::mat &rows, bool ordered, WeightModel weight)
Apply the weight model per line to already-finalised rows.
Definition accumulation.hpp:806
arma::mat finalize_row_connections(const arma::mat &row_conn, int n_codes, bool ordered, WeightModel weight, bool diagonal=false)
Finalise each per-response-row tensor connection vector.
Definition accumulation.hpp:668
arma::mat miss_matrix(const arma::rowvec &ground, const arma::rowvec &response)
Missed co-occurrences for one ground + response event pair.
Definition accumulation.hpp:390
WeightModel weight_model_from_bool(bool binary)
Map the legacy binary flag to a weight model (true → Binary, false → Product).
Definition accumulation.hpp:618
arma::rowvec aggregate_row_connections(const arma::mat &row_conn, int n_codes, bool ordered, WeightModel weight, bool diagonal=false)
Aggregate per-response-row tensor connections into a unit vector.
Definition accumulation.hpp:714
arma::mat connection_matrix(arma::rowvec ground, arma::rowvec response, double response_weight=1.0, bool ordered=true)
Compute the connection matrix for one ground + response event pair.
Definition accumulation.hpp:43
UnitNetworks accumulate_unit_with_rows(const arma::mat &codes, const std::vector< int > &unit_rows, std::function< arma::vec(int, arma::uvec)> decay_fn, bool ordered=false)
Like accumulate_unit() but also returns the per-response-row connection matrix needed by tma's accumu...
Definition accumulation.hpp:284
arma::mat rolling_window_sum(const arma::mat &codes, int window_size=1)
Rolling backward window sum of the raw code matrix.
Definition accumulation.hpp:940
Result of apply_tensor_unit().
Definition accumulation.hpp:356
arma::rowvec connection_counts
Unit-level flat vector (p²).
Definition accumulation.hpp:357
arma::mat row_connection_counts
Definition accumulation.hpp:358
arma::mat row_miss_counts
Definition accumulation.hpp:372
std::vector< std::vector< double > > row_window_wins
Definition accumulation.hpp:366
arma::rowvec miss_counts
Definition accumulation.hpp:369
std::vector< std::vector< int > > row_window_members
Definition accumulation.hpp:363
Result of accumulate_unit_networks(): a unit's finished vectors plus its raw per-line rows.
Definition accumulation.hpp:830
arma::rowvec self_connection_counts
p
Definition accumulation.hpp:833
arma::rowvec self_miss_counts
p (misses only)
Definition accumulation.hpp:837
arma::mat row_self_miss_counts
n_lines × p, raw (misses only)
Definition accumulation.hpp:838
arma::mat row_miss_counts
as row_connection_counts (misses only)
Definition accumulation.hpp:836
arma::rowvec miss_counts
as connection_counts (misses only)
Definition accumulation.hpp:835
arma::rowvec connection_counts
p² (ordered) or n_connections(p, diagonal)
Definition accumulation.hpp:831
arma::mat row_self_connection_counts
n_lines × p, raw
Definition accumulation.hpp:834
arma::mat row_connection_counts
n_lines × (p² or n_connections(p, diagonal)), raw
Definition accumulation.hpp:832
Result of accumulate_unit_with_rows().
Definition accumulation.hpp:257
arma::mat row_networks
Per-response-row directed p² matrix (n_unit_rows × p²), whatever ordered.
Definition accumulation.hpp:259
arma::rowvec networks
Flat connection vector (choose_two(p) or p²).
Definition accumulation.hpp:258