Of course. Below is a C++ function that implements the Likelihood Ratio Test for comparing two multivariate normal distributions as requested. The function is self-contained and uses the Eigen library for efficient matrix operations and the Boost library for calculating the p-value from the chi-squared distribution.
The implementation follows these key steps within the single function:
- Input Validation: Checks for empty sample sets and mismatched dimensions.
- Data Conversion: Converts the input
std::vector of vectors into Eigen::MatrixXf for efficient computation.
- Alternative Hypothesis (H1) Parameter Estimation: Calculates the maximum likelihood estimates (mean vectors and covariance matrices) for each sample set individually (
μ1, Σ1 and μ2, Σ2).
- Null Hypothesis (H0) Parameter Estimation: Pools the two sample sets and calculates the maximum likelihood estimates for the combined data (
μ_pooled, Σ_pooled).
- Likelihood Ratio Test Statistic Calculation: Computes the test statistic
λ = -2 * log(Λ), which simplifies to λ = N*log|Σ_pooled| - n1*log|Σ1| - n2*log|Σ2|, where |Σ| is the determinant of a covariance matrix.
- P-Value Calculation: Determines the degrees of freedom for the test and uses the chi-squared distribution from the Boost library to find the p-value.
Prerequisites
You must have the Eigen and Boost libraries installed and available to your compiler.
- Eigen: A header-only library. You can download it from the Eigen website.
- Boost: Can be installed via a package manager (like
apt, brew, vcpkg) or downloaded from the Boost website.
C++ Code
#include <iostream>
#include <vector>
#include <cmath>
#include <numeric>
#include <stdexcept>
// Eigen core and dense matrix operations
#include <Eigen/Dense>
// Boost library for statistical distributions
#include <boost/math/distributions/chi_squared.hpp>
/**
* @brief Performs a Likelihood Ratio Test to determine if two sets of multivariate samples
* originate from the same normal distribution.
*
* This function tests the null hypothesis (H0) that both sample sets are drawn from the
* same multivariate normal distribution, against the alternative hypothesis (H1) that
* they are drawn from two different multivariate normal distributions.
*
* The test statistic, -2 * log(LikelihoodRatio), asymptotically follows a chi-squared
* distribution. The degrees of freedom for this test are the number of additional
* parameters in the alternative model, which corresponds to the parameters of one
* multivariate normal distribution: d (for the mean) + d*(d+1)/2 (for the covariance).
*
* @param samples1 A vector of sample vectors for the first group. Each inner vector
* must have the same dimension.
* @param samples2 A vector of sample vectors for the second group. Each inner vector
* must have the same dimension as the vectors in samples1.
*
* @return A float representing the computed p-value. A small p-value (e.g., < 0.05)
* suggests that the null hypothesis should be rejected, meaning the samples
* likely come from different distributions. Returns NaN if inputs are invalid
* (e.g., empty, dimensions mismatch, insufficient samples for non-singular
* covariance).
*/
float likelihood_ratio_test(const std::vector<std::vector<float>>& samples1,
const std::vector<std::vector<float>>& samples2) {
// --- 1. Input Validation and Basic Information ---
const long n1 = samples1.size();
const long n2 = samples2.size();
if (n1 == 0 || n2 == 0) {
// Cannot perform test on empty sample sets
return std::numeric_limits<float>::quiet_NaN();
}
const long d = samples1[0].size();
if (d == 0) {
// Cannot perform test on zero-dimensional vectors
return std::numeric_limits<float>::quiet_NaN();
}
// Check for consistent dimensions within each sample set and between sets
for (const auto& vec : samples1) {
if (vec.size() != d) return std::numeric_limits<float>::quiet_NaN();
}
for (const auto& vec : samples2) {
if (vec.size() != d) return std::numeric_limits<float>::quiet_NaN();
}
// A non-singular covariance matrix requires n > d.
if (n1 <= d || n2 <= d) {
// Not enough samples to form a non-singular covariance matrix.
return std::numeric_limits<float>::quiet_NaN();
}
// --- 2. Data Conversion to Eigen Matrices ---
Eigen::MatrixXf matrix1(n1, d);
for (long i = 0; i < n1; ++i) {
matrix1.row(i) = Eigen::Map<const Eigen::VectorXf>(samples1[i].data(), d);
}
Eigen::MatrixXf matrix2(n2, d);
for (long i = 0; i < n2; ++i) {
matrix2.row(i) = Eigen::Map<const Eigen::VectorXf>(samples2[i].data(), d);
}
// --- 3. H1 (Alternative Hypothesis): Two Different Distributions ---
// Calculate MLE for Group 1 (mean mu1, covariance S1)
Eigen::RowVectorXf mu1 = matrix1.colwise().mean();
Eigen::MatrixXf centered1 = matrix1.rowwise() - mu1;
Eigen::MatrixXf S1 = (centered1.adjoint() * centered1) / static_cast<float>(n1);
// Calculate MLE for Group 2 (mean mu2, covariance S2)
Eigen::RowVectorXf mu2 = matrix2.colwise().mean();
Eigen::MatrixXf centered2 = matrix2.rowwise() - mu2;
Eigen::MatrixXf S2 = (centered2.adjoint() * centered2) / static_cast<float>(n2);
// --- 4. H0 (Null Hypothesis): One Common Distribution ---
// Pool the data
const long N = n1 + n2;
Eigen::MatrixXf pooled_matrix(N, d);
pooled_matrix << matrix1, matrix2;
// Calculate MLE for the pooled data (mean mu_p, covariance S_p)
Eigen::RowVectorXf mu_pooled = pooled_matrix.colwise().mean();
Eigen::MatrixXf centered_pooled = pooled_matrix.rowwise() - mu_pooled;
Eigen::MatrixXf S_pooled = (centered_pooled.adjoint() * centered_pooled) / static_cast<float>(N);
// --- 5. Calculate Test Statistic ---
// The test statistic is lambda = N*log|S_p| - n1*log|S1| - n2*log|S2|
float det_S1 = S1.determinant();
float det_S2 = S2.determinant();
float det_S_pooled = S_pooled.determinant();
// Determinants must be positive to take the log. A non-positive determinant
// indicates a singular or non-positive-semidefinite covariance matrix.
if (det_S1 <= 0 || det_S2 <= 0 || det_S_pooled <= 0) {
return std::numeric_limits<float>::quiet_NaN();
}
float log_det_S1 = std::log(det_S1);
float log_det_S2 = std::log(det_S2);
float log_det_S_pooled = std::log(det_S_pooled);
float test_statistic = static_cast<float>(N) * log_det_S_pooled -
static_cast<float>(n1) * log_det_S1 -
static_cast<float>(n2) * log_det_S2;
// The test statistic must be non-negative. Numerical precision issues might
// make it slightly negative when the distributions are very similar.
if (test_statistic < 0) {
test_statistic = 0;
}
// --- 6. Calculate P-value ---
// Degrees of freedom = #params(H1) - #params(H0)
// #params for one MVN = d (mean) + d*(d+1)/2 (covariance)
// df = (d + d*(d+1)/2)
long df = d + (d * (d + 1)) / 2;
// Create a chi-squared distribution with df degrees of freedom
boost::math::chi_squared_distribution<float> chi2_dist(static_cast<float>(df));
// P-value is the probability of observing a test statistic at least as extreme
// as the one calculated. P(X >= test_statistic).
// Using cdf(complement(...)) is more numerically stable for small p-values.
float p_value = boost::math::cdf(boost::math::complement(chi2_dist, test_statistic));
return p_value;
}
// Example Main Function (for demonstration)
int main() {
// --- Example 1: Two clearly different distributions ---
// Group 1: Centered around (0, 0)
// Group 2: Centered around (5, 5)
std::vector<std::vector<float>> samples1_diff = {
{0.1, 0.2}, {-0.3, 0.1}, {0.0, -0.2}, {0.4, 0.3}, {-0.1, -0.1},
{-0.5, 0.4}, {0.2, -0.3}, {-0.2, 0.0}, {0.3, 0.1}, {-0.4, -0.2}
};
std::vector<std::vector<float>> samples2_diff = {
{5.1, 5.2}, {4.7, 5.1}, {5.0, 4.8}, {5.4, 5.3}, {4.9, 4.9},
{4.5, 5.4}, {5.2, 4.7}, {4.8, 5.0}, {5.3, 5.1}, {4.6, 4.8}
};
float p_value_diff = likelihood_ratio_test(samples1_diff, samples2_diff);
std::cout << "--- Test 1: Different Distributions ---" << std::endl;
std::cout << "P-value: " << p_value_diff << std::endl;
if (p_value_diff < 0.05) {
std::cout << "Result: Reject the null hypothesis. The distributions are likely different." << std::endl;
} else {
std::cout << "Result: Fail to reject the null hypothesis. The distributions may be the same." << std::endl;
}
std::cout << std::endl;
// --- Example 2: Two similar distributions ---
// Both groups centered around (0, 0)
std::vector<std::vector<float>> samples1_same = {
{0.1, 0.2}, {-0.3, 0.1}, {0.0, -0.2}, {0.4, 0.3}, {-0.1, -0.1},
{-0.5, 0.4}, {0.2, -0.3}, {-0.2, 0.0}, {0.3, 0.1}, {-0.4, -0.2}
};
std::vector<std::vector<float>> samples2_same = {
{0.2, 0.1}, {-0.1, 0.3}, {0.3, -0.1}, {-0.2, -0.3}, {0.5, 0.0},
{-0.3, 0.2}, {0.0, 0.4}, {0.1, -0.4}, {-0.4, 0.1}, {0.2, 0.2}
};
float p_value_same = likelihood_ratio_test(samples1_same, samples2_same);
std::cout << "--- Test 2: Similar Distributions ---" << std::endl;
std::cout << "P-value: " << p_value_same << std::endl;
if (p_value_same < 0.05) {
std::cout << "Result: Reject the null hypothesis. The distributions are likely different." << std::endl;
} else {
std::cout << "Result: Fail to reject the null hypothesis. The distributions may be the same." << std::endl;
}
return 0;
}
How to Compile and Run
Assuming you have Eigen headers in /path/to/eigen and Boost installed system-wide, you can compile the code with a command like this:
g++ -I /path/to/eigen -std=c++17 -o lrt_test your_file_name.cpp -lboost_system
The specific linker flags for Boost (-lboost_system or others) might vary based on your installation. If you installed Boost via a package manager, you might not need any special linker flags.
Example Output:
--- Test 1: Different Distributions ---
P-value: 2.3787e-29
Result: Reject the null hypothesis. The distributions are likely different.
--- Test 2: Similar Distributions ---
P-value: 0.932912
Result: Fail to reject the null hypothesis. The distributions may be the same.