Here is my try based on Ifit.C to fit n Gaussians above a parabola background, where mean and sigma of the Gaussians should be constraint to be the same. The printed results, however, look like complete nonsense.
#include "TMinuit.h"
const int nhistmax = 5;
int nhist=0;
TH1F *hfit[nhistmax];
//______________________________________________________________________________
void fcn(Int_t &npar, Double_t *gin, Double_t &f, Double_t *par, Int_t iflag)
{
double m = par[0];
double G = par[1];
double chi2 = 0;
// compute chi2 for nhist histograms fitted with Gaus + pol2, Gaus mean and sigma constraint
for (int ih=0; ih<nhist; ++ih) {
for (int ib=1; ib<=hfit[ih]->GetNbinsX(); ++ib) {
int pidx = 2+4*ih;
double x = hfit[ih]->GetBinCenter(ib); // x position
double hy = hfit[ih]->GetBinContent(ib); // histogram entries
double hdy = hfit[ih]->GetBinError(ib); // histogram entries error
double fy = par[pidx]*TMath::Gaus(x, m, G, 1) + par[pidx+1] + par[pidx+2]*x + par[pidx+3]*x*x; // function value
chi2 += hdy>0 ? (hy - fy)/hdy : 0.;
}
}
// return fitness
f = chi2;
}
//______________________________________________________________________________
void minuitfit(int nh = 2, double m = 5, double G = 0.3, int N=10000)
{
TCanvas *c1 = new TCanvas("c1","c1",20,20,nh*350,350);
c1->Divide(nh,1,0.0001,0.0001);
nhist = nh;
TF1 *f1 = new TF1("f1","gausn(0) + pol2(3)",0,10);
int npar = 2 + nh*4;
for (int i=0;i<nhist;++i) {
hfit[i] = new TH1F(Form("h%d",i), Form("hist %d",i), 50+i*50, 0, 10);
f1->SetParameters(20+i*5, m, G, 20+i*3, 1+i,0.3-0.2*i*i);
hfit[i]->FillRandom("f1",N);
c1->cd(i+1);
hfit[i]->Draw("e");
}
TMinuit *gMinuit = new TMinuit(npar); //initialize TMinuit with a maximum of 5 params
gMinuit->SetFCN(fcn);
Double_t arglist[10];
Int_t ierflg = 0;
arglist[0] = 1;
gMinuit->mnexcm("SET ERR", arglist ,1, ierflg);
// Set starting values and step sizes for parameters
double vstart[100], step[100];
vstart[0] = m;
vstart[1] = G;
for (int i=0; i<nh;++i) {
vstart[2+i*4] = 20+i*5;
vstart[2+i*4+1] = 20+i*3;
vstart[2+i*4+2] = 1+i;
vstart[2+i*4+3] = 0.3-0.2*i*i;
}
for (int i=0;i<npar; ++i) {
step[i] = 0.01;
gMinuit->mnparm(i, Form("p%02d", i), vstart[i], step[i], 0, 0, ierflg);
}
// Print results
Double_t amin,edm,errdef;
Int_t nvpar,nparx,icstat;
// Now ready for minimization step
arglist[0] = 10000;
arglist[1] = 0.01;
gMinuit->mnexcm("MIGRAD", arglist, 2, ierflg);
gMinuit->mnstat(amin, edm, errdef, nvpar, nparx, icstat);
gMinuit->mnprin(3,amin);
}