Hello, I’m trying to make a 2D lorentzian fit of a TH2D histogram, but the fit doesn’t seem to be right. Any idea how I can improve it?
I have attached the code that I’m using here
#include <iostream>
#include <iomanip>
#include <TF2.h>
#include <vector>
double Lorentzian2Dr(double *x, double *par) {
double r = sqrt(pow((x[0] - par[2]), 2.) + pow((x[1] - par[3]), 2.));
return (0.5*par[0]*par[1]/TMath::Pi()) /
TMath::Max( 1.e-10, r*r
+ .25*par[1]*par[1]);
}
void Graph2D(){
TH2D *gxyz = new TH2D("","",30,0,1500,30,0,1500);
TFile* myfile = new TFile("output_CO_2D_2_test.root", "READ");
TFile* proj = new TFile("2DGraph.root", "RECREATE");
TH3D* hxyz=(TH3D*)myfile->Get("LaBr3_Tdiff_3D_0_8");
hxyz->Write();
Int_t nx = hxyz->GetNbinsX();
Int_t ny = hxyz->GetNbinsY();
Int_t nz = hxyz->GetNbinsZ();
double Constant=1000;
double MeanX= hxyz->GetMean(2);
double SigmaX= hxyz->GetStdDev(2);
double MeanY= hxyz->GetMean(3);
double SigmaY= hxyz->GetStdDev(3);
Int_t nn = 0;
Double_t x, y, z, nw, nevts;
Double_t avgz = 0.0;
for (Int_t j = 1; j <= nx; j++) {
x = hxyz->GetXaxis()->GetBinCenter(j);
for (Int_t i = 1; i <= ny; i++) {
y = hxyz->GetYaxis()->GetBinCenter(i);
double nevts = 0;
double avgz = 0.0;
for (Int_t k = 1; k <= nz; k++) {
z = hxyz->GetZaxis()->GetBinCenter(k);
nw = hxyz->GetBinContent(j,i,k);
avgz += (z*nw);
nevts += nw;
}
if (avgz != 0) {
gxyz->Fill(x,y);
gxyz->SetBinContent(j,i,avgz/nevts);
}
}
}
TCanvas *c = new TCanvas("c","c",1000,600);
double maxResponse= gxyz->GetMaximumBin();
double Max= gxyz->GetBinContent(maxResponse);
double xMax= gxyz->GetXaxis()->GetBinCenter(maxResponse);
double yMax= gxyz->GetYaxis()->GetBinCenter(maxResponse);
TF2 *fLorentz = 0;
double par[] = {Max, -2, xMax, yMax};
fLorentz = new TF2("fLorentz",Lorentzian2Dr,
0, 1500,
0, 1500,4
);
fLorentz->SetParameters(par);
// fLorentz->FixParameter(2, xMax);
// fLorentz->FixParameter(3, yMax);
int fitResult = gxyz->Fit("fLorentz");
fLorentz->GetParameters(par);
gxyz->Fit("fLorentz");
gxyz->Draw("lego2");
proj->Close();
myfile->Close();
}