8#include "TFitResultPtr.h"
9#include "TVirtualFitter.h"
24template<
typename T> T
Sqr(T in) {
return in*in;}
34 {
"tag", {JSON::value_t::string, 1,
true,
true}},
35 {
"enabled", {JSON::value_t::boolean, 1,
true,
true}},
36 {
"LGMode", {JSON::value_t::number_unsigned, 1,
false,
true}},
37 {
"Nsample", {JSON::value_t::number_integer, 1,
false,
true}},
38 {
"FADCFreqMHz", {JSON::value_t::number_integer, 1,
false,
true}},
39 {
"preSampleIdx", {JSON::value_t::number_integer, 1,
true,
true}},
40 {
"nominalPedestal", {JSON::value_t::number_integer, 1,
false,
true}},
41 {
"fitFunction", {JSON::value_t::string, 1,
true,
true}},
42 {
"peakSample", {JSON::value_t::number_integer, 1,
true,
true}},
43 {
"peakTolerance", {JSON::value_t::number_integer, 1,
true,
false}},
44 {
"quietFits", {JSON::value_t::boolean, 1,
false,
false}},
45 {
"2ndDerivThreshHG", {JSON::value_t::number_integer, 1,
true,
true}},
46 {
"2ndDerivThreshLG", {JSON::value_t::number_integer, 1,
true,
true}},
47 {
"2ndDerivStep", {JSON::value_t::number_integer, 1,
false,
false}},
48 {
"HGOverflowADC", {JSON::value_t::number_integer, 1,
true,
true}},
49 {
"HGUnderflowADC", {JSON::value_t::number_integer, 1,
true,
true}},
50 {
"LGOverflowADC", {JSON::value_t::number_integer, 1,
true,
true}},
51 {
"nominalT0HG", {JSON::value_t::number_float, 1,
true,
true}},
52 {
"nominalT0LG", {JSON::value_t::number_float, 1,
true,
true}},
53 {
"nominalTau1", {JSON::value_t::number_float, 1,
true,
false}},
54 {
"nominalTau2", {JSON::value_t::number_float, 1,
true,
false}},
55 {
"fixTau1", {JSON::value_t::boolean, 1,
true,
false}},
56 {
"fixTau2", {JSON::value_t::boolean, 1,
true,
false}},
57 {
"T0CutsHG", {JSON::value_t::array, 2,
true,
true}},
58 {
"T0CutsLG", {JSON::value_t::array, 2,
true,
true}},
59 {
"chisqDivAmpCutHG", {JSON::value_t::number_float, 1,
true,
true}},
60 {
"chisqDivAmpCutLG", {JSON::value_t::number_float, 1,
true,
true}},
61 {
"chisqDivAmpScaleHG", {JSON::value_t::number_float, 1,
true,
true}},
62 {
"chisqDivAmpScaleLG", {JSON::value_t::number_float, 1,
true,
true}},
63 {
"chisqDivAmpOffsetHG", {JSON::value_t::number_float, 1,
true,
true}},
64 {
"chisqDivAmpOffsetLG", {JSON::value_t::number_float, 1,
true,
true}},
65 {
"chisqDivAmpPowerHG", {JSON::value_t::number_float, 1,
true,
true}},
66 {
"chisqDivAmpPowerLG", {JSON::value_t::number_float, 1,
true,
true}},
67 {
"gainFactorHG", {JSON::value_t::number_float, 1,
true,
true}},
68 {
"gainFactorLG", {JSON::value_t::number_float, 1,
true,
true}},
69 {
"noiseSigmaHG", {JSON::value_t::number_float, 1,
true,
true}},
70 {
"noiseSigmaLG", {JSON::value_t::number_float, 1,
true,
true}},
71 {
"perSampleNoiseSigmaHG", {JSON::value_t::array, -1,
true,
true}},
72 {
"perSampleNoiseSigmaLG", {JSON::value_t::array, -1,
true,
true}},
73 {
"enableRepass", {JSON::value_t::boolean, 1,
false,
false}},
74 {
"Repass2ndDerivThreshHG", {JSON::value_t::number_integer, 1,
true,
true}},
75 {
"Repass2ndDerivThreshLG", {JSON::value_t::number_integer, 1,
true,
true}},
76 {
"fitAmpMinMaxHG", {JSON::value_t::array, 2,
true,
false}},
77 {
"fitAmpMinMaxLG", {JSON::value_t::array, 2,
true,
false}},
78 {
"ampMinSignifHGLG", {JSON::value_t::array, 2,
true,
false}},
79 {
"enablePreExclusion", {JSON::value_t::array, 3,
false,
false}},
80 {
"enablePostExclusion", {JSON::value_t::array, 3,
false,
false}},
81 {
"enableUnderflowExclusionHG", {JSON::value_t::array, 2,
true,
false}},
82 {
"enableUnderflowExclusionLG", {JSON::value_t::array, 2,
true,
false}},
83 {
"enablePrePulseDetection", {JSON::value_t::boolean, 1,
false,
false}},
84 {
"enablePostPulseDetection", {JSON::value_t::boolean, 1,
false,
false}},
85 {
"enableTimingCorrection", {JSON::value_t::array, 3,
false,
false}},
86 {
"timeCorrCoeffHG", {JSON::value_t::array, 6,
true,
false}},
87 {
"timeCorrCoeffLG", {JSON::value_t::array, 6,
true,
false}},
88 {
"enableADCNLCorrection", {JSON::value_t::array, 3,
false,
false}},
89 {
"ADCNLCorrCoeffs", {JSON::value_t::array, 0,
true,
false}},
90 {
"enableNLCorrection", {JSON::value_t::array, 2,
false,
false}},
91 {
"HGNLCorrCoeffs", {JSON::value_t::array, 5,
true,
false}},
92 {
"LGNLCorrCoeffs", {JSON::value_t::array, 5,
true,
false}},
93 {
"useDelayed", {JSON::value_t::boolean, 1,
false,
false}},
94 {
"delayDeltaT", {JSON::value_t::number_float, 1,
true,
false}},
95 {
"delayDefaultPedestalShift", {JSON::value_t::number_float, 1,
true,
false}},
96 {
"fitTimeMax", {JSON::value_t::number_float, 1,
true,
false}}
117 double chiSquare = 0;
119 float delayBaselineAdjust = par[0];
123 for (
int isample = 0; isample < nSamples; isample++) {
133 double pull = (histValue - funcVal) / histError;
136 chiSquare += pull * pull;
141 for (
int isample = 0; isample < nSamples; isample++) {
143 double histError = std::max(
s_delayedFitHist->GetBinError(isample + 1), 1.0);
150 double pull = (histValue - funcVal) / histError;
153 chiSquare += pull * pull;
161 const std::string& fitFunction,
int peak2ndDerivMinSample,
162 float peak2ndDerivMinThreshHG,
float peak2ndDerivMinThreshLG) :
174 m_tmin = -deltaTSample / 2;
179 std::string histName =
"ZDCFitHist" + tag;
180 std::string histNameLGRefit =
"ZDCFitHist" + tag +
"_LGRefit";
201 (*m_msgFunc_p)(
ZDCMsg::Debug,
"ConfigFromJSON produced result: "+ resultString2);
212 std::string histName =
"ZDCFitHist" +
m_tag;
213 std::string histNameLGRefit =
"ZDCFitHist" +
m_tag +
"_LGRefit";
238 std::string delayedHGName = std::string(
m_fitHist->GetName()) +
"delayed";
239 std::string delayedLGName = std::string(
m_fitHistLGRefit->GetName()) +
"delayed";
544 std::ostringstream ostrm;
555 (*m_msgFunc_p)(
ZDCMsg::Error, (
"ZDCPulseAnalyzer::SetFitTimeMax:: invalid FitTimeMax: " + std::to_string(tmax)));
572 float deltaT0MinHG,
float deltaT0MaxHG,
573 float deltaT0MinLG,
float deltaT0MaxLG)
595 float deltaT0MinLG,
float deltaT0MaxLG)
605 float chisqDivAmpCutLG,
float chisqDivAmpScaleLG,
float chisqDivAmpOffsetLG,
float chisqDivAmpPowerLG)
619 const std::vector<double>& parsHG,
620 const std::vector<double>& parsLG)
627 std::string timeResHGName =
"TimeResFuncHG_" +
m_tag;
628 std::string timeResLGName =
"TimeResFuncLG_" +
m_tag;
630 TF1* funcHG_p =
new TF1(timeResHGName.c_str(), TF1String.c_str(), 0,
m_HGOverflowADC);
631 TF1* funcLG_p =
new TF1(timeResLGName.c_str(), TF1String.c_str(), 0,
m_LGOverflowADC);
633 if (parsHG.size() !=
static_cast<unsigned int>(funcHG_p->GetNpar()) ||
634 parsLG.size() !=
static_cast<unsigned int>(funcLG_p->GetNpar())) {
639 funcHG_p->SetParameters(&parsHG[0]);
640 funcLG_p->SetParameters(&parsLG[0]);
654 auto getXmin=[](
const TH1 * pH){
655 return pH->GetXaxis()->GetXmin();
657 auto getXmax=[](
const TH1 * pH){
658 return pH->GetXaxis()->GetXmax();
660 auto xmin= getXmin(correHistHG.get());
661 auto xmax= getXmax(correHistHG.get());
662 if (std::abs(
xmin+0.5) > 1e-3 || std::abs(
xmax - 4095.5) > 1e-3) {
663 (*m_msgFunc_p)(
ZDCMsg::Error,
"ZDCPulseAnalyzer::enableFADCCorrections:: invalid high gain correction histogram range: xmin, xmax = " +
664 std::to_string(
xmin ) +
", " + std::to_string(
xmax) );
669 xmin= getXmin(correHistLG.get());
670 xmax= getXmax(correHistLG.get());
671 if (std::abs(
xmin+0.5) > 1e-3 ||
672 std::abs(
xmax - 4095.5) > 1e-3) {
673 (*m_msgFunc_p)(
ZDCMsg::Error,
"ZDCPulseAnalyzer::enableFADCCorrections:: invalid low gain correction histogram range: xmin, xmax = " +
674 std::to_string(
xmin) +
", " + std::to_string(
xmax) );
700 std::vector<float> pulls(
m_Nsample, -100);
703 const TF1* fit_p =
static_cast<const TF1*
>(dataHist_p->GetListOfFunctions()->Last());
705 for (
size_t ibin = 0; ibin <
m_Nsample ; ibin++) {
706 float t = dataHist_p->GetBinCenter(ibin + 1);
707 float fitVal = fit_p->Eval(t);
708 float histVal = dataHist_p->GetBinContent(ibin + 1);
709 float histErr = dataHist_p->GetBinError(ibin + 1);
710 float pull = (histVal - fitVal)/histErr;
720 double amplCorrFactor = 1;
726 amplCorrFactor *= fadcCorr;
738 float invNLCorr = 1.0;
752 amplCorrFactor /= invNLCorr;
755 return amplCorrFactor;
760 float prePulseTMin = 0;
866 (*m_msgFunc_p)(
ZDCMsg::Fatal,
"ZDCPulseAnalyzer::LoadAndAnalyzeData:: Wrong LoadAndAnalyzeData called -- expecting both delayed and undelayed samples");
890 const std::vector<float>& ADCSamplesHGDelayed,
const std::vector<float>& ADCSamplesLGDelayed)
893 (*m_msgFunc_p)(
ZDCMsg::Fatal,
"ZDCPulseAnalyzer::LoadAndAnalyzeData:: Wrong LoadAndAnalyzeData called -- expecting only undelayed samples");
920 for (
size_t isample = 0; isample <
m_Nsample; isample++) {
921 float ADCHG = ADCSamplesHG[isample];
922 float ADCLG = ADCSamplesLG[isample];
963 bool doDump = (*m_msgFunc_p)(
ZDCMsg::Verbose,
"Dumping all samples before subtraction: ");
965 std::ostringstream dumpStringHG;
966 dumpStringHG <<
"HG: ";
968 dumpStringHG << std::setw(4) << val <<
" ";
976 std::ostringstream dumpStringLG;
977 dumpStringLG <<
"LG: " << std::setw(4) << std::setfill(
' ');
979 dumpStringLG << std::setw(4) << val <<
" ";
993 for (
size_t isample = 0; isample <
m_NSamplesAna; isample++) {
1168 float deriv2ndThreshHG = 0;
1169 float deriv2ndThreshLG = 0;
1190 (
float chisq,
float amp,
unsigned int fitNDoF,
float& ratio)->
bool
1194 if (amp < 1e-6)
return true;
1195 ratio = chisq /(offset + scale* (std::pow(amp/1000, power)));
1196 if (chisq/fitNDoF > 2 && ratio > cut)
return false;
1239 (
float chisq,
float amp,
unsigned int fitNDoF,
float& ratio)->
bool
1243 if (amp < 1e-6)
return true;
1244 ratio = chisq /(offset + scale*(std::pow(amp/1000, power)));
1245 if (chisq/
float(fitNDoF) > 2 && ratio > cut)
return false;
1298 const std::vector<float>& samples,
1299 const std::vector<float>& samplesNoise,
1300 const std::vector<bool>& useSample,
1301 float peak2ndDerivMinThresh,
1302 const std::vector<float>& t0CorrParams,
1304 float minT0Corr,
float maxT0Corr
1317 bool haveFirst =
false;
1318 unsigned int lastUsed = 0;
1320 for (
unsigned int sample = preSampleIdx; sample < nSamples; sample++) {
1321 if (useSample[sample]) {
1377 std::ostringstream baselineMsg;
1378 baselineMsg <<
"Delayed samples baseline correction = " <<
m_baselineCorr << std::endl;
1384 for (
size_t isample = 0; isample < nSamples; isample++) {
1430 if ((deltaLeft2 > 0 || deltaLeft > 0) && (deltaRight2 > 0 || deltaRight > 0)) {
1447 if ((deltaLeft2 > 0 || deltaLeft > 0) && (deltaRight2 > 0 || deltaRight > 0)) {
1499 if (derivPresampleSig < -5) {
1505 if (!useSample[isample])
continue;
1524 float maxPrepulseSig = 0;
1525 unsigned int maxPrepulseSample = 0;
1527 for (
int isample = loopStart; isample <= loopLimit; isample++) {
1528 if (!useSample[isample])
continue;
1542 if (prePulseSig > maxPrepulseSig) {
1543 maxPrepulseSig = prePulseSig;
1544 maxPrepulseSample = isample;
1575 if (!useSample[isample] || !useSample[isample +1])
continue;
1593 std::ostringstream
msg;
1594 msg <<
"ZDCPulseAnalyzer for " <<
m_tag <<
" Found a post pulse at sample " << isample
1595 <<
" deriv = " << deriv <<
", derivErr = " << derivErr
1596 <<
" deriv2nd = " << deriv2nd <<
", deriv2ndErr = " << deriv2nd;
1620 std::ostringstream ostrm;
1637 float correction = 0;
1639 for (
unsigned int ipow = 0; ipow < t0CorrParams.size(); ipow++) {
1640 correction += t0CorrParams[ipow]*std::pow(t0CorrFact,
double(ipow));
1658 double timeResolution = 0;
1670 if (failFixedCut)
m_badT0 =
true;
1690 const std::vector<bool>& useSamples)
1699 for (
unsigned int idx = 0; idx < samplesLG.size(); idx++) {
1702 if (useSamples[idx]) {
1716 TH1* hist_p =
nullptr;
1721 float ampInitial, fitAmpMin, fitAmpMax, t0Initial;
1742 if (ampInitial < fitAmpMin) ampInitial = fitAmpMin * 1.5;
1764 fitWrapper->
Initialize(ampInitial, t0Initial, fitAmpMin, fitAmpMax);
1783 int fitStatus = result_ptr;
1789 if (fitStatus != 0 && result_ptr->Edm() > 0.001)
1799 if ((
int) constrFitResult_ptr != 0) {
1809 if ((
int) unconstrFitResult_ptr != 0) {
1816 if ((
int) constrFit2Result_ptr != 0) {
1823 result_ptr = constrFit2Result_ptr;
1827 result_ptr = unconstrFitResult_ptr;
1837 hist_p->GetListOfFunctions()->Clear();
1840 std::string name = func->GetName();
1842 TF1* copyFunc =
static_cast<TF1*
>(func->Clone((name +
"_copy").c_str()));
1843 hist_p->GetListOfFunctions()->Add(copyFunc);
1886 for (
size_t ipar = 0; ipar < numPars; ipar++) {
1905 TH1* hist_p =
nullptr, *delayedHist_p =
nullptr;
1917 float fitAmpMin, fitAmpMax, t0Initial, ampInitial;
1933 if (ampInitial < fitAmpMin) ampInitial = fitAmpMin * 1.5;
1959 fitWrapper->
Initialize(ampInitial, t0Initial, fitAmpMin, fitAmpMax);
1964 TFitter* theFitter =
nullptr;
1988 size_t numFitPar = theFitter->GetNumberTotalParameters();
1990 theFitter->GetMinuit()->fISW[4] = -1;
1995 theFitter->GetMinuit()->fISW[4] = -1;
1998 theFitter->GetMinuit()->mnexcm(
"SET NOWarnings",
nullptr,0,ierr);
2000 else theFitter->GetMinuit()->fISW[4] = 0;
2005 theFitter->SetParameter(0,
"delayBaselineAdjust", 0, 0.01, -100, 100);
2006 theFitter->ReleaseParameter(0);
2009 theFitter->SetParameter(0,
"delayBaselineAdjust", 0, 0.01, -100, 100);
2010 theFitter->FixParameter(0);
2014 double arglist[100];
2017 int status = theFitter->ExecuteCommand(
"MIGRAD", arglist, 2);
2019 double fitAmp = theFitter->GetParameter(1);
2023 double chi2, edm, errdef;
2026 theFitter->GetStats(
chi2, edm, errdef, nvpar, nparx);
2031 if (status || fitAmp < fitAmpMin * 1.01 || edm > 0.01){
2036 theFitter->SetParameter(0,
"delayBaselineAdjust", 0, 0.01, -100, 100);
2037 theFitter->FixParameter(0);
2041 if (fitAmp < fitAmpMin * 1.01) {
2047 fitWrapper->
Initialize(ampInitial, t0Initial, fitAmpMin, fitAmpMax);
2051 status = theFitter->ExecuteCommand(
"MIGRAD", arglist, 2);
2056 theFitter->ReleaseParameter(0);
2064 theFitter->ReleaseParameter(0);
2065 status = theFitter->ExecuteCommand(
"MIGRAD", arglist, 2);
2070 theFitter->SetParameter(0,
"delayBaselineAdjust", 0, 0.01, -100, 100);
2071 theFitter->FixParameter(0);
2072 status = theFitter->ExecuteCommand(
"MIGRAD", arglist, 2);
2080 fitAmp = theFitter->GetParameter(1);
2084 if (fitAmp < fitAmpMin * 1.01) {
2095 if (!
m_quietFits) theFitter->GetMinuit()->fISW[4] = -1;
2097 std::vector<double> funcParams(numFitPar - 1);
2098 std::vector<double> funcParamErrs(numFitPar - 1);
2106 for (
size_t ipar = 1; ipar < numFitPar; ipar++) {
2107 funcParams[ipar - 1] = theFitter->GetParameter(ipar);
2108 funcParamErrs[ipar - 1] = theFitter->GetParError(ipar);
2116 theFitter->GetStats(
chi2, edm, errdef, nvpar, nparx);
2136 theFitter->ExecuteCommand(
"Cal1fcn", arglist, 1);
2169 for (
size_t ipar = 0; ipar < numPars; ipar++) {
2187 for (
int ipar = 0; ipar < func->GetNpar(); ipar++) {
2188 double parLimitLow, parLimitHigh;
2190 func->GetParLimits(ipar, parLimitLow, parLimitHigh);
2193 "ZDCPulseAnalyzer name=" + std::string(func->GetName())
2194 +
" ipar=" + std::to_string(ipar)
2195 +
" parLimitLow=" + std::to_string(parLimitLow)
2196 +
" parLimitHigh="+ std::to_string(parLimitHigh)
2200 if (std::abs(parLimitHigh - parLimitLow) > (1e-6)*std::abs(parLimitLow)) {
2201 double value = func->GetParameter(ipar);
2202 if (value >= parLimitHigh) {
2203 value = parLimitHigh * 0.9;
2205 else if (value <= parLimitLow) {
2206 value = parLimitLow + 0.1*std::abs(parLimitLow);
2208 func->SetParameter(ipar, value);
2215 TVirtualFitter::SetDefaultFitter(
"Minuit");
2217 size_t nFitParams = func->GetNpar() + 1;
2218 std::unique_ptr<TFitter> fitter = std::make_unique<TFitter>(nFitParams);
2220 fitter->GetMinuit()->fISW[4] = -1;
2221 fitter->SetParameter(0,
"delayBaselineAdjust", 0, 0.01, -100, 100);
2223 for (
size_t ipar = 0; ipar < nFitParams - 1; ipar++) {
2224 double parLimitLow, parLimitHigh;
2226 func->GetParLimits(ipar, parLimitLow, parLimitHigh);
2227 if (std::abs(parLimitHigh - parLimitLow) < (1e-6)*std::abs(parLimitLow)) {
2228 double value = func->GetParameter(ipar);
2229 double lowLim = std::min(value * 0.99, value * 1.01);
2230 double highLim = std::max(value * 0.99, value * 1.01);
2232 fitter->SetParameter(ipar + 1, func->GetParName(ipar), func->GetParameter(ipar), 0.01, lowLim, highLim);
2233 fitter->FixParameter(ipar + 1);
2236 double value = func->GetParameter(ipar);
2237 if (value >= parLimitHigh) value = parLimitHigh * 0.99;
2238 else if (value <= parLimitLow) value = parLimitLow * 1.01;
2240 double step = std::min((parLimitHigh - parLimitLow)/100., (value - parLimitLow)/100.);
2242 fitter->SetParameter(ipar + 1, func->GetParName(ipar), value, step, parLimitLow, parLimitHigh);
2253 double parLimitLow, parLimitHigh;
2256 func_p->GetParLimits(1, parLimitLow, parLimitHigh);
2258 fitter->SetParameter(2, func_p->GetParName(1), func_p->GetParameter(1), 0.01, parLimitLow, parLimitHigh);
2263 func_p->GetParLimits(parIndex, parLimitLow, parLimitHigh);
2264 fitter->SetParameter(parIndex + 1, func_p->GetParName(parIndex), func_p->GetParameter(parIndex), 0.01, parLimitLow, parLimitHigh);
2275 (*m_msgFunc_p)(
ZDCMsg::Info, (
"using delayed samples with delta T = " + std::to_string(
m_delayedDeltaT) +
", and pedestalDiff == " +
2279 std::ostringstream message1;
2280 message1 <<
"samplesSub ";
2281 for (
size_t sample = 0; sample <
m_samplesSub.size(); sample++) {
2282 message1 <<
", [" << sample <<
"] = " <<
m_samplesSub[sample];
2286 std::ostringstream message3;
2287 message3 <<
"samplesDeriv2nd ";
2298 std::string message =
"Dump of TF1: " + std::string(func->GetName());
2299 bool continueDump = (*m_msgFunc_p)(
ZDCMsg::Verbose, std::move(message));
2300 if (!continueDump)
return;
2302 unsigned int npar = func->GetNpar();
2303 for (
unsigned int ipar = 0; ipar < npar; ipar++) {
2304 std::ostringstream msgstr;
2306 double parMin = 0, parMax = 0;
2307 func->GetParLimits(ipar, parMin, parMax);
2309 msgstr <<
"Parameter " << ipar <<
", value = " << func->GetParameter(ipar) <<
", error = "
2310 << func->GetParError(ipar) <<
", min = " << parMin <<
", max = " << parMax;
2317 std::ostringstream ostrStream;
2318 (*m_msgFunc_p)(
ZDCMsg::Info, (
"\n ZDCPulserAnalyzer:: ======================================================================="));
2319 (*m_msgFunc_p)(
ZDCMsg::Info, (
"ZDCPulserAnalyzer:: settings for instance: " +
m_tag));
2321 ostrStream <<
"Nsample = " <<
m_Nsample <<
" at frequency " <<
m_freqMHz <<
" MHz, preSample index = "
2324 (*m_msgFunc_p)(
ZDCMsg::Info, ostrStream.str()); ostrStream.str(
""); ostrStream.clear();
2327 (*m_msgFunc_p)(
ZDCMsg::Info, ostrStream.str()); ostrStream.str(
""); ostrStream.clear();
2330 ostrStream <<
"Using per-sample noise sigmas for high gain, values = ";
2332 ostrStream <<
"end";
2333 (*m_msgFunc_p)(
ZDCMsg::Info, ostrStream.str()); ostrStream.str(
""); ostrStream.clear();
2337 ostrStream <<
"Using per-sample noise sigmas for low gain, values = ";
2339 ostrStream <<
"end";
2340 (*m_msgFunc_p)(
ZDCMsg::Info, ostrStream.str()); ostrStream.str(
""); ostrStream.clear();
2346 (*m_msgFunc_p)(
ZDCMsg::Info, ostrStream.str()); ostrStream.str(
""); ostrStream.clear();
2349 ostrStream <<
"using delayed samples with delta T = " <<
m_delayedDeltaT <<
", and default pedestalDiff == "
2351 (*m_msgFunc_p)(
ZDCMsg::Info, ostrStream.str()); ostrStream.str(
""); ostrStream.clear();
2359 (*m_msgFunc_p)(
ZDCMsg::Info, ostrStream.str()); ostrStream.str(
""); ostrStream.clear();
2363 (*m_msgFunc_p)(
ZDCMsg::Info, ostrStream.str()); ostrStream.str(
""); ostrStream.clear();
2368 (*m_msgFunc_p)(
ZDCMsg::Info, ostrStream.str()); ostrStream.str(
""); ostrStream.clear();
2372 (*m_msgFunc_p)(
ZDCMsg::Info, ostrStream.str()); ostrStream.str(
""); ostrStream.clear();
2376 (*m_msgFunc_p)(
ZDCMsg::Info,
"Pre-pulse and negative exponential pulse checking disabled");
2379 (*m_msgFunc_p)(
ZDCMsg::Info,
"Post-pulse checking disabled");
2383 ostrStream <<
"Pre-exclusion enabled for up to " <<
m_maxSamplesPreExcl <<
", samples with ADC threshold HG = "
2385 (*m_msgFunc_p)(
ZDCMsg::Info, ostrStream.str()); ostrStream.str(
""); ostrStream.clear();
2388 ostrStream <<
"Post-exclusion enabled for up to " <<
m_maxSamplesPostExcl <<
", samples with ADC threshold HG = "
2390 (*m_msgFunc_p)(
ZDCMsg::Info, ostrStream.str()); ostrStream.str(
""); ostrStream.clear();
2396 (*m_msgFunc_p)(
ZDCMsg::Info, ostrStream.str()); ostrStream.str(
""); ostrStream.clear();
2401 (*m_msgFunc_p)(
ZDCMsg::Info, ostrStream.str()); ostrStream.str(
""); ostrStream.clear();
2404 ostrStream <<
"Minimum significance cuts applied: HG min. sig. = " <<
m_sigMinHG <<
", LG min. sig. " <<
m_sigMinLG;
2405 (*m_msgFunc_p)(
ZDCMsg::Info, ostrStream.str()); ostrStream.str(
""); ostrStream.clear();
2412 unsigned int statusMask = 0;
2449 TH1* hist_p =
nullptr, *delayedHist_p =
nullptr;
2459 std::shared_ptr<TGraphErrors> theGraph = std::make_shared<TGraphErrors>(TGraphErrors(2 *
m_Nsample));
2462 for (
int ipt = 0; ipt < hist_p->GetNbinsX(); ipt++) {
2463 theGraph->SetPoint(npts, hist_p->GetBinCenter(ipt + 1), hist_p->GetBinContent(ipt + 1));
2464 theGraph->SetPointError(npts++, 0, hist_p->GetBinError(ipt + 1));
2467 for (
int iDelayPt = 0; iDelayPt < delayedHist_p->GetNbinsX(); iDelayPt++) {
2468 theGraph->SetPoint(npts, delayedHist_p->GetBinCenter(iDelayPt + 1), delayedHist_p->GetBinContent(iDelayPt + 1) -
m_delayedBaselineShift);
2469 theGraph->SetPointError(npts++, 0, delayedHist_p->GetBinError(iDelayPt + 1));
2472 TF1* func_p =
static_cast<TF1*
>(hist_p->GetListOfFunctions()->Last());
2474 theGraph->GetListOfFunctions()->Add(
new TF1(*func_p));
2475 hist_p->GetListOfFunctions()->SetOwner (
false);
2478 theGraph->SetName(( std::string(hist_p->GetName()) +
"combinaed").c_str());
2480 theGraph->SetMarkerStyle(20);
2481 theGraph->SetMarkerColor(1);
2494 std::shared_ptr<TGraphErrors> theGraph = std::make_shared<TGraphErrors>(TGraphErrors(
m_Nsample));
2497 for (
int ipt = 0; ipt < hist_p->GetNbinsX(); ipt++) {
2498 theGraph->SetPoint(npts, hist_p->GetBinCenter(ipt + 1), hist_p->GetBinContent(ipt + 1));
2499 theGraph->SetPointError(npts++, 0, hist_p->GetBinError(ipt + 1));
2502 TF1* func_p =
static_cast<TF1*
>(hist_p->GetListOfFunctions()->Last());
2503 theGraph->GetListOfFunctions()->Add(func_p);
2504 theGraph->SetName(( std::string(hist_p->GetName()) +
"not_combinaed").c_str());
2506 theGraph->SetMarkerStyle(20);
2507 theGraph->SetMarkerColor(1);
2515 unsigned int nSamples = inputData.size();
2519 unsigned int vecSize = 2*(step - 1) + nSamples - step - 1;
2520 std::vector<float> results(vecSize, 0);
2524 unsigned int fillIdx = step - 1;
2526 for (
unsigned int sample = 0; sample < nSamples - step; sample++) {
2527 int deriv = inputData[sample + step] - inputData[sample];
2528 results.at(fillIdx++) = deriv;
2536 unsigned int nSamples = inputData.size();
2541 unsigned int vecSize = 2*step + nSamples - step - 1;
2542 std::vector<float> results(vecSize, 0);
2544 unsigned int fillIndex = step;
2545 for (
unsigned int sample = step; sample < nSamples - step; sample++) {
2546 auto deriv2nd = inputData[sample + step] + inputData[sample - step] - 2*inputData[sample];
2547 results.at(fillIndex++) = deriv2nd;
2553std::pair<std::vector<float>, std::vector<float>>
2556 unsigned int nSamples = inputData.size();
2561 unsigned int vecSize = 2*step + nSamples - step - 1;
2562 std::vector<float> results(vecSize, 0);
2563 std::vector<float> resultsErr(vecSize, 0);
2565 unsigned int fillIndex = step;
2566 for (
unsigned int sample = step; sample < nSamples - step; sample++) {
2567 float deriv2nd = inputData[sample + step] + inputData[sample - step] - 2*inputData[sample];
2568 float deriv2ndErr = std::sqrt(
Sqr(inputNoise[sample + step]) +
Sqr(inputNoise[sample - step]) + 2*
Sqr(inputNoise[sample]));
2570 results[fillIndex] = deriv2nd;
2571 resultsErr[fillIndex++] = deriv2ndErr;
2574 return {results, resultsErr};
2592 const unsigned int nsamples = samples.size();
2600 float minScore = 1.0e9;
2601 unsigned int minIndex = 0;
2603 for (
unsigned int idx = 2; idx < nsamples - 1; idx++) {
2604 float deriv = derivVec[idx];
2605 float prevDeriv = derivVec[idx - 1];
2607 float derivDiff = deriv - prevDeriv;
2609 float deriv2nd = deriv2ndVec[idx];
2610 if (idx > nsamples - 2) deriv2nd = deriv2ndVec[idx - 1];
2615 float score = (deriv*deriv + 2*derivDiff*derivDiff +
2616 0.5*deriv2nd*deriv2nd);
2618 if (score < minScore) {
2629 if (minIndex<2 or (minIndex+1) >=nsamples){
2630 throw std::out_of_range(
"minIndex out of range in ZDCPulseAnalyzer::obtainDelayedBaselineCorr");
2632 float sample0 = samples[minIndex - 2];
2633 float sample1 = samples[minIndex - 1];
2634 float sample2 = samples[minIndex];
2635 float sample3 = samples[minIndex + 1];
2639 float baselineCorr = (0.5 * (sample1 - sample0 + sample3 - sample2) -
2640 0.25 * (sample3 - sample1 + sample2 - sample0));
2642 if (minIndex % 2 != 0) baselineCorr =-baselineCorr;
2644 return baselineCorr;
2650 std::string resultString =
"success";
2653 auto iter = config.find(key);
2654 if (iter != config.end()) {
2658 auto jsonType = iter.value().type();
2659 auto paramType = std::get<0>(descr);
2660 if (jsonType != paramType) {
2662 resultString =
"Bad type for parameter " + key +
", type in JSON = " + std::to_string((
unsigned int) jsonType) ;
2666 size_t paramSize = std::get<1>(descr);
2667 size_t jsonSize = iter.value().size();
2668 if (jsonSize != paramSize) {
2670 resultString =
"Bad length for parameter " + key +
", length in JSON = " + std::to_string(jsonSize) ;
2675 bool required = std::get<2>(descr);
2678 resultString =
"Missing required parameter " + key;
2688 for (
auto [key, value] : config.items()) {
2697 resultString =
"Unknown parameter, key = " + key;
2703 return {result, resultString};
2709 std::string resultString =
"success";
2711 for (
auto [key, value] : config.items()) {
2715 if (key ==
"Nsample")
m_Nsample = value;
2716 else if (key ==
"tag")
m_tag = value;
2717 else if (key ==
"LGMode")
m_LGMode = value;
2718 else if (key ==
"Nsample")
m_Nsample = value;
2721 else if (key ==
"FADCFreqMHz")
m_freqMHz = value;
2722 else if (key ==
"nominalPedestal")
m_pedestal = value;
2736 else if (key ==
"fixTau1")
m_fixTau1 = value;
2737 else if (key ==
"fixTau2")
m_fixTau2 = value;
2738 else if (key ==
"T0CutsHG") {
2742 else if (key ==
"T0CutsLG") {
2759 else if (key ==
"perSampleNoiseSigmaHG") {
2763 else if (key ==
"perSampleNoiseSigmaLG") {
2772 else if (key ==
"fitTimeMax") {
2778 else if (key ==
"fitAmpMinMaxHG") {
2782 else if (key ==
"fitAmpMinMaxLG") {
2786 else if (key ==
"quietFits") {
2789 else if (key ==
"enablePreExclusion") {
2795 else if (key ==
"enablePostExclusion") {
2801 else if (key ==
"enableUnderflowExclusionHG") {
2806 else if (key ==
"enableUnderflowExclusionLG") {
2811 else if (key ==
"enablePrePulseDetection") {
2814 else if (key ==
"enablePostPulseDetection") {
2817 else if (key ==
"ampMinSignifHGLG") {
2822 else if (key ==
"enableFADCCorrections") {
2823 auto fileNameJson = value[
"filename"];
2824 auto doPerSampleCorrJson = value[
"doPerSampleCorr"];
2826 if (fileNameJson.is_null() || doPerSampleCorrJson.is_null()) {
2828 resultString =
"failure processing enableFADCCorrections object";
2836 else if(key ==
"useDelayed"){
2843 else if (key ==
"enableTimingCorrection") {
2848 else if(key ==
"timeCorrCoeffHG"){
2849 for(
int i = 0;
auto coeff:value){
2854 else if(key ==
"timeCorrCoeffLG"){
2855 for(
int i = 0;
auto coeff:value){
2860 else if(key ==
"enableNLCorrection"){
2869 else if(key ==
"HGNLCorrCoeffs"){
2870 std::string HGParamsStr =
"HG coefficients = ";
2871 for (
auto coeff : value) {
2877 else if(key ==
"LGNLCorrCoeffs"){
2878 std::string LGParamsStr =
"LG coefficients = ";
2879 for(
auto coeff:value){
2887 resultString =
"unprocessed parameter";
2892 return {result, resultString};
virtual float GetTau1() const =0
void Initialize(float initialAmp, float initialT0, float ampMin, float ampMax)
virtual float GetBkgdMaxFraction() const =0
virtual void ConstrainFit()=0
virtual TF1 * GetWrapperTF1RawPtr() const
virtual std::shared_ptr< TF1 > GetWrapperTF1()
virtual float GetAmpError() const =0
virtual void UnconstrainFit()=0
virtual float GetTime() const =0
virtual float GetShapeParameter(size_t index) const =0
virtual float GetTau2() const =0
virtual float GetAmplitude() const =0
virtual unsigned int GetNumShapeParameters() const =0
std::map< std::string, JSONParamDescr > JSONParamList
std::vector< bool > m_useSampleHG
std::shared_ptr< TGraphErrors > GetCombinedGraph(bool forceLG=false)
static TF1 * s_combinedFitFunc
float m_initialPrePulseAmp
std::unique_ptr< const TF1 > m_timeResFuncHG_p
void dumpTF1(const TF1 *) const
float m_chisqDivAmpScaleHG
float m_chisqDivAmpOffsetLG
std::unique_ptr< TFitter > m_prePulseCombinedFitter
bool underflowExclusion() const
float m_initialPostPulseT0
unsigned int m_timeCutMode
std::unique_ptr< const TH1 > m_FADCCorrLG
size_t m_peak2ndDerivMinTolerance
std::vector< float > m_fitPulls
size_t m_peak2ndDerivMinSample
std::vector< float > m_setPerSampleNoiseHG
bool ScanAndSubtractSamples()
void dumpConfiguration() const
std::vector< float > m_nonLinCorrParamsLG
bool excludeEarlyLG() const
float m_peak2ndDerivMinThreshHG
bool m_havePerSampleNoiseLG
std::vector< float > m_samplesNoiseLGRefit
static std::vector< float > s_pullValues
std::unique_ptr< const TF1 > m_timeResFuncLG_p
static TH1 * s_undelayedFitHist
std::pair< bool, std::string > ConfigFromJSON(const JSON &config)
static std::vector< float > calculate2ndDerivative(const std::vector< float > &inputData, unsigned int step)
std::unique_ptr< ZDCFitWrapper > m_defaultFitWrapper
std::string m_fitFunction
unsigned int m_preSampleIdx
std::vector< float > m_LGT0CorrParams
std::vector< float > m_samplesLGRefit
std::vector< float > m_samplesNoise
void SetTauT0Values(bool fixTau1, bool fixTau2, float tau1, float tau2, float t0HG, float t0LG)
bool fitMinimumAmplitude() const
float m_chisqDivAmpPowerLG
const TH1 * GetHistogramPtr(bool refitLG=false)
float m_peak2ndDerivMinRepassLG
void SetGainFactorsHGLG(float gainFactorHG, float gainFactorLG)
int m_lastHGOverFlowSample
unsigned int m_preExclLGADCThresh
unsigned int m_prePulseDelta
void enablePostPulseCheck(unsigned int postPulseSampleDelta, float postPulseDerivMinSig, float postPulseAbsDer2ndMinSig, float minMainDer2ndRatio)
unsigned int m_postExclLGADCThresh
std::vector< float > m_shapeParameters
unsigned int m_NSamplesAna
bool DoAnalysis(bool repass)
void setMinimumSignificance(float sigMinHG, float sigMinLG)
static std::unique_ptr< TFitter > MakeCombinedFitter(TF1 *func)
std::unique_ptr< TH1 > m_delayedHistLGRefit
float m_delayedBaselineShift
unsigned int m_timingCorrMode
float m_chisqDivAmpScaleLG
std::vector< float > m_sampleNoiseLG
unsigned int m_maxSampleEvt
int m_firstHGOverFlowSample
unsigned int m_maxSamplesPreExcl
std::vector< float > m_setPerSampleNoiseLG
std::vector< float > m_ADCSamplesLG
unsigned int m_underFlowExclSamplesPreLG
float m_postPulseMainMinDer2ndRatio
static float s_combinedFitTMin
std::vector< float > m_nonLinCorrParamsHG
ZDCPulseAnalyzer(ZDCMsg::MessageFunctionPtr msgFunc_p, const std::string &tag, int Nsample, float deltaTSample, size_t preSampleIdx, int pedestal, const std::string &fitFunction, int peak2ndDerivMinSample, float peak2DerivMinThreshHG, float peak2DerivMinThreshLG)
unsigned int m_underFlowExclSamplesPostHG
unsigned int m_maxSamplesPostExcl
void SetADCOverUnderflowValues(int HGOverflowADC, int HGUnderflowADC, int LGOverflowADC)
float m_chisqDivAmpPowerHG
std::vector< float > m_ADCSamplesHGSub
std::unique_ptr< ZDCPrePulseFitWrapper > m_prePulseFitWrapper
void UpdateFitterTimeLimits(TFitter *fitter, ZDCFitWrapper *wrapper, bool prePulse)
static float obtainDelayedBaselineCorr(const std::vector< float > &samples)
void prepareLGRefit(const std::vector< float > &samplesLG, const std::vector< float > &samplesNoise, const std::vector< bool > &useSamples)
double getAmplitudeCorrection(bool highGain)
float m_peak2ndDerivMinRepassHG
unsigned int m_underFlowExclSamplesPreHG
float m_peak2ndDerivMinThreshLG
float m_postPulseAbsDer2ndMinSig
void enableRepass(float peak2ndDerivMinRepassHG, float peak2ndDerivMinRepassLG)
void enableDelayed(float deltaT, float pedestalShift, bool fixedBaseline=false)
void DoFit(bool refitLG=false)
std::vector< float > m_ADCSamplesLGSub
bool m_enableUnderflowExclHG
float m_delayedPedestalDiff
std::vector< float > m_samplesSub
void SetFitTimeMax(float tmax)
static float s_combinedFitTMax
std::vector< bool > m_useSampleLG
void reset(bool reanalyze=false)
unsigned int m_underFlowExclSamplesPostLG
unsigned int m_postPulseDelta
std::vector< float > m_ADCSamplesHG
void checkTF1Limits(TF1 *func)
bool AnalyzeData(size_t nSamples, size_t preSample, const std::vector< float > &samples, const std::vector< float > &samplesNoise, const std::vector< bool > &useSamples, float peak2ndDerivMinThresh, const std::vector< float > &toCorrParams, ChisqCutLambdatype chisqCutLambda, float minT0Corr, float maxT0Corr)
void SetTimeCuts(float deltaT0MinHG, float deltaT0MaxHG, float deltaT0MinLG, float deltaT0MaxLG)
bool m_underflowExclusion
std::vector< float > m_sampleNoiseHG
std::vector< float > GetFitPulls(bool forceLG=false) const
bool armSumInclude() const
void SetCutValues(float chisqDivAmpCutHG, float chisqDivAmpCutLG, float deltaT0MinHG, float deltaT0MaxHG, float deltaT0MinLG, float deltaT0MaxLG)
std::vector< float > m_HGT0CorrParams
void SetChisqCuts(float chisqDivAmpCutHG, float chisqDivAmpScaleHG, float chisqDivAmpOffsetHG, float chisqDivAmpPowerHG, float chisqDivAmpCutLG, float chisqDivAmpScaleLG, float chisqDivAmpOffsetLG, float chisqDivAmpPowerLG)
std::unique_ptr< TH1 > m_fitHistLGRefit
std::unique_ptr< TH1 > m_delayedHist
std::shared_ptr< TGraphErrors > GetGraph(bool forceLG=false)
unsigned int m_preExclHGADCThresh
static TH1 * s_delayedFitHist
std::unique_ptr< TH1 > m_fitHist
std::unique_ptr< TFitter > m_defaultCombinedFitter
unsigned int m_minSampleEvt
std::vector< float > m_ADCSSampNoiseLG
bool PSHGOverUnderflow() const
unsigned int GetStatusMask() const
float m_nonLinCorrRefScale
bool LoadAndAnalyzeData(const std::vector< float > &ADCSamplesHG, const std::vector< float > &ADCSamplesLG)
void enableTimeSigCut(bool AND, float sigCut, const std::string &TF1String, const std::vector< double > &parsHG, const std::vector< double > &parsLG)
static void CombinedPulsesFCN(int &numParam, double *, double &f, double *par, int flag)
bool m_havePerSampleNoiseHG
bool m_enableUnderflowExclLG
unsigned int m_postExclHGADCThresh
bool m_haveFADCCorrections
void SetFitMinMaxAmp(float minAmpHG, float minAmpLG, float maxAmpHG, float maxAmpLG)
static std::vector< float > calculateDerivative(const std::vector< float > &inputData, unsigned int step)
float m_chisqDivAmpOffsetHG
std::unique_ptr< const TH1 > m_FADCCorrHG
std::vector< float > m_samplesDeriv2ndErr
std::unique_ptr< ZDCPreExpFitWrapper > m_preExpFitWrapper
float m_postPulseDerivMinSig
ZDCMsg::MessageFunctionPtr m_msgFunc_p
void FillHistogram(bool refitLG)
std::vector< float >::const_iterator SampleCIter
std::vector< float > m_ADCSSampNoiseHG
float m_initialPrePulseT0
static const ZDCJSONConfig::JSONParamList JSONConfigParams
std::vector< float > m_samplesDeriv2nd
std::pair< bool, std::string > ValidateJSONConfig(const JSON &config)
void DoFitCombined(bool refitLG=false)
std::string m_fadcCorrFileName
bool excludeLateLG() const
std::function< bool(float, float, float, float &)> ChisqCutLambdatype
void enableFADCCorrections(bool correctPerSample, std::unique_ptr< const TH1 > &correHistHG, std::unique_ptr< const TH1 > &correHistLG)
double chi2(TH1 *h0, TH1 *h1)
std::shared_ptr< MessageFunction > MessageFunctionPtr
Tell the compiler to optimize assuming that FP may trap.
#define CXXUTILS_TRAPPING_FP