CosmoBolognaLib
Free Software C++/Python libraries for cosmological calculations
covsample.cpp


This example shows how to generate correlated samples

// ===============================================================
// Example code: how to generate a sample from a covariance matrix
// ===============================================================
#include "Func.h"
int main () {
try {
// define a correlation matrix
std::vector<std::vector<double> > correlation = { {1, 0.6, 0.3}, {0.6, 1, 0.5}, {0.3, 0.5, 1} };
// define the mean and standard deviation of samples
int npt = 3;
std::vector<double> mean = {1., 3., 4.};
std::vector<double> stdev = {0.1, 0.3, 0.5};
std::vector<std::vector<double> > covariance(npt, std::vector<double>(npt, 0));
for (int i=0; i<npt; i++)
for (int j=0; j<npt; j++)
covariance[i][j] = correlation[i][j]*stdev[i]*stdev[j];
// generate nExtractions correlated samples
int nExtractions = 10000;
std::vector<std::vector<double> > sample = cbl::generate_correlated_data(nExtractions, mean, covariance, 231);
// measure the covariance matrix from the samples
std::vector<std::vector<double> > measured_covariance;
cbl::covariance_matrix(sample, measured_covariance);
for (size_t i=0; i<covariance.size(); i++)
for (size_t j=0; j<covariance[i].size(); j++)
std::cout << i << " " << j << " covariance: " << covariance[i][j] << ", measured covariance: " << measured_covariance[i][j] << std::endl;
std::cout << std::endl;
}
catch(cbl::glob::Exception &exc) { std::cerr << exc.what() << std::endl; exit(1); }
return 0;
}
Useful generic functions.
int main()
main function to create the logo of the CosmoBolognaLib
Definition: Logo.cpp:41
The class Exception.
Definition: Exception.h:111
const char * what() const noexcept override
the error description
Definition: Exception.h:203
std::vector< double > generate_correlated_data(const std::vector< double > mean, const std::vector< std::vector< double >> covariance, const int idum=213123)
generate a covariant sample of n points using a covariance matrix
Definition: Func.cpp:2142
void covariance_matrix(const std::vector< std::vector< double >> mat, std::vector< std::vector< double >> &cov, const bool JK=false)
compute the covariance matrix from an input dataset
Definition: Func.cpp:761