Memory issue with Minuit2 Minimizer in a loop


I am new to minuit2 and have a question. I am trying to minimize a function in a for loop (looping over possible parameters of the function). I want to minimize two parameters of a function around 5000 times (or more often), but varying its fixed variables.

When I run the example, my memory consumption increases rapidly. As a consequence it is problematic to run a similar program with more than 5000 function calls. I think I have to delete the minimizer object and clear my memory after every loop, but I don’t know how (I started just yesterday to use minuit2).
I tried also to put the definition of minimum inside the loop and than something like delete minimum; But then the program does not compile.

Can somebody help me? Thank you!

#include <TMath.h>
#include <TF2.h>
#include "TRandom2.h"
#include "Minuit2/Minuit2Minimizer.h"
#include "Math/Functor.h"

#include <stdlib.h>
#include <stack>
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <cmath> 
using namespace std;

double myfunction(const double *param)
	Double_t result = 0;
	const Double_t x = param[5];
	const Double_t y = param[6];
	TF2* Gauss = new TF2("gaus2","[0]*TMath::Gaus(x,[1],[2])*TMath::Gaus(y,[3],[4])", -20, 20, -20, 20);
	Gauss->SetParameters(param[0],param[1], param[2], param[3], param[4]);
	result += -(log(Gauss->Eval(x,y)) - Gauss->Eval(x,y));
	return result;

int minuit_test(){
	ROOT::Minuit2::Minuit2Minimizer minimum ( ROOT::Minuit2::kMigrad );
	for(Int_t l=0; l<5000; l++){
		Double_t x;
		Double_t y;
		TRandom2 r(l);
		x = r.Uniform(-19,19);
		y = r.Uniform(-19,19);
		ROOT::Math::Functor f(&myfunction,7);

		minimum.SetFixedVariable(0, "variable0", 1.0);
		minimum.SetFixedVariable(1, "variable1", x-0.5);
		minimum.SetFixedVariable(2, "variable2", y-0.5);
		minimum.SetFixedVariable(3, "variable3", 1.0);
		minimum.SetFixedVariable(4, "variable4", 1.0);
		minimum.SetVariable(5, "variable5", x, 0.01);
		minimum.SetVariable(6, "variable6", y, 0.01);
		const double *xs = minimum.X();

	return 0;

root_version: 5.34.32

I guess @moneta can help.

delete Gauss;
return result;

1 Like

Thank you, now it works!

double myfunction(const double *p) {
  Double_t v =
    p[0] * TMath::Gaus(p[5], p[1], p[2]) * TMath::Gaus(p[6], p[3], p[4]);
  if (v > 2.3e-320) v -= TMath::Log(v); else v = -736.;
  return v;

So the problem was my definition of TF2 (if I do not delete it afterwards)? Thanks for the alternative :slight_smile:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.