Transfer covarariance matrix to an output file

Hello everyone,

I am working on a project that requires me to fit data points to an exponential function. I am using the ROOT framework for the finding the best-fit parameters. I have done that part and I am exporting the best-fit values into a text file along with some descriptive statistics like errors on the fitted parameters, the chi-squared and reduced chi-squared values etc. I am also trying to transfer a covariance matrix to the output file but I am not able to do it. So, how do I transfer the covariance matrix to an output file in ROOT?

I would highly appreciate it if I could get some help on this issue.

Scroll down to “The fit result object” and see the examples; basically you need a TFitResultPtr and then use Print(“V”).

Thank you for your response. As of now, I am able to transfer the covariance matrix into a .root file. However, I would like to export the covariance matrices to a .txt file. Is there a way to do that?

Any helpful suggestions will be highly appreciated!

That depends. Are you using C++ or Python?

I am using C++. But I can also use Python if that will get the job done.

There is no quick way to do that in RooFit, but you can write your own little function for that:

/// Save the covariance matrix of a RooFitResult in a text file.
void saveRooFitCovMatrix(RooFitResult const &rooFitResult,
                         std::string const &filename)
{
   auto const &cov = rooFitResult.covarianceMatrix();

   std::ofstream ofile;
   ofile.open(filename.c_str(), std::ios::out);

   // to get max precision
   ofile.precision(std::numeric_limits<double>::max_digits10);

   for (int iRow = 0; iRow < cov.GetNrows(); ++iRow) {
      for (int iCol = 0; iCol < cov.GetNcols(); ++iCol) {
         ofile << cov(iRow, iCol);
         if (iCol != cov.GetNcols() - 1)
            ofile << ", ";
      }
      ofile << "\n";
   }

   ofile.close();
}

You would use it like:

std::unique_ptr<RooFitResult> result{model.fitTo(*data, Save())};
saveRooFitCovMatrix(*result, "covarianceMatrix.txt");

The output would look like:

0.00090086395306402506, 1.7919161569678971e-05
1.7919161569678971e-05, 0.00048056506926952091

I hope this solution works for you!

Cheers,
Jonas

2 Likes

Thank you very much! It worked! I made some changes to your code as I wanted to calculate and append the multiple covariance matrices to the text file. But I used your code heavily as a reference. Thank you very much once again!