|
libqe 0.2.5
QE C++ library
|
Namespaces | |
| namespace | bind |
| namespace | linalg |
Classes | |
| struct | GaussLegendreRule |
| struct | GroupStats |
| Per-dimension statistics from a two-group comparison. More... | |
| struct | PolyCurveFit |
| Polynomial curve fit result in 2D epistemic space. More... | |
| struct | SignedTurnLagResult |
| Result of signed turn-lag sweep across delta in [-max_lag, max_lag]. More... | |
| struct | TrajectoryDerivatives |
| Differential geometry profile along a trajectory curve. More... | |
Functions | |
| arma::mat | lookback_block (const arma::mat &block, int lookback_size=20, bool aggregate_mean=false, bool weighting_linear=false, const std::vector< int > &segment_ids={}) |
| Apply a sliding lookback window pool over a single unit's connection matrix. | |
| arma::mat | ema_block (const arma::mat &block, double alpha=0.1, const std::vector< int > &segment_ids={}) |
| Apply Exponential Moving Average (EMA) smoothing over a single unit's connection matrix. | |
| arma::mat | apply_door_lookback (const arma::mat &conn_counts, const std::vector< std::vector< int > > &unit_row_indices, const std::vector< int > &lookback_sizes, bool aggregate_mean=false, bool weighting_linear=false, const std::vector< int > &segment_ids={}) |
| Apply lookback door pooling to an entire connection matrix across multiple units. | |
| arma::mat | apply_door_ema (const arma::mat &conn_counts, const std::vector< std::vector< int > > &unit_row_indices, double alpha=0.1, const std::vector< int > &segment_ids={}) |
| Apply EMA door smoothing to an entire connection matrix across multiple units. | |
| double | soft_threshold (double z, double gamma) noexcept |
| Soft-threshold (shrinkage) operator used by coordinate descent. | |
| arma::vec | lasso_cd (const arma::mat &X, const arma::vec &y, double lambda, const arma::vec &pf, arma::vec beta0={}, int max_iter=1000, double tol=1e-7) |
| Single-response Lasso via cyclic coordinate descent at a fixed lambda. | |
| double | lasso_lambda_max (const arma::mat &X, const arma::mat &Yc, const arma::vec &pf) |
| Compute the smallest lambda that drives all penalized coefficients to zero. | |
| arma::mat | lasso_x1_contribution (const arma::mat &X_raw, const arma::mat &Y, const arma::uvec &x1_cols, const arma::vec &pf, int n_lambda=50, int k_folds=5, double eps=0.01) |
| Cross-validated multivariate Lasso; returns fitted values for target columns only. | |
| arma::mat | normalize_networks (arma::mat m) |
| Normalize each row to unit L2 norm (project onto the unit hypersphere). | |
| arma::mat | scale_networks (arma::mat m) |
| Scale every entry by the reciprocal of the largest row L2 norm. | |
| double | dist_dist_correlation (const arma::mat &X, const arma::mat &Y) |
| Compute Pearson correlation between pairwise Euclidean distance structures of two matrices. | |
| arma::mat | build_raw_poly_design (const arma::vec &t_vec, int degree) |
| arma::vec | poly_multiply_by_linear (const arma::vec &coeffs, double shift) |
| arma::mat | orthogonal_poly_basis_from_coefs (const arma::vec &t_vec, int degree, const arma::vec &alpha, const arma::vec &norm2) |
| arma::mat | orthogonal_basis_raw_coefficients (int degree, const arma::vec &alpha, const arma::vec &norm2) |
| bool | modified_gram_schmidt_qr (const arma::mat &X, arma::mat &Q, arma::mat &R) |
| arma::mat | build_orthogonal_poly_design (const arma::vec &t_vec, int degree, arma::vec &alpha, arma::vec &norm2) |
| arma::mat | build_poly_design (const arma::vec &t_vec, int degree, const std::string &basis, arma::vec &alpha, arma::vec &norm2, arma::mat &basis_raw_coeffs) |
| double | eval_poly_scalar (const arma::vec &coeffs, double t) |
| Evaluate a 1D polynomial sum(c_k * t^k) at a single time t. | |
| double | eval_poly_deriv1_scalar (const arma::vec &coeffs, double t) |
| Evaluate polynomial 1st derivative sum(k * c_k * t^(k-1)) at a single time t. | |
| double | eval_poly_deriv2_scalar (const arma::vec &coeffs, double t) |
| Evaluate polynomial 2nd derivative sum(k*(k-1) * c_k * t^(k-2)) at a single time t. | |
| arma::mat | eval_poly_curve (const arma::vec &coeffs_x, const arma::vec &coeffs_y, const arma::vec &t_eval) |
| Evaluate 2D parametric curve (x(t), y(t)) at multiple time points. | |
| PolyCurveFit | fit_poly_loocv2d (const arma::mat &points, const arma::vec &t=arma::vec(), int max_degree=3, int fixed_degree=0, const std::string &criterion="loocv", const std::string &basis="orthogonal") |
| Fit a 2D polynomial curve with automatic LOOCV-2D or AIC degree selection. | |
| TrajectoryDerivatives | eval_trajectory_derivatives (const arma::vec &coeffs_x, const arma::vec &coeffs_y, const arma::vec &t_eval) |
| Compute trajectory velocities, speeds, accelerations, heading turn rates, and curvatures. | |
| const GaussLegendreRule & | get_gl_rule_32 () |
| Obtain exact 32-point Gauss-Legendre quadrature nodes and weights on [-1, 1] via Golub-Welsch. | |
| double | integrated_curve_distance (const arma::vec &coeffs_ax, const arma::vec &coeffs_ay, const arma::vec &coeffs_bx, const arma::vec &coeffs_by, double t_start=0.0, double t_end=1.0) |
| Compute integrated Euclidean distance between two 2D parametric polynomial curves. | |
| double | lagged_curve_distance (const arma::vec &coeffs_fol_x, const arma::vec &coeffs_fol_y, const arma::vec &coeffs_ldr_x, const arma::vec &coeffs_ldr_y, double lag=0.0) |
| Compute lagged curve distance: 1/(1-lag) * integral_{lag}^1 ||F_follower(t) - F_leader(t - lag)|| dt. | |
| arma::mat | pairwise_trajectory_distance_matrix (const std::vector< arma::vec > &all_coeffs_x, const std::vector< arma::vec > &all_coeffs_y) |
| Compute pairwise integrated distance matrix across K polynomial trajectory curves. | |
| std::pair< double, int > | signed_turn_lag_distance (const arma::mat &pts_a, const arma::mat &pts_b, const arma::vec ×_a, const arma::vec ×_b, int delta) |
| Compute mean distance between agent A at turn T and agent B at turn T - delta. | |
| SignedTurnLagResult | best_signed_turn_lag (const arma::mat &pts_a, const arma::mat &pts_b, const arma::vec ×_a, const arma::vec ×_b, int max_lag=15) |
| Sweep signed turn lags in [-max_lag, max_lag] to determine leader-follower dynamics. | |
| void | require_finite (const arma::mat &m, const char *param) |
Throw if m contains NaN or Inf. | |
| void | require_dims (std::size_t n, int rows, int cols) |
Throw unless rows × cols describes exactly n elements. | |
Combinatorics | |
| int | choose_two (int n) |
Number of unordered pairs from n items (n choose 2). | |
| int | n_connections (int n, bool diagonal=false) |
Number of undirected connection columns for n codes. | |
| arma::umat | connection_indices (int len, int row=-1, bool diagonal=false) |
Upper-triangle index pairs for a symmetric matrix of side len. | |
Vector ↔ upper-triangle conversions | |
| arma::rowvec | code_connections (arma::mat v) |
| Compute pairwise products and return as a flat upper-triangle vector. | |
| arma::rowvec | fold_directed_network (arma::vec v, bool diagonal=false) |
| Fold a directed n² vector into an undirected upper-triangle vector. | |
| arma::rowvec | network_to_vector (arma::mat x, bool full=true, bool diagonal=false) |
| Flatten an adjacency matrix to a vector. | |
String utilities | |
| std::vector< std::string > | connection_names (std::vector< std::string > v, bool diagonal=false) |
| Generate "A & B" pair names for every upper-triangle position. | |
Centering | |
| arma::mat | center_points (arma::mat values) |
| Subtract column means so that every dimension is centred at the origin. | |
Group confidence intervals | |
| arma::mat | mean_ci (const arma::mat &points, double conf_level=0.95) |
| Student-t confidence interval for the mean of a group of ENA unit points. | |
| arma::mat | outlier_ci (const arma::mat &points, double iqr_factor=1.5) |
| Tukey-fence outlier interval for a group of ENA unit points. | |
Two-group comparison statistics | |
| GroupStats | group_stats (const arma::mat &g1, const arma::mat &g2) |
| Compute per-dimension two-group comparison statistics. | |
|
inline |
Apply EMA door smoothing to an entire connection matrix across multiple units.
|
inline |
Apply lookback door pooling to an entire connection matrix across multiple units.
| [in] | conn_counts | Complete connection matrix (all units). |
| [in] | unit_row_indices | Vector of row-index vectors, one per unit (0-indexed). |
| [in] | lookback_sizes | Vector of lookback sizes, one per unit. |
| [in] | aggregate_mean | When true, compute mean; when false, compute sum. |
| [in] | weighting_linear | When true, use linear weighting. |
| [in] | segment_ids | Optional vector of segment IDs for every row in conn_counts. |
conn_counts.
|
inline |
Sweep signed turn lags in [-max_lag, max_lag] to determine leader-follower dynamics.
|
inline |
|
inline |
|
inline |
|
inline |
Subtract column means so that every dimension is centred at the origin.
| [in] | values | Matrix of ENA unit points (n_units × n_dims). |
values with each column mean subtracted (centre-to-origin).center_data_c() in rENA/ena.cpp.
|
inline |
Number of unordered pairs from n items (n choose 2).
| n | Number of codes/nodes. |
(n * (n - 1)) / 2.
|
inline |
Compute pairwise products and return as a flat upper-triangle vector.
For each pair (j, i) with j < i, outputs v[j] * v[i]. The result has length choose_two(v.size()).
| v | A 1 × p row vector (or p-element matrix). |
choose_two(p). vector_to_ut() in rENA/ena.cpp.
|
inline |
Upper-triangle index pairs for a symmetric matrix of side len.
Column-major order: (0,1), (0,2), (1,2), ... – or, with diagonal, (0,0), (0,1), (1,1), (0,2), (1,2), (2,2), ... (Armadillo's trimatu_ind order), so a self-connection's row and column index are equal.
| len | Side length of the square matrix (number of codes). |
| row | Controls what is returned:
|
| diagonal | Include the diagonal (self-connections). Default false. |
arma::umat of shape 2×k or 1×k depending on row, with k = n_connections(len, diagonal). triIndices() in rENA/ena.cpp and tma/code.cpp (without diagonal).
|
inline |
Generate "A & B" pair names for every upper-triangle position.
For code names {"A", "B", "C"} returns {"A & B", "A & C", "B & C"}; with diagonal, {"A & A", "A & B", "B & B", "A & C", "B & C", "C & C"} (the connection_indices(p, -1, true) order).
| v | Ordered list of code names (length p). |
| diagonal | Include self-connections. Default false. |
n_connections(p, diagonal) label strings. svector_to_ut() in rENA/ena.cpp (without diagonal).
|
inline |
Compute Pearson correlation between pairwise Euclidean distance structures of two matrices.
Evaluates dist-dist correlation: r(dist(X), dist(Y)), measuring whether relative neighborhoods and distances are preserved across parameter changes (e.g. window vs lookback).
| [in] | X | Numeric matrix (n_rows × n_cols). |
| [in] | Y | Numeric matrix (n_rows × n_cols). |
|
inline |
Apply Exponential Moving Average (EMA) smoothing over a single unit's connection matrix.
Computes S_0 = Y_0, S_t = alpha * Y_t + (1 - alpha) * S_{t-1}. If segment_ids is non-empty, S_t resets to Y_t when transitioning to a new segment.
| [in] | block | Matrix of connection counts for one unit (n_rows × n_features). |
| [in] | alpha | Smoothing parameter alpha in (0, 1]. |
| [in] | segment_ids | Optional vector of segment/activity IDs (length n_rows). |
|
inline |
Evaluate 2D parametric curve (x(t), y(t)) at multiple time points.
|
inline |
Evaluate polynomial 1st derivative sum(k * c_k * t^(k-1)) at a single time t.
|
inline |
Evaluate polynomial 2nd derivative sum(k*(k-1) * c_k * t^(k-2)) at a single time t.
|
inline |
Evaluate a 1D polynomial sum(c_k * t^k) at a single time t.
|
inline |
Compute trajectory velocities, speeds, accelerations, heading turn rates, and curvatures.
|
inline |
Fit a 2D polynomial curve with automatic LOOCV-2D or AIC degree selection.
Given coordinates (x_i, y_i) and times t_i in [0, 1], constructs polynomial models for degrees d in [1, max_degree]. LOOCV error is computed via the closed-form hat-matrix formula: CV(d) = sum( (r_{x,i} / (1 - h_{ii}))^2 + (r_{y,i} / (1 - h_{ii}))^2 )
| [in] | points | n × 2 matrix of trajectory coordinates. |
| [in] | t | Vector of length n of strictly increasing times (default [0, 1] linearly spaced). |
| [in] | max_degree | Maximum polynomial degree to evaluate (default 3). |
| [in] | fixed_degree | When >= 1, uses this exact degree without search. |
| [in] | criterion | "loocv" (default) or "aic". |
|
inline |
Fold a directed n² vector into an undirected upper-triangle vector.
Symmetric elements are summed: A→B + B→A for every pair. With diagonal the self-connections (A→A) are kept, each once, in the connection_indices(n, -1, true) order (A & A, A & B, B & B, ...).
| v | Flat directed vector of length n², column-major (n = sqrt(v.size())). |
| diagonal | Keep the diagonal. Default false. |
n_connections(n, diagonal). vector_to_summed_uppertri() in tma/code.cpp (without diagonal).
|
inline |
Obtain exact 32-point Gauss-Legendre quadrature nodes and weights on [-1, 1] via Golub-Welsch.
|
inline |
Compute per-dimension two-group comparison statistics.
For each dimension d of the input matrices the function computes:
Parametric (Welch two-sample t-test)
(μ1−μ2) / √(((n1−1)s1² + (n2−1)s2²)/(n1+n2−2)))Non-parametric (Wilcoxon rank-sum / Mann-Whitney U)
wilcox.test W statistic)wilcox.test(..., correct=TRUE))1 − 2·U / (n1·n2) (rENA-api's nonparam.effect formula)| [in] | g1 | Unit points for group 1, n1 × n_dims. |
| [in] | g2 | Unit points for group 2, n2 × n_dims. |
group.stats() in rENA-api, moved to the C++ layer so all language bindings share a single implementation.
|
inline |
Compute integrated Euclidean distance between two 2D parametric polynomial curves.
Computes integral_{t_start}^{t_end} ||F_a(t) - F_b(t)|| dt using 32-point Gauss-Legendre quadrature.
| [in] | coeffs_ax | Coefficients of x_a(t). |
| [in] | coeffs_ay | Coefficients of y_a(t). |
| [in] | coeffs_bx | Coefficients of x_b(t). |
| [in] | coeffs_by | Coefficients of y_b(t). |
| [in] | t_start | Start of integration interval (default 0.0). |
| [in] | t_end | End of integration interval (default 1.0). |
|
inline |
Compute lagged curve distance: 1/(1-lag) * integral_{lag}^1 ||F_follower(t) - F_leader(t - lag)|| dt.
|
inline |
Single-response Lasso via cyclic coordinate descent at a fixed lambda.
Fits a Lasso regression for a single response vector using cyclic coordinate descent (naive updates). The partial-residual update for predictor
is:
where
is the residual maintained incrementally. Predictors with
skip the soft-threshold and receive the unconstrained OLS update instead.
| [in] | X | n×p column-standardized predictor matrix. |
| [in] | y | n×1 response vector (centering recommended but not required). |
| [in] | lambda | Regularization strength, on the standardized predictor scale. |
| [in] | pf | p×1 penalty factors (0 = unpenalized / forced in, 1 = standard L1). |
| [in] | beta0 | Warm-start coefficient vector; pass an empty arma::vec{} for a cold start from zero. |
| [in] | max_iter | Maximum number of coordinate-descent passes (default 1000). |
| [in] | tol | Convergence tolerance on the maximum coefficient change per pass (default 1e-7). |
|
inline |
Compute the smallest lambda that drives all penalized coefficients to zero.
For column-standardized X and column-centered Yc, lambda_max is:
Above this value every penalized coefficient is exactly zero (unpenalized predictors are unaffected and remain in via OLS regardless of lambda).
| [in] | X | n×p column-standardized predictor matrix. |
| [in] | Yc | n×q column-centered response matrix. |
| [in] | pf | p×1 penalty factors; predictors with pf(j) < 1e-12 are skipped. |
|
inline |
Cross-validated multivariate Lasso; returns fitted values for target columns only.
Fits a multivariate Lasso (one independent single-response problem per response column) along a log-spaced lambda path from lambda_max down to eps * lambda_max. Lambda is selected by k-fold cross-validation (mean squared error, averaged over folds and response columns), and the model is refit on the full data at the selected lambda using warm-starts along the path.
Preprocessing performed internally:
X_raw is column-standardized to zero mean and unit variance (zero-variance columns are left as-is to avoid division by zero).Y is column-centered to absorb the intercept.Fold assignment: row
is assigned to fold
(deterministic, order-dependent).
Return value: The n×q matrix
represents the portion of Y (mean-removed) that is linearly explained by the target predictors after penalizing covariate coefficients. A zero matrix is returned when the target predictors carry no signal at any lambda (e.g., the target is constant after subsetting). Constant shifts cancel in the downstream between-group scatter (categorical) and slope regression (numeric), so no ymu adjustment is applied to the return value.
| [in] | X_raw | n×p raw model matrix built by the caller (main effects and/or interactions); no formula parsing is done here. |
| [in] | Y | n×q ENA point matrix (multivariate response). |
| [in] | x1_cols | 0-based column indices in X_raw that belong to the target variable; these receive pf = 0 (always included). |
| [in] | pf | p×1 penalty factors: 0 for x1_cols, 1 elsewhere. The caller constructs this; non-standard weightings are supported. |
| [in] | n_lambda | Length of the lambda path (default 50). |
| [in] | k_folds | Number of cross-validation folds (default 5; clamped to [2, n/2]). |
| [in] | eps | Ratio lambda_min / lambda_max; controls how far down the path to search (default 0.01). |
x1_cols at the CV-selected lambda (lambda.min), on the original Y scale.
|
inline |
Apply a sliding lookback window pool over a single unit's connection matrix.
For each row i, pools rows in the window [max(0, i - lookback_size + 1), i]. If segment_ids is non-empty, the window does not cross rows with a different segment ID.
| [in] | block | Matrix of connection counts for one unit (n_rows × n_features). |
| [in] | lookback_size | Number of rows in the lookback window (>= 1). |
| [in] | aggregate_mean | When true, averages rows; when false, sums rows. |
| [in] | weighting_linear | When true, applies linearly increasing weights (oldest row in window has weight 1, current row has weight k). When false, all rows in window have equal weight 1. |
| [in] | segment_ids | Optional vector of segment/activity IDs (length n_rows). Window pooling resets at segment transitions. |
|
inline |
Student-t confidence interval for the mean of a group of ENA unit points.
For each dimension d:
where α = 1 − conf_level and degrees-of-freedom = n − 1.
| [in] | points | ENA unit points for a single group, n_units × n_dims. |
| [in] | conf_level | Confidence level for the interval (default 0.95). |
|
inline |
|
inline |
Number of undirected connection columns for n codes.
| n | Number of codes/nodes. |
| diagonal | Include self-connections (the diagonal, A & A). |
choose_two(n), or n(n+1)/2 with diagonal.
|
inline |
Flatten an adjacency matrix to a vector.
| x | Square adjacency matrix (n × n). |
| full | If true (default), returns the full n² vector (directed). If false, returns the upper-triangle only (undirected). |
| diagonal | With full false: include the diagonal, in the connection_indices(n, -1, true) order. Default false. |
n_connections(n, diagonal). adjacency_matrix_to_vector() in tma/code.cpp (without diagonal).
|
inline |
Normalize each row to unit L2 norm (project onto the unit hypersphere).
Rows whose L2 norm is zero are left unchanged.
| m | Input matrix (n_units × n_connections), row-major. |
fun_sphere_norm() in rENA/ena.cpp.
|
inline |
|
inline |
|
inline |
Tukey-fence outlier interval for a group of ENA unit points.
For each dimension d the half-width is computed as:
and the interval [−half_width, +half_width] is symmetric around zero, matching rENA's formula:
where the matrix is built from c(IQR(dim1), IQR(dim2), ...) * iqr_factor.
IQR uses R's default type-7 / Hyndman-Fan #7 quantile, identical to numpy.percentile(method="linear").
| [in] | points | ENA unit points for a single group, n_units × n_dims. |
| [in] | iqr_factor | Multiplier applied to the IQR (default 1.5, the standard Tukey fence threshold). |
|
inline |
Compute pairwise integrated distance matrix across K polynomial trajectory curves.
|
inline |
|
inline |
Throw unless rows × cols describes exactly n elements.
Bindings that receive a flat buffer plus explicit dimensions must call this before building an arma::mat over the buffer: arma::mat(ptr, rows, cols) reads rows*cols elements, so a short buffer would otherwise be padded with whatever memory follows it.
| std::invalid_argument | on a negative dimension or a size mismatch. |
|
inline |
Throw if m contains NaN or Inf.
| [in] | m | Matrix to check. |
| [in] | param | Name of the caller's argument, used in the message. |
| std::invalid_argument | naming param. |
|
inline |
Scale every entry by the reciprocal of the largest row L2 norm.
Preserves relative magnitudes across rows; does not normalise each row individually. If the largest row norm is zero, the matrix is returned unchanged.
| m | Input matrix (n_units × n_connections), modified in place. |
m). fun_skip_sphere_norm() in rENA/ena.cpp.
|
inline |
Compute mean distance between agent A at turn T and agent B at turn T - delta.
| [in] | pts_a | n_a × 2 coordinates for agent A. |
| [in] | pts_b | n_b × 2 coordinates for agent B. |
| [in] | times_a | Length n_a vector of calendar/turn indices for A. |
| [in] | times_b | Length n_b vector of calendar/turn indices for B. |
| [in] | delta | Signed lag in turns (delta > 0: A compares to B's past => A follows B; delta < 0: B compares to A's past => B follows A; delta = 0: sync). |
|
inlinenoexcept |
Soft-threshold (shrinkage) operator used by coordinate descent.
Computes the scalar soft-threshold function: 
| [in] | z | Input value. |
| [in] | gamma | Threshold amount (must be non-negative for meaningful use). |
|z| <= gamma.