libqe 0.2.5
QE C++ library
Loading...
Searching...
No Matches
qe Namespace Reference

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 &times_a, const arma::vec &times_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 &times_a, const arma::vec &times_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.
 

Function Documentation

◆ apply_door_ema()

arma::mat qe::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 = {} 
)
inline

Apply EMA door smoothing to an entire connection matrix across multiple units.

◆ apply_door_lookback()

arma::mat qe::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 = {} 
)
inline

Apply lookback door pooling to an entire connection matrix across multiple units.

Parameters
[in]conn_countsComplete connection matrix (all units).
[in]unit_row_indicesVector of row-index vectors, one per unit (0-indexed).
[in]lookback_sizesVector of lookback sizes, one per unit.
[in]aggregate_meanWhen true, compute mean; when false, compute sum.
[in]weighting_linearWhen true, use linear weighting.
[in]segment_idsOptional vector of segment IDs for every row in conn_counts.
Returns
Smoothed connection matrix with identical dimensions to conn_counts.

◆ best_signed_turn_lag()

SignedTurnLagResult qe::best_signed_turn_lag ( const arma::mat &  pts_a,
const arma::mat &  pts_b,
const arma::vec &  times_a,
const arma::vec &  times_b,
int  max_lag = 15 
)
inline

Sweep signed turn lags in [-max_lag, max_lag] to determine leader-follower dynamics.

◆ build_orthogonal_poly_design()

arma::mat qe::build_orthogonal_poly_design ( const arma::vec &  t_vec,
int  degree,
arma::vec &  alpha,
arma::vec &  norm2 
)
inline

◆ build_poly_design()

arma::mat qe::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 
)
inline

◆ build_raw_poly_design()

arma::mat qe::build_raw_poly_design ( const arma::vec &  t_vec,
int  degree 
)
inline

◆ center_points()

arma::mat qe::center_points ( arma::mat  values)
inline

Subtract column means so that every dimension is centred at the origin.

Parameters
[in]valuesMatrix of ENA unit points (n_units × n_dims).
Returns
A copy of values with each column mean subtracted (centre-to-origin).
Note
Equivalent to center_data_c() in rENA/ena.cpp.

◆ choose_two()

int qe::choose_two ( int  n)
inline

Number of unordered pairs from n items (n choose 2).

Parameters
nNumber of codes/nodes.
Returns
(n * (n - 1)) / 2.

◆ code_connections()

arma::rowvec qe::code_connections ( arma::mat  v)
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()).

Parameters
vA 1 × p row vector (or p-element matrix).
Returns
A row vector of length choose_two(p).
Note
Equivalent to vector_to_ut() in rENA/ena.cpp.

◆ connection_indices()

arma::umat qe::connection_indices ( int  len,
int  row = -1,
bool  diagonal = false 
)
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.

Parameters
lenSide length of the square matrix (number of codes).
rowControls what is returned:
  • -1 (default): 2 × k matrix of [row_idx; col_idx].
  • 0: row indices only (1 × k).
  • 1: column indices only (1 × k).
diagonalInclude the diagonal (self-connections). Default false.
Returns
An arma::umat of shape 2×k or 1×k depending on row, with k = n_connections(len, diagonal).
Note
Equivalent to triIndices() in rENA/ena.cpp and tma/code.cpp (without diagonal).

◆ connection_names()

std::vector< std::string > qe::connection_names ( std::vector< std::string >  v,
bool  diagonal = false 
)
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).

Parameters
vOrdered list of code names (length p).
diagonalInclude self-connections. Default false.
Returns
Vector of n_connections(p, diagonal) label strings.
Note
Equivalent to svector_to_ut() in rENA/ena.cpp (without diagonal).

◆ dist_dist_correlation()

double qe::dist_dist_correlation ( const arma::mat &  X,
const arma::mat &  Y 
)
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).

Parameters
[in]XNumeric matrix (n_rows × n_cols).
[in]YNumeric matrix (n_rows × n_cols).
Returns
Pearson correlation coefficient in [-1, 1].

◆ ema_block()

arma::mat qe::ema_block ( const arma::mat &  block,
double  alpha = 0.1,
const std::vector< int > &  segment_ids = {} 
)
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.

Parameters
[in]blockMatrix of connection counts for one unit (n_rows × n_features).
[in]alphaSmoothing parameter alpha in (0, 1].
[in]segment_idsOptional vector of segment/activity IDs (length n_rows).
Returns
A matrix of shape n_rows × n_features containing EMA-smoothed values.

◆ eval_poly_curve()

arma::mat qe::eval_poly_curve ( const arma::vec &  coeffs_x,
const arma::vec &  coeffs_y,
const arma::vec &  t_eval 
)
inline

Evaluate 2D parametric curve (x(t), y(t)) at multiple time points.

