Page MenuHomeHEPForge

No OneTemporary

This file is larger than 256 KB, so syntax highlighting was skipped.
diff --git a/src/FCN/JointFCN.cxx b/src/FCN/JointFCN.cxx
index 64d00b6..6ce228b 100755
--- a/src/FCN/JointFCN.cxx
+++ b/src/FCN/JointFCN.cxx
@@ -1,1123 +1,1123 @@
#include "JointFCN.h"
#include "FitUtils.h"
#include <stdio.h>
//***************************************************
JointFCN::JointFCN(TFile *outfile) {
//***************************************************
fOutputDir = gDirectory;
if (outfile)
Config::Get().out = outfile;
std::vector<nuiskey> samplekeys = Config::QueryKeys("sample");
LoadSamples(samplekeys);
std::vector<nuiskey> covarkeys = Config::QueryKeys("covar");
LoadPulls(covarkeys);
fCurIter = 0;
fMCFilled = false;
fIterationTree = false;
fDialVals = NULL;
fNDials = 0;
fUsingEventManager = FitPar::Config().GetParB("EventManager");
fOutputDir->cd();
}
//***************************************************
JointFCN::JointFCN(std::vector<nuiskey> samplekeys, TFile *outfile) {
//***************************************************
fOutputDir = gDirectory;
if (outfile)
Config::Get().out = outfile;
LoadSamples(samplekeys);
fCurIter = 0;
fMCFilled = false;
fOutputDir->cd();
fIterationTree = false;
fDialVals = NULL;
fNDials = 0;
fUsingEventManager = FitPar::Config().GetParB("EventManager");
fOutputDir->cd();
}
//***************************************************
JointFCN::~JointFCN() {
//***************************************************
// Delete Samples
for (MeasListConstIter iter = fSamples.begin(); iter != fSamples.end();
iter++) {
MeasurementBase *exp = *iter;
delete exp;
}
for (PullListConstIter iter = fPulls.begin(); iter != fPulls.end(); iter++) {
ParamPull *pull = *iter;
delete pull;
}
// Sort Tree
if (fIterationTree)
DestroyIterationTree();
if (fDialVals)
delete fDialVals;
if (fSampleLikes)
delete fSampleLikes;
};
//***************************************************
void JointFCN::CreateIterationTree(std::string name, FitWeight *rw) {
//***************************************************
NUIS_LOG(FIT, " Creating new iteration container! ");
DestroyIterationTree();
fIterationTreeName = name;
// Add sample likelihoods and ndof
for (MeasListConstIter iter = fSamples.begin(); iter != fSamples.end();
iter++) {
MeasurementBase *exp = *iter;
std::string name = exp->GetName();
std::string liketag = name + "_likelihood";
fNameValues.push_back(liketag);
fCurrentValues.push_back(0.0);
std::string ndoftag = name + "_ndof";
fNameValues.push_back(ndoftag);
fCurrentValues.push_back(0.0);
}
// Add Pull terms
for (PullListConstIter iter = fPulls.begin(); iter != fPulls.end(); iter++) {
ParamPull *pull = *iter;
std::string name = pull->GetName();
std::string liketag = name + "_likelihood";
fNameValues.push_back(liketag);
fCurrentValues.push_back(0.0);
std::string ndoftag = name + "_ndof";
fNameValues.push_back(ndoftag);
fCurrentValues.push_back(0.0);
}
// Add Likelihoods
fNameValues.push_back("total_likelihood");
fCurrentValues.push_back(0.0);
fNameValues.push_back("total_ndof");
fCurrentValues.push_back(0.0);
// Setup Containers
fSampleN = fSamples.size() + fPulls.size();
fSampleLikes = new double[fSampleN];
fSampleNDOF = new int[fSampleN];
// Add Dials
std::vector<std::string> dials = rw->GetDialNames();
for (size_t i = 0; i < dials.size(); i++) {
fNameValues.push_back(dials[i]);
fCurrentValues.push_back(0.0);
}
fNDials = dials.size();
fDialVals = new double[fNDials];
// Set IterationTree Flag
fIterationTree = true;
}
//***************************************************
void JointFCN::DestroyIterationTree() {
//***************************************************
fIterationCount.clear();
fCurrentValues.clear();
fNameValues.clear();
fIterationValues.clear();
}
//***************************************************
void JointFCN::WriteIterationTree() {
//***************************************************
NUIS_LOG(FIT, "Writing iteration tree");
// Make a new TTree
TTree *itree =
new TTree(fIterationTreeName.c_str(), fIterationTreeName.c_str());
double *vals = new double[fNameValues.size()];
int count = 0;
itree->Branch("iteration", &count, "Iteration/I");
for (size_t i = 0; i < fNameValues.size(); i++) {
itree->Branch(fNameValues[i].c_str(), &vals[i],
(fNameValues[i] + "/D").c_str());
}
// Fill Iterations
for (size_t i = 0; i < fIterationValues.size(); i++) {
std::vector<double> itervals = fIterationValues[i];
// Fill iteration state
count = fIterationCount[i];
for (size_t j = 0; j < itervals.size(); j++) {
vals[j] = itervals[j];
}
// Save to TTree
itree->Fill();
}
// Write to file
itree->Write();
}
//***************************************************
void JointFCN::FillIterationTree(FitWeight *rw) {
//***************************************************
// Loop over samples count
int count = 0;
for (int i = 0; i < fSampleN; i++) {
fCurrentValues[count++] = fSampleLikes[i];
fCurrentValues[count++] = double(fSampleNDOF[i]);
}
// Fill Totals
fCurrentValues[count++] = fLikelihood;
fCurrentValues[count++] = double(fNDOF);
// Loop Over Parameter Counts
rw->GetAllDials(fDialVals, fNDials);
for (int i = 0; i < fNDials; i++) {
fCurrentValues[count++] = double(fDialVals[i]);
}
// Push Back Into Container
fIterationCount.push_back(fCurIter);
fIterationValues.push_back(fCurrentValues);
}
//***************************************************
double JointFCN::DoEval(const double *x) {
//***************************************************
// WEIGHT ENGINE
fDialChanged = FitBase::GetRW()->HasRWDialChanged(x);
FitBase::GetRW()->UpdateWeightEngine(x);
if (fDialChanged) {
FitBase::GetRW()->Reconfigure();
FitBase::EvtManager().ResetWeightFlags();
}
if (LOG_LEVEL(REC)) {
FitBase::GetRW()->Print();
}
// SORT SAMPLES
ReconfigureSamples();
// GET TEST STAT
fLikelihood = GetLikelihood();
fNDOF = GetNDOF();
// PRINT PROGRESS
NUIS_LOG(FIT, "Current Stat (iter. " << this->fCurIter << ") = " << fLikelihood);
// UPDATE TREE
if (fIterationTree)
FillIterationTree(FitBase::GetRW());
return fLikelihood;
}
//***************************************************
int JointFCN::GetNDOF() {
//***************************************************
int totaldof = 0;
int count = 0;
// Total number of Free bins in each MC prediction
for (MeasListConstIter iter = fSamples.begin(); iter != fSamples.end();
iter++) {
MeasurementBase *exp = *iter;
int dof = exp->GetNDOF();
// Save Seperate DOF
if (fIterationTree) {
fSampleNDOF[count] = dof;
}
// Add to total
totaldof += dof;
count++;
}
// Loop over pulls
for (PullListConstIter iter = fPulls.begin(); iter != fPulls.end(); iter++) {
ParamPull *pull = *iter;
double dof = pull->GetLikelihood();
// Save seperate DOF
if (fIterationTree) {
fSampleNDOF[count] = dof;
}
// Add to total
totaldof += dof;
count++;
}
// Set Data Variable
if (fIterationTree) {
fSampleNDOF[count] = totaldof;
}
return totaldof;
}
//***************************************************
double JointFCN::GetLikelihood() {
//***************************************************
NUIS_LOG(MIN, std::left << std::setw(43) << "Getting likelihoods..."
<< " : "
<< "-2logL");
// Loop and add up likelihoods in an uncorrelated way
double like = 0.0;
int count = 0;
for (MeasListConstIter iter = fSamples.begin(); iter != fSamples.end();
iter++) {
MeasurementBase *exp = *iter;
double newlike = exp->GetLikelihood();
int ndof = exp->GetNDOF();
// Save seperate likelihoods
if (fIterationTree) {
fSampleLikes[count] = newlike;
}
NUIS_LOG(MIN, "-> " << std::left << std::setw(40) << exp->GetName() << " : "
<< newlike << "/" << ndof);
// Add Weight Scaling
// like *= FitBase::GetRW()->GetSampleLikelihoodWeight(exp->GetName());
// Add to total
like += newlike;
count++;
}
// Loop over pulls
for (PullListConstIter iter = fPulls.begin(); iter != fPulls.end(); iter++) {
ParamPull *pull = *iter;
double newlike = pull->GetLikelihood();
// Save seperate likelihoods
if (fIterationTree) {
fSampleLikes[count] = newlike;
}
// Add to total
like += newlike;
count++;
}
// Set Data Variable
fLikelihood = like;
if (fIterationTree) {
fSampleLikes[count] = fLikelihood;
}
return like;
};
void JointFCN::LoadSamples(std::vector<nuiskey> samplekeys) {
NUIS_LOG(MIN, "Loading Samples : " << samplekeys.size());
for (size_t i = 0; i < samplekeys.size(); i++) {
nuiskey key = samplekeys[i];
// Get Sample Options
std::string samplename = key.GetS("name");
std::string samplefile = key.GetS("input");
std::string sampletype = key.GetS("type");
std::string fakeData = "";
NUIS_LOG(MIN, "Loading Sample : " << samplename);
fOutputDir->cd();
MeasurementBase *NewLoadedSample = SampleUtils::CreateSample(key);
if (!NewLoadedSample) {
NUIS_ERR(FTL, "Could not load sample provided: " << samplename);
NUIS_ERR(FTL, "Check spelling with that in src/FCN/SampleList.cxx");
throw;
} else {
fSamples.push_back(NewLoadedSample);
}
}
}
//***************************************************
void JointFCN::LoadPulls(std::vector<nuiskey> pullkeys) {
//***************************************************
for (size_t i = 0; i < pullkeys.size(); i++) {
nuiskey key = pullkeys[i];
std::string pullname = key.GetS("name");
std::string pullfile = key.GetS("input");
std::string pulltype = key.GetS("type");
fOutputDir->cd();
fPulls.push_back(new ParamPull(pullname, pullfile, pulltype));
}
}
//***************************************************
void JointFCN::ReconfigureSamples(bool fullconfig) {
//***************************************************
int starttime = time(NULL);
NUIS_LOG(REC, "Starting Reconfigure iter. " << this->fCurIter);
// std::cout << fUsingEventManager << " " << fullconfig << " " << fMCFilled <<
// std::endl;
// Event Manager Reconf
if (fUsingEventManager) {
if (!fullconfig && fMCFilled)
ReconfigureFastUsingManager();
else
ReconfigureUsingManager();
} else {
// Loop over all Measurement Classes
for (MeasListConstIter iter = fSamples.begin(); iter != fSamples.end();
iter++) {
MeasurementBase *exp = *iter;
// If RW Either do signal or full reconfigure.
if (fDialChanged or !fMCFilled or fullconfig) {
if (!fullconfig and fMCFilled)
exp->ReconfigureFast();
else
exp->Reconfigure();
// If RW Not needed just do normalisation
} else {
exp->Renormalise();
}
}
}
// Loop over pulls and update
for (PullListConstIter iter = fPulls.begin(); iter != fPulls.end(); iter++) {
ParamPull *pull = *iter;
pull->Reconfigure();
}
fMCFilled = true;
NUIS_LOG(MIN, "Finished Reconfigure iter. " << fCurIter << " in "
<< time(NULL) - starttime << "s");
fCurIter++;
}
//***************************************************
void JointFCN::ReconfigureSignal() {
//***************************************************
ReconfigureSamples(false);
}
//***************************************************
void JointFCN::ReconfigureAllEvents() {
//***************************************************
FitBase::GetRW()->Reconfigure();
FitBase::EvtManager().ResetWeightFlags();
ReconfigureSamples(true);
}
std::vector<InputHandlerBase *> JointFCN::GetInputList() {
std::vector<InputHandlerBase *> InputList;
fIsAllSplines = true;
MeasListConstIter iterSam = fSamples.begin();
for (; iterSam != fSamples.end(); iterSam++) {
MeasurementBase *exp = (*iterSam);
std::vector<MeasurementBase *> subsamples = exp->GetSubSamples();
for (size_t i = 0; i < subsamples.size(); i++) {
InputHandlerBase *inp = subsamples[i]->GetInput();
if (std::find(InputList.begin(), InputList.end(), inp) ==
InputList.end()) {
if (subsamples[i]->GetInput()->GetType() != kSPLINEPARAMETER)
fIsAllSplines = false;
InputList.push_back(subsamples[i]->GetInput());
}
}
}
return InputList;
}
std::vector<MeasurementBase *> JointFCN::GetSubSampleList() {
std::vector<MeasurementBase *> SampleList;
MeasListConstIter iterSam = fSamples.begin();
for (; iterSam != fSamples.end(); iterSam++) {
MeasurementBase *exp = (*iterSam);
std::vector<MeasurementBase *> subsamples = exp->GetSubSamples();
for (size_t i = 0; i < subsamples.size(); i++) {
SampleList.push_back(subsamples[i]);
}
}
return SampleList;
}
//***************************************************
void JointFCN::ReconfigureUsingManager() {
//***************************************************
// 'Slow' Event Manager Reconfigure
NUIS_LOG(REC, "Event Manager Reconfigure");
int timestart = time(NULL);
// Reset all samples
MeasListConstIter iterSam = fSamples.begin();
for (; iterSam != fSamples.end(); iterSam++) {
MeasurementBase *exp = (*iterSam);
exp->ResetAll();
}
// If we are siving signal, reset all containers.
bool savesignal = (FitPar::Config().GetParB("SignalReconfigures"));
if (savesignal) {
// Reset all of our event signal vectors
fSignalEventBoxes.clear();
fSignalEventFlags.clear();
fSampleSignalFlags.clear();
fSignalEventSplines.clear();
}
// Make sure we have a list of inputs
if (fInputList.empty()) {
fInputList = GetInputList();
fSubSampleList = GetSubSampleList();
}
// If all inputs are splines make sure the readers are told
// they need to be reconfigured.
std::vector<InputHandlerBase *>::iterator inp_iter = fInputList.begin();
if (fIsAllSplines) {
for (; inp_iter != fInputList.end(); inp_iter++) {
InputHandlerBase *curinput = (*inp_iter);
// Tell reader in each BaseEvent it needs a Reconfigure next weight calc.
BaseFitEvt *curevent = curinput->FirstBaseEvent();
if (curevent->fSplineRead) {
curevent->fSplineRead->SetNeedsReconfigure(true);
}
}
}
// MAIN INPUT LOOP ====================
int fillcount = 0;
int inputcount = 0;
inp_iter = fInputList.begin();
// Loop over each input in manager
for (; inp_iter != fInputList.end(); inp_iter++) {
InputHandlerBase *curinput = (*inp_iter);
// Get event information
FitEvent *curevent = curinput->FirstNuisanceEvent();
curinput->CreateCache();
int i = 0;
int nevents = curinput->GetNEvents();
int countwidth = nevents / 10;
// Start event loop iterating until we get a NULL pointer.
while (curevent) {
// Get Event Weight
// The reweighting weight
curevent->RWWeight = FitBase::GetRW()->CalcWeight(curevent);
// The Custom weight and reweight
curevent->Weight =
curevent->RWWeight * curevent->InputWeight * curevent->CustomWeight;
if (LOGGING(REC)) {
if (countwidth && (i % countwidth == 0)) {
NUIS_LOG(REC, curinput->GetName()
<< " : Processed " << i << " events. [M, W] = ["
<< curevent->Mode << ", " << curevent->Weight << "]");
}
}
// Setup flag for if signal found in at least one sample
bool foundsignal = false;
// Create a new signal bitset for this event
std::vector<bool> signalbitset(fSubSampleList.size());
// Create a new signal box vector for this event
std::vector<MeasurementVariableBox *> signalboxes;
// Start measurement iterator
size_t measitercount = 0;
std::vector<MeasurementBase *>::iterator meas_iter =
fSubSampleList.begin();
// Loop over all subsamples (sub in JointMeas)
for (; meas_iter != fSubSampleList.end(); meas_iter++) {
MeasurementBase *curmeas = (*meas_iter);
// Compare input pointers, to current input, skip if not.
// Pointer tells us if it matches without doing ID checks.
if (curinput != curmeas->GetInput()) {
if (savesignal) {
// Set bit to 0 as definitely not signal
signalbitset[measitercount] = 0;
}
// Count up what measurement we are on.
measitercount++;
// Skip sample as input not signal.
continue;
}
// Fill events for matching inputs.
MeasurementVariableBox *box = curmeas->FillVariableBox(curevent);
bool signal = curmeas->isSignal(curevent);
curmeas->SetSignal(signal);
curmeas->FillHistograms(curevent->Weight);
// If its Signal tally up fills
if (signal) {
fillcount++;
}
// If we are saving signal/splines fill the bitset
if (savesignal) {
signalbitset[measitercount] = signal;
}
// If signal save a clone of the event box for use later.
if (savesignal and signal) {
foundsignal = true;
signalboxes.push_back(box->CloneSignalBox());
}
// Keep track of Measurement we are on.
measitercount++;
}
// Once we've filled the measurements, if saving signal
// push back if any sample flagged this event as signal
if (savesignal) {
fSignalEventFlags.push_back(foundsignal);
}
// Save the vector of signal boxes for this event
if (savesignal && foundsignal) {
fSignalEventBoxes.push_back(signalboxes);
fSampleSignalFlags.push_back(signalbitset);
}
// If all inputs are splines we can save the spline coefficients
// for fast in memory reconfigures later.
if (fIsAllSplines && savesignal && foundsignal) {
// Make temp vector to push back with
std::vector<float> coeff;
for (size_t l = 0; l < (UInt_t)curevent->fSplineRead->GetNPar(); l++) {
coeff.push_back(curevent->fSplineCoeff[l]);
}
// Push back to signal event splines. Kept in sync with
// fSignalEventBoxes size.
// int splinecount = fSignalEventSplines.size();
fSignalEventSplines.push_back(coeff);
// if (splinecount % 1000 == 0) {
// std::cout << "Pushed Back Coeff " << splinecount << " : ";
// for (size_t l = 0; l < fSignalEventSplines[splinecount].size(); l++)
// {
// std::cout << " " << fSignalEventSplines[splinecount][l];
// }
// std::cout << std::endl;
// }
}
// Clean up vectors once done with this event
signalboxes.clear();
signalbitset.clear();
// Iterate to the next event.
curevent = curinput->NextNuisanceEvent();
i++;
}
// curinput->RemoveCache();
// Keep track of what input we are on.
inputcount++;
}
// End of Event Loop ===============================
// Now event loop is finished loop over all Measurements
// Converting Binned events to XSec Distributions
iterSam = fSamples.begin();
for (; iterSam != fSamples.end(); iterSam++) {
MeasurementBase *exp = (*iterSam);
exp->ConvertEventRates();
}
// Print out statements on approximate memory usage for profiling.
NUIS_LOG(REC, "Filled " << fillcount << " signal events.");
if (savesignal) {
int mem = ( // sizeof(fSignalEventBoxes) +
// fSignalEventBoxes.size() * sizeof(fSignalEventBoxes.at(0)) +
sizeof(MeasurementVariableBox1D) * fillcount) *
1E-6;
NUIS_LOG(REC, " -> Saved " << fillcount << " signal boxes for faster access. (~"
<< mem << " MB)");
if (fIsAllSplines and !fSignalEventSplines.empty()) {
int splmem = sizeof(float) * fSignalEventSplines.size() *
fSignalEventSplines[0].size() * 1E-6;
NUIS_LOG(REC, " -> Saved " << fillcount << " " << fSignalEventSplines.size()
<< " spline sets into memory. (~" << splmem
<< " MB)");
}
}
NUIS_LOG(REC,
"Time taken ReconfigureUsingManager() : " << time(NULL) - timestart);
// Check SignalReconfigures works for all samples
if (savesignal) {
double likefull = GetLikelihood();
ReconfigureFastUsingManager();
double likefast = GetLikelihood();
if (fabs(likefull - likefast) > 0.0001) {
NUIS_ERR(FTL, "Fast and Full Likelihoods DIFFER! : " << likefull << " : "
<< likefast);
NUIS_ERR(FTL, "This means some samples you are using are not setup to use "
"SignalReconfigures=1");
NUIS_ERR(FTL, "Please turn OFF signal reconfigures.");
throw;
} else {
NUIS_LOG(FIT,
"Likelihoods for FULL and FAST match. Will use FAST next time.");
}
}
};
//***************************************************
void JointFCN::ReconfigureFastUsingManager() {
//***************************************************
NUIS_LOG(FIT, " -> Doing FAST using manager");
// Get Start time for profilling
int timestart = time(NULL);
// Reset all samples
MeasListConstIter iterSam = fSamples.begin();
for (; iterSam != fSamples.end(); iterSam++) {
MeasurementBase *exp = (*iterSam);
exp->ResetAll();
}
// Check for saved variables if not do a full reconfigure.
if (fSignalEventFlags.empty()) {
NUIS_ERR(WRN, "Signal Flags Empty! Using normal manager.");
ReconfigureUsingManager();
return;
}
bool fFillNuisanceEvent =
FitPar::Config().GetParB("FullEventOnSignalReconfigure");
// Setup fast vector iterators.
std::vector<bool>::iterator inpsig_iter = fSignalEventFlags.begin();
- std::vector<std::vector<MeasurementVariableBox *>>::iterator box_iter =
+ std::vector<std::vector<MeasurementVariableBox *> >::iterator box_iter =
fSignalEventBoxes.begin();
- std::vector<std::vector<float>>::iterator spline_iter =
+ std::vector<std::vector<float> >::iterator spline_iter =
fSignalEventSplines.begin();
- std::vector<std::vector<bool>>::iterator samsig_iter =
+ std::vector<std::vector<bool> >::iterator samsig_iter =
fSampleSignalFlags.begin();
int splinecount = 0;
// Setup stuff for logging
int fillcount = 0;
// This is just the total number of events
// int nevents = fSignalEventFlags.size();
// This is the number of events that are signal
int nevents = fSignalEventBoxes.size();
int countwidth = nevents / 10;
// If All Splines tell splines they need a reconfigure.
std::vector<InputHandlerBase *>::iterator inp_iter = fInputList.begin();
if (fIsAllSplines) {
NUIS_LOG(REC, "All Spline Inputs so using fast spline loop.");
for (; inp_iter != fInputList.end(); inp_iter++) {
InputHandlerBase *curinput = (*inp_iter);
// Tell each fSplineRead in BaseFitEvent to reconf next weight calc
BaseFitEvt *curevent = curinput->FirstBaseEvent();
if (curevent->fSplineRead)
curevent->fSplineRead->SetNeedsReconfigure(true);
}
}
// Loop over all possible spline inputs
double *coreeventweights = new double[fSignalEventBoxes.size()];
splinecount = 0;
inp_iter = fInputList.begin();
inpsig_iter = fSignalEventFlags.begin();
spline_iter = fSignalEventSplines.begin();
// Loop over all signal flags
// For each valid signal flag add one to splinecount
// Get Splines from that count and add to weight
// Add splinecount
int sigcount = 0;
// #pragma omp parallel for shared(splinecount,sigcount)
for (uint iinput = 0; iinput < fInputList.size(); iinput++) {
InputHandlerBase *curinput = fInputList[iinput];
BaseFitEvt *curevent = curinput->FirstBaseEvent();
// Loop over the events in each input
for (int i = 0; i < curinput->GetNEvents(); i++) {
double rwweight = 0.0;
// If the event is a signal event
if (fSignalEventFlags[sigcount]) {
// Get Event Info
if (!fIsAllSplines) {
if (fFillNuisanceEvent) {
curevent = curinput->GetNuisanceEvent(i);
} else {
curevent = curinput->GetBaseEvent(i);
}
} else {
curevent->fSplineCoeff = &fSignalEventSplines[splinecount][0];
}
curevent->RWWeight = FitBase::GetRW()->CalcWeight(curevent);
curevent->Weight =
curevent->RWWeight * curevent->InputWeight * curevent->CustomWeight;
rwweight = curevent->Weight;
coreeventweights[splinecount] = rwweight;
if (countwidth && ((splinecount % countwidth) == 0)) {
NUIS_LOG(REC, curinput->GetName()
<< " : Processed " << i
<< " events. W = " << curevent->Weight << std::endl);
}
// #pragma omp atomic
splinecount++;
}
// #pragma omp atomic
sigcount++;
}
}
NUIS_LOG(SAM, "Processed event weights.");
// #pragma omp barrier
// Reset Iterators
inpsig_iter = fSignalEventFlags.begin();
spline_iter = fSignalEventSplines.begin();
box_iter = fSignalEventBoxes.begin();
samsig_iter = fSampleSignalFlags.begin();
int nsplineweights = splinecount;
splinecount = 0;
// Start of Fast Event Loop ============================
// Start input iterators
// Loop over number of inputs
for (int ispline = 0; ispline < nsplineweights; ispline++) {
double rwweight = coreeventweights[ispline];
// Get iterators for this event
std::vector<bool>::iterator subsamsig_iter = (*samsig_iter).begin();
std::vector<MeasurementVariableBox *>::iterator subbox_iter =
(*box_iter).begin();
// Loop over all sub measurements.
std::vector<MeasurementBase *>::iterator meas_iter = fSubSampleList.begin();
for (; meas_iter != fSubSampleList.end(); meas_iter++, subsamsig_iter++) {
MeasurementBase *curmeas = (*meas_iter);
// If event flagged as signal for this sample fill from the box.
if (*subsamsig_iter) {
curmeas->SetSignal(true);
curmeas->FillHistogramsFromBox((*subbox_iter), rwweight);
// Move onto next box if there is one.
subbox_iter++;
fillcount++;
}
}
if (ispline % countwidth == 0) {
NUIS_LOG(REC, "Filled " << ispline << " sample weights.");
}
// Iterate over the main signal event containers.
samsig_iter++;
box_iter++;
spline_iter++;
splinecount++;
}
// End of Fast Event Loop ===================
NUIS_LOG(SAM, "Filled sample distributions.");
// Now loop over all Measurements
// Convert Binned events
iterSam = fSamples.begin();
for (; iterSam != fSamples.end(); iterSam++) {
MeasurementBase *exp = (*iterSam);
exp->ConvertEventRates();
}
// Cleanup coreeventweights
delete coreeventweights;
// Print some reconfigure profiling.
NUIS_LOG(REC, "Filled " << fillcount << " signal events.");
NUIS_LOG(REC,
"Time taken ReconfigureFastUsingManager() : " << time(NULL) - timestart);
}
//***************************************************
void JointFCN::Write() {
//***************************************************
// Save a likelihood/ndof plot
NUIS_LOG(MIN, "Writing likelihood plot...");
std::vector<double> likes;
std::vector<double> ndofs;
std::vector<std::string> names;
for (MeasListConstIter iter = fSamples.begin(); iter != fSamples.end();
iter++) {
MeasurementBase *exp = *iter;
double like = exp->GetLikelihood();
double ndof = exp->GetNDOF();
std::string name = exp->GetName();
likes.push_back(like);
ndofs.push_back(ndof);
names.push_back(name);
}
if (likes.size()) {
TH1D likehist = TH1D("likelihood_hist", "likelihood_hist", likes.size(),
0.0, double(likes.size()));
TH1D ndofhist =
TH1D("ndof_hist", "ndof_hist", ndofs.size(), 0.0, double(ndofs.size()));
TH1D divhist = TH1D("likedivndof_hist", "likedivndof_hist", likes.size(),
0.0, double(likes.size()));
for (int i = 0; i < likehist.GetNbinsX(); i++) {
likehist.SetBinContent(i + 1, likes[i]);
ndofhist.SetBinContent(i + 1, ndofs[i]);
if (ndofs[i] != 0.0) {
divhist.SetBinContent(i + 1, likes[i] / ndofs[i]);
}
likehist.GetXaxis()->SetBinLabel(i + 1, names[i].c_str());
ndofhist.GetXaxis()->SetBinLabel(i + 1, names[i].c_str());
divhist.GetXaxis()->SetBinLabel(i + 1, names[i].c_str());
}
likehist.Write();
ndofhist.Write();
divhist.Write();
}
// Loop over individual experiments and call Write
NUIS_LOG(MIN, "Writing each of the data classes...");
for (MeasListConstIter iter = fSamples.begin(); iter != fSamples.end();
iter++) {
MeasurementBase *exp = *iter;
exp->Write();
}
// Save Pull Terms
for (PullListConstIter iter = fPulls.begin(); iter != fPulls.end(); iter++) {
ParamPull *pull = *iter;
pull->Write();
}
if (FitPar::Config().GetParB("EventManager")) {
// Get list of inputs
std::map<int, InputHandlerBase *> fInputs =
FitBase::EvtManager().GetInputs();
std::map<int, InputHandlerBase *>::const_iterator iterInp;
for (iterInp = fInputs.begin(); iterInp != fInputs.end(); iterInp++) {
InputHandlerBase *input = (iterInp->second);
input->GetFluxHistogram()->Write();
input->GetXSecHistogram()->Write();
input->GetEventHistogram()->Write();
}
}
};
//***************************************************
void JointFCN::SetFakeData(std::string fakeinput) {
//***************************************************
NUIS_LOG(MIN, "Setting fake data from " << fakeinput);
for (MeasListConstIter iter = fSamples.begin(); iter != fSamples.end();
iter++) {
MeasurementBase *exp = *iter;
exp->SetFakeDataValues(fakeinput);
}
return;
}
//***************************************************
void JointFCN::ThrowDataToy() {
//***************************************************
for (MeasListConstIter iter = fSamples.begin(); iter != fSamples.end();
iter++) {
MeasurementBase *exp = *iter;
exp->ThrowDataToy();
}
return;
}
//***************************************************
std::vector<std::string> JointFCN::GetAllNames() {
//***************************************************
// Vect of all likelihoods and total
std::vector<std::string> namevect;
// Loop over samples first
for (MeasListConstIter iter = fSamples.begin(); iter != fSamples.end();
iter++) {
MeasurementBase *exp = *iter;
// Get Likelihoods and push to vector
namevect.push_back(exp->GetName());
}
// Loop over pulls second
for (PullListConstIter iter = fPulls.begin(); iter != fPulls.end(); iter++) {
ParamPull *pull = *iter;
// Push back to vector
namevect.push_back(pull->GetName());
}
// Finally add the total
namevect.push_back("total");
return namevect;
}
//***************************************************
std::vector<double> JointFCN::GetAllLikelihoods() {
//***************************************************
// Vect of all likelihoods and total
std::vector<double> likevect;
double total_likelihood = 0.0;
NUIS_LOG(MIN, "Likelihoods : ");
// Loop over samples first
for (MeasListConstIter iter = fSamples.begin(); iter != fSamples.end();
iter++) {
MeasurementBase *exp = *iter;
// Get Likelihoods and push to vector
double singlelike = exp->GetLikelihood();
likevect.push_back(singlelike);
total_likelihood += singlelike;
// Print Out
NUIS_LOG(MIN, "-> " << std::left << std::setw(40) << exp->GetName() << " : "
<< singlelike);
}
// Loop over pulls second
for (PullListConstIter iter = fPulls.begin(); iter != fPulls.end(); iter++) {
ParamPull *pull = *iter;
// Push back to vector
double singlelike = pull->GetLikelihood();
likevect.push_back(singlelike);
total_likelihood += singlelike;
// Print Out
NUIS_LOG(MIN, "-> " << std::left << std::setw(40) << pull->GetName() << " : "
<< singlelike);
}
// Finally add the total likelihood
likevect.push_back(total_likelihood);
return likevect;
}
//***************************************************
std::vector<int> JointFCN::GetAllNDOF() {
//***************************************************
// Vect of all ndof and total
std::vector<int> ndofvect;
int total_ndof = 0;
// Loop over samples first
for (MeasListConstIter iter = fSamples.begin(); iter != fSamples.end();
iter++) {
MeasurementBase *exp = *iter;
// Get Likelihoods and push to vector
int singlendof = exp->GetNDOF();
ndofvect.push_back(singlendof);
total_ndof += singlendof;
}
// Loop over pulls second
for (PullListConstIter iter = fPulls.begin(); iter != fPulls.end(); iter++) {
ParamPull *pull = *iter;
// Push back to vector
int singlendof = pull->GetNDOF();
ndofvect.push_back(singlendof);
total_ndof += singlendof;
}
// Finally add the total ndof
ndofvect.push_back(total_ndof);
return ndofvect;
}
diff --git a/src/FCN/SampleList.cxx b/src/FCN/SampleList.cxx
index e0f3fcf..aa80f6a 100644
--- a/src/FCN/SampleList.cxx
+++ b/src/FCN/SampleList.cxx
@@ -1,1431 +1,1431 @@
#include "SampleList.h"
#ifndef __NO_ANL__
#include "ANL_CCQE_Evt_1DQ2_nu.h"
#include "ANL_CCQE_XSec_1DEnu_nu.h"
// ANL CC1ppip
#include "ANL_CC1ppip_Evt_1DQ2_nu.h"
#include "ANL_CC1ppip_Evt_1DcosmuStar_nu.h"
#include "ANL_CC1ppip_Evt_1DcosthAdler_nu.h"
#include "ANL_CC1ppip_Evt_1Dphi_nu.h"
#include "ANL_CC1ppip_Evt_1Dppi_nu.h"
#include "ANL_CC1ppip_Evt_1Dthpr_nu.h"
#include "ANL_CC1ppip_XSec_1DEnu_nu.h"
#include "ANL_CC1ppip_XSec_1DQ2_nu.h"
// ANL CC1npip
#include "ANL_CC1npip_Evt_1DQ2_nu.h"
#include "ANL_CC1npip_Evt_1DcosmuStar_nu.h"
#include "ANL_CC1npip_Evt_1Dppi_nu.h"
#include "ANL_CC1npip_XSec_1DEnu_nu.h"
// ANL CC1pi0
#include "ANL_CC1pi0_Evt_1DQ2_nu.h"
#include "ANL_CC1pi0_Evt_1DcosmuStar_nu.h"
#include "ANL_CC1pi0_XSec_1DEnu_nu.h"
// ANL NC1npip (mm, exotic!)
#include "ANL_NC1npip_Evt_1Dppi_nu.h"
// ANL NC1ppim (mm, exotic!)
#include "ANL_NC1ppim_Evt_1DcosmuStar_nu.h"
#include "ANL_NC1ppim_XSec_1DEnu_nu.h"
// ANL CC2pi 1pim1pip (mm, even more exotic!)
#include "ANL_CC2pi_1pim1pip_Evt_1Dpmu_nu.h"
#include "ANL_CC2pi_1pim1pip_Evt_1Dppim_nu.h"
#include "ANL_CC2pi_1pim1pip_Evt_1Dppip_nu.h"
#include "ANL_CC2pi_1pim1pip_Evt_1Dpprot_nu.h"
#include "ANL_CC2pi_1pim1pip_XSec_1DEnu_nu.h"
// ANL CC2pi 1pip1pip (mm, even more exotic!)
#include "ANL_CC2pi_1pip1pip_Evt_1Dpmu_nu.h"
#include "ANL_CC2pi_1pip1pip_Evt_1Dpneut_nu.h"
#include "ANL_CC2pi_1pip1pip_Evt_1DppipHigh_nu.h"
#include "ANL_CC2pi_1pip1pip_Evt_1DppipLow_nu.h"
#include "ANL_CC2pi_1pip1pip_XSec_1DEnu_nu.h"
// ANL CC2pi 1pip1pi0 (mm, even more exotic!)
#include "ANL_CC2pi_1pip1pi0_Evt_1Dpmu_nu.h"
#include "ANL_CC2pi_1pip1pi0_Evt_1Dppi0_nu.h"
#include "ANL_CC2pi_1pip1pi0_Evt_1Dppip_nu.h"
#include "ANL_CC2pi_1pip1pi0_Evt_1Dpprot_nu.h"
#include "ANL_CC2pi_1pip1pi0_XSec_1DEnu_nu.h"
#endif
#ifndef __NO_ArgoNeuT__
// ArgoNeuT CC1Pi
#include "ArgoNeuT_CC1Pi_XSec_1Dpmu_antinu.h"
#include "ArgoNeuT_CC1Pi_XSec_1Dpmu_nu.h"
#include "ArgoNeuT_CC1Pi_XSec_1Dthetamu_antinu.h"
#include "ArgoNeuT_CC1Pi_XSec_1Dthetamu_nu.h"
#include "ArgoNeuT_CC1Pi_XSec_1Dthetamupi_antinu.h"
#include "ArgoNeuT_CC1Pi_XSec_1Dthetamupi_nu.h"
#include "ArgoNeuT_CC1Pi_XSec_1Dthetapi_antinu.h"
#include "ArgoNeuT_CC1Pi_XSec_1Dthetapi_nu.h"
// ArgoNeuT CC-inclusive
#include "ArgoNeuT_CCInc_XSec_1Dpmu_antinu.h"
#include "ArgoNeuT_CCInc_XSec_1Dpmu_nu.h"
#include "ArgoNeuT_CCInc_XSec_1Dthetamu_antinu.h"
#include "ArgoNeuT_CCInc_XSec_1Dthetamu_nu.h"
#endif
#ifndef __NO_BNL__
// BNL CCQE
#include "BNL_CCQE_Evt_1DQ2_nu.h"
#include "BNL_CCQE_XSec_1DEnu_nu.h"
// BNL CC1ppip
#include "BNL_CC1ppip_Evt_1DQ2_nu.h"
#include "BNL_CC1ppip_Evt_1DcosthAdler_nu.h"
#include "BNL_CC1ppip_Evt_1Dphi_nu.h"
#include "BNL_CC1ppip_XSec_1DEnu_nu.h"
// BNL CC1npip
#include "BNL_CC1npip_Evt_1DQ2_nu.h"
#include "BNL_CC1npip_XSec_1DEnu_nu.h"
// BNL CC1pi0
#include "BNL_CC1pi0_Evt_1DQ2_nu.h"
#include "BNL_CC1pi0_XSec_1DEnu_nu.h"
#endif
#ifndef __NO_FNAL__
// FNAL CCQE
#include "FNAL_CCQE_Evt_1DQ2_nu.h"
// FNAL CC1ppip
#include "FNAL_CC1ppip_Evt_1DQ2_nu.h"
#include "FNAL_CC1ppip_XSec_1DEnu_nu.h"
#include "FNAL_CC1ppip_XSec_1DQ2_nu.h"
// FNAL CC1ppim
#include "FNAL_CC1ppim_XSec_1DEnu_antinu.h"
#endif
#ifndef __NO_BEBC__
// BEBC CCQE
#include "BEBC_CCQE_XSec_1DQ2_nu.h"
// BEBC CC1ppip
#include "BEBC_CC1ppip_XSec_1DEnu_nu.h"
#include "BEBC_CC1ppip_XSec_1DQ2_nu.h"
// BEBC CC1npip
#include "BEBC_CC1npip_XSec_1DEnu_nu.h"
#include "BEBC_CC1npip_XSec_1DQ2_nu.h"
// BEBC CC1pi0
#include "BEBC_CC1pi0_XSec_1DEnu_nu.h"
#include "BEBC_CC1pi0_XSec_1DQ2_nu.h"
// BEBC CC1npim
#include "BEBC_CC1npim_XSec_1DEnu_antinu.h"
#include "BEBC_CC1npim_XSec_1DQ2_antinu.h"
// BEBC CC1ppim
#include "BEBC_CC1ppim_XSec_1DEnu_antinu.h"
#include "BEBC_CC1ppim_XSec_1DQ2_antinu.h"
#endif
#ifndef __NO_GGM__
// GGM CC1ppip
#include "GGM_CC1ppip_Evt_1DQ2_nu.h"
#include "GGM_CC1ppip_XSec_1DEnu_nu.h"
#endif
#ifndef __NO_MiniBooNE__
// MiniBooNE CCQE
#include "MiniBooNE_CCQE_XSec_1DQ2_antinu.h"
#include "MiniBooNE_CCQE_XSec_1DQ2_nu.h"
#include "MiniBooNE_CCQE_XSec_2DTcos_antinu.h"
#include "MiniBooNE_CCQE_XSec_2DTcos_nu.h"
// MiniBooNE CC1pi+ 1D
#include "MiniBooNE_CC1pip_XSec_1DEnu_nu.h"
#include "MiniBooNE_CC1pip_XSec_1DQ2_nu.h"
#include "MiniBooNE_CC1pip_XSec_1DTpi_nu.h"
#include "MiniBooNE_CC1pip_XSec_1DTu_nu.h"
// MiniBooNE CC1pi+ 2D
#include "MiniBooNE_CC1pip_XSec_2DQ2Enu_nu.h"
#include "MiniBooNE_CC1pip_XSec_2DTpiCospi_nu.h"
#include "MiniBooNE_CC1pip_XSec_2DTpiEnu_nu.h"
#include "MiniBooNE_CC1pip_XSec_2DTuCosmu_nu.h"
#include "MiniBooNE_CC1pip_XSec_2DTuEnu_nu.h"
// MiniBooNE CC1pi0
#include "MiniBooNE_CC1pi0_XSec_1DEnu_nu.h"
#include "MiniBooNE_CC1pi0_XSec_1DQ2_nu.h"
#include "MiniBooNE_CC1pi0_XSec_1DTu_nu.h"
#include "MiniBooNE_CC1pi0_XSec_1Dcosmu_nu.h"
#include "MiniBooNE_CC1pi0_XSec_1Dcospi0_nu.h"
#include "MiniBooNE_CC1pi0_XSec_1Dppi0_nu.h"
#include "MiniBooNE_NC1pi0_XSec_1Dcospi0_antinu.h"
#include "MiniBooNE_NC1pi0_XSec_1Dcospi0_nu.h"
#include "MiniBooNE_NC1pi0_XSec_1Dppi0_antinu.h"
#include "MiniBooNE_NC1pi0_XSec_1Dppi0_nu.h"
// MiniBooNE NC1pi0
//#include "MiniBooNE_NCpi0_XSec_1Dppi0_nu.h"
// MiniBooNE NCEL
#include "MiniBooNE_NCEL_XSec_Treco_nu.h"
#endif
#ifndef __NO_MicroBooNE__
#include "MicroBooNE_CCInc_XSec_2DPcos_nu.h"
#endif
#ifndef __NO_MINERvA__
// MINERvA CCQE
#include "MINERvA_CCQE_XSec_1DQ2_antinu.h"
#include "MINERvA_CCQE_XSec_1DQ2_joint.h"
#include "MINERvA_CCQE_XSec_1DQ2_nu.h"
// MINERvA CC0pi
#include "MINERvA_CC0pi_XSec_1DEe_nue.h"
#include "MINERvA_CC0pi_XSec_1DQ2_nu_proton.h"
#include "MINERvA_CC0pi_XSec_1DQ2_nue.h"
#include "MINERvA_CC0pi_XSec_1DThetae_nue.h"
// 2018 MINERvA CC0pi STV
#include "MINERvA_CC0pinp_STV_XSec_1D_nu.h"
// 2018 MINERvA CC0pi 2D
#include "MINERvA_CC0pi_XSec_1D_2018_nu.h"
#include "MINERvA_CC0pi_XSec_2D_nu.h"
// 2018 MINERvA CC0pi 2D antinu
#include "MINERvA_CC0pi_XSec_2D_antinu.h"
// MINERvA CC1pi+
#include "MINERvA_CC1pip_XSec_1DTpi_20deg_nu.h"
#include "MINERvA_CC1pip_XSec_1DTpi_nu.h"
#include "MINERvA_CC1pip_XSec_1Dth_20deg_nu.h"
#include "MINERvA_CC1pip_XSec_1Dth_nu.h"
// 2017 data update
#include "MINERvA_CC1pip_XSec_1D_2017Update.h"
// MINERvA CCNpi+
#include "MINERvA_CCNpip_XSec_1DEnu_nu.h"
#include "MINERvA_CCNpip_XSec_1DQ2_nu.h"
#include "MINERvA_CCNpip_XSec_1DTpi_nu.h"
#include "MINERvA_CCNpip_XSec_1Dpmu_nu.h"
#include "MINERvA_CCNpip_XSec_1Dth_nu.h"
#include "MINERvA_CCNpip_XSec_1Dthmu_nu.h"
// MINERvA CC1pi0
#include "MINERvA_CC1pi0_XSec_1DEnu_antinu.h"
#include "MINERvA_CC1pi0_XSec_1DQ2_antinu.h"
#include "MINERvA_CC1pi0_XSec_1DTpi0_antinu.h"
#include "MINERvA_CC1pi0_XSec_1Dpmu_antinu.h"
#include "MINERvA_CC1pi0_XSec_1Dppi0_antinu.h"
#include "MINERvA_CC1pi0_XSec_1Dth_antinu.h"
#include "MINERvA_CC1pi0_XSec_1Dthmu_antinu.h"
// MINERvA CC1pi0 neutrino
#include "MINERvA_CC1pi0_XSec_1D_nu.h"
// MINERvA CCINC
#include "MINERvA_CCinc_XSec_1DEnu_ratio.h"
#include "MINERvA_CCinc_XSec_1Dx_ratio.h"
#include "MINERvA_CCinc_XSec_2DEavq3_nu.h"
// MINERvA CCDIS
#include "MINERvA_CCDIS_XSec_1DEnu_ratio.h"
#include "MINERvA_CCDIS_XSec_1Dx_ratio.h"
// MINERvA CCCOH pion
#include "MINERvA_CCCOHPI_XSec_1DEnu_antinu.h"
#include "MINERvA_CCCOHPI_XSec_1DEpi_antinu.h"
#include "MINERvA_CCCOHPI_XSec_1DQ2_antinu.h"
#include "MINERvA_CCCOHPI_XSec_1DEpi_nu.h"
#include "MINERvA_CCCOHPI_XSec_1DQ2_nu.h"
#include "MINERvA_CCCOHPI_XSec_1Dth_nu.h"
#include "MINERvA_CCCOHPI_XSec_joint.h"
#include "MINERvA_CC0pi_XSec_1DQ2_TgtRatio_nu.h"
#include "MINERvA_CC0pi_XSec_1DQ2_Tgt_nu.h"
#endif
#ifndef __NO_T2K__
// T2K CC0pi 2016
#include "T2K_CC0pi_XSec_2DPcos_nu_I.h"
#include "T2K_CC0pi_XSec_2DPcos_nu_II.h"
// T2K CC-inclusive with full acceptance 2018
#include "T2K_CCinc_XSec_2DPcos_nu_nonuniform.h"
// T2K STV CC0pi 2018
#include "T2K_CC0pi1p_XSec_3DPcoscos_nu_nonuniform.h"
#include "T2K_CC0pinp_STV_XSec_1Ddat_nu.h"
#include "T2K_CC0pinp_STV_XSec_1Ddphit_nu.h"
#include "T2K_CC0pinp_STV_XSec_1Ddpt_nu.h"
#include "T2K_CC0pinp_ifk_XSec_3Dinfa_nu.h"
#include "T2K_CC0pinp_ifk_XSec_3Dinfip_nu.h"
#include "T2K_CC0pinp_ifk_XSec_3Dinfp_nu.h"
// T2K CC1pi+ on CH
#include "T2K_CC1pip_CH_XSec_1DAdlerPhi_nu.h"
#include "T2K_CC1pip_CH_XSec_1DCosThAdler_nu.h"
#include "T2K_CC1pip_CH_XSec_1DQ2_nu.h"
#include "T2K_CC1pip_CH_XSec_1Dppi_nu.h"
#include "T2K_CC1pip_CH_XSec_1Dthmupi_nu.h"
#include "T2K_CC1pip_CH_XSec_1Dthpi_nu.h"
#include "T2K_CC1pip_CH_XSec_2Dpmucosmu_nu.h"
//#include "T2K_CC1pip_CH_XSec_1Dthq3pi_nu.h"
//#include "T2K_CC1pip_CH_XSec_1DWrec_nu.h"
//#include "T2K_CC1pip_CH_XSec_1Dq3_nu.h"
// T2K CC1pi+ on H2O
#include "T2K_CC1pip_H2O_XSec_1DEnuDelta_nu.h"
#include "T2K_CC1pip_H2O_XSec_1DEnuMB_nu.h"
#include "T2K_CC1pip_H2O_XSec_1Dcosmu_nu.h"
#include "T2K_CC1pip_H2O_XSec_1Dcosmupi_nu.h"
#include "T2K_CC1pip_H2O_XSec_1Dcospi_nu.h"
#include "T2K_CC1pip_H2O_XSec_1Dpmu_nu.h"
#include "T2K_CC1pip_H2O_XSec_1Dppi_nu.h"
#endif
#ifndef __NO_SciBooNE__
// SciBooNE COH studies
#include "SciBooNE_CCCOH_1TRK_1DQ2_nu.h"
#include "SciBooNE_CCCOH_1TRK_1Dpmu_nu.h"
#include "SciBooNE_CCCOH_1TRK_1Dthetamu_nu.h"
#include "SciBooNE_CCCOH_MuPiNoVA_1DQ2_nu.h"
#include "SciBooNE_CCCOH_MuPiNoVA_1Dpmu_nu.h"
#include "SciBooNE_CCCOH_MuPiNoVA_1Dthetamu_nu.h"
#include "SciBooNE_CCCOH_MuPiNoVA_1Dthetapi_nu.h"
#include "SciBooNE_CCCOH_MuPiNoVA_1Dthetapr_nu.h"
#include "SciBooNE_CCCOH_MuPiVA_1DQ2_nu.h"
#include "SciBooNE_CCCOH_MuPiVA_1Dpmu_nu.h"
#include "SciBooNE_CCCOH_MuPiVA_1Dthetamu_nu.h"
#include "SciBooNE_CCCOH_MuPr_1DQ2_nu.h"
#include "SciBooNE_CCCOH_MuPr_1Dpmu_nu.h"
#include "SciBooNE_CCCOH_MuPr_1Dthetamu_nu.h"
#include "SciBooNE_CCCOH_STOPFINAL_1DQ2_nu.h"
#include "SciBooNE_CCCOH_STOP_NTrks_nu.h"
#endif
#ifndef __NO_K2K__
// K2K NC1pi0
#include "K2K_NC1pi0_Evt_1Dppi0_nu.h"
#endif
// MC Studies
#include "ExpMultDist_CCQE_XSec_1DVar_FakeStudy.h"
#include "ExpMultDist_CCQE_XSec_2DVar_FakeStudy.h"
#include "MCStudy_CCQEHistograms.h"
#include "GenericFlux_Tester.h"
#include "GenericFlux_Vectors.h"
#include "ElectronFlux_FlatTree.h"
#include "ElectronScattering_DurhamData.h"
#include "MCStudy_KaonPreSelection.h"
#include "MCStudy_MuonValidation.h"
#include "OfficialNIWGPlots.h"
#include "T2K2017_FakeData.h"
#include "Simple_Osc.h"
#include "Smear_SVDUnfold_Propagation_Osc.h"
#include "FitWeight.h"
#include "NuisConfig.h"
#include "NuisKey.h"
#ifdef __USE_DYNSAMPLES__
#include "TRegexp.h"
#include <dirent.h>
// linux
#include <dlfcn.h>
DynamicSampleFactory::DynamicSampleFactory() : NSamples(0), NManifests(0) {
LoadPlugins();
NUIS_LOG(FIT, "Loaded " << NSamples << " from " << NManifests
<< " shared object libraries.");
}
DynamicSampleFactory *DynamicSampleFactory::glblDSF = NULL;
DynamicSampleFactory::PluginManifest::~PluginManifest() {
for (size_t i_it = 0; i_it < Instances.size(); ++i_it) {
(*(DSF_DestroySample))(Instances[i_it]);
}
}
std::string EnsureTrailingSlash(std::string const &inp) {
if (!inp.length()) {
return "/";
}
if (inp[inp.length() - 1] == '/') {
return inp;
}
return inp + "/";
}
void DynamicSampleFactory::LoadPlugins() {
std::vector<std::string> SearchDirectories;
if (Config::HasPar("dynamic_sample.path")) {
SearchDirectories =
GeneralUtils::ParseToStr(Config::GetParS("dynamic_sample.path"), ":");
}
char const *envPath = getenv("NUISANCE_DS_PATH");
if (envPath) {
std::vector<std::string> envPaths = GeneralUtils::ParseToStr(envPath, ":");
for (size_t ep_it = 0; ep_it < envPaths.size(); ++ep_it) {
SearchDirectories.push_back(envPaths[ep_it]);
}
}
if (!SearchDirectories.size()) {
char const *pwdPath = getenv("PWD");
if (pwdPath) {
SearchDirectories.push_back(pwdPath);
}
}
for (size_t sp_it = 0; sp_it < SearchDirectories.size(); ++sp_it) {
std::string dirpath = EnsureTrailingSlash(SearchDirectories[sp_it]);
NUIS_LOG(FIT, "Searching for dynamic sample manifests in: " << dirpath);
Ssiz_t len = 0;
DIR *dir;
struct dirent *ent;
dir = opendir(dirpath.c_str());
if (dir != NULL) {
TRegexp matchExp("*.so", true);
while ((ent = readdir(dir)) != NULL) {
if (matchExp.Index(TString(ent->d_name), &len) != Ssiz_t(-1)) {
NUIS_LOG(FIT, "\tFound shared object: "
<< ent->d_name
<< " checking for relevant methods...");
void *dlobj =
dlopen((dirpath + ent->d_name).c_str(), RTLD_NOW | RTLD_GLOBAL);
char const *dlerr_cstr = dlerror();
std::string dlerr;
if (dlerr_cstr) {
dlerr = dlerr_cstr;
}
if (dlerr.length()) {
NUIS_ERR(WRN, "\tDL Load Error: " << dlerr);
continue;
}
PluginManifest plgManif;
plgManif.dllib = dlobj;
plgManif.soloc = (dirpath + ent->d_name);
plgManif.DSF_NSamples =
reinterpret_cast<DSF_NSamples_ptr>(dlsym(dlobj, "DSF_NSamples"));
dlerr = "";
dlerr_cstr = dlerror();
if (dlerr_cstr) {
dlerr = dlerr_cstr;
}
if (dlerr.length()) {
NUIS_ERR(WRN, "\tFailed to load symbol \"DSF_NSamples\" from "
<< (dirpath + ent->d_name) << ": " << dlerr);
dlclose(dlobj);
continue;
}
plgManif.DSF_GetSampleName = reinterpret_cast<DSF_GetSampleName_ptr>(
dlsym(dlobj, "DSF_GetSampleName"));
dlerr = "";
dlerr_cstr = dlerror();
if (dlerr_cstr) {
dlerr = dlerr_cstr;
}
if (dlerr.length()) {
NUIS_ERR(WRN, "\tFailed to load symbol \"DSF_GetSampleName\" from "
<< (dirpath + ent->d_name) << ": " << dlerr);
dlclose(dlobj);
continue;
}
plgManif.DSF_GetSample = reinterpret_cast<DSF_GetSample_ptr>(
dlsym(dlobj, "DSF_GetSample"));
dlerr = "";
dlerr_cstr = dlerror();
if (dlerr_cstr) {
dlerr = dlerr_cstr;
}
if (dlerr.length()) {
NUIS_ERR(WRN, "\tFailed to load symbol \"DSF_GetSample\" from "
<< (dirpath + ent->d_name) << ": " << dlerr);
dlclose(dlobj);
continue;
}
plgManif.DSF_DestroySample = reinterpret_cast<DSF_DestroySample_ptr>(
dlsym(dlobj, "DSF_DestroySample"));
dlerr = "";
dlerr_cstr = dlerror();
if (dlerr_cstr) {
dlerr = dlerr_cstr;
}
if (dlerr.length()) {
NUIS_ERR(WRN, "Failed to load symbol \"DSF_DestroySample\" from "
<< (dirpath + ent->d_name) << ": " << dlerr);
dlclose(dlobj);
continue;
}
plgManif.NSamples = (*(plgManif.DSF_NSamples))();
NUIS_LOG(FIT, "\tSuccessfully loaded dynamic sample manifest: "
<< plgManif.soloc << ". Contains "
<< plgManif.NSamples << " samples.");
for (size_t smp_it = 0; smp_it < plgManif.NSamples; ++smp_it) {
char const *smp_name = (*(plgManif.DSF_GetSampleName))(smp_it);
if (!smp_name) {
NUIS_ABORT("Could not load sample "
<< smp_it << " / " << plgManif.NSamples << " from "
<< plgManif.soloc);
}
if (Samples.count(smp_name)) {
NUIS_ERR(WRN, "Already loaded a sample named: \""
<< smp_name
<< "\". cannot load duplciates. This "
"sample will be skipped.");
continue;
}
plgManif.SamplesProvided.push_back(smp_name);
Samples[smp_name] = std::make_pair(plgManif.soloc, smp_it);
NUIS_LOG(FIT, "\t\t" << smp_name);
}
if (plgManif.SamplesProvided.size()) {
Manifests[plgManif.soloc] = plgManif;
NSamples += plgManif.SamplesProvided.size();
NManifests++;
} else {
dlclose(dlobj);
}
}
}
closedir(dir);
} else {
NUIS_ERR(WRN, "Tried to open non-existant directory.");
}
}
}
DynamicSampleFactory &DynamicSampleFactory::Get() {
if (!glblDSF) {
glblDSF = new DynamicSampleFactory();
}
return *glblDSF;
}
void DynamicSampleFactory::Print() {
- std::map<std::string, std::vector<std::string>> ManifestSamples;
+ std::map<std::string, std::vector<std::string> > ManifestSamples;
- for (std::map<std::string, std::pair<std::string, int>>::iterator smp_it =
+ for (std::map<std::string, std::pair<std::string, int> >::iterator smp_it =
Samples.begin();
smp_it != Samples.end(); ++smp_it) {
if (!ManifestSamples.count(smp_it->second.first)) {
ManifestSamples[smp_it->second.first] = std::vector<std::string>();
}
ManifestSamples[smp_it->second.first].push_back(smp_it->first);
}
NUIS_LOG(FIT, "Dynamic sample manifest: ");
- for (std::map<std::string, std::vector<std::string>>::iterator m_it =
+ for (std::map<std::string, std::vector<std::string> >::iterator m_it =
ManifestSamples.begin();
m_it != ManifestSamples.end(); ++m_it) {
NUIS_LOG(FIT, "\tLibrary " << m_it->first << " contains: ");
for (size_t s_it = 0; s_it < m_it->second.size(); ++s_it) {
NUIS_LOG(FIT, "\t\t" << m_it->second[s_it]);
}
}
}
bool DynamicSampleFactory::HasSample(std::string const &name) {
return Samples.count(name);
}
bool DynamicSampleFactory::HasSample(nuiskey &samplekey) {
return HasSample(samplekey.GetS("name"));
}
MeasurementBase *DynamicSampleFactory::CreateSample(nuiskey &samplekey) {
if (!HasSample(samplekey)) {
NUIS_ERR(WRN, "Asked to load unknown sample: \"" << samplekey.GetS("name")
<< "\".");
return NULL;
}
std::pair<std::string, int> sample = Samples[samplekey.GetS("name")];
NUIS_LOG(SAM,
"\tLoading sample " << sample.second << " from " << sample.first);
return (*(Manifests[sample.first].DSF_GetSample))(sample.second, &samplekey);
}
DynamicSampleFactory::~DynamicSampleFactory() { Manifests.clear(); }
#endif
//! Functions to make it easier for samples to be created and handled.
namespace SampleUtils {
//! Create a given sample given its name, file, type, fakdata(fkdt) file and the
//! current rw engine and push it back into the list fChain.
MeasurementBase *CreateSample(std::string name, std::string file,
std::string type, std::string fkdt,
FitWeight *rw) {
nuiskey samplekey = Config::CreateKey("sample");
samplekey.Set("name", name);
samplekey.Set("input", file);
samplekey.Set("type", type);
return CreateSample(samplekey);
}
MeasurementBase *CreateSample(nuiskey samplekey) {
#ifdef __USE_DYNSAMPLES__
if (DynamicSampleFactory::Get().HasSample(samplekey)) {
NUIS_LOG(SAM, "Instantiating dynamic sample...");
MeasurementBase *ds = DynamicSampleFactory::Get().CreateSample(samplekey);
if (ds) {
NUIS_LOG(SAM, "Done.");
return ds;
}
NUIS_ABORT("Failed to instantiate dynamic sample.");
}
#endif
FitWeight *rw = FitBase::GetRW();
std::string name = samplekey.GetS("name");
std::string file = samplekey.GetS("input");
std::string type = samplekey.GetS("type");
std::string fkdt = "";
/*
ANL CCQE Samples
*/
#ifndef __NO_ANL__
if (!name.compare("ANL_CCQE_XSec_1DEnu_nu") ||
!name.compare("ANL_CCQE_XSec_1DEnu_nu_PRD26") ||
!name.compare("ANL_CCQE_XSec_1DEnu_nu_PRL31") ||
!name.compare("ANL_CCQE_XSec_1DEnu_nu_PRD16")) {
return (new ANL_CCQE_XSec_1DEnu_nu(samplekey));
} else if (!name.compare("ANL_CCQE_Evt_1DQ2_nu") ||
!name.compare("ANL_CCQE_Evt_1DQ2_nu_PRL31") ||
!name.compare("ANL_CCQE_Evt_1DQ2_nu_PRD26") ||
!name.compare("ANL_CCQE_Evt_1DQ2_nu_PRD16")) {
return (new ANL_CCQE_Evt_1DQ2_nu(samplekey));
/*
ANL CC1ppip samples
*/
} else if (!name.compare("ANL_CC1ppip_XSec_1DEnu_nu") ||
!name.compare("ANL_CC1ppip_XSec_1DEnu_nu_W14Cut") ||
!name.compare("ANL_CC1ppip_XSec_1DEnu_nu_Uncorr") ||
!name.compare("ANL_CC1ppip_XSec_1DEnu_nu_W14Cut_Uncorr") ||
!name.compare("ANL_CC1ppip_XSec_1DEnu_nu_W16Cut_Uncorr")) {
return (new ANL_CC1ppip_XSec_1DEnu_nu(samplekey));
} else if (!name.compare("ANL_CC1ppip_XSec_1DQ2_nu")) {
return (new ANL_CC1ppip_XSec_1DQ2_nu(samplekey));
} else if (!name.compare("ANL_CC1ppip_Evt_1DQ2_nu") ||
!name.compare("ANL_CC1ppip_Evt_1DQ2_nu_W14Cut")) {
return (new ANL_CC1ppip_Evt_1DQ2_nu(samplekey));
} else if (!name.compare("ANL_CC1ppip_Evt_1Dppi_nu")) {
return (new ANL_CC1ppip_Evt_1Dppi_nu(samplekey));
} else if (!name.compare("ANL_CC1ppip_Evt_1Dthpr_nu")) {
return (new ANL_CC1ppip_Evt_1Dthpr_nu(samplekey));
} else if (!name.compare("ANL_CC1ppip_Evt_1DcosmuStar_nu")) {
return (new ANL_CC1ppip_Evt_1DcosmuStar_nu(samplekey));
} else if (!name.compare("ANL_CC1ppip_Evt_1DcosthAdler_nu")) {
return (new ANL_CC1ppip_Evt_1DcosthAdler_nu(samplekey));
} else if (!name.compare("ANL_CC1ppip_Evt_1Dphi_nu")) {
return (new ANL_CC1ppip_Evt_1Dphi_nu(samplekey));
/*
ANL CC1npip sample
*/
} else if (!name.compare("ANL_CC1npip_XSec_1DEnu_nu") ||
!name.compare("ANL_CC1npip_XSec_1DEnu_nu_W14Cut") ||
!name.compare("ANL_CC1npip_XSec_1DEnu_nu_Uncorr") ||
!name.compare("ANL_CC1npip_XSec_1DEnu_nu_W14Cut_Uncorr") ||
!name.compare("ANL_CC1npip_XSec_1DEnu_nu_W16Cut_Uncorr")) {
return (new ANL_CC1npip_XSec_1DEnu_nu(samplekey));
} else if (!name.compare("ANL_CC1npip_Evt_1DQ2_nu") ||
!name.compare("ANL_CC1npip_Evt_1DQ2_nu_W14Cut")) {
return (new ANL_CC1npip_Evt_1DQ2_nu(samplekey));
} else if (!name.compare("ANL_CC1npip_Evt_1Dppi_nu")) {
return (new ANL_CC1npip_Evt_1Dppi_nu(samplekey));
} else if (!name.compare("ANL_CC1npip_Evt_1DcosmuStar_nu")) {
return (new ANL_CC1npip_Evt_1DcosmuStar_nu(samplekey));
/*
ANL CC1pi0 sample
*/
} else if (!name.compare("ANL_CC1pi0_XSec_1DEnu_nu") ||
!name.compare("ANL_CC1pi0_XSec_1DEnu_nu_W14Cut") ||
!name.compare("ANL_CC1pi0_XSec_1DEnu_nu_Uncorr") ||
!name.compare("ANL_CC1pi0_XSec_1DEnu_nu_W14Cut_Uncorr") ||
!name.compare("ANL_CC1pi0_XSec_1DEnu_nu_W16Cut_Uncorr")) {
return (new ANL_CC1pi0_XSec_1DEnu_nu(samplekey));
} else if (!name.compare("ANL_CC1pi0_Evt_1DQ2_nu") ||
!name.compare("ANL_CC1pi0_Evt_1DQ2_nu_W14Cut")) {
return (new ANL_CC1pi0_Evt_1DQ2_nu(samplekey));
} else if (!name.compare("ANL_CC1pi0_Evt_1DcosmuStar_nu")) {
return (new ANL_CC1pi0_Evt_1DcosmuStar_nu(samplekey));
/*
ANL NC1npip sample
*/
} else if (!name.compare("ANL_NC1npip_Evt_1Dppi_nu")) {
return (new ANL_NC1npip_Evt_1Dppi_nu(samplekey));
/*
ANL NC1ppim sample
*/
} else if (!name.compare("ANL_NC1ppim_XSec_1DEnu_nu")) {
return (new ANL_NC1ppim_XSec_1DEnu_nu(samplekey));
} else if (!name.compare("ANL_NC1ppim_Evt_1DcosmuStar_nu")) {
return (new ANL_NC1ppim_Evt_1DcosmuStar_nu(samplekey));
/*
ANL CC2pi sample
*/
} else if (!name.compare("ANL_CC2pi_1pim1pip_XSec_1DEnu_nu")) {
return (new ANL_CC2pi_1pim1pip_XSec_1DEnu_nu(samplekey));
} else if (!name.compare("ANL_CC2pi_1pim1pip_Evt_1Dpmu_nu")) {
return (new ANL_CC2pi_1pim1pip_Evt_1Dpmu_nu(samplekey));
} else if (!name.compare("ANL_CC2pi_1pim1pip_Evt_1Dppip_nu")) {
return (new ANL_CC2pi_1pim1pip_Evt_1Dppip_nu(samplekey));
} else if (!name.compare("ANL_CC2pi_1pim1pip_Evt_1Dppim_nu")) {
return (new ANL_CC2pi_1pim1pip_Evt_1Dppim_nu(samplekey));
} else if (!name.compare("ANL_CC2pi_1pim1pip_Evt_1Dpprot_nu")) {
return (new ANL_CC2pi_1pim1pip_Evt_1Dpprot_nu(samplekey));
} else if (!name.compare("ANL_CC2pi_1pip1pip_XSec_1DEnu_nu")) {
return (new ANL_CC2pi_1pip1pip_XSec_1DEnu_nu(samplekey));
} else if (!name.compare("ANL_CC2pi_1pip1pip_Evt_1Dpmu_nu")) {
return (new ANL_CC2pi_1pip1pip_Evt_1Dpmu_nu(samplekey));
} else if (!name.compare("ANL_CC2pi_1pip1pip_Evt_1Dpneut_nu")) {
return (new ANL_CC2pi_1pip1pip_Evt_1Dpneut_nu(samplekey));
} else if (!name.compare("ANL_CC2pi_1pip1pip_Evt_1DppipHigh_nu")) {
return (new ANL_CC2pi_1pip1pip_Evt_1DppipHigh_nu(samplekey));
} else if (!name.compare("ANL_CC2pi_1pip1pip_Evt_1DppipLow_nu")) {
return (new ANL_CC2pi_1pip1pip_Evt_1DppipLow_nu(samplekey));
} else if (!name.compare("ANL_CC2pi_1pip1pi0_XSec_1DEnu_nu")) {
return (new ANL_CC2pi_1pip1pi0_XSec_1DEnu_nu(samplekey));
} else if (!name.compare("ANL_CC2pi_1pip1pi0_Evt_1Dpmu_nu")) {
return (new ANL_CC2pi_1pip1pi0_Evt_1Dpmu_nu(samplekey));
} else if (!name.compare("ANL_CC2pi_1pip1pi0_Evt_1Dppip_nu")) {
return (new ANL_CC2pi_1pip1pi0_Evt_1Dppip_nu(samplekey));
} else if (!name.compare("ANL_CC2pi_1pip1pi0_Evt_1Dppi0_nu")) {
return (new ANL_CC2pi_1pip1pi0_Evt_1Dppi0_nu(samplekey));
} else if (!name.compare("ANL_CC2pi_1pip1pi0_Evt_1Dpprot_nu")) {
return (new ANL_CC2pi_1pip1pi0_Evt_1Dpprot_nu(samplekey));
/*
ArgoNeut Samples
*/
} else
#endif
#ifndef __NO_ArgoNeuT__
if (!name.compare("ArgoNeuT_CCInc_XSec_1Dpmu_antinu")) {
return (new ArgoNeuT_CCInc_XSec_1Dpmu_antinu(samplekey));
} else if (!name.compare("ArgoNeuT_CCInc_XSec_1Dpmu_nu")) {
return (new ArgoNeuT_CCInc_XSec_1Dpmu_nu(samplekey));
} else if (!name.compare("ArgoNeuT_CCInc_XSec_1Dthetamu_antinu")) {
return (new ArgoNeuT_CCInc_XSec_1Dthetamu_antinu(samplekey));
} else if (!name.compare("ArgoNeuT_CCInc_XSec_1Dthetamu_nu")) {
return (new ArgoNeuT_CCInc_XSec_1Dthetamu_nu(samplekey));
} else if (!name.compare("ArgoNeuT_CC1Pi_XSec_1Dpmu_nu")) {
return (new ArgoNeuT_CC1Pi_XSec_1Dpmu_nu(samplekey));
} else if (!name.compare("ArgoNeuT_CC1Pi_XSec_1Dthetamu_nu")) {
return (new ArgoNeuT_CC1Pi_XSec_1Dthetamu_nu(samplekey));
} else if (!name.compare("ArgoNeuT_CC1Pi_XSec_1Dthetapi_nu")) {
return (new ArgoNeuT_CC1Pi_XSec_1Dthetapi_nu(samplekey));
} else if (!name.compare("ArgoNeuT_CC1Pi_XSec_1Dthetamupi_nu")) {
return (new ArgoNeuT_CC1Pi_XSec_1Dthetamupi_nu(samplekey));
} else if (!name.compare("ArgoNeuT_CC1Pi_XSec_1Dpmu_antinu")) {
return (new ArgoNeuT_CC1Pi_XSec_1Dpmu_antinu(samplekey));
} else if (!name.compare("ArgoNeuT_CC1Pi_XSec_1Dthetamu_antinu")) {
return (new ArgoNeuT_CC1Pi_XSec_1Dthetamu_antinu(samplekey));
} else if (!name.compare("ArgoNeuT_CC1Pi_XSec_1Dthetapi_antinu")) {
return (new ArgoNeuT_CC1Pi_XSec_1Dthetapi_antinu(samplekey));
} else if (!name.compare("ArgoNeuT_CC1Pi_XSec_1Dthetamupi_antinu")) {
return (new ArgoNeuT_CC1Pi_XSec_1Dthetamupi_antinu(samplekey));
/*
BNL Samples
*/
} else
#endif
#ifndef __NO_BNL__
if (!name.compare("BNL_CCQE_XSec_1DEnu_nu")) {
return (new BNL_CCQE_XSec_1DEnu_nu(samplekey));
} else if (!name.compare("BNL_CCQE_Evt_1DQ2_nu")) {
return (new BNL_CCQE_Evt_1DQ2_nu(samplekey));
/*
BNL CC1ppip samples
*/
} else if (!name.compare("BNL_CC1ppip_XSec_1DEnu_nu") ||
!name.compare("BNL_CC1ppip_XSec_1DEnu_nu_Uncorr") ||
!name.compare("BNL_CC1ppip_XSec_1DEnu_nu_W14Cut") ||
!name.compare("BNL_CC1ppip_XSec_1DEnu_nu_W14Cut_Uncorr")) {
return (new BNL_CC1ppip_XSec_1DEnu_nu(samplekey));
} else if (!name.compare("BNL_CC1ppip_Evt_1DQ2_nu") ||
!name.compare("BNL_CC1ppip_Evt_1DQ2_nu_W14Cut")) {
return (new BNL_CC1ppip_Evt_1DQ2_nu(samplekey));
} else if (!name.compare("BNL_CC1ppip_Evt_1DcosthAdler_nu")) {
return (new BNL_CC1ppip_Evt_1DcosthAdler_nu(samplekey));
} else if (!name.compare("BNL_CC1ppip_Evt_1Dphi_nu")) {
return (new BNL_CC1ppip_Evt_1Dphi_nu(samplekey));
/*
BNL CC1npip samples
*/
} else if (!name.compare("BNL_CC1npip_XSec_1DEnu_nu") ||
!name.compare("BNL_CC1npip_XSec_1DEnu_nu_Uncorr")) {
return (new BNL_CC1npip_XSec_1DEnu_nu(samplekey));
} else if (!name.compare("BNL_CC1npip_Evt_1DQ2_nu")) {
return (new BNL_CC1npip_Evt_1DQ2_nu(samplekey));
/*
BNL CC1pi0 samples
*/
} else if (!name.compare("BNL_CC1pi0_XSec_1DEnu_nu")) {
return (new BNL_CC1pi0_XSec_1DEnu_nu(samplekey));
} else if (!name.compare("BNL_CC1pi0_Evt_1DQ2_nu")) {
return (new BNL_CC1pi0_Evt_1DQ2_nu(samplekey));
/*
FNAL Samples
*/
} else
#endif
#ifndef __NO_FNAL__
if (!name.compare("FNAL_CCQE_Evt_1DQ2_nu")) {
return (new FNAL_CCQE_Evt_1DQ2_nu(samplekey));
/*
FNAL CC1ppip
*/
} else if (!name.compare("FNAL_CC1ppip_XSec_1DEnu_nu")) {
return (new FNAL_CC1ppip_XSec_1DEnu_nu(samplekey));
} else if (!name.compare("FNAL_CC1ppip_XSec_1DQ2_nu")) {
return (new FNAL_CC1ppip_XSec_1DQ2_nu(samplekey));
} else if (!name.compare("FNAL_CC1ppip_Evt_1DQ2_nu")) {
return (new FNAL_CC1ppip_Evt_1DQ2_nu(samplekey));
/*
FNAL CC1ppim
*/
} else if (!name.compare("FNAL_CC1ppim_XSec_1DEnu_antinu")) {
return (new FNAL_CC1ppim_XSec_1DEnu_antinu(samplekey));
/*
BEBC Samples
*/
} else
#endif
#ifndef __NO_BEBC__
if (!name.compare("BEBC_CCQE_XSec_1DQ2_nu")) {
return (new BEBC_CCQE_XSec_1DQ2_nu(samplekey));
/*
BEBC CC1ppip samples
*/
} else if (!name.compare("BEBC_CC1ppip_XSec_1DEnu_nu")) {
return (new BEBC_CC1ppip_XSec_1DEnu_nu(samplekey));
} else if (!name.compare("BEBC_CC1ppip_XSec_1DQ2_nu")) {
return (new BEBC_CC1ppip_XSec_1DQ2_nu(samplekey));
/*
BEBC CC1npip samples
*/
} else if (!name.compare("BEBC_CC1npip_XSec_1DEnu_nu")) {
return (new BEBC_CC1npip_XSec_1DEnu_nu(samplekey));
} else if (!name.compare("BEBC_CC1npip_XSec_1DQ2_nu")) {
return (new BEBC_CC1npip_XSec_1DQ2_nu(samplekey));
/*
BEBC CC1pi0 samples
*/
} else if (!name.compare("BEBC_CC1pi0_XSec_1DEnu_nu")) {
return (new BEBC_CC1pi0_XSec_1DEnu_nu(samplekey));
} else if (!name.compare("BEBC_CC1pi0_XSec_1DQ2_nu")) {
return (new BEBC_CC1pi0_XSec_1DQ2_nu(samplekey));
/*
BEBC CC1npim samples
*/
} else if (!name.compare("BEBC_CC1npim_XSec_1DEnu_antinu")) {
return (new BEBC_CC1npim_XSec_1DEnu_antinu(samplekey));
} else if (!name.compare("BEBC_CC1npim_XSec_1DQ2_antinu")) {
return (new BEBC_CC1npim_XSec_1DQ2_antinu(samplekey));
/*
BEBC CC1ppim samples
*/
} else if (!name.compare("BEBC_CC1ppim_XSec_1DEnu_antinu")) {
return (new BEBC_CC1ppim_XSec_1DEnu_antinu(samplekey));
} else if (!name.compare("BEBC_CC1ppim_XSec_1DQ2_antinu")) {
return (new BEBC_CC1ppim_XSec_1DQ2_antinu(samplekey));
/*
GGM CC1ppip samples
*/
} else
#endif
#ifndef __NO_GGM__
if (!name.compare("GGM_CC1ppip_XSec_1DEnu_nu")) {
return (new GGM_CC1ppip_XSec_1DEnu_nu(samplekey));
} else if (!name.compare("GGM_CC1ppip_Evt_1DQ2_nu")) {
return (new GGM_CC1ppip_Evt_1DQ2_nu(samplekey));
/*
MiniBooNE Samples
*/
/*
CCQE
*/
} else
#endif
#ifndef __NO_MiniBooNE__
if (!name.compare("MiniBooNE_CCQE_XSec_1DQ2_nu") ||
!name.compare("MiniBooNE_CCQELike_XSec_1DQ2_nu")) {
return (new MiniBooNE_CCQE_XSec_1DQ2_nu(samplekey));
} else if (!name.compare("MiniBooNE_CCQE_XSec_1DQ2_antinu") ||
!name.compare("MiniBooNE_CCQELike_XSec_1DQ2_antinu") ||
!name.compare("MiniBooNE_CCQE_CTarg_XSec_1DQ2_antinu")) {
return (new MiniBooNE_CCQE_XSec_1DQ2_antinu(samplekey));
} else if (!name.compare("MiniBooNE_CCQE_XSec_2DTcos_nu") ||
!name.compare("MiniBooNE_CCQELike_XSec_2DTcos_nu")) {
return (new MiniBooNE_CCQE_XSec_2DTcos_nu(samplekey));
} else if (!name.compare("MiniBooNE_CCQE_XSec_2DTcos_antinu") ||
!name.compare("MiniBooNE_CCQELike_XSec_2DTcos_antinu")) {
return (new MiniBooNE_CCQE_XSec_2DTcos_antinu(samplekey));
/*
MiniBooNE CC1pi+
*/
// 1D
} else if (!name.compare("MiniBooNE_CC1pip_XSec_1DEnu_nu")) {
return (new MiniBooNE_CC1pip_XSec_1DEnu_nu(samplekey));
} else if (!name.compare("MiniBooNE_CC1pip_XSec_1DQ2_nu")) {
return (new MiniBooNE_CC1pip_XSec_1DQ2_nu(samplekey));
} else if (!name.compare("MiniBooNE_CC1pip_XSec_1DTpi_nu")) {
return (new MiniBooNE_CC1pip_XSec_1DTpi_nu(samplekey));
} else if (!name.compare("MiniBooNE_CC1pip_XSec_1DTu_nu")) {
return (new MiniBooNE_CC1pip_XSec_1DTu_nu(samplekey));
// 2D
} else if (!name.compare("MiniBooNE_CC1pip_XSec_2DQ2Enu_nu")) {
return (new MiniBooNE_CC1pip_XSec_2DQ2Enu_nu(samplekey));
} else if (!name.compare("MiniBooNE_CC1pip_XSec_2DTpiCospi_nu")) {
return (new MiniBooNE_CC1pip_XSec_2DTpiCospi_nu(samplekey));
} else if (!name.compare("MiniBooNE_CC1pip_XSec_2DTpiEnu_nu")) {
return (new MiniBooNE_CC1pip_XSec_2DTpiEnu_nu(samplekey));
} else if (!name.compare("MiniBooNE_CC1pip_XSec_2DTuCosmu_nu")) {
return (new MiniBooNE_CC1pip_XSec_2DTuCosmu_nu(samplekey));
} else if (!name.compare("MiniBooNE_CC1pip_XSec_2DTuEnu_nu")) {
return (new MiniBooNE_CC1pip_XSec_2DTuEnu_nu(samplekey));
/*
MiniBooNE CC1pi0
*/
} else if (!name.compare("MiniBooNE_CC1pi0_XSec_1DEnu_nu")) {
return (new MiniBooNE_CC1pi0_XSec_1DEnu_nu(samplekey));
} else if (!name.compare("MiniBooNE_CC1pi0_XSec_1DQ2_nu")) {
return (new MiniBooNE_CC1pi0_XSec_1DQ2_nu(samplekey));
} else if (!name.compare("MiniBooNE_CC1pi0_XSec_1DTu_nu")) {
return (new MiniBooNE_CC1pi0_XSec_1DTu_nu(samplekey));
} else if (!name.compare("MiniBooNE_CC1pi0_XSec_1Dcosmu_nu")) {
return (new MiniBooNE_CC1pi0_XSec_1Dcosmu_nu(samplekey));
} else if (!name.compare("MiniBooNE_CC1pi0_XSec_1Dcospi0_nu")) {
return (new MiniBooNE_CC1pi0_XSec_1Dcospi0_nu(samplekey));
} else if (!name.compare("MiniBooNE_CC1pi0_XSec_1Dppi0_nu")) {
return (new MiniBooNE_CC1pi0_XSec_1Dppi0_nu(samplekey));
} else if (!name.compare("MiniBooNE_NC1pi0_XSec_1Dcospi0_antinu") ||
!name.compare("MiniBooNE_NC1pi0_XSec_1Dcospi0_rhc")) {
return (new MiniBooNE_NC1pi0_XSec_1Dcospi0_antinu(samplekey));
} else if (!name.compare("MiniBooNE_NC1pi0_XSec_1Dcospi0_nu") ||
!name.compare("MiniBooNE_NC1pi0_XSec_1Dcospi0_fhc")) {
return (new MiniBooNE_NC1pi0_XSec_1Dcospi0_nu(samplekey));
} else if (!name.compare("MiniBooNE_NC1pi0_XSec_1Dppi0_antinu") ||
!name.compare("MiniBooNE_NC1pi0_XSec_1Dppi0_rhc")) {
return (new MiniBooNE_NC1pi0_XSec_1Dppi0_antinu(samplekey));
} else if (!name.compare("MiniBooNE_NC1pi0_XSec_1Dppi0_nu") ||
!name.compare("MiniBooNE_NC1pi0_XSec_1Dppi0_fhc")) {
return (new MiniBooNE_NC1pi0_XSec_1Dppi0_nu(samplekey));
/*
MiniBooNE NCEL
*/
} else if (!name.compare("MiniBooNE_NCEL_XSec_Treco_nu")) {
return (new MiniBooNE_NCEL_XSec_Treco_nu(samplekey));
} else
#endif
#ifndef __NO_MicroBooNE__
/*
MicroBooNE Samples
*/
/*
MicroBooNE CCinclusive
*/
if (!name.compare("MicroBooNE_CCInc_XSec_2DPcos_nu")) {
return (new MicroBooNE_CCInc_XSec_2DPcos_nu(samplekey));
} else
#endif
#ifndef __NO_MINERvA__
/*
MINERvA Samples
*/
if (!name.compare("MINERvA_CCQE_XSec_1DQ2_nu") ||
!name.compare("MINERvA_CCQE_XSec_1DQ2_nu_20deg") ||
!name.compare("MINERvA_CCQE_XSec_1DQ2_nu_oldflux") ||
!name.compare("MINERvA_CCQE_XSec_1DQ2_nu_20deg_oldflux")) {
return (new MINERvA_CCQE_XSec_1DQ2_nu(samplekey));
} else if (!name.compare("MINERvA_CCQE_XSec_1DQ2_antinu") ||
!name.compare("MINERvA_CCQE_XSec_1DQ2_antinu_20deg") ||
!name.compare("MINERvA_CCQE_XSec_1DQ2_antinu_oldflux") ||
!name.compare("MINERvA_CCQE_XSec_1DQ2_antinu_20deg_oldflux")) {
return (new MINERvA_CCQE_XSec_1DQ2_antinu(samplekey));
} else if (!name.compare("MINERvA_CCQE_XSec_1DQ2_joint_oldflux") ||
!name.compare("MINERvA_CCQE_XSec_1DQ2_joint_20deg_oldflux") ||
!name.compare("MINERvA_CCQE_XSec_1DQ2_joint") ||
!name.compare("MINERvA_CCQE_XSec_1DQ2_joint_20deg")) {
return (new MINERvA_CCQE_XSec_1DQ2_joint(samplekey));
} else if (!name.compare("MINERvA_CC0pi_XSec_1DEe_nue")) {
return (new MINERvA_CC0pi_XSec_1DEe_nue(samplekey));
} else if (!name.compare("MINERvA_CC0pi_XSec_1DQ2_nue")) {
return (new MINERvA_CC0pi_XSec_1DQ2_nue(samplekey));
} else if (!name.compare("MINERvA_CC0pi_XSec_1DThetae_nue")) {
return (new MINERvA_CC0pi_XSec_1DThetae_nue(samplekey));
} else if (!name.compare("MINERvA_CC0pinp_STV_XSec_1Dpmu_nu") ||
!name.compare("MINERvA_CC0pinp_STV_XSec_1Dthmu_nu") ||
!name.compare("MINERvA_CC0pinp_STV_XSec_1Dpprot_nu") ||
!name.compare("MINERvA_CC0pinp_STV_XSec_1Dthprot_nu") ||
!name.compare("MINERvA_CC0pinp_STV_XSec_1Dpnreco_nu") ||
!name.compare("MINERvA_CC0pinp_STV_XSec_1Ddalphat_nu") ||
!name.compare("MINERvA_CC0pinp_STV_XSec_1Ddpt_nu") ||
!name.compare("MINERvA_CC0pinp_STV_XSec_1Ddphit_nu")) {
return (new MINERvA_CC0pinp_STV_XSec_1D_nu(samplekey));
} else if (!name.compare("MINERvA_CC0pi_XSec_1DQ2_nu_proton")) {
return (new MINERvA_CC0pi_XSec_1DQ2_nu_proton(samplekey));
} else if (!name.compare("MINERvA_CC0pi_XSec_1DQ2_TgtC_nu") ||
!name.compare("MINERvA_CC0pi_XSec_1DQ2_TgtCH_nu") ||
!name.compare("MINERvA_CC0pi_XSec_1DQ2_TgtFe_nu") ||
!name.compare("MINERvA_CC0pi_XSec_1DQ2_TgtPb_nu")) {
return (new MINERvA_CC0pi_XSec_1DQ2_Tgt_nu(samplekey));
} else if (!name.compare("MINERvA_CC0pi_XSec_1DQ2_TgtRatioC_nu") ||
!name.compare("MINERvA_CC0pi_XSec_1DQ2_TgtRatioFe_nu") ||
!name.compare("MINERvA_CC0pi_XSec_1DQ2_TgtRatioPb_nu")) {
return (new MINERvA_CC0pi_XSec_1DQ2_TgtRatio_nu(samplekey));
// Dan Ruterbories measurements of late 2018
} else if (!name.compare("MINERvA_CC0pi_XSec_2Dptpz_nu")) {
return (new MINERvA_CC0pi_XSec_2D_nu(samplekey));
} else if (!name.compare("MINERvA_CC0pi_XSec_1Dpt_nu") ||
!name.compare("MINERvA_CC0pi_XSec_1Dpz_nu") ||
!name.compare("MINERvA_CC0pi_XSec_1DQ2QE_nu") ||
!name.compare("MINERvA_CC0pi_XSec_1DEnuQE_nu")) {
return (new MINERvA_CC0pi_XSec_1D_2018_nu(samplekey));
// C. Patrick's early 2018 measurements
} else if (!name.compare("MINERvA_CC0pi_XSec_2Dptpz_antinu") ||
!name.compare("MINERvA_CC0pi_XSec_2DQ2QEEnuQE_antinu") ||
!name.compare("MINERvA_CC0pi_XSec_2DQ2QEEnuTrue_antinu")) {
return (new MINERvA_CC0pi_XSec_2D_antinu(samplekey));
/*
CC1pi+
*/
// DONE
} else if (!name.compare("MINERvA_CC1pip_XSec_1DTpi_nu") ||
!name.compare("MINERvA_CC1pip_XSec_1DTpi_nu_20deg") ||
!name.compare("MINERvA_CC1pip_XSec_1DTpi_nu_fluxcorr") ||
!name.compare("MINERvA_CC1pip_XSec_1DTpi_nu_20deg_fluxcorr")) {
return (new MINERvA_CC1pip_XSec_1DTpi_nu(samplekey));
// DONE
} else if (!name.compare("MINERvA_CC1pip_XSec_1Dth_nu") ||
!name.compare("MINERvA_CC1pip_XSec_1Dth_nu_20deg") ||
!name.compare("MINERvA_CC1pip_XSec_1Dth_nu_fluxcorr") ||
!name.compare("MINERvA_CC1pip_XSec_1Dth_nu_20deg_fluxcorr")) {
return (new MINERvA_CC1pip_XSec_1Dth_nu(samplekey));
} else if (!name.compare("MINERvA_CC1pip_XSec_1DTpi_nu_2017") ||
!name.compare("MINERvA_CC1pip_XSec_1Dth_nu_2017") ||
!name.compare("MINERvA_CC1pip_XSec_1Dpmu_nu_2017") ||
!name.compare("MINERvA_CC1pip_XSec_1Dthmu_nu_2017") ||
!name.compare("MINERvA_CC1pip_XSec_1DQ2_nu_2017") ||
!name.compare("MINERvA_CC1pip_XSec_1DEnu_nu_2017")) {
return (new MINERvA_CC1pip_XSec_1D_2017Update(samplekey));
/*
CCNpi+
*/
} else if (!name.compare("MINERvA_CCNpip_XSec_1Dth_nu") ||
!name.compare("MINERvA_CCNpip_XSec_1Dth_nu_2015") ||
!name.compare("MINERvA_CCNpip_XSec_1Dth_nu_2016") ||
!name.compare("MINERvA_CCNpip_XSec_1Dth_nu_2015_20deg") ||
!name.compare("MINERvA_CCNpip_XSec_1Dth_nu_2015_fluxcorr") ||
!name.compare("MINERvA_CCNpip_XSec_1Dth_nu_2015_20deg_fluxcorr")) {
return (new MINERvA_CCNpip_XSec_1Dth_nu(samplekey));
} else if (!name.compare("MINERvA_CCNpip_XSec_1DTpi_nu") ||
!name.compare("MINERvA_CCNpip_XSec_1DTpi_nu_2015") ||
!name.compare("MINERvA_CCNpip_XSec_1DTpi_nu_2016") ||
!name.compare("MINERvA_CCNpip_XSec_1DTpi_nu_2015_20deg") ||
!name.compare("MINERvA_CCNpip_XSec_1DTpi_nu_2015_fluxcorr") ||
!name.compare(
"MINERvA_CCNpip_XSec_1DTpi_nu_2015_20deg_fluxcorr")) {
return (new MINERvA_CCNpip_XSec_1DTpi_nu(samplekey));
} else if (!name.compare("MINERvA_CCNpip_XSec_1Dthmu_nu")) {
return (new MINERvA_CCNpip_XSec_1Dthmu_nu(samplekey));
} else if (!name.compare("MINERvA_CCNpip_XSec_1Dpmu_nu")) {
return (new MINERvA_CCNpip_XSec_1Dpmu_nu(samplekey));
} else if (!name.compare("MINERvA_CCNpip_XSec_1DQ2_nu")) {
return (new MINERvA_CCNpip_XSec_1DQ2_nu(samplekey));
} else if (!name.compare("MINERvA_CCNpip_XSec_1DEnu_nu")) {
return (new MINERvA_CCNpip_XSec_1DEnu_nu(samplekey));
/*
MINERvA CC1pi0 anti-nu
*/
// Done
} else if (!name.compare("MINERvA_CC1pi0_XSec_1Dth_antinu") ||
!name.compare("MINERvA_CC1pi0_XSec_1Dth_antinu_2015") ||
!name.compare("MINERvA_CC1pi0_XSec_1Dth_antinu_2016") ||
!name.compare("MINERvA_CC1pi0_XSec_1Dth_antinu_fluxcorr") ||
!name.compare("MINERvA_CC1pi0_XSec_1Dth_antinu_2015_fluxcorr") ||
!name.compare("MINERvA_CC1pi0_XSec_1Dth_antinu_2016_fluxcorr")) {
return (new MINERvA_CC1pi0_XSec_1Dth_antinu(samplekey));
} else if (!name.compare("MINERvA_CC1pi0_XSec_1Dppi0_antinu") ||
!name.compare("MINERvA_CC1pi0_XSec_1Dppi0_antinu_fluxcorr")) {
return (new MINERvA_CC1pi0_XSec_1Dppi0_antinu(samplekey));
} else if (!name.compare("MINERvA_CC1pi0_XSec_1DTpi0_antinu")) {
return (new MINERvA_CC1pi0_XSec_1DTpi0_antinu(samplekey));
// Done
} else if (!name.compare("MINERvA_CC1pi0_XSec_1DQ2_antinu")) {
return (new MINERvA_CC1pi0_XSec_1DQ2_antinu(samplekey));
// Done
} else if (!name.compare("MINERvA_CC1pi0_XSec_1Dthmu_antinu")) {
return (new MINERvA_CC1pi0_XSec_1Dthmu_antinu(samplekey));
// Done
} else if (!name.compare("MINERvA_CC1pi0_XSec_1Dpmu_antinu")) {
return (new MINERvA_CC1pi0_XSec_1Dpmu_antinu(samplekey));
// Done
} else if (!name.compare("MINERvA_CC1pi0_XSec_1DEnu_antinu")) {
return (new MINERvA_CC1pi0_XSec_1DEnu_antinu(samplekey));
// MINERvA CC1pi0 nu
} else if (!name.compare("MINERvA_CC1pi0_XSec_1DTpi_nu") ||
!name.compare("MINERvA_CC1pi0_XSec_1Dth_nu") ||
!name.compare("MINERvA_CC1pi0_XSec_1Dpmu_nu") ||
!name.compare("MINERvA_CC1pi0_XSec_1Dthmu_nu") ||
!name.compare("MINERvA_CC1pi0_XSec_1DQ2_nu") ||
!name.compare("MINERvA_CC1pi0_XSec_1DEnu_nu") ||
!name.compare("MINERvA_CC1pi0_XSec_1DWexp_nu") ||
!name.compare("MINERvA_CC1pi0_XSec_1DPPi0Mass_nu") ||
!name.compare("MINERvA_CC1pi0_XSec_1DPPi0MassDelta_nu") ||
!name.compare("MINERvA_CC1pi0_XSec_1DCosAdler_nu") ||
!name.compare("MINERvA_CC1pi0_XSec_1DPhiAdler_nu")) {
return (new MINERvA_CC1pi0_XSec_1D_nu(samplekey));
/*
CCINC
*/
} else if (!name.compare("MINERvA_CCinc_XSec_2DEavq3_nu")) {
return (new MINERvA_CCinc_XSec_2DEavq3_nu(samplekey));
} else if (!name.compare("MINERvA_CCinc_XSec_1Dx_ratio_C12_CH") ||
!name.compare("MINERvA_CCinc_XSec_1Dx_ratio_Fe56_CH") ||
!name.compare("MINERvA_CCinc_XSec_1Dx_ratio_Pb208_CH")) {
return (new MINERvA_CCinc_XSec_1Dx_ratio(samplekey));
} else if (!name.compare("MINERvA_CCinc_XSec_1DEnu_ratio_C12_CH") ||
!name.compare("MINERvA_CCinc_XSec_1DEnu_ratio_Fe56_CH") ||
!name.compare("MINERvA_CCinc_XSec_1DEnu_ratio_Pb208_CH")) {
return (new MINERvA_CCinc_XSec_1DEnu_ratio(samplekey));
/*
CCDIS
*/
} else if (!name.compare("MINERvA_CCDIS_XSec_1Dx_ratio_C12_CH") ||
!name.compare("MINERvA_CCDIS_XSec_1Dx_ratio_Fe56_CH") ||
!name.compare("MINERvA_CCDIS_XSec_1Dx_ratio_Pb208_CH")) {
return (new MINERvA_CCDIS_XSec_1Dx_ratio(samplekey));
} else if (!name.compare("MINERvA_CCDIS_XSec_1DEnu_ratio_C12_CH") ||
!name.compare("MINERvA_CCDIS_XSec_1DEnu_ratio_Fe56_CH") ||
!name.compare("MINERvA_CCDIS_XSec_1DEnu_ratio_Pb208_CH")) {
return (new MINERvA_CCDIS_XSec_1DEnu_ratio(samplekey));
/*
CC-COH
*/
} else if (!name.compare("MINERvA_CCCOHPI_XSec_1DEnu_nu")) {
return (new MINERvA_CCCOHPI_XSec_1DEnu_nu(samplekey));
} else if (!name.compare("MINERvA_CCCOHPI_XSec_1DEpi_nu")) {
return (new MINERvA_CCCOHPI_XSec_1DEpi_nu(samplekey));
} else if (!name.compare("MINERvA_CCCOHPI_XSec_1Dth_nu")) {
return (new MINERvA_CCCOHPI_XSec_1Dth_nu(samplekey));
} else if (!name.compare("MINERvA_CCCOHPI_XSec_1DQ2_nu")) {
return (new MINERvA_CCCOHPI_XSec_1DQ2_nu(samplekey));
} else if (!name.compare("MINERvA_CCCOHPI_XSec_1DEnu_antinu")) {
return (new MINERvA_CCCOHPI_XSec_1DEnu_antinu(samplekey));
} else if (!name.compare("MINERvA_CCCOHPI_XSec_1DEpi_antinu")) {
return (new MINERvA_CCCOHPI_XSec_1DEpi_antinu(samplekey));
} else if (!name.compare("MINERvA_CCCOHPI_XSec_1Dth_antinu")) {
return (new MINERvA_CCCOHPI_XSec_1Dth_antinu(samplekey));
} else if (!name.compare("MINERvA_CCCOHPI_XSec_1DQ2_antinu")) {
return (new MINERvA_CCCOHPI_XSec_1DQ2_antinu(samplekey));
} else if (!name.compare("MINERvA_CCCOHPI_XSec_1DEnu_joint")) {
return (new MINERvA_CCCOHPI_XSec_joint(samplekey));
} else if (!name.compare("MINERvA_CCCOHPI_XSec_1DEpi_joint")) {
return (new MINERvA_CCCOHPI_XSec_joint(samplekey));
} else if (!name.compare("MINERvA_CCCOHPI_XSec_1Dth_joint")) {
return (new MINERvA_CCCOHPI_XSec_joint(samplekey));
} else if (!name.compare("MINERvA_CCCOHPI_XSec_1DQ2_joint")) {
return (new MINERvA_CCCOHPI_XSec_joint(samplekey));
/*
T2K Samples
*/
} else
#endif
#ifndef __NO_T2K__
if (!name.compare("T2K_CC0pi_XSec_2DPcos_nu_I")) {
return (new T2K_CC0pi_XSec_2DPcos_nu_I(samplekey));
} else if (!name.compare("T2K_CC0pi_XSec_2DPcos_nu_II")) {
return (new T2K_CC0pi_XSec_2DPcos_nu_II(samplekey));
} else if (!name.compare("T2K_CCinc_XSec_2DPcos_nu_nonuniform")) {
return (new T2K_CCinc_XSec_2DPcos_nu_nonuniform(samplekey));
/*
T2K CC1pi+ CH samples
*/
// Comment these out for now because we don't have the proper data
} else if (!name.compare("T2K_CC1pip_CH_XSec_2Dpmucosmu_nu")) {
return (new T2K_CC1pip_CH_XSec_2Dpmucosmu_nu(samplekey));
} else if (!name.compare("T2K_CC1pip_CH_XSec_1Dppi_nu")) {
return (new T2K_CC1pip_CH_XSec_1Dppi_nu(samplekey));
} else if (!name.compare("T2K_CC1pip_CH_XSec_1Dthpi_nu")) {
return (new T2K_CC1pip_CH_XSec_1Dthpi_nu(samplekey));
} else if (!name.compare("T2K_CC1pip_CH_XSec_1Dthmupi_nu")) {
return (new T2K_CC1pip_CH_XSec_1Dthmupi_nu(samplekey));
} else if (!name.compare("T2K_CC1pip_CH_XSec_1DQ2_nu")) {
return (new T2K_CC1pip_CH_XSec_1DQ2_nu(samplekey));
} else if (!name.compare("T2K_CC1pip_CH_XSec_1DAdlerPhi_nu")) {
return (new T2K_CC1pip_CH_XSec_1DAdlerPhi_nu(samplekey));
} else if (!name.compare("T2K_CC1pip_CH_XSec_1DCosThAdler_nu")) {
return (new T2K_CC1pip_CH_XSec_1DCosThAdler_nu(samplekey));
// Maybe something for the future: were in Raquel's thesis
//} else if (!name.compare("T2K_CC1pip_CH_XSec_1Dq3_nu")) {
// return (new T2K_CC1pip_CH_XSec_1Dq3_nu(file, rw, type, fkdt));
//} else if (!name.compare("T2K_CC1pip_CH_XSec_1Dthq3pi_nu")) {
// return (new T2K_CC1pip_CH_XSec_1Dthq3pi_nu(file, rw, type, fkdt));
//} else if (!name.compare("T2K_CC1pip_CH_XSec_1DWrec_nu")) {
// return (new T2K_CC1pip_CH_XSec_1DWrec_nu(file, rw, type, fkdt));
/*
T2K CC1pi+ H2O samples
*/
} else if (!name.compare("T2K_CC1pip_H2O_XSec_1DEnuDelta_nu")) {
return (new T2K_CC1pip_H2O_XSec_1DEnuDelta_nu(samplekey));
} else if (!name.compare("T2K_CC1pip_H2O_XSec_1DEnuMB_nu")) {
return (new T2K_CC1pip_H2O_XSec_1DEnuMB_nu(samplekey));
} else if (!name.compare("T2K_CC1pip_H2O_XSec_1Dcosmu_nu")) {
return (new T2K_CC1pip_H2O_XSec_1Dcosmu_nu(samplekey));
} else if (!name.compare("T2K_CC1pip_H2O_XSec_1Dcosmupi_nu")) {
return (new T2K_CC1pip_H2O_XSec_1Dcosmupi_nu(samplekey));
} else if (!name.compare("T2K_CC1pip_H2O_XSec_1Dcospi_nu")) {
return (new T2K_CC1pip_H2O_XSec_1Dcospi_nu(samplekey));
} else if (!name.compare("T2K_CC1pip_H2O_XSec_1Dpmu_nu")) {
return (new T2K_CC1pip_H2O_XSec_1Dpmu_nu(samplekey));
} else if (!name.compare("T2K_CC1pip_H2O_XSec_1Dppi_nu")) {
return (new T2K_CC1pip_H2O_XSec_1Dppi_nu(samplekey));
/*
T2K CC0pi + np CH samples
*/
} else if (!name.compare("T2K_CC0pinp_STV_XSec_1Ddpt_nu")) {
return (new T2K_CC0pinp_STV_XSec_1Ddpt_nu(samplekey));
} else if (!name.compare("T2K_CC0pinp_STV_XSec_1Ddphit_nu")) {
return (new T2K_CC0pinp_STV_XSec_1Ddphit_nu(samplekey));
} else if (!name.compare("T2K_CC0pinp_STV_XSec_1Ddat_nu")) {
return (new T2K_CC0pinp_STV_XSec_1Ddat_nu(samplekey));
} else if (!name.compare("T2K_CC0pi1p_XSec_3DPcoscos_nu_nonuniform")) {
return (new T2K_CC0pi1p_XSec_3DPcoscos_nu_nonuniform(samplekey));
} else if (!name.compare("T2K_CC0pinp_ifk_XSec_3Dinfp_nu")) {
return (new T2K_CC0pinp_ifk_XSec_3Dinfp_nu(samplekey));
} else if (!name.compare("T2K_CC0pinp_ifk_XSec_3Dinfa_nu")) {
return (new T2K_CC0pinp_ifk_XSec_3Dinfa_nu(samplekey));
} else if (!name.compare("T2K_CC0pinp_ifk_XSec_3Dinfip_nu")) {
return (new T2K_CC0pinp_ifk_XSec_3Dinfip_nu(samplekey));
// SciBooNE COH studies
} else
#endif
#ifndef __NO_SciBooNE__
if (!name.compare("SciBooNE_CCCOH_STOP_NTrks_nu")) {
return (new SciBooNE_CCCOH_STOP_NTrks_nu(samplekey));
} else if (!name.compare("SciBooNE_CCCOH_1TRK_1DQ2_nu")) {
return (new SciBooNE_CCCOH_1TRK_1DQ2_nu(samplekey));
} else if (!name.compare("SciBooNE_CCCOH_1TRK_1Dpmu_nu")) {
return (new SciBooNE_CCCOH_1TRK_1Dpmu_nu(samplekey));
} else if (!name.compare("SciBooNE_CCCOH_1TRK_1Dthetamu_nu")) {
return (new SciBooNE_CCCOH_1TRK_1Dthetamu_nu(samplekey));
} else if (!name.compare("SciBooNE_CCCOH_MuPr_1DQ2_nu")) {
return (new SciBooNE_CCCOH_MuPr_1DQ2_nu(samplekey));
} else if (!name.compare("SciBooNE_CCCOH_MuPr_1Dpmu_nu")) {
return (new SciBooNE_CCCOH_MuPr_1Dpmu_nu(samplekey));
} else if (!name.compare("SciBooNE_CCCOH_MuPr_1Dthetamu_nu")) {
return (new SciBooNE_CCCOH_MuPr_1Dthetamu_nu(samplekey));
} else if (!name.compare("SciBooNE_CCCOH_MuPiVA_1DQ2_nu")) {
return (new SciBooNE_CCCOH_MuPiVA_1DQ2_nu(samplekey));
} else if (!name.compare("SciBooNE_CCCOH_MuPiVA_1Dpmu_nu")) {
return (new SciBooNE_CCCOH_MuPiVA_1Dpmu_nu(samplekey));
} else if (!name.compare("SciBooNE_CCCOH_MuPiVA_1Dthetamu_nu")) {
return (new SciBooNE_CCCOH_MuPiVA_1Dthetamu_nu(samplekey));
} else if (!name.compare("SciBooNE_CCCOH_MuPiNoVA_1DQ2_nu")) {
return (new SciBooNE_CCCOH_MuPiNoVA_1DQ2_nu(samplekey));
} else if (!name.compare("SciBooNE_CCCOH_MuPiNoVA_1Dthetapr_nu")) {
return (new SciBooNE_CCCOH_MuPiNoVA_1Dthetapr_nu(samplekey));
} else if (!name.compare("SciBooNE_CCCOH_MuPiNoVA_1Dthetapi_nu")) {
return (new SciBooNE_CCCOH_MuPiNoVA_1Dthetapi_nu(samplekey));
} else if (!name.compare("SciBooNE_CCCOH_MuPiNoVA_1Dthetamu_nu")) {
return (new SciBooNE_CCCOH_MuPiNoVA_1Dthetamu_nu(samplekey));
} else if (!name.compare("SciBooNE_CCCOH_MuPiNoVA_1Dpmu_nu")) {
return (new SciBooNE_CCCOH_MuPiNoVA_1Dpmu_nu(samplekey));
} else if (!name.compare("SciBooNE_CCCOH_STOPFINAL_1DQ2_nu")) {
return (new SciBooNE_CCCOH_STOPFINAL_1DQ2_nu(samplekey));
/*
K2K Samples
*/
/*
NC1pi0
*/
} else
#endif
#ifndef __NO_K2K__
if (!name.compare("K2K_NC1pi0_Evt_1Dppi0_nu")) {
return (new K2K_NC1pi0_Evt_1Dppi0_nu(samplekey));
/*
Fake Studies
*/
} else
#endif
if (name.find("ExpMultDist_CCQE_XSec_1D") != std::string::npos &&
name.find("_FakeStudy") != std::string::npos) {
return (
new ExpMultDist_CCQE_XSec_1DVar_FakeStudy(name, file, rw, type, fkdt));
} else if (name.find("ExpMultDist_CCQE_XSec_2D") != std::string::npos &&
name.find("_FakeStudy") != std::string::npos) {
return (
new ExpMultDist_CCQE_XSec_2DVar_FakeStudy(name, file, rw, type, fkdt));
} else if (name.find("GenericFlux_") != std::string::npos) {
return (new GenericFlux_Tester(name, file, rw, type, fkdt));
} else if (name.find("GenericVectors_") != std::string::npos) {
return (new GenericFlux_Vectors(name, file, rw, type, fkdt));
} else if (!name.compare("T2K2017_FakeData")) {
return (new T2K2017_FakeData(samplekey));
} else if (!name.compare("MCStudy_CCQE")) {
return (new MCStudy_CCQEHistograms(name, file, rw, type, fkdt));
} else if (!name.compare("ElectronFlux_FlatTree")) {
return (new ElectronFlux_FlatTree(name, file, rw, type, fkdt));
} else if (name.find("ElectronData_") != std::string::npos) {
return new ElectronScattering_DurhamData(samplekey);
} else if (name.find("MuonValidation_") != std::string::npos) {
return (new MCStudy_MuonValidation(name, file, rw, type, fkdt));
} else if (!name.compare("NIWGOfficialPlots")) {
return (new OfficialNIWGPlots(samplekey));
} else if (!name.compare("Simple_Osc")) {
return (new Simple_Osc(samplekey));
} else if (!name.compare("Smear_SVDUnfold_Propagation_Osc")) {
return (new Smear_SVDUnfold_Propagation_Osc(samplekey));
} else {
NUIS_ABORT("Error: No such sample: " << name << std::endl);
}
// Return NULL if no sample loaded.
return NULL;
}
} // namespace SampleUtils
diff --git a/src/FitBase/MeasurementBase.cxx b/src/FitBase/MeasurementBase.cxx
index 66e0d9d..e59484e 100644
--- a/src/FitBase/MeasurementBase.cxx
+++ b/src/FitBase/MeasurementBase.cxx
@@ -1,597 +1,597 @@
// Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret
/*******************************************************************************
* This file is part of NUISANCE.
*
* NUISANCE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NUISANCE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NUISANCE. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
#include "MeasurementBase.h"
/*
Constructor/Destructors
*/
//********************************************************************
// 2nd Level Constructor (Inherits From MeasurementBase.h)
MeasurementBase::MeasurementBase(void) {
//********************************************************************
fScaleFactor = 1.0;
fMCFilled = false;
fNoData = false;
fInput = NULL;
NSignal = 0;
// Set the default values
// After-wards this gets set in SetupMeasurement
EnuMin = 0.;
EnuMax = 1.E5;
fMeasurementSpeciesType = kSingleSpeciesMeasurement;
fEventVariables = NULL;
fIsJoint = false;
fNPOT = 0xdeadbeef;
fFluxIntegralOverride = 0xdeadbeef;
fTargetVolume = 0xdeadbeef;
fTargetMaterialDensity = 0xdeadbeef;
fEvtRateScaleFactor = 0xdeadbeef;
};
void MeasurementBase::FinaliseMeasurement() {
// Used to setup default data hists, covars, etc.
}
//********************************************************************
// 2nd Level Destructor (Inherits From MeasurementBase.h)
MeasurementBase::~MeasurementBase(){
//********************************************************************
};
//********************************************************************
double MeasurementBase::TotalIntegratedFlux(std::string intOpt, double low,
double high) {
//********************************************************************
// Set Energy Limits
if (low == -9999.9)
low = this->EnuMin;
if (high == -9999.9)
high = this->EnuMax;
return GetInput()->TotalIntegratedFlux(low, high, intOpt);
};
//********************************************************************
double MeasurementBase::PredictedEventRate(std::string intOpt, double low,
double high) {
//********************************************************************
// Set Energy Limits
if (low == -9999.9)
low = this->EnuMin;
if (high == -9999.9)
high = this->EnuMax;
return GetInput()->PredictedEventRate(low, high, intOpt) * 1E-38;
};
//********************************************************************
void MeasurementBase::SetupInputs(std::string inputfile) {
//********************************************************************
// Add this infile to the global manager
if (FitPar::Config().GetParB("EventManager")) {
fInput = FitBase::AddInput(fName, inputfile);
} else {
std::vector<std::string> file_descriptor =
GeneralUtils::ParseToStr(inputfile, ":");
if (file_descriptor.size() != 2) {
NUIS_ABORT("File descriptor had no filetype declaration: \""
<< inputfile << "\". expected \"FILETYPE:file.root\"");
}
InputUtils::InputType inpType =
InputUtils::ParseInputType(file_descriptor[0]);
fInput = InputUtils::CreateInputHandler(fName, inpType, file_descriptor[1]);
}
fNEvents = fInput->GetNEvents();
// Expect INPUTTYPE:FileLocation(s)
std::vector<std::string> file_descriptor =
GeneralUtils::ParseToStr(inputfile, ":");
if (file_descriptor.size() != 2) {
NUIS_ABORT("File descriptor had no filetype declaration: \""
<< inputfile << "\". expected \"FILETYPE:file.root\"");
}
fInputType = InputUtils::ParseInputType(file_descriptor[0]);
fInputFileName = file_descriptor[1];
if (EnuMin == 0 && EnuMax == 1.E5) {
EnuMin = fInput->GetFluxHistogram()->GetBinLowEdge(1);
EnuMax = fInput->GetFluxHistogram()->GetBinLowEdge(
fInput->GetFluxHistogram()->GetNbinsX() + 1);
}
fFluxHist = fInput->GetFluxHistogram();
fEventHist = fInput->GetEventHistogram();
}
//***********************************************
int MeasurementBase::GetInputID() {
//***********************************************
return FitBase::GetInputID(fInputFileName);
}
//***********************************************
SampleSettings MeasurementBase::LoadSampleSettings(nuiskey samplekey) {
//***********************************************
SampleSettings setting = SampleSettings(samplekey);
fName = setting.GetS("name");
// Used as an initial setup function incase we need to do anything here.
NUIS_LOG(SAM, "Loading Sample : " << setting.GetName());
fEvtRateScaleFactor = 0xdeadbeef;
if (!fIsJoint) {
SetupInputs(setting.GetS("input"));
fNPOT = samplekey.Has("NPOT") ? samplekey.GetD("NPOT") : 1;
fFluxIntegralOverride = samplekey.Has("FluxIntegralOverride")
? samplekey.GetD("FluxIntegralOverride")
: 0xdeadbeef;
fTargetVolume = samplekey.Has("TargetVolume")
? samplekey.GetD("TargetVolume")
: 0xdeadbeef;
fTargetMaterialDensity = samplekey.Has("TargetMaterialDensity")
? samplekey.GetD("TargetMaterialDensity")
: 0xdeadbeef;
if ((fTargetVolume != 0xdeadbeef) &&
(fTargetMaterialDensity != 0xdeadbeef)) {
double TargetMass_kg = fTargetVolume * fTargetMaterialDensity;
double NNucleons = TargetMass_kg / PhysConst::mass_nucleon_kg;
double NNeutrinos =
((fFluxIntegralOverride == 0xdeadbeef) ? TotalIntegratedFlux()
: fFluxIntegralOverride) *
fNPOT;
fEvtRateScaleFactor = NNeutrinos * NNucleons;
NUIS_LOG(SAM, "\tEvent rate prediction : ");
NUIS_LOG(SAM, "\t\tTarget volume : " << fTargetVolume << " m^3");
NUIS_LOG(SAM, "\t\tTarget density : " << fTargetMaterialDensity << " kg/m^3");
NUIS_LOG(SAM, "\t\tTarget mass : " << TargetMass_kg << " kg");
NUIS_LOG(SAM, "\t\tNTarget Nucleons : " << NNucleons);
if ((fNPOT != 1)) {
NUIS_LOG(SAM, "\t\tTotal POT : " << fNPOT);
}
NUIS_LOG(SAM, "\t\tNNeutrinos : "
<< NNeutrinos << ((fNPOT != 1) ? " /cm^2" : " /POT /cm^2"));
NUIS_LOG(SAM, "\t\tXSec -> EvtRate scale factor : " << fEvtRateScaleFactor);
}
}
return setting;
}
//***********************************************
SampleSettings MeasurementBase::LoadSampleSettings(std::string name,
std::string input,
std::string type) {
//***********************************************
nuiskey samplekey = Config::CreateKey("sample");
samplekey.SetS("name", name);
samplekey.SetS("input", input);
samplekey.SetS("type", type);
return LoadSampleSettings(samplekey);
}
void MeasurementBase::FinaliseSampleSettings() {
EnuMin = fSettings.GetD("enu_min");
EnuMax = fSettings.GetD("enu_max");
}
//***********************************************
void MeasurementBase::Reconfigure() {
//***********************************************
NUIS_LOG(REC, " Reconfiguring sample " << fName);
// Reset Histograms
ResetExtraHistograms();
AutoResetExtraTH1();
this->ResetAll();
// FitEvent* cust_event = fInput->GetEventPointer();
int fNEvents = fInput->GetNEvents();
int countwidth = (fNEvents / 5);
// MAIN EVENT LOOP
FitEvent *cust_event = fInput->FirstNuisanceEvent();
int i = 0;
int npassed = 0;
while (cust_event) {
cust_event->RWWeight = fRW->CalcWeight(cust_event);
cust_event->Weight = cust_event->RWWeight * cust_event->InputWeight;
Weight = cust_event->Weight;
// Initialize
fXVar = -999.9;
fYVar = -999.9;
fZVar = -999.9;
Signal = false;
Mode = cust_event->Mode;
// Extract Measurement Variables
this->FillEventVariables(cust_event);
Signal = this->isSignal(cust_event);
if (Signal)
npassed++;
GetBox()->SetX(fXVar);
GetBox()->SetY(fYVar);
GetBox()->SetZ(fZVar);
GetBox()->SetMode(Mode);
// GetBox()->fSignal = Signal;
// Fill Histogram Values
GetBox()->FillBoxFromEvent(cust_event);
// this->FillExtraHistograms(GetBox(), Weight);
this->FillHistogramsFromBox(GetBox(), Weight);
// Print Out
if (LOG_LEVEL(REC) && countwidth > 0 && !(i % countwidth)) {
std::stringstream ss("");
ss.unsetf(std::ios_base::fixed);
ss << std::setw(7) << std::right << i << "/" << fNEvents << " events ("
<< std::setw(2) << int(double(i) / double(fNEvents) * 100.) + 1
<< std::left << std::setw(5) << "%) "
<< "[S,X,Y,Z,M,W] = [" << std::fixed << std::setprecision(2)
<< std::right << Signal << ", " << std::setw(5) << fXVar << ", "
<< std::setw(5) << fYVar << ", " << std::setw(5) << fYVar << ", "
<< std::setw(3) << (int)Mode << ", " << std::setw(5) << Weight << "] "
<< std::endl;
NUIS_LOG(SAM, ss.str());
}
// iterate
cust_event = fInput->NextNuisanceEvent();
i++;
}
NUIS_LOG(SAM, npassed << "/" << fNEvents << " passed selection ");
if (npassed == 0) {
NUIS_LOG(SAM, "WARNING: NO EVENTS PASSED SELECTION!");
}
NUIS_LOG(REC,
std::setw(10) << std::right << NSignal << "/" << fNEvents
<< " events passed selection + binning after reweight");
// Finalise Histograms
fMCFilled = true;
this->ConvertEventRates();
}
void MeasurementBase::FillHistogramsFromBox(MeasurementVariableBox *var,
double weight) {
fXVar = var->GetX();
fYVar = var->GetY();
fZVar = var->GetZ();
Weight = weight;
fEventVariables = var;
FillHistograms();
FillExtraHistograms(var, weight);
}
void MeasurementBase::FillHistograms(double weight) {
Weight = weight * GetBox()->GetSampleWeight();
FillHistograms();
FillExtraHistograms(GetBox(), Weight);
}
MeasurementVariableBox *MeasurementBase::FillVariableBox(FitEvent *event) {
GetBox()->Reset();
Mode = event->Mode;
Weight = 1.0; // event->Weight;
this->FillEventVariables(event);
Signal = this->isSignal(event);
GetBox()->FillBoxFromEvent(event);
GetBox()->SetX(fXVar);
GetBox()->SetY(fYVar);
GetBox()->SetZ(fZVar);
GetBox()->SetMode(event->Mode);
GetBox()->SetSampleWeight(Weight);
// GetBox()->fSignal = Signal;
return GetBox();
}
MeasurementVariableBox *MeasurementBase::GetBox() {
if (!fEventVariables)
fEventVariables = CreateBox();
return fEventVariables;
}
//***********************************************
void MeasurementBase::ReconfigureFast() {
//***********************************************
this->Reconfigure();
}
//***********************************************
void MeasurementBase::ConvertEventRates() {
//***********************************************
AutoScaleExtraTH1();
ScaleExtraHistograms(GetBox());
this->ScaleEvents();
double normval = fRW->GetSampleNorm(this->fName);
if (normval < 0.01 or normval > 10.0) {
NUIS_ERR(WRN,
"Norm Value inside MeasurementBase::ConvertEventRates() looks off!");
NUIS_ERR(WRN,
"It could have become out of sync with the minimizer norm list.");
NUIS_ERR(WRN, "Setting it to 1.0");
normval = 1.0;
}
AutoNormExtraTH1(normval);
NormExtraHistograms(GetBox(), normval);
this->ApplyNormScale(normval);
}
//***********************************************
InputHandlerBase *MeasurementBase::GetInput() {
//***********************************************
if (!fInput) {
NUIS_ABORT("MeasurementBase::fInput not set. Please submit your command "
"line options and input cardfile with a bug report to: "
"nuisance@projects.hepforge.org");
}
return fInput;
};
//***********************************************
void MeasurementBase::Renormalise() {
//***********************************************
// Called when the fitter has changed a measurements normalisation but not any
// reweight dials
// Means we don't have to call the time consuming reconfigure when this
// happens.
double norm = fRW->GetDialValue(this->fName + "_norm");
if ((this->fCurrentNorm == 0.0 and norm != 0.0) or not fMCFilled) {
this->ReconfigureFast();
return;
}
if (this->fCurrentNorm == norm)
return;
this->ApplyNormScale(1.0 / this->fCurrentNorm);
this->ApplyNormScale(norm);
return;
};
//***********************************************
void MeasurementBase::SetSignal(bool sig) {
//***********************************************
Signal = sig;
}
//***********************************************
void MeasurementBase::SetSignal(FitEvent *evt) {
//***********************************************
Signal = this->isSignal(evt);
}
//***********************************************
void MeasurementBase::SetWeight(double wght) {
//***********************************************
Weight = wght;
}
//***********************************************
void MeasurementBase::SetMode(int md) {
//***********************************************
Mode = md;
}
//***********************************************
std::vector<TH1 *> MeasurementBase::GetFluxList() {
//***********************************************
return GetInput()->GetFluxList();
}
//***********************************************
std::vector<TH1 *> MeasurementBase::GetEventRateList() {
//***********************************************
return GetInput()->GetEventList();
}
//***********************************************
std::vector<TH1 *> MeasurementBase::GetXSecList() {
//***********************************************
return GetInput()->GetXSecList();
}
void MeasurementBase::ProcessExtraHistograms(int cmd,
MeasurementVariableBox *vars,
double weight) {
// This should be overriden if we have extra histograms!!!
// Add a flag to tell user this...
return;
}
void MeasurementBase::FillExtraHistograms(MeasurementVariableBox *vars,
double weight) {
ProcessExtraHistograms(kCMD_Fill, vars, weight);
}
void MeasurementBase::ScaleExtraHistograms(MeasurementVariableBox *vars) {
ProcessExtraHistograms(kCMD_Scale, vars, 1.0);
}
void MeasurementBase::ResetExtraHistograms() {
ProcessExtraHistograms(kCMD_Reset, NULL, 1.0);
}
void MeasurementBase::NormExtraHistograms(MeasurementVariableBox *vars,
double norm) {
ProcessExtraHistograms(kCMD_Norm, vars, norm);
}
void MeasurementBase::WriteExtraHistograms() {
ProcessExtraHistograms(kCMD_Write, NULL, 1.00);
}
void MeasurementBase::SetAutoProcessTH1(TH1 *hist, int c1, int c2, int c3,
int c4, int c5) {
FakeStack *fake = new FakeStack(hist);
SetAutoProcessTH1(fake, c1, c2, c3, c4,
c5); // Need to add a destroy command!
}
void MeasurementBase::SetAutoProcess(TH1 *hist, int c1, int c2, int c3, int c4,
int c5) {
FakeStack *fake = new FakeStack(hist);
SetAutoProcessTH1(fake, c1, c2, c3, c4,
c5); // Need to add a destroy command!
}
void MeasurementBase::SetAutoProcess(TGraph *g, int c1, int c2, int c3, int c4,
int c5) {
FakeStack *fake = new FakeStack(g);
SetAutoProcessTH1(fake, c1, c2, c3, c4,
c5); // Need to add a destroy command!
}
void MeasurementBase::SetAutoProcess(TF1 *f, int c1, int c2, int c3, int c4,
int c5) {
FakeStack *fake = new FakeStack(f);
SetAutoProcessTH1(fake, c1, c2, c3, c4,
c5); // Need to add a destroy command!
}
void MeasurementBase::SetAutoProcess(StackBase *hist, int c1, int c2, int c3,
int c4, int c5) {
SetAutoProcessTH1(hist, c1, c2, c3, c4, c5);
}
void MeasurementBase::SetAutoProcessTH1(StackBase *hist, int c1, int c2, int c3,
int c4, int c5) {
// Set Defaults
// int ncommands = kCMD_extraplotflags;
int givenflags[5];
givenflags[0] = c1;
givenflags[1] = c2;
givenflags[2] = c3;
givenflags[3] = c4;
givenflags[4] = c5;
fExtraTH1s[hist] = std::vector<int>(5, 0);
// Setup a default one.
if (c1 == -1 && c2 == -1 && c3 == -1 && c4 == -1 && c5 == -1) {
fExtraTH1s[hist][kCMD_Reset] = 1;
fExtraTH1s[hist][kCMD_Scale] = 1;
fExtraTH1s[hist][kCMD_Norm] = 1;
fExtraTH1s[hist][kCMD_Write] = 1;
}
for (int i = 0; i < 5; i++) {
switch (givenflags[i]) {
// Skip over...
case -1:
break;
case kCMD_Reset:
case kCMD_Scale:
case kCMD_Norm:
case kCMD_Write:
fExtraTH1s[hist][givenflags[i]] = 1;
break;
case kCMD_Fill: {
NUIS_ERR(FTL, "Can't auto fill yet!");
break;
}
default:
break;
}
}
}
void MeasurementBase::AutoFillExtraTH1() {
NUIS_ABORT("Can't auto fill yet! it's too inefficent!");
return;
}
void MeasurementBase::AutoResetExtraTH1() {
- for (std::map<StackBase *, std::vector<int>>::iterator iter =
+ for (std::map<StackBase *, std::vector<int> >::iterator iter =
fExtraTH1s.begin();
iter != fExtraTH1s.end(); iter++) {
if (!((*iter).second)[kCMD_Reset])
continue;
(*iter).first->Reset();
}
};
void MeasurementBase::AutoScaleExtraTH1() {
- for (std::map<StackBase *, std::vector<int>>::iterator iter =
+ for (std::map<StackBase *, std::vector<int> >::iterator iter =
fExtraTH1s.begin();
iter != fExtraTH1s.end(); iter++) {
if (!((*iter).second)[kCMD_Scale])
continue;
if (fIsNoWidth) {
(*iter).first->Scale(fScaleFactor);
} else {
(*iter).first->Scale(fScaleFactor, "width");
}
}
};
void MeasurementBase::AutoNormExtraTH1(double norm) {
double sfactor = 0.0;
if (norm != 0.0)
sfactor = 1.0 / norm;
- for (std::map<StackBase *, std::vector<int>>::iterator iter =
+ for (std::map<StackBase *, std::vector<int> >::iterator iter =
fExtraTH1s.begin();
iter != fExtraTH1s.end(); iter++) {
if (!((*iter).second)[kCMD_Norm])
continue;
(*iter).first->Scale(sfactor);
}
};
void MeasurementBase::AutoWriteExtraTH1() {
- for (std::map<StackBase *, std::vector<int>>::iterator iter =
+ for (std::map<StackBase *, std::vector<int> >::iterator iter =
fExtraTH1s.begin();
iter != fExtraTH1s.end(); iter++) {
if (!(((*iter).second)[kCMD_Write]))
continue;
(*iter).first->Write();
}
};
diff --git a/src/MCStudies/GenericFlux_Vectors.cxx b/src/MCStudies/GenericFlux_Vectors.cxx
index b55f58c..1deb7f4 100644
--- a/src/MCStudies/GenericFlux_Vectors.cxx
+++ b/src/MCStudies/GenericFlux_Vectors.cxx
@@ -1,441 +1,441 @@
// Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret
/*******************************************************************************
* This file is part of NUISANCE.
*
* NUISANCE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NUISANCE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NUISANCE. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
#include "GenericFlux_Vectors.h"
GenericFlux_Vectors::GenericFlux_Vectors(std::string name,
std::string inputfile, FitWeight *rw,
std::string type,
std::string fakeDataFile) {
// Measurement Details
fName = name;
eventVariables = NULL;
// Define our energy range for flux calcs
EnuMin = 0.;
EnuMax = 1E10; // Arbritrarily high energy limit
if (Config::HasPar("EnuMin")) {
EnuMin = Config::GetParD("EnuMin");
}
if (Config::HasPar("EnuMax")) {
EnuMax = Config::GetParD("EnuMax");
}
SavePreFSI = Config::Get().GetParB("nuisflat_SavePreFSI");
NUIS_LOG(SAM,
"Running GenericFlux_Vectors saving pre-FSI particles? " << SavePreFSI);
// Set default fitter flags
fIsDiag = true;
fIsShape = false;
fIsRawEvents = false;
// This function will sort out the input files automatically and parse all the
// inputs,flags,etc.
// There may be complex cases where you have to do this by hand, but usually
// this will do.
Measurement1D::SetupMeasurement(inputfile, type, rw, fakeDataFile);
eventVariables = NULL;
// Setup fDataHist as a placeholder
this->fDataHist = new TH1D(("empty_data"), ("empty-data"), 1, 0, 1);
this->SetupDefaultHist();
fFullCovar = StatUtils::MakeDiagonalCovarMatrix(fDataHist);
covar = StatUtils::GetInvert(fFullCovar);
// 1. The generator is organised in SetupMeasurement so it gives the
// cross-section in "per nucleon" units.
// So some extra scaling for a specific measurement may be required. For
// Example to get a "per neutron" measurement on carbon
// which we do here, we have to multiple by the number of nucleons 12 and
// divide by the number of neutrons 6.
// N.B. MeasurementBase::PredictedEventRate includes the 1E-38 factor that is
// often included here in other classes that directly integrate the event
// histogram. This method is used here as it now respects EnuMin and EnuMax
// correctly.
this->fScaleFactor =
(this->PredictedEventRate("width", 0, EnuMax) / double(fNEvents)) /
this->TotalIntegratedFlux("width");
NUIS_LOG(SAM, " Generic Flux Scaling Factor = "
<< fScaleFactor
<< " [= " << (GetEventHistogram()->Integral("width") * 1E-38)
<< "/(" << (fNEvents + 0.) << "*"
<< TotalIntegratedFlux("width") << ")]");
if (fScaleFactor <= 0.0) {
NUIS_ABORT("SCALE FACTOR TOO LOW");
}
// Setup our TTrees
this->AddEventVariablesToTree();
this->AddSignalFlagsToTree();
}
void GenericFlux_Vectors::AddEventVariablesToTree() {
// Setup the TTree to save everything
if (!eventVariables) {
Config::Get().out->cd();
eventVariables = new TTree((this->fName + "_VARS").c_str(),
(this->fName + "_VARS").c_str());
}
NUIS_LOG(SAM, "Adding Event Variables");
eventVariables->Branch("Mode", &Mode, "Mode/I");
eventVariables->Branch("cc", &cc, "cc/B");
eventVariables->Branch("PDGnu", &PDGnu, "PDGnu/I");
eventVariables->Branch("Enu_true", &Enu_true, "Enu_true/F");
eventVariables->Branch("tgt", &tgt, "tgt/I");
eventVariables->Branch("tgta", &tgta, "tgta/I");
eventVariables->Branch("tgtz", &tgtz, "tgtz/I");
eventVariables->Branch("PDGLep", &PDGLep, "PDGLep/I");
eventVariables->Branch("ELep", &ELep, "ELep/F");
eventVariables->Branch("CosLep", &CosLep, "CosLep/F");
// Basic interaction kinematics
eventVariables->Branch("Q2", &Q2, "Q2/F");
eventVariables->Branch("q0", &q0, "q0/F");
eventVariables->Branch("q3", &q3, "q3/F");
eventVariables->Branch("Enu_QE", &Enu_QE, "Enu_QE/F");
eventVariables->Branch("Q2_QE", &Q2_QE, "Q2_QE/F");
eventVariables->Branch("W_nuc_rest", &W_nuc_rest, "W_nuc_rest/F");
eventVariables->Branch("W", &W, "W/F");
eventVariables->Branch("W_genie", &W_genie, "W_genie/F");
eventVariables->Branch("x", &x, "x/F");
eventVariables->Branch("y", &y, "y/F");
eventVariables->Branch("Eav", &Eav, "Eav/F");
eventVariables->Branch("EavAlt", &EavAlt, "EavAlt/F");
eventVariables->Branch("dalphat", &dalphat, "dalphat/F");
eventVariables->Branch("dpt", &dpt, "dpt/F");
eventVariables->Branch("dphit", &dphit, "dphit/F");
eventVariables->Branch("pnreco_C", &pnreco_C, "pnreco_C/F");
// Save outgoing particle vectors
eventVariables->Branch("nfsp", &nfsp, "nfsp/I");
eventVariables->Branch("px", px, "px[nfsp]/F");
eventVariables->Branch("py", py, "py[nfsp]/F");
eventVariables->Branch("pz", pz, "pz[nfsp]/F");
eventVariables->Branch("E", E, "E[nfsp]/F");
eventVariables->Branch("pdg", pdg, "pdg[nfsp]/I");
eventVariables->Branch("pdg_rank", pdg_rank, "pdg_rank[nfsp]/I");
// Save init particle vectors
eventVariables->Branch("ninitp", &ninitp, "ninitp/I");
eventVariables->Branch("px_init", px_init, "px_init[ninitp]/F");
eventVariables->Branch("py_init", py_init, "py_init[ninitp]/F");
eventVariables->Branch("pz_init", pz_init, "pz_init[ninitp]/F");
eventVariables->Branch("E_init", E_init, "E_init[ninitp]/F");
eventVariables->Branch("pdg_init", pdg_init, "pdg_init[ninitp]/I");
// Save pre-FSI vectors
eventVariables->Branch("nvertp", &nvertp, "nvertp/I");
eventVariables->Branch("px_vert", px_vert, "px_vert[nvertp]/F");
eventVariables->Branch("py_vert", py_vert, "py_vert[nvertp]/F");
eventVariables->Branch("pz_vert", pz_vert, "pz_vert[nvertp]/F");
eventVariables->Branch("E_vert", E_vert, "E_vert[nvertp]/F");
eventVariables->Branch("pdg_vert", pdg_vert, "pdg_vert[nvertp]/I");
// Event Scaling Information
eventVariables->Branch("Weight", &Weight, "Weight/F");
eventVariables->Branch("InputWeight", &InputWeight, "InputWeight/F");
eventVariables->Branch("RWWeight", &RWWeight, "RWWeight/F");
// Should be a double because may be 1E-39 and less
eventVariables->Branch("fScaleFactor", &fScaleFactor, "fScaleFactor/D");
// The customs
eventVariables->Branch("CustomWeight", &CustomWeight, "CustomWeight/F");
eventVariables->Branch("CustomWeightArray", CustomWeightArray,
"CustomWeightArray[6]/F");
return;
}
void GenericFlux_Vectors::FillEventVariables(FitEvent *event) {
ResetVariables();
// Fill Signal Variables
FillSignalFlags(event);
NUIS_LOG(DEB, "Filling signal");
// Now fill the information
Mode = event->Mode;
cc = event->IsCC();
// Get the incoming neutrino and outgoing lepton
FitParticle *nu = event->GetBeamPart();
FitParticle *lep = event->GetHMFSAnyLepton();
PDGnu = nu->fPID;
Enu_true = nu->fP.E() / 1E3;
tgt = event->fTargetPDG;
tgta = event->fTargetA;
tgtz = event->fTargetZ;
if (lep != NULL) {
PDGLep = lep->fPID;
ELep = lep->fP.E() / 1E3;
CosLep = cos(nu->fP.Vect().Angle(lep->fP.Vect()));
// Basic interaction kinematics
Q2 = -1 * (nu->fP - lep->fP).Mag2() / 1E6;
q0 = (nu->fP - lep->fP).E() / 1E3;
q3 = (nu->fP - lep->fP).Vect().Mag() / 1E3;
// These assume C12 binding from MINERvA... not ideal
Enu_QE = FitUtils::EnuQErec(lep->fP, CosLep, 34., true);
Q2_QE = FitUtils::Q2QErec(lep->fP, CosLep, 34., true);
Eav = FitUtils::GetErecoil_MINERvA_LowRecoil(event) / 1.E3;
EavAlt = FitUtils::Eavailable(event) / 1.E3;
// Get W_true with assumption of initial state nucleon at rest
float m_n = (float)PhysConst::mass_proton;
// Q2 assuming nucleon at rest
W_nuc_rest = sqrt(-Q2 + 2 * m_n * q0 + m_n * m_n);
// True Q2
W = sqrt(-Q2 + 2 * m_n * q0 + m_n * m_n);
x = Q2 / (2 * m_n * q0);
y = 1 - ELep / Enu_true;
dalphat = FitUtils::Get_STV_dalphat(event, PDGnu, true);
dpt = FitUtils::Get_STV_dpt(event, PDGnu, true);
dphit = FitUtils::Get_STV_dphit(event, PDGnu, true);
pnreco_C = FitUtils::Get_pn_reco_C(event, PDGnu, true);
}
// Loop over the particles and store all the final state particles in a vector
for (UInt_t i = 0; i < event->Npart(); ++i) {
if (event->PartInfo(i)->fIsAlive &&
event->PartInfo(i)->Status() == kFinalState)
partList.push_back(event->PartInfo(i));
if (SavePreFSI && event->fPrimaryVertex[i])
vertList.push_back(event->PartInfo(i));
if (SavePreFSI && event->PartInfo(i)->IsInitialState())
initList.push_back(event->PartInfo(i));
}
// Save outgoing particle vectors
nfsp = (int)partList.size();
- std::map<int, std::vector<std::pair<double, int>>> pdgMap;
+ std::map<int, std::vector<std::pair<double, int> > > pdgMap;
for (int i = 0; i < nfsp; ++i) {
px[i] = partList[i]->fP.X() / 1E3;
py[i] = partList[i]->fP.Y() / 1E3;
pz[i] = partList[i]->fP.Z() / 1E3;
E[i] = partList[i]->fP.E() / 1E3;
pdg[i] = partList[i]->fPID;
pdgMap[pdg[i]].push_back(std::make_pair(partList[i]->fP.Vect().Mag(), i));
}
- for (std::map<int, std::vector<std::pair<double, int>>>::iterator iter =
+ for (std::map<int, std::vector<std::pair<double, int> > >::iterator iter =
pdgMap.begin();
iter != pdgMap.end(); ++iter) {
- std::vector<std::pair<double, int>> thisVect = iter->second;
+ std::vector<std::pair<double, int> > thisVect = iter->second;
std::sort(thisVect.begin(), thisVect.end());
// Now save the order... a bit funky to avoid inverting
int nPart = (int)thisVect.size() - 1;
for (int i = nPart; i >= 0; --i) {
pdg_rank[thisVect[i].second] = nPart - i;
}
}
// Save pre-FSI particles
nvertp = (int)vertList.size();
for (int i = 0; i < nvertp; ++i) {
px_vert[i] = vertList[i]->fP.X() / 1E3;
py_vert[i] = vertList[i]->fP.Y() / 1E3;
pz_vert[i] = vertList[i]->fP.Z() / 1E3;
E_vert[i] = vertList[i]->fP.E() / 1E3;
pdg_vert[i] = vertList[i]->fPID;
}
// Save init particles
ninitp = (int)initList.size();
for (int i = 0; i < ninitp; ++i) {
px_init[i] = initList[i]->fP.X() / 1E3;
py_init[i] = initList[i]->fP.Y() / 1E3;
pz_init[i] = initList[i]->fP.Z() / 1E3;
E_init[i] = initList[i]->fP.E() / 1E3;
pdg_init[i] = initList[i]->fPID;
}
#ifdef __GENIE_ENABLED__
if (event->fType == kGENIE) {
EventRecord *gevent = static_cast<EventRecord *>(event->genie_event->event);
const Interaction *interaction = gevent->Summary();
const Kinematics &kine = interaction->Kine();
double W_genie = kine.W();
}
#endif
// Fill event weights
Weight = event->RWWeight * event->InputWeight;
RWWeight = event->RWWeight;
InputWeight = event->InputWeight;
// And the Customs
CustomWeight = event->CustomWeight;
for (int i = 0; i < 6; ++i) {
CustomWeightArray[i] = event->CustomWeightArray[i];
}
// Fill the eventVariables Tree
eventVariables->Fill();
return;
};
//********************************************************************
void GenericFlux_Vectors::ResetVariables() {
//********************************************************************
cc = false;
// Reset all Function used to extract any variables of interest to the event
Mode = PDGnu = tgt = tgta = tgtz = PDGLep = 0;
Enu_true = ELep = CosLep = Q2 = q0 = q3 = Enu_QE = Q2_QE = W_nuc_rest = W =
x = y = Eav = EavAlt = -999.9;
W_genie = -999;
// Other fun variables
// MINERvA-like ones
dalphat = dpt = dphit = pnreco_C = -999.99;
nfsp = ninitp = nvertp = 0;
for (int i = 0; i < kMAX; ++i) {
px[i] = py[i] = pz[i] = E[i] = -999;
pdg[i] = pdg_rank[i] = 0;
px_init[i] = py_init[i] = pz_init[i] = E_init[i] = -999;
pdg_init[i] = 0;
px_vert[i] = py_vert[i] = pz_vert[i] = E_vert[i] = -999;
pdg_vert[i] = 0;
}
Weight = InputWeight = RWWeight = 0.0;
CustomWeight = 0.0;
for (int i = 0; i < 6; ++i)
CustomWeightArray[i] = 0.0;
partList.clear();
initList.clear();
vertList.clear();
flagCCINC = flagNCINC = flagCCQE = flagCC0pi = flagCCQELike = flagNCEL =
flagNC0pi = flagCCcoh = flagNCcoh = flagCC1pip = flagNC1pip = flagCC1pim =
flagNC1pim = flagCC1pi0 = flagNC1pi0 = false;
}
//********************************************************************
void GenericFlux_Vectors::FillSignalFlags(FitEvent *event) {
//********************************************************************
// Some example flags are given from SignalDef.
// See src/Utils/SignalDef.cxx for more.
int nuPDG = event->PartInfo(0)->fPID;
// Generic signal flags
flagCCINC = SignalDef::isCCINC(event, nuPDG);
flagNCINC = SignalDef::isNCINC(event, nuPDG);
flagCCQE = SignalDef::isCCQE(event, nuPDG);
flagCCQELike = SignalDef::isCCQELike(event, nuPDG);
flagCC0pi = SignalDef::isCC0pi(event, nuPDG);
flagNCEL = SignalDef::isNCEL(event, nuPDG);
flagNC0pi = SignalDef::isNC0pi(event, nuPDG);
flagCCcoh = SignalDef::isCCCOH(event, nuPDG, 211);
flagNCcoh = SignalDef::isNCCOH(event, nuPDG, 111);
flagCC1pip = SignalDef::isCC1pi(event, nuPDG, 211);
flagNC1pip = SignalDef::isNC1pi(event, nuPDG, 211);
flagCC1pim = SignalDef::isCC1pi(event, nuPDG, -211);
flagNC1pim = SignalDef::isNC1pi(event, nuPDG, -211);
flagCC1pi0 = SignalDef::isCC1pi(event, nuPDG, 111);
flagNC1pi0 = SignalDef::isNC1pi(event, nuPDG, 111);
}
void GenericFlux_Vectors::AddSignalFlagsToTree() {
if (!eventVariables) {
Config::Get().out->cd();
eventVariables = new TTree((this->fName + "_VARS").c_str(),
(this->fName + "_VARS").c_str());
}
NUIS_LOG(SAM, "Adding signal flags");
// Signal Definitions from SignalDef.cxx
eventVariables->Branch("flagCCINC", &flagCCINC, "flagCCINC/O");
eventVariables->Branch("flagNCINC", &flagNCINC, "flagNCINC/O");
eventVariables->Branch("flagCCQE", &flagCCQE, "flagCCQE/O");
eventVariables->Branch("flagCC0pi", &flagCC0pi, "flagCC0pi/O");
eventVariables->Branch("flagCCQELike", &flagCCQELike, "flagCCQELike/O");
eventVariables->Branch("flagNCEL", &flagNCEL, "flagNCEL/O");
eventVariables->Branch("flagNC0pi", &flagNC0pi, "flagNC0pi/O");
eventVariables->Branch("flagCCcoh", &flagCCcoh, "flagCCcoh/O");
eventVariables->Branch("flagNCcoh", &flagNCcoh, "flagNCcoh/O");
eventVariables->Branch("flagCC1pip", &flagCC1pip, "flagCC1pip/O");
eventVariables->Branch("flagNC1pip", &flagNC1pip, "flagNC1pip/O");
eventVariables->Branch("flagCC1pim", &flagCC1pim, "flagCC1pim/O");
eventVariables->Branch("flagNC1pim", &flagNC1pim, "flagNC1pim/O");
eventVariables->Branch("flagCC1pi0", &flagCC1pi0, "flagCC1pi0/O");
eventVariables->Branch("flagNC1pi0", &flagNC1pi0, "flagNC1pi0/O");
};
void GenericFlux_Vectors::Write(std::string drawOpt) {
// First save the TTree
eventVariables->Write();
// Save Flux and Event Histograms too
GetInput()->GetFluxHistogram()->Write();
GetInput()->GetEventHistogram()->Write();
return;
}
// Override functions which aren't really necessary
bool GenericFlux_Vectors::isSignal(FitEvent *event) {
(void)event;
return true;
};
void GenericFlux_Vectors::ScaleEvents() { return; }
void GenericFlux_Vectors::ApplyNormScale(float norm) {
this->fCurrentNorm = norm;
return;
}
void GenericFlux_Vectors::FillHistograms() { return; }
void GenericFlux_Vectors::ResetAll() {
eventVariables->Reset();
return;
}
float GenericFlux_Vectors::GetChi2() { return 0.0; }
diff --git a/src/Reweight/LikelihoodWeightEngine.cxx b/src/Reweight/LikelihoodWeightEngine.cxx
index 9bdf0e9..8366fcc 100644
--- a/src/Reweight/LikelihoodWeightEngine.cxx
+++ b/src/Reweight/LikelihoodWeightEngine.cxx
@@ -1,81 +1,81 @@
#include "WeightUtils.h"
#include "LikelihoodWeightEngine.h"
LikelihoodWeightEngine::LikelihoodWeightEngine(std::string name) {
// Setup the NEUT Reweight engien
fCalcName = name;
NUIS_LOG(FIT, "Setting up Likelihood Weight RW : " << fCalcName);
// Set Abs Twk Config
fIsAbsTwk = true;
};
void LikelihoodWeightEngine::IncludeDial(std::string name, double startval) {
// Get NUISANCE Enum
int nuisenum = Reweight::ConvDial(name, kNORM);
// Setup Maps
fEnumIndex[nuisenum]; // = std::vector<size_t>(0);
fNameIndex[name]; // = std::vector<size_t>(0);
// Split by commas
std::vector<std::string> allnames = GeneralUtils::ParseToStr(name, ",");
for (uint i = 0; i < allnames.size(); i++) {
std::string singlename = allnames[i];
// Fill Maps
int index = fValues.size();
fValues.push_back(1.0);
fEnumIndex[nuisenum].push_back(index);
fNameIndex[name].push_back(index);
}
// Set Value if given
if (startval != -999.9) {
SetDialValue(name, startval);
}
};
void LikelihoodWeightEngine::SetDialValue(int nuisenum, double val) {
std::vector<size_t> indices = fEnumIndex[nuisenum];
for (uint i = 0; i < indices.size(); i++) {
fValues[indices[i]] = val;
}
}
void LikelihoodWeightEngine::SetDialValue(std::string name, double val) {
std::vector<size_t> indices = fNameIndex[name];
for (uint i = 0; i < indices.size(); i++) {
fValues[indices[i]] = val;
}
}
double LikelihoodWeightEngine::GetDialValue(std::string name) {
// Check for exact dial names
if (fNameIndex.find(name) != fNameIndex.end()) {
return fValues[fNameIndex[name][0]];
// If not iterate and check entry in one of the keys
} else {
- for (std::map<std::string, std::vector<size_t>>::iterator iter =
+ for (std::map<std::string, std::vector<size_t> >::iterator iter =
fNameIndex.begin();
iter != fNameIndex.end(); iter++) {
std::string keyname = iter->first;
if (keyname.find(name) != std::string::npos) {
return fValues[iter->second[0]];
}
}
}
return -1.0;
}
void LikelihoodWeightEngine::Reconfigure(bool silent) {
// Empty placeholder incase we want print statements...
}
diff --git a/src/Reweight/NIWGWeightEngine.cxx b/src/Reweight/NIWGWeightEngine.cxx
index 2e67e0d..54bc4fd 100644
--- a/src/Reweight/NIWGWeightEngine.cxx
+++ b/src/Reweight/NIWGWeightEngine.cxx
@@ -1,216 +1,216 @@
#include "NIWGWeightEngine.h"
NIWGWeightEngine::NIWGWeightEngine(std::string name) {
#ifdef __NIWG_ENABLED__
#ifdef __NEUT_ENABLED__
// Setup the NEUT Reweight engien
fCalcName = name;
- LOG(FIT) << "Setting up NIWG RW : " << fCalcName << std::endl;
+ NUIS_LOG(FIT, "Setting up NIWG RW : " << fCalcName);
// Create RW Engine suppressing cout
StopTalking();
fNIWGRW = new niwg::rew::NIWGReWeight();
// Get List of Veto Calcs (For Debugging)
std::string rw_engine_list = FitPar::Config().GetParS("FitWeight_fNIWGRW_veto");
bool niwg_2012a = rw_engine_list.find("niwg_2012a") == std::string::npos;
bool niwg_2014a = rw_engine_list.find("niwg_2014a") == std::string::npos;
bool niwg_pimult = rw_engine_list.find("niwg_pimult") == std::string::npos;
bool niwg_mec = rw_engine_list.find("niwg_mec") == std::string::npos;
bool niwg_rpa = rw_engine_list.find("niwg_rpa") == std::string::npos;
bool niwg_eff_rpa = rw_engine_list.find("niwg_eff_rpa") == std::string::npos;
bool niwg_proton = rw_engine_list.find("niwg_protonFSIbug") == std::string::npos;
bool niwg_hadron = rw_engine_list.find("niwg_HadronMultSwitch") == std::string::npos;
bool niwg_qelowq2 = rw_engine_list.find("niwg_LowQEQ2") == std::string::npos;
// Add the RW Calcs
if (niwg_2012a)
fNIWGRW->AdoptWghtCalc("niwg_2012a", new niwg::rew::NIWGReWeight2012a);
if (niwg_2014a)
fNIWGRW->AdoptWghtCalc("niwg_2014a", new niwg::rew::NIWGReWeight2014a);
if (niwg_pimult)
fNIWGRW->AdoptWghtCalc("niwg_pimult", new niwg::rew::NIWGReWeightPiMult);
if (niwg_mec)
fNIWGRW->AdoptWghtCalc("niwg_mec", new niwg::rew::NIWGReWeightMEC);
if (niwg_rpa)
fNIWGRW->AdoptWghtCalc("niwg_rpa", new niwg::rew::NIWGReWeightRPA);
if (niwg_eff_rpa)
fNIWGRW->AdoptWghtCalc("niwg_eff_rpa",
new niwg::rew::NIWGReWeightEffectiveRPA);
if (niwg_proton)
fNIWGRW->AdoptWghtCalc("niwg_protonFSIbug",
new niwg::rew::NIWGReWeightProtonFSIbug);
if (niwg_hadron)
fNIWGRW->AdoptWghtCalc("niwg_HadronMultSwitch",
new niwg::rew::NIWGReWeightHadronMultSwitch);
// Add in Luke's low Q2 suppression
if (niwg_qelowq2)
fNIWGRW->AdoptWghtCalc("niwg_QELowQ2", new niwg::rew::NIWGReWeightEffectiveQELowQ2Suppression);
fNIWGRW->Reconfigure();
// Set Abs Twk Config
fIsAbsTwk = (FitPar::Config().GetParB("setabstwk"));
// allow cout again
StartTalking();
#else
NUIS_ABORT("NIWG RW Enabled but NEUT RW is not!");
#endif
#else
NUIS_ABORT("NIWG RW NOT ENABLED!");
#endif
};
void NIWGWeightEngine::IncludeDial(std::string name, double startval) {
#ifdef __NIWG_ENABLED__
#ifdef __NEUT_ENABLED__
// Get First enum
int nuisenum = Reweight::ConvDial(name, kNIWG);
// Setup Maps
fEnumIndex[nuisenum]; // = std::vector<size_t>(0);
fNameIndex[name]; // = std::vector<size_t>(0);
// Split by commas
std::vector<std::string> allnames = GeneralUtils::ParseToStr(name, ",");
for (uint i = 0; i < allnames.size(); i++) {
std::string singlename = allnames[i];
// Get RW
niwg::rew::NIWGSyst_t gensyst = niwg::rew::NIWGSyst::FromString(name);
// Fill Maps
int index = fValues.size();
fValues.push_back(0.0);
fNIWGSysts.push_back(gensyst);
// Initialize dial
NUIS_LOG(FIT, "Registering " << singlename << " from " << name);
fNIWGRW->Systematics().Init(fNIWGSysts[index]);
// If Absolute
if (fIsAbsTwk) {
niwg::rew::NIWGSystUncertainty::Instance()->SetUncertainty(
fNIWGSysts[index], 1.0, 1.0);
}
// Setup index
fEnumIndex[nuisenum].push_back(index);
fNameIndex[name].push_back(index);
}
// Set Value if given
if (startval != -999.9) {
SetDialValue(nuisenum, startval);
}
#endif
#endif
}
void NIWGWeightEngine::SetDialValue(int nuisenum, double val) {
#ifdef __NIWG_ENABLED__
#ifdef __NEUT_ENABLED__
std::vector<size_t> indices = fEnumIndex[nuisenum];
for (uint i = 0; i < indices.size(); i++) {
fValues[indices[i]] = val;
std::cout << "Setting NIWG Dial Value " << i << " " << indices[i] << " "
<< fNIWGSysts[indices[i]] << std::endl;
fNIWGRW->Systematics().Set(fNIWGSysts[indices[i]], val);
}
#endif
#endif
}
void NIWGWeightEngine::SetDialValue(std::string name, double val) {
#ifdef __NIWG_ENABLED__
#ifdef __NEUT_ENABLED__
std::vector<size_t> indices = fNameIndex[name];
for (uint i = 0; i < indices.size(); i++) {
fValues[indices[i]] = val;
fNIWGRW->Systematics().Set(fNIWGSysts[indices[i]], val);
}
#endif
#endif
}
void NIWGWeightEngine::Reconfigure(bool silent) {
#ifdef __NIWG_ENABLED__
#ifdef __NEUT_ENABLED__
// Hush now...
if (silent)
StopTalking();
// Reconf
fNIWGRW->Reconfigure();
// Shout again
if (silent)
StartTalking();
#endif
#endif
}
double NIWGWeightEngine::CalcWeight(BaseFitEvt *evt) {
double rw_weight = 1.0;
#ifdef __NEUT_ENABLED__
#ifdef __NIWG_ENABLED__
// Skip Non GENIE
if (evt->fType != kNEUT)
return 1.0;
// Hush now
StopTalking();
niwg::rew::NIWGEvent *niwg_event =
NIWGWeightEngine::GetNIWGEventLocal(evt->fNeutVect);
rw_weight *= fNIWGRW->CalcWeight(*niwg_event);
delete niwg_event;
// Speak Now
StartTalking();
#endif
#endif
// Return rw_weight
return rw_weight;
}
#ifdef __NEUT_ENABLED__
#ifdef __NIWG_ENABLED__
niwg::rew::NIWGEvent *NIWGWeightEngine::GetNIWGEventLocal(NeutVect *nvect) {
niwg::rew::NIWGEvent *fDummyNIWGEvent = NULL;
fDummyNIWGEvent = new niwg::rew::NIWGEvent();
fDummyNIWGEvent->detid = 1; // MiniBooNE (apply CCQE LowE variations)
fDummyNIWGEvent->neutmode = nvect->Mode;
fDummyNIWGEvent->targetA = nvect->TargetA;
fDummyNIWGEvent->recenu_ccqe_sk = -1;
if (nvect->Ibound == 0)
fDummyNIWGEvent->targetA = 1; // RT: identifies as H, rather than O16
// Fill initial particle stack
for (int ip = 0; ip < nvect->Npart(); ++ip) {
niwg::rew::NIWGPartStack fDummyPartStack;
fDummyPartStack.p = (nvect->PartInfo(ip)->fP) * 0.001; // Convert to GeV
fDummyPartStack.pdg = nvect->PartInfo(ip)->fPID;
fDummyPartStack.chase = nvect->PartInfo(ip)->fIsAlive;
fDummyPartStack.parent =
nvect->ParentIdx(ip) -
1; // WARNING: this needs to be tested with a NeutRoot file
fDummyNIWGEvent->part_stack.push_back(fDummyPartStack);
}
fDummyNIWGEvent->CalcKinematics();
return fDummyNIWGEvent;
}
#endif
#endif
diff --git a/src/Reweight/SampleNormEngine.cxx b/src/Reweight/SampleNormEngine.cxx
index 80be47e..9c74232 100644
--- a/src/Reweight/SampleNormEngine.cxx
+++ b/src/Reweight/SampleNormEngine.cxx
@@ -1,80 +1,80 @@
#include "WeightUtils.h"
#include "SampleNormEngine.h"
SampleNormEngine::SampleNormEngine(std::string name) {
// Setup the NEUT Reweight engien
fCalcName = name;
NUIS_LOG(FIT, "Setting up Likelihood Weight RW : " << fCalcName);
// Set Abs Twk Config
fIsAbsTwk = true;
};
void SampleNormEngine::IncludeDial(std::string name, double startval) {
// Get NUISANCE Enum
int nuisenum = Reweight::ConvDial(name, kNORM);
// Setup Maps
fEnumIndex[nuisenum]; // = std::vector<size_t>(0);
fNameIndex[name]; // = std::vector<size_t>(0);
// Split by commas
std::vector<std::string> allnames = GeneralUtils::ParseToStr(name, ",");
for (uint i = 0; i < allnames.size(); i++) {
std::string singlename = allnames[i];
// Fill Maps
int index = fValues.size();
fValues.push_back(1.0);
fEnumIndex[nuisenum].push_back(index);
fNameIndex[name].push_back(index);
}
// Set Value if given
if (startval != -999.9) {
SetDialValue(name, startval);
}
};
void SampleNormEngine::SetDialValue(int nuisenum, double val) {
std::vector<size_t> indices = fEnumIndex[nuisenum];
for (uint i = 0; i < indices.size(); i++) {
fValues[indices[i]] = val;
}
}
void SampleNormEngine::SetDialValue(std::string name, double val) {
std::vector<size_t> indices = fNameIndex[name];
for (uint i = 0; i < indices.size(); i++) {
fValues[indices[i]] = val;
}
}
double SampleNormEngine::GetDialValue(std::string name) {
// Check for exact dial names
if (fNameIndex.find(name) != fNameIndex.end()) {
return fValues[fNameIndex[name][0]];
// If not iterate and check entry in one of the keys
} else {
- for (std::map<std::string, std::vector<size_t>>::iterator iter =
+ for (std::map<std::string, std::vector<size_t> >::iterator iter =
fNameIndex.begin();
iter != fNameIndex.end(); iter++) {
std::string keyname = iter->first;
if (keyname.find(name) != std::string::npos) {
return fValues[iter->second[0]];
}
}
}
return -1.0;
}
void SampleNormEngine::Reconfigure(bool silent) {
// Empty placeholder incase we want print statements...
}
diff --git a/src/Routines/SplineRoutines.cxx b/src/Routines/SplineRoutines.cxx
index 6e9409b..c5b1fed 100755
--- a/src/Routines/SplineRoutines.cxx
+++ b/src/Routines/SplineRoutines.cxx
@@ -1,2598 +1,2598 @@
// Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret
/*******************************************************************************
* This file is part of NUISANCE.
*
* NUISANCE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NUISANCE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NUISANCE. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
#include "SplineRoutines.h"
void SplineRoutines::Init() {
fStrategy = "SaveEvents";
fRoutines.clear();
fCardFile = "";
fSampleFCN = NULL;
fRW = NULL;
fAllowedRoutines = ("SaveEvents,TestEvents,SaveSplineEvents");
};
SplineRoutines::~SplineRoutines(){};
SplineRoutines::SplineRoutines(int argc, char *argv[]) {
// Initialise Defaults
Init();
nuisconfig configuration = Config::Get();
// Default containers
std::string cardfile = "";
std::string maxevents = "-1";
int errorcount = 0;
int verbocount = 0;
std::vector<std::string> xmlcmds;
std::vector<std::string> configargs;
// Make easier to handle arguments.
std::vector<std::string> args = GeneralUtils::LoadCharToVectStr(argc, argv);
ParserUtils::ParseArgument(args, "-c", fCardFile, true);
ParserUtils::ParseArgument(args, "-o", fOutputFile, false, false);
ParserUtils::ParseArgument(args, "-n", maxevents, false, false);
ParserUtils::ParseArgument(args, "-f", fStrategy, false, false);
ParserUtils::ParseArgument(args, "-i", xmlcmds);
ParserUtils::ParseArgument(args, "-q", configargs);
ParserUtils::ParseCounter(args, "e", errorcount);
ParserUtils::ParseCounter(args, "v", verbocount);
ParserUtils::CheckBadArguments(args);
// Add extra defaults if none given
if (fCardFile.empty() and xmlcmds.empty()) {
NUIS_ABORT("No input supplied!");
}
if (fOutputFile.empty() and !fCardFile.empty()) {
fOutputFile = fCardFile + ".root";
NUIS_ERR(WRN, "No output supplied so saving it to: " << fOutputFile);
} else if (fOutputFile.empty()) {
NUIS_ABORT("No output file or cardfile supplied!");
}
// Configuration Setup =============================
// Check no comp key is available
nuiskey fCompKey;
if (Config::Get().GetNodes("nuiscomp").empty()) {
fCompKey = Config::Get().CreateNode("nuiscomp");
} else {
fCompKey = Config::Get().GetNodes("nuiscomp")[0];
}
if (!fCardFile.empty())
fCompKey.Set("cardfile", fCardFile);
fCompKey.Set("outputfile", fOutputFile);
if (!fStrategy.empty())
fCompKey.Set("strategy", fStrategy);
// Load XML Cardfile
configuration.LoadSettings(fCompKey.GetS("cardfile"), "");
// Add Config Args
for (size_t i = 0; i < configargs.size(); i++) {
configuration.OverrideConfig(configargs[i]);
}
if (maxevents.compare("-1")) {
std::cout << "[ NUISANCE ] : Overriding "
<< "MAXEVENTS=" + maxevents << std::endl;
configuration.OverrideConfig("MAXEVENTS=" + maxevents);
}
// Finish configuration XML
configuration.FinaliseSettings(fCompKey.GetS("outputfile") + ".xml");
// Add Error Verbo Lines
verbocount += Config::GetParI("VERBOSITY");
errorcount += Config::GetParI("ERROR");
std::cout << "[ NUISANCE ]: Setting VERBOSITY=" << verbocount << std::endl;
std::cout << "[ NUISANCE ]: Setting ERROR=" << errorcount << std::endl;
// FitPar::log_verb = verbocount;
SETVERBOSITY(verbocount);
// ERR_VERB(errorcount);
// Starting Setup
// ---------------------------
SetupRWEngine();
return;
};
/*
Setup Functions
*/
//*************************************
void SplineRoutines::SetupRWEngine() {
//*************************************
fRW = new FitWeight("splineweight");
// std::vector<nuiskey> splinekeys = Config::QueryKeys("spline");
std::vector<nuiskey> parameterkeys = Config::QueryKeys("parameter");
// Add Parameters
for (size_t i = 0; i < parameterkeys.size(); i++) {
nuiskey key = parameterkeys[i];
std::string parname = key.GetS("name");
std::string partype = key.GetS("type");
double nom = key.GetD("nominal");
fRW->IncludeDial(key.GetS("name"), FitBase::ConvDialType(key.GetS("type")),
nom);
fRW->SetDialValue(key.GetS("name"), key.GetD("nominal"));
}
fRW->Reconfigure();
return;
}
/*
Fitting Functions
*/
//*************************************
void SplineRoutines::UpdateRWEngine(std::map<std::string, double> &updateVals) {
//*************************************
for (UInt_t i = 0; i < fParams.size(); i++) {
std::string name = fParams[i];
if (updateVals.find(name) == updateVals.end())
continue;
fRW->SetDialValue(name, updateVals.at(name));
}
fRW->Reconfigure();
return;
}
//*************************************
void SplineRoutines::Run() {
//*************************************
std::cout << "Running " << std::endl;
// Parse given routines
fRoutines = GeneralUtils::ParseToStr(fStrategy, ",");
if (fRoutines.empty()) {
NUIS_ABORT("Trying to run ComparisonRoutines with no routines given!");
}
for (size_t i = 0; i < fRoutines.size(); i++) {
NUIS_LOG(FIT, "Running Routine: " << fRoutines[i]);
std::string rout = fRoutines[i];
if (!rout.compare("SaveEvents"))
SaveEvents();
else if (!rout.compare("TestEvents"))
TestEvents();
else if (!rout.compare("GenerateEventSplines")) {
GenerateEventWeights();
BuildEventSplines();
} else if (!rout.compare("GenerateEventWeights")) {
GenerateEventWeights();
} else if (!rout.compare("GenerateEventWeightChunks")) {
GenerateEventWeightChunks(FitPar::Config().GetParI("spline_procchunk"));
} else if (!rout.compare("BuildEventSplines")) {
BuildEventSplines();
} else if (!rout.compare("TestSplines_1DEventScan"))
TestSplines_1DEventScan();
else if (!rout.compare("TestSplines_NDEventThrow"))
TestSplines_NDEventThrow();
else if (!rout.compare("SaveSplinePlots"))
SaveSplinePlots();
else if (!rout.compare("TestSplines_1DLikelihoodScan"))
TestSplines_1DLikelihoodScan();
else if (!rout.compare("TestSplines_NDLikelihoodThrow"))
TestSplines_NDLikelihoodThrow();
else if (!rout.compare("BuildEventSplinesChunks")) {
int chunk = FitPar::Config().GetParI("spline_procchunk");
BuildEventSplines(chunk);
} else if (!rout.compare("MergeEventSplinesChunks")) {
MergeEventSplinesChunks();
}
}
}
//*************************************
void SplineRoutines::SaveEvents() {
//*************************************
if (fRW)
delete fRW;
SetupRWEngine();
fRW->Reconfigure();
fRW->Print();
// Generate a set of nominal events
// Method, Loop over inputs, create input handler, then create a ttree
std::vector<nuiskey> eventkeys = Config::QueryKeys("events");
for (size_t i = 0; i < eventkeys.size(); i++) {
nuiskey key = eventkeys.at(i);
// Get I/O
std::string inputfilename = key.GetS("input");
if (inputfilename.empty()) {
NUIS_ABORT("No input given for set of input events!");
}
std::string outputfilename = key.GetS("output");
if (outputfilename.empty()) {
outputfilename = inputfilename + ".nuisance.root";
NUIS_ERR(WRN, "No output give for set of output events! Saving to "
<< outputfilename);
}
// Make new outputfile
TFile *outputfile = new TFile(outputfilename.c_str(), "RECREATE");
outputfile->cd();
// Make a new input handler
std::vector<std::string> file_descriptor =
GeneralUtils::ParseToStr(inputfilename, ":");
if (file_descriptor.size() != 2) {
NUIS_ABORT("File descriptor had no filetype declaration: \""
<< inputfilename << "\". expected \"FILETYPE:file.root\"");
}
InputUtils::InputType inptype =
InputUtils::ParseInputType(file_descriptor[0]);
InputHandlerBase *input = InputUtils::CreateInputHandler(
"eventsaver", inptype, file_descriptor[1]);
// Get info from inputhandler
int nevents = input->GetNEvents();
int countwidth = (nevents / 10);
FitEvent *nuisevent = input->FirstNuisanceEvent();
// Setup a TTree to save the event
outputfile->cd();
TTree *eventtree = new TTree("nuisance_events", "nuisance_events");
nuisevent->AddBranchesToTree(eventtree);
// Loop over all events and fill the TTree
int icount = 0;
// int countwidth = nevents / 5;
while (nuisevent) {
// Get Event Weight
nuisevent->RWWeight = fRW->CalcWeight(nuisevent);
// if (nuisevent->RWWeight != 1.0){
// std::cout << "Weight = " << nuisevent->RWWeight << std::endl;
// }
// Save everything
eventtree->Fill();
// Logging
if (icount % countwidth == 0) {
NUIS_LOG(REC, "Saved " << icount << "/" << nevents
<< " nuisance events. [M, W] = [" << nuisevent->Mode
<< ", " << nuisevent->RWWeight << "]");
}
// iterate
nuisevent = input->NextNuisanceEvent();
icount++;
}
// Save flux and close file
outputfile->cd();
eventtree->Write();
input->GetFluxHistogram()->Write("nuisance_fluxhist");
input->GetEventHistogram()->Write("nuisance_eventhist");
// Close Output
outputfile->Close();
// Delete Inputs
delete input;
}
// remove Keys
eventkeys.clear();
// Finished
NUIS_LOG(FIT, "Finished processing all nuisance events.");
}
//*************************************
void SplineRoutines::TestEvents() {
//*************************************
NUIS_LOG(FIT, "Testing events.");
// Create a new file for the test samples
if (!fOutputRootFile) {
fOutputRootFile =
new TFile(fCompKey.GetS("outputfile").c_str(), "RECREATE");
}
// Loop over all tests
int count = 0;
std::vector<nuiskey> testkeys = Config::QueryKeys("sampletest");
for (std::vector<nuiskey>::iterator iter = testkeys.begin();
iter != testkeys.end(); iter++) {
nuiskey key = (*iter);
// 0. Create new measurement list
std::list<MeasurementBase *> samplelist;
// 1. Build Sample From Events
std::string samplename = key.GetS("name");
std::string eventsid = key.GetS("inputid");
nuiskey eventskey = Config::QueryLastKey("events", "id=" + eventsid);
std::string rawfile = eventskey.GetS("input");
NUIS_LOG(FIT, "Creating sample " << samplename);
MeasurementBase *rawsample = SampleUtils::CreateSample(
samplename, rawfile, "", "", FitBase::GetRW());
// 2. Build Sample From Nuisance Events
std::string eventsfile = eventskey.GetS("output");
NUIS_LOG(FIT, "Creating Fit Eevnt Sample " << samplename << " " << eventsfile);
MeasurementBase *nuissample = SampleUtils::CreateSample(
samplename, "FEVENT:" + eventsfile, "", "", FitBase::GetRW());
// 3. Make some folders to save stuff
TDirectory *sampledir = (TDirectory *)fOutputRootFile->mkdir(
Form((samplename + "_test_%d").c_str(), count));
TDirectory *rawdir = (TDirectory *)sampledir->mkdir("raw");
TDirectory *nuisancedir = (TDirectory *)sampledir->mkdir("nuisance");
TDirectory *difdir = (TDirectory *)sampledir->mkdir("difference");
// 4. Reconfigure both
rawdir->cd();
rawsample->Reconfigure();
rawsample->Write();
nuisancedir->cd();
nuissample->Reconfigure();
nuissample->Write();
// 4. Compare Raw to Nuisance Events
// Loop over all keyse
TIter next(rawdir->GetListOfKeys());
TKey *dirkey;
while ((dirkey = (TKey *)next())) {
// If not a 1D/2D histogram skip
TClass *cl = gROOT->GetClass(dirkey->GetClassName());
if (!cl->InheritsFrom("TH1D") and !cl->InheritsFrom("TH2D"))
continue;
// Get TH1* from both dir
TH1 *rawplot = (TH1 *)rawdir->Get(dirkey->GetName());
TH1 *nuisanceplot = (TH1 *)nuisancedir->Get(dirkey->GetName());
// Take Difference
nuisanceplot->Add(rawplot, -1.0);
// Save to dif folder
difdir->cd();
nuisanceplot->Write();
}
// 5. Tidy Up
samplelist.clear();
// Iterator
count++;
}
}
void SplineRoutines::GenerateEventWeightChunks(int procchunk) {
if (fRW)
delete fRW;
SetupRWEngine();
// Setup the spline reader
SplineWriter *splwrite = new SplineWriter(fRW);
std::vector<nuiskey> splinekeys = Config::QueryKeys("spline");
// Add splines to splinewriter
for (std::vector<nuiskey>::iterator iter = splinekeys.begin();
iter != splinekeys.end(); iter++) {
nuiskey splkey = (*iter);
// Add Spline Info To Reader
splwrite->AddSpline(splkey);
}
splwrite->SetupSplineSet();
// Event Loop
// Loop over all events and calculate weights for each parameter set.
// Generate a set of nominal events
// Method, Loop over inputs, create input handler, then create a ttree
std::vector<nuiskey> eventkeys = Config::QueryKeys("events");
for (size_t i = 0; i < eventkeys.size(); i++) {
nuiskey key = eventkeys.at(i);
// Get I/O
std::string inputfilename = key.GetS("input");
if (inputfilename.empty()) {
NUIS_ABORT("No input given for set of input events!");
}
std::string outputfilename = key.GetS("output");
if (outputfilename.empty()) {
outputfilename = inputfilename + ".nuisance.root";
NUIS_ERR(WRN,"No output give for set of output events! Saving to "
<< outputfilename);
}
outputfilename += ".weights.root";
// Make new outputfile
TFile *outputfile = new TFile(outputfilename.c_str(), "RECREATE");
outputfile->cd();
// Make a new input handler
std::vector<std::string> file_descriptor =
GeneralUtils::ParseToStr(inputfilename, ":");
if (file_descriptor.size() != 2) {
NUIS_ABORT("File descriptor had no filetype declaration: \""
<< inputfilename << "\". expected \"FILETYPE:file.root\"");
}
InputUtils::InputType inptype =
InputUtils::ParseInputType(file_descriptor[0]);
InputHandlerBase *input = InputUtils::CreateInputHandler(
"eventsaver", inptype, file_descriptor[1]);
// Get info from inputhandler
int nevents = input->GetNEvents();
// int countwidth = (nevents / 1000);
FitEvent *nuisevent = input->FirstNuisanceEvent();
// Setup a TTree to save the event
outputfile->cd();
TTree *eventtree = new TTree("nuisance_events", "nuisance_events");
// Add a flag that allows just splines to be saved.
nuisevent->AddBranchesToTree(eventtree);
// Save the spline reader
splwrite->Write("spline_reader");
// Setup the spline TTree
TTree *weighttree = new TTree("weight_tree", "weight_tree");
splwrite->AddWeightsToTree(weighttree);
// Make container for all weights
int nweights = splwrite->GetNWeights();
// int npar = splwrite->GetNPars();
// double* weightcont = new double[nweights];
int lasttime = time(NULL);
// Load N Chunks of the Weights into Memory
// Split into N processing chunks
int nchunks = FitPar::Config().GetParI("spline_chunks");
if (nchunks <= 0)
nchunks = 1;
if (nchunks >= nevents / 2)
nchunks = nevents / 2;
std::cout << "Starting NChunks " << nchunks << std::endl;
for (int ichunk = 0; ichunk < nchunks; ichunk++) {
// Skip to only do one processing chunk
if (procchunk != -1 and procchunk != ichunk)
continue;
NUIS_LOG(FIT, "On Processing Chunk " << ichunk);
int neventsinchunk = nevents / nchunks;
int loweventinchunk = neventsinchunk * ichunk;
// int higheventinchunk = neventsinchunk * (ichunk + 1);
double **allweightcont = new double *[neventsinchunk];
for (int k = 0; k < neventsinchunk; k++) {
allweightcont[k] = new double[nweights];
}
// Start Set Processing Here.
for (int iset = 0; iset < nweights; iset++) {
splwrite->ReconfigureSet(iset);
// Could reorder this to save the weightconts in order instead of
// reconfiguring per event. Loop over all events and fill the TTree
for (int i = 0; i < neventsinchunk; i++) {
nuisevent = input->GetNuisanceEvent(i + loweventinchunk);
double w = splwrite->GetWeightForThisSet(nuisevent);
if (iset == 0) {
allweightcont[i][0] = w;
} else {
allweightcont[i][iset] = w / allweightcont[i][0];
}
// Save everything
if (iset == 0) {
eventtree->Fill();
}
}
std::ostringstream timestring;
int timeelapsed = time(NULL) - lasttime;
if (timeelapsed) {
lasttime = time(NULL);
int setsleft =
(nweights - iset - 1) + (nweights * (nchunks - ichunk - 1));
float proj = (float(setsleft) * timeelapsed) / 60 / 60;
timestring << setsleft << " sets remaining. Last one took "
<< timeelapsed << ". " << proj << " hours remaining.";
}
NUIS_LOG(REC, "Processed Set " << iset << "/" << nweights << " in chunk "
<< ichunk << "/" << nchunks << " "
<< timestring.str());
}
// Fill weights for this chunk into the TTree
for (int k = 0; k < neventsinchunk; k++) {
splwrite->SetWeights(allweightcont[k]);
weighttree->Fill();
}
}
// at end of the chunk, when all sets have been done
// loop over the container and fill weights to ttree
outputfile->cd();
eventtree->Write();
weighttree->Write();
input->GetFluxHistogram()->Write("nuisance_fluxhist");
input->GetEventHistogram()->Write("nuisance_eventhist");
splwrite->Write("spline_reader");
outputfile->Close();
// Close Output
outputfile->Close();
// Delete Inputs
delete input;
}
// remove Keys
eventkeys.clear();
}
//*************************************
void SplineRoutines::GenerateEventWeights() {
//*************************************
if (fRW)
delete fRW;
SetupRWEngine();
// Setup the spline reader
SplineWriter *splwrite = new SplineWriter(fRW);
std::vector<nuiskey> splinekeys = Config::QueryKeys("spline");
// Add splines to splinewriter
for (std::vector<nuiskey>::iterator iter = splinekeys.begin();
iter != splinekeys.end(); iter++) {
nuiskey splkey = (*iter);
// Add Spline Info To Reader
splwrite->AddSpline(splkey);
}
splwrite->SetupSplineSet();
// Event Loop
// Loop over all events and calculate weights for each parameter set.
// Generate a set of nominal events
// Method, Loop over inputs, create input handler, then create a ttree
std::vector<nuiskey> eventkeys = Config::QueryKeys("events");
for (size_t i = 0; i < eventkeys.size(); i++) {
nuiskey key = eventkeys.at(i);
// Get I/O
std::string inputfilename = key.GetS("input");
if (inputfilename.empty()) {
NUIS_ABORT("No input given for set of input events!");
}
std::string outputfilename = key.GetS("output");
if (outputfilename.empty()) {
outputfilename = inputfilename + ".nuisance.root";
NUIS_ERR(WRN, "No output give for set of output events! Saving to "
<< outputfilename);
}
outputfilename += ".weights.root";
// Make new outputfile
TFile *outputfile = new TFile(outputfilename.c_str(), "RECREATE");
outputfile->cd();
// Make a new input handler
std::vector<std::string> file_descriptor =
GeneralUtils::ParseToStr(inputfilename, ":");
if (file_descriptor.size() != 2) {
NUIS_ABORT("File descriptor had no filetype declaration: \""
<< inputfilename << "\". expected \"FILETYPE:file.root\"");
}
InputUtils::InputType inptype =
InputUtils::ParseInputType(file_descriptor[0]);
InputHandlerBase *input = InputUtils::CreateInputHandler(
"eventsaver", inptype, file_descriptor[1]);
// Get info from inputhandler
int nevents = input->GetNEvents();
int countwidth = (nevents / 1000);
FitEvent *nuisevent = input->FirstNuisanceEvent();
// Setup a TTree to save the event
outputfile->cd();
TTree *eventtree = new TTree("nuisance_events", "nuisance_events");
// Add a flag that allows just splines to be saved.
nuisevent->AddBranchesToTree(eventtree);
// Save the spline reader
splwrite->Write("spline_reader");
// Setup the spline TTree
TTree *weighttree = new TTree("weight_tree", "weight_tree");
splwrite->AddWeightsToTree(weighttree);
// Make container for all weights
int nweights = splwrite->GetNWeights();
// int npar = splwrite->GetNPars();
double *weightcont = new double[nweights];
int lasttime = time(NULL);
// Could reorder this to save the weightconts in order instead of
// reconfiguring per event. Loop over all events and fill the TTree
while (nuisevent) {
// Calculate the weights for each parameter set
splwrite->GetWeightsForEvent(nuisevent, weightcont);
// Save everything
eventtree->Fill();
weighttree->Fill();
// Logging
if (i % countwidth == 0) {
std::ostringstream timestring;
int timeelapsed = time(NULL) - lasttime;
if (i != 0 and timeelapsed) {
lasttime = time(NULL);
int eventsleft = nevents - i;
float speed = float(countwidth) / float(timeelapsed);
float proj = (float(eventsleft) / float(speed)) / 60 / 60;
timestring << proj << " hours remaining.";
}
NUIS_LOG(REC, "Saved " << i << "/" << nevents
<< " nuisance spline weights. " << timestring.str());
}
// Iterate
i++;
nuisevent = input->NextNuisanceEvent();
}
// at end of the chunk, when all sets have been done
// loop over the container and fill weights to ttree
outputfile->cd();
eventtree->Write();
weighttree->Write();
input->GetFluxHistogram()->Write("nuisance_fluxhist");
input->GetEventHistogram()->Write("nuisance_eventhist");
splwrite->Write("spline_reader");
outputfile->Close();
// Close Output
outputfile->Close();
// Delete Inputs
delete input;
}
// remove Keys
eventkeys.clear();
}
//*************************************
void SplineRoutines::GenerateEventSplines() {
//*************************************
if (fRW)
delete fRW;
SetupRWEngine();
// Setup the spline reader
SplineWriter *splwrite = new SplineWriter(fRW);
std::vector<nuiskey> splinekeys = Config::QueryKeys("spline");
// Add splines to splinewriter
for (std::vector<nuiskey>::iterator iter = splinekeys.begin();
iter != splinekeys.end(); iter++) {
nuiskey splkey = (*iter);
// Add Spline Info To Reader
splwrite->AddSpline(splkey);
}
splwrite->SetupSplineSet();
// Make an ugly list for N cores
int ncores = FitPar::Config().GetParI("NCORES"); // omp_get_max_threads();
std::vector<SplineWriter *> splwriterlist;
for (int i = 0; i < ncores; i++) {
SplineWriter *tmpwriter = new SplineWriter(fRW);
for (std::vector<nuiskey>::iterator iter = splinekeys.begin();
iter != splinekeys.end(); iter++) {
nuiskey splkey = (*iter);
// Add Spline Info To Reader
tmpwriter->AddSpline(splkey);
}
tmpwriter->SetupSplineSet();
splwriterlist.push_back(tmpwriter);
}
// Event Loop
// Loop over all events and calculate weights for each parameter set.
// Generate a set of nominal events
// Method, Loop over inputs, create input handler, then create a ttree
std::vector<nuiskey> eventkeys = Config::QueryKeys("events");
for (size_t i = 0; i < eventkeys.size(); i++) {
nuiskey key = eventkeys.at(i);
// Get I/O
std::string inputfilename = key.GetS("input");
if (inputfilename.empty()) {
NUIS_ABORT("No input given for set of input events!");
}
std::string outputfilename = key.GetS("output");
if (outputfilename.empty()) {
outputfilename = inputfilename + ".nuisance.root";
NUIS_ERR(WRN, "No output give for set of output events! Saving to "
<< outputfilename);
}
// Make new outputfile
TFile *outputfile = new TFile(outputfilename.c_str(), "RECREATE");
outputfile->cd();
// Make a new input handler
std::vector<std::string> file_descriptor =
GeneralUtils::ParseToStr(inputfilename, ":");
if (file_descriptor.size() != 2) {
NUIS_ABORT("File descriptor had no filetype declaration: \""
<< inputfilename << "\". expected \"FILETYPE:file.root\"");
}
InputUtils::InputType inptype =
InputUtils::ParseInputType(file_descriptor[0]);
InputHandlerBase *input = InputUtils::CreateInputHandler(
"eventsaver", inptype, file_descriptor[1]);
// Get info from inputhandler
int nevents = input->GetNEvents();
int countwidth = (nevents / 1000);
FitEvent *nuisevent = input->FirstNuisanceEvent();
// Setup a TTree to save the event
outputfile->cd();
TTree *eventtree = new TTree("nuisance_events", "nuisance_events");
// Add a flag that allows just splines to be saved.
nuisevent->AddBranchesToTree(eventtree);
// Save the spline reader
splwrite->Write("spline_reader");
// Setup the spline TTree
TTree *weighttree = new TTree("weight_tree", "weight_tree");
splwrite->AddWeightsToTree(weighttree);
// Make container for all weights
int nweights = splwrite->GetNWeights();
double **weightcont = new double *[nevents];
for (int k = 0; k < nevents; k++) {
weightcont[k] = new double[nweights];
}
int npar = splwrite->GetNPars();
int lasttime = time(NULL);
// Could reorder this to save the weightconts in order instead of
// reconfiguring per event. Loop over all events and fill the TTree
while (nuisevent) {
// std::cout << "Fitting event " << i << std::endl;
// Calculate the weights for each parameter set
// splwrite->FitSplinesForEvent(nuisevent);
splwrite->GetWeightsForEvent(nuisevent, weightcont[i]);
bool hasresponse = false;
for (int j = 0; j < nweights; j++) {
if (weightcont[i][j] != 1.0) {
// std::cout << "Non Zero Weight at " << i << " " << j <<
// std::endl;
hasresponse = true;
} else {
// std::cout << "Empty Weight at " << i << " " << j << std::endl;
}
}
if (!hasresponse) {
// std::cout << "Deleting flat response " << nuisevent->Mode <<
// std::endl;
delete weightcont[i];
weightcont[i] = NULL;
}
// Save everything
eventtree->Fill();
weighttree->Fill();
// splinetree->Fill();
// nuisevent->Print();
// std::cout << "Done with event " << i << std::endl;
// Push weight sets into a the array
// sleep(4);
// Logging
if (i % countwidth == 0) {
std::ostringstream timestring;
int timeelapsed = time(NULL) - lasttime;
if (i != 0 and timeelapsed) {
lasttime = time(NULL);
int eventsleft = nevents - i;
float speed = float(countwidth) / float(timeelapsed);
float proj = (float(eventsleft) / float(speed)) / 60 / 60;
timestring << proj << " hours remaining.";
}
NUIS_LOG(REC, "Saved " << i << "/" << nevents
<< " nuisance spline weights. " << timestring.str());
}
// Iterate
i++;
nuisevent = input->NextNuisanceEvent();
}
outputfile->cd();
eventtree->Write();
weighttree->Write();
input->GetFluxHistogram()->Write("nuisance_fluxhist");
input->GetEventHistogram()->Write("nuisance_eventhist");
outputfile->Close();
outputfile = new TFile(outputfilename.c_str(), "UPDATE");
outputfile->cd();
weighttree = (TTree *)outputfile->Get("weight_tree");
// splwrite->ReadWeightsFromTree(weighttree);
// Divide weights container into Ncores.
// Parrallelise this loop checking for what core we are on.
// for (int i = 0; i < nevents; i++){
// splwriterlist[int(i / (nevents/4))]->FitSplinesForEvent(coeff);
// }
// // Now loop over weights tree
// for (int i = 0; i < weighttree->GetEntries(); i++) {
// weighttree->GetEntry(i);
// splwrite->FitSplinesForEvent();
// splinetree->Fill();
// if (i % countwidth == 0) {
// std::ostringstream timestring;
// int timeelapsed = time(NULL) - lasttime;
// if (i != 0 and timeelapsed) {
// lasttime = time(NULL);
// int eventsleft = nevents - i;
// float speed = float(countwidth) / float(timeelapsed);
// float proj = (float(eventsleft) / float(speed)) / 60 / 60;
// timestring << proj << " hours remaining.";
// }
// LOG(REC) << "Built " << i << "/" << nevents << " nuisance spline
// events. " << timestring.str() << std::endl;
// }
// }
// Get Splines
float **allcoeff = new float *[nevents];
for (int k = 0; k < nevents; k++) {
allcoeff[k] = new float[npar];
}
// #pragma omp parallel for num_threads(ncores)
for (int i = 0; i < nevents; i++) {
//#pragma omp atomic
// printf("Using Thread %d to build event %d \n",
// int(omp_get_thread_num()), (int)i ); std::cout<< " -> Writer = "
// << splwriterlist[ i / (nevents/ncores) ] << std::endl;
// #pragma omp atomic
if (weightcont[i]) {
splwriterlist[int(omp_get_thread_num())]->FitSplinesForEvent(
weightcont[i], allcoeff[i]);
} else {
for (int j = 0; j < npar; j++) {
allcoeff[i][j] = float(0.0);
}
}
// splwrite->FitSplinesForEvent(weightcont[i], allcoeff[i]);
if (i % 500 == 0) {
if (LOG_LEVEL(REC)) {
printf("Using Thread %d to build event %d \n",
int(omp_get_thread_num()), (int)i);
}
}
/*
std::ostringstream timestring;
int timeelapsed = time(NULL) - lasttime;
if (i != 0 and timeelapsed) {
lasttime = time(NULL);
int eventsleft = nevents - i;
float speed = float(countwidth) / float(timeelapsed);
float proj = (float(eventsleft) / float(speed)) / 60 / 60;
timestring << proj << " hours remaining.";
timestring << " Using Writer at " << i / (nevents/ncores) << " = " <<
splwriterlist[ i / (nevents/ncores) ] << std::endl;
}
LOG(REC) << "Built " << i << "/" << nevents << " nuisance spline events.
" << timestring.str() << std::endl;
}
*/
}
// Save Splines into TTree
float *coeff = new float[npar];
outputfile->cd();
TTree *splinetree = new TTree("spline_tree", "spline_tree");
splinetree->Branch("SplineCoeff", coeff, Form("SplineCoeff[%d]/F", npar));
std::cout << "Saving to the allcoeff" << std::endl;
for (int k = 0; k < nevents; k++) {
for (int l = 0; l < npar; l++) {
coeff[l] = allcoeff[k][l];
}
std::cout << "Coeff 0, 1, 2 = " << coeff[0] << " " << coeff[1] << " "
<< coeff[2] << std::endl;
splinetree->Fill();
}
// Save flux and close file
outputfile->cd();
splinetree->Write();
// Delete the container.
for (int k = 0; k < nevents; k++) {
delete weightcont[k];
}
delete weightcont;
delete coeff;
// Close Output
outputfile->Close();
// Delete Inputs
delete input;
}
// remove Keys
eventkeys.clear();
}
//*************************************
void SplineRoutines::BuildEventSplines(int procchunk) {
//*************************************
if (fRW)
delete fRW;
SetupRWEngine();
// Setup the spline reader
SplineWriter *splwrite = new SplineWriter(fRW);
std::vector<nuiskey> splinekeys = Config::QueryKeys("spline");
// Add splines to splinewriter
for (std::vector<nuiskey>::iterator iter = splinekeys.begin();
iter != splinekeys.end(); iter++) {
nuiskey splkey = (*iter);
// Add Spline Info To Reader
splwrite->AddSpline(splkey);
}
splwrite->SetupSplineSet();
// Make an ugly list for N cores
int ncores =
FitPar::Config().GetParI("spline_cores"); // omp_get_max_threads();
if (ncores > omp_get_max_threads())
ncores = omp_get_max_threads();
if (ncores <= 0)
ncores = 1;
std::vector<SplineWriter *> splwriterlist;
for (int i = 0; i < ncores; i++) {
SplineWriter *tmpwriter = new SplineWriter(fRW);
for (std::vector<nuiskey>::iterator iter = splinekeys.begin();
iter != splinekeys.end(); iter++) {
nuiskey splkey = (*iter);
// Add Spline Info To Reader
tmpwriter->AddSpline(splkey);
}
tmpwriter->SetupSplineSet();
splwriterlist.push_back(tmpwriter);
}
// Event Loop
// Loop over all events and calculate weights for each parameter set.
// Generate a set of nominal events
// Method, Loop over inputs, create input handler, then create a ttree
std::vector<nuiskey> eventkeys = Config::QueryKeys("events");
for (size_t i = 0; i < eventkeys.size(); i++) {
nuiskey key = eventkeys.at(i);
// Get I/O
std::string inputfilename = key.GetS("input");
if (inputfilename.empty()) {
NUIS_ABORT("No input given for set of input events!");
}
std::string outputfilename = key.GetS("output");
if (outputfilename.empty()) {
outputfilename = inputfilename + ".nuisance.root";
NUIS_ERR(WRN, "No output give for set of output events! Saving to "
<< outputfilename);
}
// Make new outputfile
TFile *outputfile;
if (procchunk == -1)
outputfile = new TFile(outputfilename.c_str(), "RECREATE");
else
outputfile = new TFile(
(outputfilename + std::string(Form(".coeffchunk_%d.root", procchunk)))
.c_str(),
"RECREATE");
outputfile->cd();
// Get Weights File
TFile *weightsfile =
new TFile((outputfilename + ".weights.root").c_str(), "READ");
TTree *weighttree = (TTree *)weightsfile->Get("weight_tree");
// Get SPLWRite Info
// splwrite->ReadWeightsFromTree(weighttree);
int nevents = weighttree->GetEntries();
// int countwidth = (nevents / 1000);
int nweights = splwrite->GetNWeights();
int npar = splwrite->GetNPars();
// Access Weights
double *eventweights = new double[nweights];
weighttree->SetBranchAddress("SplineWeights", eventweights);
// Make counter
// int lasttime = time(NULL);
// Setup Splines To Be Saved into TTree
outputfile->cd();
TTree *splinetree = new TTree("spline_tree", "spline_tree");
float *coeff = new float[npar];
splinetree->Branch("SplineCoeff", coeff, Form("SplineCoeff[%d]/F", npar));
// Load N Chunks of the Weights into Memory
// Split into N processing chunks
int nchunks = FitPar::Config().GetParI("spline_chunks");
if (nchunks <= 0)
nchunks = 1;
if (nchunks >= nevents / 2)
nchunks = nevents / 2;
std::cout << "Starting NChunks " << nchunks << std::endl;
sleep(1);
for (int ichunk = 0; ichunk < nchunks; ichunk++) {
// Skip to only do one processing chunk
if (procchunk != -1 and procchunk != ichunk)
continue;
NUIS_LOG(FIT, "On Processing Chunk " << ichunk);
int neventsinchunk = nevents / nchunks;
int loweventinchunk = neventsinchunk * ichunk;
// int higheventinchunk = neventsinchunk * (ichunk + 1);
// Build Chunk Containers for Event Weights
double **weightcont = new double *[nevents];
float **allcoeff = new float *[nevents];
// Load Chunks into Containers
for (int k = 0; k < neventsinchunk; k++) {
weighttree->GetEntry(loweventinchunk + k);
weightcont[k] = new double[nweights];
allcoeff[k] = new float[npar];
bool hasresponse = false;
for (int j = 0; j < nweights; j++) {
weightcont[k][j] = eventweights[j];
if (eventweights[j] != 1.0)
hasresponse = true;
}
if (!hasresponse)
delete weightcont[k];
}
// Loop over ncores and process chunks
// #pragma omp parallel for num_threads(ncores)
for (int k = 0; k < neventsinchunk; k++) {
if (weightcont[k]) {
splwriterlist[int(omp_get_thread_num())]->FitSplinesForEvent(
weightcont[k], allcoeff[k]);
} else {
for (int j = 0; j < npar; j++) {
allcoeff[k][j] = float(0.0);
}
}
if (k + loweventinchunk % 500 == 0) {
if (LOG_LEVEL(REC)) {
printf("Using Thread %d to build event %d in chunk %d \n",
int(omp_get_thread_num()), (int)loweventinchunk + k, ichunk);
}
}
}
// Save Coeff To Tree
std::cout << "Saving coeffs to Tree in Chunk " << ichunk << std::endl;
for (int k = 0; k < neventsinchunk; k++) {
for (int l = 0; l < npar; l++) {
coeff[l] = allcoeff[k][l];
}
// std::cout << "Coeff 0, 1, 2 = " << coeff[0] << " " << coeff[1] << " "
// << coeff[2] << std::endl;
splinetree->Fill();
}
// Delete the container.
for (int k = 0; k < neventsinchunk; k++) {
if (weightcont[k])
delete weightcont[k];
if (allcoeff[k])
delete allcoeff[k];
}
delete allcoeff;
delete weightcont;
}
// Save flux and close file
outputfile->cd();
splinetree->Write();
if (procchunk == -1 or procchunk == 0) {
outputfile->cd();
splwrite->Write("spline_reader");
TTree *nuisanceevents = (TTree *)weightsfile->Get("nuisance_events");
nuisanceevents->CloneTree()->Write();
weighttree->CloneTree()->Write();
TH1D *nuisance_fluxhist = (TH1D *)weightsfile->Get("nuisance_fluxhist");
TH1D *nuisance_eventhist = (TH1D *)weightsfile->Get("nuisance_eventhist");
nuisance_fluxhist->Write("nuisance_fluxhist");
nuisance_eventhist->Write("nuisance_eventhist");
}
weightsfile->Close();
// Add option to build seperate chunks
// Close Output
outputfile->Close();
}
// remove Keys
eventkeys.clear();
}
void SplineRoutines::MergeEventSplinesChunks() {
if (fRW)
delete fRW;
SetupRWEngine();
// Setup the spline reader
SplineWriter *splwrite = new SplineWriter(fRW);
std::vector<nuiskey> splinekeys = Config::QueryKeys("spline");
// Add splines to splinewriter
for (std::vector<nuiskey>::iterator iter = splinekeys.begin();
iter != splinekeys.end(); iter++) {
nuiskey splkey = (*iter);
// Add Spline Info To Reader
splwrite->AddSpline(splkey);
}
splwrite->SetupSplineSet();
std::vector<nuiskey> eventkeys = Config::QueryKeys("events");
for (size_t i = 0; i < eventkeys.size(); i++) {
nuiskey key = eventkeys.at(i);
// Get I/O
std::string inputfilename = key.GetS("input");
if (inputfilename.empty()) {
NUIS_ABORT("No input given for set of input events!");
}
std::string outputfilename = key.GetS("output");
if (outputfilename.empty()) {
outputfilename = inputfilename + ".nuisance.root";
NUIS_ERR(WRN, "No output give for set of output events! Saving to "
<< outputfilename);
}
// Make new outputfile
TFile *outputfile = new TFile(outputfilename.c_str(), "RECREATE");
outputfile->cd();
// Get Weights File
TFile *weightsfile =
new TFile((outputfilename + ".weights.root").c_str(), "READ");
TTree *weighttree = (TTree *)weightsfile->Get("weight_tree");
// Get SPLWRite Info
// splwrite->ReadWeightsFromTree(weighttree);
int nevents = weighttree->GetEntries();
// int countwidth = (nevents / 1000);
// int nweights = splwrite->GetNWeights();
int npar = splwrite->GetNPars();
// Make counter
// int lasttime = time(NULL);
// Setup Splines To Be Saved into TTree
outputfile->cd();
TTree *splinetree = new TTree("spline_tree", "spline_tree");
float *coeff = new float[npar];
splinetree->Branch("SplineCoeff", coeff, Form("SplineCoeff[%d]/F", npar));
// Load N Chunks of the Weights into Memory
// Split into N processing chunks
int nchunks = FitPar::Config().GetParI("spline_chunks");
if (nchunks <= 0)
nchunks = 1;
if (nchunks >= nevents / 2)
nchunks = nevents / 2;
int neventsinchunk = nevents / nchunks;
for (int ichunk = 0; ichunk < nchunks; ichunk++) {
// Get Output File
TFile *chunkfile = new TFile(
(outputfilename + std::string(Form(".coeffchunk_%d.root", ichunk)))
.c_str());
// Get TTree for spline coeffchunk
TTree *splinetreechunk = (TTree *)chunkfile->Get("spline_tree");
// Set Branch Address to coeffchunk
float *coeffchunk = new float[npar];
splinetreechunk->SetBranchAddress("SplineCoeff", coeffchunk);
// Loop over nevents in chunk
for (int k = 0; k < neventsinchunk; k++) {
splinetreechunk->GetEntry(k);
for (int j = 0; j < npar; j++) {
coeff[j] = coeffchunk[j];
}
splinetree->Fill();
}
// Close up
chunkfile->Close();
delete coeffchunk;
std::cout << "Merged chunk " << ichunk << std::endl;
}
// Save flux and close file
outputfile->cd();
splinetree->Write();
outputfile->cd();
splwrite->Write("spline_reader");
TTree *nuisanceevents = (TTree *)weightsfile->Get("nuisance_events");
nuisanceevents->CloneTree()->Write();
weighttree->CloneTree()->Write();
TH1D *nuisance_fluxhist = (TH1D *)weightsfile->Get("nuisance_fluxhist");
TH1D *nuisance_eventhist = (TH1D *)weightsfile->Get("nuisance_eventhist");
nuisance_fluxhist->Write("nuisance_fluxhist");
nuisance_eventhist->Write("nuisance_eventhist");
weightsfile->Close();
// Add option to build seperate chunks
// Close Output
outputfile->Close();
}
// remove Keys
eventkeys.clear();
}
// void SplineRoutines::BuildSplineChunk(){
//}
// void SplineRoutines::MergeSplineChunks(){
//}
//*************************************
void SplineRoutines::MergeSplines() {
//*************************************
// Loop over all 'splinemerge' keys.
// Add them to the Merger.
// Call setup splines.
// Get the key with eventinput
// - remaining keys should have splineinput
// - Loop over number of entries.
// - FillEntry in merger.
// - Fill NUISANCEEvent into a new TTree.
SplineMerger *splmerge = new SplineMerger();
std::vector<nuiskey> splinekeys = Config::QueryKeys("splinemerge");
for (std::vector<nuiskey>::iterator iter = splinekeys.begin();
iter != splinekeys.end(); iter++) {
nuiskey splkey = (*iter);
TFile *infile = new TFile(splkey.GetS("input").c_str(), "READ");
splmerge->AddSplineSetFromFile(infile);
}
splmerge->SetupSplineSet();
// Now get Event File
std::vector<nuiskey> eventkeys = Config::QueryKeys("eventmerge");
nuiskey key = eventkeys[0];
std::string inputfilename = key.GetS("input");
// Make a new input handler
std::vector<std::string> file_descriptor =
GeneralUtils::ParseToStr(inputfilename, ":");
if (file_descriptor.size() != 2) {
NUIS_ABORT("File descriptor had no filetype declaration: \""
<< inputfilename << "\". expected \"FILETYPE:file.root\"");
}
InputUtils::InputType inptype =
InputUtils::ParseInputType(file_descriptor[0]);
InputHandlerBase *input =
InputUtils::CreateInputHandler("eventsaver", inptype, file_descriptor[1]);
std::string outputfilename = key.GetS("output");
if (outputfilename.empty()) {
outputfilename = inputfilename + ".nuisance.root";
NUIS_ERR(WRN, "No output give for set of output events! Saving to "
<< outputfilename);
}
// Make new outputfile
TFile *outputfile = new TFile(outputfilename.c_str(), "RECREATE");
outputfile->cd();
// Get info from inputhandler
int nevents = input->GetNEvents();
int countwidth = (nevents / 1000);
FitEvent *nuisevent = input->FirstNuisanceEvent();
// Setup a TTree to save the event
outputfile->cd();
TTree *eventtree = new TTree("nuisance_events", "nuisance_events");
// Add a flag that allows just splines to be saved.
nuisevent->AddBranchesToTree(eventtree);
// Save the spline reader
splmerge->Write("spline_reader");
// Setup the spline TTree
TTree *splinetree = new TTree("spline_tree", "spline_tree");
splmerge->AddCoefficientsToTree(splinetree);
int lasttime = time(NULL);
int i = 0;
// Loop over all events and fill the TTree
while (nuisevent) {
// Calculate the weights for each parameter set
splmerge->FillMergedSplines(i);
// Save everything
eventtree->Fill();
splinetree->Fill();
// Logging
if (i % countwidth == 0) {
std::ostringstream timestring;
int timeelapsed = time(NULL) - lasttime;
if (i != 0 and timeelapsed) {
lasttime = time(NULL);
int eventsleft = nevents - i;
float speed = float(countwidth) / float(timeelapsed);
float proj = (float(eventsleft) / float(speed)) / 60 / 60;
timestring << proj << " hours remaining.";
}
NUIS_LOG(REC, "Saved " << i << "/" << nevents << " nuisance spline events. "
<< timestring.str());
}
// Iterate
i++;
nuisevent = input->NextNuisanceEvent();
}
// Save flux and close file
outputfile->cd();
eventtree->Write();
splinetree->Write();
input->GetFluxHistogram()->Write("nuisance_fluxhist");
input->GetEventHistogram()->Write("nuisance_eventhist");
// Close Output
outputfile->Close();
// Delete Inputs
delete input;
}
//*************************************
void SplineRoutines::TestSplines_1DEventScan() {
//*************************************
// Setup RW Engine
if (fRW)
delete fRW;
SetupRWEngine();
// Make a spline RW Engine too.
FitWeight *splweight = new FitWeight("splinerwaweight");
// std::vector<nuiskey> splinekeys = Config::QueryKeys("spline");
std::vector<nuiskey> parameterkeys = Config::QueryKeys("parameter");
TH1D *parhisttemplate = new TH1D("parhist", "parhist", parameterkeys.size(),
0.0, float(parameterkeys.size()));
// Add Parameters
for (size_t i = 0; i < parameterkeys.size(); i++) {
nuiskey key = parameterkeys[i];
std::string parname = key.GetS("name");
std::string partype = key.GetS("type");
double nom = key.GetD("nominal");
parhisttemplate->SetBinContent(i + 1, nom);
parhisttemplate->GetXaxis()->SetBinLabel(i + 1, parname.c_str());
splweight->IncludeDial(key.GetS("name"), kSPLINEPARAMETER, nom);
splweight->SetDialValue(key.GetS("name"), key.GetD("nominal"));
}
splweight->Reconfigure();
// Make a high resolution spline set.
std::vector<double> nomvals = fRW->GetDialValues();
// int testres = FitPar::Config().GetParI("spline_test_resolution");
- std::vector<std::vector<double>> scanparset_vals;
+ std::vector<std::vector<double> > scanparset_vals;
std::vector<TH1D *> scanparset_hists;
// Loop over all params
// Add Parameters
for (size_t i = 0; i < parameterkeys.size(); i++) {
nuiskey key = parameterkeys[i];
// Get Par Name
std::string name = key.GetS("name");
if (!key.Has("low") or !key.Has("high") or !key.Has("step")) {
continue;
}
// Push Back Scan
double low = key.GetD("low");
double high = key.GetD("high");
double cur = low;
double step = key.GetD("step");
while (cur <= high) {
// Make new set
std::vector<double> newvals = nomvals;
newvals[i] = cur;
// Add to vects
scanparset_vals.push_back(newvals);
TH1D *parhist = (TH1D *)parhisttemplate->Clone();
for (size_t j = 0; j < newvals.size(); j++) {
parhist->SetBinContent(j + 1, newvals[j]);
}
scanparset_hists.push_back(parhist);
// Move to next one
cur += step;
}
}
// Print out the parameter set to test
for (uint i = 0; i < scanparset_vals.size(); i++) {
std::cout << "Parset " << i;
for (uint j = 0; j < scanparset_vals[i].size(); j++) {
std::cout << " " << scanparset_vals[i][j];
}
std::cout << std::endl;
}
// Weight holders
double *rawweights = new double[scanparset_vals.size()];
double *splweights = new double[scanparset_vals.size()];
double *difweights = new double[scanparset_vals.size()];
int nweights = scanparset_vals.size();
// int NParSets = scanparset_vals.size();
// Loop over all event I/O
std::vector<nuiskey> eventkeys = Config::QueryKeys("events");
for (size_t i = 0; i < eventkeys.size(); i++) {
nuiskey key = eventkeys.at(i);
// Get I/O
std::string inputfilename = key.GetS("input");
if (inputfilename.empty()) {
NUIS_ABORT("No input given for set of input events!")
}
std::string outputfilename = key.GetS("output");
if (outputfilename.empty()) {
outputfilename = inputfilename + ".nuisance.root";
NUIS_ERR(WRN, "No output give for set of output events! Saving to "
<< outputfilename);
}
// Make a new input handler
std::vector<std::string> file_descriptor =
GeneralUtils::ParseToStr(inputfilename, ":");
if (file_descriptor.size() != 2) {
NUIS_ABORT("File descriptor had no filetype declaration: \""
<< inputfilename << "\". expected \"FILETYPE:file.root\"");
}
InputUtils::InputType inptype =
InputUtils::ParseInputType(file_descriptor[0]);
// Make handlers for input and output
InputHandlerBase *input = InputUtils::CreateInputHandler(
"rawevents", inptype, file_descriptor[1]);
InputHandlerBase *output = InputUtils::CreateInputHandler(
"splineevents", InputUtils::kEVSPLN_Input, outputfilename);
// Get Base Events for each case.
FitEvent *rawevent = input->FirstNuisanceEvent();
FitEvent *splevent = output->FirstNuisanceEvent();
// Setup outputfile
std::string outputtest = outputfilename + ".splinetest.1DEventScan.root";
TFile *outputtestfile = new TFile(outputtest.c_str(), "RECREATE");
outputtestfile->cd();
// Save Parameter Sets
for (size_t i = 0; i < scanparset_hists.size(); i++) {
scanparset_hists[i]->Write(Form("Paramater_Set_%i", (int)i));
}
// Save a TTree of weights and differences.
TTree *weighttree = new TTree("weightscan", "weightscan");
// Make a branch for each weight set
for (size_t i = 0; i < scanparset_hists.size(); i++) {
weighttree->Branch(Form("RawWeights_Set_%i", (int)i), &rawweights[i],
Form("RawWeights_Set_%i/D", (int)i));
weighttree->Branch(Form("SplineWeights_Set_%i", (int)i), &splweights[i],
Form("SplineWeights_Set_%i/D", (int)i));
weighttree->Branch(Form("DifWeights_Set_%i", (int)i), &difweights[i],
Form("DifWeights_Set_%i/D", (int)i));
}
// Count
// int i = 0;
int nevents = input->GetNEvents();
int lasttime = time(NULL);
// Load N Chunks of the Weights into Memory
// Split into N processing chunks
int nchunks = FitPar::Config().GetParI("spline_chunks");
if (nchunks <= 0)
nchunks = 1;
if (nchunks >= nevents / 2)
nchunks = nevents / 2;
std::cout << "Starting NChunks " << nchunks << std::endl;
for (int ichunk = 0; ichunk < nchunks; ichunk++) {
// Skip to only do one processing chunk
// if (procchunk != -1 and procchunk != ichunk) continue;
NUIS_LOG(FIT, "On Processing Chunk " << ichunk);
int neventsinchunk = nevents / nchunks;
int loweventinchunk = neventsinchunk * ichunk;
// int higheventinchunk = neventsinchunk * (ichunk + 1);
double **allrawweights = new double *[neventsinchunk];
double **allsplweights = new double *[neventsinchunk];
double **alldifweights = new double *[neventsinchunk];
for (int k = 0; k < neventsinchunk; k++) {
allrawweights[k] = new double[nweights];
allsplweights[k] = new double[nweights];
alldifweights[k] = new double[nweights];
}
// Start Set Processing Here.
for (int iset = 0; iset < nweights; iset++) {
// Reconfigure
fRW->SetAllDials(&scanparset_vals[iset][0],
scanparset_vals[iset].size());
fRW->Reconfigure();
// Reconfigure spline RW
splweight->SetAllDials(&scanparset_vals[iset][0],
scanparset_vals[iset].size());
splweight->Reconfigure();
splevent->fSplineRead->SetNeedsReconfigure(true);
// Could reorder this to save the weightconts in order instead of
// reconfiguring per event. Loop over all events and fill the TTree
for (int i = 0; i < neventsinchunk; i++) {
rawevent = input->GetNuisanceEvent(i + loweventinchunk);
splevent = output->GetNuisanceEvent(i + loweventinchunk);
allrawweights[i][iset] = fRW->CalcWeight(rawevent);
allsplweights[i][iset] = splweight->CalcWeight(splevent);
alldifweights[i][iset] =
allsplweights[i][iset] - allrawweights[i][iset];
}
std::ostringstream timestring;
int timeelapsed = time(NULL) - lasttime;
if (timeelapsed) {
lasttime = time(NULL);
int setsleft =
(nweights - iset - 1) + (nweights * (nchunks - ichunk - 1));
float proj = (float(setsleft) * timeelapsed) / 60 / 60;
timestring << setsleft << " sets remaining. Last one took "
<< timeelapsed << ". " << proj << " hours remaining.";
}
NUIS_LOG(REC, "Processed Set " << iset << "/" << nweights << " in chunk "
<< ichunk << "/" << nchunks << " "
<< timestring.str());
}
// Fill weights for this chunk into the TTree
for (int k = 0; k < neventsinchunk; k++) {
for (int l = 0; l < nweights; l++) {
rawweights[l] = allrawweights[k][l];
splweights[l] = allsplweights[k][l];
difweights[l] = alldifweights[k][l];
}
weighttree->Fill();
}
}
// Loop over nchunks
// Loop over parameter sets
// Set All Dials and reconfigure
// Loop over events in chunk
// Fill Chunkweightcontainers
// Once all dials are done, fill the weight tree
// Iterator to next chunk
outputtestfile->cd();
weighttree->Write();
outputtestfile->Close();
}
}
/*
// Make a high resolution spline set.
std::vector<double> nomvals = fRW->GetDialValues();
int testres = FitPar::Config().GetParI("spline_test_resolution");
std::vector< std::vector<double> > scanparset_vals;
std::vector< TH1D* > scanparset_hists;
// Loop over all params
// Add Parameters
for (size_t i = 0; i < parameterkeys.size(); i++) {
nuiskey key = parameterkeys[i];
// Get Par Name
std::string name = key.GetS("name");
if (!key.Has("low") or !key.Has("high") or !key.Has("step")) {
continue;
}
// Push Back Scan
double low = key.GetD("low");
double high = key.GetD("high");
double cur = low;
double step = key.GetD("step");
while (cur <= high) {
// Make new set
std::vector<double> newvals = nomvals;
newvals[i] = cur;
// Add to vects
scanparset_vals.push_back(newvals);
TH1D* parhist = (TH1D*)parhisttemplate->Clone();
for (size_t j = 0; j < newvals.size(); j++) {
parhist->SetBinContent(j + 1, newvals[j]);
}
scanparset_hists.push_back(parhist);
// Move to next one
cur += step;
}
}
// Print out the parameter set to test
for (int i = 0; i < scanparset_vals.size(); i++) {
std::cout << "Parset " << i;
for (int j = 0 ; j < scanparset_vals[i].size(); j++) {
std::cout << " " << scanparset_vals[i][j];
}
std::cout << std::endl;
}
// Weight holders
double* rawweights = new double[scanparset_vals.size()];
double* splweights = new double[scanparset_vals.size()];
double* difweights = new double[scanparset_vals.size()];
int NParSets = scanparset_vals.size();
// Loop over all event I/O
std::vector<nuiskey> eventkeys = Config::QueryKeys("events");
for (size_t i = 0; i < eventkeys.size(); i++) {
nuiskey key = eventkeys.at(i);
// Get I/O
std::string inputfilename = key.GetS("input");
if (inputfilename.empty()) {
ERR(FTL) << "No input given for set of input events!" << std::endl;
throw;
}
std::string outputfilename = key.GetS("output");
if (outputfilename.empty()) {
outputfilename = inputfilename + ".nuisance.root";
ERR(FTL) << "No output give for set of output events! Saving to "
<< outputfilename << std::endl;
}
// Make a new input handler
std::vector<std::string> file_descriptor =
GeneralUtils::ParseToStr(inputfilename, ":");
if (file_descriptor.size() != 2) {
ERR(FTL) << "File descriptor had no filetype declaration: \"" <<
inputfilename
<< "\". expected \"FILETYPE:file.root\"" << std::endl;
throw;
}
InputUtils::InputType inptype =
InputUtils::ParseInputType(file_descriptor[0]);
// Make handlers for input and output
InputHandlerBase* input = InputUtils::CreateInputHandler("rawevents",
inptype, file_descriptor[1]); InputHandlerBase* output =
InputUtils::CreateInputHandler("splineevents", InputUtils::kEVSPLN_Input,
outputfilename);
// Get Base Events for each case.
FitEvent* rawevent = input->FirstNuisanceEvent();
FitEvent* splevent = output->FirstNuisanceEvent();
// Setup outputfile
std::string outputtest = outputfilename + ".splinetest.1DEventScan.root";
TFile* outputtestfile = new TFile(outputtest.c_str(), "RECREATE");
outputtestfile->cd();
// Save Parameter Sets
for (size_t i = 0; i < scanparset_hists.size(); i++) {
scanparset_hists[i]->Write(Form("Paramater_Set_%i", (int)i));
}
// Save a TTree of weights and differences.
TTree* weighttree = new TTree("weightscan", "weightscan");
// Make a branch for each weight set
for (size_t i = 0; i < scanparset_hists.size(); i++) {
weighttree->Branch(Form("RawWeights_Set_%i", (int)i), &rawweights[i],
Form("RawWeights_Set_%i/D", (int)i) );
weighttree->Branch(Form("SplineWeights_Set_%i", (int)i), &splweights[i],
Form("SplineWeights_Set_%i/D", (int)i) );
weighttree->Branch(Form("DifWeights_Set_%i", (int)i), &difweights[i],
Form("DifWeights_Set_%i/D", (int)i) );
}
// Count
int i = 0;
int nevents = input->GetNEvents();
while (rawevent and splevent) {
// Loop over 1D parameter sets.
for (size_t j = 0; j < scanparset_vals.size(); j++) {
// Reconfigure
fRW->SetAllDials(&scanparset_vals[j][0], scanparset_vals[j].size());
fRW->Reconfigure();
// Reconfigure spline RW
splweight->SetAllDials(&scanparset_vals[j][0],
scanparset_vals[j].size()); splweight->Reconfigure();
splevent->fSplineRead->SetNeedsReconfigure(true);
// Calc weight for both events
rawweights[j] = fRW->CalcWeight(rawevent);
splweights[j] = splweight->CalcWeight(splevent);
difweights[j] = splweights[j] - rawweights[j];
}
if (i % 1000 == 0) {
LOG(FIT) << "Processed " << i << "/" << nevents << std::endl;
}
// Fill Array
weighttree->Fill();
// Iterate to next event.
i++;
rawevent = input->NextNuisanceEvent();
splevent = output->NextNuisanceEvent();
}
outputtestfile->cd();
weighttree->Write();
outputtestfile->Close();
}
}
*/
//*************************************
void SplineRoutines::TestSplines_NDEventThrow() {
//*************************************
// Setup RW Engine
if (fRW)
delete fRW;
SetupRWEngine();
// Make a spline RW Engine too.
FitWeight *splweight = new FitWeight("splinerwaweight");
std::vector<nuiskey> parameterkeys = Config::QueryKeys("parameter");
TH1D *parhisttemplate = new TH1D("parhist", "parhist", parameterkeys.size(),
0.0, float(parameterkeys.size()));
// Add Parameters
for (size_t i = 0; i < parameterkeys.size(); i++) {
nuiskey key = parameterkeys[i];
std::string parname = key.GetS("name");
std::string partype = key.GetS("type");
double nom = key.GetD("nominal");
parhisttemplate->SetBinContent(i + 1, nom);
parhisttemplate->GetXaxis()->SetBinLabel(i + 1, parname.c_str());
splweight->IncludeDial(key.GetS("name"), kSPLINEPARAMETER, nom);
splweight->SetDialValue(key.GetS("name"), key.GetD("nominal"));
}
splweight->Reconfigure();
// Make a high resolution spline set.
std::vector<double> nomvals = fRW->GetDialValues();
// int testres = FitPar::Config().GetParI("spline_test_resolution");
std::vector<std::string> scanparset_names;
- std::vector<std::vector<double>> scanparset_vals;
+ std::vector<std::vector<double> > scanparset_vals;
std::vector<TH1D *> scanparset_hists;
// Loop over all params
// Add Parameters
int nthrows = FitPar::Config().GetParI("spline_test_throws");
for (int i = 0; i < nthrows; i++) {
std::vector<double> newvals = nomvals;
for (size_t j = 0; j < parameterkeys.size(); j++) {
nuiskey key = parameterkeys[j];
if (!key.Has("low") or !key.Has("high") or !key.Has("step")) {
continue;
}
// Push Back Scan
double low = key.GetD("low");
double high = key.GetD("high");
newvals[j] = gRandom->Uniform(low, high);
}
// Add to vects
scanparset_vals.push_back(newvals);
TH1D *parhist = (TH1D *)parhisttemplate->Clone();
for (size_t j = 0; j < newvals.size(); j++) {
parhist->SetBinContent(j + 1, newvals[j]);
}
scanparset_hists.push_back(parhist);
}
// Print out the parameter set to test
for (uint i = 0; i < scanparset_vals.size(); i++) {
std::cout << "Parset " << i;
for (uint j = 0; j < scanparset_vals[i].size(); j++) {
std::cout << " " << scanparset_vals[i][j];
}
std::cout << std::endl;
}
// Weight holders
double *rawweights = new double[scanparset_vals.size()];
double *splweights = new double[scanparset_vals.size()];
double *difweights = new double[scanparset_vals.size()];
int nweights = scanparset_vals.size();
// int NParSets = scanparset_vals.size();
// Loop over all event I/O
std::vector<nuiskey> eventkeys = Config::QueryKeys("events");
for (size_t i = 0; i < eventkeys.size(); i++) {
nuiskey key = eventkeys.at(i);
// Get I/O
std::string inputfilename = key.GetS("input");
if (inputfilename.empty()) {
NUIS_ABORT("No input given for set of input events!");
}
std::string outputfilename = key.GetS("output");
if (outputfilename.empty()) {
outputfilename = inputfilename + ".nuisance.root";
NUIS_ERR(WRN, "No output give for set of output events! Saving to "
<< outputfilename);
}
// Make a new input handler
std::vector<std::string> file_descriptor =
GeneralUtils::ParseToStr(inputfilename, ":");
if (file_descriptor.size() != 2) {
NUIS_ABORT("File descriptor had no filetype declaration: \""
<< inputfilename << "\". expected \"FILETYPE:file.root\"");
}
InputUtils::InputType inptype =
InputUtils::ParseInputType(file_descriptor[0]);
// Make handlers for input and output
InputHandlerBase *input = InputUtils::CreateInputHandler(
"rawevents", inptype, file_descriptor[1]);
InputHandlerBase *output = InputUtils::CreateInputHandler(
"splineevents", InputUtils::kEVSPLN_Input, outputfilename);
// Get Base Events for each case.
FitEvent *rawevent = input->FirstNuisanceEvent();
FitEvent *splevent = output->FirstNuisanceEvent();
// Setup outputfile
std::string outputtest = outputfilename + ".splinetest.NDEventThrow.root";
TFile *outputtestfile = new TFile(outputtest.c_str(), "RECREATE");
outputtestfile->cd();
// Save Parameter Sets
for (size_t i = 0; i < scanparset_hists.size(); i++) {
scanparset_hists[i]->Write(Form("Paramater_Set_%i", (int)i));
}
// Save a TTree of weights and differences.
TTree *weighttree = new TTree("weightscan", "weightscan");
// Make a branch for each weight set
for (size_t i = 0; i < scanparset_hists.size(); i++) {
weighttree->Branch(Form("RawWeights_Set_%i", (int)i), &rawweights[i],
Form("RawWeights_Set_%i/D", (int)i));
weighttree->Branch(Form("SplineWeights_Set_%i", (int)i), &splweights[i],
Form("SplineWeights_Set_%i/D", (int)i));
weighttree->Branch(Form("DifWeights_Set_%i", (int)i), &difweights[i],
Form("DifWeights_Set_%i/D", (int)i));
}
// Count
// int i = 0;
int nevents = input->GetNEvents();
int lasttime = time(NULL);
// Load N Chunks of the Weights into Memory
// Split into N processing chunks
int nchunks = FitPar::Config().GetParI("spline_chunks");
if (nchunks <= 0)
nchunks = 1;
if (nchunks >= nevents / 2)
nchunks = nevents / 2;
std::cout << "Starting NChunks " << nchunks << std::endl;
for (int ichunk = 0; ichunk < nchunks; ichunk++) {
// Skip to only do one processing chunk
// if (procchunk != -1 and procchunk != ichunk) continue;
NUIS_LOG(FIT, "On Processing Chunk " << ichunk);
int neventsinchunk = nevents / nchunks;
int loweventinchunk = neventsinchunk * ichunk;
// int higheventinchunk = neventsinchunk * (ichunk + 1);
double **allrawweights = new double *[neventsinchunk];
double **allsplweights = new double *[neventsinchunk];
double **alldifweights = new double *[neventsinchunk];
for (int k = 0; k < neventsinchunk; k++) {
allrawweights[k] = new double[nweights];
allsplweights[k] = new double[nweights];
alldifweights[k] = new double[nweights];
}
// Start Set Processing Here.
for (int iset = 0; iset < nweights; iset++) {
// Reconfigure
fRW->SetAllDials(&scanparset_vals[iset][0],
scanparset_vals[iset].size());
fRW->Reconfigure();
// Reconfigure spline RW
splweight->SetAllDials(&scanparset_vals[iset][0],
scanparset_vals[iset].size());
splweight->Reconfigure();
splevent->fSplineRead->SetNeedsReconfigure(true);
// Could reorder this to save the weightconts in order instead of
// reconfiguring per event. Loop over all events and fill the TTree
for (int i = 0; i < neventsinchunk; i++) {
rawevent = input->GetNuisanceEvent(i + loweventinchunk);
splevent = output->GetNuisanceEvent(i + loweventinchunk);
allrawweights[i][iset] = fRW->CalcWeight(rawevent);
allsplweights[i][iset] = splweight->CalcWeight(splevent);
alldifweights[i][iset] =
allsplweights[i][iset] - allrawweights[i][iset];
}
std::ostringstream timestring;
int timeelapsed = time(NULL) - lasttime;
if (timeelapsed) {
lasttime = time(NULL);
int setsleft =
(nweights - iset - 1) + (nweights * (nchunks - ichunk - 1));
float proj = (float(setsleft) * timeelapsed) / 60 / 60;
timestring << setsleft << " sets remaining. Last one took "
<< timeelapsed << ". " << proj << " hours remaining.";
}
NUIS_LOG(REC, "Processed Set " << iset << "/" << nweights << " in chunk "
<< ichunk << "/" << nchunks << " "
<< timestring.str());
}
// Fill weights for this chunk into the TTree
for (int k = 0; k < neventsinchunk; k++) {
for (int l = 0; l < nweights; l++) {
rawweights[l] = allrawweights[k][l];
splweights[l] = allsplweights[k][l];
difweights[l] = alldifweights[k][l];
}
weighttree->Fill();
}
}
// Loop over nchunks
// Loop over parameter sets
// Set All Dials and reconfigure
// Loop over events in chunk
// Fill Chunkweightcontainers
// Once all dials are done, fill the weight tree
// Iterator to next chunk
outputtestfile->cd();
weighttree->Write();
outputtestfile->Close();
}
}
void SplineRoutines::SaveSplinePlots() {
if (fRW)
delete fRW;
SetupRWEngine();
// Setup the spline reader
SplineWriter *splwrite = new SplineWriter(fRW);
std::vector<nuiskey> splinekeys = Config::QueryKeys("spline");
// Add splines to splinewriter
for (std::vector<nuiskey>::iterator iter = splinekeys.begin();
iter != splinekeys.end(); iter++) {
nuiskey splkey = (*iter);
// Add Spline Info To Reader
splwrite->AddSpline(splkey);
}
splwrite->SetupSplineSet();
// Event Loop
// Loop over all events and calculate weights for each parameter set.
// Generate a set of nominal events
// Method, Loop over inputs, create input handler, then create a ttree
std::vector<nuiskey> eventkeys = Config::QueryKeys("events");
for (size_t i = 0; i < eventkeys.size(); i++) {
nuiskey key = eventkeys.at(i);
// Get I/O
std::string inputfilename = key.GetS("input");
if (inputfilename.empty()) {
NUIS_ABORT("No input given for set of input events!");
}
std::string outputfilename = key.GetS("output");
if (outputfilename.empty()) {
outputfilename = inputfilename + ".nuisance.root";
NUIS_ERR(WRN, "No output give for set of output events! Saving to "
<< outputfilename);
}
// Make new outputfile
outputfilename += ".SplinePlots.root";
TFile *outputfile = new TFile(outputfilename.c_str(), "RECREATE");
outputfile->cd();
// Make a new input handler
std::vector<std::string> file_descriptor =
GeneralUtils::ParseToStr(inputfilename, ":");
if (file_descriptor.size() != 2) {
NUIS_ABORT("File descriptor had no filetype declaration: \""
<< inputfilename << "\". expected \"FILETYPE:file.root\"");
}
InputUtils::InputType inptype =
InputUtils::ParseInputType(file_descriptor[0]);
InputHandlerBase *input = InputUtils::CreateInputHandler(
"eventsaver", inptype, file_descriptor[1]);
// Get info from inputhandler
int nevents = input->GetNEvents();
int countwidth = (nevents / 1000);
FitEvent *nuisevent = input->FirstNuisanceEvent();
outputfile->cd();
// int lasttime = time(NULL);
TCanvas *fitcanvas = NULL;
// Loop over all events and fill the TTree
while (nuisevent) {
// std::cout << "Fitting event " << i << std::endl;
// Calculate the weights for each parameter set
splwrite->GetWeightsForEvent(nuisevent);
splwrite->FitSplinesForEvent(fitcanvas, true);
if (fitcanvas) {
outputfile->cd();
fitcanvas->Write(Form("Event_SplineCanvas_%i", (int)i));
}
// Logging
if (i % countwidth == 0) {
NUIS_LOG(REC,
"Saved " << i << "/" << nevents << " nuisance spline plots. ");
}
// Iterate
i++;
nuisevent = input->NextNuisanceEvent();
}
// Save flux and close file
outputfile->cd();
// Close Output
outputfile->Close();
// Delete Inputs
delete input;
}
// remove Keys
eventkeys.clear();
}
void SplineRoutines::TestSplines_NDLikelihoodThrow() {
// Setup RW Engine
if (fRW)
delete fRW;
SetupRWEngine();
// Make a spline RW Engine too.
FitWeight *splweight = new FitWeight("splinerwaweight");
std::vector<nuiskey> parameterkeys = Config::QueryKeys("parameter");
TH1D *parhisttemplate = new TH1D("parhist", "parhist", parameterkeys.size(),
0.0, float(parameterkeys.size()));
// Add Parameters
for (size_t i = 0; i < parameterkeys.size(); i++) {
nuiskey key = parameterkeys[i];
std::string parname = key.GetS("name");
std::string partype = key.GetS("type");
double nom = key.GetD("nominal");
parhisttemplate->SetBinContent(i + 1, nom);
parhisttemplate->GetXaxis()->SetBinLabel(i + 1, parname.c_str());
splweight->IncludeDial(key.GetS("name"), kSPLINEPARAMETER, nom);
splweight->SetDialValue(key.GetS("name"), key.GetD("nominal"));
}
splweight->Reconfigure();
// Make a high resolution spline set.
std::vector<double> nomvals = fRW->GetDialValues();
// int testres = FitPar::Config().GetParI("spline_test_resolution");
std::vector<std::string> scanparset_names;
- std::vector<std::vector<double>> scanparset_vals;
+ std::vector<std::vector<double> > scanparset_vals;
std::vector<TH1D *> scanparset_hists;
// Loop over all params
// Add Parameters
int nthrows = FitPar::Config().GetParI("spline_test_throws");
for (int i = 0; i < nthrows; i++) {
std::vector<double> newvals = nomvals;
for (size_t j = 0; j < parameterkeys.size(); j++) {
nuiskey key = parameterkeys[j];
if (!key.Has("low") or !key.Has("high") or !key.Has("step")) {
continue;
}
// Push Back Scan
double low = key.GetD("low");
double high = key.GetD("high");
newvals[j] = gRandom->Uniform(low, high);
}
// Add to vects
scanparset_vals.push_back(newvals);
TH1D *parhist = (TH1D *)parhisttemplate->Clone();
for (size_t j = 0; j < newvals.size(); j++) {
parhist->SetBinContent(j + 1, newvals[j]);
}
scanparset_hists.push_back(parhist);
}
// Print out the parameter set to test
for (uint i = 0; i < scanparset_vals.size(); i++) {
std::cout << "Parset " << i;
for (uint j = 0; j < scanparset_vals[i].size(); j++) {
std::cout << " " << scanparset_vals[i][j];
}
std::cout << std::endl;
}
// Make a new set of Raw/Spline Sample Keys
std::vector<nuiskey> eventkeys = Config::QueryKeys("events");
std::vector<nuiskey> testkeys = Config::QueryKeys("sampletest");
std::vector<nuiskey> rawkeys;
std::vector<nuiskey> splkeys;
for (std::vector<nuiskey>::iterator iter = testkeys.begin();
iter != testkeys.end(); iter++) {
nuiskey key = (*iter);
std::string samplename = key.GetS("name");
std::string eventsid = key.GetS("inputid");
nuiskey eventskey = Config::QueryLastKey("events", "id=" + eventsid);
std::string rawfile = eventskey.GetS("input");
std::string splfile = eventskey.GetS("output");
nuiskey rawkeytemp = Config::CreateKey("sample");
rawkeytemp.SetS("name", samplename);
rawkeytemp.SetS("input", rawfile);
nuiskey splkeytemp = Config::CreateKey("sample");
splkeytemp.SetS("name", samplename);
splkeytemp.SetS("input", "EVSPLN:" + splfile);
rawkeys.push_back(rawkeytemp);
splkeys.push_back(splkeytemp);
}
if (fOutputRootFile)
delete fOutputRootFile;
fOutputRootFile = new TFile(fOutputFile.c_str(), "RECREATE");
fOutputRootFile->ls();
// Make two new JointFCN
JointFCN *rawfcn = new JointFCN(rawkeys, fOutputRootFile);
JointFCN *splfcn = new JointFCN(splkeys, fOutputRootFile);
// Create iteration tree in output file
fOutputRootFile->cd();
rawfcn->CreateIterationTree("raw_iterations", fRW);
splfcn->CreateIterationTree("spl_iterations", splweight);
// Loop over parameter sets.
for (size_t j = 0; j < scanparset_vals.size(); j++) {
FitBase::SetRW(fRW);
double rawtotal = rawfcn->DoEval(&scanparset_vals[j][0]);
FitBase::SetRW(splweight);
double spltotal = splfcn->DoEval(&scanparset_vals[j][0]);
NUIS_LOG(FIT, "RAW SPLINE DIF = " << rawtotal << " " << spltotal << " "
<< spltotal - rawtotal);
}
fOutputRootFile->cd();
rawfcn->WriteIterationTree();
splfcn->WriteIterationTree();
}
void SplineRoutines::TestSplines_1DLikelihoodScan() {
// Setup RW Engine.
if (fRW)
delete fRW;
SetupRWEngine();
// Setup Parameter Set.
// Make a spline RW Engine too.
FitWeight *splweight = new FitWeight("splinerwaweight");
// std::vector<nuiskey> splinekeys = Config::QueryKeys("spline");
std::vector<nuiskey> parameterkeys = Config::QueryKeys("parameter");
TH1D *parhisttemplate = new TH1D("parhist", "parhist", parameterkeys.size(),
0.0, float(parameterkeys.size()));
// Add Parameters
for (size_t i = 0; i < parameterkeys.size(); i++) {
nuiskey key = parameterkeys[i];
std::string parname = key.GetS("name");
std::string partype = key.GetS("type");
double nom = key.GetD("nominal");
parhisttemplate->SetBinContent(i + 1, nom);
parhisttemplate->GetXaxis()->SetBinLabel(i + 1, parname.c_str());
splweight->IncludeDial(key.GetS("name"), kSPLINEPARAMETER, nom);
splweight->SetDialValue(key.GetS("name"), key.GetD("nominal"));
}
splweight->Reconfigure();
// Make a high resolution spline set.
std::vector<double> nomvals = fRW->GetDialValues();
// int testres = FitPar::Config().GetParI("spline_test_resolution");
- std::vector<std::vector<double>> scanparset_vals;
+ std::vector<std::vector<double> > scanparset_vals;
std::vector<TH1D *> scanparset_hists;
// Loop over all params
// Add Parameters
for (size_t i = 0; i < parameterkeys.size(); i++) {
nuiskey key = parameterkeys[i];
// Get Par Name
std::string name = key.GetS("name");
if (!key.Has("low") or !key.Has("high") or !key.Has("step")) {
continue;
}
// Push Back Scan
double low = key.GetD("low");
double high = key.GetD("high");
double cur = low;
double step = key.GetD("step");
while (cur <= high) {
// Make new set
std::vector<double> newvals = nomvals;
newvals[i] = cur;
// Add to vects
scanparset_vals.push_back(newvals);
TH1D *parhist = (TH1D *)parhisttemplate->Clone();
for (size_t j = 0; j < newvals.size(); j++) {
parhist->SetBinContent(j + 1, newvals[j]);
}
scanparset_hists.push_back(parhist);
// Move to next one
cur += step;
}
}
// Print out the parameter set to test
for (uint i = 0; i < scanparset_vals.size(); i++) {
std::cout << "Parset " << i;
for (uint j = 0; j < scanparset_vals[i].size(); j++) {
std::cout << " " << scanparset_vals[i][j];
}
std::cout << std::endl;
}
// Make a new set of Raw/Spline Sample Keys
std::vector<nuiskey> eventkeys = Config::QueryKeys("events");
std::vector<nuiskey> testkeys = Config::QueryKeys("sampletest");
std::vector<nuiskey> rawkeys;
std::vector<nuiskey> splkeys;
for (std::vector<nuiskey>::iterator iter = testkeys.begin();
iter != testkeys.end(); iter++) {
nuiskey key = (*iter);
std::string samplename = key.GetS("name");
std::string eventsid = key.GetS("inputid");
nuiskey eventskey = Config::QueryLastKey("events", "id=" + eventsid);
std::string rawfile = eventskey.GetS("input");
std::string splfile = eventskey.GetS("output");
nuiskey rawkeytemp = Config::CreateKey("sample");
rawkeytemp.SetS("name", samplename);
rawkeytemp.SetS("input", rawfile);
nuiskey splkeytemp = Config::CreateKey("sample");
splkeytemp.SetS("name", samplename);
splkeytemp.SetS("input", "EVSPLN:" + splfile);
rawkeys.push_back(rawkeytemp);
splkeys.push_back(splkeytemp);
}
if (fOutputRootFile)
delete fOutputRootFile;
fOutputRootFile = new TFile(fOutputFile.c_str(), "RECREATE");
fOutputRootFile->ls();
// Make two new JointFCN
JointFCN *rawfcn = new JointFCN(rawkeys, fOutputRootFile);
JointFCN *splfcn = new JointFCN(splkeys, fOutputRootFile);
// Create iteration tree in output file
fOutputRootFile->cd();
rawfcn->CreateIterationTree("raw_iterations", fRW);
splfcn->CreateIterationTree("spl_iterations", splweight);
// Loop over parameter sets.
for (size_t j = 0; j < scanparset_vals.size(); j++) {
FitBase::SetRW(fRW);
double rawtotal = rawfcn->DoEval(&scanparset_vals[j][0]);
FitBase::SetRW(splweight);
double spltotal = splfcn->DoEval(&scanparset_vals[j][0]);
NUIS_LOG(FIT, "RAW SPLINE DIF = " << rawtotal << " " << spltotal << " "
<< spltotal - rawtotal);
}
fOutputRootFile->cd();
rawfcn->WriteIterationTree();
splfcn->WriteIterationTree();
}
/*
MISC Functions
*/
//*************************************
int SplineRoutines::GetStatus() {
//*************************************
return 0;
}
diff --git a/src/Splines/Spline.cxx b/src/Splines/Spline.cxx
index 54bc6e0..4e022e2 100644
--- a/src/Splines/Spline.cxx
+++ b/src/Splines/Spline.cxx
@@ -1,473 +1,473 @@
#include "Spline.h"
using namespace SplineUtils;
// Setup Functions
// ----------------------------------------------
Spline::Spline(std::string splname, std::string form, std::string points) {
// Save Definition
fName = splname;
fForm = form;
fPoints = points;
fROOTFunction = NULL;
// Setup Min Max for each Parameter
fSplitNames = GeneralUtils::ParseToStr(splname, ";");
- std::vector<std::vector<double>> gridvals =
+ std::vector<std::vector<double> > gridvals =
SplineUtils::GetSplitDialPoints(fPoints);
for (size_t i = 0; i < fSplitNames.size(); i++) {
for (size_t j = 0; j < gridvals.size(); j++) {
if (i == 0)
fXScan.push_back(gridvals[j][0]);
if (i == 1)
fXScan.push_back(gridvals[j][1]);
}
double xmin = 9999.9;
double xmax = -9999.9;
for (size_t j = 0; j < gridvals.size(); j++) {
if (gridvals[j][i] < xmin)
xmin = gridvals[j][i];
if (gridvals[j][i] > xmax)
xmax = gridvals[j][i];
}
fVal.push_back(0.0);
fValMin.push_back(xmin);
fValMax.push_back(xmax);
// Define TSpline3 1D iterators here
if (i == 0) {
iter_low = fXScan.begin();
iter_high = fXScan.begin();
iter_high++;
off = 0;
}
}
// Set form from list
if (!fForm.compare("1DPol1")) {
Setup(k1DPol1, 1, 2);
} else if (!fForm.compare("1DPol2")) {
Setup(k1DPol2, 1, 3);
} else if (!fForm.compare("1DPol3")) {
Setup(k1DPol3, 1, 4);
} else if (!fForm.compare("1DPol4")) {
Setup(k1DPol4, 1, 5);
} else if (!fForm.compare("1DPol5")) {
Setup(k1DPol5, 1, 6);
} else if (!fForm.compare("1DPol6")) {
Setup(k1DPol6, 1, 7);
} else if (!fForm.compare("1DTSpline3")) {
Setup(k1DTSpline3, 1, fXScan.size() * 4);
} else if (!fForm.compare("2DPol6")) {
Setup(k2DPol6, 2, 28);
} else if (!fForm.compare("2DGaus")) {
Setup(k2DGaus, 2, 8);
} else if (!fForm.compare("2DTSpline3")) {
Setup(k2DTSpline3, 2, fXScan.size() * fYScan.size() * 8);
} else {
NUIS_ABORT("Unknown spline form : " << fForm);
}
// Run Checks
if ((UInt_t)fNDim != fSplitNames.size()) {
NUIS_ABORT("Spline Dim:Names mismatch!");
}
NUIS_LOG(SAM, "Setup Spline " << fForm << " = " << fType << " " << fNPar);
};
void Spline::Setup(int type, int ndim, int npar) {
fType = type;
fNDim = ndim;
fNPar = npar;
}
// Reconfigure Functions
// ----------------------------------------------
void Spline::Reconfigure(float x, int index) {
// std::cout << "Reconfigured spline : " << fName << " : " << fForm << " to be
// " << x << " " << index << std::endl;
fVal[index] = x;
fOutsideLimits = false;
if (fVal[index] > fValMax[index])
fVal[index] = fValMax[index];
if (fVal[index] < fValMin[index])
fVal[index] = fValMin[index];
// std::cout << "Set at edge = " << fVal[index] << " " << index << std::endl;
}
void Spline::Reconfigure(std::string name, float x) {
for (size_t i = 0; i < fSplitNames.size(); i++) {
// std::cout << "-> Comparing in spline " << name << " to " <<
// fSplitNames[i] << " = " << !fSplitNames[i].compare(name.c_str()) <<
// std::endl;
if (!fSplitNames[i].compare(name.c_str())) {
// std::cout << "-> Reconfigured spline : " << fSplitNames[i] << " " <<
// name << " to be " << x << " " << i << std::endl;
Reconfigure(x, i);
}
}
}
// Evaluation Functions
// ----------------------------------------------
double Spline::operator()(const Double_t *x, const Double_t *par) {
Float_t *tempx = new Float_t[fNDim];
for (size_t i = 0; i < (UInt_t)fNDim; i++) {
tempx[i] = x[i];
}
Float_t *tempp = new Float_t[fNPar];
for (size_t i = 0; i < (UInt_t)fNPar; i++) {
tempp[i] = par[i];
}
float val = DoEval(tempx, tempp);
delete tempp;
delete tempx;
if (val < 0.0)
val = 0.0;
return val;
}
double Spline::DoEvalPar(const double *x, const double *p) const {
Float_t *tempx = new Float_t[fNDim];
for (size_t i = 0; i < (UInt_t)fNDim; i++) {
tempx[i] = x[i];
}
Float_t *tempp = new Float_t[fNPar];
for (size_t i = 0; i < (UInt_t)fNPar; i++) {
tempp[i] = p[i];
}
float val = DoEval(tempx, tempp);
delete tempp;
delete tempx;
if (val < 0.0)
val = 0.0;
return val;
}
float Spline::operator()(const Float_t *x, const Float_t *par) const {
float val = DoEval(x, par);
if (val < 0.0)
val = 0.0;
return val;
}
float Spline::DoEval(const Float_t *x, const Float_t *par) const {
// Setup current fX to value
for (size_t i = 0; i < (UInt_t)fNDim; i++) {
fVal[i] = x[i];
if (fVal[i] > fValMax[i])
fVal[i] = fValMax[i];
if (fVal[i] < fValMin[i])
fVal[i] = fValMin[i];
}
double w = DoEval(&par[0], false);
if (w < 0.0)
w = 0.0;
// Now evaluate spline how FitWeight will do it.
return w;
}
float Spline::DoEval(const Float_t *par, bool checkresponse) const {
if (!par)
return 1.0;
// std::cout << "Spline::DoEval = " << par << std::endl;
// Check response
if (checkresponse) {
bool hasresponse = false;
for (int i = 0; i < fNPar; i++) {
if (par[i] != 0.0) {
hasresponse = true;
break;
}
}
if (!hasresponse) {
// std::cout << "No Response" << std::endl;
return 1.0;
}
}
// std::cout << "TYpe = " << fType << " "<< fForm << std::endl;
// Now evaluate spline
switch (fType) {
case k1DPol1: {
return Spline1DPol1(par);
}
case k1DPol2: {
return Spline1DPol2(par);
}
case k1DPol3: {
return Spline1DPol3(par);
}
case k1DPol4: {
return Spline1DPol4(par);
}
case k1DPol5: {
return Spline1DPol5(par);
}
case k1DPol6: {
return Spline1DPol6(par);
}
case k1DTSpline3: {
return Spline1DTSpline3(par);
}
case k2DPol6: {
return Spline2DPol(par, 6);
}
case k2DGaus: {
return Spline2DGaus(par);
}
case k2DTSpline3: {
return Spline2DTSpline3(par);
}
}
// Return nominal weight
return 1.0;
};
// Spline Functions
// ----------------------------------------------
// 1D Functions
// ----------------------------------------------
float Spline::Spline1DPol1(const Float_t *par) const {
float xp = fVal[0];
return par[0] + par[1] * xp;
};
float Spline::Spline1DPol2(const Float_t *par) const {
float xp = fVal[0];
return par[0] + par[1] * xp + par[2] * xp * xp;
};
float Spline::Spline1DPol3(const Float_t *par) const {
float xp = fVal[0];
return par[0] + par[1] * xp + par[2] * xp * xp + par[3] * xp * xp * xp;
};
float Spline::Spline1DPol4(const Float_t *par) const {
float xp = fVal[0];
return (par[0] + par[1] * xp + par[2] * xp * xp + par[3] * xp * xp * xp +
par[4] * xp * xp * xp * xp);
};
float Spline::Spline1DPol5(const Float_t *par) const {
float xp = fVal[0];
return (par[0] + par[1] * xp + par[2] * xp * xp + par[3] * xp * xp * xp +
par[4] * xp * xp * xp * xp + par[5] * xp * xp * xp * xp * xp);
};
float Spline::Spline1DPol6(const Float_t *par) const {
float xp = fVal[0];
float w = 0.0;
// std::cout << "Pol Eval " << std::endl;
for (int i = fNPar - 1; i > 0; i--) {
w = xp * (par[0 + i] + w);
}
w += par[0];
return w;
};
float Spline::Spline1DTSpline3(const Float_t *par) const {
// Find matching point
iter_low = fXScan.begin();
iter_high = fXScan.begin();
iter_high++;
off = 0;
fX = fVal[0];
while (iter_high != fXScan.end() and
(fX < (*iter_low) or fX >= (*iter_high))) {
off += 4;
iter_low++;
iter_high++;
}
float dx = fX - (*iter_low);
float weight = (par[off] + dx * (par[off + 1] +
dx * (par[off + 2] + dx * par[off + 3])));
return weight;
};
// 2D Functions
// ----------------------------------------------
float Spline::Spline2DPol(const Float_t *par, int n) const {
float wx = (fVal[0] - fValMin[0]) / (fValMax[0] - fValMin[0]);
float wy = (fVal[1] - fValMin[1]) / (fValMax[1] - fValMin[1]);
float w = 0.0;
int count = 0;
w += par[count++];
w += par[count++] * wx;
w += par[count++] * wy;
w += par[count++] * wx * wx;
w += par[count++] * wx * wy;
w += par[count++] * wy * wy;
w += par[count++] * wx * wx * wx;
w += par[count++] * wx * wx * wy;
w += par[count++] * wx * wy * wy;
w += par[count++] * wy * wy * wy;
w += par[count++] * wx * wx * wx * wx;
w += par[count++] * wx * wx * wx * wy;
w += par[count++] * wx * wx * wy * wy;
w += par[count++] * wx * wy * wy * wy;
w += par[count++] * wy * wy * wy * wy;
w += par[count++] * wx * wx * wx * wx * wx;
w += par[count++] * wx * wx * wx * wx * wy;
w += par[count++] * wx * wx * wx * wy * wy;
w += par[count++] * wx * wx * wy * wy * wy;
w += par[count++] * wx * wy * wy * wy * wy;
w += par[count++] * wy * wy * wy * wy * wy;
w += par[count++] * wx * wx * wx * wx * wx * wx;
w += par[count++] * wx * wx * wx * wx * wx * wy;
w += par[count++] * wx * wx * wx * wx * wy * wy;
w += par[count++] * wx * wx * wx * wy * wy * wy;
w += par[count++] * wx * wx * wy * wy * wy * wy;
w += par[count++] * wx * wy * wy * wy * wy * wy;
w += par[count++] * wy * wy * wy * wy * wy * wy;
return w;
}
float Spline::Spline2DGaus(const Float_t *par) const {
double Norm = 5.0 + par[1] * 20.0;
double Tilt = par[2] * 10.0;
double Pq0 = 1.0 + par[3] * 1.0;
double Wq0 = 0.5 + par[4] * 1.0;
double Pq3 = 1.0 + par[5] * 1.0;
double Wq3 = 0.5 + par[6] * 1.0;
double q0 = (fVal[0] - fValMin[0]) / (fValMax[0] - fValMin[0]);
double q3 = (fVal[1] - fValMin[1]) / (fValMax[1] - fValMin[1]);
double a = cos(Tilt) * cos(Tilt) / (2 * Wq0 * Wq0);
a += sin(Tilt) * sin(Tilt) / (2 * Wq3 * Wq3);
double b = -sin(2 * Tilt) / (4 * Wq0 * Wq0);
b += sin(2 * Tilt) / (4 * Wq3 * Wq3);
double c = sin(Tilt) * sin(Tilt) / (2 * Wq0 * Wq0);
c += cos(Tilt) * cos(Tilt) / (2 * Wq3 * Wq3);
double w = Norm;
w *= exp(-a * (q0 - Pq0) * (q0 - Pq0));
w *= exp(+2.0 * b * (q0 - Pq0) * (q3 - Pq3));
w *= exp(-c * (q3 - Pq3) * (q3 - Pq3));
return w;
}
float Spline::Spline2DTSpline3(const Float_t *par) const {
// Find matching point
std::vector<float>::iterator iter_low_x = fXScan.begin();
std::vector<float>::iterator iter_high_x = fXScan.begin();
std::vector<float>::iterator iter_low_y = fYScan.begin();
std::vector<float>::iterator iter_high_y = fYScan.begin();
iter_high_x++;
iter_high_y++;
off = 0;
fX = fVal[0];
fY = fVal[1];
while ((iter_high_x != fXScan.end() and iter_high_y != fYScan.end()) and
(fX < (*iter_low_y) or fX >= (*iter_high) or fY < (*iter_low_y) or
fY >= (*iter_low_y))) {
off += 9;
iter_low_x++;
iter_high_x++;
if (iter_high_x == fXScan.end()) {
iter_low_x = fXScan.begin();
iter_high_x = fXScan.begin();
iter_low_y++;
iter_high_y++;
std::cout << "Skipping to next tspline 3 rung " << *iter_low_y
<< std::endl;
}
}
std::cout << "Evaluting TSpline3 at " << fX << " " << (*iter_low_x) << " "
<< fY << " " << (*iter_low_y) << std::endl;
// sleep(1.0);
float dx = fX - (*iter_low_x);
float dy = fY - (*iter_low_y);
float weight = (par[off] + dx * (par[off + 1] +
dx * (par[off + 2] + dx * par[off + 3])));
float weight2 =
(par[off + 4] +
dy * (par[off + 5] + dy * (par[off + 6] + dy * par[off + 7])));
return weight * weight2 * par[off + 8];
};
TF1 *Spline::GetFunction() {
if (!fROOTFunction) {
if (fNDim == 1) {
std::cout << "Creating new 1D Function";
fROOTFunction = new TF1("f1", this, -30.0, 30.0, this->GetNPar());
}
if (fNDim == 2) {
std::cout << "Creating new 2D Function" << std::endl;
// ROOT::Math::IParametricFunctionMultiDim* func; // = new
// ROOT::Math::IParametricFunctionMultiDim(this);
fROOTFunction = new TF2("f2", SplineUtils::Func2DWrapper, -30.0, 30.0,
-30.0, -30.0, this->GetNPar());
}
}
// Reset ROOT function before returning.
fROOTFunction->SetParameter(0, 1.0);
for (int i = 1; i < this->GetNPar(); i++) {
fROOTFunction->SetParameter(i, 0.1);
}
if (fNDim == 2) {
if (SplineUtils::gSpline != this)
SplineUtils::gSpline = this;
}
return (TF1 *)fROOTFunction;
}
namespace SplineUtils {
Spline *gSpline = NULL;
}
double SplineUtils::Func2DWrapper(double *x, double *p) {
return (*gSpline)(x, p);
}
diff --git a/src/Splines/SplineWriter.cxx b/src/Splines/SplineWriter.cxx
index 3cad0bc..06be1b6 100644
--- a/src/Splines/SplineWriter.cxx
+++ b/src/Splines/SplineWriter.cxx
@@ -1,780 +1,780 @@
#include "SplineWriter.h"
using namespace SplineUtils;
// Spline reader should have access to every spline.
// Should know when reconfigure is called what its limits are and adjust
// accordingly. Then should pass it the index required in the stack as
// &xvals[index], and &pars[parindex]
void SplineWriter::Write(std::string name) {
// Create a TTree with each form and scan points in it.
TTree *tr = new TTree(name.c_str(), name.c_str());
// Loop over all splines and add a TString in the TTree for its inputs
tr->Branch("Spline", &fSpline);
tr->Branch("Type", &fType);
tr->Branch("Form", &fForm);
tr->Branch("Points", &fPoints);
tr->Fill();
tr->Write();
delete tr;
}
void SplineWriter::AddWeightsToTree(TTree *tr) {
// Add only the fitted spline coefficients to the ttree
std::cout << "Saving Spline Weights to TTree = "
<< Form("SplineWeights[%d]/F", (int)fValList.size()) << std::endl;
// sleep(1);
tr->Branch("SplineWeights", fWeightList,
Form("SplineWeights[%d]/D", (int)fValList.size()));
}
void SplineWriter::ReadWeightsFromTree(TTree *tr) {
tr->SetBranchAddress("SplineWeights", fWeightList);
}
void SplineWriter::AddCoefficientsToTree(TTree *tr) {
// Add only the fitted spline coefficients to the ttree
std::cout << "Saving Spline Coeff to TTree = "
<< Form("SplineCoeff[%d]/F", fNCoEff) << std::endl;
// sleep(1);
tr->Branch("SplineCoeff", fCoEffStorer, Form("SplineCoeff[%d]/F", fNCoEff));
}
void SplineWriter::SetupSplineSet() {
std::cout << "Setting up spline set" << std::endl;
fDrawSplines = FitPar::Config().GetParB("draw_splines");
// Create the coefficients double*
fNCoEff = 0;
for (size_t i = 0; i < fAllSplines.size(); i++) {
fNCoEff += fAllSplines[i].GetNPar();
}
fCoEffStorer = new float[fNCoEff];
std::cout << "NCoeff = " << fNCoEff << std::endl;
// Calculate the grid of parsets
// Setup the list of parameter coefficients.
std::vector<double> nomvals = fRW->GetDialValues();
fParVect.clear();
fSetIndex.clear();
fParVect.push_back(nomvals);
fSetIndex.push_back(0);
// fWeightList.push_back(1.0);
fValList.push_back(std::vector<double>(1, 0.0));
// Loop over all splines.
for (size_t i = 0; i < fAllSplines.size(); i++) {
// For each dial loop over all points within a given position
std::vector<double> newvals = nomvals;
std::vector<int>
pos; // = SplineUtils::GetSplitDialPositions(fRW, fSpline[i]);
std::vector<std::string> splitnames =
GeneralUtils::ParseToStr(fSpline[i], ";");
for (size_t j = 0; j < splitnames.size(); j++) {
int temppos = fRW->GetDialPos(splitnames[j]);
pos.push_back(temppos);
}
- std::vector<std::vector<double>> vals =
+ std::vector<std::vector<double> > vals =
SplineUtils::GetSplitDialPoints(fPoints[i]);
for (size_t j = 0; j < vals.size(); j++) {
for (size_t k = 0; k < pos.size(); k++) {
newvals[pos[k]] = vals[j][k];
}
fParVect.push_back(newvals);
fValList.push_back(vals[j]);
// fWeightList.push_back(1.0);
fSetIndex.push_back(i + 1);
}
}
fWeightList = new double[fValList.size()];
for (uint i = 0; i < fValList.size(); i++) {
fWeightList[i] = 1.0;
}
// Print out the parameter set
NUIS_LOG(FIT, "Parset | Index | Pars --- ");
for (size_t i = 0; i < fSetIndex.size(); i++) {
NUIS_LOGN(FIT, " Set " << i << ". | " << fSetIndex[i] << " | ");
if (LOG_LEVEL(FIT)) {
for (size_t j = 0; j < fParVect[i].size(); j++) {
NUIS_LOGN(FIT, " " << fParVect[i][j]);
}
NUIS_LOG(FIT, "");
}
}
}
void SplineWriter::GetWeightsForEvent(FitEvent *event) {
// Get Starting Weight
fRW->SetAllDials(&fParVect[0][0], fParVect[0].size());
double nomweight = fRW->CalcWeight(event);
event->RWWeight = nomweight;
if (fDrawSplines) {
std::cout << "Nominal Spline Weight = " << nomweight << std::endl;
}
fWeightList[0] = nomweight;
// Loop over parameter sets
for (size_t i = 1; i < fParVect.size(); i++) {
// Update FRW
fRW->SetAllDials(&fParVect[i][0], fParVect[i].size());
// Calculate a weight for event
double weight = fRW->CalcWeight(event);
if (weight >= 0.0 and weight < 200) {
// Fill Weight Set
fWeightList[i] = weight / nomweight;
if (fDrawSplines)
std::cout << "Calculating values from weight set " << i << " "
<< fParVect[i][0] << " = " << weight << " "
<< weight / nomweight << std::endl;
} else {
fWeightList[i] = 1.0;
}
}
}
void SplineWriter::GetWeightsForEvent(FitEvent *event, double *weights) {
// Get Starting Weight
fRW->SetAllDials(&fParVect[0][0], fParVect[0].size());
double nomweight = fRW->CalcWeight(event);
event->RWWeight = nomweight;
if (fDrawSplines) {
std::cout << "Nominal Spline Weight = " << nomweight << std::endl;
}
weights[0] = nomweight;
// Loop over parameter sets
for (size_t i = 1; i < fParVect.size(); i++) {
// Update FRW
fRW->SetAllDials(&fParVect[i][0], fParVect[i].size());
// Calculate a weight for event
double weight = fRW->CalcWeight(event);
if (weight >= 0.0 and weight < 200) {
// Fill Weight Set
weights[i] = weight / nomweight;
if (fDrawSplines)
std::cout << "Calculating values from weight set " << i << " "
<< fParVect[i][0] << " = " << weight << " "
<< weight / nomweight << std::endl;
} else {
weights[i] = 1.0;
}
fWeightList[i] = weights[i];
}
}
void SplineWriter::ReconfigureSet(int iset) {
fCurrentSet = iset;
fRW->SetAllDials(&fParVect[iset][0], fParVect[iset].size());
}
double SplineWriter::GetWeightForThisSet(FitEvent *event, int iset) {
if (iset != -1 and iset != fCurrentSet) {
ReconfigureSet(iset);
}
return fRW->CalcWeight(event);
}
void SplineWriter::SetWeights(double *weights) {
for (uint i = 0; i < fParVect.size(); i++) {
fWeightList[i] = weights[i];
}
}
void SplineWriter::FitSplinesForEvent(double *inputweights, float *coeff) {
int n = fAllSplines.size();
int coeffcount = 0;
for (int i = 0; i < n; i++) {
// DialVals
- std::vector<std::vector<double>> dialvals;
+ std::vector<std::vector<double> > dialvals;
std::vector<double> weightvals;
bool hasresponse = false;
for (size_t j = 0; j < fSetIndex.size(); j++) {
if (fSetIndex[j] != i + 1)
continue;
dialvals.push_back(fValList[j]);
double tempw = inputweights[j];
weightvals.push_back(tempw);
if (tempw != 1.0)
hasresponse = true;
}
// Perform Fit
if (hasresponse) {
// std::cout << "Fitting Coeff" << std::endl;
FitCoeff(&fAllSplines[i], dialvals, weightvals, &coeff[coeffcount],
fDrawSplines);
} else {
for (int j = 0; coeffcount + j < fNCoEff; j++) {
// std::cout << "Setting 0.0 response " << coeffcount + i << " " <<
// fNCoEff << std::endl;
coeff[coeffcount + j] = 0.0;
}
}
// std::cout << "Adding coeffcount" << std::endl;
// Offset coeffcount
coeffcount += (fAllSplines[i]).GetNPar();
}
// std::cout << "FitEvent" << std::endl;
return;
}
void SplineWriter::FitSplinesForEvent(TCanvas *fitcanvas, bool saveplot) {
// Loop over splines
// int count = 0;
int coeffcount = 0;
int n = fAllSplines.size();
std::vector<int> splinecounter;
for (int i = 0; i < n; i++) {
splinecounter.push_back(coeffcount);
coeffcount += fAllSplines[i].GetNPar();
}
// #pragma omp parallel for
for (int i = 0; i < n; i++) {
// Store X/Y Vals
- std::vector<std::vector<double>> dialvals;
+ std::vector<std::vector<double> > dialvals;
std::vector<double> weightvals;
bool hasresponse = false;
int npar = (fAllSplines[i]).GetNPar();
coeffcount = splinecounter[i];
for (size_t j = 0; j < fSetIndex.size(); j++) {
if (fSetIndex[j] != i + 1)
continue;
dialvals.push_back(fValList[j]);
double tempw = fWeightList[j];
weightvals.push_back(tempw);
if (tempw != 1.0)
hasresponse = true;
}
// Make a new graph and fit coeff if response
if (hasresponse) {
FitCoeff(&fAllSplines[i], dialvals, weightvals, &fCoEffStorer[coeffcount],
fDrawSplines);
} else {
for (int i = 0; i < npar; i++) {
fCoEffStorer[coeffcount + i] = 0.0;
}
}
}
// Check overrides
// if (saveplot) {
// coeffcount = 0;
// // Make new canvas to save stuff into
// if (fitcanvas) delete fitcanvas;
// fitcanvas = new TCanvas("c1", "c1", fAllSplines.size() * 400 , 600);
// fitcanvas->Divide(fAllSplines.size(), 1);
// // Clear out points
// for (size_t i = 0; i < fAllDrawnGraphs.size(); i++) {
// if (fAllDrawnGraphs[i]) delete fAllDrawnGraphs[i];
// if (fAllDrawnHists[i]) delete fAllDrawnHists[i];
// }
// fAllDrawnGraphs.clear();
// fAllDrawnHists.clear();
// for (size_t i = 0; i < fAllSplines.size(); i++) {
// fitcanvas->cd(i + 1);
// // Store X/Y Vals
// std::vector<std::vector<double> > dialvals;
// std::vector<double> weightvals;
// bool hasresponse = false;
// int npar = (fAllSplines[i]).GetNPar();
// for (size_t j = 0; j < fSetIndex.size(); j++) {
// if ((UInt_t)fSetIndex[j] != (UInt_t)i + 1) continue;
// dialvals.push_back(fValList[j]);
// weightvals.push_back(fWeightList[j] - 0.0);
// if (fWeightList[j] != 1.0) hasresponse = true;
// }
// if (hasresponse) {
// TGraph* gr = new TGraph(dialvals.size(), dialvals, weightvals);
// fAllDrawnGraphs.push_back(gr);
// // Get XMax Min
// int n = xvals.size();
// double xmin = 99999.9;
// double xmax = -99999.9;
// for (int j = 0; j < n; j++) {
// if (xvals[j] > xmax) xmax = xvals[j];
// if (xvals[j] < xmin) xmin = xvals[j];
// }
// TH1D* hist = new TH1D("temp", "temp", 100, xmin, xmax);
// fAllDrawnHists.push_back(hist);
// for (int k = 0; k < 100; k++) {
// double xtemp = hist->GetXaxis()->GetBinCenter(k + 1);
// fAllSplines[i].Reconfigure(xtemp);
// double ytemp = fAllSplines[i].DoEval(&fCoEffStorer[coeffcount]);
// hist->SetBinContent(k + 1, ytemp);
// }
// // gr->Draw("APL");
// hist->SetLineColor(kRed);
// hist->Draw("HIST C");
// hist->SetTitle("Spline Response");
// // hist->GetYaxis()->SetRangeUser(0.0, 3.0);
// // gStyle->SetOptStat(0);
// hist->SetStats(0);
// gr->SetMarkerStyle(20);
// gr->SetTitle("True Weight Points");
// gr->Draw("P SAME");
// gPad->BuildLegend(0.6, 0.6, 0.85, 0.85);
// gPad->Update();
// hist->SetTitle(fSpline[i].c_str());
// hist->GetXaxis()->SetTitle("Dial Variation");
// hist->GetYaxis()->SetTitle("Event Weight");
// fitcanvas->Update();
// }
// coeffcount += npar;
// }
// }
}
// Fitting
// ----------------------------------------------
-void SplineWriter::FitCoeff(Spline *spl, std::vector<std::vector<double>> &v,
+void SplineWriter::FitCoeff(Spline *spl, std::vector<std::vector<double> > &v,
std::vector<double> &w, float *coeff, bool draw) {
std::vector<double> x;
std::vector<double> y;
std::vector<double> z;
for (size_t i = 0; i < v.size(); i++) {
x.push_back(v[i][0]);
if (v[i].size() > 1)
y.push_back(v[i][1]);
if (v[i].size() > 2)
z.push_back(v[i][2]);
}
switch (spl->GetType()) {
// Polynominal Graph Fits
case k1DPol1:
case k1DPol2:
case k1DPol3:
case k1DPol4:
case k1DPol5:
case k1DPol6:
FitCoeff1DGraph(spl, v.size(), &x[0], &w[0], coeff, draw);
break;
case k1DTSpline3:
GetCoeff1DTSpline3(spl, x.size(), &x[0], &w[0], coeff, draw);
break;
case k2DPol6:
case k2DGaus:
case k2DTSpline3:
FitCoeff2DGraph(spl, v.size(), &x[0], &y[0], &w[0], coeff, draw);
break;
default:
break;
}
#ifdef __MINUIT2_ENABLED__
if (fDrawSplines) {
fSplineFCNs[spl] = new SplineFCN(spl, v, w);
fSplineFCNs[spl]->SaveAs("mysplinetest_" + spl->GetName() + ".pdf", coeff);
sleep(1);
delete fSplineFCNs[spl];
}
#endif
}
void SplineWriter::FitCoeff1DGraph(Spline *spl, int n, double *x, double *y,
float *coeff, bool draw) {
TGraph *gr = new TGraph(n, x, y);
double xmin = 99999.9;
double xmax = -99999.9;
for (int i = 0; i < n; i++) {
if (x[i] > xmax)
xmax = x[i];
if (x[i] < xmin)
xmin = x[i];
}
double xwidth = xmax - xmin;
xmin = xmin - xwidth * 0.01;
xmax = xmax + xwidth * 0.01;
// Create a new function for fitting.
TF1 *func = spl->GetFunction();
// Run the actual spline fit
StopTalking();
// If linear fit with two points
if (n == 2 and spl->GetType() == k1DPol1) {
float m = (y[1] - y[0]) / (x[1] - x[0]);
float c = y[0] - (0.0 - x[0]) * m;
func->SetParameter(0, c);
func->SetParameter(1, m);
} else if (spl->GetType() == k1DPol1) {
gr->Fit(func, "WQ");
} else {
gr->Fit(func, "FMWQ");
}
StartTalking();
for (int i = 0; i < spl->GetNPar(); i++) {
coeff[i] = func->GetParameter(i);
}
if (draw) {
gr->Draw("APL");
gPad->Update();
gPad->SaveAs(("plot_test_" + spl->GetName() + ".pdf").c_str());
std::cout << "Saving Graph" << std::endl;
sleep(3);
}
// delete func;
delete gr;
}
double SplineFCN::operator()(const double *x) const { return DoEval(x); }
double SplineFCN::DoEval(const double *x) const {
float *fx = new float[fSpl->GetNPar()];
for (int i = 0; i < fSpl->GetNPar(); i++) {
fx[i] = x[i];
} //
double tot = 0;
for (size_t i = 0; i < fVal.size(); i++) {
int nonzero = 0;
for (size_t j = 0; j < fVal[i].size(); j++) {
fSpl->Reconfigure(fVal[i][j], j);
// std::cout << "Reconfiguring " << fVal[i][j] << " " << j << std::endl;
if (fVal[i][j] != 0.0)
nonzero++;
}
if (uncorrelated and nonzero > 1)
continue;
double w = fSpl->DoEval(fx);
double wdif = (w - fWeight[i]); // / (fWeight[i] * 0.05);
tot += sqrt(wdif * wdif);
}
// delete fx;
return tot;
}
void SplineFCN::UpdateWeights(std::vector<double> &w) {
for (uint i = 0; i < w.size(); i++) {
fWeight[i] = w[i];
}
}
void SplineFCN::SetCorrelated(bool state) { uncorrelated = !state; }
void SplineFCN::SaveAs(std::string name, const float *fx) {
if (fVal[0].size() > 2) {
TCanvas *c1 = new TCanvas("c1", "c1", 800, 600);
c1->Divide(2, 1);
TH1D *histmc =
new TH1D("hist", "hist", fVal.size(), 0.0, double(fVal.size()));
TH1D *histdt =
new TH1D("histdt", "histdt", fVal.size(), 0.0, double(fVal.size()));
for (size_t i = 0; i < fVal.size(); i++) {
for (size_t j = 0; j < fVal[i].size(); j++) {
fSpl->Reconfigure(fVal[i][j], j);
}
histmc->SetBinContent(i + 1, fSpl->DoEval(fx));
histdt->SetBinContent(i + 1, fWeight[i]);
}
// histmc->Add(histdt,-1.0);
c1->cd(1);
histmc->SetTitle("Spline;Parameter Set;Weight");
histmc->Draw("HIST");
histdt->SetLineColor(kRed);
histdt->Draw("SAME HIST");
c1->cd(2);
TH1D *histdif = (TH1D *)histmc->Clone();
histdif->Add(histdt, -1.0);
histdif->Draw("HIST");
c1->Update();
c1->SaveAs(name.c_str());
delete c1;
} else if (fVal[0].size() == 2) {
TGraph2D *histmc = new TGraph2D();
TGraph2D *histdt = new TGraph2D();
TGraph2D *histdif = new TGraph2D();
for (size_t i = 0; i < fVal.size(); i++) {
for (size_t j = 0; j < fVal[i].size(); j++) {
fSpl->Reconfigure(fVal[i][j], j);
}
histmc->SetPoint(histmc->GetN(), fVal[i][0], fVal[i][1],
fSpl->DoEval(fx));
histdt->SetPoint(histdt->GetN(), fVal[i][0], fVal[i][1], fWeight[i]);
histdif->SetPoint(histdif->GetN(), fVal[i][0], fVal[i][1],
fabs(fSpl->DoEval(fx) - fWeight[i]));
}
TCanvas *c1 = new TCanvas("c1", "c1", 800, 600);
c1->Divide(3, 1);
c1->cd(1);
histmc->SetTitle(("Spline;" + fSpl->GetName()).c_str());
histmc->Draw("COLZ");
gPad->Update();
c1->cd(2);
histdt->SetTitle(("Raw;" + fSpl->GetName()).c_str());
histdt->Draw("COLZ");
c1->cd(3);
histdif->SetTitle(("Dif;" + fSpl->GetName()).c_str());
histdif->Draw("COLZ");
gPad->SetRightMargin(0.15);
// gPad->SetLogz(1);
gPad->Update();
c1->SaveAs(name.c_str());
delete c1;
} else if (fVal[0].size() == 1) {
TGraph *histmc = new TGraph();
TGraph *histdt = new TGraph();
TGraph *histdif = new TGraph();
for (size_t i = 0; i < fVal.size(); i++) {
for (size_t j = 0; j < fVal[i].size(); j++) {
fSpl->Reconfigure(fVal[i][j], j);
}
histmc->SetPoint(histmc->GetN(), fVal[i][0], fSpl->DoEval(fx));
histdt->SetPoint(histdt->GetN(), fVal[i][0], fWeight[i]);
histdif->SetPoint(histdif->GetN(), fVal[i][0],
fabs(fSpl->DoEval(fx) - fWeight[i]));
}
TCanvas *c1 = new TCanvas("c1", "c1", 800, 600);
c1->Divide(2, 1);
c1->cd(1);
histmc->SetTitle(("Spline;" + fSpl->GetName()).c_str());
histmc->Draw("AC");
histmc->SetLineColor(kRed);
histdt->SetTitle(("Raw;" + fSpl->GetName()).c_str());
histdt->Draw("SAME P");
histdt->SetMarkerStyle(20);
gPad->Update();
c1->cd(2);
histdif->SetTitle(("Dif;" + fSpl->GetName()).c_str());
histdif->Draw("APL");
gPad->Update();
c1->SaveAs(name.c_str());
delete c1;
}
// gPad->SaveAs(name.c_str());
}
void SplineWriter::FitCoeff2DGraph(Spline *spl, int n, double *x, double *y,
double *w, float *coeff, bool draw) {
#pragma omp critical
{
TF2 *f2 = (TF2 *)spl->GetFunction();
TGraph2D *histmc = new TGraph2D(n, x, y, w);
f2->SetNpx(400);
StopTalking();
histmc->Fit(f2, "FMWQ");
StartTalking();
for (int i = 0; i < spl->GetNPar(); i++) {
coeff[i] = f2->GetParameter(i);
}
// delete f2;
delete histmc;
}
}
void SplineWriter::FitCoeffNDGraph(Spline *spl,
- std::vector<std::vector<double>> &v,
+ std::vector<std::vector<double> > &v,
std::vector<double> &w, float *coeff,
bool draw) {
#ifdef __MINUIT2_ENABLED__
if (fSplineFunctors.find(spl) != fSplineFunctors.end()) {
delete fSplineFunctors[spl];
fSplineFunctors.erase(spl);
}
if (fSplineFCNs.find(spl) != fSplineFCNs.end()) {
delete fSplineFCNs[spl];
fSplineFCNs.erase(spl);
}
if (fSplineMinimizers.find(spl) != fSplineMinimizers.end()) {
delete fSplineMinimizers[spl];
fSplineMinimizers.erase(spl);
}
if (fSplineMinimizers.find(spl) == fSplineMinimizers.end()) {
std::cout << "Building new ND minimizer for " << spl << std::endl;
fSplineFCNs[spl] = new SplineFCN(spl, v, w);
// fSplineFCNs[spl] = new SplineFCN(spl, v, w);
fSplineFunctors[spl] =
new ROOT::Math::Functor(*fSplineFCNs[spl], spl->GetNPar());
fSplineMinimizers[spl] =
ROOT::Math::Factory::CreateMinimizer("Minuit2", "Combined");
fSplineMinimizers[spl]->SetMaxFunctionCalls(1E8);
fSplineMinimizers[spl]->SetMaxIterations(1E8);
fSplineMinimizers[spl]->SetTolerance(1.E-6);
fSplineMinimizers[spl]->SetStrategy(2);
for (int j = 0; j < spl->GetNPar(); j++) {
fSplineMinimizers[spl]->SetVariable(j, Form("Par_%i", j), 0.1, 0.1);
}
}
// Create a new function for fitting.
// StopTalking();
// Update FCN
fSplineFCNs[spl]->UpdateWeights(w);
// fSplineMinimizers[spl]->SetDefaultOptions();
// fSplineMinimizers[spl]->Clear();
for (int j = 0; j < spl->GetNPar(); j++) {
if (j != 0) {
fSplineMinimizers[spl]->SetVariableValue(j, 0.1);
// fSplineMinimizers[spl]->SetParameter(j, Form("Par_%i", j), 0.1, 0.1,
// -100.0, 100.0 );
// fSplineMinimizers[spl]->SetVariableValue(j, 0.1);
}
}
// fSplineFCNs[spl]->SetCorrelated(false);
// fSplineFunctors[spl] = new ROOT::Math::Functor( *fSplineFCNs[spl],
// spl->GetNPar() );
// fSplineMinimizers[spl]->SetFunction(*fSplineFunctors[spl]);
// fSplineMinimizers[spl]->Minimize();
fSplineFCNs[spl]->SetCorrelated(true);
delete fSplineFunctors[spl];
fSplineFunctors[spl] =
new ROOT::Math::Functor(*fSplineFCNs[spl], spl->GetNPar());
fSplineMinimizers[spl]->SetFunction(*fSplineFunctors[spl]);
// ((TFitterMinuit*)fSplineMinimizers[spl])->CreateMinimizer(TFitterMinuit::kMigrad);
fSplineMinimizers[spl]->Minimize();
fSplineMinimizers[spl]->Minimize();
// ((TFitterMinuit*)fSplineMinimizers[spl])->CreateMinimizer(TFitterMinuit::kMigrad);
// fSplineMinimizers[spl]->Minimize();
// delete minimizer;
// StartTalking();
// Now Get Parameters
const double *values = fSplineMinimizers[spl]->X();
for (int i = 0; i < spl->GetNPar(); i++) {
std::cout << "Updated Coeff " << i << " " << values[i] << std::endl;
coeff[i] = values[i];
}
// Save a sample
fSplineFCNs[spl]->SaveAs("mysplinetest_" + spl->GetName() + ".pdf", coeff);
sleep(1);
// delete values;
// delete minimizer;
#endif
}
// Spline extraction Functions
void SplineWriter::GetCoeff1DTSpline3(Spline *spl, int n, double *x, double *y,
float *coeff, bool draw) {
StopTalking();
TSpline3 temp_spline = TSpline3("temp_spline", x, y, n);
StartTalking();
for (size_t i = 0; i < (UInt_t)n; i++) {
double a, b, c, d, e;
temp_spline.GetCoeff(i, a, b, c, d, e);
coeff[i * 4] = y[i];
coeff[i * 4 + 1] = c;
coeff[i * 4 + 2] = d;
coeff[i * 4 + 3] = e;
}
if (draw) {
TGraph *gr = new TGraph(n, x, y);
temp_spline.Draw("CA");
gr->Draw("PL SAME");
gPad->Update();
gPad->SaveAs(("plot_test_" + spl->GetName() + ".pdf").c_str());
delete gr;
}
return;
}
diff --git a/src/Utils/PlotUtils.cxx b/src/Utils/PlotUtils.cxx
index 0077b34..89dc4f2 100644
--- a/src/Utils/PlotUtils.cxx
+++ b/src/Utils/PlotUtils.cxx
@@ -1,1197 +1,1197 @@
// Copyright 2016 L. Pickering, P Stowell, R. Terri, C. Wilkinson, C. Wret
/*******************************************************************************
* This file is part of NUISANCE.
*
* NUISANCE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NUISANCE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NUISANCE. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
#include "PlotUtils.h"
#include "FitEvent.h"
#include "StatUtils.h"
// MOVE TO MB UTILS!
// This function is intended to be modified to enforce a consistent masking for
// all models.
TH2D *PlotUtils::SetMaskHist(std::string type, TH2D *data) {
TH2D *fMaskHist = (TH2D *)data->Clone("fMaskHist");
for (int xBin = 0; xBin < fMaskHist->GetNbinsX(); ++xBin) {
for (int yBin = 0; yBin < fMaskHist->GetNbinsY(); ++yBin) {
if (data->GetBinContent(xBin + 1, yBin + 1) == 0)
fMaskHist->SetBinContent(xBin + 1, yBin + 1, 0);
else
fMaskHist->SetBinContent(xBin + 1, yBin + 1, 0.5);
if (!type.compare("MB_numu_2D")) {
if (yBin == 19 && xBin < 8)
fMaskHist->SetBinContent(xBin + 1, yBin + 1, 1.0);
} else {
if (yBin == 19 && xBin < 11)
fMaskHist->SetBinContent(xBin + 1, yBin + 1, 1.0);
}
if (yBin == 18 && xBin < 3)
fMaskHist->SetBinContent(xBin + 1, yBin + 1, 1.0);
if (yBin == 17 && xBin < 2)
fMaskHist->SetBinContent(xBin + 1, yBin + 1, 1.0);
if (yBin == 16 && xBin < 1)
fMaskHist->SetBinContent(xBin + 1, yBin + 1, 1.0);
}
}
return fMaskHist;
};
// MOVE TO GENERAL UTILS?
bool PlotUtils::CheckObjectWithName(TFile *inFile, std::string substring) {
TIter nextkey(inFile->GetListOfKeys());
TKey *key;
while ((key = (TKey *)nextkey())) {
std::string test(key->GetName());
if (test.find(substring) != std::string::npos)
return true;
}
return false;
};
// MOVE TO GENERAL UTILS?
std::string PlotUtils::GetObjectWithName(TFile *inFile, std::string substring) {
TIter nextkey(inFile->GetListOfKeys());
TKey *key;
std::string output = "";
while ((key = (TKey *)nextkey())) {
std::string test(key->GetName());
if (test.find(substring) != std::string::npos)
output = test;
}
return output;
};
void PlotUtils::CreateNeutModeArray(TH1 *hist, TH1 *neutarray[]) {
for (int i = 0; i < 60; i++) {
neutarray[i] = (TH1 *)hist->Clone(Form("%s_NMODE_%i", hist->GetName(), i));
}
return;
};
void PlotUtils::DeleteNeutModeArray(TH1 *neutarray[]) {
for (int i = 0; i < 60; i++) {
delete neutarray[i];
}
return;
};
void PlotUtils::FillNeutModeArray(TH1D *hist[], int mode, double xval,
double weight) {
if (abs(mode) > 60)
return;
hist[abs(mode)]->Fill(xval, weight);
return;
};
void PlotUtils::FillNeutModeArray(TH2D *hist[], int mode, double xval,
double yval, double weight) {
if (abs(mode) > 60)
return;
hist[abs(mode)]->Fill(xval, yval, weight);
return;
};
THStack PlotUtils::GetNeutModeStack(std::string title, TH1 *ModeStack[],
int option) {
(void)option;
THStack allmodes = THStack(title.c_str(), title.c_str());
for (int i = 0; i < 60; i++) {
allmodes.Add(ModeStack[i]);
}
// Credit to Clarence for copying all this out.
// CC
ModeStack[1]->SetTitle("CCQE");
ModeStack[1]->SetFillColor(kBlue);
// ModeStack[1]->SetFillStyle(3444);
ModeStack[1]->SetLineColor(kBlue);
ModeStack[2]->SetTitle("2p/2h Nieves");
ModeStack[2]->SetFillColor(kRed);
// ModeStack[2]->SetFillStyle(3344);
ModeStack[2]->SetLineColor(kRed);
// ModeStack[11]->SetTitle("#it{#nu + p #rightarrow l^{-} + p + #pi^{+}}");
ModeStack[11]->SetTitle("CC1#pi^{+} on p");
ModeStack[11]->SetFillColor(kGreen);
// ModeStack[11]->SetFillStyle(3004);
ModeStack[11]->SetLineColor(kGreen);
// ModeStack[12]->SetTitle("#it{#nu + n #rightarrow l^{-} + p + #pi^{0}}");
ModeStack[12]->SetTitle("CC1#pi^{0} on n");
ModeStack[12]->SetFillColor(kGreen + 3);
// ModeStack[12]->SetFillStyle(3005);
ModeStack[12]->SetLineColor(kGreen);
// ModeStack[13]->SetTitle("#it{#nu + n #rightarrow l^{-} + n + #pi^{+}}");
ModeStack[13]->SetTitle("CC1#pi^{+} on n");
ModeStack[13]->SetFillColor(kGreen - 2);
// ModeStack[13]->SetFillStyle(3004);
ModeStack[13]->SetLineColor(kGreen);
ModeStack[16]->SetTitle("CC coherent");
ModeStack[16]->SetFillColor(kBlue);
// ModeStack[16]->SetFillStyle(3644);
ModeStack[16]->SetLineColor(kBlue);
// ModeStack[17]->SetTitle("#it{#nu + n #rightarrow l^{-} + p + #gamma}");
ModeStack[17]->SetTitle("CC1#gamma");
ModeStack[17]->SetFillColor(kMagenta);
// ModeStack[17]->SetFillStyle(3001);
ModeStack[17]->SetLineColor(kMagenta);
ModeStack[21]->SetTitle("Multi #pi (1.3 < W < 2.0)");
ModeStack[21]->SetFillColor(kYellow);
// ModeStack[21]->SetFillStyle(3005);
ModeStack[21]->SetLineColor(kYellow);
// ModeStack[22]->SetTitle("#it{#nu + n #rightarrow l^{-} + p + #eta^{0}}");
ModeStack[22]->SetTitle("CC1#eta^{0} on n");
ModeStack[22]->SetFillColor(kYellow - 2);
// ModeStack[22]->SetFillStyle(3013);
ModeStack[22]->SetLineColor(kYellow - 2);
// ModeStack[23]->SetTitle("#it{#nu + n #rightarrow l^{-} + #Lambda +
// K^{+}}");
ModeStack[23]->SetTitle("CC1#Labda1K^{+}");
ModeStack[23]->SetFillColor(kYellow - 6);
// ModeStack[23]->SetFillStyle(3013);
ModeStack[23]->SetLineColor(kYellow - 6);
ModeStack[26]->SetTitle("DIS (W > 2.0)");
ModeStack[26]->SetFillColor(kRed);
// ModeStack[26]->SetFillStyle(3006);
ModeStack[26]->SetLineColor(kRed);
// NC
// ModeStack[31]->SetTitle("#it{#nu + n #rightarrow #nu + n + #pi^{0}}");
ModeStack[31]->SetTitle("NC1#pi^{0} on n");
ModeStack[31]->SetFillColor(kBlue);
// ModeStack[31]->SetFillStyle(3004);
ModeStack[31]->SetLineColor(kBlue);
// ModeStack[32]->SetTitle("#it{#nu + p #rightarrow #nu + p + #pi^{0}}");
ModeStack[32]->SetTitle("NC1#pi^{0} on p");
ModeStack[32]->SetFillColor(kBlue + 3);
// ModeStack[32]->SetFillStyle(3004);
ModeStack[32]->SetLineColor(kBlue + 3);
// ModeStack[33]->SetTitle("#it{#nu + n #rightarrow #nu + p + #pi^{-}}");
ModeStack[33]->SetTitle("NC1#pi^{-} on n");
ModeStack[33]->SetFillColor(kBlue - 2);
// ModeStack[33]->SetFillStyle(3005);
ModeStack[33]->SetLineColor(kBlue - 2);
// ModeStack[34]->SetTitle("#it{#nu + p #rightarrow #nu + n + #pi^{+}}");
ModeStack[34]->SetTitle("NC1#pi^{+} on p");
ModeStack[34]->SetFillColor(kBlue - 8);
// ModeStack[34]->SetFillStyle(3005);
ModeStack[34]->SetLineColor(kBlue - 8);
ModeStack[36]->SetTitle("NC Coherent");
ModeStack[36]->SetFillColor(kBlue + 8);
// ModeStack[36]->SetFillStyle(3644);
ModeStack[36]->SetLineColor(kBlue + 8);
// ModeStack[38]->SetTitle("#it{#nu + n #rightarrow #nu + n + #gamma}");
ModeStack[38]->SetTitle("NC1#gamma on n");
ModeStack[38]->SetFillColor(kMagenta);
// ModeStack[38]->SetFillStyle(3001);
ModeStack[38]->SetLineColor(kMagenta);
// ModeStack[39]->SetTitle("#it{#nu + p #rightarrow #nu + p + #gamma}");
ModeStack[39]->SetTitle("NC1#gamma on p");
ModeStack[39]->SetFillColor(kMagenta - 10);
// ModeStack[39]->SetFillStyle(3001);
ModeStack[39]->SetLineColor(kMagenta - 10);
ModeStack[41]->SetTitle("Multi #pi (1.3 < W < 2.0)");
ModeStack[41]->SetFillColor(kBlue - 10);
// ModeStack[41]->SetFillStyle(3005);
ModeStack[41]->SetLineColor(kBlue - 10);
// ModeStack[42]->SetTitle("#it{#nu + n #rightarrow #nu + n + #eta^{0}}");
ModeStack[42]->SetTitle("NC1#eta^{0} on n");
ModeStack[42]->SetFillColor(kYellow - 2);
// ModeStack[42]->SetFillStyle(3013);
ModeStack[42]->SetLineColor(kYellow - 2);
// ModeStack[43]->SetTitle("#it{#nu + p #rightarrow #nu + p + #eta^{0}}");
ModeStack[43]->SetTitle("NC1#eta^{0} on p");
ModeStack[43]->SetFillColor(kYellow - 4);
// ModeStack[43]->SetFillStyle(3013);
ModeStack[43]->SetLineColor(kYellow - 4);
// ModeStack[44]->SetTitle("#it{#nu + n #rightarrow #nu + #Lambda + K^{0}}");
ModeStack[44]->SetTitle("NC1#Lambda1K^{0} on n");
ModeStack[44]->SetFillColor(kYellow - 6);
// ModeStack[44]->SetFillStyle(3014);
ModeStack[44]->SetLineColor(kYellow - 6);
// ModeStack[45]->SetTitle("#it{#nu + p #rightarrow #nu + #Lambda + K^{+}}");
ModeStack[45]->SetTitle("NC1#Lambda1K^{+}");
ModeStack[45]->SetFillColor(kYellow - 10);
// ModeStack[45]->SetFillStyle(3014);
ModeStack[45]->SetLineColor(kYellow - 10);
ModeStack[46]->SetTitle("DIS (W > 2.0)");
ModeStack[46]->SetFillColor(kRed);
// ModeStack[46]->SetFillStyle(3006);
ModeStack[46]->SetLineColor(kRed);
// ModeStack[51]->SetTitle("#it{#nu + p #rightarrow #nu + p}");
ModeStack[51]->SetTitle("NC on p");
ModeStack[51]->SetFillColor(kBlack);
// ModeStack[51]->SetFillStyle(3444);
ModeStack[51]->SetLineColor(kBlack);
// ModeStack[52]->SetTitle("#it{#nu + n #rightarrow #nu + n}");
ModeStack[52]->SetTitle("NC on n");
ModeStack[52]->SetFillColor(kGray);
// ModeStack[52]->SetFillStyle(3444);
ModeStack[52]->SetLineColor(kGray);
return allmodes;
};
TLegend PlotUtils::GenerateStackLegend(THStack stack, int xlow, int ylow,
int xhigh, int yhigh) {
TLegend leg = TLegend(xlow, ylow, xhigh, yhigh);
TObjArray *histarray = stack.GetStack();
int nhist = histarray->GetEntries();
for (int i = 0; i < nhist; i++) {
TH1 *hist = (TH1 *)(histarray->At(i));
leg.AddEntry((hist), ((TH1 *)histarray->At(i))->GetTitle(), "fl");
}
leg.SetName(Form("%s_LEG", stack.GetName()));
return leg;
};
void PlotUtils::ScaleNeutModeArray(TH1 *hist[], double factor,
std::string option) {
for (int i = 0; i < 60; i++) {
if (hist[i])
hist[i]->Scale(factor, option.c_str());
}
return;
};
void PlotUtils::ResetNeutModeArray(TH1 *hist[]) {
for (int i = 0; i < 60; i++) {
if (hist[i])
hist[i]->Reset();
}
return;
};
//********************************************************************
// This assumes the Enu axis is the x axis, as is the case for MiniBooNE 2D
// distributions
void PlotUtils::FluxUnfoldedScaling(TH2D *fMCHist, TH1D *fhist, TH1D *ehist,
double scalefactor) {
//********************************************************************
// Make clones to avoid changing stuff
TH1D *eventhist = (TH1D *)ehist->Clone();
TH1D *fFluxHist = (TH1D *)fhist->Clone();
// Undo width integral in SF
fMCHist->Scale(scalefactor /
eventhist->Integral(1, eventhist->GetNbinsX() + 1, "width"));
// Standardise The Flux
eventhist->Scale(1.0 / fFluxHist->Integral());
fFluxHist->Scale(1.0 / fFluxHist->Integral());
// Do interpolation for 2D plots?
// fFluxHist = PlotUtils::InterpolateFineHistogram(fFluxHist,100,"width");
// eventhist = PlotUtils::InterpolateFineHistogram(eventhist,100,"width");
// eventhist->Scale(1.0/fFluxHist->Integral());
// fFluxHist->Scale(1.0/fFluxHist->Integral());
// Scale fMCHist by eventhist integral
fMCHist->Scale(eventhist->Integral(1, eventhist->GetNbinsX() + 1));
// Find which axis is the Enu axis
bool EnuOnXaxis = false;
std::string xaxis = fMCHist->GetXaxis()->GetTitle();
if (xaxis.find("E") != std::string::npos &&
xaxis.find("nu") != std::string::npos)
EnuOnXaxis = true;
std::string yaxis = fMCHist->GetYaxis()->GetTitle();
if (yaxis.find("E") != std::string::npos &&
xaxis.find("nu") != std::string::npos) {
// First check that xaxis didn't also find Enu
if (EnuOnXaxis) {
NUIS_ERR(FTL, fMCHist->GetTitle() << " error:");
NUIS_ERR(FTL, "Found Enu in xaxis title: " << xaxis);
NUIS_ERR(FTL, "AND");
NUIS_ERR(FTL, "Found Enu in yaxis title: " << yaxis);
NUIS_ABORT("Enu on x and Enu on y flux unfolded scaling isn't "
"implemented, please modify "
<< __FILE__ << ":" << __LINE__);
}
EnuOnXaxis = false;
}
// Now Get a flux PDF assuming X axis is Enu
TH1D *pdfflux = NULL;
// If xaxis is Enu
if (EnuOnXaxis)
pdfflux = (TH1D *)fMCHist->ProjectionX()->Clone();
// If yaxis is Enu
else
pdfflux = (TH1D *)fMCHist->ProjectionY()->Clone();
// pdfflux->Write( (std::string(fMCHist->GetName()) + "_PROJX").c_str());
pdfflux->Reset();
// Awful MiniBooNE Check for the time being
// Needed because the flux is in GeV whereas the measurement is in MeV
bool ismb =
std::string(fMCHist->GetName()).find("MiniBooNE") != std::string::npos;
for (int i = 0; i < pdfflux->GetNbinsX(); i++) {
double Ml = pdfflux->GetXaxis()->GetBinLowEdge(i + 1);
double Mh = pdfflux->GetXaxis()->GetBinLowEdge(i + 2);
// double Mc = pdfflux->GetXaxis()->GetBinCenter(i+1);
// double Mw = pdfflux->GetBinWidth(i+1);
double fluxint = 0.0;
// Scaling to match flux for MB
if (ismb) {
Ml /= 1.E3;
Mh /= 1.E3;
// Mc /= 1.E3;
// Mw /= 1.E3;
}
for (int j = 0; j < fFluxHist->GetNbinsX(); j++) {
// double Fc = fFluxHist->GetXaxis()->GetBinCenter(j+1);
double Fl = fFluxHist->GetXaxis()->GetBinLowEdge(j + 1);
double Fh = fFluxHist->GetXaxis()->GetBinLowEdge(j + 2);
double Fe = fFluxHist->GetBinContent(j + 1);
double Fw = fFluxHist->GetXaxis()->GetBinWidth(j + 1);
if (Fl >= Ml and Fh <= Mh) {
fluxint += Fe;
} else if (Fl < Ml and Fl < Mh and Fh > Ml and Fh < Mh) {
fluxint += Fe * (Fh - Ml) / Fw;
} else if (Fh > Mh and Fl < Mh and Fh > Ml and Fl > Ml) {
fluxint += Fe * (Mh - Fl) / Fw;
} else if (Ml >= Fl and Mh <= Fh) {
fluxint += Fe * (Mh - Ml) / Fw;
} else {
continue;
}
}
pdfflux->SetBinContent(i + 1, fluxint);
}
// Then finally divide by the bin-width in
for (int i = 0; i < fMCHist->GetNbinsX(); i++) {
for (int j = 0; j < fMCHist->GetNbinsY(); j++) {
if (pdfflux->GetBinContent(i + 1) == 0.0)
continue;
// Different scaling depending on if Enu is on x or y axis
double scaling = 1.0;
// If Enu is on the x-axis, we want the ith entry of the flux
// And to divide by the bin width of the jth bin
if (EnuOnXaxis) {
double binWidth = fMCHist->GetYaxis()->GetBinLowEdge(j + 2) -
fMCHist->GetYaxis()->GetBinLowEdge(j + 1);
scaling = pdfflux->GetBinContent(i + 1) * binWidth;
} else {
double binWidth = fMCHist->GetXaxis()->GetBinLowEdge(i + 2) -
fMCHist->GetXaxis()->GetBinLowEdge(i + 1);
scaling = pdfflux->GetBinContent(j + 1) * binWidth;
}
// fMCHist->SetBinContent(i + 1, j + 1,
// fMCHist->GetBinContent(i + 1, j + 1) /
// pdfflux->GetBinContent(i + 1) / binWidth);
// fMCHist->SetBinError(i + 1, j + 1, fMCHist->GetBinError(i + 1, j + 1) /
// pdfflux->GetBinContent(i + 1) /
// binWidth);
fMCHist->SetBinContent(i + 1, j + 1,
fMCHist->GetBinContent(i + 1, j + 1) / scaling);
fMCHist->SetBinError(i + 1, j + 1,
fMCHist->GetBinError(i + 1, j + 1) / scaling);
}
}
delete eventhist;
delete fFluxHist;
};
TH1D *PlotUtils::InterpolateFineHistogram(TH1D *hist, int res,
std::string opt) {
int nbins = hist->GetNbinsX();
double elow = hist->GetXaxis()->GetBinLowEdge(1);
double ehigh = hist->GetXaxis()->GetBinLowEdge(nbins + 1);
bool width = true; // opt.find("width") != std::string::npos;
TH1D *fine = new TH1D("fine", "fine", nbins * res, elow, ehigh);
TGraph *temp = new TGraph();
for (int i = 0; i < nbins; i++) {
double E = hist->GetXaxis()->GetBinCenter(i + 1);
double C = hist->GetBinContent(i + 1);
double W = hist->GetXaxis()->GetBinWidth(i + 1);
if (!width)
W = 1.0;
if (W != 0.0)
temp->SetPoint(temp->GetN(), E, C / W);
}
for (int i = 0; i < fine->GetNbinsX(); i++) {
double E = fine->GetXaxis()->GetBinCenter(i + 1);
double W = fine->GetBinWidth(i + 1);
if (!width)
W = 1.0;
fine->SetBinContent(i + 1, temp->Eval(E, 0, "S") * W);
}
fine->Scale(hist->Integral(1, hist->GetNbinsX() + 1) /
fine->Integral(1, fine->GetNbinsX() + 1));
// std::cout << "Interpolation Difference = "
//<< fine->Integral(1, fine->GetNbinsX() + 1) << "/"
//<< hist->Integral(1, hist->GetNbinsX() + 1) << std::endl;
return fine;
}
//********************************************************************
// This interpolates the flux by a TGraph instead of requiring the flux and MC
// flux to have the same binning
void PlotUtils::FluxUnfoldedScaling(TH1D *mcHist, TH1D *fhist, TH1D *ehist,
double scalefactor, int nevents) {
//********************************************************************
TH1D *eventhist = (TH1D *)ehist->Clone();
TH1D *fFluxHist = (TH1D *)fhist->Clone();
if (FitPar::Config().GetParB("save_flux_debug")) {
std::string name = std::string(mcHist->GetName());
mcHist->Write((name + "_UNF_MC").c_str());
fFluxHist->Write((name + "_UNF_FLUX").c_str());
eventhist->Write((name + "_UNF_EVT").c_str());
TH1D *scalehist = new TH1D("scalehist", "scalehist", 1, 0.0, 1.0);
scalehist->SetBinContent(1, scalefactor);
scalehist->SetBinContent(2, nevents);
scalehist->Write((name + "_UNF_SCALE").c_str());
}
// Undo width integral in SF
mcHist->Scale(scalefactor /
eventhist->Integral(1, eventhist->GetNbinsX() + 1, "width"));
// Standardise The Flux
eventhist->Scale(1.0 / fFluxHist->Integral());
fFluxHist->Scale(1.0 / fFluxHist->Integral());
// Scale mcHist by eventhist integral
mcHist->Scale(eventhist->Integral(1, eventhist->GetNbinsX() + 1));
// Now Get a flux PDF
TH1D *pdfflux = (TH1D *)mcHist->Clone();
pdfflux->Reset();
for (int i = 0; i < mcHist->GetNbinsX(); i++) {
double Ml = mcHist->GetXaxis()->GetBinLowEdge(i + 1);
double Mh = mcHist->GetXaxis()->GetBinLowEdge(i + 2);
// double Mc = mcHist->GetXaxis()->GetBinCenter(i+1);
// double Me = mcHist->GetBinContent(i+1);
// double Mw = mcHist->GetBinWidth(i+1);
double fluxint = 0.0;
for (int j = 0; j < fFluxHist->GetNbinsX(); j++) {
// double Fc = fFluxHist->GetXaxis()->GetBinCenter(j+1);
double Fl = fFluxHist->GetXaxis()->GetBinLowEdge(j + 1);
double Fh = fFluxHist->GetXaxis()->GetBinLowEdge(j + 2);
double Fe = fFluxHist->GetBinContent(j + 1);
double Fw = fFluxHist->GetXaxis()->GetBinWidth(j + 1);
if (Fl >= Ml and Fh <= Mh) {
fluxint += Fe;
} else if (Fl < Ml and Fl < Mh and Fh > Ml and Fh < Mh) {
fluxint += Fe * (Fh - Ml) / Fw;
} else if (Fh > Mh and Fl < Mh and Fh > Ml and Fl > Ml) {
fluxint += Fe * (Mh - Fl) / Fw;
} else if (Ml >= Fl and Mh <= Fh) {
fluxint += Fe * (Mh - Ml) / Fw;
} else {
continue;
}
}
pdfflux->SetBinContent(i + 1, fluxint);
}
// Scale MC hist by pdfflux
for (int i = 0; i < mcHist->GetNbinsX(); i++) {
if (pdfflux->GetBinContent(i + 1) == 0.0)
continue;
mcHist->SetBinContent(i + 1, mcHist->GetBinContent(i + 1) /
pdfflux->GetBinContent(i + 1));
mcHist->SetBinError(i + 1, mcHist->GetBinError(i + 1) /
pdfflux->GetBinContent(i + 1));
}
delete eventhist;
delete fFluxHist;
};
// MOVE TO GENERAL UTILS
//********************************************************************
void PlotUtils::Set2DHistFromText(std::string dataFile, TH2 *hist, double norm,
bool skipbins) {
//********************************************************************
std::string line;
std::ifstream data(dataFile.c_str(), std::ifstream::in);
int yBin = 0;
while (std::getline(data >> std::ws, line, '\n')) {
std::vector<double> entries = GeneralUtils::ParseToDbl(line, " ");
// Loop over entries and insert them into the histogram
for (uint xBin = 0; xBin < entries.size(); xBin++) {
if (!skipbins || entries[xBin] != -1.0)
hist->SetBinContent(xBin + 1, yBin + 1, entries[xBin] * norm);
}
yBin++;
}
return;
}
// MOVE TO GENERAL UTILS
TH1D *PlotUtils::GetTH1DFromFile(std::string dataFile, std::string title,
std::string fPlotTitles,
std::string alt_name) {
TH1D *tempPlot;
// If format is a root file
if (dataFile.find(".root") != std::string::npos) {
TFile *temp_infile = new TFile(dataFile.c_str(), "READ");
tempPlot = (TH1D *)temp_infile->Get(title.c_str());
tempPlot->SetDirectory(0);
temp_infile->Close();
delete temp_infile;
// Else its a space seperated txt file
} else {
// Make a TGraph Errors
TGraphErrors *gr = new TGraphErrors(dataFile.c_str(), "%lg %lg %lg");
if (gr->IsZombie()) {
NUIS_ABORT(dataFile
<< " is a zombie and could not be read. Are you sure it exists?"
<< std::endl);
}
double *bins = gr->GetX();
double *values = gr->GetY();
double *errors = gr->GetEY();
int npoints = gr->GetN();
// Fill the histogram from it
tempPlot = new TH1D(title.c_str(), title.c_str(), npoints - 1, bins);
for (int i = 0; i < npoints; ++i) {
tempPlot->SetBinContent(i + 1, values[i]);
// If only two columns are present in the input file, use the sqrt(values)
// as the error equivalent to assuming that the error is statistical. Also
// check that we're looking at an event rate rather than a cross section
if (!errors[i] && values[i] > 1E-30) {
tempPlot->SetBinError(i + 1, sqrt(values[i]));
} else {
tempPlot->SetBinError(i + 1, errors[i]);
}
}
delete gr;
}
// Allow alternate naming for root files
if (!alt_name.empty()) {
tempPlot->SetNameTitle(alt_name.c_str(), alt_name.c_str());
}
// Allow alternate axis titles
if (!fPlotTitles.empty()) {
tempPlot->SetNameTitle(
tempPlot->GetName(),
(std::string(tempPlot->GetTitle()) + fPlotTitles).c_str());
}
return tempPlot;
};
TH1D *PlotUtils::GetRatioPlot(TH1D *hist1, TH1D *hist2) {
// make copy of first hist
TH1D *new_hist = (TH1D *)hist1->Clone();
// Do bins and errors ourselves as scales can go awkward
for (int i = 0; i < new_hist->GetNbinsX(); i++) {
if (hist2->GetBinContent(i + 1) == 0.0) {
new_hist->SetBinContent(i + 1, 0.0);
}
new_hist->SetBinContent(i + 1, hist1->GetBinContent(i + 1) /
hist2->GetBinContent(i + 1));
new_hist->SetBinError(i + 1, hist1->GetBinError(i + 1) /
hist2->GetBinContent(i + 1));
}
return new_hist;
};
TH1D *PlotUtils::GetRenormalisedPlot(TH1D *hist1, TH1D *hist2) {
// make copy of first hist
TH1D *new_hist = (TH1D *)hist1->Clone();
if (hist1->Integral("width") == 0 or hist2->Integral("width") == 0) {
new_hist->Reset();
return new_hist;
}
Double_t scaleF = hist2->Integral("width") / hist1->Integral("width");
new_hist->Scale(scaleF);
return new_hist;
};
TH1D *PlotUtils::GetShapePlot(TH1D *hist1) {
// make copy of first hist
TH1D *new_hist = (TH1D *)hist1->Clone();
if (hist1->Integral("width") == 0) {
new_hist->Reset();
return new_hist;
}
Double_t scaleF1 = 1.0 / hist1->Integral("width");
new_hist->Scale(scaleF1);
return new_hist;
};
TH1D *PlotUtils::GetShapeRatio(TH1D *hist1, TH1D *hist2) {
TH1D *new_hist1 = GetShapePlot(hist1);
TH1D *new_hist2 = GetShapePlot(hist2);
// Do bins and errors ourselves as scales can go awkward
for (int i = 0; i < new_hist1->GetNbinsX(); i++) {
if (hist2->GetBinContent(i + 1) == 0) {
new_hist1->SetBinContent(i + 1, 0.0);
}
new_hist1->SetBinContent(i + 1, new_hist1->GetBinContent(i + 1) /
new_hist2->GetBinContent(i + 1));
new_hist1->SetBinError(i + 1, new_hist1->GetBinError(i + 1) /
new_hist2->GetBinContent(i + 1));
}
delete new_hist2;
return new_hist1;
};
TH2D *PlotUtils::GetCovarPlot(TMatrixDSym *cov, std::string name,
std::string title) {
TH2D *CovarPlot;
if (cov)
CovarPlot = new TH2D((*cov));
else
CovarPlot = new TH2D(name.c_str(), title.c_str(), 1, 0, 1, 1, 0, 1);
CovarPlot->SetName(name.c_str());
CovarPlot->SetTitle(title.c_str());
return CovarPlot;
}
TH2D *PlotUtils::GetFullCovarPlot(TMatrixDSym *cov, std::string name) {
return PlotUtils::GetCovarPlot(
cov, name + "_COV", name + "_COV;Bins;Bins;Covariance (#times10^{-76})");
}
TH2D *PlotUtils::GetInvCovarPlot(TMatrixDSym *cov, std::string name) {
return PlotUtils::GetCovarPlot(
cov, name + "_INVCOV",
name + "_INVCOV;Bins;Bins;Inv. Covariance (#times10^{-76})");
}
TH2D *PlotUtils::GetDecompCovarPlot(TMatrixDSym *cov, std::string name) {
return PlotUtils::GetCovarPlot(
cov, name + "_DECCOV",
name + "_DECCOV;Bins;Bins;Decomp Covariance (#times10^{-76})");
}
TH1D *PlotUtils::GetTH1DFromRootFile(std::string file, std::string name) {
if (name.empty()) {
std::vector<std::string> tempfile = GeneralUtils::ParseToStr(file, ";");
file = tempfile[0];
name = tempfile[1];
}
TFile *rootHistFile = new TFile(file.c_str(), "READ");
TH1D *tempHist = (TH1D *)rootHistFile->Get(name.c_str())->Clone();
if (tempHist == NULL) {
NUIS_ABORT("Could not find distribution " << name << " in file " << file);
}
tempHist->SetDirectory(0);
rootHistFile->Close();
return tempHist;
}
TH2D *PlotUtils::GetTH2DFromRootFile(std::string file, std::string name) {
if (name.empty()) {
std::vector<std::string> tempfile = GeneralUtils::ParseToStr(file, ";");
file = tempfile[0];
name = tempfile[1];
}
TFile *rootHistFile = new TFile(file.c_str(), "READ");
TH2D *tempHist = (TH2D *)rootHistFile->Get(name.c_str())->Clone();
tempHist->SetDirectory(0);
rootHistFile->Close();
delete rootHistFile;
return tempHist;
}
TH1 *PlotUtils::GetTH1FromRootFile(std::string file, std::string name) {
if (name.empty()) {
std::vector<std::string> tempfile = GeneralUtils::ParseToStr(file, ";");
file = tempfile[0];
name = tempfile[1];
}
TFile *rootHistFile = new TFile(file.c_str(), "READ");
if (!rootHistFile || rootHistFile->IsZombie()) {
NUIS_ABORT("Couldn't open root file: \"" << file << "\".");
}
TH1 *tempHist = dynamic_cast<TH1 *>(rootHistFile->Get(name.c_str())->Clone());
if (!tempHist) {
NUIS_ABORT("Couldn't retrieve: \"" << name << "\" from root file: \"" << file
<< "\".");
}
tempHist->SetDirectory(0);
rootHistFile->Close();
delete rootHistFile;
return tempHist;
}
TGraph *PlotUtils::GetTGraphFromRootFile(std::string file, std::string name) {
if (name.empty()) {
std::vector<std::string> tempfile = GeneralUtils::ParseToStr(file, ";");
file = tempfile[0];
name = tempfile[1];
}
TDirectory *olddir = gDirectory;
TFile *rootHistFile = new TFile(file.c_str(), "READ");
if (!rootHistFile || rootHistFile->IsZombie()) {
NUIS_ABORT("Couldn't open root file: \"" << file << "\".");
}
TDirectory *newdir = gDirectory;
TGraph *temp =
dynamic_cast<TGraph *>(rootHistFile->Get(name.c_str())->Clone());
if (!temp) {
NUIS_ABORT("Couldn't retrieve: \"" << name << "\" from root file: \"" << file
<< "\".");
}
newdir->Remove(temp);
olddir->Append(temp);
rootHistFile->Close();
olddir->cd();
return temp;
}
/// Returns a vector of named TH1*s found in a single input file.
///
/// Expects a descriptor like: file.root[hist1|hist2|...]
std::vector<TH1 *>
PlotUtils::GetTH1sFromRootFile(std::string const &descriptor) {
std::vector<std::string> descriptors =
GeneralUtils::ParseToStr(descriptor, ",");
std::vector<TH1 *> hists;
for (size_t d_it = 0; d_it < descriptors.size(); ++d_it) {
std::string &d = descriptors[d_it];
std::vector<std::string> fname = GeneralUtils::ParseToStr(d, "[");
if (!fname.size() || !fname[0].length()) {
NUIS_ABORT("Couldn't find input file when attempting to parse : \""
<< d << "\". Expected input.root[hist1|hist2|...].");
}
if (fname[1][fname[1].length() - 1] == ']') {
fname[1] = fname[1].substr(0, fname[1].length() - 1);
}
std::vector<std::string> histnames =
GeneralUtils::ParseToStr(fname[1], "|");
if (!histnames.size()) {
NUIS_ABORT("Couldn't find any histogram name specifiers when attempting to "
"parse "
": \""
<< fname[1] << "\". Expected hist1|hist2|...");
}
TFile *rootHistFile = new TFile(fname[0].c_str(), "READ");
if (!rootHistFile || rootHistFile->IsZombie()) {
NUIS_ABORT("Couldn't open root file: \"" << fname[0] << "\".");
}
for (size_t i = 0; i < histnames.size(); ++i) {
TH1 *tempHist =
dynamic_cast<TH1 *>(rootHistFile->Get(histnames[i].c_str())->Clone());
if (!tempHist) {
NUIS_ABORT("Couldn't retrieve: \""
<< histnames[i] << "\" from root file: \"" << fname[0] << "\".");
}
tempHist->SetDirectory(0);
hists.push_back(tempHist);
}
rootHistFile->Close();
}
return hists;
}
// Create an array from an input file
std::vector<double> PlotUtils::GetArrayFromTextFile(std::string DataFile) {
std::string line;
std::ifstream data(DataFile.c_str(), std::ifstream::in);
// Get first line
std::getline(data >> std::ws, line, '\n');
// Convert from a string into a vector of double
std::vector<double> entries = GeneralUtils::ParseToDbl(line, " ");
return entries;
}
// Get a 2D array from a text file
-std::vector<std::vector<double>>
+std::vector<std::vector<double> >
PlotUtils::Get2DArrayFromTextFile(std::string DataFile) {
std::string line;
- std::vector<std::vector<double>> DataArray;
+ std::vector<std::vector<double> > DataArray;
std::ifstream data(DataFile.c_str(), std::ifstream::in);
while (std::getline(data >> std::ws, line, '\n')) {
std::vector<double> entries = GeneralUtils::ParseToDbl(line, " ");
DataArray.push_back(entries);
}
return DataArray;
}
TH2D *PlotUtils::GetTH2DFromTextFile(std::string data, std::string binx,
std::string biny) {
// First read in the binning
// Array of x binning
std::vector<double> xbins = GetArrayFromTextFile(binx);
// Array of y binning
std::vector<double> ybins = GetArrayFromTextFile(biny);
// Read in the data
- std::vector<std::vector<double>> Data = Get2DArrayFromTextFile(data);
+ std::vector<std::vector<double> > Data = Get2DArrayFromTextFile(data);
// And finally fill the data
TH2D *DataPlot = new TH2D("TempHist", "TempHist", xbins.size() - 1, &xbins[0],
ybins.size() - 1, &ybins[0]);
int nBinsX = 0;
int nBinsY = 0;
- for (std::vector<std::vector<double>>::iterator it = Data.begin();
+ for (std::vector<std::vector<double> >::iterator it = Data.begin();
it != Data.end(); ++it) {
nBinsX++;
// Get the inner vector
std::vector<double> temp = *it;
// Save the previous number[of bins to make sure it's uniform binning
int oldBinsY = nBinsY;
// Reset the counter
nBinsY = 0;
for (std::vector<double>::iterator jt = temp.begin(); jt != temp.end();
++jt) {
nBinsY++;
DataPlot->SetBinContent(nBinsX, nBinsY, *jt);
DataPlot->SetBinError(nBinsX, nBinsY, 0.0);
}
if (oldBinsY > 0 && oldBinsY != nBinsY) {
NUIS_ERR(FTL, "Found non-uniform y-binning in " << data);
NUIS_ERR(FTL, "Previous slice: " << oldBinsY);
NUIS_ERR(FTL, "Current slice: " << nBinsY);
NUIS_ABORT("Non-uniform binning is not supported in "
"PlotUtils::GetTH2DFromTextFile");
}
}
// Check x bins
if (size_t(nBinsX + 1) != xbins.size()) {
NUIS_ERR(FTL, "Number of x bins in data histogram does not match the binning "
"histogram!");
NUIS_ERR(FTL,
"Are they the wrong way around (i.e. xbinning should be ybinning)?");
NUIS_ERR(FTL, "Data: " << nBinsX);
NUIS_ABORT("From " << binx << " binning: " << xbins.size());
}
// Check y bins
if (size_t(nBinsY + 1) != ybins.size()) {
NUIS_ERR(FTL, "Number of y bins in data histogram does not match the binning "
"histogram!");
NUIS_ERR(FTL,
"Are they the wrong way around (i.e. xbinning should be ybinning)?");
NUIS_ERR(FTL, "Data: " << nBinsY);
NUIS_ABORT("From " << biny << " binning: " << ybins.size());
}
return DataPlot;
}
TH1D *PlotUtils::GetSliceY(TH2D *Hist, int SliceNo) {
TH1D *Slice = Hist->ProjectionX(Form("%s_SLICEY%i", Hist->GetName(), SliceNo),
SliceNo, SliceNo, "e");
Slice->SetTitle(Form("%s, %.2f-%.2f", Hist->GetYaxis()->GetTitle(),
Hist->GetYaxis()->GetBinLowEdge(SliceNo),
Hist->GetYaxis()->GetBinLowEdge(SliceNo + 1)));
Slice->GetYaxis()->SetTitle(Hist->GetZaxis()->GetTitle());
return Slice;
}
TH1D *PlotUtils::GetSliceX(TH2D *Hist, int SliceNo) {
TH1D *Slice = Hist->ProjectionY(Form("%s_SLICEX%i", Hist->GetName(), SliceNo),
SliceNo, SliceNo, "e");
Slice->SetTitle(Form("%s, %.2f-%.2f", Hist->GetXaxis()->GetTitle(),
Hist->GetXaxis()->GetBinLowEdge(SliceNo),
Hist->GetXaxis()->GetBinLowEdge(SliceNo + 1)));
Slice->GetYaxis()->SetTitle(Hist->GetZaxis()->GetTitle());
return Slice;
}
void PlotUtils::AddNeutModeArray(TH1D *hist1[], TH1D *hist2[], double scaling) {
for (int i = 0; i < 60; i++) {
if (!hist2[i])
continue;
if (!hist1[i])
continue;
hist1[i]->Add(hist2[i], scaling);
}
return;
}
void PlotUtils::ScaleToData(TH1D *data, TH1D *mc, TH1I *mask) {
double scaleF = GetDataMCRatio(data, mc, mask);
mc->Scale(scaleF);
return;
}
void PlotUtils::MaskBins(TH1D *hist, TH1I *mask) {
for (int i = 0; i < hist->GetNbinsX(); i++) {
if (mask->GetBinContent(i + 1) <= 0.5)
continue;
hist->SetBinContent(i + 1, 0.0);
hist->SetBinError(i + 1, 0.0);
NUIS_LOG(REC, "MaskBins: Set " << hist->GetName() << " Bin " << i + 1
<< " to 0.0 +- 0.0");
}
return;
}
void PlotUtils::MaskBins(TH2D *hist, TH2I *mask) {
for (int i = 0; i < hist->GetNbinsX(); i++) {
for (int j = 0; j < hist->GetNbinsY(); j++) {
if (mask->GetBinContent(i + 1, j + 1) <= 0.5)
continue;
hist->SetBinContent(i + 1, j + 1, 0.0);
hist->SetBinError(i + 1, j + 1, 0.0);
NUIS_LOG(REC, "MaskBins: Set " << hist->GetName() << " Bin " << i + 1 << " "
<< j + 1 << " to 0.0 +- 0.0");
}
}
return;
}
double PlotUtils::GetDataMCRatio(TH1D *data, TH1D *mc, TH1I *mask) {
double rat = 1.0;
TH1D *newmc = (TH1D *)mc->Clone();
TH1D *newdt = (TH1D *)data->Clone();
if (mask) {
MaskBins(newmc, mask);
MaskBins(newdt, mask);
}
rat = newdt->Integral() / newmc->Integral();
return rat;
}
TH2D *PlotUtils::GetCorrelationPlot(TH2D *cov, std::string name) {
TH2D *cor = (TH2D *)cov->Clone();
cor->Reset();
for (int i = 0; i < cov->GetNbinsX(); i++) {
for (int j = 0; j < cov->GetNbinsY(); j++) {
if (cov->GetBinContent(i + 1, i + 1) != 0.0 and
cov->GetBinContent(j + 1, j + 1) != 0.0)
cor->SetBinContent(i + 1, j + 1,
cov->GetBinContent(i + 1, j + 1) /
(sqrt(cov->GetBinContent(i + 1, i + 1) *
cov->GetBinContent(j + 1, j + 1))));
}
}
if (!name.empty()) {
cor->SetNameTitle(name.c_str(), (name + ";;correlation").c_str());
}
cor->SetMinimum(-1);
cor->SetMaximum(1);
return cor;
}
TH2D *PlotUtils::GetDecompPlot(TH2D *cov, std::string name) {
TMatrixDSym *covarmat = new TMatrixDSym(cov->GetNbinsX());
for (int i = 0; i < cov->GetNbinsX(); i++)
for (int j = 0; j < cov->GetNbinsY(); j++)
(*covarmat)(i, j) = cov->GetBinContent(i + 1, j + 1);
TMatrixDSym *decompmat = StatUtils::GetDecomp(covarmat);
TH2D *dec = (TH2D *)cov->Clone();
for (int i = 0; i < cov->GetNbinsX(); i++)
for (int j = 0; j < cov->GetNbinsY(); j++)
dec->SetBinContent(i + 1, j + 1, (*decompmat)(i, j));
delete covarmat;
delete decompmat;
dec->SetNameTitle(name.c_str(), (name + ";;;decomposition").c_str());
return dec;
}
TH2D *PlotUtils::MergeIntoTH2D(TH1D *xhist, TH1D *yhist, std::string zname) {
std::vector<double> xedges, yedges;
for (int i = 0; i < xhist->GetNbinsX() + 2; i++) {
xedges.push_back(xhist->GetXaxis()->GetBinLowEdge(i + 1));
}
for (int i = 0; i < yhist->GetNbinsX() + 2; i++) {
yedges.push_back(yhist->GetXaxis()->GetBinLowEdge(i + 1));
}
int nbinsx = xhist->GetNbinsX();
int nbinsy = yhist->GetNbinsX();
std::string name =
std::string(xhist->GetName()) + "_vs_" + std::string(yhist->GetName());
std::string titles = ";" + std::string(xhist->GetXaxis()->GetTitle()) + ";" +
std::string(yhist->GetXaxis()->GetTitle()) + ";" + zname;
TH2D *newplot = new TH2D(name.c_str(), (name + titles).c_str(), nbinsx,
&xedges[0], nbinsy, &yedges[0]);
return newplot;
}
//***************************************************
void PlotUtils::MatchEmptyBins(TH1D *data, TH1D *mc) {
//**************************************************
for (int i = 0; i < data->GetNbinsX(); i++) {
if (data->GetBinContent(i + 1) == 0.0 or data->GetBinError(i + 1) == 0.0)
mc->SetBinContent(i + 1, 0.0);
}
return;
}
//***************************************************
void PlotUtils::MatchEmptyBins(TH2D *data, TH2D *mc) {
//**************************************************
for (int i = 0; i < data->GetNbinsX(); i++) {
for (int j = 0; j < data->GetNbinsY(); j++) {
if (data->GetBinContent(i + 1, j + 1) == 0.0 or
data->GetBinError(i + 1, j + 1) == 0.0)
mc->SetBinContent(i + 1, j + 1, 0.0);
}
}
return;
}
//***************************************************
TH1D *PlotUtils::GetProjectionX(TH2D *hist, TH2I *mask) {
//***************************************************
TH2D *maskedhist = StatUtils::ApplyHistogramMasking(hist, mask);
// This includes the underflow/overflow
TH1D* hist_X = maskedhist->ProjectionX("_px", 1, maskedhist->GetXaxis()->GetNbins());
hist_X->SetTitle(Form("%s x no under/overflow", hist_X->GetTitle()));
delete maskedhist;
return hist_X;
}
//***************************************************
TH1D *PlotUtils::GetProjectionY(TH2D *hist, TH2I *mask) {
//***************************************************
TH2D *maskedhist = StatUtils::ApplyHistogramMasking(hist, mask);
// This includes the underflow/overflow
TH1D* hist_Y = maskedhist->ProjectionY("_py", 1, maskedhist->GetYaxis()->GetNbins());
hist_Y->SetTitle(Form("%s y no under/overflow", hist_Y->GetTitle()));
delete maskedhist;
return hist_Y;
}

File Metadata

Mime Type
text/x-diff
Expires
Wed, May 14, 11:24 AM (11 h, 1 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
5083232
Default Alt Text
(294 KB)

Event Timeline