void perform_smart_fit(TGraphErrors * gabscor, TF1 * fabscor) { int maxFitIter = 50; int fitIter = 0; vector<double> bestPars; double bestRChi2 = 0; do { // // do the fit, get the results and the parameters of the fitted function // TFitResultPtr fitResPtr = gabscor->Fit(fabscor,"RQ0S"); vector<double> auxPars = fitResPtr.Get()->Parameters(); // // compute the reduced chi2 of this fit and if it is the best fit so far // then save the parameters // double rchi2 = fitResPtr.Get()->Chi2()/ fitResPtr.Get()->Ndf(); if (fitResPtr.Get()->Ndf() == 0) rchi2 = 0; if (rchi2 > 0 && (rchi2<bestRChi2 || bestRChi2==0)){ bestRChi2 = rchi2; bestPars = auxPars; } // // increment the counter // fitIter++; }while(( bestRChi2 > 2 || bestRChi2 == 0 ) && fitIter < maxFitIter); // // set the best parameters and chi2 to the fit function // TF1 * ffh = gabscor->GetFunction("fit"); for (unsigned int np=0;np < bestPars.size() ; np++){ ffh->SetParameter(np,bestPars[np]); fabscor->SetParameter(np,bestPars[np]); } fabscor->SetChisquare(bestRChi2 * fabscor->GetNDF()); ffh->SetChisquare(bestRChi2 * fabscor->GetNDF()); // // warn if the fit diverges at low pt // //if (fabscor->Integral(0,10) > 25) //cout << "\t***ERROR***, fit for histo " << gabscor->GetName() << " diverges at low pt (<10 GeV/c)" << endl; // // check for failed fits // a chi2 of zero is symptomatic of a failed fit. // if (bestRChi2 < 0.001){ cout<<"\t***ERROR***, FIT HAS FAILED for histo "<<gabscor->GetName() <<" which has a reduced chi2="<<bestRChi2 <<" after "<<fitIter<<" iterations. "<<endl; } // // check for large reduced chi2's // above 10 is a plain error; between 5 and 10 is a warning // if (bestRChi2 > 5){ if (bestRChi2 > 10) cout<<"\t***ERROR***,"; else cout<<"\tWARNING,"; cout<<" fit for histo "<<gabscor->GetName() <<" has a reduced chi2="<<bestRChi2 <<" after "<<fitIter<<" iterations"<<endl; } }