◆ eval_poly_deriv1_scalar()

double qe::eval_poly_deriv1_scalar ( const arma::vec &  coeffs,
double  t 
)
inline

Evaluate polynomial 1st derivative sum(k * c_k * t^(k-1)) at a single time t.

◆ eval_poly_deriv2_scalar()

double qe::eval_poly_deriv2_scalar ( const arma::vec &  coeffs,
double  t 
)
inline

Evaluate polynomial 2nd derivative sum(k*(k-1) * c_k * t^(k-2)) at a single time t.

◆ eval_poly_scalar()

double qe::eval_poly_scalar ( const arma::vec &  coeffs,
double  t 
)
inline

Evaluate a 1D polynomial sum(c_k * t^k) at a single time t.

◆ eval_trajectory_derivatives()

TrajectoryDerivatives qe::eval_trajectory_derivatives ( const arma::vec &  coeffs_x,
const arma::vec &  coeffs_y,
const arma::vec &  t_eval 
)
inline

Compute trajectory velocities, speeds, accelerations, heading turn rates, and curvatures.

◆ fit_poly_loocv2d()

PolyCurveFit qe::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" 
)
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 )

Parameters
[in]pointsn × 2 matrix of trajectory coordinates.
[in]tVector of length n of strictly increasing times (default [0, 1] linearly spaced).
[in]max_degreeMaximum polynomial degree to evaluate (default 3).
[in]fixed_degreeWhen >= 1, uses this exact degree without search.
[in]criterion"loocv" (default) or "aic".
Returns
PolyCurveFit containing optimal degree, coefficients, errors, and fitted points.

◆ fold_directed_network()

arma::rowvec qe::fold_directed_network ( arma::vec  v,
bool  diagonal = false 
)
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, ...).

Parameters
vFlat directed vector of length n², column-major (n = sqrt(v.size())).
diagonalKeep the diagonal. Default false.
Returns
Upper-triangle row vector of length n_connections(n, diagonal).
Note
Equivalent to vector_to_summed_uppertri() in tma/code.cpp (without diagonal).

◆ get_gl_rule_32()

const GaussLegendreRule & qe::get_gl_rule_32 ( )
inline

Obtain exact 32-point Gauss-Legendre quadrature nodes and weights on [-1, 1] via Golub-Welsch.

◆ group_stats()

GroupStats qe::group_stats ( const arma::mat &  g1,
const arma::mat &  g2 
)
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)

  • t-statistic and Welch–Satterthwaite degrees of freedom
  • Two-tailed p-value via the regularised incomplete beta function
  • Cohen's d using the pooled-SD formula ((μ1−μ2) / √(((n1−1)s1² + (n2−1)s2²)/(n1+n2−2)))
  • Per-group means and sample standard deviations

Non-parametric (Wilcoxon rank-sum / Mann-Whitney U)

  • U statistic for group 1 (identical to R's wilcox.test W statistic)
  • Two-tailed p-value via the normal approximation with tie correction and continuity correction (matching R's wilcox.test(..., correct=TRUE))
  • Rank-biserial effect size: 1 − 2·U / (n1·n2) (rENA-api's nonparam.effect formula)
  • Per-group medians
Parameters
[in]g1Unit points for group 1, n1 × n_dims.
[in]g2Unit points for group 2, n2 × n_dims.
Returns
A GroupStats struct.
Note
Parametric statistics are NaN when either group has fewer than 2 units (no sample variance). All statistics are NaN when either group is empty.
The Wilcoxon p-value uses the normal approximation regardless of sample size; R switches to an exact test for small (n ≤ ~50) tie-free samples, so p-values may differ slightly in those cases.
Equivalent to group.stats() in rENA-api, moved to the C++ layer so all language bindings share a single implementation.

◆ integrated_curve_distance()

double qe::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 
)
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.

Parameters
[in]coeffs_axCoefficients of x_a(t).
[in]coeffs_ayCoefficients of y_a(t).
[in]coeffs_bxCoefficients of x_b(t).
[in]coeffs_byCoefficients of y_b(t).
[in]t_startStart of integration interval (default 0.0).
[in]t_endEnd of integration interval (default 1.0).
Returns
Integrated distance scalar.

◆ lagged_curve_distance()

double qe::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 
)
inline

Compute lagged curve distance: 1/(1-lag) * integral_{lag}^1 ||F_follower(t) - F_leader(t - lag)|| dt.

◆ lasso_cd()

arma::vec qe::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 
)
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 $j$ is:

\[
  z_j = \frac{X_j^\top r}{n} + \frac{X_j^\top X_j}{n}\,\beta_j
\]

\[
  \beta_j \leftarrow \frac{S\!\left(z_j,\;\lambda\,\mathit{pf}_j\right)}{X_j^\top X_j / n}
\]

