Create a TF1 from a TGraph

Dear rooters,

I’m trying to fit my spectra from experiment with monte carlo data (with some parameters) with a code that simulates the experiment.

So, I have the experimental data saved in a TGraphErrors and the simulated data in a TH1F. I’ve created a TGraph from the TH1F of the simulated data and according to root.cern.ch/doc/master/classTF1.html I could do something like this :

TGraph * g = new TGraph(npointx, xvec, yvec); 
TF1 * f = new TF1("f",[&](double*x, double *p){ return p[0]*g->Eval(x[0]); }, xmin, xmax, 1); 

Please find below my code, it compiles without any error but when running gives:
 *** Break *** segmentation violation
 Generating stack trace...
void analyze() {

cout.precision(12) ;

TFile * simulf=new TFile("simulations_3/Histogram_antiparallel_3139.583_.05.root");


TFile * f_antiparallel= new TFile("data/data_2011_01_06_root/2011_06_01_18h09m28s.root");

TGraphErrors * h_antiparallel=(TGraphErrors*)f_antiparallel->Get("h_exp");//get the  antiparallel histo saved in the root file
TH1F * simul=(TH1F*)simulf->Get("h_simul");// load all the simulation histos from the files
TGraph *s imulations_parallel= new TGraph(simul);

TCanvas * c1 = new TCanvas("c1","test_simul");


c1->cd();
		
		TF1 *fit_antip= new TF1("fit_antip",[&](double*x, double *par){ return par[1]+par[0]*simulations_parallel->Eval(x[0]-par[2])+par[3]*x[0];}, 51.941, 52.139, 4);
		Double_t par[4] ={0.008394655361534658,76.42844706478005,0.0002313449355976212,-1.515272195510712}; 
		fit_antip->SetParameters(par);	
	    fit_antip->SetParName(0,"amplitude");
	    fit_antip->SetParName(1,"baseline");
	    fit_antip->SetParName(2,"energy offset");
		fit_antip->SetParName(3,"slope");
		
		fit_antip->SetNpx(1000);
		h_antiparallel->Draw("*AP");
		h_antiparallel->Fit("fit_antip","R");	
}

Anyone knows what might be the problem. Thanks

Hi,

The problem is in storing the fit function in the histogram or graph object. I will fix this problem. For the moment you should use the option “N” when fitting (don’t store the function and don’t draw it) and if you want to draw the functions you should do it manually as following:

 h_antiparallel->Fit("fit_antip","R N");  
 TF1 * fittedFunc = (TF1*) fit_antip->Clone(); 
 h_antiparallel->GetListOfFunctions()->Add(fittedFunc); 

Best Regards

Lorenzo

Thanks Lorenzo,

It works fine now :smiley:.

Best Regards,

Jorge