where $r = y - X\beta$ is the residual maintained incrementally. Predictors with $\mathit{pf}_j = 0$ skip the soft-threshold and receive the unconstrained OLS update instead.

Parameters
[in]Xn×p column-standardized predictor matrix.
[in]yn×1 response vector (centering recommended but not required).
[in]lambdaRegularization strength, on the standardized predictor scale.
[in]pfp×1 penalty factors (0 = unpenalized / forced in, 1 = standard L1).
[in]beta0Warm-start coefficient vector; pass an empty arma::vec{} for a cold start from zero.
[in]max_iterMaximum number of coordinate-descent passes (default 1000).
[in]tolConvergence tolerance on the maximum coefficient change per pass (default 1e-7).
Returns
p×1 coefficient vector on the standardized predictor scale.

◆ lasso_lambda_max()

double qe::lasso_lambda_max ( const arma::mat &  X,
const arma::mat &  Yc,
const arma::vec &  pf 
)
inline

Compute the smallest lambda that drives all penalized coefficients to zero.

For column-standardized X and column-centered Yc, lambda_max is:

\[
  \lambda_{\max} = \max_{\substack{j:\,\mathit{pf}_j > 0 \\ k}} \frac{|X_j^\top Y_{c,k}|}{n}
\]

Above this value every penalized coefficient is exactly zero (unpenalized predictors are unaffected and remain in via OLS regardless of lambda).

Parameters
[in]Xn×p column-standardized predictor matrix.
[in]Ycn×q column-centered response matrix.
[in]pfp×1 penalty factors; predictors with pf(j) < 1e-12 are skipped.
Returns
Scalar lambda_max value.

◆ lasso_x1_contribution()

arma::mat qe::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 
)
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.
  • Coefficients are unstandardized before the contribution is computed.

Fold assignment: row $i$ is assigned to fold $i \bmod k$ (deterministic, order-dependent).

Return value: The n×q matrix $X_{\text{raw},x_1} \hat{B}_{x_1}$ 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.

Parameters
[in]X_rawn×p raw model matrix built by the caller (main effects and/or interactions); no formula parsing is done here.
[in]Yn×q ENA point matrix (multivariate response).
[in]x1_cols0-based column indices in X_raw that belong to the target variable; these receive pf = 0 (always included).
[in]pfp×1 penalty factors: 0 for x1_cols, 1 elsewhere. The caller constructs this; non-standard weightings are supported.
[in]n_lambdaLength of the lambda path (default 50).
[in]k_foldsNumber of cross-validation folds (default 5; clamped to [2, n/2]).
[in]epsRatio lambda_min / lambda_max; controls how far down the path to search (default 0.01).
Returns
n×q matrix of fitted values attributable to x1_cols at the CV-selected lambda (lambda.min), on the original Y scale.

◆ lookback_block()

arma::mat qe::lookback_block ( const arma::mat &  block,
int  lookback_size = 20,
bool  aggregate_mean = false,
bool  weighting_linear = false,
const std::vector< int > &  segment_ids = {} 
)
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.

Parameters
[in]blockMatrix of connection counts for one unit (n_rows × n_features).
[in]lookback_sizeNumber of rows in the lookback window (>= 1).
[in]aggregate_meanWhen true, averages rows; when false, sums rows.
[in]weighting_linearWhen 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_idsOptional vector of segment/activity IDs (length n_rows). Window pooling resets at segment transitions.
Returns
A matrix of shape n_rows × n_features containing door-smoothed values.

◆ mean_ci()

arma::mat qe::mean_ci ( const arma::mat &  points,
double  conf_level = 0.95 
)
inline

Student-t confidence interval for the mean of a group of ENA unit points.

For each dimension d:

mean ± t_{α/2, n-1} × (sample_sd / sqrt(n))

where α = 1 − conf_level and degrees-of-freedom = n − 1.

Parameters
[in]pointsENA unit points for a single group, n_units × n_dims.
[in]conf_levelConfidence level for the interval (default 0.95).
Returns
An n_dims × 3 matrix whose columns are [mean, ci_lower, ci_upper]. When n == 0 all entries are NaN. When n == 1 the CI bounds are ±Inf.

◆ modified_gram_schmidt_qr()

bool qe::modified_gram_schmidt_qr ( const arma::mat &  X,
arma::mat &  Q,
arma::mat &  R 
)
inline

◆ n_connections()

int qe::n_connections ( int  n,
bool  diagonal = false 
)
inline

Number of undirected connection columns for n codes.

Parameters
nNumber of codes/nodes.
diagonalInclude self-connections (the diagonal, A & A).
Returns
choose_two(n), or n(n+1)/2 with diagonal.

◆ network_to_vector()

arma::rowvec qe::network_to_vector ( arma::mat  x,
bool  full = true,
bool  diagonal = false 
)
inline

Flatten an adjacency matrix to a vector.

Parameters
xSquare adjacency matrix (n × n).
fullIf true (default), returns the full n² vector (directed). If false, returns the upper-triangle only (undirected).
diagonalWith full false: include the diagonal, in the connection_indices(n, -1, true) order. Default false.
Returns
Row vector of length n² or n_connections(n, diagonal).
Note
Equivalent to adjacency_matrix_to_vector() in tma/code.cpp (without diagonal).

◆ normalize_networks()

arma::mat qe::normalize_networks ( arma::mat  m)
inline

Normalize each row to unit L2 norm (project onto the unit hypersphere).

Rows whose L2 norm is zero are left unchanged.

Parameters
mInput matrix (n_units × n_connections), row-major.
Returns
Matrix of the same shape with each row divided by its L2 norm.
Note
Equivalent to fun_sphere_norm() in rENA/ena.cpp.

◆ orthogonal_basis_raw_coefficients()

arma::mat qe::orthogonal_basis_raw_coefficients ( int  degree,
const arma::vec &  alpha,
const arma::vec &  norm2 
)
inline

◆ orthogonal_poly_basis_from_coefs()

arma::mat qe::orthogonal_poly_basis_from_coefs ( const arma::vec &  t_vec,
int  degree,
const arma::vec &  alpha,
const arma::vec &  norm2 
)
inline

◆ outlier_ci()

arma::mat qe::outlier_ci ( const arma::mat &  points,
double  iqr_factor = 1.5 
)
inline

Tukey-fence outlier interval for a group of ENA unit points.

For each dimension d the half-width is computed as:

half_width[d] = iqr_factor * IQR(points[:, d])

and the interval [−half_width, +half_width] is symmetric around zero, matching rENA's formula:

outlier.interval.values = matrix(...) * c(-1, 1)

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").

Parameters
[in]pointsENA unit points for a single group, n_units × n_dims.
[in]iqr_factorMultiplier applied to the IQR (default 1.5, the standard Tukey fence threshold).
Returns
An n_dims × 2 matrix whose columns are [lower, upper]. When n == 0 all entries are NaN. When n == 1, IQR == 0, so lower == upper == 0.

◆ pairwise_trajectory_distance_matrix()

arma::mat qe::pairwise_trajectory_distance_matrix ( const std::vector< arma::vec > &  all_coeffs_x,
const std::vector< arma::vec > &  all_coeffs_y 
)
inline

Compute pairwise integrated distance matrix across K polynomial trajectory curves.

◆ poly_multiply_by_linear()

arma::vec qe::poly_multiply_by_linear ( const arma::vec &  coeffs,
double  shift 
)
inline

◆ require_dims()

void qe::require_dims ( std::size_t  n,
int  rows,
int  cols 
)
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.

Exceptions
std::invalid_argumenton a negative dimension or a size mismatch.

◆ require_finite()

void qe::require_finite ( const arma::mat &  m,
const char *  param 
)
inline

Throw if m contains NaN or Inf.

Parameters
[in]mMatrix to check.
[in]paramName of the caller's argument, used in the message.
Exceptions
std::invalid_argumentnaming param.

◆ scale_networks()

arma::mat qe::scale_networks ( arma::mat  m)
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.

Parameters
mInput matrix (n_units × n_connections), modified in place.
Returns
Scaled matrix (same shape as m).
Note
Equivalent to fun_skip_sphere_norm() in rENA/ena.cpp.

◆ signed_turn_lag_distance()

std::pair< double, int > qe::signed_turn_lag_distance ( const arma::mat &  pts_a,
const arma::mat &  pts_b,
const arma::vec &  times_a,
const arma::vec &  times_b,
int  delta 
)
inline

Compute mean distance between agent A at turn T and agent B at turn T - delta.

Parameters
[in]pts_an_a × 2 coordinates for agent A.
[in]pts_bn_b × 2 coordinates for agent B.
[in]times_aLength n_a vector of calendar/turn indices for A.
[in]times_bLength n_b vector of calendar/turn indices for B.
[in]deltaSigned 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).
Returns
Pair of (mean_distance, valid_pairs_count).

◆ soft_threshold()

double qe::soft_threshold ( double  z,
double  gamma 
)
inlinenoexcept

Soft-threshold (shrinkage) operator used by coordinate descent.

Computes the scalar soft-threshold function: $ S(z,\gamma) = \operatorname{sign}(z)\,\max(|z|-\gamma,\,0) $

Parameters
[in]zInput value.
[in]gammaThreshold amount (must be non-negative for meaningful use).
Returns
Soft-thresholded value; exactly zero when |z| <= gamma.